path
stringlengths
7
265
concatenated_notebook
stringlengths
46
17M
Notebook archive/2_PSQL_basic_connection_and_retrieval.ipynb
###Markdown 2 Connecting to postgresql A little introduction to the concepts of Postgresql and Pandas interaction. To retrieve data from the postgresql database, I use [Pandas](http://pandas.pydata.org/pandas-docs/stable/index.html), which basically has Postgresql interaction built in and returns *dataframe* objects that can be easily displayed, filtered, plotted and so on. Interaction with the data happens via **queries** that are used to retrieve a subset of the data scattered throughout the database. These queries can have simple to complex forms and use their own (postgresql specific) language, which is quite easy to understand. The beauty about these queries is that they allow filtering on the flow, sorting, and - maybe most importantly - the merging of different tables matching certain criteria. Common tasks are for example the retrieval of data within a user specified range from a specific table or the data that has a common ID in two tables. Examples will be given below and in the next notebooks.Authentication happens in two ways: Every computer has to have a password file saved which will be automatically accessed by postgres and will be used to log in to a specific database as a specific user. Additionally, the basic parameters are set in subfunctions (saved under `/database_helpers`).This computer here has read-only access to the database, but your office computer has administrator privilege access because it needs also to change / edit data. Basic setup Every interaction starts with the basic import of libraries and functions ... ###Code # the following two lines indicate that external functions are auto-reloaded as soon as they change. # That's a nice trick! %load_ext autoreload %autoreload 2 # Print statements from __future__ import print_function # Python 2.x # General stuff: import sys import argparse import os import json import numpy as np import math import psycopg2 import cPickle import numpy as np import pandas as pd from datetime import date from tqdm import tqdm_notebook # Plotting: from matplotlib import pyplot as plt import seaborn as sns import matplotlib.cm as cm import matplotlib as mpl %matplotlib inline # External functions from subfolder /database_helpers. # as soon as you change something in there and press save, it will auto reload on next execution. from database_helpers.psql_start import * from database_helpers.create_tables import * from database_helpers.write2tables import * # register pickle type to retrieve binary data from database psycopg2.extensions.register_type(psycopg2.extensions.new_type(psycopg2.BINARY.values, 'BINARY-PICKLE', cast_pickle)) ###Output Loaded analysis helpers: General ###Markdown Postgresql Try a first handshake with the database via the function `test_connect()` ###Code db_status = test_connect() if db_status == False: print('Grrr... no database connection could be established.') else: print('Yippiyeah! Database connection is established!') ###Output Connecting to the PostgreSQL database... Grrr... no database connection could be established. ###Markdown Query database with pandas Every retrieval of data consists of **two steps**: Creation of sql query command, and execution of that command through pandas to retrieve a dataframe. To keep the data size small it is important to filter the data to be retrieved, but let's skip that for now (see below). Once loaded in a pandas dataframe, operations are run locally and additional filtering / manipulations can be applied. ###Code # load the parameters to connect to data_1 params = config() %%time sql = "SELECT * FROM meta_tb" # sql command sql_db_pd = pd.read_sql_query(sql, psycopg2.connect(**params), index_col=None) # execute query and read into pandas dataframe ###Output _____no_output_____ ###Markdown The code above loads the parameters (`params`) to connect to the database data_1. This only has to be done once per notebook. Then a sql command is created (`sql`) and it passed into a pandas `read_sql_query` command to retrieve a pandas dataframe object for that query. Let's look at that sql query:`SELECT * FROM meta_tb` - SELECT - we want to read data, - we don't filter any columns (*) -- give me all the columns that are available - FROM meta_tb - which table to we want to read fromLet's see what we got. A convenient way to look at a pandas dataframe object is just to call it and pass a .head() or .tail() to it, which will show a snippet of the start or the end. An optional number within brackets defines how many rows you want to show. ###Code sql_db_pd.head() ###Output _____no_output_____ ###Markdown We have retrieved the complete meta_tb table and can inspect the output as dataframe object. Let's make both the sql query as well as the pandas function a bit more sophisticated: Simple filtering ###Code sql = "SELECT * FROM meta_tb WHERE session_ts > '1/6/2016' AND session_ts < '25/04/2017'" sql_db_pd = pd.read_sql_query(sql, psycopg2.connect(**params), index_col=None,parse_dates=['session_ts','analysis_ts']) sql_db_pd.sort_values(by='analysis_ts', ascending=False).head(3) ###Output _____no_output_____ ###Markdown Executing that statement should have produced a view of the top 3 meta table entries sorted by analysis timestamp in descending order. What we integrated was a **filter** option (via `WHERE` in the sql query, filtering for a date range in the session timestamp column) and an additional parameter (`parse_dates`) in the pandas retrieval function, such that dates are parsed correctly. We also told pandas to sort the output for the analysis timestamp (`ascending=False`).So in practice filtering can be done on the level of the database interaction within the sql command AND later on in the dataframe. The first filtering step is the most important one because we want to keep the dataset that is transferred via the local network small. But quering with a complex statement can put significant strain on the database server - so there is a trade off ... One more example: ###Code sql = "SELECT * FROM clusters_tb" sql_db_pd = pd.read_sql_query(sql, psycopg2.connect(**params), index_col=None,parse_dates=['session_ts','analysis_ts']) sql_db_pd.sort_values(by='analysis_ts', ascending=False).head(3) ###Output _____no_output_____
examples/plot_grainpop.ipynb
###Markdown How to construct a SingleGrainPop object ###Code sgpop = SingleGrainPop('Powerlaw', 'Silicate', 'Mie') sgpop.calculate_ext(LAMVALS, unit='angs') ax = plt.subplot(111) sgpop.plot_ext(ax, 'all', loc='upper right', frameon=False) plt.semilogy() ax = plt.subplot(111) sgpop.plot_ext(ax, 'ext', color='g', lw=3) sgpop.plot_ext(ax, 'sca', color='b', lw=2) sgpop.plot_ext(ax, 'abs', color='r', lw=1) plt.semilogy() ###Output _____no_output_____ ###Markdown SingleGrainPop objects can be combined into a larger GrainPop ###Code silpop = SingleGrainPop('Powerlaw', 'Silicate', 'Mie') grapop = SingleGrainPop('Powerlaw', 'Graphite', 'Mie') myPop = GrainPop([silpop, grapop], keys=['sil','gra']) myPop.calculate_ext(LAMVALS, unit='angs') ax = plt.subplot(111) myPop['sil'].plot_ext(ax, 'ext', color='g', label='Silicate Extinction') myPop['gra'].plot_ext(ax, 'ext', color='b', label='Graphite Extinction') myPop.plot_ext(ax, 'ext', color='k', lw=2, label='Total') ax.legend(loc='upper right', frameon=False) plt.semilogy() myPop.info() ###Output _____no_output_____ ###Markdown Shortcut (helper) functions ###Code NH = 1.e22 # cm^-2 MD = NH * 0.009 * constants.m_p ###Output _____no_output_____ ###Markdown make_MRN ###Code mrn = make_MRN(md=MD) mrn.calculate_ext(LAMVALS, unit='angs') ax = plt.subplot(111) mrn.plot_ext(ax, 'all', frameon=False) ax = plt.subplot(111) mrn.plot_ext(ax, 'ext', color='k', lw=2, label='total') for k in mrn.keys: mrn[k].plot_ext(ax, 'ext', ls='--', label=k) ax.legend(loc='upper right', frameon=False) mrn.info() ###Output _____no_output_____ ###Markdown make_MRN_drude ###Code mrn_rgd = make_MRN_drude(md=MD) mrn_rgd.calculate_ext(EVALS, unit='kev') ax = plt.subplot(111) mrn_rgd.plot_ext(ax, 'all') plt.loglog() mrn_rgd.info() ###Output _____no_output_____
_notebooks/2022-04-28-initialise_undirected_graph_networkx.ipynb
###Markdown Initialising an Undirected Graph in NetworkX> Initialise an undirected graph in NetworkX using a DataFrame.- toc: true- badges: true- comments: true- categories: [graphs]- permalink: /2022/04/28/initialise_undirected_graph_networkx/ Dependencies ###Code import networkx as nx import laughingrook as lr ###Output _____no_output_____ ###Markdown Notes- We use local constants to refer to the `DataFrame` columns - We feel it improves the readability of the code, but it is optional- We initialise a *weighted* undirected graph in this example. See the `weight` key in the *edge generator*. - If we did not pass a *weight*, then it would the returned graph would be *unweighted*- The |*edges*| $\ne$ |*edge list*| because the `networkx.Graph` class does not permit parallel edges between two nodes. Inputs/Outputs Inputs- *eroads* (`DataFrame`), data on the road network in Europe as an *edge list*. Nodes are cities, and the edges between them represent roads. - See [The International E-road Network and Neo4j](http://lassewesth.blogspot.com/2018/07/the-international-e-road-network-and.html). Intermediate- *edges* (`list[dict]`), each row in *eroads* as a `dict`, with key=column title Outputs- *g* (`Graph`), a weighted undirected graph Load the data ###Code eroads = lr.datasets.get_csv_file('graphs/eroads_edge_list.csv') eroads.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 1250 entries, 0 to 1249 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 road_number 1250 non-null object 1 origin_country_code 1250 non-null object 2 origin_reference_place 1250 non-null object 3 destination_country_code 1250 non-null object 4 destination_reference_place 1250 non-null object 5 distance 1250 non-null int64 6 watercrossing 1250 non-null bool dtypes: bool(1), int64(1), object(5) memory usage: 59.9+ KB ###Markdown Prepare the data Initialise local constants ###Code U = 'origin_reference_place' V = 'destination_reference_place' UCO = 'origin_country_code' VCO = 'destination_country_code' W = 'distance' RN = 'road_number' WC = 'watercrossing' ###Output _____no_output_____ ###Markdown Get the DataFrame as a `dict` ###Code edges = eroads.to_dict(orient='records') edges[0] ###Output _____no_output_____ ###Markdown Initalise the graph ###Code g = nx.Graph() ###Output _____no_output_____ ###Markdown Add the nodes ###Code g.add_nodes_from((edge[U], {'country': edge[UCO]}) for edge in edges) g.add_nodes_from((edge[V], {'country': edge[VCO]}) for edge in edges) ###Output _____no_output_____ ###Markdown Add edges ###Code g.add_edges_from ((edge[U], edge[V], {'weight': edge[W], RN: edge[RN]}) for edge in edges) ###Output _____no_output_____ ###Markdown Check the graphView three nodes. ###Code list(g.nodes(data=True))[:5] ###Output _____no_output_____ ###Markdown View the edges of the Roma node. ###Code list(g.edges('Roma', data=True)) ###Output _____no_output_____
notebooks/LSTM for household power consumption prediction_univariate_multistep.ipynb
###Markdown LSTM prediction, univariate, multi-stepcf. https://www.youtube.com/watch?v=HeQpGKNqkcs&list=PLc2rvfiptPSR3iwFp1VHVJFK4yAMo0wuF&index=19Dataset: https://archive.ics.uci.edu/ml/datasets/Individual+household+electric+power+consumptionDownload: https://archive.ics.uci.edu/ml/machine-learning-databases/00235/household_power_consumption.zip ###Code import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from numpy import nan from tensorflow.keras import Sequential from tensorflow.keras.layers import LSTM, Dense data = pd.read_csv('data/household_power_consumption.txt', sep=';', parse_dates=True, low_memory=False) data.head() data.info() data['date_time'] = data['Date'].str.cat(data['Time'], sep=' ') data.drop(['Date', 'Time'], inplace=True, axis = 1) data.head() data.set_index(['date_time'], inplace=True) data.head() data.replace('?', nan, inplace=True) data = data.astype('float') data.info() np.isnan(data).sum() def fill_missing(data): one_day = 24 * 60 for row in range(data.shape[0]): for col in range(data.shape[1]): if np.isnan(data[row][col]): data[row][col] = data[row - one_day][col] fill_missing(data.values) np.isnan(data).sum() data.describe() data.shape data.head() ###Output _____no_output_____ ###Markdown Prepare power consumption for each day ###Code data.to_csv('data/cleaned_household_power_consumption.csv') dataset = pd.read_csv('data/cleaned_household_power_consumption.csv', parse_dates=True, index_col='date_time', low_memory=False) dataset.head() dataset.tail() ###Output _____no_output_____ ###Markdown Let's do EDA ###Code data = dataset.resample('D').sum() data.head() fig, ax = plt.subplots(figsize=(18,18)) for i in range(len(data.columns)): plt.subplot(len(data.columns), 1, i+1) name = data.columns[i] plt.plot(data[name]) plt.title(name, y=0, loc = 'right') plt.yticks([]) plt.show() fig.tight_layout() ###Output _____no_output_____ ###Markdown Exploring active power consumption for each year ###Code years = ['2007', '2008', '2009', '2010'] fig, ax = plt.subplots(figsize=(18,18)) for i in range(len(years)): plt.subplot(len(years), 1, i+1) year = years [i] active_power_data = data[str(year)] plt.plot(active_power_data['Global_active_power']) plt.title(str(year), y=0, loc = 'left') plt.yticks([]) plt.show() fig.tight_layout() ###Output _____no_output_____ ###Markdown Power consumption distribution with histogram hist for active power ###Code fig, ax = plt.subplots(figsize=(18,18)) for i in range(len(years)): plt.subplot(len(years), 1, i+1) year = years [i] active_power_data = data[str(year)] active_power_data['Global_active_power'].hist(bins= 200) plt.title(str(year), y=0, loc = 'left') plt.yticks([]) plt.show() fig.tight_layout() ###Output _____no_output_____ ###Markdown hist for full data ###Code fig, ax = plt.subplots(figsize=(18,18)) for i in range(len(data.columns)): plt.subplot(len(data.columns), 1, i+1) name = data.columns[i] data[name].hist(bins = 200) plt.title(name, y=0, loc = 'right') plt.yticks([]) plt.show() fig.tight_layout() ###Output _____no_output_____ ###Markdown plot power consumption hist for each month of 2007 ###Code months = [i for i in range(1,13)] fig, ax = plt.subplots(figsize=(18,18)) for i in range(len(months)): ax = plt.subplot(len(months), 1, i+1) month = '2007-' + str(months[i]) active_power_data = dataset[month] active_power_data['Global_active_power'].hist(bins= 100) ax.set_xlim(0,5) plt.title(month, y=0, loc = 'right') plt.show() fig.tight_layout() dataset['2007-' + str(months[3])] ###Output _____no_output_____ ###Markdown active power uses prediction- forecast hourly for next day- forecast daily for next week- forecast daily for next month- forecast monthly for next year ###Code # forecast daily for next week # [Week1] -> Week2 # [Week2] -> Week3 # Given recent power consumption, what is the expected power consumption for the week ahead? data.head() data.tail() data_train = data.loc[:'2009-12-31',:]['Global_active_power'] data_train.tail() data_test = data['2010']['Global_active_power'] data_test.tail() data_train.shape, data_test.shape ###Output _____no_output_____ ###Markdown Prepare training data ###Code data_train.head(14) data_train = np.array(data_train) X_train, y_train = [], [] for i in range(7, len(data_train) - 7): X_train.append(data_train[i-7:i]) # past 7 days y_train.append(data_train[i:i+7]) # next 7 days X_train, y_train = np.array(X_train), np.array(y_train) X_train.shape, y_train.shape X_train[0], y_train[0] pd.DataFrame(X_train) x_scaler = MinMaxScaler() X_train = x_scaler.fit_transform(X_train) y_scaler = MinMaxScaler() y_train = y_scaler.fit_transform(y_train) X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1) # 1 feature only X_train.shape ###Output _____no_output_____ ###Markdown Build LSTM Model ###Code regressor = Sequential() num_features = 1 # open, high, low, close, volume # units -> dimension of latent state vector of LSTM cell ~ capacity/#weights of LSTM cell # return_sequences -> True so that all hidden states h_t (i.e. entire sequence) get passed to the next LSTM layer for it # to process the entire sequence as well regressor.add(LSTM(units = 200, activation = 'relu', input_shape = (X_train.shape[1], num_features))) regressor.add(Dense(units = 7)) regressor.compile(loss='mse', optimizer='adam') regressor.fit(X_train, y_train, epochs=100) ###Output Train on 1098 samples Epoch 1/100 1098/1098 [==============================] - 2s 2ms/sample - loss: 0.0600 Epoch 2/100 1098/1098 [==============================] - 0s 432us/sample - loss: 0.0246 Epoch 3/100 1098/1098 [==============================] - 0s 377us/sample - loss: 0.0242 Epoch 4/100 1098/1098 [==============================] - 1s 512us/sample - loss: 0.0241 Epoch 5/100 1098/1098 [==============================] - 1s 740us/sample - loss: 0.0240 Epoch 6/100 1098/1098 [==============================] - 1s 545us/sample - loss: 0.0239 Epoch 7/100 1098/1098 [==============================] - 1s 610us/sample - loss: 0.0240 Epoch 8/100 1098/1098 [==============================] - 1s 561us/sample - loss: 0.0242 Epoch 9/100 1098/1098 [==============================] - 1s 669us/sample - loss: 0.0239 Epoch 10/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0239 Epoch 11/100 1098/1098 [==============================] - 1s 913us/sample - loss: 0.0237 Epoch 12/100 1098/1098 [==============================] - 1s 773us/sample - loss: 0.0242 Epoch 13/100 1098/1098 [==============================] - 1s 949us/sample - loss: 0.0237 Epoch 14/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0238 Epoch 15/100 1098/1098 [==============================] - 1s 884us/sample - loss: 0.0238 Epoch 16/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0237 Epoch 17/100 1098/1098 [==============================] - 1s 756us/sample - loss: 0.0236 Epoch 18/100 1098/1098 [==============================] - 1s 760us/sample - loss: 0.0237 Epoch 19/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0236 Epoch 20/100 1098/1098 [==============================] - 1s 772us/sample - loss: 0.0234 Epoch 21/100 1098/1098 [==============================] - 1s 854us/sample - loss: 0.0234 Epoch 22/100 1098/1098 [==============================] - 1s 991us/sample - loss: 0.0234 Epoch 23/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0234 Epoch 24/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0235 Epoch 25/100 1098/1098 [==============================] - 1s 790us/sample - loss: 0.0234 Epoch 26/100 1098/1098 [==============================] - 1s 900us/sample - loss: 0.0233 Epoch 27/100 1098/1098 [==============================] - 1s 739us/sample - loss: 0.0233 Epoch 28/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0236 Epoch 29/100 1098/1098 [==============================] - 1s 599us/sample - loss: 0.0235 Epoch 30/100 1098/1098 [==============================] - 1s 730us/sample - loss: 0.0233 Epoch 31/100 1098/1098 [==============================] - 1s 734us/sample - loss: 0.0232 Epoch 32/100 1098/1098 [==============================] - 1s 672us/sample - loss: 0.0233s - loss: 0.023 Epoch 33/100 1098/1098 [==============================] - 1s 607us/sample - loss: 0.0232 Epoch 34/100 1098/1098 [==============================] - 1s 536us/sample - loss: 0.0233 Epoch 35/100 1098/1098 [==============================] - 1s 681us/sample - loss: 0.0233 Epoch 36/100 1098/1098 [==============================] - 1s 652us/sample - loss: 0.0232s - loss: 0. Epoch 37/100 1098/1098 [==============================] - 1s 546us/sample - loss: 0.0232 Epoch 38/100 1098/1098 [==============================] - 0s 427us/sample - loss: 0.0232 Epoch 39/100 1098/1098 [==============================] - 1s 710us/sample - loss: 0.0231 Epoch 40/100 1098/1098 [==============================] - 1s 679us/sample - loss: 0.0232 Epoch 41/100 1098/1098 [==============================] - 1s 549us/sample - loss: 0.0232 Epoch 42/100 1098/1098 [==============================] - 1s 547us/sample - loss: 0.0232 Epoch 43/100 1098/1098 [==============================] - 0s 417us/sample - loss: 0.0233 Epoch 44/100 1098/1098 [==============================] - 1s 805us/sample - loss: 0.0232 Epoch 45/100 1098/1098 [==============================] - 1s 630us/sample - loss: 0.0231 Epoch 46/100 1098/1098 [==============================] - 1s 674us/sample - loss: 0.0231 Epoch 47/100 1098/1098 [==============================] - 1s 623us/sample - loss: 0.0232 Epoch 48/100 1098/1098 [==============================] - 1s 813us/sample - loss: 0.0232 Epoch 49/100 1098/1098 [==============================] - 1s 597us/sample - loss: 0.0231s - loss: 0.023 Epoch 50/100 1098/1098 [==============================] - 1s 597us/sample - loss: 0.0232 Epoch 51/100 1098/1098 [==============================] - 1s 709us/sample - loss: 0.0231 Epoch 52/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0231 Epoch 53/100 1098/1098 [==============================] - 1s 966us/sample - loss: 0.0231 Epoch 54/100 1098/1098 [==============================] - 1s 760us/sample - loss: 0.0231 Epoch 55/100 1098/1098 [==============================] - 1s 901us/sample - loss: 0.0230 Epoch 56/100 1098/1098 [==============================] - 1s 849us/sample - loss: 0.0230 Epoch 57/100 1098/1098 [==============================] - 1s 556us/sample - loss: 0.0231s - loss: 0.0 Epoch 58/100 1098/1098 [==============================] - 1s 870us/sample - loss: 0.0232 Epoch 59/100 1098/1098 [==============================] - 1s 910us/sample - loss: 0.0232 Epoch 60/100 1098/1098 [==============================] - 1s 700us/sample - loss: 0.0230 Epoch 61/100 1098/1098 [==============================] - 1s 641us/sample - loss: 0.0229 Epoch 62/100 1098/1098 [==============================] - 1s 713us/sample - loss: 0.0230 Epoch 63/100 1098/1098 [==============================] - 1s 661us/sample - loss: 0.0231 Epoch 64/100 1098/1098 [==============================] - 1s 533us/sample - loss: 0.0230 Epoch 65/100 1098/1098 [==============================] - 1s 971us/sample - loss: 0.0232 Epoch 66/100 1098/1098 [==============================] - 1s 856us/sample - loss: 0.0230 Epoch 67/100 1098/1098 [==============================] - 1s 989us/sample - loss: 0.0230 Epoch 68/100 1098/1098 [==============================] - 1s 997us/sample - loss: 0.0230 Epoch 69/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0231 Epoch 70/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0230 Epoch 71/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0231 Epoch 72/100 1098/1098 [==============================] - 1s 848us/sample - loss: 0.0229 Epoch 73/100 1098/1098 [==============================] - 1s 938us/sample - loss: 0.0229 Epoch 74/100 1098/1098 [==============================] - 1s 724us/sample - loss: 0.0230 Epoch 75/100 1098/1098 [==============================] - 1s 788us/sample - loss: 0.0229s - loss: 0.02 Epoch 76/100 1098/1098 [==============================] - 1s 696us/sample - loss: 0.0230 Epoch 77/100 1098/1098 [==============================] - 1s 921us/sample - loss: 0.0230 Epoch 78/100 1098/1098 [==============================] - 1s 885us/sample - loss: 0.0229 Epoch 79/100 1098/1098 [==============================] - 1s 881us/sample - loss: 0.0229 Epoch 80/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0229 Epoch 81/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0230 Epoch 82/100 1098/1098 [==============================] - 1s 1ms/sample - loss: 0.0229 Epoch 83/100 1098/1098 [==============================] - 1s 838us/sample - loss: 0.0229 Epoch 84/100 1098/1098 [==============================] - 1s 764us/sample - loss: 0.0229 Epoch 85/100 1098/1098 [==============================] - 1s 738us/sample - loss: 0.0229 Epoch 86/100 1098/1098 [==============================] - 1s 909us/sample - loss: 0.0229 Epoch 87/100 1098/1098 [==============================] - 1s 751us/sample - loss: 0.0228 Epoch 88/100 1098/1098 [==============================] - 1s 590us/sample - loss: 0.0229 Epoch 89/100 1098/1098 [==============================] - 1s 646us/sample - loss: 0.0228 Epoch 90/100 1098/1098 [==============================] - 1s 704us/sample - loss: 0.0229 Epoch 91/100 1098/1098 [==============================] - 1s 938us/sample - loss: 0.0228 Epoch 92/100 ###Markdown Prepare test dataset and test LSTM model ###Code data_test = np.array(data_test) X_test, y_test = [], [] for i in range(7, len(data_test) - 7): X_test.append(data_test[i-7:i]) # past 7 days y_test.append(data_test[i:i+7]) # next 7 days X_test = np.array(X_test) y_test = np.array(y_test) X_test.shape, y_test.shape X_test = x_scaler.transform(X_test) y_test = y_scaler.transform(y_test) X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1) X_test.shape y_pred = regressor.predict(X_test) y_pred = y_scaler.inverse_transform(y_pred) y_pred y_true = y_scaler.inverse_transform(y_test) y_true.shape ###Output _____no_output_____ ###Markdown Evaluate model with RMSE ###Code def evaluate_model(y_true, y_predicted): scores = [] # calculate scores for each day for i in range(y_true.shape[1]): mse = mean_squared_error(y_true[:, i], y_predicted[:, i]) rmse = np.sqrt(mse) scores.append(rmse) # calculate score for whole prediction total_score = 0 for row in range(y_true.shape[0]): for col in range(y_predicted.shape[1]): total_score = total_score + (y_true[row, col] - y_predicted[row, col])**2 total_score = np.sqrt(total_score/(y_true.shape[0]*y_predicted.shape[1])) return total_score, scores ts, s = evaluate_model(y_true, y_pred) ts, s ###Output _____no_output_____ ###Markdown how to measure your model? -> global standard deviation of your model to the true values if error is less than the standard deviation, you can say your model is good ###Code np.std(y_true[0]), np.std (y_true[1]), np.std(y_true[2]) ###Output _____no_output_____
examples/Jupyter_notebook_examples/text_to_models/.ipynb_checkpoints/requirement_generator-checkpoint.ipynb
###Markdown Scripts to Models ###Code import os import sys sys.path.insert(0, os.path.abspath('..\..\..\sysmpy')) from sysmpy import * ###Output _____no_output_____ ###Markdown Requirement Generation ###Code text = "SAI should automatically optimize the spatial box arrangement." # 1. Perform SystemModelExtractor sp = SystemModelExtractor(text) model_info = sp.run() print(model_info) # 2. Perform ModelGenerator for requirement mg = ModelGenerator() req = mg.to_requirement(model_info) print(req) ###Output {'WHO': SAI, 'VERB': optimize, 'WHAT': the spatial box arrangement} SAI {'des': 'SAI shall optimize the spatial box arrangement'} ###Markdown Action Model Generation ###Code texts = ["System should automatically optimize the spatial box arrangement.", "System shall deliver three small products to each green level customer.", "System shall deliver two larger products to each gold level customer.", "System shall complete all product deliveries between 9PM Dec 24 and 6 AM Dec 25."] # 1. Perform SystemModelExtractor for t in texts: sp = SystemModelExtractor(t) model_info = sp.run() # 3. Perform ModelGenerator for action model mg = ModelGenerator() am = mg.to_action_model(model_info) # 2. covert the action model in the memory to an action model script sg = ScriptGenerator() script = sg.run(am) print(script) show(am, width=150) ###Output ID1756243530952 = Process('System') ID1756340927496 = ID1756243530952.Action('optimize the spatial box arrangement') ID1756330819848 = ID1756243530952.Action('deliver three small products') ID1756459032200 = ID1756243530952.Action('deliver two larger products') ID1756332097160 = ID1756243530952.Action('complete all product deliveries')
Exercise_notebooks/On_topic/10_data_types/numbers/01_numbers_exercise.ipynb
###Markdown 1. Creating formulasWrite the following mathematical formula in Python:\begin{align} result = 6a^3 - \frac{8b^2 }{4c} + 11\end{align} ###Code a = 2 b = 3 c = 2 # Your formula here: result = 50 assert result == 50 ###Output _____no_output_____ ###Markdown 2. Floating point pitfallsShow that `0.1 + 0.2 == 0.3` ###Code # Your solution here # This won't work: # assert 0.1 + 0.2 == 0.3 ###Output _____no_output_____
Movie_recommendation_system.ipynb
###Markdown Data acquisition RATINGS (userId / itemId) ###Code column_list = ['user id', 'item id', 'rating', 'timestamp'] data_content = pd.read_csv('ml-100k/u.data', delimiter='\t', names=column_list) data_content.head() ###Output _____no_output_____ ###Markdown USERS (age, gender, occupation & location) ###Code column_list = ['user id', 'age' , 'gender' , 'occupation' , 'zip code'] user_content = pd.read_csv('ml-100k/u.user', delimiter='\|', names=column_list, index_col=column_list[0], engine="python") user_content.head() ###Output _____no_output_____ ###Markdown MOVIES (Name & Categories) ###Code column_list = ['movie id', 'movie title', 'release date', 'video release date','IMDb URL','unknown','Action','Adventure','Animation','Childrens','Comedy','Crime','Documentary','Drama','fantasy','Film-Noir','Horror','Musical','Mystery','Romance','Sci-Fi','Thriller','War',' Western'] item_content = pd.read_csv('ml-100k/u.item', delimiter='\|', names=column_list, index_col=column_list[0], engine="python") item_content.head() #item_content['Average_rate'] = average_df #item_content ###Output _____no_output_____ ###Markdown USER-MOVIE Combined: ###Code # Define the number of users and the number of movies NB_USERS = len(user_content) NB_MOVIES = len(item_content) user_movie_rating = np.zeros((NB_USERS, NB_MOVIES)) for u_id in range(1, NB_USERS+1): #first id is 1 for index, row in data_content.loc[data_content['user id'] == u_id].iterrows(): user_movie_rating[u_id - 1][row['item id'] - 1] = row['rating'] #first id is 1 users_movies_df = pd.DataFrame(user_movie_rating) users_movies_df.columns = list(range(1, NB_MOVIES+1)) #first id is 1 users_movies_df.index = list(range(1, NB_USERS+1)) #first id is 1 users_movies_df = users_movies_df.rename_axis("movie_id", axis="columns") users_movies_df = users_movies_df.rename_axis("user_id", axis="rows") users_movies_df.head() ###Output _____no_output_____ ###Markdown Data Exploration RATINGS DF EXPLORATION ###Code NB_RATINGS = len(data_content) NB_RATINGS data_content['rating'].value_counts() plt.figure(figsize=(16, 8)) plt.subplot(121) n, bins, patches = plt.hist(data_content['rating'], np.arange(0.5, 5.6, 1), density=True, rwidth=0.8) plt.grid(True) x = np.linspace(1.0, 5.0, 1000) y = scipy.stats.norm.pdf(x, data_content['rating'].mean(), data_content['rating'].std()) plt.plot(x, y, color='red', linewidth=5) plt.xlabel("Ratings") plt.ylabel("%") plt.legend(["Gaussian approximation", "Distribution"]) plt.title("Ratings distribution in a histogram") #plt.subplot(122) #plt.pie(n, labels=list(range(1, 6)), autopct='%1.1f%%', shadow=False) #startangle=90, counterclock=False) #plt.title("Ratings distribution in a pie") #plt.show() plt.subplot(122) colors = ['tab:orange'] plt.barh(list(range(1, 6)), width=n, color=colors) plt.xlabel("Count") plt.ylabel("Rating") plt.title("Ratings distribution in a bar chart") plt.show() print("\t--> Average ratings : ", data_content['rating'].mean(), "/ 5") print("\t--> Standard deviation of the ratings : ", data_content['rating'].std()) print("\t--> Number of ratings : ", NB_RATINGS) ###Output _____no_output_____ ###Markdown ___________________________________________________________________________________________________________________ USERS DF EXPLORATION ###Code # Define the number of categories from the Movies (i.e. item_content) dataframe only_categories = item_content.drop(columns=["movie title", "release date", "video release date", "IMDb URL"]) categories_total = dict(only_categories.sum(axis=0)) NB_CATEGORIES = len(categories_total) NB_CATEGORIES_SELECTED = sum(categories_total.values()) print(NB_CATEGORIES) print(NB_CATEGORIES_SELECTED) gender_user_count = user_content['gender'].value_counts() gender_user_count # Reverse to show from largest to smallest gender_labels = list(gender_user_count.keys()) gender_labels.reverse() gender_user_count_list = list(gender_user_count) gender_user_count_list.reverse() plt.figure(figsize=(8, 8)) colors = ['tab:blue', 'tab:orange'] plt.barh(gender_labels, width=gender_user_count_list, color=colors) plt.xlabel("Count") plt.ylabel("Gender") plt.title("Distribution of genders within users") plt.show() print("\t--> Number of users : ", NB_USERS) age_user = user_content['age'] age_user_min = min(age_user) age_user_max = max(age_user) age_user_mean = age_user.mean() age_user_std = age_user.std() plt.figure(figsize=(12, 8)) plt.hist(age_user, np.arange(5, 76, 5), rwidth=0.95, alpha=0.4) plt.hist(age_user, np.arange(5, 76, 1), rwidth=0.7, color='blue') plt.legend(["Per 5 years", "Per year"]) plt.xlabel("Age") plt.ylabel("Count") plt.title("Ages of users") plt.show() print("\t--> Min age of users : ", age_user_min) print("\t--> Max age of users : ", age_user_max) print("\t--> Mean of ages of users : ", age_user_mean) print("\t--> Standart deviation of ages of users : ", age_user_std) occupation_user_count = user_content['occupation'].value_counts() NB_OCCUPATION = len(occupation_user_count) categories_total = {k: v for k, v in sorted(occupation_user_count.items(), key=lambda item: item[1])} #sort the dict labels = list(occupation_user_count.keys()) sizes = list(occupation_user_count.values) # Reverse the lists so that it is sorted from largest to smallest labels.reverse() sizes.reverse() plt.figure(figsize=(16, 8)) plt.barh(labels, width=sizes, color='tab:orange') plt.xlabel("Count") plt.ylabel("Occupations") plt.title("Occupations of users") plt.show() print("\t--> Number of categories : ", NB_CATEGORIES) print("\t--> Number of : ", NB_CATEGORIES_SELECTED) user_content['zip code'].value_counts() ###Output _____no_output_____ ###Markdown User Feature-Graph: ###Code users_attributes_content = user_content.copy() users_attributes_content.head() ###Output _____no_output_____ ###Markdown Create Gender Features: ###Code # Find male users, store as numpy array of 1s and 0s, then add as new column to users_attributes_content males = users_attributes_content['gender'].str.match('M').astype(int).to_numpy() users_attributes_content['male'] = males # Find female users, store as numpy array of 1s and 0s, then add as new column to users_attributes_content females = users_attributes_content['gender'].str.match('F').astype(int).to_numpy() users_attributes_content['female'] = females # Drop the original 'gender' column as it is no longer needed users_attributes_content = users_attributes_content.drop(columns=['gender']) # Visualize the result users_attributes_content.tail() ###Output _____no_output_____ ###Markdown Create Occupation Features: ###Code # Get the list of occupations from u.occupation # Probably a better way to do this, but just want it to be easy for now... column_list = ['occupations'] occupations_df = pd.read_csv('ml-100k/u.occupation', names=column_list) occupations_np_array = occupations_df['occupations'].to_numpy() # Iteratate over the occupations to add them as features to the users_attributes_content dataframe for occupation in (occupations_np_array): # Find occupation, store as numpy array of 1s and 0s, then add as new column to users_attributes_content occupation_feature_to_add = users_attributes_content['occupation'].str.match(occupation).astype(int).to_numpy() users_attributes_content[occupation] = occupation_feature_to_add # Drop the original 'occupation' column as it is no longer needed users_attributes_content = users_attributes_content.drop(columns=['occupation']) # Visualize the result users_attributes_content.head() ###Output _____no_output_____ ###Markdown Create Age Features: ###Code # Find age_range of users, store as numpy array of 1s and 0s, then add as new column to users_attributes_content # Range: 0-9 age_range_gt = users_attributes_content['age'].ge(0).to_numpy() age_range_lt = users_attributes_content['age'].lt(10).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['0-9'] = age_range_and # Range: 10-19 age_range_gt = users_attributes_content['age'].ge(10).to_numpy() age_range_lt = users_attributes_content['age'].lt(20).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['10-19'] = age_range_and # Range: 20-29 age_range_gt = users_attributes_content['age'].ge(20).to_numpy() age_range_lt = users_attributes_content['age'].lt(30).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['20-29'] = age_range_and # Range: 30-39 age_range_gt = users_attributes_content['age'].ge(30).to_numpy() age_range_lt = users_attributes_content['age'].lt(40).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['30-39'] = age_range_and # Range: 40-49 age_range_gt = users_attributes_content['age'].ge(40).to_numpy() age_range_lt = users_attributes_content['age'].lt(50).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['40-49'] = age_range_and # Range: 50-59 age_range_gt = users_attributes_content['age'].ge(50).to_numpy() age_range_lt = users_attributes_content['age'].lt(60).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['50-59'] = age_range_and # Range: 60-69 age_range_gt = users_attributes_content['age'].ge(60).to_numpy() age_range_lt = users_attributes_content['age'].lt(70).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['60-69'] = age_range_and # Range: 70-79 age_range_gt = users_attributes_content['age'].ge(70).to_numpy() age_range_lt = users_attributes_content['age'].lt(80).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['70-79'] = age_range_and # Range: 80-89 age_range_gt = users_attributes_content['age'].ge(80).to_numpy() age_range_lt = users_attributes_content['age'].lt(90).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['80-89'] = age_range_and # Range: 90-99 age_range_gt = users_attributes_content['age'].ge(90).to_numpy() age_range_lt = users_attributes_content['age'].lt(100).to_numpy() age_range_and = np.logical_and(age_range_lt,age_range_gt).astype(int) users_attributes_content['90-99'] = age_range_and # Drop the original 'age' column as it is no longer needed users_attributes_content = users_attributes_content.drop(columns=['age']) # Visualize the result users_attributes_content.tail() ###Output _____no_output_____ ###Markdown Create ZipCode Features:Note: used Wikipedia page for understanding Zipcode format: https://en.wikipedia.org/wiki/ZIP_Code ###Code # First find zipcodes that aren't integers (e.g. Alphanumeric zipcodes) and place them in 'Other' Category # Likely these are Canadian postal codes which were placed into the American zipcode format (e.g. V6T 1Z4 --> V6T1Z) other_zipcodes_inverted = users_attributes_content['zip code'].str.isnumeric().to_numpy() # Have to invert because we want the alphanumeric zipcodes to be '1' other_zipcodes = np.logical_not(other_zipcodes_inverted).astype(int) users_attributes_content['other_zipcodes'] = other_zipcodes # Get indices of "other zipcodes" other_zipcode_indices = np.argwhere(other_zipcodes).flatten() # Get numeric zipcodes and replace the 'other' zipcodes with an arbitrarily high number numeric_zipcodes = users_attributes_content['zip code'].copy() numeric_zipcodes_np = numeric_zipcodes.to_numpy() np.put(numeric_zipcodes_np,other_zipcode_indices,[99999]) # Get the first digits of all the zipcodes # Note the 9 will need some postprocessing due the replacing of alphanumeric zipcodes zipcodes_first_dig = numeric_zipcodes_np.astype(int).copy() zipcodes_first_dig = zipcodes_first_dig // 10**4 % 10 # Find all instances where the first digit of the zipcode is: 1 dig_1 = np.isin(zipcodes_first_dig,1) users_attributes_content['zip_1'] = dig_1.astype(int) # Find all instances where the first digit of the zipcode is: 2 dig_2 = np.isin(zipcodes_first_dig,2) users_attributes_content['zip_2'] = dig_2.astype(int) # Find all instances where the first digit of the zipcode is: 3 dig_3 = np.isin(zipcodes_first_dig,3) users_attributes_content['zip_3'] = dig_3.astype(int) # Find all instances where the first digit of the zipcode is: 4 dig_4 = np.isin(zipcodes_first_dig,4) users_attributes_content['zip_4'] = dig_4.astype(int) # Find all instances where the first digit of the zipcode is: 5 dig_5 = np.isin(zipcodes_first_dig,5) users_attributes_content['zip_5'] = dig_5.astype(int) # Find all instances where the first digit of the zipcode is: 6 dig_6 = np.isin(zipcodes_first_dig,6) users_attributes_content['zip_6'] = dig_6.astype(int) # Find all instances where the first digit of the zipcode is: 7 dig_7 = np.isin(zipcodes_first_dig,7) users_attributes_content['zip_7'] = dig_7.astype(int) # Find all instances where the first digit of the zipcode is: 8 dig_8 = np.isin(zipcodes_first_dig,8) users_attributes_content['zip_8'] = dig_8.astype(int) # Find all instances where the first digit of the zipcode is: 9 dig_9 = np.isin(zipcodes_first_dig,9).astype(int) # Note, need to correct for the alphanumeric zipcode replacement np.put(dig_9,other_zipcode_indices,[0]) users_attributes_content['zip_9'] = dig_9.astype(int) # Drop the original 'zip code' column as it is no longer needed users_attributes_content = users_attributes_content.drop(columns=['zip code']) # Visualize the result users_attributes_content.tail() ###Output _____no_output_____ ###Markdown Create Adjacency Matrix: ###Code # Create a copy to use later users_attributes_content_copy = users_attributes_content.copy() # Convert to array users_attributes_content = np.array(users_attributes_content) #users_attributes_content = np.where(users_attributes_content == 'M', 10, users_attributes_content) #users_attributes_content = np.where(users_attributes_content == 'F', 0, users_attributes_content) users_attributes_content = users_attributes_content.astype(np.int32) distance_users_attributes = np.zeros((NB_USERS, NB_USERS)) A_users_attributes = np.zeros((NB_USERS, NB_USERS)) from scipy.spatial import distance for user_idx in range(NB_USERS): for user_idx2 in range(NB_USERS): if user_idx != user_idx2: dst = distance.euclidean(users_attributes_content[user_idx], users_attributes_content[user_idx2]) distance_users_attributes[user_idx][user_idx2] = dst else: distance_users_attributes[user_idx][user_idx2] = 0 # Display the mean distance between users based on their features mean_distance_us_att = distance_users_attributes.mean() mean_distance_us_att # Plot a histogram of the euclidean distances plt.figure(1, figsize=(8, 4)) plt.title("Histogram of Euclidean distances between users") plt.hist(distance_users_attributes.flatten()); # Choose the mean_distance as the threshold threshold = mean_distance_us_att for i in range(A_users_attributes.shape[0]): for j in range(A_users_attributes.shape[1]): if i != j: if distance_users_attributes[i][j] < threshold: A_users_attributes[i][j] = 1 ###Output _____no_output_____ ###Markdown Degree Distribution: ###Code num_nodes_users_attributes = NB_USERS num_edges_users_attributes = int(np.where(A_users_attributes > 0, 1, 0).sum() / 2) print(f"Number of nodes in the users graph: {num_nodes_users_attributes}") print(f"Number of edges in the users graph: {num_edges_users_attributes}") degrees_users_attributes = A_users_attributes.sum(axis=1) deg_hist_normalization = np.ones(degrees_users_attributes.shape[0]) / degrees_users_attributes.shape[0] plt.figure(figsize=(8, 4)) plt.title('Users attributes (features) graph degree distribution') plt.hist(degrees_users_attributes, weights=deg_hist_normalization, rwidth=0.95); feat_moment_1 = degrees_users_attributes.mean() feat_moment_2 = (degrees_users_attributes**2).mean() print(f"1st moment of feature graph: {feat_moment_1}") print(f"2nd moment of feature graph: {feat_moment_2}") # Observe sparsity pattern of the graph: plt.figure(figsize=(8, 8)) plt.title('User Feature graph: adjacency matrix sparsity pattern') plt.spy(A_users_attributes); ###Output _____no_output_____ ###Markdown Network Model for User Feature-Graph: ###Code import networkx as nx G_feature = nx.from_numpy_matrix(A_users_attributes) print('Number of nodes: {}, Number of edges: {}'. format(G_feature.number_of_nodes(), G_feature.number_of_edges())) print('Number of self-loops: {}, Number of connected components: {}'. format(G_feature.number_of_selfloops(), nx.number_connected_components(G_feature))) ###Output Number of nodes: 943, Number of edges: 153468 Number of self-loops: 0, Number of connected components: 1 ###Markdown Clustering coefficient: ###Code nx.average_clustering(G_feature) ###Output _____no_output_____ ###Markdown Epsilon Similarity Graph for User Feature-Graph: ###Code from scipy.spatial.distance import pdist, squareform def epsilon_similarity_graph(X: np.ndarray, sigma=1, epsilon=0): """ X (n x d): coordinates of the n data points in R^d. sigma (float): width of the kernel epsilon (float): threshold Return: adjacency (n x n ndarray): adjacency matrix of the graph. """ #Computation of Weighted adjacency matrix (Kernel rbf) distance_condensed = pdist(X, 'euclidean') distance_redundant = squareform(distance_condensed) K_rbf = np.exp(-(distance_redundant**2)/(2*(sigma**2))) #Display results plt.figure(figsize=(15,4)) plt.subplot(1, 2, 1) plt.scatter(distance_redundant[::100], K_rbf[::100]) plt.plot([distance_condensed.min(), distance_condensed.max()], [epsilon, epsilon], 'r-', lw=2) plt.legend(("threshold", "with sigma="+str(sigma))) plt.xlabel("dist(i, j)") plt.ylabel("w(i,j)") #W other way to calculate K_rbf = W K_rbf = np.where(K_rbf < epsilon, 0, K_rbf) - np.eye(K_rbf.shape[0]) adjacency = K_rbf #Display results plt.subplot(1, 3, 3) counts, bins = np.histogram(adjacency) plt.title('Adjacency degree distribution') plt.hist(bins[:-1], bins, weights = counts) plt.show() return adjacency def distanceMean(X: np.ndarray): distance_condensed = pdist(X, 'euclidean') return distance_condensed.mean() adjacency = epsilon_similarity_graph(users_attributes_content_copy, sigma=distanceMean(users_attributes_content_copy)*0.375, epsilon=0.1) plt.spy(adjacency) plt.show() ###Output _____no_output_____ ###Markdown Laplacian: ###Code def compute_laplacian(adjacency: np.ndarray, normalize: bool): """ Return: L (n x n ndarray): combinatorial or symmetric normalized Laplacian. """ D = np.diag(np.sum(adjacency, 1)) # Degree matrix combinatorial = D - adjacency if normalize: D_norm = np.diag(np.clip(np.sum(adjacency, 1), 1, None)**(-1/2)) return D_norm @ combinatorial @ D_norm else: return combinatorial laplacian_comb = compute_laplacian(adjacency, normalize=False) laplacian_norm = compute_laplacian(adjacency, normalize=True) def spectral_decomposition(laplacian: np.ndarray): """ Return: lamb (np.array): eigenvalues of the Laplacian U (np.ndarray): corresponding eigenvectors. """ return np.linalg.eigh(laplacian) lamb_comb, U_comb = spectral_decomposition(laplacian_comb) lamb_norm, U_norm = spectral_decomposition(laplacian_norm) plt.figure(figsize=(12,5)) plt.subplot(121) plt.plot(lamb_comb) plt.xlabel('Index') plt.ylabel('Eigenvalue') plt.title('Eigenvalues $L_{comb}$') plt.subplot(122) plt.plot(lamb_norm) plt.xlabel('Index') plt.ylabel('Eigenvalue') plt.title('Eigenvalues $L_{norm}$') plt.show() ###Output _____no_output_____ ###Markdown ______________________________________________________________________________________________________ MOVIES DF EXPLORATION ###Code # Get a movie's 'average rating' based off the ratings from each user in the user_movies_df average_df = users_movies_df.sum(axis=0) average_df = average_df/ users_movies_df.astype(bool).sum(axis=0) average_df # Add this new average rating as a column in the item_content dataframe item_content['Average_rate'] = average_df # Display the updated dataframe to see the change item_content.head() full_dates = item_content['release date'].values all_years = [] for date in full_dates: if date is not np.nan : year = date[-4:] all_years.append(int(year)) all_years = np.array(sorted(all_years)) min_year = all_years.min() max_year = all_years.max() only_categories = item_content.drop(columns=["movie title", "release date", "video release date", "IMDb URL", "Average_rate"]) categories_total = dict(only_categories.sum(axis=0)) NB_CATEGORIES = len(categories_total) NB_CATEGORIES_SELECTED = sum(categories_total.values()) categories_total = {k: v for k, v in sorted(categories_total.items(), key=lambda item: item[1])} #sort the dict labels = list(categories_total.keys()) sizes = list(categories_total.values()) plt.figure(figsize=(12, 15)) plt.subplot(211) plt.hist(all_years, np.arange(1920, 2001, 10), density=False, rwidth=0.95, alpha=0.2, color='red') plt.hist(all_years, np.arange(min_year, max_year, 1), density=False, rwidth=0.8) plt.xlabel("Date") plt.ylabel("Count") plt.legend(["Per decade", "Per year"]) plt.title("Number of movies rated per epoch in the dataset") plt.subplot(212) plt.barh(labels, width=sizes, color='orange') plt.xlabel("Count") plt.ylabel("Categories") plt.title("Categories of movies rated") plt.show() print("REF to figure 1:") print("\t--> Number of movies rated : ", NB_MOVIES) print("\t--> Epoch of movies rated : ", min_year, 'to', max_year) print("\nREF to figure 2:") print("\t--> Number of categories : ", NB_CATEGORIES) print("\t--> Number of : ", NB_CATEGORIES_SELECTED) movies_content = item_content.drop(columns=["movie title", "release date", "video release date", "IMDb URL"]) movies_content ###Output _____no_output_____ ###Markdown Create Adjacency Matrix: ###Code movies_content = np.array(movies_content) distance_movies = np.zeros((NB_MOVIES, NB_MOVIES)) A_movies = np.zeros((NB_MOVIES, NB_MOVIES)) for movie_idx in range(NB_MOVIES): for movie_idx2 in range(NB_MOVIES): #similiraty = np.logical_and(movies_content[movie_idx], movies_content[movie_idx2]) #_max = max(movies_content[movie_idx].sum(), movies_content[movie_idx2].sum()) #score = similiraty.sum() / _max if movie_idx != movie_idx2: dst = distance.euclidean(movies_content[movie_idx], movies_content[movie_idx2]) distance_movies[movie_idx][movie_idx2] = dst else: distance_movies[movie_idx][movie_idx2] = 0 # Display the mean distance between movies based on their features mean_distance_mov_att = distance_movies.mean() mean_distance_mov_att # Plot a histogram of the euclidean distances plt.figure(1, figsize=(8, 4)) plt.title("Histogram of Euclidean distances between movies") plt.hist(distance_movies.flatten()); # Choose the mean_distance as the threshold threshold = mean_distance_mov_att for i in range(A_movies.shape[0]): for j in range(A_movies.shape[1]): if i != j: if distance_movies[i][j] < threshold: A_movies[i][j] = 1 ###Output _____no_output_____ ###Markdown Feature Degree Distribution: ###Code num_nodes_movies_attributes = NB_MOVIES num_edges_movies_attributes = int(np.where(A_movies > 0, 1, 0).sum() / 2) print(f"Number of nodes in the users graph: {num_nodes_movies_attributes}") print(f"Number of edges in the users graph: {num_edges_movies_attributes}") degrees_movies_attributes = A_movies.sum(axis=1) deg_hist_normalization = np.ones(degrees_movies_attributes.shape[0]) / degrees_movies_attributes.shape[0] plt.figure(figsize=(8, 4)) plt.title('Movies - features graph degree distribution') plt.hist(degrees_movies_attributes, weights=deg_hist_normalization, rwidth=0.95); feat_moment_1 = degrees_movies_attributes.mean() feat_moment_2 = (degrees_movies_attributes**2).mean() print(f"1st moment of feature graph: {feat_moment_1}") print(f"2nd moment of feature graph: {feat_moment_2}") # Observe sparsity pattern of the graph: plt.figure(figsize=(8, 8)) plt.title('Movie Feature graph: adjacency matrix sparsity pattern') plt.spy(A_movies); ###Output _____no_output_____ ###Markdown Clustering coefficient: ###Code import networkx as nx G_feature = nx.from_numpy_matrix(A_movies) print('Number of nodes: {}, Number of edges: {}'. format(G_feature.number_of_nodes(), G_feature.number_of_edges())) print('Number of self-loops: {}, Number of connected components: {}'. format(G_feature.number_of_selfloops(), nx.number_connected_components(G_feature))) nx.average_clustering(G_feature) ###Output _____no_output_____ ###Markdown Epsilon Similarity Graph for Movie Feature-Graph: ###Code adjacency = epsilon_similarity_graph(movies_content, sigma=distanceMean(movies_content)*0.475, epsilon=0.175) plt.spy(adjacency) plt.show() laplacian_comb = compute_laplacian(adjacency, normalize=False) laplacian_norm = compute_laplacian(adjacency, normalize=True) lamb_comb, U_comb = spectral_decomposition(laplacian_comb) lamb_norm, U_norm = spectral_decomposition(laplacian_norm) plt.figure(figsize=(12,5)) plt.subplot(121) plt.plot(lamb_comb) plt.xlabel('Index') plt.ylabel('Eigenvalue') plt.title('Eigenvalues $L_{comb}$') plt.subplot(122) plt.plot(lamb_norm) plt.xlabel('Index') plt.ylabel('Eigenvalue') plt.title('Eigenvalues $L_{norm}$') plt.show() def compute_number_connected_components(lamb: np.array, threshold: float): """ lamb: array of eigenvalues of a Laplacian Return: n_components (int): number of connected components. """ n_components = np.count_nonzero(lamb < threshold) return (n_components) print(compute_number_connected_components(lamb_norm, threshold=1e-20)) ###Output 1 ###Markdown Spectral clustering ###Code from sklearn.cluster import KMeans x = U_norm[:, 1] x = x.reshape(-1, 1) y = U_norm[:, 2] kmeans = KMeans(n_clusters=18) y_pred = kmeans.fit_predict(x) plt.scatter(x,y, c=y_pred) plt.show() class SpectralClustering(): def __init__(self, n_classes: int, normalize: bool): self.n_classes = n_classes self.normalize = normalize self.laplacian = None self.e = None self.U = None self.clustering_method = KMeans(n_classes) def fit_predict(self, adjacency): """ Your code should be correct both for the combinatorial and the symmetric normalized spectral clustering. Return: y_pred (np.ndarray): cluster assignments. """ self.laplacian = compute_laplacian(adjacency, self.normalize) self.e, self.U = spectral_decomposition(self.laplacian) self.U = self.U[:,:2] #compute eigenvectors of k smallest eigenvalues U=[u1|u2|...uk] watchOUT it starts with 1 y_pred = KMeans(n_clusters = self.n_classes).fit_predict(self.U) return y_pred print("Connected components:", compute_number_connected_components(lamb_norm, threshold=1e-30)) spectral_clustering = SpectralClustering(n_classes=18, normalize=True) y_pred = spectral_clustering.fit_predict(adjacency) plt.scatter(U_norm[:, 1], U_norm[:, 2], c=y_pred) plt.show() ###Output Connected components: 1 ###Markdown __________________________________________________________________________________________________ Data Exploitation USER - MOVIE DF ###Code user_movie_rating = np.zeros((NB_USERS, NB_MOVIES)) for u_id in range(1, NB_USERS+1): #first id is 1 for index, row in data_content.loc[data_content['user id'] == u_id].iterrows(): user_movie_rating[u_id - 1][row['item id'] - 1] = row['rating'] #first id is 1 users_movies_df = pd.DataFrame(user_movie_rating) users_movies_df.columns = list(range(1, NB_MOVIES+1)) #first id is 1 users_movies_df.index = list(range(1, NB_USERS+1)) #first id is 1 users_movies_df = users_movies_df.rename_axis("movie_id", axis="columns") users_movies_df = users_movies_df.rename_axis("user_id", axis="rows") users_movies_df users_movies = np.array(users_movies_df).astype(np.int32) users_movies users_categories = np.zeros((NB_USERS ,NB_CATEGORIES)) # Reinitialize movies_content to remove extra "Average_rate" column we added earlier movies_content = item_content.drop(columns=["movie title", "release date", "video release date", "IMDb URL", "Average_rate"]) movies_content = np.array(movies_content) for user_idx in range(NB_USERS): for movie_idx in range(NB_MOVIES): if users_movies[user_idx][movie_idx] != 0: users_categories[user_idx] += movies_content[movie_idx] users_categories_normalize = np.zeros((NB_USERS ,NB_CATEGORIES)) for row in range(users_categories.shape[0]): users_categories_normalize[row] = users_categories[row] / users_categories.sum(axis=1)[row] pd.DataFrame(users_categories_normalize) #Cluster each user accordint to their categories #Find best number of clusters thanks to the elbow method from sklearn.cluster import KMeans sse = {} for k in range(1, 30): model = KMeans(n_clusters=k) y_pred = model.fit_predict(users_categories_normalize) sse[k] = model.inertia_ plt.figure(figsize=(15, 8)) plt.plot(list(sse.keys()), list(sse.values()), '-*') plt.xlabel("Number of cluster") plt.ylabel("SSE") plt.title("Elbow curve") plt.show() #Thanks to the Elbow method, 6 clusters seems to be good ! N_CLUSTERS = 6 model = KMeans(n_clusters=N_CLUSTERS) y_pred = model.fit_predict(users_categories_normalize) #Cluster analyze 1 CLUSTER, N_USERS_CLUSTER = np.unique(y_pred, return_counts=True) plt.figure() plt.bar(x=range(N_CLUSTERS), height=N_USERS_CLUSTER) plt.xlabel('Cluster') plt.ylabel('Count') plt.title('Number of users per cluster') plt.show() #Visualization of the clustering approach thanks to Isomap from sklearn.decomposition import PCA from sklearn.manifold import TSNE, Isomap X_embedded_2d = Isomap(n_components=2, n_neighbors=5).fit_transform(users_categories_normalize) plt.figure(figsize=(12, 10)) for i in range(N_CLUSTERS): mask = y_pred == i plt.scatter(X_embedded_2d[mask, 0], X_embedded_2d[mask, 1], label=i) plt.legend() plt.show() #Define the different cluster (user_id) group_0 = np.argwhere(y_pred == 0).reshape(-1) group_1 = np.argwhere(y_pred == 1).reshape(-1) group_2 = np.argwhere(y_pred == 2).reshape(-1) group_3 = np.argwhere(y_pred == 3).reshape(-1) group_4 = np.argwhere(y_pred == 4).reshape(-1) group_5 = np.argwhere(y_pred == 5).reshape(-1) groups = [group_0, group_1, group_2, group_3, group_4, group_5] #Cluster analyze 2 : Ratio of ratings per categorie in each cluster plt.figure(figsize=(20, 30)) plt.subplot(611) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_0].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 0") plt.subplot(612) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_1].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 1") plt.subplot(613) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_2].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 2") plt.subplot(614) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_3].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 3") plt.subplot(615) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_4].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 4") plt.subplot(616) plt.bar(x=list(categories_total.keys()), height=users_categories_normalize[group_5].mean(axis=0)) plt.ylabel('%') plt.ylim([0, 0.4]) plt.title("Cluster 5") plt.show() #Cluster analyze 3 ratio_movies_watched = [] for group in groups: ratio_movies_watched.append(np.where(users_movies[group].sum(axis = 0) > 0, 1, 0).sum() / NB_MOVIES) plt.figure(figsize=(12, 7)) plt.bar(x=np.arange(N_CLUSTERS) - 0.35/2 , height=ratio_movies_watched, width=0.35) plt.bar(x=np.arange(N_CLUSTERS) + 0.35/2 , height=N_USERS_CLUSTER/NB_USERS, width=0.35) plt.ylim([0, 1]) plt.xlabel('Cluster') plt.ylabel('%') plt.legend(["Number of movies watched (relative to the total number of movies)", "Number of users in the cluster (relative to the total number of users)"]) plt.show() #Cluster analyze 4 : how a movie has been watched by users movie_180_count_groups = [] movie_26_count_groups = [] movie_1279_count_groups = [] movie_915_count_groups = [] for group_idx, group in enumerate(groups): movie_180_count_groups.append(np.count_nonzero(users_movies[group], axis = 0)[180] / N_USERS_CLUSTER[group_idx]) movie_26_count_groups.append(np.count_nonzero(users_movies[group], axis = 0)[26] / N_USERS_CLUSTER[group_idx]) movie_1279_count_groups.append(np.count_nonzero(users_movies[group], axis = 0)[1279] / N_USERS_CLUSTER[group_idx]) movie_915_count_groups.append(np.count_nonzero(users_movies[group], axis = 0)[915] / N_USERS_CLUSTER[group_idx]) plt.figure(figsize=(16, 10)) plt.subplot(221) plt.bar(x=range(N_CLUSTERS), height=movie_180_count_groups) plt.xlabel('Cluster') plt.ylabel('%') plt.title("Ratio of users who have watched the movie 180") plt.subplot(222) plt.bar(x=range(N_CLUSTERS), height=movie_26_count_groups) plt.xlabel('Cluster') plt.ylabel('%') plt.title("Ratio of users who have watched the movie 26") plt.subplot(223) plt.bar(x=range(N_CLUSTERS), height=movie_1279_count_groups) plt.xlabel('Cluster') plt.ylabel('%') plt.title("Ratio of users who have watched the movie 1279") plt.subplot(224) plt.bar(x=range(N_CLUSTERS), height=movie_915_count_groups) plt.xlabel('Cluster') plt.ylabel('%') plt.title("Ratio of users who have watched the movie 915") plt.show() #Recommandation model #Average of ratings for each movie ratings_movies = (users_movies.sum(axis = 0) / np.count_nonzero(users_movies, axis=0)) ratings_movies #Average of ratings for each movie for each cluster #Sort the movie for each cluster according to these averages ratings_mean_groups = [] movies_sort_groups = [] for group in groups: ratings_mean_group = users_movies[group].sum(axis = 0) / np.count_nonzero(users_movies[group], axis=0) ratings_mean_group = np.where(np.isnan(ratings_mean_group), 0, ratings_mean_group) movies_sort_group = np.argsort(ratings_mean_group) for i, v in enumerate(movies_sort_group): if ratings_mean_group[v] == 0: lim = i movies_sort_group = movies_sort_group[lim+1:] ratings_mean_groups.append(ratings_mean_group) movies_sort_groups.append(movies_sort_group) def recommandation(user_id: int, number_recommandations: int): "Return a list of movie_id according to the ratings of movies and the group of the user." #Determine the group of the user for group_idx, group in enumerate(groups): if np.isin(group, user_id).any(): break #Determine which movie the user has aready watched user_has_watched = np.nonzero(users_movies[user_id])[0] cluster_have_watched = movies_sort_groups[group_idx] #Detemine which movie the user has not watched relative to his group user_has_not_watched = [] for movie_id in cluster_have_watched: if np.isin(user_has_watched, movie_id).any() == False: user_has_not_watched.append(movie_id) #Determine the "ratings" of these movies by tacking into account the rating of the cluster and the rating of all users: ratings_recommandation = np.zeros((NB_MOVIES)) for movie_id in user_has_not_watched: ratings_recommandation[movie_id] = (ratings_movies[movie_id] + ratings_mean_groups[group_idx][movie_id]) / 2 #Sort these ratings user_recommandation = np.argsort(ratings_recommandation) #Return if len(user_recommandation) > number_recommandations: return user_recommandation[-number_recommandations:], group_idx else: return user_recommandation, group_idx def display_recommandation(user_recommandation, group_idx): for i, movie_id in enumerate(user_recommandation): print("-- Recommandation ", i+1, "--") print("\tTitle: ", item_content.iloc[movie_id][0]) print("\tRelease date: ", item_content.iloc[movie_id][1]) print("\tCluster rating: ", ratings_mean_groups[group_idx][movie_id], "/5") print("\tRating of all users: ", ratings_movies[movie_id], "/5") print("\tCategorie(s): ", [k for k, v in (item_content.iloc[movie_id].items()) if v==1]) print() #Test these recommandation system with the user_id = 189 user_recommandation, group_idx = recommandation(189, 8) display_recommandation(user_recommandation, group_idx) ###Output -- Recommandation 1 -- Title: Schindler's List (1993) Release date: 01-Jan-1993 Cluster rating: 4.666666666666667 /5 Rating of all users: 4.466442953020135 /5 Categorie(s): ['Drama', 'War'] -- Recommandation 2 -- Title: Henry V (1989) Release date: 01-Jan-1989 Cluster rating: 5.0 /5 Rating of all users: 4.137096774193548 /5 Categorie(s): ['Drama', 'War'] -- Recommandation 3 -- Title: Thin Man, The (1934) Release date: 01-Jan-1934 Cluster rating: 5.0 /5 Rating of all users: 4.15 /5 Categorie(s): ['Mystery'] -- Recommandation 4 -- Title: Raise the Red Lantern (1991) Release date: 01-Jan-1991 Cluster rating: 5.0 /5 Rating of all users: 4.155172413793103 /5 Categorie(s): ['Drama'] -- Recommandation 5 -- Title: Kaspar Hauser (1993) Release date: 07-Jun-1996 Cluster rating: 5.0 /5 Rating of all users: 4.25 /5 Categorie(s): ['Drama'] -- Recommandation 6 -- Title: Shall We Dance? (1996) Release date: 11-Jul-1997 Cluster rating: 5.0 /5 Rating of all users: 4.260869565217392 /5 Categorie(s): ['Comedy'] -- Recommandation 7 -- Title: 12 Angry Men (1957) Release date: 01-Jan-1957 Cluster rating: 5.0 /5 Rating of all users: 4.344 /5 Categorie(s): ['Drama'] -- Recommandation 8 -- Title: Star Kid (1997) Release date: 16-Jan-1998 Cluster rating: 5.0 /5 Rating of all users: 5.0 /5 Categorie(s): ['Adventure', 'Childrens', 'fantasy', 'Sci-Fi'] ###Markdown This project is a code along for the article I read here: https://www.analyticsvidhya.com/blog/2020/11/create-your-own-movie-movie-recommendation-system/ ###Code # Importing required libraries and packages import pandas as pd import numpy as np from scipy.sparse import csr_matrix from sklearn.neighbors import NearestNeighbors import matplotlib.pyplot as plt import seaborn as sns # Importing the datasets movies = pd.read_csv('Movie_recommendation_datasets/movies.csv') ratings = pd.read_csv("Movie_recommendation_datasets/ratings.csv") movies.head() ratings.head() final_dataset = ratings.pivot(index='movieId',columns='userId',values='rating') final_dataset.head() final_dataset.fillna(0,inplace=True) final_dataset.head() ###Output _____no_output_____ ###Markdown Visualizing the filters ###Code no_user_voted = ratings.groupby('movieId')['rating'].agg('count') no_movies_voted = ratings.groupby('userId')['rating'].agg('count') f,ax = plt.subplots(1,1,figsize=(16,4)) # ratings['rating'].plot(kind='hist') plt.scatter(no_user_voted.index,no_user_voted,color='mediumseagreen') plt.axhline(y=10,color='r') plt.xlabel('MovieId') plt.ylabel('No. of users voted') plt.show() ###Output _____no_output_____ ###Markdown Making the necessary modifications as per the threshold set ###Code final_dataset = final_dataset.loc[no_user_voted[no_user_voted > 10].index,:] f,ax = plt.subplots(1,1,figsize=(16,4)) plt.scatter(no_movies_voted.index,no_movies_voted,color='mediumseagreen') plt.axhline(y=50,color='r') plt.xlabel('UserId') plt.ylabel('No. of votes by user') plt.show() final_dataset=final_dataset.loc[:,no_movies_voted[no_movies_voted > 50].index] final_dataset ###Output _____no_output_____ ###Markdown Removing sparsity ###Code sample = np.array([[0,0,3,0,0],[4,0,0,0,2],[0,0,0,0,1]]) sparsity = 1.0 - ( np.count_nonzero(sample) / float(sample.size) ) print(sparsity) csr_sample = csr_matrix(sample) print(csr_sample) csr_data = csr_matrix(final_dataset.values) final_dataset.reset_index(inplace=True) ###Output _____no_output_____ ###Markdown Making the movie recommendation system model ###Code knn = NearestNeighbors(metric='cosine', algorithm='brute', n_neighbors=20, n_jobs=-1) knn.fit(csr_data) ###Output _____no_output_____ ###Markdown Making the recommendation function ###Code def get_movie_recommendation(movie_name): n_movies_to_reccomend = 10 movie_list = movies[movies['title']].str.contains(movie_name) if len(movie_list): movie_idx = movie_list.iloc[0]['movieId'] movie_idx = final_dataset[final_dataset['movieId'] == movie_idx].index[0] distances , indices = knn.kneighbors(csr_data[movie_idx],n_neighbors=n_movies_to_reccomend+1) rec_movie_indices = sorted(list(zip(indices.squeeze().tolist(),distances.squeeze().tolist())),key=lambda x: x[1])[:0:-1] recommend_frame = [] for val in rec_movie_indices: movie_idx = final_dataset.iloc[val[0]]['movieId'] idx = movies[movies['movieId'] == movie_idx].index recommend_frame.append({'Title':movies.iloc[idx]['title'].values[0],'Distance':val[1]}) df = pd.DataFrame(recommend_frame,index=range(1,n_movies_to_reccomend+1)) return df else: return "No movies found. Please check your input" ###Output _____no_output_____ ###Markdown We are going to use imdb dataset to create content based recommended system.Datasets = https://drive.google.com/file/d/1bPm6emwAUgCwGs_jX6FGAUTPUCDcvApR/view?usp=sharing,%20https://drive.google.com/file/d/1urB8DUCOEMAbMyo1sMBTkcKm7JquZ2dE/view?usp=sharing ###Code import pandas as pd import numpy as np credits = pd.read_csv("/content/tmdb_5000_credits.csv") movies = pd.read_csv("/content/tmdb_5000_movies.csv") (movies.info()) (movies.head()) credits.info() credits.head() print('credits :',credits.shape) print('movies :',movies.shape) ###Output credits : (4803, 4) movies : (4803, 20) ###Markdown Now we will merge both the datasets on the basis of movie id ###Code credits_renamed = credits.rename(index=str,columns={"movie_id":"id"}) credits_renamed = credits.drop(columns=['title']) movies_credits_merge= movies.merge(credits_rename, on='id') (movies_credits_merge.head()) movies_cleaned =movies_credits_merge.drop(columns=['homepage','status','title_x','title_y','production_countries']) movies_cleaned.info() ###Output <class 'pandas.core.frame.DataFrame'> Int64Index: 4803 entries, 0 to 4802 Data columns (total 18 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 budget 4803 non-null int64 1 genres 4803 non-null object 2 id 4803 non-null int64 3 keywords 4803 non-null object 4 original_language 4803 non-null object 5 original_title 4803 non-null object 6 overview 4800 non-null object 7 popularity 4803 non-null float64 8 production_companies 4803 non-null object 9 release_date 4802 non-null object 10 revenue 4803 non-null int64 11 runtime 4801 non-null float64 12 spoken_languages 4803 non-null object 13 tagline 3959 non-null object 14 vote_average 4803 non-null float64 15 vote_count 4803 non-null int64 16 cast 4803 non-null object 17 crew 4803 non-null object dtypes: float64(3), int64(4), object(11) memory usage: 712.9+ KB ###Markdown Now we are going to use movie summaries to create a vector for each movie in which we will use the words in our summary. Then we will compare vectors of all movies and recommend those which will have similar values.We will use tfidf from sklearn to implement this. ###Code from sklearn.feature_extraction.text import TfidfVectorizer tfv = TfidfVectorizer(min_df = 3, max_features=None, strip_accents='unicode', analyzer='word', token_pattern= 'r\w{1,}', # \w{1,} = alphanum with minimum 1 letter ngram_range=(1,3), # will create combination sets of 1 to 3 words stop_words='english') # we fill fit the tfidf on summary text print(movies_cleaned['overview']) tfv_matrix = tfv.fit_transform(movies_cleaned['overview'].values.astype('U')) #astype converts it to unicode print(tfv_matrix, ' \n', tfv_matrix.shape) # so now we have vectors from sklearn.metrics.pairwise import sigmoid_kernel '''sigmoid kernel basically calculates hyperbolic tangent betw two vectors,i.e,distance between 2 vectors This will show us how similar two movie summaries are based on the distances betw vector values''' sigma = sigmoid_kernel(tfv_matrix,tfv_matrix) print(sig[0]) # Now we will map these values with their titles # we have created a Series which has title:index which is hashed indices = pd.Series(movies_cleaned.index, index = movies_cleaned['original_title']).drop_duplicates() print(indices) print(indices['Avatar']) print(sig[4802]) print(list(enumerate(sigma[indices['Avatar']]))) # this shows us vector of avatar compared with all the movies # now we have sorted the list based on vector values closest to our given movie print(sorted(list(enumerate(sigma[indices['Avatar']])),key=lambda x: x[1], reverse=True)) # now we will give create a function to give 10 recommendations based on movie title def give_recommendations(title): #get index idx= indices[title] #Get similarity score sigma_scores = list(enumerate(sigma[idx])) #sort the movies according to scores sigma_scores = sorted(sigma_scores, key= lambda x: x[1], reverse=True) #get 10 most similar movies sigma_scores =sigma_scores[1:11] # print(sigma_scores) #get Movie indices movie_indices = [ i[0] for i in sigma_scores] #print(movie_indices) #print 10 similar movies print('Movies similar to ',title," are : \n") return movies_cleaned['original_title'].iloc[movie_indices] print(give_recommendations('Spectre'),'\n') print(give_recommendations("The Dark Knight Rises")) # this was a very basic attempt at doing this , I will be fine tuning this... ###Output Movies similar to Spectre are : 3162 Thunderball 1281 Hackers 3351 The Man with the Golden Gun 1967 The Fisher King 367 The Interpreter 4402 In Her Line of Fire 3285 Restless 753 The Sentinel 1200 The Living Daylights 2933 F.I.S.T. Name: original_title, dtype: object Movies similar to The Dark Knight Rises are : 299 Batman Forever 2507 Slow Burn 65 The Dark Knight 1181 JFK 879 Law Abiding Citizen 1202 Legal Eagles 3595 Halloween: The Curse of Michael Myers 307 The Expendables 3 2193 Secret in Their Eyes 42 Toy Story 3 Name: original_title, dtype: object
DS2020-14-MAY-Python.ipynb
###Markdown List Comprehension ###Code # Advance list sequence and using for loop u can create a built-in function. It is represented in [] Lst= [x for x in "Python"] Lst lst= [x for x in range (6)] lst range(6) list(range(6)) lst = [x**2 for x in range(1,11)] lst list(range(1,11)) lst= [x+2 for x in range(1,11,4)] lst list(range(1,11,4)) ###Output _____no_output_____ ###Markdown Fahrenheit = (9/5)*Temp(c) +32 ###Code Fahrenheit = [float(9/5)* Temp +32 for Temp in [100,200,300, 120]] Fahrenheit # converting Fahrenheit to celcius ###Output _____no_output_____ ###Markdown Celcius = (F-32)*(5/9) ###Code Celcius= [(F-32)*(5/9) for F in [212.0, 392.0, 572.0, 248.0]] Celcius ###Output _____no_output_____ ###Markdown Nested list comprehension ###Code Lst= [x+2 for x in [x**2 for x in range(5)]] Lst A= [x**2 for x in range(5)] A Lst= [x for x in range(11) if x %2 ==0] Lst ###Output _____no_output_____ ###Markdown Lambda Function Called an Anonymous function. use code with single line of expression. When you want to create an ad-hoc function, Lambda function can be used.'def'==> for creation of user-defined function, when u have to perform simple codesdef is used for more larger coding ###Code def square(num): return num**2 print(square(5)) def square(num): return num**2 square(8) def square (num): return num**2 square(4) square = lambda num : num**2 square(5) add= lambda x,y : x+y add(4,6) Add= lambda x,y,z : x*y+z*2 Add(2,5,1) # 2*5 +1*2= 10+2=12 Fahrenheit = lambda T : (9/5)*T +32 Fahrenheit(100) ###Output _____no_output_____ ###Markdown Function Functions are main building bloacks to construct larger amount of code to solve problems. ==> Functions can be reused once defined. it encourages code reusability. divides a program into Modules which makes code easier to "Manage","Debug", and "Scale def function_name(arg1, arg2, arg3,..): ''' '''returnprint( call the function(arg1, arg2)) Rules to define function Name: Fist element or Begins with (A-Z), (a-z), or '_' rest others (A-Z), (a-z), or '_', (0-9) Built-in functions: len(), any(), string(), dir(),print(), range(), set(), int(),float() ###Code def int(num): return num+2 print(int(5)) def Add(num1, num2): return num1+num2 Add(4,6) Add('Hi','Hello') def is_even(num): if num% 2==0: return 1 else: return 0 is_even(8) is_even(7) User Defined Function Built-in Function Lambda Function Recurssion function ###Output _____no_output_____
examples/data-centric/mnist/.ipynb_checkpoints/01-FL-mnist-populate-a-grid-node-checkpoint.ipynb
###Markdown Federated Learning - MNIST Example Populate remote GridNodes with labeled tensorsIn this notebbok, we will show how to populate a GridNode with labeled data, so it will be used later (link to second part) by people interested in train models.In particular, we will consider that two Data Owners (Alice & Bob) want to populate their nodes with some data from the well-known MNIST dataset. 0 - Previous setupComponents: - PyGrid Network http://network:7000 - PyGrid Node Alice (http://alice:5000) - PyGrid Node Bob (http://bob:5001)This tutorial assumes that these components are running in background. See [instructions](https://github.com/OpenMined/PyGrid/tree/dev/exampleshow-to-run-this-tutorial) for more details. Import dependenciesHere we import core dependencies ###Code import syft as sy from syft.grid.clients.data_centric_fl_client import DataCentricFLClient # websocket client. It sends commands to the node servers import torch import torchvision from torchvision import datasets, transforms import requests ###Output _____no_output_____ ###Markdown Syft and client configurationNow we hook Torch and connect the clients to the servers ###Code # address alice_address = "http://alice:5000" bob_address = "http://bob:5001" hook = sy.TorchHook(torch) # Connect direcly to grid nodes compute_nodes = {} compute_nodes["Alice"] = DataCentricFLClient(hook, alice_address) compute_nodes["Bob"] = DataCentricFLClient(hook, bob_address) # Check if they are connected for key, value in compute_nodes.items(): print("Is " + key + " connected?: " + str(value.ws.connected)) ###Output _____no_output_____ ###Markdown 1 - Load datasetDownload (and load) the MNIST dataset ###Code N_SAMPLES = 10000 # Number of samples MNIST_PATH = './dataset' # Path to save MNIST dataset # Define a transformation. transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), # mean and std ]) # Download and load MNIST dataset trainset = datasets.MNIST(MNIST_PATH, download=True, train=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=N_SAMPLES, shuffle=True) dataiter = iter(trainloader) images_train_mnist, labels_train_mnist = dataiter.next() # Train images and their labels ###Output _____no_output_____ ###Markdown 2 - Split datasetWe split our dataset ... ###Code images_train_mnist = torch.split(images_train_mnist, int(len(images_train_mnist) / len(compute_nodes)), dim=0 ) #tuple of chunks (dataset / number of nodes) labels_train_mnist = torch.split(labels_train_mnist, int(len(labels_train_mnist) / len(compute_nodes)), dim=0 ) #tuple of chunks (labels / number of nodes) ###Output _____no_output_____ ###Markdown ... and we add tags to them so that we can search them later ###Code for index, _ in enumerate(compute_nodes): images_train_mnist[index]\ .tag("#X", "#mnist", "#dataset")\ .describe("The input datapoints to the MNIST dataset.") labels_train_mnist[index]\ .tag("#Y", "#mnist", "#dataset") \ .describe("The input labels to the MNIST dataset.") ###Output _____no_output_____ ###Markdown 3 - Sending our tensor to grid nodesWe can consider the previous steps as data preparation, i.e., in a more realistic scenario Alice and Bob would already have their data, so they just would need to load their tensors into their nodes. ###Code for index, key in enumerate(compute_nodes): print("Sending data to", key) images_train_mnist[index].send(compute_nodes[key], garbage_collect_data=False) labels_train_mnist[index].send(compute_nodes[key], garbage_collect_data=False) ###Output _____no_output_____ ###Markdown If everything is ok, tensors must be hosted in the nodes. GridNode have a specific endpoint to request what tensors are hosted. Let's check it! ###Code print("Alice's tags: ", requests.get(alice_address + "/data-centric/dataset-tags").json()) print("Bob's tags: ", requests.get(bob_address + "/data-centric/dataset-tags").json()) ###Output _____no_output_____
intermediate_notebooks/examples/rf_demo.ipynb
###Markdown Random Forest Classification**Authorship**Original Author: Saloni JainLast Edit: Taurean Dyer, 9/25/2019**Test System Specs**Test System Hardware: GV100Test System Software: Ubuntu 18.04RAPIDS Version: 0.10.0a - Docker InstallDriver: 410.79CUDA: 10.0**Known Working Systems**RAPIDS Versions: 0.4, 0.5, 0.5.1, 0.6, 0.6.1, 0.7, 0.8, 0.9, 0.10 IntroThe Random Forest algorithm is a classification algorithm which builds several decision trees, and aggregates each of their outputs to make a prediction. This makes it more robust to overfitting.In order to convert your dataset to cudf format please read the cudf documentation on https://rapidsai.github.io/projects/cudf/en/latest/. For additional information on the RandomForest model please refer to the documentation on https://rapidsai.github.io/projects/cuml/en/latest/index.htmlThis notebook demonstratrates fitting a RandomForestClassifier on the Higgs dataset. It is a binary classification problem to distinguish between a signal process which produces Higgs bosons and a background process which does not. The notebook also compares the performance (accuracy and speed) with sklearn's parallel RandomForestClassifier implementation. ###Code from cuml import RandomForestClassifier as cuRF from sklearn.ensemble import RandomForestClassifier as sklRF from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import cudf import numpy as np import pandas as pd import os from urllib.request import urlretrieve import gzip ###Output _____no_output_____ ###Markdown Helper function to download and extract the Higgs dataset ###Code def download_higgs(compressed_filepath, decompressed_filepath): higgs_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00280/HIGGS.csv.gz' if not os.path.isfile(compressed_filepath): urlretrieve(higgs_url, compressed_filepath) if not os.path.isfile(decompressed_filepath): cf = gzip.GzipFile(compressed_filepath) with open(decompressed_filepath, 'wb') as df: df.write(cf.read()) ###Output _____no_output_____ ###Markdown Download Higgs data and read using cudf ###Code data_dir = '../../data/rf/' if not os.path.exists(data_dir): print('creating rf data directory') os.system('mkdir ../../data/rf') compressed_filepath = data_dir+'HIGGS.csv.gz' # Set this as path for gzipped Higgs data file, if you already have decompressed_filepath = data_dir+'HIGGS.csv' # Set this as path for decompressed Higgs data file, if you already have download_higgs(compressed_filepath, decompressed_filepath) col_names = ['label'] + ["col-{}".format(i) for i in range(2, 30)] # Assign column names dtypes_ls = ['int32'] + ['float32' for _ in range(2, 30)] # Assign dtypes to each column data = cudf.read_csv(decompressed_filepath, names=col_names, dtype=dtypes_ls) data.head().to_pandas() ###Output _____no_output_____ ###Markdown Make train test splits ###Code X, y = data[data.columns.difference(['label'])].as_matrix(), data['label'].to_array() # Separate data into X and y del data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=500_000) print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) ###Output _____no_output_____ ###Markdown You can consult RandomForestClassifier docstring to check all the parameters, but here are some of the more important ones: 1. n_estimators: (default = 10) number of trees in the forest.2. max_depth: (default = -1) Maximum tree depth. Unlimited (i.e, until leaves are pure), if -1.3. n_bins: (default = 8) Number of bins used by the split algorithm.Note on `nbins`: Reducing `n_bins` shrinks the histograms used to compute which tree nodes to split. This reduction improves training time, but if you reduce it too low, you may harm model accuracy. ###Code # cuml Random Forest params cu_rf_params = { 'n_estimators': 25, 'max_depth': 13, 'n_bins': 15, } ###Output _____no_output_____ ###Markdown The methods that can be used with the RandomForestClassifier are:1. fit: Fit the model with X and y.2. get_params: Sklearn style return parameter state3. predict: Predicts the y for X.4. set_params: Sklearn style set parameter state to dictionary of params.5. cross_validate: Predicts the accuracy of the model for X. Note on input to `fit` method: Since `fit` is processed on the GPU, it can accept `cudf` dataframes or `numpy` arrays ###Code %%time # Train cuml RF cu_rf = cuRF(**cu_rf_params) cu_rf.fit(X_train, y_train) ###Output _____no_output_____ ###Markdown Set Sklearn params and fit RandomForestClassifier ###Code # sklearn Random Forest params skl_rf_params = { 'n_estimators': 25, 'max_depth': 13, } %%time # Train sklearn RF parallely skl_rf = sklRF(**skl_rf_params, n_jobs=20) skl_rf.fit(X_train, y_train) ###Output _____no_output_____ ###Markdown Predict and compare cuml and sklearn RandomForestClassifier Note on input to cuml `predict` method: Since `predict` is processed on the CPU, it can only accept `numpy` arrays ###Code # Predict print("cuml RF Accuracy Score: ", accuracy_score(cu_rf.predict(X_test), y_test)) print("sklearn RF Accuracy Score: ", accuracy_score(skl_rf.predict(X_test), y_test)) ###Output _____no_output_____ ###Markdown Random Forest ClassificationThe Random Forest algorithm is a classification algorithm which builds several decision trees, and aggregates each of their outputs to make a prediction. This makes it more robust to overfitting.In order to convert your dataset to cudf format please read the cudf documentation on https://rapidsai.github.io/projects/cudf/en/latest/. For additional information on the RandomForest model please refer to the documentation on https://rapidsai.github.io/projects/cuml/en/latest/index.htmlThis notebook demonstratrates fitting a RandomForestClassifier on the Higgs dataset. It is a binary classification problem to distinguish between a signal process which produces Higgs bosons and a background process which does not. The notebook also compares the performance (accuracy and speed) with sklearn's parallel RandomForestClassifier implementation. ###Code from cuml import RandomForestClassifier as cuRF from sklearn.ensemble import RandomForestClassifier as sklRF from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split import cudf import numpy as np import pandas as pd import os from urllib.request import urlretrieve import gzip ###Output _____no_output_____ ###Markdown Helper function to download and extract the Higgs dataset ###Code def download_higgs(compressed_filepath, decompressed_filepath): higgs_url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/00280/HIGGS.csv.gz' if not os.path.isfile(compressed_filepath): urlretrieve(higgs_url, compressed_filepath) if not os.path.isfile(decompressed_filepath): cf = gzip.GzipFile(compressed_filepath) with open(decompressed_filepath, 'wb') as df: df.write(cf.read()) ###Output _____no_output_____ ###Markdown Download Higgs data and read using cudf ###Code compressed_filepath = 'HIGGS.csv.gz' # Set this as path for gzipped Higgs data file, if you already have decompressed_filepath = 'HIGGS.csv' # Set this as path for decompressed Higgs data file, if you already have download_higgs(compressed_filepath, decompressed_filepath) col_names = ['label'] + ["col-{}".format(i) for i in range(2, 30)] # Assign column names dtypes_ls = ['int32'] + ['float32' for _ in range(2, 30)] # Assign dtypes to each column data = cudf.read_csv(decompressed_filepath, names=col_names, dtype=dtypes_ls) data.head().to_pandas() ###Output _____no_output_____ ###Markdown Make train test splits ###Code X, y = data[data.columns.difference(['label'])].as_matrix(), data['label'].to_array() # Separate data into X and y del data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=500_000) print(X_train.shape, y_train.shape, X_test.shape, y_test.shape) ###Output (10500000, 28) (10500000,) (500000, 28) (500000,) ###Markdown You can consult RandomForestClassifier docstring to check all the parameters, but here are some of the more important ones: 1. n_estimators: (default = 10) number of trees in the forest.2. max_depth: (default = -1) Maximum tree depth. Unlimited (i.e, until leaves are pure), if -1.3. n_bins: (default = 8) Number of bins used by the split algorithm.Note on `nbins`: Reducing `n_bins` shrinks the histograms used to compute which tree nodes to split. This reduction improves training time, but if you reduce it too low, you may harm model accuracy. ###Code # cuml Random Forest params cu_rf_params = { 'n_estimators': 25, 'max_depth': 13, 'n_bins': 15, } ###Output _____no_output_____ ###Markdown The methods that can be used with the RandomForestClassifier are:1. fit: Fit the model with X and y.2. get_params: Sklearn style return parameter state3. predict: Predicts the y for X.4. set_params: Sklearn style set parameter state to dictionary of params.5. cross_validate: Predicts the accuracy of the model for X. Note on input to `fit` method: Since `fit` is processed on the GPU, it can accept `cudf` dataframes or `numpy` arrays ###Code %%time # Train cuml RF cu_rf = cuRF(**cu_rf_params) cu_rf.fit(X_train, y_train) ###Output CPU times: user 40.4 s, sys: 13.1 s, total: 53.5 s Wall time: 53.6 s ###Markdown Set Sklearn params and fit RandomForestClassifier ###Code # sklearn Random Forest params skl_rf_params = { 'n_estimators': 25, 'max_depth': 13, } %%time # Train sklearn RF parallely skl_rf = sklRF(**skl_rf_params, n_jobs=20) skl_rf.fit(X_train, y_train) ###Output CPU times: user 56min 27s, sys: 1min, total: 57min 27s Wall time: 4min 30s ###Markdown Predict and compare cuml and sklearn RandomForestClassifier Note on input to cuml `predict` method: Since `predict` is processed on the CPU, it can only accept `numpy` arrays ###Code # Predict print("cuml RF Accuracy Score: ", accuracy_score(cu_rf.predict(X_test), y_test)) print("sklearn RF Accuracy Score: ", accuracy_score(skl_rf.predict(X_test), y_test)) ###Output cuml RF Accuracy Score: 0.72466 sklearn RF Accuracy Score: 0.72177
content/labs/lab3/.ipynb_checkpoints/cs109b_lect10_bayes_1_2021_students-checkpoint.ipynb
###Markdown CS109B Data Science 2: Advanced Topics in Data Science Lecture 10 - Bayesian Analysis and Introduction to pyMC3**Harvard University****Spring 2021****Instructors:** Pavlos Protopapas, Mark Glickman, and Chris Tanner**Additional Instructor and content:** Eleni Angelaki Kaxiras--- ###Code ## RUN THIS CELL TO PROPERLY HIGHLIGHT THE EXERCISES import requests from IPython.core.display import HTML styles = requests.get("https://raw.githubusercontent.com/Harvard-IACS/2019-CS109B/master/content/styles/cs109.css").text HTML(styles) import pymc3 as pm # from pymc3 import summary import arviz as az from matplotlib import gridspec # Ignore a common pymc3 warning that comes from library functions, not our code. # Pymc3 may throw additional warnings, but other warnings should be manageable # by following the instructions included within the warning messages. import warnings messages=[ "Using `from_pymc3` without the model will be deprecated in a future release", ] # or silence all warnings (not recommended) # warnings.filterwarnings('ignore') for m in messages: warnings.filterwarnings("ignore", message=m) print(f"Using PyMC3 version: {pm.__version__}") print(f"Using ArviZ version: {az.__version__}") import pymc3 as pm from scipy import optimize import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats import pandas as pd import seaborn as sns %matplotlib inline %%javascript IPython.OutputArea.auto_scroll_threshold = 20000; # pandas trick pd.options.display.max_columns = 50 # or =None -> No Restrictions pd.options.display.max_rows = 200 # or =None -> *Be careful with this* pd.options.display.max_colwidth = 100 pd.options.display.precision = 3 ###Output _____no_output_____ ###Markdown Learning ObjectivesBy the end of this lab, you should be able to:* identify and describe some of the most important probability distributions.* apply Bayes Rule in calculating probabilities (and would have had fun in the process).* create probabilistic models in the PyMC3 library. Table of Contents1. [Some common families of distributions (review)](1)2. [The Bayesian Way of Thinking](2) 3. [Bayesian Regression with pyMC3](3) and [Defining a model in pyMC3](model) 4. [Bayesian Logistic Regression with pyMC3](4)[Appendix](appe) 1. Some common families of distributionsStatistical distributions are characterized by one of more parameters, such as $\mu$ and $\sigma^2$ for a Gaussian distribution. \begin{equation}Y \sim \mathcal{N}(\mu,\,\sigma^{2})\end{equation} Discrete DistributionsThe **probability mass function (pmf)** of a discrete random variable $Y$ is equal to the probability that our random variable will take a specific value $y$: $f_y=P(Y=y)$ for all $y$. The variable, most of the times, assumes integer values. Plots for **pmf**s are better understood as stem plots since we have discrete values for the probabilities and not a curve. Probabilities should add up to 1 for proper distributions. - **Bernoulli** for a binary outcome, success has probability $\theta$, and we only have $one$ trial: \begin{equation}P(Y=k) = \theta^k(1-\theta)^{1-k}\end{equation} - **Binomial** for a binary outcome, success has probability $\theta$, $k$ successes in $n$ trials:Our random variable is $Y$= number of successes in $n$ trials.\begin{equation}P(Y=k|n,\theta) = {{n}\choose{k}} \cdot \theta^k(1-\theta)^{n-k} \quad k=0,1,2,...,n\end{equation}As a reminder ${{n}\choose{k}}$ is "from $n$ choose $k$":\begin{equation}{{n}\choose{k}} = \frac{n!}{k!(n-k)!} \end{equation}$EY=n\theta$, $VarY = np(1-p)$ **Note** : Binomial (1,$p$) = Bernouli ($p$) Exercise: Run the code below (that plots the Binomial distribution using stats.binom.pmf) for various values of the probability for a success $\theta\in [0,1]$. Look at the ordinate values to verify that they add up to 1. ###Code # probabity of success theta = 0.5 n = 5 k = np.arange(0, n+1) print(k) pmf = stats.binom.pmf(k, n, theta) plt.style.use('seaborn-darkgrid') plt.stem(k, pmf, label=r'n = {}, $\theta$ = {}'.format(n, theta)) plt.xlabel('Y', fontsize=14) plt.ylabel('P(Y)', fontsize=14) plt.legend() plt.show() ###Output [0 1 2 3 4 5] ###Markdown - **Negative Binomial** for a binary outcome, success has probability $\theta$, we have $r$ successes in $x$ trials:Our random variable is $X$= number of trials to get to $r$ successes.\begin{equation}P(X=x|r,\theta) = {{x-1}\choose{r-1}} \cdot \theta^r(1-\theta)^{x-r} \quad x=r,r+1,...\end{equation} - **Poisson** (counts independent events and has a single parameter $\lambda$) \begin{equation}P\left( Y=y|\lambda \right) = \frac{{e^{ - \lambda } \lambda ^y }}{{y!}} \quad y = 0,1,2,...\end{equation} Exercise: Change the value of $\lambda$ in the Poisson pmf plot below and see how the plot changes. Remember that the y-axis in a discrete probability distribution shows the probability of the random variable having a specific value in the x-axis. We use stats.poisson.pmf(x, $\lambda$), where $\lambda$ is the parameter. ###Code plt.style.use('seaborn-darkgrid') x = np.arange(0, 10) lam = 4 pmf = stats.poisson.pmf(x, lam) plt.stem(x, pmf, label='$\lambda$ = {}'.format(lam)) plt.xlabel('Y', fontsize=12) plt.ylabel('P(Y)', fontsize=12) plt.legend(loc=1) plt.ylim=(-0.1) plt.show() ###Output _____no_output_____ ###Markdown - **Discrete Uniform** for a random variable $X\in(1,N)$: \begin{equation}P(X=x|N) = \frac{1}{N}, \quad x=1,2,...,N\end{equation} ###Code # boring but useful as a prior plt.style.use('seaborn-darkgrid') N = 40 x = np.arange(0, N) pmf = stats.randint.pmf(x, 0, N) plt.plot(x, pmf, label='$N$ = {}'.format(N)) fontsize=14 plt.xlabel('X', fontsize=fontsize) plt.ylabel(f'P(X|{N})', fontsize=fontsize) plt.legend() plt.show() ###Output _____no_output_____ ###Markdown - **Categorical, or Multinulli** (random variables can take any of K possible categories, each having its own probability; this is a generalization of the Bernoulli distribution for a discrete variable with more than two possible outcomes, such as the roll of a die)\begin{equation}f(x_1,x_2,...,x_n) = \frac{m}{x_1!\cdot x_2!\dotsb x_n!} \cdot p_1^{x_1}\cdot p_2^{x_2}\dotsb p_n^{x_n}\end{equation} Continuous DistributionsThe random variable has a **probability density function (pdf)** whose area under the curve equals to 1.- **Uniform** (variable equally likely to be near each value in interval $(a,b)$)\begin{equation}f(x|a,b) = \frac{1}{b - a} \quad x\in [a,b] \quad \text{and 0 elsewhere}.\end{equation} Exercise: Change the value of $\mu$ in the Uniform PDF and see how the plot changes. Remember that the y-axis in a continuous probability distribution does not shows the actual probability of the random variable having a specific value in the x-axis because that probability is zero!. Instead, to see the probability that the variable is within a small margin we look at the integral below the curve of the PDF.The uniform is often used as a noninformative prior.```Uniform - numpy.random.uniform(a=0.0, b=1.0, size)```$\alpha$ and $\beta$ are our parameters. `size` is how many tries to perform.The mean is $\mu = \frac{(a+b)}{2}$ ###Code from scipy.stats import uniform a = 0 b = 1 r = uniform.rvs(loc=a, scale=b-a, size=1000) pdf = uniform.pdf(r,loc=a, scale=b-a) plt.plot(r, pdf,'b-', lw=3, alpha=0.6, label='uniform pdf') plt.hist(r, density=True, histtype='stepfilled', alpha=0.2) plt.ylabel(r'pdf') plt.xlabel(f'x') plt.legend(loc='best', frameon=False) plt.show() ###Output _____no_output_____ ###Markdown - **Normal** (a.k.a. Gaussian)\begin{equation}X \sim \mathcal{N}(\mu,\,\sigma^{2})\end{equation} A Normal distribution can be parameterized either in terms of precision $\tau$ or variance $\sigma^{2}$. The link between the two is given by\begin{equation}\tau = \frac{1}{\sigma^{2}}\end{equation} - Expected value (mean) $\mu$ - Variance $\frac{1}{\tau}$ or $\sigma^{2}$ - Parameters: `mu: float`, `sigma: float` or `tau: float` - Range of values (-$\infty$, $\infty$) ###Code plt.style.use('seaborn-darkgrid') x = np.linspace(-5, 5, 1000) mus = [0., 0., 0., -2.] sigmas = [0.4, 1., 2., 0.4] for mu, sigma in zip(mus, sigmas): pdf = stats.norm.pdf(x, mu, sigma) plt.plot(x, pdf, label=r'$\mu$ = '+ f'{mu},' + r'$\sigma$ = ' + f'{sigma}') plt.xlabel('random variable', fontsize=12) plt.ylabel('probability density', fontsize=12) plt.legend(loc=1) plt.show() ###Output _____no_output_____ ###Markdown - **Beta** (where the variable ($\theta$) takes on values in the interval $(0,1)$, and is parametrized by two positive parameters, $\alpha$ and $\beta$ that control the shape of the distribution. Note that Beta is a good distribution to use for priors (beliefs) because its range is $[0,1]$ which is the natural range for a probability and because we can model a wide range of functions by changing the $\alpha$ and $\beta$ parameters. Its density (pdf) is:\begin{equation}\label{eq:beta} P(\theta|a,b) = \frac{1}{B(\alpha, \beta)} {\theta}^{\alpha - 1} (1 - \theta)^{\beta - 1} \propto {\theta}^{\alpha - 1} (1 - \theta)^{\beta - 1}\end{equation}where the normalisation constant, $B$, is a beta function of $\alpha$ and $\beta$,\begin{equation}B(\alpha, \beta) = \int_{x=0}^1 x^{\alpha - 1} (1 - x)^{\beta - 1} dx.\end{equation} - 'Nice', unimodal distribution - Range of values $[0, 1]$$EX = \frac{a}{a+b}$, $VarX = \frac{ab}{(a+b)^2(a+b+1)}$Exercise: Try out various combinations of $a$ and $b$. We get an amazing set of shapes by tweaking the two parameters $a$ and $b$. Notice that for $a=b=1.$ we get the uniform distribution. As the values increase, we get a curve that looks more and more Gaussian. ###Code from scipy.stats import beta fontsize = 15 alphas = [0.5] #, 0.5, 1., 3., 6.] betas = [0.5] #, 1., 1., 3., 6.] x = np.linspace(0, 1, 1000) colors = ['red', 'green', 'blue', 'black', 'pink'] fig, ax = plt.subplots(figsize=(8, 5)) for a, b, colors in zip(alphas, betas, colors): plt.plot(x, beta.pdf(x,a,b), c=colors, label=f'a={a}, b={b}') ax.set_ylim(0, 3) ax.set_xlabel(r'$\theta$', fontsize=fontsize) ax.set_ylabel(r'P ($\theta|\alpha,\beta)$', fontsize=fontsize) ax.set_title('Beta Distribution', fontsize=fontsize*1.2) ax.legend(loc='best') fig.show(); ###Output _____no_output_____ ###Markdown At home: Prove the formula mentioned in class which gives the probability density for a Beta distribution with parameters $2$ and $5$:$p(\theta|2,5) = 30 \cdot \theta(1 - \theta)^4$ Code Resources: - Statistical Distributions in numpy/scipy: [scipy.stats](https://docs.scipy.org/doc/scipy/reference/stats.html) [Top](top) 2. The Bayesian way of Thinking```Here is my state of knowledge about the situation. Here is some data, I am now going to revise my state of knowledge.``` Bayes Rule\begin{equation}\label{eq:bayes} P(A|\textbf{B}) = \frac{P(\textbf{B} |A) P(A) }{P(\textbf{B})} \end{equation}$P(A|\textbf{B})$ is the **posterior** distribution, probability(parameters| data). $P(\textbf{B} |A)$ is the **likelihood** function, how probable is my data for different values of the parameters.$P(A)$ is the marginal probability to observe the data, called the **prior**, this captures our belief about the data before observing it.$P(\textbf{B})$ is the marginal distribution (sometimes called marginal likelihood). This serves a normalization purpose. Let's Make a Deal The problem we are about to solve gained fame as part of a game show "Let's Make A Deal" hosted by Monty Hall, hence its name. It was first raised by Steve Selvin in American Statistician in 1975. The game is as follows: there are 3 doors behind **one** of which are the keys to a new car. There is a goat behind each of the other two doors. Let's assume your goal is to get the car and not a goat.You are asked to pick one door, and let's say you pick **Door1**. The host knows where the keys are. Of the two remaining closed doors, he will always open the door that has a goat behind it. He'll say "I will do you a favor and open **Door2**". So he opens Door2 inside which there is, of course, a goat. He now asks you, do you want to open the initial Door1 you chose or change to **Door3**? Generally, in this game, when you are presented with this choice should you swap the doors?**Hint:**- Start by defining the `events` of this probabilities game. One definition is: - $A_i$: car is behind door $i$ - $B_i$ host opens door $i$ $i\in[1,2,3]$ - In more math terms, the question is: is the probability of **the price is behind Door 1** higher than the probability of **the price is behind Door2**, given that an event **has occured**? Breakout Game: Solve the Monty Hall Paradox using Bayes Rule. Bayes rule revisited We have data that we believe come from an underlying distribution of unknown parameters. If we find those parameters, we know everything about the process that generated this data and we can make inferences (create new data).\begin{equation}P(\theta|\textbf{D}) = \frac{P(\textbf{D} |\theta) P(\theta) }{P(\textbf{D})} \end{equation} But what is $\theta \;$?$\theta$ is an unknown yet fixed set of parameters. In Bayesian inference we express our belief about what $\theta$ might be and instead of trying to guess $\theta$ exactly, we look for its **probability distribution**. What that means is that we are looking for the **parameters** of that distribution. For example, for a Poisson distribution our $\theta$ is only $\lambda$. In a normal distribution, our $\theta$ is often just $\mu$ and $\sigma$. [Top](top) 3. Bayesian Regression with `pyMC3` PyMC3 is a Python library for programming Bayesian analysis, and more specifically, data creation, model definition, model fitting, and posterior analysis. It uses the concept of a `model` which contains assigned parametric statistical distributions to unknown quantities in the model. Within models we define random variables and their distributions. A distribution requires at least a `name` argument, and other `parameters` that define it. You may also use the `logp()` method in the model to build the model log-likelihood function. We define and fit the model.PyMC3 includes a comprehensive set of pre-defined statistical distributions that can be used as model building blocks. They are not meant to be used outside of a `model`, and you can invoke them by using the prefix `pm`, as in `pm.Normal`. For more see: [PyMC3 Quickstart](https://docs.pymc.io/notebooks/api_quickstart.html) Distributions in `PyMC3`: - Statistical [Distributions in pyMC3](https://docs.pymc.io/api/distributions.html). Information about PyMC3 functions including descriptions of distributions, sampling methods, and other functions, is available via the `help` command. ###Code #help(pm.Beta) ###Output _____no_output_____ ###Markdown Defining a Model in PyMC3 Our problem is the following: we want to perform multiple linear regression to predict an outcome variable $Y$ which depends on variables $\bf{x}_1$ and $\bf{x}_2$.We will model $Y$ as normally distributed observations with an expected value $mu$ that is a linear function of the two predictor variables, $\bf{x}_1$ and $\bf{x}_2$.\begin{equation}Y \sim \mathcal{N}(\mu,\,\sigma^{2})\end{equation} \begin{equation}\mu = \beta_0 + \beta_1 \bf{x}_1 + \beta_2 x_2 \end{equation}where $\sigma^2$ represents the measurement error (in this example, we will use $\sigma^2 = 10$)We also choose the parameters to have normal distributions with those parameters set by us.\begin{eqnarray}\beta_i \sim \mathcal{N}(0,\,10) \\\sigma^2 \sim |\mathcal{N}(0,\,10)|\end{eqnarray} We will artificially create the data to predict on. We will then see if our model predicts them correctly. Let's create some synthetic data ###Code np.random.seed(123) ################################### ## Hidden true parameter values sigma = 1 beta0 = 1 beta = [1, 2.5] #################################### # Size of dataset size = 100 # Predictor variable x1 = np.linspace(0, 1., size) x2 = np.linspace(0,2., size) # Simulate outcome variable Y = beta0 + beta[0]*x1 + beta[1]*x2 + np.random.randn(size)*sigma Y.shape, x1.shape, x2.shape from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() fontsize=14 labelsize=8 title='Observed Data (created artificially by ' + r'$Y(x_1,x_2)$)' ax = fig.add_subplot(111, projection='3d') ax.scatter(x1, x2, Y) ax.set_xlabel(r'$x_1$', fontsize=fontsize) ax.set_ylabel(r'$x_2$', fontsize=fontsize) ax.set_zlabel(r'$Y$', fontsize=fontsize) ax.tick_params(labelsize=labelsize) fig.suptitle(title, fontsize=fontsize) fig.tight_layout(pad=.1, w_pad=10.1, h_pad=2.) fig.subplots_adjust(); #top=0.5 plt.tight_layout plt.show() ###Output _____no_output_____ ###Markdown Building the model**Step1:** Formulate the probability model for our data: $Y \sim \mathcal{N}(\mu,\,\sigma^{2})$```Y_obs = pm.Normal('Y_obs', mu=mu, sd=sigma, observed=Y)```**Step2:** Choose a prior distribution for our unknown parameters. ``` beta0 = Normal('beta0', mu=0, sd=10) Note: betas is a vector of two variables, b1 and b2, (denoted by shape=2) so, in array notation, our beta1 = betas[0], and beta2=betas[1] betas = Normal('betas', mu=0, sd=10, shape=2) sigma = HalfNormal('sigma', sd=1)```**Step3:** Construct the likelihood function.**Step4:** Determine the posterior distribution, **this is our main goal**.**Step5:** Summarize important features of the posterior and/or plot the parameters. ###Code with pm.Model() as my_linear_model: # Priors for unknown model parameters, specifically created stochastic random variables # with Normal prior distributions for the regression coefficients, # and a half-normal distribution for the standard deviation of the observations. # These are our parameters. # I need to give the prior some initial values for the parameters mu0 = 0 sd0 = 10 beta0 = pm.Normal('beta0', mu=mu0, sd=sd0) # Note: betas is a vector of two variables, b1 and b2, (denoted by shape=2) # so, in array notation, our beta1 = betas[0], and beta2=betas[1] mub = 0 sdb = 10 betas = pm.Normal('betas', mu=mub, sd=sdb, shape=2) sds = 1 sigma = pm.HalfNormal('sigma', sd=sds) # mu is what is called a deterministic random variable, which implies that # its value is completely determined by its parents’ values # (betas and sigma in our case). There is no uncertainty in the # variable beyond that which is inherent in the parents’ values mu = beta0 + betas[0]*x1 + betas[1]*x2 # Likelihood function = how probable is my observed data? # This is an observed variable; it is identical to a standard # stochastic variable, except that its observed argument, # which passes the data to the variable, indicates that the values for this # variable were observed, and should not be changed by any # fitting algorithm applied to the model. # The data can be passed in the form of a numpy.ndarray or pandas.DataFrame object. Y_obs = pm.Normal('Y_obs', mu=mu, sd=sigma, observed=Y) my_linear_model.basic_RVs my_linear_model.free_RVs ###Output _____no_output_____ ###Markdown **Note**: If our problem was a classification for which we would use Logistic regression. ###Code ## do not worry if this does not work, it's just a nice graph to have ## you need to install python-graphviz first # conda install -c conda-forge python-graphviz pm.model_to_graphviz(my_linear_model) ###Output _____no_output_____ ###Markdown Now all we need to do is sample our model. ... to be continued Appendix A: Bayesian Logistic Regression with `pyMC3` If the problem above was a classification that required a Logistic Regression, we would use the logistic function ( where $\beta_0$ is the intercept, and $\beta_i$ (i=1, 2, 3) determines the shape of the logistic function).\begin{equation}Pr(Y=1|X_1,X_2,X3) = {\frac{1}{1 + exp^{-(\beta_0 + \beta_1X_1 + \beta_2X_2 + \beta_3X_3)}}}\end{equation}Since both $\beta_0$ and the $\beta_i$s can be any possitive or negative number, we can model them as gaussian random variables.\begin{eqnarray}\beta_0 \sim \mathcal{N}(\mu,\,\sigma^2) \\\beta_i \sim \mathcal{N}(\mu_i,\,\sigma_i^2)\end{eqnarray} In PyMC3 we can model those as:```pm.Normal('beta_0', mu=0, sigma=100)```(where $\mu$ and $\sigma^2$ can have some initial values that we assign them, e.g. 0 and 100)The dererministic variable would be:```logitp = beta0 + beta_1 * X_1 + beta_2 * X_2 + beta_3 * X_3```To connect this variable (logit-p) with our observed data, we would use a Bernoulli as our likelihood.```our_likelihood = pm.Bernoulli('our_likelihood', logit_p=logitp, observed=our_data)``` Notice that the main difference with Linear Regression is the use of a Bernoulli distribution instead of a Gaussian distribution, and the use of the logistic function instead of the identity function. Breakout Room Exercise: Write the model above in code. Suppose that your training dataframe (df_train) has the following features:**numerical**- df_train['age']- df_train['weight'] **categorical**- df_train['hypertension'] ###Code # A reminder of what the logistic function looks like. # Change parameters a and b to see the shape of the curve change b = 5. x = np.linspace(-8, 8, 100) plt.plot(x, 1 / (1 + np.exp(-b*x))) plt.xlabel('y') plt.ylabel('y=logistic(x)') ###Output _____no_output_____ ###Markdown Appendix B: Is this a fair coin? Is this a fair coin?Let's say you visit the casino in **Monte Carlo**. You want to test your theory that casinos are dubious places where coins have been manipulated to have a larger probability for tails. So you will try to estimate how fair a coin is based on a certain amount of flips. You have no prior opinion on the coin's fairness (i.e. what $p$ might be), and begin flipping the coin. You get either Heads ($H$) or Tails ($T$) as our observed data and want to see if your posterior probabilities change as you obtain more data, that is, more coin flips. A nice way to visualize this is to plot the posterior probabilities as we observe more flips (data). We will be using Bayes rule. $\textbf{D}$ is our data.\begin{equation}P(\theta|\textbf{D}) = \frac{P(\textbf{D} |\theta) P(\theta) }{P(\textbf{D})} \end{equation}We start with a non-informative prior, a Beta distribution with (a=b=1.) \begin{equation}P(\theta|\textbf{k=0}) = Beta(1., 1.) \end{equation} Then, as we get new data (say, we observe $k$ heads in $n$ tosses), we update our Beta with new a,b as follows: \begin{equation}P(\theta|\textbf{k}) = Beta(\alpha + \textbf{k}, \beta + (n - \textbf{k})) \end{equation}*(the proof is beyond our scope, if interested, see this [Wikipedia article](https://en.wikipedia.org/wiki/Conjugate_priorExample))* we can say that $\alpha$ and $\beta$ play the roles of a "prior number of heads" and "prior number of tails". ###Code # play with the priors - here we manually set them but we could be sampling from a separate Beta trials = np.array([0, 1, 3, 5, 10, 15, 20, 100, 200, 300]) heads = np.array([0, 1, 2, 4, 8, 10, 10, 50, 180, 150]) x = np.linspace(0, 1, 100) # for simplicity we set a,b=1 plt.figure(figsize=(10,8)) for k, N in enumerate(trials): sx = plt.subplot(len(trials)/2, 2, k+1) posterior = stats.beta.pdf(x, 1 + heads[k], 1 + trials[k] - heads[k]) plt.plot(x, posterior, alpha = 0.5, label=f'{trials[k]} tosses\n {heads[k]} heads'); plt.fill_between(x, 0, posterior, color="#348ABD", alpha=0.4) plt.legend(loc='upper left', fontsize=10) plt.legend() plt.autoscale(tight=True) plt.suptitle("Posterior probabilities for coin flips", fontsize=15); plt.tight_layout() plt.subplots_adjust(top=0.88) ###Output _____no_output_____
src/documentation/SoS_Magics.ipynb
###Markdown SoS Magics ###Code %revisions --source ###Output _____no_output_____ ###Markdown In addition to SoS statements, you can use a few SoS magics in Jupyter notebook. 1. SoS magics have to be specified at the beginning of a cell, although they can be specified after empty lines and comments.2. Lines ending with `"\"` will be joined so you can break long magics into multiple lines3. Multiple magics can be used in a single cell. This section lists all magics that SoS supports. To get a list of magics, you can enter `%` at the beginning of a line and press tab. You can also get the detailed usage of a magic by executing a magic with `-h` option, for example: ###Code %use -h ###Output usage: %use [-h] [-k KERNEL] [-l LANGUAGE] [-c COLOR] [-r] [-i [IN_VARS [IN_VARS ...]]] [-o [OUT_VARS [OUT_VARS ...]]] [name] Switch to a specified subkernel. positional arguments: name Displayed name of kernel to start (if no kernel with name is specified) or switch to (if a kernel with this name is already started). The name is usually a kernel name (e.g. %use ir) or a language name (e.g. %use R) in which case the language name will be used. One or more parameters --language or --kernel will need to be specified if a new name is used to start a separate instance of a kernel. optional arguments: -h, --help show this help message and exit -k KERNEL, --kernel KERNEL kernel name as displayed in the output of jupyter kernelspec list. Default to the default kernel of selected language (e.g. ir for language R. -l LANGUAGE, --language LANGUAGE Language extension that enables magics such as %get and %put for the kernel, which should be in the name of a registered language (e.g. R), or a specific language module in the format of package.module:class. SoS maitains a list of languages and kernels so this option is only needed for starting a new instance of a kernel. -c COLOR, --color COLOR Background color of new or existing kernel, which overrides the default color of the language. A special value "default" can be used to reset color to default. -r, --restart Restart the kernel if it is running. -i [IN_VARS [IN_VARS ...]], --in [IN_VARS [IN_VARS ...]] Input variables (variables to get from SoS kernel) -o [OUT_VARS [OUT_VARS ...]], --out [OUT_VARS [OUT_VARS ...]] Output variables (variables to put back to SoS kernel before switching back to the SoS kernel ###Markdown Note that subkernels can have their own magics, and SoS basically processes all blank lines and known magics and send rest of the cell content to the subkernel. That is to say, because SoS does not define a `pwd` magic, the following magic would be process by the Python 3 subkernel. ###Code %pwd ###Output _____no_output_____ ###Markdown `%capture` The `capture` magic is executed after the evaluation of the current cell (in SoS or any subkernel), capture the output of the cell (either `stdout` (`stdout` of `stream` message type, the default), `stdout` (`stderr` of `stream` messages), `text` (`text/html` of `display_data` messages), `html` (`text/html` of `display_data` messages), or `raw` (all messages as a list, mostly for debugging purposes). The results are saved to a variable specified by options `--to` or `--append`.When the capture type is plain text (from `stdout`, `stderr`, or `text`), the return result can be parse it as `text`, `json`, `csv`, or `tsv`, and save (`--to`) or append (`--append`) the result to specified variable as text, Python dictionary, or `Pandas` `DataFrame`. ###Code %capture -h ###Output usage: %capture [-h] [--as [{text,json,csv,tsv}]] [-t VAR | -a VAR] [{stdout,stderr,text,markdown,html,raw}] Capture output (stdout) or output file from a subkernel as variable in SoS positional arguments: {stdout,stderr,text,markdown,html,raw} Message type to capture, default to standard output. In terms of Jupyter message types, "stdout" refers to "stream" message with "stdout" type, "stderr" refers to "stream" message with "stderr" type, "text", "markdown" and "html" refers to "display_data" message with "text/plain", "text/markdown" and "text/html" type respectively. If "raw" is specified, all returned messages will be returned in a list format. optional arguments: -h, --help show this help message and exit --as [{text,json,csv,tsv}] How to interpret the captured text. This only applicable to stdout, stderr and text message type where the text from cell output will be collected. If this option is given, SoS will try to parse the text as json, csv (comma separated text), tsv (tab separated text), and store text (from text), Pandas DataFrame (from csv or tsv), dict or other types (from json) to the variable. -t VAR, --to VAR Name of variable to which the captured content will be saved. If no varialbe is specified, the return value will be saved to variable "__captured" and be displayed at the side panel. -a VAR, --append VAR Name of variable to which the captured content will be appended. This option is equivalent to --to if VAR does not exist. If VAR exists and is of the same type of new content (str or dict or DataFrame), the new content will be appended to VAR if VAR is of str (str concatenation), dict (dict update), or DataFrame (DataFrame.append) types. If VAR is of list type, the new content will be appended to the end of the list. ###Markdown The magic can be applied to any kernel (including SoS) but it only captures output as standard output. For example, in the following R code, although both statements print something, only the `cat` function writes to standard output. The result of function `paste` is returned as the result of the cell and is displayed. ###Code %capture --to R_out cat("this is to stdout") paste("this is the return value") R_out ###Output _____no_output_____ ###Markdown Now, if you would like to capture the output of `paste`, you will have to specify `text` to capture text output of the cell: ###Code %capture text --to R_out paste("this is the return value") R_out ###Output _____no_output_____ ###Markdown If you do not know what the cell outputs, you can use option `raw` to display every output messages and decide how to capture it. When no `--to` option is specified, the output will be written to `__captured` and be displayed in the side panel. ###Code %capture raw paste("this is the return value") ###Output _____no_output_____ ###Markdown Option `--as` tries to convert the captured data in a more useful format. For example, if we are doing a sparql search, which outputs result in JSON format: The ability to parse tables as `Pandas` `DataFrame` is convenient but magic parse tables with `pandas.read_csv(sep)` with any additional parameter. If you need more flexibility in parsing the table (e.g. table without header), you will have to capture the output as text and parse it by yourself. `%cd` Change the current working directory of the SoS kernel and all subkernels to `dir`. `%clear` Magic `clear` clears task lists or the output of cells in the following ways:1. If `%clear` is used in a regular cell, the output of the cell will be cleared after the cell is executed, effectively suppress any output of the cell. This is useful in suppressing long output of sos workflows or shell commands.2. If `%clear` is executed in the side panel, the output of currently selected cells in the main notebook will be cleared. This magic can then be used as a way to selectively clean up the main notebook without leaving the magic itself in the notebook.3. If `%clear -a` or `%clear --all` is executed, it would remove the output of all cells in the notebook, leaving a clean notebook without any output. This is usually used in removing all tests results and leaving only defined workflow steps in the notebook.4. If option `-s` (`--status`) is specified with a status (most frequently `completed`), all tasks with matching status will be removed. The aforementioned rules apply to the cells that will be affected. For example, the output of the following cell is suppressed with the `%clear` magic: ###Code %clear python: print('hello') ###Output _____no_output_____ ###Markdown `%dict` The `%dict` magic lists or rests the content of SoS dict, using syntax```%dict [-a|-all] [-k|--keys] [-r|--reset] [var1] [var2] ...```where* `var1`, `var2` etc are name of variables. All variables will be displayed if no variable is specified.* `-a|-all`: list all dictionary keys, including SoS functions and variables.* `-k|--keys`: list only keys, not their values* `-r|--reset`: reset the dictionary to its original content (with only SoS internal values) ###Code %dict --reset %dict --keys ###Output _____no_output_____ ###Markdown and reset the dictionary with the `--reset` option ###Code %dict --keys ###Output _____no_output_____ ###Markdown For example, you can see all keys in the SoS dictionary using ###Code %dict --reset %dict --keys ###Output _____no_output_____ ###Markdown and reset the dictionary with the `--reset` option ###Code %dict --keys ###Output _____no_output_____ ###Markdown `%expand` Script in SoS cells are by default sent to SoS or the subkernels in verbatim. However, similar to the `expand` option of the SoS actions, you can interpolate scripts before they are executed by the kernels. Basically,1. By default, scripts are not interpolated.2. With `%expand` magic, scripts are treated as Python f-string and are interpolated with sigil `{ }`3. With `%expand ${ }` or other sigils, scripts are interpolated with specified sigil so that you can avoid using symbols that already used in the script.As you can imagine, string interpolation allows passing information from the SoS kernel to the subkernels. Although this method is less flexible and powerful than inter-kernel variable exchange using magics such as `%get`, it is sometimes easier to use and can be especially useful if you plan to include the script as a SoS action in a SoS workflow.For example, ###Code par = 100 %expand cat("A parameter {par} is specified.") ###Output A parameter 100 is specified. ###Markdown If the script contains `{ }`, which is quite common in R, you can double the braces ###Code %expand if ({par} > 50) {{ cat("A parameter {par} greater than 50 is specified."); }} ###Output A parameter 100 greater than 50 is specified. ###Markdown If there are multiple braces, it is obviously better to use a different sigil, such as `${ }` to interpolate the script ###Code %expand ${ } if (${par} > 50) { cat("A parameter ${par} greater than 50 is specified."); } ###Output A parameter 100 greater than 50 is specified. ###Markdown `%get` Magics `%get` retrieve variables from SoS or another subkernel to the current subkernel started by magic `%use`. For example, ###Code %use sos a = [1, 2, 3] b = [1, 2, "3"] c = True %use R %get a b c a b c ###Output _____no_output_____ ###Markdown The `%preview` magic cannot be used to preview variables in the subkernel so we have to list them one by one. As you can see, a Python list can be converted to `R` array or list depending on its content. Similar to the `%put` magic, SoS automatically translate variables with invalid Python names. For example ###Code %use sos _var = 'Hi, Bob' %use R %get _var .var %use sos ###Output _____no_output_____ ###Markdown Also similar to the `--to` option of magic `%put`, magic `%get` accept a parameter `--from` to get variables from SoS (default) any kernel. For example, ###Code R_var <- 'R variable' %get --from R R_var R_var ###Output _____no_output_____ ###Markdown Depending on how the language module is defined, such cross-subkernel variable exchange can be achived directly, or by way of SoS, so after the `%get --from R R_var` statement, the `R_var` variable might or might not exist in the SoS kernel. `%matplotlib`Similar to ipython's `matplotlib` magic, the `%matplotlib inline` magic allows the display of matplotlib figures inline in Jupyter notebook or qtconsole. ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10) plt.plot(x, np.sin(x), '--', linewidth=2) plt.show() ###Output _____no_output_____ ###Markdown `%paste` This magic pastes content of clipboard to the cell and execute the cell. It is similar but sometimes more convenient than pasting the content using system shortcuts such as `Cmd-V` (mac). The additional options allow you to execute the pasted workflow with these options (see magic `%run` for details). `%put` Magics `%put` are used to put variables from subkernel to SoS or another subkernel. For example ###Code %use R a = c(1) b = c(1, 2, 3) c = list(1, 2, 3) d = list(1, 2, "3") e = matrix(c(1,2,3,4), ncol=2) %put a b c d e %preview a b c d e ###Output Loading required package: feather ###Markdown As you can see, although `a` is technically an array with length 1 in `R`, it is convertered to an integer in SoS. Variables `b` and `c` are converted to the same type (`list`) although they are of different types in `R`. Variable `e` are converted from `R` matrix to `numpy` array. Sometimes a valid variale name in a subkernel is not a valid name in SoS/Python. SoS would automatically convert such names with a warning message. For example, ###Code .a.b = 5 %put .a.b %preview _a_b --kernel sos ###Output Variable .a.b is put to SoS as _a_b ###Markdown In addition to putting variables from subkernel to SoS, you can also put variables from SoS to subkernel, or from any subkernel to another, using parameter `--to`. For example, ###Code R_var <- 'R variable' %put --to Python3 R_var R_var ###Output _____no_output_____ ###Markdown Depending on the language module, such cross-subkernel variable exchange can be performed directly, or by way of SoS. The former is generally faster and, in case of data exchange between instances of the same language, can usually be done witout loss of information. `%preview` The `%preview` magic has been discussed above. Here is a complete list of options: ###Code %preview -h ###Output usage: %preview [-h] [-k KERNEL] [-w] [-o] [-s {table,scatterplot,png}] [-r [HOST]] [--off] [-p | -n] [-c CONFIG] [items [items ...]] Preview files, sos variables, or expressions in the side panel, or notebook if side panel is not opened, unless options --panel or --notebook is specified. positional arguments: items Filename, variable name, or expression. Wildcard characters such as '*' and '?' are allowed for filenames. optional arguments: -h, --help show this help message and exit -k KERNEL, --kernel KERNEL kernel in which variables will be previewed. By default the variable will be previewed in the current kernel of the cell. -w, --workflow Preview notebook workflow -o, --keep-output Do not clear the output of the side panel. -s {table,scatterplot,png}, --style {table,scatterplot,png} Option for preview file or variable, which by default is "table" for Pandas DataFrame. The %preview magic also accepts arbitrary additional keyword arguments, which would be interpreted by individual style. Passing '-h' with '--style' would display the usage information of particular style. -r [HOST], --host [HOST] Preview files on specified remote host, which should be defined under key host of sos configuration files (preferrably in ~/.sos/hosts.yml). If this option is specified without value, SoS will list all configured queues and stop. --off Turn off file preview -p, --panel Preview in side panel even if the panel is currently closed -n, --notebook Preview in the main notebook. -c CONFIG, --config CONFIG A configuration file with host definitions, in case the definitions are not defined in global or local sos config.yml files. ###Markdown `%render` The `%render` magic converts the output of a cell to certain format before displaying it in the notebook. The format can be any format supported by the [`IPython.display` module](https://ipython.org/ipython-doc/3/api/generated/IPython.display.html) and is default to `Markdown`. For example, the following code displays all supported options of `%render` by checking the subclasses of `IPython.display`. The cell returns a string in markdown format and is rendered in `Markdown`. ###Code %render import IPython.display import inspect res = ''' Options of magic %render ''' for key in IPython.display.__dict__.keys(): cls = getattr(IPython.display, key) if inspect.isclass(cls) and issubclass(cls, IPython.display.DisplayObject): res += '* {}\n'.format(key) # this is the output of this cell and will be rendered in Markdown format res ###Output _____no_output_____ ###Markdown Similarly, you can use magic `%render` to render output in other formats: ###Code %render --as HTML ''' This is a table in HTML format <br> <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> ''' ###Output _____no_output_____ ###Markdown The `%render` magic captures not only the return value of SoS cell, but also standard output of SoS and other cells. For example, a subprocess of the following cell (a Python script) prints the content of a SVG file to standard output, which is captured and displayed by magic `%render`. ###Code %render --as SVG python: print(r''' <svg height="140" width="140"> <defs> <filter id="f1" x="0" y="0" width="200%" height="200%"> <feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" /> <feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> </defs> <rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /> Sorry, your browser does not support inline SVG. </svg> ''') ###Output <svg height="140" width="140"> <defs> <filter id="f1" x="0" y="0" width="200%" height="200%"> <feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" /> <feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> </defs> <rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /> Sorry, your browser does not support inline SVG. </svg> ###Markdown The `%render` magic also works for other kernels although it can be tricky to determine what is printed to standard output. For kernel R, the function to print to standard output is `cat` so you can use `cat` to print something to the standard output for `%render` to process. For example, ###Code %render a <- rnorm(5) cat(paste(length(a), "random numbers")) cat(paste('*', a, collapse='\n')) ###Output 5 random numbers* -1.50442651757407 * -0.977242498620981 * 0.534575832846015 * -0.390538801124654 * 0.107239275008704 ###Markdown Finally, it worth noting that `%render` captures `stdout` by default but it can also capture and render text from `text/html` from `display_data` messages. This requires a parameter `text` after `%render`. Please check the details about this capture mechanism from magic `%capture`. `%runfile` The `%runfile` magic executes a SoS script from specified file with specified option. Both SoS scripts (usually with extension .sos) and SoS notebooks (with extension .ipynb) are supported. ###Code %run %save runfile_test -f parameter: a = 10 [10] print(f"a is set to f{a}") %runfile runfile_test --a 20 ###Output a is set to f20 ###Markdown `%revisions` The `%revisions` magic displays revisions of the current document if the document is managed by git.This magic accepts a few options: ###Code %revisions -h ###Output usage: %revision [-h] [-s [SOURCE]] [-l LINKS [LINKS ...]] Revision history of the document, parsed from the log message of the notebook if it is kept in a git repository. Additional parameters to "git log" command (e.g. -n 5 --since --after) could be specified to limit the revisions to display. optional arguments: -h, --help show this help message and exit -s [SOURCE], --source [SOURCE] Source URL to to create links for revisions. SoS automatically parse source URL of the origin and provides variables "repo" for complete origin URL without trailing ".git" (e.g. https://github.com/vatlab/sos-notebook), "path" for complete path name (e.g. src/document/doc.ipynb), "filename" for only the name of the "path", and "revision" for revisions. Because sos interpolates command line by default, variables in URL template should be included with double braceses (e.g. --source {{repo}}/blob/{{revision}}/{{path}})). If this option is provided without value and the document is hosted on github, a default template will be provided. -l LINKS [LINKS ...], --links LINKS [LINKS ...] Name and URL or additional links for related files (e.g. --links report URL_to_repo ) with URL interpolated as option --source. ###Markdown First, any options that are acceptable to [command `git log`](https://git-scm.com/docs/git-log) can be passed to this magic. The most useful ones are options to limit the commits to display such as `-n` (number of commits to output), `--since=` and `--after=`. For example, you can display five most recent commits with command ###Code %revisions -n 5 ###Output _____no_output_____ ###Markdown Another useful option is the `--source` option that allows you to link the revision to specific URL (e.g. github). This option should be specified as a string with `repo`, `revision`, `path`, and `filename` interpolated as URL to the repository, revision id, and path and name of the document respectively. Here `repo` is retrieved from the output of command `git ls-remote --get-url origin` without trailing `.git` (if available). Because SoS Notebook interpolates magics automatically, you should include variables in double braces.For example, the github URL of a particular revision of this document is `https://github.com/REPO/blob/REVISION/PATH/TO/FILENAME` so the command to link this document to its source on github would be: ###Code %revisions -n 5 --source '{{repo}}/blob/{{revision}}/{{path}}' ###Output _____no_output_____ ###Markdown Because `github` is the most widely used git repository, we provide the aforementioned template by default if you specify option `--source` without value. That is to say, if your document is hosted in `github.com`, you can simply use```%revisions --source```to link revisions to github. The links do not have to point to the source of the document. For example, because we always convert this document to HTML in another directory and display it on our homepage, we can link the revisions to the HTML version as follows: ###Code %revisions -n 5 \ --source '{{repo}}/blob/{{revision}}/doc/documentation/{{filename[:-6]}}.html' ###Output _____no_output_____ ###Markdown And if you would like to display one or more links next to the revision number, you can do so with the `--links` option: ###Code %revisions -n 5 --source \ --links HTML '{{repo}}/blob/{{revision}}/doc/documentation/{{filename[:-6]}}.html' ###Output _____no_output_____ ###Markdown `%run` The `%run` magic allows you to run the content of a cell as a SoS workflow with specify SoS options such as `-v` (verbosity), `-j` (max number of jobs), and workflow options as defined by `parameter:` keyword.The content of the cell is extracted and executed as an independent SoS script. The script does not use any existing variable so all parameters must be passed from command line (options of `%run`). The resulting dictionary will merged to the SoS dictionary to make it easy to check the result of the workflow, unless the workflow is executed remotely on another server (option `-r HOST`). For example, if we define a variable in the SoS kernel, ###Code var = 100 ###Output _____no_output_____ ###Markdown it is can be used in other scratch cells, ###Code var += 100 print(var) ###Output 200 ###Markdown But not in the workflow executed by magic %run` ###Code %sandbox --expect-error %run print(var) ###Output --------------------------------------------------------------------------- NameError Traceback (most recent call last) script_5226703861919018952 in <module> ----> print(var) NameError: name 'var' is not defined ###Markdown So you will have to pass the value as a parameter ###Code %run --var 40 parameter: var = int var += 400 ###Output _____no_output_____ ###Markdown However, when the workflow is executed, the workflow dictionary is merged to the SoS kernel so that you can examine the resulting variables, ###Code print(var) ###Output 440 ###Markdown The `%run` magics also provides you a way to execute the same cell multiple times with different parameters, for example ###Code %run %run --var 1 parameter: var=0 sh: expand=True echo {var} ###Output 0 1 ###Markdown The `[global]` section header is optional for SoS scripts so you can define global variables in a cell executed by magic `%run` as follows: ###Code %run VAR = "this is local global" [step] print(VAR) ###Output this is local global ###Markdown Remember that `%sosrun` collects all sections from a notebook and merge multiple `[global]` sections into one, using the global section without a header is actually recommended if the definition is meant to be confined to the cell workflow. A complete list of arguments can be shown using the `-h` option. ###Code %run -h ###Output usage: run [-h] [-j JOBS] [-J EXTERNAL_JOBS] [-c CONFIG_FILE] [-t FILE [FILE ...]] [-b [BIN_DIR [BIN_DIR ...]]] [-q [QUEUE]] [-w] [-W] [-r [HOST]] [-n] [-s SIGMODE] [-d [DAG]] [-p [REPORT]] [-v {0,1,2,3,4}] [WORKFLOW] Execute default or specified workflow defined in script positional arguments: WORKFLOW Name of the workflow to execute. This option can be ignored if the script defines a default workflow (with no name or with name `default`) or defines only a single workflow. A subworkflow or a combined workflow can also be specified, where a subworkflow executes a subset of workflow (`name_steps` where `steps` can be `n` (a step `n`), `:n` (up to step `n`), `n:m` (from step `n` to `m`), and `n:` (from step `n`)), and a combined workflow executes to multiple (sub)workflows combined by `+` (e.g. `A_0+B+C`). optional arguments: -h, --help show this help message and exit -j JOBS Maximum number of worker processes for the execution of steps in a workflow and substeps in a step (with input option concurrent), default to half of number of CPUs -J EXTERNAL_JOBS Maximum number of externally running tasks. This option overrides option "max_running_jobs" of a task queue (option -q) so that you can, for example, submit one job at a time (with -J 1) to test the task queue. -c CONFIG_FILE A configuration file in the format of YAML/JSON. The content of the configuration file will be available as a dictionary CONF in the SoS script being executed. -t FILE [FILE ...] One of more files or alias of other targets that will be the target of execution. If specified, SoS will execute only part of a workflow or multiple workflows or auxiliary steps to generate specified targets. -b [BIN_DIR [BIN_DIR ...]] Extra directories in which SoS will look for executables before standard $PATH. This option essentially prefix $PATH with these directories. Note that the default value '~/.sos/bin' is by convention a default directory for commands that are installed by SoS. You can use option '-b' without value to disallow commands under ~/.sos/bin. -q [QUEUE] host (server) or job queues to execute all tasks in the workflow. The queue can be defined in global or local sos configuration file, or a file specified by option --config. A host is assumed to be a remote machine with process type if no configuration is found. If this option is specified without value, SoS will list all configured queues and exit. -w Wait for the completion of external tasks regardless of the setting of individual task queue. -W Do not wait for the completion of external tasks and quit SoS if all tasks are being executed by external task queues. This option overrides the default wait setting of task queues. -r [HOST] Execute the workflow in specified remote host, which should be defined under key host of sos configuration files (preferrably in ~/.sos/hosts.yml). This option basically copy the workflow to remote host and invoke sos command there. No path translation and input/output file synchronization will be performed before or after the execution of the workflow. Run mode options: Control how sos scirpt is executed. -n Execute a workflow in dryrun mode. Please check command sos dryrun for details of the dryrun mode. -s SIGMODE How runtime signature would be handled, which can be "default" (save and use signature, default mode in batch mode), "ignore" (ignore runtime signature, default mode in interactive mode), "force" (ignore existing signature and overwrite them while executing the workflow), "build" (build new or overwrite existing signature from existing environment and output files), and "assert" for validating existing files against their signatures. Please refer to online documentation for details about the use of runtime signatures. Output options: Output of workflow -d [DAG] Output Direct Acyclic Graph (DAGs) in graphiviz .dot format. Because DAG and status of nodes will change during the execution of workflow, multiple DAGs will be written to the specified file with names {workflow}_1, {workflow}_2 etc. The dot file would be named {script_name}_{timestamp}.dot unless a separate filename is specified. -p [REPORT] Output a report that summarizes the execution of the workflow after the completion of the execution. This includes command line, steps executed, tasks executed, CPU/memory of tasks, and DAG if option -d is also specified. The report will by be named {script_name}_{timestamp}.html unless a separate filename is specified. -v {0,1,2,3,4} Output error (0), warning (1), info (2), debug (3) and trace (4) information to standard output (default to 2). Arbitrary parameters defined by the [parameters] step of the script, and [parameters] steps of other scripts if nested workflows are defined in other SoS files (option `source`). The name, default and type of the parameters are specified in the script. Single value parameters should be passed using option `--name value` and multi-value parameters should be passed using option `--name value1 value2`. ###Markdown `%save` Magic `%save` saves the content of the current cell (after the magic itself) to specified file. It accepts the following options: ###Code %save -h ###Output _____no_output_____ ###Markdown `%sosrun` The `%sosrun` option is a very special magic in that it **executes SoS steps defined in the entire notebook**. Essentially speaking, this magic* Collect the content of all SoS cells in the notebook (including the present cell) and extract all sections from it. Comments, magics, and statements before section header is ignored.* Execute the entire workflow with options specified by magic `%sosrun` as a **separate workflow**. Default options specified by magic `%set` is honored. Similar to magic `%run`, the script does not use any existing variable but the workflow dictionary will be merged to the notebook dictionary after the completion of workflow (see magic `%run` for details). For example, ###Code [global] # this is the global section of a workflow parameter: gvar = 20 [workflow_10] print(f"This is step {step_name}, with {gvar}") [workflow_20] print(f"This is step {step_name}, with {gvar}") %sosrun workflow --gvar 40 ###Output This is step workflow_10, with 40 This is step workflow_20, with 40 ###Markdown The content of the workflow is displayed at the side panel (if opened) so that you know what has been collected. Using the workflow feature of SoS, you can execute cells of a notebook conditionally, repeatedly, with different parameters...The following example demonstrates how to execute a step repeated as a nested workflow of another workflow. ###Code # this is a worker step [worker] parameter: val = 5 sh: expand=True echo process {val} # this step will execute the previous cell multiple times %sosrun batch [batch] input: for_each={'val': range(5)} sos_run('worker',val=val) ###Output process 0 process 1 process 2 process 3 process 4 ###Markdown It is worth mentioning that "global definitions" in a cell without `[global]` header is excluded from the notebook workflow. For example, if we have a global definition ###Code [global] VAR = "this is global" ###Output _____no_output_____ ###Markdown A `%run` magic can override definitions in a global section with global definitions without `[global]` header: ###Code %run VAR = "this is local global" [local_global] print(VAR) ###Output this is local global ###Markdown However, because `VAR = "this is local global"` is not included in a section and is execlued from the notebook workflow, the following `%sosrun` magic will have see the statements in the named `[global]` section: ###Code %sosrun local_global ###Output this is global ###Markdown This is why we sometimes call global statements without `[global]` header **local global section** because they are only executed by magic `%run`, not `%sosrun`. `%sossave` Magic `%sossave` saves the **report** or **workflow** defined in the notebook to specified file, according to specified template.1. Save workflow in `.sos` format * By default a workflow will be saved, which consists of cells that start with section header (ignoring leading comments and magics). The content of the file would be identical to the output of magic `%preview --workflow`. * If option `--all` (`-a`) is specified, all cells will be saved to a .sos file that might or might not be executable in batch mode. 2. Save report in `HTML` format * By default a template `sos-report` will be used to generate a HTML report, which includes all cells except for those with a `scratch` tag, and will display by default markdown cells without a `hide_output` tag, and output of code cells with a `report_output` tag. In another word, all mark down cells are displayed and output from all code cells are hidden unless you tag them otherwise with keyboard shortcut `Ctrl-Shift-O`. All contents could be displayed with a hidden control panel to the top left corner of the screen. * Other templates could be specified with option `--template`. For example, a `sos-full` report will generate a HTML file with all content. This magic determines file format with file extension (e.g. `output.html` or option `--to` (e.g. `-t html`), an option `--force` to override existing file, and an option `-x` to add executable permission to the saved .sos file. The `%sossave` can also help you track revisions of your analysis by committing files to git repository. If your notebook is under a git repository, you can use* Option `-c` (`--commit`) to run command `git commit SAVEDFILE` with optional message specified by option `-m` (`--message`).* Option `-p` (`--push`) to run command `git push`. ###Code %sossave -h ###Output usage: %sossave [-h] [-t {sos,html}] [-c] [-a] [-m MESSAGE] [-p] [-f] [-x] [--template TEMPLATE] [filename] Save the jupyter notebook as workflow (consisting of all sos steps defined in cells starting with section header) or a HTML report to specified file. positional arguments: filename Filename of saved report or script. Default to notebookname with file extension determined by option --to. optional arguments: -h, --help show this help message and exit -t {sos,html}, --to {sos,html} Destination format, default to sos. -c, --commit Commit the saved file to git directory using command git commit FILE -a, --all The --all option for sos convert script.ipynb script.sos, which saves all cells and their metadata to a .sos file, that contains all input information of the notebook but might not be executable in batch mode. -m MESSAGE, --message MESSAGE Message for git commit. Default to "save FILENAME" -p, --push Push the commit with command "git push" -f, --force If destination file already exists, overwrite it. -x, --set-executable Set `executable` permission to saved script. --template TEMPLATE Template to generate HTML output. The default template is a template defined by configuration key default- sos-template, or sos-report if such a key does not exist. ###Markdown `%set` The `%set` magic sets a persistent sos options so you do not have to enter them each time after `%run` or `%paste`. For example, if you set `%set -v3`, you can execute all cells in the notebook at verbosity level 3 (`DEBUG`).Note that this magic only accepts keyword arguments (with leading `-` or `--`) so you cannot use it to specify a default workflow to execute. ###Code %set -v2 [cat_10] [cat_20] %set -v1 [mouse_10] [mouse_20] ###Output Set sos options to "-v1" ###Markdown `%sandbox` The `%sandbox` magic executes the current cell in the temporary directory with a separate dictionary so that it would change SoS dictionary and files in the current directory. This magic accepts three parameters:1. If `-d` or `--dir` is specified, sandbox will use the specified directory. It will create the directory if it is does not exist, and will not clean or remove the directory after the completion of execution.2. If `-k` or `--keep-dict` is specified, the cell would use the existing SoS dictionary instead of creating a new one.3. If `-e` or `--expect-error` is specified, the cell expects an error and would return `ok` only if an `error` occurs. In practice, this option would prevent Jupyter from stopping at a cell that expects an error when you execute the whole notebook with "execute all". For example, this `ls` commands happens at the current directory ###Code !ls Auxil* ###Output ls: Auxil*: No such file or directory ###Markdown but the notebook is not available in the sandbox ###Code %sandbox !ls Auxil* ###Output ls: Auxil*: No such file or directory ###Markdown and the sandbox dictionary is empty ###Code %sandbox %dict --keys ###Output _____no_output_____ ###Markdown Note that the working directory of subkernels is not affected by the `%sandbox` magic. `%sessioninfo` Magic `%sessioninfo` returns the session information of SoS and all the subkernels, which for example include version of the python interpreter and name and version of all imported modules for Python kernels, and the output of function `sessionInfo()` for language R. This magic also outputs values of a variable `sessioninfo` in the SoS namespace, which can be a dictionary of section header and items in the format of string, list of strings or `(key, value)` pairs, or dictionaries. This mechanism is designed to output arbitrary additional session information, such as revision of documents and versions of commands. The latter has to be collected manually because there is no standard way to get the version information of commands.For example, let us find the revision of this document and versions of two commands `rsync`, and `awk` and put them in `sessioninfo`: ###Code %preview -n sessioninfo import time from collections import OrderedDict sessioninfo = OrderedDict() sessioninfo['Programs'] = [ ['rsync', get_output('rsync --version | head -1')], ['awk', get_output('awk -version')] ] sessioninfo['Extra'] = [ ['Date', time.strftime("%d/%m/%Y")], ['Revision', get_output('git rev-list --count HEAD')], ['HASH', get_output('git rev-parse HEAD')] ] ###Output _____no_output_____ ###Markdown Then, after we load Python3 and R, ###Code import pandas import numpy library('ggplot2') ###Output _____no_output_____ ###Markdown We can run `%sessioninfo` to display all session information: ###Code %sessioninfo ###Output _____no_output_____ ###Markdown `%shutdown` Magic `%shutdown` shuts down a specified kernel, or the current running kernel, with an option to restart it (`--restart`, `-r`). SoS will switch to kernel `SoS` if the current kernel is shutdown. In summary| current kernel | command | kernel after magic||----|----|----|| `R` (for example) | `%shutdown` | `SoS` || `R` | `%shutdown -r` | `R` (new) || `SoS` | `%shutdown R ` | `SoS` (`R` is shutdown) || `SoS` | `%shutdown -r R` | `SoS` (`R` is restarted) | `%taskinfo` When you execute a SoS workflow with external task, one or more tasks would be displayed in the notebook. ![tasks](../media/tasks.png) When you click on the task ID, a `%taskinfo` magic would be executed at the side panel, displaying the detailed information of the task, including a plot of the CPU and memory usage of the task during its execution. ![resource_history](../media/resource_history.png) You can also execute the magic directly by running it in the side panel or a regular cell, with command```%taskinfo 6dbe51a2c129f02e34e454be5f0cbcd9 -q queue```Note that the `-q` (`--queue`) option specifies the task queue in which the task is being executed. `%tasks` The `%tasks` magic lists all or selected tasks in local or remote task queue so that you can monitor them using the notebook interface. The tasks would be listed as shown above and you can1. select the icon to stop a running or pending task, or resume failed or aborted tasks.2. select the task ID to retrieve the details of the task. This magic accepts parameters `-q` (`--queue`), and option `-s` (`--status`) to limit tasks in certain status and `--age`) to limit tasks older or newer than specified age. Option `age` accepts a number with unit `s` (second), `m` (minute), `h` (hour), or `d` (day, default), or hours, minutes and seconds in the `HH:MM:SS` format, with an optional prefix `+` for older than specified time. For example, you can use magic```%tasks -q host -s running```to list all running tasks on a remote task queue named `host`, or ```%tasks -s running -t +2d```to list all tasks that has been running for more than 2 days. `%toc` The `%toc` magic works in two ways. By default, it displays the table of content of the current notebook **in the side panel** which makes it easy for you to navigate within a long notebook. SoS defines a keyboard shortcut `Ctrl-Shift-t` for this magic so there is rarely a need to type it in. The TOC is automatically updated with the addition and removal of headers in the main notebook.If an option `-n` (`--notebook`) is specified, a TOC will be returned as the result of the magic. In contrast to the TOC in side panel, this TOC will not be updated with the editing of the notebook. This usage is therefore suitable for the addition of a TOC at the beginning of the document before exporting the notebook in HTML format. An optional parameter `--id` can be used to give the TOC an ID in case you would like to apply css styles to the TOC. ###Code %toc -n --id magics ###Output _____no_output_____ ###Markdown `%use` As shown above, the `%use name` magic starts or switch to a subkernel named `name`. The kernel can be any locally installed Jupyter kenel, or name of a **language** (e.g. `R` for kernel `ir`). A `language` is usually built upon the corresponding subkernel, with added support for data exchange between SoS and the subkernel. Without any parameter, magic `%use` lists the available subkernels: ###Code %use ###Output Active subkernels: Available subkernels: Bash (bash) JavaScript (javascript) Julia (julia-0.6) Octave (octave) Python2 (python2) Python3 (python3) R (ir) SAS (sas) SoS (sos) TypeScript (typescript) markdown (markdown) ###Markdown The value of magic `%use`, compared to choosing existing kernels interactively, is its ability to start multiple instances of the same subkernel, change properties of existing subkernels, and create new subkernels. These are achieved with options `-k` (`--kernel`), `-l` (`--language`) and `-c` (`--color`), more specifically|usage | sample command | Comment ||---|---| ---||Customize the background color of a subkernel | `%use R -c red` | Can be applied to existing and new subkernels to change background. A special `default` name can reset color back to language default.||Start a separate instance of a known subkernel, with a different name|`%use R2 -k ir -c 'bfff00'`| Use kernel `ir` and its default langauge interface || |`%use R2 -l R -c CCCCCC`| Use default kernel (`ir`) or language `R`||Start a subkernel with a customized language module |`%use R2 -l mymodule.sos_R`| `mymodule.sos_R` should be derived from `sos.R.sos_R` ||Start an existing kernel without langauge definition with a known language module | `%use R_remote -l R`| `R_remote` could be a kernel defined by [remote_ikernel](https://pypi.python.org/pypi/remote_ikernel)||Start another subkernel with a customized language module | `%use R2 -k R_remote -l mymodule.sos_R` | |Note that [remote_ikernel](https://pypi.python.org/pypi/remote_ikernel) provides an interesting way of using SoS because the kernel is actually started on a remote host, possibly on a cluster managed by PBS/Torch, Sun Grid etc. Using a remote kernel along with a local kernel allows you to exchange data between local and remote kernels (although exchanging of large datasets might not work if the data exchange is performed through local files). `%with` The `%with` magic switches to an existing subkernel for the evaluation of the current cell. It accepts options `--in` (or `-i`) and `--out` (or `-o`), so you could use ###Code %with R -i n -o ran ran <- rnorm(n) ###Output _____no_output_____ ###Markdown to get a list of normally distributed numbers using R's `rnorm` function. ###Code ran ###Output _____no_output_____ ###Markdown `!shell-command` If any other command is entered after `!`, sos will treat the rest of the line as a shell command and execute it. Only single-line commands are supported. String interpolation is supported. Note that `!cd` does not change the current working directory because the command is executed in a separate process. Use magic `%cd` for that purpose. The command line would accept string interpolation so you can for example do ###Code import tempfile filename = tempfile.mkstemp()[1] with open(filename, 'w') as out: out.write('something\n') !cat {filename} # clean up !rm {filename} ###Output _____no_output_____ ###Markdown SoS Magics ###Code %revisions --source ###Output _____no_output_____ ###Markdown In addition to SoS statements, you can use a few SoS magics in Jupyter notebook. 1. SoS magics have to be specified at the beginning of a cell, although they can be specified after empty lines and comments.2. Lines ending with `"\"` will be joined so you can break long magics into multiple lines3. Multiple magics can be used in a single cell. This section lists all magics that SoS supports. To get a list of magics, you can enter `%` at the beginning of a line and press tab. You can also get the detailed usage of a magic by executing a magic with `-h` option, for example: ###Code %use -h ###Output usage: %use [-h] [-k KERNEL] [-l LANGUAGE] [-c COLOR] [-r] [-i [IN_VARS [IN_VARS ...]]] [-o [OUT_VARS [OUT_VARS ...]]] [name] Switch to a specified subkernel. positional arguments: name Displayed name of kernel to start (if no kernel with name is specified) or switch to (if a kernel with this name is already started). The name is usually a kernel name (e.g. %use ir) or a language name (e.g. %use R) in which case the language name will be used. One or more parameters --language or --kernel will need to be specified if a new name is used to start a separate instance of a kernel. optional arguments: -h, --help show this help message and exit -k KERNEL, --kernel KERNEL kernel name as displayed in the output of jupyter kernelspec list. Default to the default kernel of selected language (e.g. ir for language R. -l LANGUAGE, --language LANGUAGE Language extension that enables magics such as %get and %put for the kernel, which should be in the name of a registered language (e.g. R), or a specific language module in the format of package.module:class. SoS maitains a list of languages and kernels so this option is only needed for starting a new instance of a kernel. -c COLOR, --color COLOR Background color of new or existing kernel, which overrides the default color of the language. A special value "default" can be used to reset color to default. -r, --restart Restart the kernel if it is running. -i [IN_VARS [IN_VARS ...]], --in [IN_VARS [IN_VARS ...]] Input variables (variables to get from SoS kernel) -o [OUT_VARS [OUT_VARS ...]], --out [OUT_VARS [OUT_VARS ...]] Output variables (variables to put back to SoS kernel before switching back to the SoS kernel ###Markdown Note that subkernels can have their own magics, and SoS basically processes all blank lines and known magics and send rest of the cell content to the subkernel. That is to say, because SoS does not define a `pwd` magic, the following magic would be process by the Python 3 subkernel. ###Code %pwd ###Output _____no_output_____ ###Markdown `%capture` The `capture` magic is executed after the evaluation of the current cell (in SoS or any subkernel), capture the output of the cell (either `stdout` (`stdout` of `stream` message type, the default), `stdout` (`stderr` of `stream` messages), `text` (`text/html` of `display_data` messages), `html` (`text/html` of `display_data` messages), or `raw` (all messages as a list, mostly for debugging purposes). The results are saved to a variable specified by options `--to` or `--append`.When the capture type is plain text (from `stdout`, `stderr`, or `text`), the return result can be parse it as `text`, `json`, `csv`, or `tsv`, and save (`--to`) or append (`--append`) the result to specified variable as text, Python dictionary, or `Pandas` `DataFrame`. ###Code %capture -h ###Output usage: %capture [-h] [--as [{text,json,csv,tsv}]] [-t VAR | -a VAR] [{stdout,stderr,text,markdown,html,raw}] Capture output (stdout) or output file from a subkernel as variable in SoS positional arguments: {stdout,stderr,text,markdown,html,raw} Message type to capture, default to standard output. In terms of Jupyter message types, "stdout" refers to "stream" message with "stdout" type, "stderr" refers to "stream" message with "stderr" type, "text", "markdown" and "html" refers to "display_data" message with "text/plain", "text/markdown" and "text/html" type respectively. If "raw" is specified, all returned messages will be returned in a list format. optional arguments: -h, --help show this help message and exit --as [{text,json,csv,tsv}] How to interpret the captured text. This only applicable to stdout, stderr and text message type where the text from cell output will be collected. If this option is given, SoS will try to parse the text as json, csv (comma separated text), tsv (tab separated text), and store text (from text), Pandas DataFrame (from csv or tsv), dict or other types (from json) to the variable. -t VAR, --to VAR Name of variable to which the captured content will be saved. If no varialbe is specified, the return value will be saved to variable "__captured" and be displayed at the side panel. -a VAR, --append VAR Name of variable to which the captured content will be appended. This option is equivalent to --to if VAR does not exist. If VAR exists and is of the same type of new content (str or dict or DataFrame), the new content will be appended to VAR if VAR is of str (str concatenation), dict (dict update), or DataFrame (DataFrame.append) types. If VAR is of list type, the new content will be appended to the end of the list. ###Markdown The magic can be applied to any kernel (including SoS) but it only captures output as standard output. For example, in the following R code, although both statements print something, only the `cat` function writes to standard output. The result of function `paste` is returned as the result of the cell and is displayed. ###Code %capture --to R_out cat("this is to stdout") paste("this is the return value") R_out ###Output _____no_output_____ ###Markdown Now, if you would like to capture the output of `paste`, you will have to specify `text` to capture text output of the cell: ###Code %capture text --to R_out paste("this is the return value") R_out ###Output _____no_output_____ ###Markdown If you do not know what the cell outputs, you can use option `raw` to display every output messages and decide how to capture it. When no `--to` option is specified, the output will be written to `__captured` and be displayed in the side panel. ###Code %capture raw paste("this is the return value") ###Output _____no_output_____ ###Markdown Option `--as` tries to convert the captured data in a more useful format. For example, if we are doing a sparql search, which outputs result in JSON format: The ability to parse tables as `Pandas` `DataFrame` is convenient but magic parse tables with `pandas.read_csv(sep)` with any additional parameter. If you need more flexibility in parsing the table (e.g. table without header), you will have to capture the output as text and parse it by yourself. `%cd` Change the current working directory of the SoS kernel and all subkernels to `dir`. `%clear` Magic `clear` clears task lists or the output of cells in the following ways:1. If `%clear` is used in a regular cell, the output of the cell will be cleared after the cell is executed, effectively suppress any output of the cell. This is useful in suppressing long output of sos workflows or shell commands.2. If `%clear` is executed in the side panel, the output of currently selected cells in the main notebook will be cleared. This magic can then be used as a way to selectively clean up the main notebook without leaving the magic itself in the notebook.3. If `%clear -a` or `%clear --all` is executed, it would remove the output of all cells in the notebook, leaving a clean notebook without any output. This is usually used in removing all tests results and leaving only defined workflow steps in the notebook.4. If option `-s` (`--status`) is specified with a status (most frequently `completed`), all tasks with matching status will be removed. The aforementioned rules apply to the cells that will be affected. For example, the output of the following cell is suppressed with the `%clear` magic: ###Code %clear python: print('hello') ###Output _____no_output_____ ###Markdown `%dict` The `%dict` magic lists or rests the content of SoS dict, using syntax```%dict [-a|-all] [-k|--keys] [-r|--reset] [var1] [var2] ...```where* `var1`, `var2` etc are name of variables. All variables will be displayed if no variable is specified.* `-a|-all`: list all dictionary keys, including SoS functions and variables.* `-k|--keys`: list only keys, not their values* `-r|--reset`: reset the dictionary to its original content (with only SoS internal values) ###Code %dict --reset %dict --keys ###Output _____no_output_____ ###Markdown and reset the dictionary with the `--reset` option ###Code %dict --keys ###Output _____no_output_____ ###Markdown For example, you can see all keys in the SoS dictionary using ###Code %dict --reset %dict --keys ###Output _____no_output_____ ###Markdown and reset the dictionary with the `--reset` option ###Code %dict --keys ###Output _____no_output_____ ###Markdown `%expand` Script in SoS cells are by default sent to SoS or the subkernels in verbatim. However, similar to the `expand` option of the SoS actions, you can interpolate scripts before they are executed by the kernels. Basically,1. By default, scripts are not interpolated.2. With `%expand` magic, scripts are treated as Python f-string and are interpolated with sigil `{ }`3. With `%expand ${ }` or other sigils, scripts are interpolated with specified sigil so that you can avoid using symbols that already used in the script.As you can imagine, string interpolation allows passing information from the SoS kernel to the subkernels. Although this method is less flexible and powerful than inter-kernel variable exchange using magics such as `%get`, it is sometimes easier to use and can be especially useful if you plan to include the script as a SoS action in a SoS workflow.For example, ###Code par = 100 %expand cat("A parameter {par} is specified.") ###Output A parameter 100 is specified. ###Markdown If the script contains `{ }`, which is quite common in R, you can double the braces ###Code %expand if ({par} > 50) {{ cat("A parameter {par} greater than 50 is specified."); }} ###Output A parameter 100 greater than 50 is specified. ###Markdown If there are multiple braces, it is obviously better to use a different sigil, such as `${ }` to interpolate the script ###Code %expand ${ } if (${par} > 50) { cat("A parameter ${par} greater than 50 is specified."); } ###Output A parameter 100 greater than 50 is specified. ###Markdown `%get` Magics `%get` retrieve variables from SoS or another subkernel to the current subkernel started by magic `%use`. For example, ###Code %use sos a = [1, 2, 3] b = [1, 2, "3"] c = True %use R %get a b c a b c ###Output _____no_output_____ ###Markdown The `%preview` magic cannot be used to preview variables in the subkernel so we have to list them one by one. As you can see, a Python list can be converted to `R` array or list depending on its content. Similar to the `%put` magic, SoS automatically translate variables with invalid Python names. For example ###Code %use sos _var = 'Hi, Bob' %use R %get _var .var %use sos ###Output _____no_output_____ ###Markdown Also similar to the `--to` option of magic `%put`, magic `%get` accept a parameter `--from` to get variables from SoS (default) any kernel. For example, ###Code R_var <- 'R variable' %get --from R R_var R_var ###Output _____no_output_____ ###Markdown Depending on how the language module is defined, such cross-subkernel variable exchange can be achived directly, or by way of SoS, so after the `%get --from R R_var` statement, the `R_var` variable might or might not exist in the SoS kernel. `%matplotlib`Similar to ipython's `matplotlib` magic, the `%matplotlib inline` magic allows the display of matplotlib figures inline in Jupyter notebook or qtconsole. ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 10) plt.plot(x, np.sin(x), '--', linewidth=2) plt.show() ###Output _____no_output_____ ###Markdown `%paste` This magic pastes content of clipboard to the cell and execute the cell. It is similar but sometimes more convenient than pasting the content using system shortcuts such as `Cmd-V` (mac). The additional options allow you to execute the pasted workflow with these options (see magic `%run` for details). `%put` Magics `%put` are used to put variables from subkernel to SoS or another subkernel. For example ###Code %use R a = c(1) b = c(1, 2, 3) c = list(1, 2, 3) d = list(1, 2, "3") e = matrix(c(1,2,3,4), ncol=2) %put a b c d e %preview a b c d e ###Output Loading required package: feather ###Markdown As you can see, although `a` is technically an array with length 1 in `R`, it is convertered to an integer in SoS. Variables `b` and `c` are converted to the same type (`list`) although they are of different types in `R`. Variable `e` are converted from `R` matrix to `numpy` array. Sometimes a valid variale name in a subkernel is not a valid name in SoS/Python. SoS would automatically convert such names with a warning message. For example, ###Code .a.b = 5 %put .a.b %preview _a_b --kernel sos ###Output Variable .a.b is put to SoS as _a_b ###Markdown In addition to putting variables from subkernel to SoS, you can also put variables from SoS to subkernel, or from any subkernel to another, using parameter `--to`. For example, ###Code R_var <- 'R variable' %put --to Python3 R_var R_var ###Output _____no_output_____ ###Markdown Depending on the language module, such cross-subkernel variable exchange can be performed directly, or by way of SoS. The former is generally faster and, in case of data exchange between instances of the same language, can usually be done witout loss of information. `%preview` The `%preview` magic has been discussed above. Here is a complete list of options: ###Code %preview -h ###Output usage: %preview [-h] [-k KERNEL] [-w] [-o] [-s {table,scatterplot,png}] [-r [HOST]] [--off] [-p | -n] [-c CONFIG] [items [items ...]] Preview files, sos variables, or expressions in the side panel, or notebook if side panel is not opened, unless options --panel or --notebook is specified. positional arguments: items Filename, variable name, or expression. Wildcard characters such as '*' and '?' are allowed for filenames. optional arguments: -h, --help show this help message and exit -k KERNEL, --kernel KERNEL kernel in which variables will be previewed. By default the variable will be previewed in the current kernel of the cell. -w, --workflow Preview notebook workflow -o, --keep-output Do not clear the output of the side panel. -s {table,scatterplot,png}, --style {table,scatterplot,png} Option for preview file or variable, which by default is "table" for Pandas DataFrame. The %preview magic also accepts arbitrary additional keyword arguments, which would be interpreted by individual style. Passing '-h' with '--style' would display the usage information of particular style. -r [HOST], --host [HOST] Preview files on specified remote host, which should be defined under key host of sos configuration files (preferrably in ~/.sos/hosts.yml). If this option is specified without value, SoS will list all configured queues and stop. --off Turn off file preview -p, --panel Preview in side panel even if the panel is currently closed -n, --notebook Preview in the main notebook. -c CONFIG, --config CONFIG A configuration file with host definitions, in case the definitions are not defined in global or local sos config.yml files. ###Markdown `%render` The `%render` magic converts the output of a cell to certain format before displaying it in the notebook. The format can be any format supported by the [`IPython.display` module](https://ipython.org/ipython-doc/3/api/generated/IPython.display.html) and is default to `Markdown`. For example, the following code displays all supported options of `%render` by checking the subclasses of `IPython.display`. The cell returns a string in markdown format and is rendered in `Markdown`. ###Code %render import IPython.display import inspect res = ''' Options of magic %render ''' for key in IPython.display.__dict__.keys(): cls = getattr(IPython.display, key) if inspect.isclass(cls) and issubclass(cls, IPython.display.DisplayObject): res += '* {}\n'.format(key) # this is the output of this cell and will be rendered in Markdown format res ###Output _____no_output_____ ###Markdown Similarly, you can use magic `%render` to render output in other formats: ###Code %render --as HTML ''' This is a table in HTML format <br> <table style="width:100%"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> ''' ###Output _____no_output_____ ###Markdown The `%render` magic captures not only the return value of SoS cell, but also standard output of SoS and other cells. For example, a subprocess of the following cell (a Python script) prints the content of a SVG file to standard output, which is captured and displayed by magic `%render`. ###Code %render --as SVG python: print(r''' <svg height="140" width="140"> <defs> <filter id="f1" x="0" y="0" width="200%" height="200%"> <feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" /> <feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> </defs> <rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /> Sorry, your browser does not support inline SVG. </svg> ''') ###Output <svg height="140" width="140"> <defs> <filter id="f1" x="0" y="0" width="200%" height="200%"> <feOffset result="offOut" in="SourceAlpha" dx="20" dy="20" /> <feGaussianBlur result="blurOut" in="offOut" stdDeviation="10" /> <feBlend in="SourceGraphic" in2="blurOut" mode="normal" /> </filter> </defs> <rect width="90" height="90" stroke="green" stroke-width="3" fill="yellow" filter="url(#f1)" /> Sorry, your browser does not support inline SVG. </svg> ###Markdown The `%render` magic also works for other kernels although it can be tricky to determine what is printed to standard output. For kernel R, the function to print to standard output is `cat` so you can use `cat` to print something to the standard output for `%render` to process. For example, ###Code %render a <- rnorm(5) cat(paste(length(a), "random numbers")) cat(paste('*', a, collapse='\n')) ###Output 5 random numbers* -1.50442651757407 * -0.977242498620981 * 0.534575832846015 * -0.390538801124654 * 0.107239275008704 ###Markdown Finally, it worth noting that `%render` captures `stdout` by default but it can also capture and render text from `text/html` from `display_data` messages. This requires a parameter `text` after `%render`. Please check the details about this capture mechanism from magic `%capture`. `%rerun` The `%rerun` magic re-executed the last script, which is basically content of the last cell without the magics. This allows you to re-run the last cell with or without a new set of parameters. Note that cells without a script (e.g. a cell with only magics) does not change the last executed script. ###Code %run parameter: a = 10 [10] print(f"a is set to f{a}") %rerun --a 20 ###Output a is set to f20 ###Markdown `%revisions` The `%revisions` magic displays revisions of the current document if the document is managed by git.This magic accepts a few options: ###Code %revisions -h ###Output usage: %revision [-h] [-s [SOURCE]] [-l LINKS [LINKS ...]] Revision history of the document, parsed from the log message of the notebook if it is kept in a git repository. Additional parameters to "git log" command (e.g. -n 5 --since --after) could be specified to limit the revisions to display. optional arguments: -h, --help show this help message and exit -s [SOURCE], --source [SOURCE] Source URL to to create links for revisions. SoS automatically parse source URL of the origin and provides variables "repo" for complete origin URL without trailing ".git" (e.g. https://github.com/vatlab/sos-notebook), "path" for complete path name (e.g. src/document/doc.ipynb), "filename" for only the name of the "path", and "revision" for revisions. Because sos interpolates command line by default, variables in URL template should be included with double braceses (e.g. --source {{repo}}/blob/{{revision}}/{{path}})). If this option is provided without value and the document is hosted on github, a default template will be provided. -l LINKS [LINKS ...], --links LINKS [LINKS ...] Name and URL or additional links for related files (e.g. --links report URL_to_repo ) with URL interpolated as option --source. ###Markdown First, any options that are acceptable to [command `git log`](https://git-scm.com/docs/git-log) can be passed to this magic. The most useful ones are options to limit the commits to display such as `-n` (number of commits to output), `--since=` and `--after=`. For example, you can display five most recent commits with command ###Code %revisions -n 5 ###Output _____no_output_____ ###Markdown Another useful option is the `--source` option that allows you to link the revision to specific URL (e.g. github). This option should be specified as a string with `repo`, `revision`, `path`, and `filename` interpolated as URL to the repository, revision id, and path and name of the document respectively. Here `repo` is retrieved from the output of command `git ls-remote --get-url origin` without trailing `.git` (if available). Because SoS Notebook interpolates magics automatically, you should include variables in double braces.For example, the github URL of a particular revision of this document is `https://github.com/REPO/blob/REVISION/PATH/TO/FILENAME` so the command to link this document to its source on github would be: ###Code %revisions -n 5 --source '{{repo}}/blob/{{revision}}/{{path}}' ###Output _____no_output_____ ###Markdown Because `github` is the most widely used git repository, we provide the aforementioned template by default if you specify option `--source` without value. That is to say, if your document is hosted in `github.com`, you can simply use```%revisions --source```to link revisions to github. The links do not have to point to the source of the document. For example, because we always convert this document to HTML in another directory and display it on our homepage, we can link the revisions to the HTML version as follows: ###Code %revisions -n 5 \ --source '{{repo}}/blob/{{revision}}/doc/documentation/{{filename[:-6]}}.html' ###Output _____no_output_____ ###Markdown And if you would like to display one or more links next to the revision number, you can do so with the `--links` option: ###Code %revisions -n 5 --source \ --links HTML '{{repo}}/blob/{{revision}}/doc/documentation/{{filename[:-6]}}.html' ###Output _____no_output_____ ###Markdown `%run` The `%run` magic allows you to run the content of a cell as a SoS workflow with specify SoS options such as `-v` (verbosity), `-j` (max number of jobs), and workflow options as defined by `parameter:` keyword.The content of the cell is extracted and executed as an independent SoS script. The script does not use any existing variable so all parameters must be passed from command line (options of `%run`). The resulting dictionary will merged to the SoS dictionary to make it easy to check the result of the workflow, unless the workflow is executed remotely on another server (option `-r HOST`). For example, if we define a variable in the SoS kernel, ###Code var = 100 ###Output _____no_output_____ ###Markdown it is can be used in other scratch cells, ###Code var += 100 print(var) ###Output 200 ###Markdown But not in the workflow executed by magic %run` ###Code %sandbox --expect-error %run print(var) ###Output --------------------------------------------------------------------------- NameError Traceback (most recent call last) script_5226703861919018952 in <module> ----> print(var) NameError: name 'var' is not defined ###Markdown So you will have to pass the value as a parameter ###Code %run --var 40 parameter: var = int var += 400 ###Output _____no_output_____ ###Markdown However, when the workflow is executed, the workflow dictionary is merged to the SoS kernel so that you can examine the resulting variables, ###Code print(var) ###Output 440 ###Markdown The `%run` magics also provides you a way to execute the same cell multiple times with different parameters, for example ###Code %run %run --var 1 parameter: var=0 sh: expand=True echo {var} ###Output 0 1 ###Markdown The `[global]` section header is optional for SoS scripts so you can define global variables in a cell executed by magic `%run` as follows: ###Code %run VAR = "this is local global" [step] print(VAR) ###Output this is local global ###Markdown Remember that `%sosrun` collects all sections from a notebook and merge multiple `[global]` sections into one, using the global section without a header is actually recommended if the definition is meant to be confined to the cell workflow. A complete list of arguments can be shown using the `-h` option. ###Code %run -h ###Output usage: run [-h] [-j JOBS] [-J EXTERNAL_JOBS] [-c CONFIG_FILE] [-t FILE [FILE ...]] [-b [BIN_DIR [BIN_DIR ...]]] [-q [QUEUE]] [-w] [-W] [-r [HOST]] [-n] [-s SIGMODE] [-d [DAG]] [-p [REPORT]] [-v {0,1,2,3,4}] [WORKFLOW] Execute default or specified workflow defined in script positional arguments: WORKFLOW Name of the workflow to execute. This option can be ignored if the script defines a default workflow (with no name or with name `default`) or defines only a single workflow. A subworkflow or a combined workflow can also be specified, where a subworkflow executes a subset of workflow (`name_steps` where `steps` can be `n` (a step `n`), `:n` (up to step `n`), `n:m` (from step `n` to `m`), and `n:` (from step `n`)), and a combined workflow executes to multiple (sub)workflows combined by `+` (e.g. `A_0+B+C`). optional arguments: -h, --help show this help message and exit -j JOBS Maximum number of worker processes for the execution of steps in a workflow and substeps in a step (with input option concurrent), default to half of number of CPUs -J EXTERNAL_JOBS Maximum number of externally running tasks. This option overrides option "max_running_jobs" of a task queue (option -q) so that you can, for example, submit one job at a time (with -J 1) to test the task queue. -c CONFIG_FILE A configuration file in the format of YAML/JSON. The content of the configuration file will be available as a dictionary CONF in the SoS script being executed. -t FILE [FILE ...] One of more files or alias of other targets that will be the target of execution. If specified, SoS will execute only part of a workflow or multiple workflows or auxiliary steps to generate specified targets. -b [BIN_DIR [BIN_DIR ...]] Extra directories in which SoS will look for executables before standard $PATH. This option essentially prefix $PATH with these directories. Note that the default value '~/.sos/bin' is by convention a default directory for commands that are installed by SoS. You can use option '-b' without value to disallow commands under ~/.sos/bin. -q [QUEUE] host (server) or job queues to execute all tasks in the workflow. The queue can be defined in global or local sos configuration file, or a file specified by option --config. A host is assumed to be a remote machine with process type if no configuration is found. If this option is specified without value, SoS will list all configured queues and exit. -w Wait for the completion of external tasks regardless of the setting of individual task queue. -W Do not wait for the completion of external tasks and quit SoS if all tasks are being executed by external task queues. This option overrides the default wait setting of task queues. -r [HOST] Execute the workflow in specified remote host, which should be defined under key host of sos configuration files (preferrably in ~/.sos/hosts.yml). This option basically copy the workflow to remote host and invoke sos command there. No path translation and input/output file synchronization will be performed before or after the execution of the workflow. Run mode options: Control how sos scirpt is executed. -n Execute a workflow in dryrun mode. Please check command sos dryrun for details of the dryrun mode. -s SIGMODE How runtime signature would be handled, which can be "default" (save and use signature, default mode in batch mode), "ignore" (ignore runtime signature, default mode in interactive mode), "force" (ignore existing signature and overwrite them while executing the workflow), "build" (build new or overwrite existing signature from existing environment and output files), and "assert" for validating existing files against their signatures. Please refer to online documentation for details about the use of runtime signatures. Output options: Output of workflow -d [DAG] Output Direct Acyclic Graph (DAGs) in graphiviz .dot format. Because DAG and status of nodes will change during the execution of workflow, multiple DAGs will be written to the specified file with names {workflow}_1, {workflow}_2 etc. The dot file would be named {script_name}_{timestamp}.dot unless a separate filename is specified. -p [REPORT] Output a report that summarizes the execution of the workflow after the completion of the execution. This includes command line, steps executed, tasks executed, CPU/memory of tasks, and DAG if option -d is also specified. The report will by be named {script_name}_{timestamp}.html unless a separate filename is specified. -v {0,1,2,3,4} Output error (0), warning (1), info (2), debug (3) and trace (4) information to standard output (default to 2). Arbitrary parameters defined by the [parameters] step of the script, and [parameters] steps of other scripts if nested workflows are defined in other SoS files (option `source`). The name, default and type of the parameters are specified in the script. Single value parameters should be passed using option `--name value` and multi-value parameters should be passed using option `--name value1 value2`. ###Markdown `%save` Magic `%save` saves the content of the current cell (after the magic itself) to specified file. It accepts the following options: ###Code %save -h ###Output _____no_output_____ ###Markdown `%sosrun` The `%sosrun` option is a very special magic in that it **executes SoS steps defined in the entire notebook**. Essentially speaking, this magic* Collect the content of all SoS cells in the notebook (including the present cell) and extract all sections from it. Comments, magics, and statements before section header is ignored.* Execute the entire workflow with options specified by magic `%sosrun` as a **separate workflow**. Default options specified by magic `%set` is honored. Similar to magic `%run`, the script does not use any existing variable but the workflow dictionary will be merged to the notebook dictionary after the completion of workflow (see magic `%run` for details). For example, ###Code [global] # this is the global section of a workflow parameter: gvar = 20 [workflow_10] print(f"This is step {step_name}, with {gvar}") [workflow_20] print(f"This is step {step_name}, with {gvar}") %sosrun workflow --gvar 40 ###Output This is step workflow_10, with 40 This is step workflow_20, with 40 ###Markdown The content of the workflow is displayed at the side panel (if opened) so that you know what has been collected. Using the workflow feature of SoS, you can execute cells of a notebook conditionally, repeatedly, with different parameters...The following example demonstrates how to execute a step repeated as a nested workflow of another workflow. ###Code # this is a worker step [worker] parameter: val = 5 sh: expand=True echo process {val} # this step will execute the previous cell multiple times %sosrun batch [batch] input: for_each={'val': range(5)} sos_run('worker',val=val) ###Output process 0 process 1 process 2 process 3 process 4 ###Markdown It is worth mentioning that "global definitions" in a cell without `[global]` header is excluded from the notebook workflow. For example, if we have a global definition ###Code [global] VAR = "this is global" ###Output _____no_output_____ ###Markdown A `%run` magic can override definitions in a global section with global definitions without `[global]` header: ###Code %run VAR = "this is local global" [local_global] print(VAR) ###Output this is local global ###Markdown However, because `VAR = "this is local global"` is not included in a section and is execlued from the notebook workflow, the following `%sosrun` magic will have see the statements in the named `[global]` section: ###Code %sosrun local_global ###Output this is global ###Markdown This is why we sometimes call global statements without `[global]` header **local global section** because they are only executed by magic `%run`, not `%sosrun`. `%sossave` Magic `%sossave` saves the **report** or **workflow** defined in the notebook to specified file, according to specified template.1. Save workflow in `.sos` format * By default a workflow will be saved, which consists of cells that start with section header (ignoring leading comments and magics). The content of the file would be identical to the output of magic `%preview --workflow`. * If option `--all` (`-a`) is specified, all cells will be saved to a .sos file that might or might not be executable in batch mode. 2. Save report in `HTML` format * By default a template `sos-report` will be used to generate a HTML report, which includes all cells except for those with a `scratch` tag, and will display by default markdown cells without a `hide_output` tag, and output of code cells with a `report_output` tag. In another word, all mark down cells are displayed and output from all code cells are hidden unless you tag them otherwise with keyboard shortcut `Ctrl-Shift-O`. All contents could be displayed with a hidden control panel to the top left corner of the screen. * Other templates could be specified with option `--template`. For example, a `sos-full` report will generate a HTML file with all content. This magic determines file format with file extension (e.g. `output.html` or option `--to` (e.g. `-t html`), an option `--force` to override existing file, and an option `-x` to add executable permission to the saved .sos file. The `%sossave` can also help you track revisions of your analysis by committing files to git repository. If your notebook is under a git repository, you can use* Option `-c` (`--commit`) to run command `git commit SAVEDFILE` with optional message specified by option `-m` (`--message`).* Option `-p` (`--push`) to run command `git push`. ###Code %sossave -h ###Output usage: %sossave [-h] [-t {sos,html}] [-c] [-a] [-m MESSAGE] [-p] [-f] [-x] [--template TEMPLATE] [filename] Save the jupyter notebook as workflow (consisting of all sos steps defined in cells starting with section header) or a HTML report to specified file. positional arguments: filename Filename of saved report or script. Default to notebookname with file extension determined by option --to. optional arguments: -h, --help show this help message and exit -t {sos,html}, --to {sos,html} Destination format, default to sos. -c, --commit Commit the saved file to git directory using command git commit FILE -a, --all The --all option for sos convert script.ipynb script.sos, which saves all cells and their metadata to a .sos file, that contains all input information of the notebook but might not be executable in batch mode. -m MESSAGE, --message MESSAGE Message for git commit. Default to "save FILENAME" -p, --push Push the commit with command "git push" -f, --force If destination file already exists, overwrite it. -x, --set-executable Set `executable` permission to saved script. --template TEMPLATE Template to generate HTML output. The default template is a template defined by configuration key default- sos-template, or sos-report if such a key does not exist. ###Markdown `%set` The `%set` magic sets a persistent sos options so you do not have to enter them each time after `%run` or `%paste`. For example, if you set `%set -v3`, you can execute all cells in the notebook at verbosity level 3 (`DEBUG`).Note that this magic only accepts keyword arguments (with leading `-` or `--`) so you cannot use it to specify a default workflow to execute. ###Code %set -v2 [cat_10] [cat_20] %set -v1 [mouse_10] [mouse_20] ###Output Set sos options to "-v1" ###Markdown `%sandbox` The `%sandbox` magic executes the current cell in the temporary directory with a separate dictionary so that it would change SoS dictionary and files in the current directory. This magic accepts three parameters:1. If `-d` or `--dir` is specified, sandbox will use the specified directory. It will create the directory if it is does not exist, and will not clean or remove the directory after the completion of execution.2. If `-k` or `--keep-dict` is specified, the cell would use the existing SoS dictionary instead of creating a new one.3. If `-e` or `--expect-error` is specified, the cell expects an error and would return `ok` only if an `error` occurs. In practice, this option would prevent Jupyter from stopping at a cell that expects an error when you execute the whole notebook with "execute all". For example, this `ls` commands happens at the current directory ###Code !ls Auxil* ###Output ls: Auxil*: No such file or directory ###Markdown but the notebook is not available in the sandbox ###Code %sandbox !ls Auxil* ###Output ls: Auxil*: No such file or directory ###Markdown and the sandbox dictionary is empty ###Code %sandbox %dict --keys ###Output _____no_output_____ ###Markdown Note that the working directory of subkernels is not affected by the `%sandbox` magic. `%sessioninfo` Magic `%sessioninfo` returns the session information of SoS and all the subkernels, which for example include version of the python interpreter and name and version of all imported modules for Python kernels, and the output of function `sessionInfo()` for language R. This magic also outputs values of a variable `sessioninfo` in the SoS namespace, which can be a dictionary of section header and items in the format of string, list of strings or `(key, value)` pairs, or dictionaries. This mechanism is designed to output arbitrary additional session information, such as revision of documents and versions of commands. The latter has to be collected manually because there is no standard way to get the version information of commands.For example, let us find the revision of this document and versions of two commands `rsync`, and `awk` and put them in `sessioninfo`: ###Code %preview -n sessioninfo import time from collections import OrderedDict sessioninfo = OrderedDict() sessioninfo['Programs'] = [ ['rsync', get_output('rsync --version | head -1')], ['awk', get_output('awk -version')] ] sessioninfo['Extra'] = [ ['Date', time.strftime("%d/%m/%Y")], ['Revision', get_output('git rev-list --count HEAD')], ['HASH', get_output('git rev-parse HEAD')] ] ###Output _____no_output_____ ###Markdown Then, after we load Python3 and R, ###Code import pandas import numpy library('ggplot2') ###Output _____no_output_____ ###Markdown We can run `%sessioninfo` to display all session information: ###Code %sessioninfo ###Output _____no_output_____ ###Markdown `%shutdown` Magic `%shutdown` shuts down a specified kernel, or the current running kernel, with an option to restart it (`--restart`, `-r`). SoS will switch to kernel `SoS` if the current kernel is shutdown. In summary| current kernel | command | kernel after magic||----|----|----|| `R` (for example) | `%shutdown` | `SoS` || `R` | `%shutdown -r` | `R` (new) || `SoS` | `%shutdown R ` | `SoS` (`R` is shutdown) || `SoS` | `%shutdown -r R` | `SoS` (`R` is restarted) | `%taskinfo` When you execute a SoS workflow with external task, one or more tasks would be displayed in the notebook. ![tasks](../media/tasks.png) When you click on the task ID, a `%taskinfo` magic would be executed at the side panel, displaying the detailed information of the task, including a plot of the CPU and memory usage of the task during its execution. ![resource_history](../media/resource_history.png) You can also execute the magic directly by running it in the side panel or a regular cell, with command```%taskinfo 6dbe51a2c129f02e34e454be5f0cbcd9 -q queue```Note that the `-q` (`--queue`) option specifies the task queue in which the task is being executed. `%tasks` The `%tasks` magic lists all or selected tasks in local or remote task queue so that you can monitor them using the notebook interface. The tasks would be listed as shown above and you can1. select the icon to stop a running or pending task, or resume failed or aborted tasks.2. select the task ID to retrieve the details of the task. This magic accepts parameters `-q` (`--queue`), and option `-s` (`--status`) to limit tasks in certain status and `--age`) to limit tasks older or newer than specified age. Option `age` accepts a number with unit `s` (second), `m` (minute), `h` (hour), or `d` (day, default), or hours, minutes and seconds in the `HH:MM:SS` format, with an optional prefix `+` for older than specified time. For example, you can use magic```%tasks -q host -s running```to list all running tasks on a remote task queue named `host`, or ```%tasks -s running -t +2d```to list all tasks that has been running for more than 2 days. `%toc` The `%toc` magic works in two ways. By default, it displays the table of content of the current notebook **in the side panel** which makes it easy for you to navigate within a long notebook. SoS defines a keyboard shortcut `Ctrl-Shift-t` for this magic so there is rarely a need to type it in. The TOC is automatically updated with the addition and removal of headers in the main notebook.If an option `-n` (`--notebook`) is specified, a TOC will be returned as the result of the magic. In contrast to the TOC in side panel, this TOC will not be updated with the editing of the notebook. This usage is therefore suitable for the addition of a TOC at the beginning of the document before exporting the notebook in HTML format. An optional parameter `--id` can be used to give the TOC an ID in case you would like to apply css styles to the TOC. ###Code %toc -n --id magics ###Output _____no_output_____ ###Markdown `%use` As shown above, the `%use name` magic starts or switch to a subkernel named `name`. The kernel can be any locally installed Jupyter kenel, or name of a **language** (e.g. `R` for kernel `ir`). A `language` is usually built upon the corresponding subkernel, with added support for data exchange between SoS and the subkernel. Without any parameter, magic `%use` lists the available subkernels: ###Code %use ###Output Active subkernels: Available subkernels: Bash (bash) JavaScript (javascript) Julia (julia-0.6) Octave (octave) Python2 (python2) Python3 (python3) R (ir) SAS (sas) SoS (sos) TypeScript (typescript) markdown (markdown) ###Markdown The value of magic `%use`, compared to choosing existing kernels interactively, is its ability to start multiple instances of the same subkernel, change properties of existing subkernels, and create new subkernels. These are achieved with options `-k` (`--kernel`), `-l` (`--language`) and `-c` (`--color`), more specifically|usage | sample command | Comment ||---|---| ---||Customize the background color of a subkernel | `%use R -c red` | Can be applied to existing and new subkernels to change background. A special `default` name can reset color back to language default.||Start a separate instance of a known subkernel, with a different name|`%use R2 -k ir -c 'bfff00'`| Use kernel `ir` and its default langauge interface || |`%use R2 -l R -c CCCCCC`| Use default kernel (`ir`) or language `R`||Start a subkernel with a customized language module |`%use R2 -l mymodule.sos_R`| `mymodule.sos_R` should be derived from `sos.R.sos_R` ||Start an existing kernel without langauge definition with a known language module | `%use R_remote -l R`| `R_remote` could be a kernel defined by [remote_ikernel](https://pypi.python.org/pypi/remote_ikernel)||Start another subkernel with a customized language module | `%use R2 -k R_remote -l mymodule.sos_R` | |Note that [remote_ikernel](https://pypi.python.org/pypi/remote_ikernel) provides an interesting way of using SoS because the kernel is actually started on a remote host, possibly on a cluster managed by PBS/Torch, Sun Grid etc. Using a remote kernel along with a local kernel allows you to exchange data between local and remote kernels (although exchanging of large datasets might not work if the data exchange is performed through local files). `%with` The `%with` magic switches to an existing subkernel for the evaluation of the current cell. It accepts options `--in` (or `-i`) and `--out` (or `-o`), so you could use ###Code %with R -i n -o ran ran <- rnorm(n) ###Output _____no_output_____ ###Markdown to get a list of normally distributed numbers using R's `rnorm` function. ###Code ran ###Output _____no_output_____ ###Markdown `!shell-command` If any other command is entered after `!`, sos will treat the rest of the line as a shell command and execute it. Only single-line commands are supported. String interpolation is supported. Note that `!cd` does not change the current working directory because the command is executed in a separate process. Use magic `%cd` for that purpose. The command line would accept string interpolation so you can for example do ###Code import tempfile filename = tempfile.mkstemp()[1] with open(filename, 'w') as out: out.write('something\n') !cat {filename} # clean up !rm {filename} ###Output _____no_output_____
1/S-4_1.ipynb
###Markdown コードの実行コードの入力は全て**半角**で行います。下のセルを実行すると、 1+1が計算され、`2`と表示されます。セルを実行するためには、コードセルの左側にある`[ ]`となっている部分にマウスカーソルを合わせると再生ボタンに変化するので、その状態でクリックするか、コードセルを選択した状態でCtrl+Enter (macでは ⌘+Enter)キーを押下します。 ###Code 1 + 1 ###Output _____no_output_____ ###Markdown `1 + 1`は`1+1`と変わりませんが、式に応じて適宜スペースを入れると見やすくなります。 ###Code 1+1 1*2 + 3*4 ###Output _____no_output_____ ###Markdown 変数変数を使用することで、値を保持することができます。変数は、`変数名 = 値`で宣言します。宣言した変数は同名でアクセスすることで保存した値を呼び出すことができます。 スカラー変数整数、浮動小数点数、文字列、真偽値など単一の値を持つデータはスカラー値と呼ばれ、スカラー値を持つ変数をスカラー変数と呼びます。 ###Code # 整数 a = 1 a # 計算で変数を利用する a + 1 # 浮動小数点数 pi = 3.1415 pi # 文字列 message = 'hello' message # 真偽値 f = 1 == 2 # False f ###Output _____no_output_____ ###Markdown 上記の例のように、コードブロックの最後に変数名を記述すると、最後書かれた変数の値が結果として表示されますが、明示的に値を画面に出力したい場合は`print()`関数を使用します。 ###Code print(a) print(pi) print(message) print(f) ###Output _____no_output_____ ###Markdown 同じ変数名に代入を行うと、前に保存されていた値は消去され、新しい値が上書きされます。 ###Code print(a) # 1 a = 2 print(a) # 2 ###Output _____no_output_____ ###Markdown 配列同じ種類のデータを複数並べたものが配列(list)です。配列の宣言は以下のように行います。 ###Code # 空配列 empty_list = [] # 要素を指定した宣言 l = [1, 2, 3, 4, 5] print(empty_list) print(l) ###Output _____no_output_____ ###Markdown 要素にアクセスする場合は、`変数名[添字]`とします。Pythonでは添字は0から始まるので、2番目の要素にアクセスしたい場合は添字に1を指定します。 ###Code l[1] # 2 ###Output _____no_output_____ ###Markdown 配列の範囲を指定する場合は添字を`始点:終点+1`とします。数学的に表現すると、`[a:b]`と指定した場合、半開区間$[a,b)$が指定されたことになります。別の言い方をすれば、添字$a$から$b-a$個の要素を取り出します。 ###Code # 始点・終点両方を指定する場合 l[1:3] # [2, 3] # 始点のみを指定する場合: 始点の添字から配列の最後まで l[1:] # [2, 3, 4, 5] # 終点のみを指定する場合: 配列の最初から終点(+1)の添字まで l[:3] # [1, 2, 3] ###Output _____no_output_____ ###Markdown 辞書辞書(dictionary)は連想配列とも呼ばれ、キー(文字列)に対して値が対応付けされたデータ構造です。辞書の宣言は以下のように行います。 ###Code # 空の辞書 empty_dic = {} # 要素を指定して宣言 tmp_dic = { 'one': 1, 'two': 2, 'three': 3} print(empty_dic) print(tmp_dic) ###Output _____no_output_____ ###Markdown 辞書の要素へのアクセスは`変数名['キー']`とします。 ###Code tmp_dic['one'] # 1 ###Output _____no_output_____ ###Markdown 辞書は、`変数名.keys()`および`変数名.values()`でキーおよび値を配列として取得可能です。 ###Code tmp_dic.keys() # ['one', 'two', 'three'] tmp_dic.values() # [1, 2, 3] # 使用例: 所定のキーが含まれているか調べる print('one' in tmp_dic.keys()) # True print('four' in tmp_dic.keys()) # False ###Output _____no_output_____ ###Markdown 配列、辞書の入れ子構造配列および辞書はそれぞれ入れ子にすることができます。 ###Code # 配列の配列 (2次元配列) list_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] list_list[0][2] # 3 # 辞書の配列 profs = [ { 'name': 'Takahiro Yano' }, { 'name': 'Masaru Sanuki' }, { 'name': 'Haruka Ozaki' }, { 'name': 'Keitaro Kume' }, { 'name': 'Rina Kagawa' } ] profs[1]['name'] # 'Masaru Sanuki' # 配列の辞書 last_7days_new_positives = { # 9/6 - 8/31 (new to first) 'Ibaraki': [ 158, 259, 263, 263, 220, 215, 160], 'Tokyo': [ 968, 1853, 2362, 2539, 3099, 3168, 2909] } last_7days_new_positives['Ibaraki'][1] # 259 # 辞書の辞書 univ_tsukuba_undergraduate_schools = { 'Medicine and Health Sciences': { 'colleges': ['Medicine', 'Nursing', 'Medical Sciences'], 'dean': 'Masayuki Masu' }, 'Informatics': { 'colleges': ['Information Science', 'Media Arts, Science and Technology', 'Knowledge and Library Sciences'], 'dean': 'Shinichi Nakayama' # as of website } } print(univ_tsukuba_undergraduate_schools) univ_tsukuba_undergraduate_schools['Medicine and Health Sciences']['dean'] # 'Masayuki Masu' ###Output _____no_output_____ ###Markdown 小課題`univ_tsukuba_undergraduate_schools`から`'Information Science'`を取り出すにはどのようにアクセスすれば良いか? ###Code # 小課題 ###Output _____no_output_____ ###Markdown 課題以下の課題を行うこと。 課題1次の表のデータを保存するデータ構造を考え、Python上の1つの変数として宣言するコードを書きなさい。また、正しく値が格納されているか変数を出力して確かめること。宣言した変数は後の課題で操作するので、操作がしやすい構造を考えること。| 名前(name) | 血液型(blood_type) | 年齢(age) | 好きな食べ物(favorite_foods) || ---------- | ------------------ | --------- | ---------------------------- || Alice | A | 20 | pizza, pudding || Bob | B | 31 | beer, candy, steak || Jessie | O | 42 | (None) || Kenshiro | AB | 28 | sake, sushi |(食べ物の中に飲み物が含まれているというツッコミは無しでお願いします) ###Code # 課題1 ###Output _____no_output_____ ###Markdown 課題2表のデータには間違いがあり、Jessieさんの年齢は正しくは35歳でした。Jessieさんの年齢を修正し、Jessieさんに関する情報を辞書の形で出力するコードを記述せよ。 ###Code # 課題2 ###Output _____no_output_____ ###Markdown 課題3Bobさんの好きな食べ物の中に、- pizza- steakが含まれているか。それぞれ判定し、真偽値を出力するコードを記述せよ。 ###Code # 課題3: pizza # 課題3: steak ###Output _____no_output_____
Machine Learning/Predictive ads/predictive_ads_analytics_test.ipynb
###Markdown The following document has information about my process of experimenting with various models to solve a classification problem, in which I tested different models of supervised and unsupervised learning. Which then save in a file to be consumed after training.As it is a proof of concept the code is not ordered and neither optimized. ###Code import pandas as pd import os from os import walk import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split, KFold, cross_val_score, GridSearchCV, StratifiedKFold from sklearn.metrics import confusion_matrix, classification_report, precision_score, accuracy_score, recall_score, f1_score, roc_auc_score, roc_curve, auc from sklearn.pipeline import Pipeline from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier, VotingClassifier from sklearn.neural_network import MLPClassifier import xgboost as xgb from xgboost import plot_tree import joblib import tensorflow as tf import keras from keras.wrappers.scikit_learn import KerasClassifier from keras import Sequential from keras.layers import Dense from keras.models import load_model os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'credentials.json' query_url = """ WITH urls_main_table AS ( SELECT source, ad_id, image_asset_url as url FROM `omg-latam-prd-adh-datahouse-cl.clients_table.main_url_dh` where source = 'Facebook ads' and image_asset_url != '0' group by 1,2,3 UNION ALL SELECT source, ad_id, promoted_tweet_card_image_url as url FROM `omg-latam-prd-adh-datahouse-cl.clients_table.main_url_dh` where source = 'Twitter ads' and promoted_tweet_card_image_url != '0' group by 1,2,3 ), ad_values AS ( SELECT date, ad_id, spend, post_engagements as clicks FROM `main_views_tables.main_ad` where regexp_contains(account_name, '(?i).*scoti.*') ), spend_average AS ( select ad_id, avg(spend) as avg_spend, avg(post_engagements) as avg_clicks from `main_views_tables.main_ad` group by 1 ), categorical_feats AS ( SELECT ad_id, main_topic, main_color, locale, second_topic, second_color, third_topic, third_color FROM `clients_table.main_categorical_values` ) SELECT date, source, url, e.ad_id, main_topic, main_color, locale, second_topic, second_color, third_topic, third_color, (CASE WHEN spend >= avg_spend THEN 1 WHEN spend < avg_spend THEN 0 END) as over_avg_spend, (CASE WHEN clicks >= avg_clicks THEN 1 WHEN clicks < avg_clicks THEN 0 END) as over_avg_clicks FROM (SELECT date, source, url, c.ad_id, main_topic, main_color, locale, second_topic, second_color, third_topic, third_color, spend, clicks FROM (SELECT date, a.source, a.url, b.ad_id, b.spend, b.clicks FROM urls_main_table a RIGHT JOIN ad_values b ON a.ad_id = b.ad_id) c INNER JOIN categorical_feats d ON c.ad_id = d.ad_id) e INNER JOIN spend_average f ON e.ad_id = f.ad_id """ dataframe = pd.read_gbq(query_url) dataframe = dataframe[['main_topic', 'main_color', 'second_topic', 'second_color', 'third_topic', 'third_color', 'locale', 'over_avg_spend', 'over_avg_clicks']] vars = ['main_topic', 'main_color', 'second_topic', 'second_color', 'third_topic', 'third_color', 'locale'] for var in vars: cat_list = 'var' + '_' + var cat_list = pd.get_dummies(dataframe[var], prefix= var) dataframe1 = dataframe.join(cat_list) dataframe = dataframe1 dataframe data_vars = dataframe.columns.values.tolist() to_keep = [i for i in data_vars if i not in vars] data_final = dataframe[to_keep] data_final.columns.values data_final_vars = data_final.columns.values.tolist() v_y = ['over_avg_clicks'] v_x = [i for i in data_final_vars if i not in v_y] X = dataframe[v_x] y = dataframe[v_y] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state = 40, stratify = y) model_xgb = xgb.XGBClassifier(objective = 'binary:logistic', n_estimators = 105, max_depth=75, seed = 10, reg_alpha=7) model_xgb.fit(X_train.values, y_train.values.ravel()) y_pred = model_xgb.predict(X_test.values) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) print('accuracy:', round(accuracy_score(y_test, y_pred), 2)) print(confusion_matrix(y_test, y_pred)) base_frame = dict.fromkeys(list(X_train.columns), [0]) main_topic = 'Clothing' #@param ['Table', 'Smile','Laptop', 'video', 'Arm', 'Hair', 'Jaw', 'Forehead','Head','Chin','Clothing','Sleeve','Plant','Tire', 'Eyelash','Hand', 'Mobilephone', 'Glasses','Shorts'] second_topic = 'Jaw' #@param ['Jaw', 'Product', 'Flashphotography', 'Sleeve', 'Beard', 'Computer', 'Glasses', 'Visioncare', 'Fashion', 'Shirt', 'Jeans', 'Wheel', 'Jersey', 'Smile', 'CommunicationDevice', 'Plant', 'Mobilephone', 'Green', 'Chin', 'Human'] third_topic = 'Font' #@param ['Beard', 'Font', 'Jersey', 'Jaw', 'Chin', 'Eyewear', 'Sleeve', 'Cap', 'Smile', 'Tableware', 'Personalcomputer', 'Eyelash', 'Skin', 'Landvehicle', 'Tabletcomputer', 'Gesture', 'Organism', 'Outerwear', 'Flashphotography', 'Sportsuniform', 'Furniture'] locale = 'en' #@param ['es', 'en'] main_color = 'skyblue' #@param ['black', 'darkslategray', 'darkolivegreen', 'cadetblue', 'dodgerblue', 'mediumpurple', 'hotpink', 'skyblue', 'dimgray', 'linen', 'yellowgreen', 'sienna'] second_color = 'darkgray' #@param ['darkslategray', 'dimgray', 'black', 'darkgray', 'seagreen','skyblue', 'maroon', 'paleturquoise', 'silver', 'crimson','darkgreen', 'slategray', 'mediumpurple', 'gray'] third_color = 'lightgray' #@param ['darkslategray', 'slateblue', 'lightgray', 'mistyrose', 'gray', 'maroon', 'black', 'tan', 'darkgray', 'crimson', 'slategray', 'dimgray', 'silver'] over_avg_spend = 'False' #@param ['True', 'False'] if over_avg_spend == 'False': over_avg_spend = 0 else: over_avg_spend = 1 dataframe = pd.DataFrame({'main_topic':[main_topic], 'main_color':[main_color], 'second_topic':[second_topic], 'second_color':[second_color], 'third_topic':[third_topic], 'third_color':[third_color], 'locale':[locale], 'over_avg_spend':[over_avg_spend]}) vars = ['main_topic', 'main_color', 'second_topic', 'second_color', 'third_topic', 'third_color', 'locale'] for var in vars: cat_list = 'var' + '_' + var cat_list = pd.get_dummies(dataframe[var], prefix= var) dataframe1 = dataframe.join(cat_list) dataframe = dataframe1 data_vars = dataframe.columns.values.tolist() to_keep = [i for i in data_vars if i not in vars] data_final = dataframe[to_keep] my_dict_frame = data_final.to_dict('records') base_frame.update(my_dict_frame[0]) to_predict_frame = pd.DataFrame(base_frame) result = model_xgb.predict(to_predict_frame.values) result_prob = model_xgb.predict_proba(to_predict_frame.values) print('If the ad can be above the average of the results studied it will be classified as 1, otherwise it will be classified as 0. \nThe classification of the ad model entered is: {}'.format(result)) print('Probability of not being successful according to the given parameters: {}%'.format(result_prob[0][0] * 100), '\nProbability of success according to the given parameters: {}%'.format(result_prob[0][1]*100)) plot_tree(model_xgb, num_trees=75) plt.show() ###Output _____no_output_____ ###Markdown FIRST MDOEL ###Code model_classifier = Sequential() input_dimension = len(v_x) layers = 6 neurons = 16 output_layer = 1 for layer in range(layers): model_classifier.add(Dense(neurons, activation= 'relu', kernel_initializer= 'random_normal')) if layer == layers-1: model_classifier.add(Dense(output_layer, activation= 'sigmoid', kernel_initializer='random_normal')) define_optimizer = keras.optimizers.Adam(lr = 0.01) model_classifier.compile(optimizer = define_optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) history_values = model_classifier.fit(x = X_train.values, y = y_train.values, batch_size = 15, epochs = 350, validation_split = 0.15) model_classifier.summary() evaluation_model = model_classifier.evaluate(X_train, y_train) print(evaluation_model) y_pred = model_classifier.predict(X_test).ravel() y_pred = (y_pred > 0.5) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) print('accuracy:', round(accuracy_score(y_test, y_pred), 2)) print(confusion_matrix(y_test, y_pred)) ###Output [[ 38 0] [ 25 6490]] ###Markdown KERAS SKLEARN ###Code def create_model(init='random_normal'): model = Sequential() model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(16, kernel_initializer=init, activation='relu')) model.add(Dense(1, kernel_initializer=init, activation='sigmoid')) define_optimizer = keras.optimizers.Adam(lr = 0.01) model.compile(loss='binary_crossentropy', optimizer=define_optimizer, metrics=['accuracy']) return model model = KerasClassifier(build_fn=create_model, verbose=0, validation_split=0.35) model._estimator_type = "classifier" init = ['random_normal'] epochs = [350] batches = [15] param_grid = dict(epochs=epochs, batch_size=batches, init=init) grid = GridSearchCV(estimator=model, param_grid=param_grid) grid_result = grid.fit(X_train, y_train) # summarize results print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] print(means, stds, params) y_pred = grid_result.predict(X_test) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) print('accuracy:', round(accuracy_score(y_test, y_pred), 2)) print('') print(confusion_matrix(y_test, y_pred)) ###Output /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/sequential.py:450: UserWarning: `model.predict_classes()` is deprecated and will be removed after 2021-01-01. Please use instead:* `np.argmax(model.predict(x), axis=-1)`, if your model does multi-class classification (e.g. if it uses a `softmax` last-layer activation).* `(model.predict(x) > 0.5).astype("int32")`, if your model does binary classification (e.g. if it uses a `sigmoid` last-layer activation). warnings.warn('`model.predict_classes()` is deprecated and ' ###Markdown OTHER MODEL ###Code tree_model = RandomForestClassifier() param_grid = {'criterion':['gini', 'entropy'], 'max_depth': np.arange(5,15,5), 'min_samples_leaf': np.arange(1,15,10), 'n_estimators': np.arange(5,105,10), 'ccp_alpha':[0.0, 0.1,0.5,0.9, 1]} grid_tree_model = GridSearchCV(tree_model, param_grid, cv = 10) grid_tree_model.fit(X_train.values, y_train.values.ravel()) print('Tuned Decision Tree: {}'.format(grid_tree_model.best_params_)) print('Tuned accuracy: {}'.format(grid_tree_model.best_score_)) y_pred = grid_tree_model.predict(X_test.values) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) print('accuracy:', round(accuracy_score(y_test, y_pred), 2)) print(confusion_matrix(y_test, y_pred)) ###Output [[ 36 2] [ 13 6502]] ###Markdown OTHER XGBOOST ###Code import xgboost as xgb model_xgb = xgb.XGBClassifier(objective = 'binary:logistic', n_estimators = 105, max_depth=75, seed = 10, reg_alpha=7) model_xgb.fit(X_train.values, y_train.values.ravel()) y_pred = model_xgb.predict(X_test.values) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) round(accuracy_score(y_test, y_pred), 2) print(confusion_matrix(y_test, y_pred)) ###Output [[ 38 0] [ 25 6490]] ###Markdown SKLEARN NN ###Code nn_class = MLPClassifier() param_grid = {'hidden_layer_sizes':[(8,8,8,8,8,8,8), (16,16,16,16,16,16)], 'activation': ['relu', 'logistic', 'tanh'], 'solver': ['lbfgs', 'adam'], 'max_iter': [800], 'learning_rate': ['constant', 'adaptive'] } grid_nn_class = GridSearchCV(nn_class, param_grid, cv = 10) grid_nn_class.fit(X_train.values, y_train.values.ravel()) print('Tuned Decision Tree: {}'.format(grid_nn_class.best_params_)) print('Tuned accuracy: {}'.format(grid_nn_class.best_score_)) y_pred = grid_nn_class.predict(X_test.values) print('Area debajo de la curva:', roc_auc_score(y_test, y_pred)) print('Recall:', recall_score(y_test, y_pred)) print('Precision:', precision_score(y_test, y_pred)) print('accuracy:', round(accuracy_score(y_test, y_pred), 2)) print(confusion_matrix(y_test, y_pred)) ###Output [[ 36 2] [ 13 6502]] ###Markdown VOTING ###Code client = 'someclient' model_classifier.save("model.h5") # keras joblib.dump(model_xgb, 'xgboost_tree' + client +'.pkl') #xgboost joblib.dump(grid_tree_model, 'sklearn_tree' + client +'.pkl') #sklearn joblib.dump(grid_nn_class, 'sklearn_nn'+ client +'.pkl') #sklearn _, _, filenames = next(walk('/content')) ###Output _____no_output_____
day11/lab/lab10-problem1-convolution.ipynb
###Markdown Vertical Edge Detection ###Code '''Create numpy array as image1 and display it. [[10 10 10 0 0 0] [10 10 10 0 0 0] [10 10 10 0 0 0] [10 10 10 0 0 0] [10 10 10 0 0 0] [10 10 10 0 0 0]] ''' image1 = np.array( [[10, 10, 10, 0, 0, 0]] * 6 ) display(image1) '''Create vertical_edge_kernel and display it: [[ 1 0 -1] [ 1 0 -1] [ 1 0 -1]] ''' vertical_edge_kernel = np.array([[1, 0, -1]] * 3) display(vertical_edge_kernel) # Call your convolution2d() and display the result. display(convolution2d(image1, vertical_edge_kernel)) '''Create a numpy array and display it: [[ 0 0 0 10 10 10] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10]] ''' image2 = np.array( [[0, 0, 0, 10, 10, 10]] * 6 ) display(image2) # Call your convolution2d() and display the result. display(convolution2d(image2, vertical_edge_kernel)) ###Output [[ 0 -30 -30 0] [ 0 -30 -30 0] [ 0 -30 -30 0] [ 0 -30 -30 0]] ###Markdown Horizontal Edge Detection ###Code '''Create horizontal_edge_kernel and display it: [[ 1 1 1] [ 0 0 0] [-1 -1 -1]] ''' horizontal_edge_kernel = np.rot90(np.array([[1, 0, -1]]*3), 3) horizontal_edge_kernel = np.array( [[1, 1, 1,], [0, 0, 0], [-1, -1, -1]] ) horizontal_edge_kernel = np.array([[1, 0, -1]] * 3).T display(horizontal_edge_kernel) '''Create an numpy array and display it: [[10 10 10 0 0 0] [10 10 10 0 0 0] [10 10 10 0 0 0] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10] [ 0 0 0 10 10 10]] ''' image3 = np.array( [[10, 10, 10, 0, 0, 0]] * 3 + [[0, 0, 0, 10, 10, 10]] * 3 ) display(image3) '''Value 0 means there is no edge detected. Value 30 means 3 bright pixels on top, 3 dark pixels on the bottom. Value -30 means 3 dark pixels on top, 3 bright pixels on the bottom. Value 10 is similar to 30 some part of the edge is not bright pixel on top and dark pixel on the bottom. Value -10 is similar to -30 some part of the edge is not dark pixel on top and bright pixel on the bottom. ''' # Call your convolution2d(), store it as image4, and display the result. image4 = convolution2d(image3, horizontal_edge_kernel) display(image4) # Apply vertical edge kernel on the previous feature maps to see the result. display(vertical_edge_kernel) display(convolution2d(image4, vertical_edge_kernel)) ###Output _____no_output_____
nlp/Ex_Files_NLP_Python_ML_EssT/Exercise Files/Ch03/03_02/End/03_02.ipynb
###Markdown Vectorizing Raw Data: Count Vectorization Count vectorization Creates a document-term matrix where the entry of each cell will be a count of the number of times that word occurred in that document. Read in text ###Code import pandas as pd import re import string import nltk pd.set_option('display.max_colwidth', 100) stopwords = nltk.corpus.stopwords.words('english') ps = nltk.PorterStemmer() # faster, but not as good data = pd.read_csv("SMSSpamCollection.tsv", sep='\t') data.columns = ['label', 'body_text'] data.shape ###Output _____no_output_____ ###Markdown Create function to remove punctuation, tokenize, remove stopwords, and stem ###Code def clean_text(text): text = "".join([word.lower() for word in text if word not in string.punctuation]) tokens = re.split('\W+', text) text = [ps.stem(word) for word in tokens if word not in stopwords] return text ###Output _____no_output_____ ###Markdown Apply CountVectorizer ###Code from sklearn.feature_extraction.text import CountVectorizer count_vect = CountVectorizer(analyzer=clean_text) X_counts = count_vect.fit_transform(data['body_text']) print(X_counts.shape) print(count_vect.get_feature_names()) ###Output (5567, 8104) ['', '0', '008704050406', '0089mi', '0121', '01223585236', '01223585334', '0125698789', '02', '020603', '0207', '02070836089', '02072069400', '02073162414', '02085076972', '020903', '021', '050703', '0578', '06', '060505', '061104', '07008009200', '07046744435', '07090201529', '07090298926', '07099833605', '071104', '07123456789', '0721072', '07732584351', '07734396839', '07742676969', '07753741225', '0776xxxxxxx', '07786200117', '077xxx', '078', '07801543489', '07808', '07808247860', '07808726822', '07815296484', '07821230901', '0784987', '0789xxxxxxx', '0794674629107880867867', '0796xxxxxx', '07973788240', '07xxxxxxxxx', '0800', '08000407165', '08000776320', '08000839402', '08000930705', '08000938767', '08001950382', '08002888812', '08002986030', '08002986906', '08002988890', '08006344447', '0808', '08081263000', '08081560665', '0825', '0844', '08448350055', '08448714184', '0845', '08450542832', '08452810071', '08452810073', '08452810075over18', '0870', '08700621170150p', '08701213186', '08701237397', '08701417012', '08701417012150p', '0870141701216', '087016248', '08701752560', '087018728737', '0870241182716', '08702490080', '08702840625', '08702840625comuk', '08704439680', '08704439680tsc', '08706091795', '0870737910216yr', '08707500020', '08707509020', '0870753331018', '08707808226', '08708034412', '08708800282', '08709222922', '08709501522', '0870k', '087104711148', '08712101358', '08712103738', '0871212025016', '08712300220', '087123002209am7pm', '08712317606', '08712400200', '08712400603', '08712402050', '08712402578', '08712402779', '08712402902', '08712402972', '08712404000', '08712405020', '08712405022', '08712460324', '08712460324nat', '08712466669', '0871277810710pmin', '0871277810810', '0871277810910pmin', '087143423992stop', '087147123779am7pm', '08714712379', '08714712388', '08714712394', '08714712412', '08714714011', '08714719523', '08715203028', '08715203649', '08715203652', '08715203656', '08715203677', '08715203685', '08715203694', '08715205273', '08715500022', '08715705022', '08717111821', '08717168528', '08717205546', '08717507382', '08717507711', '08717509990', '08717890890', '08717895698', '08717898035', '08718711108', '08718720201', '08718723815', '08718725756', '08718726270', '08718726270150gbpmtmsg18', '08718726970', '08718726971', '08718726978', '087187272008', '08718727868', '08718727870', '08718729755', '08718729758', '08718730555', '08718730666', '08718738001', '08718738002', '08718738034', '08719180219', '08719180248', '08719181259', '08719181503', '08719181513', '08719839835', '08719899217', '08719899229', '08719899230', '09041940223', '09050000301', '09050000332', '09050000460', '09050000555', '09050000878', '09050000928', '09050001295', '09050001808', '09050002311', '09050003091', '09050005321', '09050090044', '09050280520', '09053750005', '09056242159', '09057039994', '09058091854', '09058091870', '09058094454', '09058094455', '09058094507', '09058094565', '09058094583', '09058094594', '09058094597', '09058094599', '09058095107', '09058095201', '09058097189', '09058097218', '09058098002', '09058099801', '09061104276', '09061104283', '09061209465', '09061213237', '09061221061', '09061221066', '09061701444', '09061701461', '09061701851', '09061701939', '09061702893', '09061743386', '09061743806', '09061743810', '09061743811', '09061744553', '09061749602', '09061790121', '09061790125', '09061790126', '09063440451', '09063442151', '09063458130', '0906346330', '09064011000', '09064012103', '09064012160', '09064015307', '09064017295', '09064017305', '09064018838', '09064019014', '09064019788', '09065069120', '09065069154', '09065171142stopsms08', '09065171142stopsms08718727870150ppm', '09065174042', '09065394514', '09065394973', '09065989180', '09065989182', '09066350750', '09066358152', '09066358361', '09066361921', '09066362206', '09066362220', '09066362231', '09066364311', '09066364349', '09066364589', '09066368327', '09066368470', '09066368753', '09066380611', '09066382422', '09066612661', '09066649731from', '09066660100', '09071512432', '09071512433', '09071517866', '09077818151', '09090204448', '09090900040', '09094100151', '09094646631', '09094646899', '09095350301', '09096102316', '09099725823', '09099726395', '09099726429', '09099726481', '09099726553', '09111030116', '09111032124', '09701213186', '0anetwork', '1', '10', '100', '1000', '10000', '100000', '1000call', '100603', '100psm', '1010', '1013', '101mega', '1030', '10803', '10am', '10am7pm', '10am9pm', '10k', '10p', '10pmin', '10ppm', '10th', '11', '1120', '113', '1131', '11414', '1146', '1148', '116', '1172', '118pmsg', '11mth', '12', '120', '12000pe', '1205', '121', '1225', '123', '1230', '125', '1250', '125gift', '128', '12hour', '12hr', '12mth', '12price', '13', '130', '131004', '1327', '13404', '139', '140', '1405', '140ppm', '145', '1450', '146tf150p', '14thmarch', '150', '1500', '150ea', '150morefrmmob', '150msg', '150mtmsgrcvd18', '150p', '150pday', '150perweeksub', '150perwksub', '150pm', '150pmeg', '150pmin', '150pmmorefrommobile2bremovedmobypobox734ls27yf', '150pmsg', '150pmsgrcvd', '150pmsgrcvdhgsuite3422landsroww1j6hl', '150pmt', '150pmtmsg', '150pmtmsgrcvd18', '150ppermesssubscript', '150ppm', '150ppmpobox10183bhamb64x', '150ppmsg', '150prcvd', '150psm', '150ptext', '150ptone', '150pw', '150pwk', '150rcvd', '150week', '150wk', '151', '1526', '153', '15541', '15pmin', '16', '1680', '169', '16onli', '177', '18', '180', '181104', '1843', '186', '18onli', '18ptxt', '18yr', '195', '1956669', '1appledayno', '1childish', '1cup', '1da', '1er', '1hanuman', '1hi', '1hr', '1im', '1lemondayno', '1mcflyall', '1million', '1minmobsmor', '1minmobsmorelkpobox177hp51fl', '1minmoremobsemspobox45po139wa', '1month', '1pm', '1s', '1st', '1st4term', '1stchoicecouk', '1stone', '1tulsi', '1u', '1unbreak', '1winaweek', '1winawk', '1x150pwk', '1yf', '2', '20', '200', '2000', '20000', '2003', '2004', '2005', '2006', '2007', '2025050', '20f', '20m12aq', '20p', '20pmin', '21', '211104', '215', '21870000hi', '21m', '21st', '22', '220cm2', '23', '2309', '230ish', '24', '241', '241004', '247mp', '24hr', '24m', '24th', '25', '250', '250k', '255', '25f', '25p', '260305', '261004', '261104', '2667', '26th', '2703', '27603', '28', '2814032', '285', '28day', '28th', '28thfebtc', '290305', '29100', '29m', '2b', '2bajarangabali', '2bold', '2c', '2channel', '2day', '2daylov', '2docdpleas', '2end', '2exit', '2ez', '2getha', '2geva', '2go', '2godid', '2gthr', '2hook', '2hr', '2i', '2im', '2kbsubject', '2marrow', '2moro', '2morow', '2morro', '2morrow', '2morrowxxxx', '2mro', '2mrw', '2mwen', '2naughti', '2nd', '2nhite', '2night', '2nite', '2nitetel', '2optout', '2optoutd3wv', '2p', '2polic', '2px', '2rcv', '2stop', '2stoptx', '2stoptxt', '2u', '2u2', '2untam', '2watershd', '2waxsto', '2when', '2wk', '2wt', '2wu', '2year', '2yr', '3', '30', '300', '3000', '300603', '300603tcsbcm4235wc1n3xxcallcost150ppmmobilesvari', '300p', '3030', '30apr', '30pptxt', '30th', '31', '3100', '310303', '311004', '31pmsg150p', '32000', '3230', '32323', '326', '32f', '330', '3350', '3365', '350', '3510i', '35p', '3650', '36504', '3680', '3680offer', '373', '3750', '375max', '38', '391784', '399', '3aj', '3cover', '3d', '3day', '3db', '3g', '3gbp', '3hr', '3lion', '3lp', '3maruti', '3mile', '3min', '3mobil', '3optic', '3pound', '3qxj9', '3rd', '3sentiment', '3ss', '3u', '3unkempt', '3uz', '3wife', '3wk', '3x', '3xx', '4', '40', '400', '400minscal', '402', '4041', '40411', '40533', '40gb', '40mph', '415', '41685', '41782', '420', '42049', '4217', '42478', '42810', '430', '434', '44', '4403ldnw1a7rw18', '447797706009', '447801259231', '447per', '448712404000pleas', '449050000301', '449071512431', '449month', '45', '450', '450p', '450ppw', '450pw', '45239', '46', '47', '4712', '4742', '48', '4882', '48922', '49557', '4a', '4brekki', '4cook', '4d', '4eva', '4few', '4fil', '4get', '4give', '4got', '4goten', '4info', '4jx', '4lux', '4mi', '4mth', '4o', '4pavanaputra', '4press', '4rowdi', '4some1', '4tctxt', '4th', '4the', '4thnovbehind', '4txt120p', '4txtú120', '4u', '4ui', '4utxt', '4w', '4ward', '4wrd', '4year', '5', '50', '500', '5000', '500000', '505060', '50award', '50p', '515', '515pm', '5226', '5249', '526', '528', '530', '532', '54', '542', '545', '5903', '5digit', '5free', '5ful', '5garden', '5gentli', '5i', '5ish', '5k', '5min', '5ml', '5month', '5p', '5pm', '5sankatmochan', '5terror', '5th', '5wb', '5we', '5wkg', '5wq', '5year', '6', '600', '6031', '60400thousadi', '60p', '60pmin', '61200', '61610', '62220cncl', '6230', '62468', '62735', '630', '63mile', '645', '645pm', '650', '6669', '67441233', '68866', '69101', '69200', '69669', '69696', '69698', '69855', '6986618', '69876', '69888', '69888nyt', '69911', '69969', '69988', '6cruel', '6day', '6hl', '6housemaid', '6hr', '6ish', '6miss', '6month', '6pm', '6ramaduth', '6romant', '6th', '6time', '6wu', '6zf', '7', '700', '71', '725', '7250', '7250i', '730', '730ish', '730pm', '731', '74355', '750', '75000', '7548', '7634', '7684', '7732584351', '78', '786', '7876150ppm', '78pmin', '79', '7am', '7cfca1a', '7children', '7ish', '7mahav', '7oz', '7pm', '7romant', '7shi', '7th', '7w', '7z', '8', '80', '800', '8000930705', '80062', '8007', '80082', '80086', '80122300pwk', '80155', '80160', '80182', '8027', '80488', '80488biz', '80608', '8077', '80878', '81010', '81151', '81303', '81618', '816183', '82242', '82277', '82277unsub', '82324', '82468', '830', '83021', '83039', '83049', '83110', '83118', '83222', '83332pleas', '83338', '83355', '83370', '83383', '83435', '83600', '83738', '84', '84025', '84122', '84128', '84128custcar', '84199', '84484', '85', '850', '85023', '85069', '85222', '85233', '8552', '85555', '86021', '861', '863', '864233', '86688', '86888', '87021', '87066', '87070', '87077', '87121', '87131', '8714714', '87239', '87575', '8800', '88039', '88039skilgmetscs087147403231winawkage16', '88066', '88088', '88222', '8830', '88600', '88800', '8883', '88877', '88877free', '88888', '89034', '89070', '89080', '89105', '89123', '89545', '89555', '89693', '89938', '8am', '8attract', '8ball', '8hr', '8lb', '8lovabl', '8neighbour', '8o', '8pm', '8th', '8wp', '9', '900', '9061100010', '9153', '924', '92h', '930', '945', '946', '95pax', '96', '97n7qp', '98321561', '9996', '9ae', '9am', '9am11pm', '9decent', '9funni', '9ja', '9pm', '9t', '9th', '9yt', 'a21', 'a30', 'aa', 'aah', 'aaniy', 'aaooooright', 'aathilov', 'aathiwher', 'ab', 'abbey', 'abdomen', 'abeg', 'abelu', 'aberdeen', 'abi', 'abil', 'abiola', 'abj', 'abl', 'abnorm', 'abouta', 'abroad', 'absenc', 'absolut', 'abstract', 'abt', 'abta', 'aburo', 'abus', 'ac', 'academ', 'acc', 'accent', 'accentur', 'accept', 'access', 'accid', 'accident', 'accommod', 'accommodationvouch', 'accomod', 'accordin', 'accordingli', 'accordinglyor', 'account', 'accumul', 'ach', 'achanammarakheshqatar', 'achiev', 'acid', 'acknowledg', 'acl03530150pm', 'acnt', 'acoentry41', 'across', 'acsmsreward', 'act', 'actin', 'action', 'activ', 'activ8', 'actor', 'actual', 'acwicmb3cktz8r74', 'ad', 'adam', 'add', 'addamsfa', 'addi', 'addict', 'address', 'addressul', 'adewal', 'adi', 'adjust', 'admin', 'administr', 'admir', 'admiss', 'admit', 'admiti', 'ador', 'adp', 'adress', 'adrian', 'adrink', 'adsens', 'adult', 'advanc', 'adventur', 'advic', 'advis', 'advisor', 'aeronaut', 'aeroplan', 'afew', 'affair', 'affect', 'affection', 'affectionsamp', 'affidavit', 'afford', 'afghanistan', 'afraid', 'africa', 'african', 'aft', 'afternon', 'afternoon', 'afterward', 'aftr', 'ag', 'againcal', 'againlov', 'agalla', 'age', 'age16', 'age16150ppermesssubscript', 'age23', 'agenc', 'agent', 'agesr', 'agidhan', 'ago', 'agocusoon', 'agre', 'agreen', 'ah', 'aha', 'ahead', 'ahge', 'ahhh', 'ahhhhjust', 'ahmad', 'ahnow', 'ahold', 'ahsen', 'ahth', 'ahwhat', 'aid', 'aig', 'aight', 'aint', 'air', 'air1', 'airport', 'airtel', 'aiya', 'aiyah', 'aiyar', 'aiyo', 'ajith', 'ak', 'aka', 'akonlon', 'al', 'alaikkumprid', 'alaipayuth', 'albi', 'album', 'albumquit', 'alcohol', 'aldrin', 'alert', 'alertfrom', 'alett', 'alex', 'alfi', 'algarv', 'algebra', 'algorithm', 'ali', 'alian', 'alibi', 'aliv', 'alivebett', 'all', 'allah', 'allahmeet', 'allahrakhesh', 'allalo', 'allday', 'allo', 'allow', 'almost', 'alon', 'along', 'alot', 'alreadi', 'alreadysabarish', 'alright', 'alrightokay', 'alrit', 'alritehav', 'also', 'alsoor', 'alter', 'alternativehop', 'although', 'alwa', 'alway', 'alwi', 'am', 'amanda', 'amaz', 'ambiti', 'ambrithmaduraimet', 'american', 'ami', 'amigo', 'amk', 'ammaelif', 'ammo', 'amnow', 'among', 'amongst', 'amount', 'amp', 'amplikat', 'amrca', 'amrita', 'amt', 'amus', 'amx', 'an', 'ana', 'anal', 'analysi', 'anand', 'anderson', 'andor', 'andr', 'andrewsboy', 'andro', 'angel', 'angri', 'anim', 'anji', 'anjola', 'anna', 'anni', 'anniversari', 'annonc', 'announc', 'annoy', 'annoyin', 'anonym', 'anot', 'anoth', 'ansr', 'answer', 'answerin', 'answr', 'antelop', 'anthoni', 'anti', 'antibiot', 'anybodi', 'anyhow', 'anymor', 'anyon', 'anyplac', 'anyth', 'anythi', 'anythin', 'anythingtomorrow', 'anytim', 'anyway', 'anywher', 'aom', 'apart', 'ape', 'apeshit', 'aphex', 'apnt', 'apo', 'apolog', 'apologet', 'apologis', 'app', 'appar', 'appeal', 'appear', 'appendix', 'appi', 'applebe', 'applespairsal', 'appli', 'applic', 'apply2', 'appoint', 'appreci', 'approach', 'appropri', 'approv', 'approx', 'appt', 'april', 'aproach', 'apt', 'aptitud', 'aquariu', 'ar', 'arab', 'arabian', 'arcad', 'archiv', 'ard', 'ardé', 'area', 'arent', 'arestaur', 'aretak', 'argentina', 'argh', 'argu', 'argument', 'ari', 'aris', 'arithmet', 'arm', 'armand', 'armenia', 'arng', 'arngd', 'arnt', 'around', 'aroundn', 'arpraveesh', 'arr', 'arrang', 'arrest', 'arriv', 'arrow', 'arsen', 'art', 'arti', 'artist', 'arul', 'arun', 'asa', 'asap', 'asapok', 'asda', 'ash', 'ashley', 'ashwini', 'asia', 'asian', 'ask', 'askd', 'askin', 'aslamalaikkuminsha', 'asleep', 'aspect', 'ass', 'assess', 'asshol', 'assist', 'associ', 'assum', 'asther', 'asthma', 'astn', 'astoundingli', 'astrolog', 'astronom', 'asu', 'asusual1', 'ate', 'athlet', 'athom', 'atlanta', 'atlast', 'atleast', 'atm', 'atroci', 'attach', 'attack', 'attempt', 'atten', 'attend', 'attent', 'attitud', 'attract', 'attractioni', 'attribut', 'atyour', 'auction', 'auctionpunj', 'audiit', 'audit', 'audrey', 'audri', 'august', 'aunt', 'aunti', 'aust', 'australia', 'authoris', 'auto', 'autocorrect', 'av', 'ava', 'avail', 'availa', 'availablei', 'availablethey', 'avalarr', 'avatar', 'avbl', 'ave', 'aveng', 'avent', 'avenu', 'avin', 'avo', 'avoid', 'await', 'awak', 'award', 'away', 'awesom', 'awkward', 'aww', 'awww', 'ax', 'axi', 'ay', 'ayn', 'ayo', 'b', 'b4', 'b4190604', 'b4280703', 'b4u', 'ba', 'ba128nnfwfly150ppm', 'baaaaaaaab', 'baaaaab', 'babe', 'babeprobpop', 'babesozi', 'babi', 'babygoodby', 'babyhop', 'babyjontet', 'babysit', 'bac', 'back', 'backa', 'backdoor', 'backward', 'bad', 'badass', 'badli', 'badrith', 'bag', 'bagi', 'bahama', 'baig', 'bailiff', 'bak', 'bakra', 'bakrid', 'balanc', 'ball', 'baller', 'balloon', 'bam', 'bambl', 'ban', 'band', 'bandag', 'bang', 'bangb', 'bangbab', 'bani', 'bank', 'banneduk', 'banter', 'bao', 'bar', 'barbi', 'barcelona', 'bare', 'bari', 'barkley', 'barm', 'barolla', 'barrel', 'barri', 'base', 'bash', 'basic', 'basket', 'basketbal', 'basqihav', 'bat', 'batch', 'batchlor', 'bath', 'bathroom', 'batsman', 'batt', 'batteri', 'battl', 'bawl', 'bay', 'bb', 'bbc', 'bbdelux', 'bbdpooja', 'bbdtht', 'bblue', 'bbq', 'bc', 'bcaz', 'bck', 'bcm', 'bcm1896wc1n3xx', 'bcm4284', 'bcmsfwc1n3xx', 'bcoz', 'bcozi', 'bcum', 'bcz', 'bday', 'beach', 'bead', 'bear', 'beat', 'beauti', 'beautifulmay', 'bec', 'becau', 'becausethey', 'becom', 'becoz', 'becz', 'bed', 'bedbut', 'bedreal', 'bedrm', 'bedrm900', 'bedroom', 'bedroomlov', 'beeen', 'beehoon', 'beendrop', 'beer', 'beerag', 'beerr', 'befor', 'beforehand', 'beforew', 'beg', 'beggar', 'begin', 'begun', 'behalf', 'behav', 'behind', 'bein', 'believ', 'beliv', 'bell', 'bellearli', 'belli', 'belliger', 'belong', 'belov', 'belovd', 'belt', 'ben', 'bend', 'beneath', 'beneficiari', 'benefit', 'benni', 'bergkamp', 'besid', 'best', 'best1', 'bestcongrat', 'bestrpli', 'bet', 'beta', 'beth', 'betta', 'better', 'bettersn', 'beverag', 'bevieswaz', 'bewar', 'beyond', 'bf', 'bff', 'bfore', 'bhaskar', 'bhayandar', 'bian', 'biatch', 'bid', 'big', 'bigger', 'biggest', 'bike', 'bill', 'billi', 'billion', 'bilo', 'bimbo', 'bin', 'biola', 'bird', 'birla', 'biro', 'birth', 'birthdat', 'birthday', 'bishan', 'bit', 'bitch', 'bite', 'bk', 'black', 'blackand', 'blackberri', 'blackim', 'blacko', 'blah', 'blake', 'blame', 'blank', 'blanket', 'blastin', 'bleak', 'bleh', 'bless', 'blessget', 'blimey', 'blind', 'block', 'blog', 'bloke', 'blond', 'bloo', 'blood', 'bloodblood', 'bloodi', 'bloodsend', 'bloomberg', 'bloombergcom', 'blow', 'blown', 'blu', 'blue', 'bluetooth', 'bluetoothhdset', 'blueu', 'bluff', 'blur', 'bluray', 'bmw', 'board', 'boat', 'boatin', 'bob', 'bodi', 'boggi', 'bognor', 'bold', 'bold2', 'bollox', 'boltblu', 'bomb', 'bone', 'bong', 'bonu', 'boo', 'boob', 'book', 'bookedth', 'bookmark', 'bookshelf', 'boooo', 'boost', 'booti', 'bootydeli', 'borderlin', 'bore', 'borin', 'born', 'bornpleas', 'borrow', 'boss', 'boston', 'bot', 'bother', 'bottl', 'bottom', 'bought', 'boundari', 'bout', 'boutxx', 'bowa', 'bowl', 'box', 'box1146', 'box139', 'box177', 'box245c2150pm', 'box326', 'box334', 'box334sk38ch', 'box385', 'box39822', 'box403', 'box420', 'box42wr29c', 'box434sk38wp150ppm18', 'box61m60', 'box95qu', 'box97n7qp', 'boy', 'boyf', 'boyfriend', 'boyi', 'boytoy', 'bpo', 'bra', 'brah', 'brain', 'braindanc', 'braini', 'brainless', 'brand', 'brandi', 'brat', 'brave', 'bray', 'brb', 'brdget', 'bread', 'breadstick', 'break', 'breaker', 'breakfast', 'breakin', 'breath', 'breathe1', 'breez', 'breezi', 'bribe', 'bridg', 'bridgwat', 'brief', 'bright', 'brighten', 'brilliant', 'brilliant1thingi', 'brilliantli', 'brin', 'bring', 'brisk', 'brison', 'bristol', 'british', 'britney', 'bro', 'broad', 'broadband', 'broke', 'broken', 'brolli', 'broth', 'brotha', 'brother', 'brought', 'browni', 'brows', 'browser', 'browsin', 'bruce', 'brum', 'bruv', 'bslvyl', 'bsn', 'bsnl', 'bstfrnd', 'bt', 'bthere', 'bthmm', 'btnation', 'btnationalr', 'btooth', 'btw', 'btwn', 'bu', 'buck', 'bud', 'buddi', 'budget', 'buen', 'buff', 'buffet', 'buffi', 'bugi', 'build', 'built', 'bulb', 'bull', 'bullshit', 'bun', 'bunch', 'bundl', 'bunker', 'burden', 'burger', 'burgundi', 'burial', 'burn', 'burnt', 'burrito', 'bus822656166382', 'buse', 'busetop', 'busi', 'busti', 'busyi', 'but', 'butt', 'butther', 'button', 'buy', 'buyer', 'buz', 'buzi', 'buzz', 'buzzzz', 'bw', 'bx', 'bx420', 'bx420ip45w', 'bx526', 'byatch', 'bye', 'c', 'c52', 'cab', 'cabin', 'cabl', 'cafe', 'cage', 'cake', 'caken', 'cal', 'calcul', 'cali', 'calicut', 'california', 'call', 'call09050000327', 'call2optout4qf2', 'call2optout674', 'call2optoutf4q', 'call2optouthf8', 'call2optoutj', 'call2optoutj5q', 'call2optoutlf56', 'call2optoutn9dx', 'call2optoutyhl', 'callback', 'callcost', 'callcoz', 'calld', 'calldrov', 'caller', 'callertun', 'callfreefon', 'callin', 'callingforgot', 'callon', 'calls150ppm', 'callsmessagesmiss', 'callurg', 'calm', 'cam', 'camcord', 'came', 'camera', 'cameravideo', 'camp', 'campu', 'camri', 'canada', 'canal', 'canari', 'cancel', 'cancer', 'candont', 'canlov', 'cannam', 'cannot', 'cannt', 'cant', 'cantdo', 'canteen', 'cap', 'capac', 'capit', 'cappuccino', 'captain', 'car', 'card', 'cardiff', 'cardin', 'care', 'careabout', 'career', 'careinsha', 'careless', 'carent', 'careswt', 'careumma', 'carewhoev', 'carli', 'carlin', 'carlo', 'carlosl', 'carolin', 'carolina', 'carpark', 'carri', 'carryin', 'carso', 'carton', 'cartoon', 'case', 'cash', 'cashbal', 'cashbincouk', 'cashin', 'cashto', 'cast', 'castor', 'casualti', 'cat', 'catch', 'categori', 'caught', 'caus', 'cave', 'caveboy', 'cbe', 'cc', 'cc100pmin', 'ccna', 'cd', 'cdgt', 'cedar', 'ceil', 'celeb', 'celeb4', 'celebr', 'cell', 'censu', 'center', 'centr', 'centuri', 'cer', 'cereal', 'ceri', 'certainli', 'certif', 'cha', 'chachi', 'chad', 'chain', 'challeng', 'champ', 'champlaxig', 'champney', 'chanc', 'chang', 'channel', 'chap', 'chapel', 'chapter', 'charact', 'charg', 'charged150pmsg2', 'chariti', 'charl', 'charli', 'charm', 'chart', 'chase', 'chastiti', 'chat', 'chat80155', 'chatim', 'chatlin', 'chatter', 'cheap', 'cheaper', 'cheat', 'chechi', 'check', 'checkbox', 'checkin', 'checkmat', 'checkup', 'cheek', 'cheer', 'cheeri', 'chees', 'cheesi', 'cheeto', 'chef', 'chennai', 'chennaibecaus', 'chennaii', 'chequ', 'cherish', 'cherthalain', 'chess', 'chest', 'chex', 'cheyyamoand', 'chez', 'chg', 'chic', 'chick', 'chicken', 'chief', 'chik', 'chikku', 'chikkuali', 'chikkub', 'chikkudb', 'chikkugo', 'chikkuil', 'chikkuk', 'chikkusimpl', 'chikkuwat', 'child', 'childish', 'childporn', 'children', 'chile', 'chill', 'chillaxin', 'chillin', 'china', 'chinatown', 'chinchilla', 'chines', 'chinki', 'chiong', 'chip', 'chitchat', 'chk', 'chloe', 'chocol', 'choic', 'choos', 'chop', 'chord', 'chore', 'chosen', 'chrgd50p', 'christ', 'christian', 'christma', 'christmasmerri', 'christmassi', 'chuck', 'chuckin', 'church', 'ciao', 'cin', 'cine', 'cinema', 'citi', 'citizen', 'citylink', 'cl', 'cla', 'claim', 'claimcod', 'clair', 'clarif', 'clarifi', 'clash', 'class', 'classic', 'classmat', 'claypot', 'cld', 'clean', 'clear', 'clearer', 'clearli', 'clever', 'click', 'cliff', 'clip', 'clock', 'clos1', 'close', 'closebi', 'closedinclud', 'closer', 'closingdate040902', 'cloth', 'cloud', 'clover', 'club', 'club4', 'club4mobilescom', 'clue', 'cm', 'cme', 'cmon', 'cn', 'cnl', 'cnn', 'co', 'coach', 'coast', 'coat', 'coax', 'cocacola', 'coccoon', 'cochin', 'cock', 'cocksuck', 'coco', 'code', 'code4xx26', 'coffe', 'coher', 'coimbator', 'coin', 'coincid', 'colani', 'cold', 'coldheard', 'colin', 'collag', 'collaps', 'colleagu', 'collect', 'colleg', 'collegexx', 'color', 'colour', 'colourredtextcolourtxtstar', 'com', 'comb', 'combin', 'come', 'comedi', 'comedyc', 'comei', 'cometil', 'comfey', 'comfort', 'comin', 'comingdown', 'comingtmorow', 'command', 'comment', 'commerci', 'commit', 'common', 'commun', 'comp', 'compani', 'companion', 'compar', 'compass', 'compens', 'competit', 'complac', 'complain', 'complaint', 'complementari', 'complet', 'complex', 'compliment', 'complimentari', 'compofstuff', 'comprehens', 'compromis', 'compulsori', 'comput', 'computerless', 'comuk220cm2', 'con', 'conact', 'concentr', 'concern', 'concert', 'conclus', 'condit', 'conditionand', 'conduct', 'conect', 'confer', 'confid', 'configur', 'confirm', 'confirmd', 'confirmdeni', 'conform', 'confus', 'congrat', 'congratul', 'connect', 'consensu', 'consent', 'conserv', 'consid', 'consist', 'consol', 'constant', 'constantli', 'contact', 'contain', 'content', 'contin', 'continu', 'contract', 'contribut', 'control', 'conveni', 'convers', 'convert', 'convey', 'convinc', 'convincingjust', 'cook', 'cooki', 'cool', 'coolmob', 'coop', 'cooper', 'cop', 'cope', 'copi', 'corect', 'cornwal', 'corpor', 'corrct', 'correct', 'correctionor', 'correctli', 'corrupt', 'corvett', 'cosign', 'cost', 'costa', 'costum', 'couch', 'cougarpen', 'cough', 'could', 'coulda', 'couldnt', 'count', 'countin', 'countinlot', 'countri', 'coupl', 'coupla', 'courag', 'cours', 'court', 'courtroom', 'cousin', 'cover', 'coveragd', 'coz', 'cozi', 'cozsomtim', 'cp', 'cr', 'cr01327bt', 'cr9', 'crab', 'crack', 'craigslist', 'cram', 'cramp', 'crap', 'crash', 'crave', 'crazi', 'craziest', 'crazyin', 'cream', 'creat', 'creativ', 'cred', 'credit', 'creep', 'creepi', 'cresubi', 'cri', 'cribb', 'cricket', 'crickit', 'crisi', 'crisisspk', 'cro1327', 'crore', 'cross', 'crowd', 'croydon', 'crucial', 'crucifi', 'cruis', 'cruisin', 'crush', 'cs', 'csh11', 'cst', 'cstore', 'ctagg', 'ctargg', 'cthen', 'ctla', 'cttargg', 'ctter', 'cttergg', 'cu', 'cuck', 'cud', 'cuddl', 'cudnt', 'culdnt', 'cultur', 'cum', 'cumin', 'cup', 'cupboard', 'cuppa', 'curfew', 'curiou', 'current', 'curri', 'curtsey', 'cust', 'custcar', 'custcare08718720201', 'custom', 'customercar', 'customersqueriesnetvisionukcom', 'cut', 'cute', 'cutefrnd', 'cutest', 'cuti', 'cutter', 'cuz', 'cw25wx', 'cya', 'cyclist', 'cyst', 'da', 'daal', 'daalway', 'dabbl', 'dabook', 'dad', 'daddi', 'dado', 'dagood', 'dahe', 'dahow', 'dai', 'daili', 'dajst', 'dammit', 'damn', 'dan', 'danalla', 'danc', 'dancc', 'dancin', 'dane', 'dang', 'danger', 'dao', 'dapleas', 'dare', 'dark', 'darker', 'darkest', 'darl', 'darlin', 'darlinim', 'darren', 'dartboard', 'dasara', 'dat', 'data', 'date', 'datebox1282essexcm61xn', 'datingi', 'datoday', 'datz', 'daurgent', 'dave', 'dawhat', 'dawher', 'dawn', 'day', 'day2', 'day2find', 'dayexcept', 'dayha', 'daysh', 'daysso', 'dayswil', 'daysèn', 'daytim', 'dayu', 'daywith', 'dd', 'de', 'dead', 'deadwel', 'deal', 'dealer', 'dealfarm', 'deam', 'dear', 'dear1', 'dearer', 'deari', 'dearli', 'dearlov', 'dearm', 'dearrakhesh', 'dearregret', 'dearshal', 'dearslp', 'deartak', 'death', 'debat', 'dec', 'decad', 'decemb', 'decid', 'decim', 'decis', 'deck', 'declar', 'decor', 'dedic', 'deduct', 'deep', 'deepak', 'deepest', 'deer', 'deeraj', 'def', 'defeat', 'defer', 'definit', 'definitli', 'defo', 'degre', 'dehydr', 'del', 'delay', 'delet', 'delhi', 'delici', 'deliv', 'deliveredtomorrow', 'deliveri', 'deltomorrow', 'delux', 'dem', 'demand', 'den', 'dena', 'dengra', 'deni', 'dent', 'dental', 'dentist', 'depart', 'depend', 'deposit', 'depress', 'dept', 'der', 'derek', 'derp', 'describ', 'descript', 'desert', 'deserv', 'design', 'desir', 'desk', 'despar', 'desper', 'despit', 'dessert', 'destin', 'destini', 'detail', 'detailsi', 'determin', 'detroit', 'deu', 'develop', 'devic', 'devil', 'devour', 'dey', 'deyhop', 'deyi', 'dha', 'dhina', 'dhoni', 'dhort', 'di', 'dial', 'diall', 'dialogu', 'diamond', 'diaper', 'dice', 'dick', 'dict', 'dictionari', 'diddi', 'didnt', 'didntgiv', 'didt', 'die', 'diesel', 'diet', 'diff', 'differ', 'differb', 'difficult', 'difficulti', 'dificult', 'digi', 'digit', 'digniti', 'dileepthank', 'dime', 'dimens', 'din', 'dine', 'dinero', 'ding', 'dinner', 'dinnermsg', 'dino', 'dint', 'dip', 'dippeditinadew', 'direct', 'directli', 'director', 'dirt', 'dirti', 'dirtiest', 'disagre', 'disappear', 'disappoint', 'disast', 'disastr', 'disc', 'disclos', 'disconnect', 'discount', 'discreet', 'discuss', 'diseas', 'diskyou', 'dislik', 'dismay', 'dismissi', 'display', 'distanc', 'distract', 'disturb', 'disturbancemight', 'ditto', 'divert', 'divis', 'divorc', 'diwali', 'dizzamn', 'dizze', 'dl', 'dled', 'dlf', 'dload', 'dnt', 'dob', 'dobbi', 'doc', 'dock', 'doctor', 'document', 'dodda', 'dodgey', 'doesdiscountshitinnit', 'doesnt', 'dog', 'dogbreath', 'dogg', 'doggi', 'doggin', 'dogwood', 'doin', 'doinat', 'doinghow', 'doingwhat', 'doinnearli', 'dointerest', 'doke', 'dokey', 'doll', 'dollar', 'dolld', 'dom', 'domain', 'donat', 'done', 'donew', 'donno', 'dont', 'dont4get2text', 'dontcha', 'dontignor', 'dontpleas', 'donyt', 'doom', 'door', 'dorm', 'dormitori', 'dorothykiefercom', 'dose', 'dosometh', 'dot', 'doubl', 'doublefaggot', 'doublemin', 'doubletxt', 'doubt', 'doug', 'dough', 'down', 'download', 'downon', 'downstem', 'dozen', 'dp', 'dr', 'dracula', 'drama', 'dramastorm', 'dramat', 'drastic', 'draw', 'drawpleas', 'dread', 'dream', 'dreamlov', 'dreamsmuah', 'dreamstak', 'dreamsu', 'dreamz', 'dress', 'dresser', 'dri', 'drink', 'drinkin', 'drinkpa', 'drive', 'driver', 'drivin', 'drizzl', 'drm', 'drmstake', 'drop', 'drove', 'drpd', 'drug', 'drugdeal', 'drum', 'drunk', 'drunkard', 'drunken', 'drvgsto', 'dryer', 'dsnt', 'dt', 'dual', 'dub', 'dubsack', 'duchess', 'duck', 'dude', 'dudett', 'due', 'duffer', 'dull', 'dumb', 'dump', 'dun', 'dungere', 'dunno', 'duo', 'durban', 'durham', 'dusk', 'dust', 'duvet', 'dvd', 'dvg', 'dwn', 'dysentri', 'e', 'e14', 'eachoth', 'ear', 'earli', 'earlier', 'earlierw', 'earliest', 'earn', 'earth', 'earthsofa', 'easi', 'easier', 'easiest', 'easili', 'east', 'eastend', 'easter', 'eat', 'eaten', 'eatin', 'ebay', 'ec2a', 'echo', 'eckankar', 'ecstaci', 'ecstasi', 'edg', 'edha', 'edison', 'edit', 'edrunk', 'educ', 'edukkukaye', 'edward', 'ee', 'eek', 'eeri', 'eerulli', 'effect', 'effici', 'efreefon', 'eg', 'eg23f', 'eg23g', 'egbon', 'egg', 'eggpotato', 'eggspert', 'ego', 'eh', 'eh74rr', 'eight', 'eighth', 'eightish', 'eir', 'either', 'el', 'ela', 'elabor', 'elain', 'elama', 'elaya', 'eldest', 'elect', 'electr', 'eleph', 'eleven', 'elliot', 'ello', 'els', 'elsewher', 'elvi', 'em', 'email', 'embarass', 'embarrass', 'embassi', 'emerg', 'emigr', 'emili', 'emot', 'employ', 'employe', 'empti', 'en', 'enam', 'enc', 'end', 'endless', 'endof', 'endow', 'enemi', 'energi', 'eng', 'engag', 'engalnd', 'engin', 'england', 'english', 'enjoy', 'enjoyin', 'enketa', 'enna', 'ennal', 'enough', 'enter', 'entertain', 'entey', 'entir', 'entitl', 'entrepreneur', 'entri', 'entrop', 'enufcredeit', 'enuff', 'envelop', 'envi', 'epi', 'epsilon', 'equal', 'er', 'ericson', 'ericsson', 'erm', 'erot', 'err', 'error', 'ertini', 'eruku', 'erupt', 'erutupalam', 'eryth', 'esaplanad', 'escal', 'escap', 'ese', 'eshxxxxxxxxxxx', 'especi', 'espel', 'esplanad', 'essay', 'essenti', 'establish', 'eta', 'etc', 'etern', 'ethnic', 'ethreat', 'ettan', 'euro', 'euro2004', 'eurodisinc', 'europ', 'evalu', 'evapor', 'eve', 'eveb', 'evei', 'even', 'event', 'eventu', 'ever', 'everi', 'every1', 'everybodi', 'everyboy', 'everyday', 'everyon', 'everyso', 'everyth', 'everythin', 'everytim', 'everywher', 'evey', 'evict', 'evil', 'evn', 'evng', 'evo', 'evon', 'evr', 'evrey', 'evri', 'evry1', 'evrydi', 'ew', 'ex', 'exact', 'exactli', 'exam', 'excel', 'except', 'exchang', 'excit', 'excus', 'exe', 'execut', 'exercis', 'exet', 'exhaust', 'exhibit', 'exist', 'exmpel', 'exorc', 'exorcist', 'exp', 'expect', 'expens', 'experi', 'experiencehttpwwwvouch4mecometlpdiningasp', 'expert', 'expir', 'expiredso', 'expiri', 'explain', 'explicit', 'explicitli', 'explos', 'expos', 'express', 'ext', 'extermin', 'extra', 'extract', 'extrem', 'exwif', 'ey', 'eye', 'eyeddont', 'f', 'fa', 'fab', 'faber', 'face', 'faceasssssholeee', 'facebook', 'facil', 'fact', 'factori', 'fade', 'faggi', 'faglord', 'fail', 'failur', 'faint', 'fair', 'faith', 'faitheven', 'fake', 'fakemi', 'fakey', 'fal', 'falconerf', 'fall', 'fallen', 'famamu', 'famili', 'familiar', 'familymay', 'famou', 'fan', 'fanci', 'fantasi', 'fantast', 'far', 'farm', 'farrel', 'fart', 'fassyol', 'fast', 'faster', 'fastest', 'fastpl', 'fat', 'fate', 'father', 'fathima', 'fatti', 'fault', 'faultal', 'faultf', 'fav', 'fave', 'favor', 'favorit', 'favour', 'favourit', 'fb', 'fear', 'featheri', 'featur', 'feb', 'febapril', 'februari', 'fedex', 'fee', 'feed', 'feel', 'feelin', 'feelingood', 'feelingwav', 'feet', 'fell', 'fellow', 'felt', 'femal', 'feng', 'festiv', 'fetch', 'fever', 'fffff', 'ffffffffff', 'ffffuuuuuuu', 'fgkslpo', 'fgkslpopw', 'fidalf', 'field', 'fieldof', 'fiendmak', 'fifa', 'fifteen', 'fifth', 'fifti', 'fight', 'fightng', 'figur', 'file', 'fill', 'film', 'filth', 'filthi', 'filthyguy', 'final', 'finalis', 'financ', 'financi', 'find', 'fine', 'fineabsolutli', 'fineinshah', 'finest', 'finewhen', 'finger', 'finish', 'finishd', 'fink', 'finn', 'fire', 'firefox', 'fireplac', 'firesar', 'firmwar', 'firsg', 'first', 'fish', 'fishhead', 'fishrman', 'fit', 'fite', 'five', 'fix', 'fixd', 'fixedlin', 'fizz', 'flag', 'flake', 'flaki', 'flame', 'flash', 'flat', 'flatter', 'flavour', 'flea', 'fletcher', 'flew', 'fli', 'flight', 'flim', 'flip', 'flippin', 'flirt', 'float', 'flood', 'floor', 'floppi', 'florida', 'flow', 'flower', 'fluid', 'flung', 'flurri', 'flute', 'flyim', 'flyng', 'fml', 'fmyou', 'fne', 'fo', 'fold', 'foley', 'folk', 'follow', 'followin', 'fond', 'fondli', 'fone', 'fonin', 'food', 'fool', 'foot', 'footbal', 'footblcrckt', 'footi', 'footprint', 'forc', 'foreg', 'foreign', 'forev', 'forevr', 'forfeit', 'forget', 'forgiv', 'forgiven', 'forgot', 'forgotten', 'forgt', 'form', 'formal', 'formallypl', 'format', 'formclark', 'formsdon', 'forth', 'fortun', 'forum', 'forward', 'found', 'foundurself', 'four', 'fourth', 'foward', 'fowler', 'fox', 'fp', 'fr', 'fraction', 'fran', 'frankgood', 'franki', 'franxx', 'franyxxxxx', 'fraud', 'freak', 'freaki', 'fredericksburg', 'free', 'free2day', 'freedom', 'freeentri', 'freefon', 'freek', 'freeli', 'freemessag', 'freemsg', 'freemsgfav', 'freemsgfeelin', 'freenokia', 'freephon', 'freerington', 'freeringtonerepli', 'freesend', 'freez', 'freind', 'fren', 'french', 'frequent', 'fresh', 'fresher', 'fret', 'fri', 'friday', 'fridayhop', 'fridg', 'friend', 'friendofafriend', 'friendsar', 'friendship', 'friendshipmotherfatherteacherschildren', 'fring', 'frm', 'frmcloud', 'frnd', 'frndship', 'frndshp', 'frndsship', 'frndz', 'frnt', 'fro', 'frog', 'frogaxel', 'fromm', 'fromwrk', 'front', 'frontiervil', 'frosti', 'fruit', 'frwd', 'ft', 'fuck', 'fuckin', 'fuckinniceselfishdeviousbitchanywayi', 'fudg', 'fuell', 'fujitsu', 'ful', 'full', 'fullonsmscom', 'fumbl', 'fun', 'function', 'fund', 'fundament', 'funer', 'funk', 'funki', 'funni', 'furnitur', 'fusion', 'futur', 'fuuuuck', 'fwiw', 'fyi', 'g', 'g2', 'g696ga', 'ga', 'gail', 'gailxx', 'gain', 'gal', 'galcan', 'galileo', 'galno', 'galsu', 'gam', 'game', 'gamestar', 'gandhipuram', 'ganesh', 'gang', 'gap', 'garag', 'garbag', 'garden', 'gari', 'garment', 'gastroenter', 'gate', 'gaug', 'gautham', 'gave', 'gay', 'gayd', 'gayl', 'gaytextbuddycom', 'gaze', 'gb', 'gbp', 'gbp150week', 'gbp450week', 'gbp5month', 'gbpsm', 'gbpweek', 'gd', 'gdeve', 'gdnow', 'gdthe', 'ge', 'gee', 'geeee', 'geeeee', 'geelat', 'gei', 'gek1510', 'gender', 'gene', 'gener', 'geniu', 'gent', 'gentl', 'gentleman', 'gentli', 'genu', 'genuin', 'geoenvironment', 'georg', 'gep', 'ger', 'germani', 'get', 'get4an18th', 'gete', 'geti', 'getsleep', 'getstop', 'gettin', 'getzedcouk', 'gf', 'ghodbandar', 'ghost', 'gibb', 'gibe', 'gift', 'giggl', 'gigolo', 'gimm', 'gimmi', 'gin', 'girl', 'girld', 'girlfrnd', 'girli', 'gist', 'giv', 'give', 'given', 'givit', 'glad', 'gland', 'glasgow', 'glass', 'glo', 'global', 'glori', 'gloriou', 'gloucesterroad', 'gmgngegn', 'gmgngegnt', 'gmw', 'gn', 'gnarl', 'go', 'go2', 'go2sri', 'goa', 'goal', 'goalsteam', 'gobi', 'god', 'godi', 'godnot', 'godtaken', 'godyou', 'goe', 'goggl', 'goigng', 'goin', 'goin2b', 'gokila', 'gold', 'golddigg', 'golden', 'goldvik', 'golf', 'gon', 'gona', 'gone', 'goneu', 'gong', 'gonna', 'gonnamissu', 'good', 'gooddhanush', 'goodenviron', 'goodeven', 'goodfin', 'goodfriend', 'goodi', 'goodmat', 'goodmorn', 'goodmorningmi', 'goodnight', 'goodnit', 'goodno', 'goodnoon', 'goodo', 'goodtimeoli', 'goodwhen', 'googl', 'gopalettan', 'gorgeou', 'gosh', 'gossip', 'gossx', 'got', 'gota', 'gotani', 'gotmarri', 'goto', 'gotta', 'gotten', 'gotto', 'gover', 'govtinstituit', 'gowait', 'gower', 'gpr', 'gpu', 'gr8', 'gr8fun', 'gr8prize', 'grab', 'grace', 'graduat', 'grahmbel', 'gram', 'gran', 'grand', 'grandfath', 'grandma', 'granit', 'graphic', 'grasp', 'grate', 'grave', 'gravel', 'gravi', 'graviti', 'gray', 'graze', 'gre', 'great', 'greatbhaji', 'greatby', 'greatest', 'greatli', 'greec', 'green', 'greeni', 'greet', 'grief', 'grin', 'grinder', 'grinul', 'grl', 'grocer', 'groov', 'groovi', 'ground', 'groundamla', 'group', 'grow', 'grown', 'grownup', 'growrandom', 'grr', 'grumbl', 'grumpi', 'gs', 'gsex', 'gsoh', 'gt', 'gua', 'guai', 'guarante', 'gucci', 'gud', 'gudk', 'gudni8', 'gudnit', 'gudnitetcpractic', 'gudnyt', 'guess', 'guessin', 'guid', 'guidanc', 'guild', 'guilti', 'guitar', 'gumbi', 'guoyang', 'gurl', 'gut', 'guy', 'gv', 'gving', 'gwr', 'gym', 'gymnast', 'gyna', 'gyno', 'h', 'ha', 'habbahw', 'habit', 'hack', 'hadnt', 'hadya', 'haf', 'haha', 'hahahaus', 'hahatak', 'hai', 'hail', 'hair', 'haircut', 'hairdress', 'haiyoh', 'haiz', 'half', 'half8th', 'hall', 'halla', 'hallaq', 'halloween', 'ham', 'hamper', 'hamster', 'hand', 'handl', 'handset', 'handsom', 'hang', 'hanger', 'hangin', 'hank', 'hannaford', 'hanumanji', 'happen', 'happend', 'happenin', 'happi', 'happier', 'happiest', 'happili', 'hard', 'hardcor', 'harder', 'hardest', 'hardli', 'hari', 'harish', 'harlem', 'harri', 'hasbroin', 'hasnt', 'hassl', 'hat', 'hate', 'haughaighgtujhyguj', 'haul', 'haunt', 'hav', 'hav2hear', 'hava', 'havbeen', 'havebeen', 'havent', 'haventcn', 'havin', 'havnt', 'hcl', 'hdd', 'he', 'head', 'headach', 'headin', 'headset', 'headstart', 'heal', 'healer', 'healthi', 'heap', 'hear', 'heard', 'hearin', 'heart', 'heartgn', 'heartheart', 'heartsnot', 'heat', 'heater', 'heaven', 'heavi', 'heavili', 'hectic', 'hee', 'heehe', 'hehe', 'height', 'held', 'helen', 'hell', 'hella', 'hello', 'hellodrivby0quit', 'hellogorg', 'hellohow', 'helloooo', 'helloy', 'help', 'help08700469649', 'help08700621170150p', 'help08712400602450p', 'help08714742804', 'help08718728876', 'helplin', 'heltiniiyo', 'hen', 'henc', 'henri', 'hep', 'herepl', 'hererememb', 'herethanksi', 'heri', 'herlov', 'hermi', 'hero', 'heroi', 'heron', 'hersh', 'herwho', 'herwil', 'hesit', 'hex', 'hey', 'heygreat', 'hgsuite3422land', 'hgsuite3422landsroww1j6hl', 'hhahhaahahah', 'hi', 'hict', 'hidden', 'hide', 'hidid', 'high', 'highest', 'hii', 'hilariousalso', 'hill', 'hillsborough', 'himso', 'himthen', 'hint', 'hip', 'hiphop', 'hire', 'hisher', 'histori', 'hit', 'hitechn', 'hitler', 'hitman', 'hitteranyway', 'hittng', 'hiwhat', 'hiya', 'hl', 'hlday', 'hlp', 'hm', 'hme', 'hmm', 'hmmbad', 'hmmm', 'hmmmbut', 'hmmmhow', 'hmmmi', 'hmmmkbut', 'hmmmm', 'hmmmstill', 'hmph', 'hmv', 'hmv1', 'ho', 'hockey', 'hogidhechinnu', 'hogli', 'hogolo', 'hol', 'holbi', 'hold', 'holder', 'hole', 'holi', 'holiday', 'holidayso', 'holla', 'hollalat', 'home', 'homebut', 'homecheck', 'homeleft', 'homelov', 'homeown', 'homewot', 'hon', 'honest', 'honesti', 'honestli', 'honey', 'honeybe', 'honeydid', 'honeymoon', 'honi', 'hont', 'hoo', 'hooch', 'hoodi', 'hook', 'hoop', 'hop', 'hope', 'hopeafternoon', 'hopeso', 'hopeu', 'hor', 'horni', 'horniest', 'horo', 'horribl', 'hors', 'hospit', 'hostbas', 'hostel', 'hostil', 'hot', 'hotel', 'hotmix', 'hottest', 'hour', 'hourish', 'hous', 'housemaid', 'housew', 'housework', 'how', 'howard', 'howda', 'howdi', 'howev', 'howr', 'howu', 'howv', 'howz', 'hp', 'hp20', 'hppnss', 'hr', 'hrishi', 'hsbc', 'html', 'httpalto18coukwavewaveaspo44345', 'httpcareer', 'httpdoit', 'httpgotbabescouk', 'httpimg', 'httptm', 'httpwap', 'httpwwwbubbletextcom', 'httpwwwetlpcoukexpressoff', 'httpwwwetlpcoukreward', 'httpwwwgr8prizescom', 'httpwwwurawinnercom', 'httpwwwwtlpcouktext', 'hu', 'huai', 'hubbi', 'hudgi', 'hug', 'huge', 'hugh', 'huh', 'hui', 'huim', 'hum', 'human', 'hun', 'hundr', 'hundredh', 'hungov', 'hungri', 'hunk', 'hunlov', 'hunni', 'hunnyhop', 'hunnyjust', 'hunnywot', 'hunonbu', 'hunt', 'hurri', 'hurrican', 'hurt', 'husband', 'hussey', 'hustl', 'hut', 'hv', 'hvae', 'hw', 'hwd', 'hwkeep', 'hyde', 'hypertens', 'hypotheticalhuagauahahuagahyuhagga', 'ia', 'iam', 'ibh', 'ibhltd', 'ibiza', 'ibm', 'ibn', 'ibor', 'ibuprofen', 'ic', 'iccha', 'ice', 'icic', 'icicibankcom', 'icki', 'icon', 'id', 'idc', 'idconvey', 'idea', 'ideal', 'identif', 'identifi', 'idiot', 'idk', 'idp', 'idu', 'ie', 'iff', 'ifink', 'ifwhenhow', 'ig11', 'ignor', 'ijust', 'ikea', 'ikno', 'iknow', 'il', 'ileav', 'ill', 'illspeak', 'ilol', 'im', 'ima', 'imag', 'imagin', 'imaginationmi', 'imat', 'imf', 'imin', 'imma', 'immedi', 'immunis', 'imp', 'impati', 'implic', 'import', 'importantli', 'impos', 'imposs', 'impost', 'impress', 'improv', 'imprtant', 'in2', 'inc', 'inch', 'incid', 'inclu', 'includ', 'inclus', 'incomm', 'inconsider', 'inconveni', 'incorrect', 'increas', 'incred', 'increment', 'ind', 'inde', 'independ', 'india', 'indian', 'indianpl', 'indic', 'individu', 'individualtim', 'indyarockscom', 'inev', 'infact', 'infect', 'infern', 'influx', 'info', 'inforingtonekingcouk', 'inform', 'informedrgdsrakheshkerala', 'infotxt82228couk', 'infovipclub4u', 'infowww100percentrealcom', 'infra', 'infront', 'ing', 'ingredi', 'initi', 'ink', 'inlud', 'inmind', 'inner', 'inning', 'innoc', 'innu', 'inour', 'inperialmus', 'inperson', 'inr', 'insect', 'insha', 'inshah', 'insid', 'inspect', 'inst', 'instal', 'instant', 'instantli', 'instead', 'instruct', 'insur', 'intellig', 'intend', 'intent', 'interest', 'interflora', 'interfu', 'intern', 'internet', 'internetservic', 'interview', 'interviw', 'intha', 'intim', 'intrepid', 'intro', 'intrud', 'invad', 'invent', 'invest', 'investig', 'invit', 'invnt', 'invoic', 'involv', 'iouri', 'ip', 'ip4', 'ipad', 'ipaditan', 'iphon', 'ipod', 'iq', 'iraq', 'ireneer', 'iriv', 'iron', 'irrit', 'irulina', 'isaiahd', 'isar', 'iscom', 'ish', 'ishtamayoohappi', 'island', 'islov', 'isnt', 'issu', 'isvimport', 'italian', 'itboth', 'itc', 'itcould', 'item', 'iter', 'ithi', 'ithink', 'iti', 'itjust', 'itleav', 'itlet', 'itll', 'itmail', 'itmay', 'itna', 'itnow', 'itor', 'itplspl', 'itried2tel', 'itsnot', 'ittb', 'itu', 'itwhichturnedinto', 'itxt', 'itxx', 'itz', 'ivatt', 'ive', 'iwana', 'iwasmarinethat', 'iz', 'izzit', 'j', 'j89', 'jabo', 'jack', 'jacket', 'jackpot', 'jackson', 'jacuzzi', 'jada', 'jade', 'jaklin', 'jam', 'jame', 'jamster', 'jamstercouk', 'jamsterget', 'jamz', 'jan', 'janarig', 'jane', 'janinexx', 'januari', 'janx', 'jap', 'japanes', 'jason', 'java', 'jay', 'jaya', 'jaykwon', 'jaz', 'jazz', 'jb', 'jd', 'je', 'jealou', 'jean', 'jeetey', 'jeevithathil', 'jelli', 'jen', 'jenn', 'jenni', 'jenxxx', 'jeremiah', 'jeri', 'jerk', 'jerri', 'jersey', 'jess', 'jesu', 'jet', 'jetton', 'jewelri', 'jez', 'ji', 'jia', 'jiayin', 'jide', 'jiu', 'jjc', 'jo', 'joanna', 'job', 'jobyet', 'jock', 'jod', 'jog', 'john', 'join', 'joinedhop', 'joinedso', 'joke', 'joker', 'jokethet', 'jokin', 'jolli', 'jolt', 'jon', 'jone', 'jontin', 'jordan', 'jordantxt', 'jorgeshock', 'jot', 'journey', 'joy', 'jp', 'js', 'jsco', 'jst', 'jstfrnd', 'jsut', 'ju', 'juan', 'judgementali', 'juici', 'jule', 'juli', 'juliana', 'julianaland', 'jump', 'jumper', 'june', 'jungl', 'junna', 'justbeen', 'justifi', 'justthought', 'juswok', 'juz', 'k', 'k52', 'k61', 'k718', 'kaaj', 'kadeem', 'kafter', 'kaiez', 'kaila', 'kaitlyn', 'kalaachutaarama', 'kalainar', 'kalisidar', 'kall', 'kalli', 'kalstiyathen', 'kama', 'kanagu', 'kane', 'kanji', 'kano', 'kanoanyway', 'kanoil', 'kanowhr', 'kappa', 'karaok', 'karnan', 'karo', 'kate', 'katexxx', 'kath', 'kavalan', 'kay', 'kaypoh', 'kb', 'kbut', 'kdo', 'ke', 'keen', 'keep', 'keepintouch', 'kegger', 'keluviri', 'ken', 'keng', 'kent', 'kept', 'kerala', 'keralacircl', 'keri', 'kettoda', 'key', 'keypad', 'keyword', 'kfc', 'kg', 'kgive', 'kgood', 'khelat', 'ki', 'kicchu', 'kick', 'kickbox', 'kickoff', 'kid', 'kidz', 'kill', 'kilo', 'kim', 'kind', 'kinda', 'kindli', 'king', 'kingdom', 'kintu', 'kiosk', 'kip', 'kisi', 'kiss', 'kit', 'kitti', 'kittum', 'kkadvanc', 'kkani', 'kkapo', 'kkare', 'kkcongratul', 'kkfrom', 'kkgoodstudi', 'kkhow', 'kkim', 'kkit', 'kkthi', 'kkwhat', 'kkwhen', 'kkwhere', 'kkwhi', 'kkyesterday', 'kl341', 'knacker', 'knee', 'knew', 'knicker', 'knock', 'know', 'knowh', 'known', 'knowneway', 'knowthi', 'knowwait', 'knowyetund', 'knw', 'ko', 'kochi', 'kodstini', 'kodthini', 'konw', 'korch', 'korean', 'korli', 'kort', 'kote', 'kothi', 'kr', 'ksri', 'kthen', 'ktv', 'ku', 'kuch', 'kudiyarasu', 'kusruthi', 'kvb', 'kwish', 'kyou', 'kz', 'l', 'l8', 'l8er', 'l8r', 'l8tr', 'la', 'la1', 'la3', 'la32wu', 'lab', 'labor', 'lac', 'lack', 'lacsthat', 'lacsther', 'laden', 'ladi', 'ladiesu', 'lag', 'lage', 'lager', 'laid', 'laidwant', 'lakh', 'lambda', 'lambu', 'lamp', 'lancast', 'land', 'landlin', 'landlineonli', 'landmark', 'lane', 'langport', 'languag', 'lanka', 'lanr', 'lap', 'lapdanc', 'laptop', 'lar', 'lara', 'lareadi', 'larg', 'largest', 'lark', 'lasagna', 'last', 'lastest', 'late', 'latebut', 'latei', 'latelyxxx', 'later', 'lateso', 'latest', 'latr', 'laugh', 'laundri', 'lauri', 'lautech', 'lavend', 'law', 'laxinorf', 'lay', 'layin', 'lazi', 'lccltd', 'ldn', 'ldnw15h', 'le', 'lead', 'leadership', 'leafcutt', 'leafdayno', 'leagu', 'leannewhat', 'learn', 'least', 'least5tim', 'leastwhich', 'leav', 'lect', 'lectur', 'left', 'leftov', 'leg', 'legal', 'legitimat', 'leh', 'lehhaha', 'lei', 'lekdog', 'lemm', 'length', 'lennon', 'leo', 'leona', 'leonardo', 'less', 'lesser', 'lesson', 'let', 'letter', 'leu', 'level', 'li', 'liao', 'liaoso', 'liaotoo', 'lib', 'libertin', 'librari', 'lick', 'lido', 'lie', 'life', 'lifeand', 'lifebook', 'lifei', 'lifethi', 'lifetim', 'lifey', 'lifpartnr', 'lift', 'light', 'lighter', 'lightli', 'lik', 'like', 'likeyour', 'likingb', 'lil', 'lili', 'lim', 'limit', 'limp', 'lindsay', 'line', 'linear', 'linerent', 'liney', 'lingeri', 'lingo', 'link', 'linux', 'lion', 'lionm', 'lionp', 'lip', 'lipo', 'liquor', 'list', 'listen', 'listening2th', 'listn', 'lit', 'liter', 'litr', 'littl', 'live', 'liver', 'liverpool', 'lk', 'lkpobox177hp51fl', 'llspeak', 'lm', 'lmao', 'lmaonic', 'lnli', 'lo', 'load', 'loan', 'lobbi', 'local', 'locat', 'locaxx', 'lock', 'lodg', 'log', 'login', 'logo', 'logoff', 'logon', 'logop', 'logosmusicnew', 'loko', 'lol', 'lolnic', 'lololo', 'londn', 'london', 'lone', 'loneli', 'long', 'longer', 'lonlin', 'loo', 'look', 'lookatm', 'lookin', 'lool', 'loooooool', 'looovvv', 'loos', 'loosu', 'lor', 'lord', 'lorgoin', 'lorw', 'lose', 'loser', 'loss', 'lost', 'lot', 'loti', 'lotr', 'lotsli', 'lotsof', 'lotta', 'lotto', 'lotwil', 'lotz', 'lou', 'loud', 'loung', 'lousi', 'lov', 'lovabl', 'love', 'loveabl', 'lovejen', 'lovem', 'lover', 'loverakhesh', 'loverboy', 'lovin', 'lovingli', 'lovli', 'low', 'lowcost', 'lower', 'loxahatche', 'loyal', 'loyalti', 'lrg', 'ls1', 'ls15hb', 'ls278bb', 'lst', 'lt', 'lt3', 'ltd', 'ltdecimalgt', 'ltdhelpdesk', 'ltemailgt', 'ltgt', 'lttimegt', 'lttr', 'lturlgt', 'lubli', 'luci', 'luck', 'luck2', 'lucki', 'luckili', 'lucozad', 'lucozadecoukwrc', 'lucyxx', 'luk', 'lul', 'lunch', 'lunchtim', 'lunchyou', 'lunsford', 'lush', 'luton', 'luv', 'luvd', 'luvnight', 'lux', 'luxuri', 'lv', 'lvblefrnd', 'lyf', 'lyfu', 'lyk', 'lyric', 'lyricalladie21f', 'm100', 'm221bp', 'm227xi', 'm26', 'm263uz', 'm39m51', 'm6', 'm8', 'm95', 'ma', 'maaaan', 'maangalyam', 'maat', 'mac', 'macedonia', 'macha', 'machan', 'machiani', 'machin', 'macho', 'mack', 'macleran', 'mad', 'mad1', 'mad2', 'madam', 'madamregret', 'made', 'madodu', 'madok', 'madstini', 'madthen', 'mag', 'maga', 'magazin', 'maggi', 'magic', 'magicalsongsblogspotcom', 'mah', 'mahal', 'mahfuuzmean', 'mail', 'mailbox', 'maili', 'main', 'maintain', 'major', 'make', 'maki', 'makin', 'malaria', 'malarki', 'male', 'mall', 'mallika', 'man', 'manag', 'manchest', 'manda', 'mandan', 'mandara', 'mandi', 'maneesha', 'maneg', 'mango', 'mani', 'maniac', 'manki', 'manual', 'map', 'mapquest', 'maraikara', 'marandratha', 'march', 'maretar', 'margaret', 'margin', 'mari', 'mark', 'market', 'marley', 'marrgeremembr', 'marri', 'marriag', 'marriageprogram', 'marsm', 'marvel', 'mask', 'massag', 'massagetiepo', 'massiv', 'master', 'masteriast', 'mat', 'match', 'mate', 'math', 'mathemat', 'mathew', 'matra', 'matric', 'matrix3', 'matter', 'mattermsg', 'matthew', 'matur', 'max', 'max10min', 'max6month', 'maxim', 'maximum', 'may', 'mayb', 'mb', 'mc', 'mca', 'mcat', 'mcr', 'meal', 'mean', 'meaning', 'meaningless', 'meant', 'meanwhil', 'mear', 'measur', 'meat', 'meatbal', 'mecaus', 'med', 'medic', 'medicin', 'medont', 'mee', 'meet', 'meetgreet', 'meetin', 'meetitz', 'mega', 'meh', 'mei', 'meim', 'meiv', 'mel', 'melik', 'mell', 'melnit', 'melodi', 'melt', 'member', 'membership', 'membershiptak', 'memor', 'memori', 'men', 'mene', 'mental', 'mention', 'mentionedtomorrow', 'mentor', 'menu', 'meok', 'meow', 'meowd', 'mere', 'merememberin', 'meremov', 'merri', 'mesag', 'mesh', 'meso', 'mess', 'messag', 'messageit', 'messageno', 'messagepandi', 'messagesim', 'messagesom', 'messagestext', 'messagethank', 'messeng', 'messi', 'met', 'method', 'meummifyingby', 'mf', 'mfl', 'mg', 'mi', 'mia', 'michael', 'mid', 'middl', 'midnight', 'might', 'miiiiiiissssssssss', 'mila', 'mile', 'mileag', 'milk', 'milkdayno', 'miller', 'million', 'miltazindgi', 'min', 'mina', 'minapn', 'mind', 'mindi', 'mindsetbeliev', 'mine', 'mineal', 'minecraft', 'mini', 'minimum', 'minnaminungint', 'minor', 'mins100txtmth', 'minstand', 'minstext', 'mint', 'minu', 'minut', 'miracl', 'mirror', 'misbehav', 'mise', 'miser', 'misfit', 'misplac', 'miss', 'misscal', 'missi', 'missin', 'mission', 'missionari', 'misss', 'misstak', 'missunderstd', 'mist', 'mistak', 'mistakeu', 'misundrstud', 'mite', 'mitsak', 'mittelschmertz', 'miwa', 'mix', 'mj', 'mjzgroup', 'mk17', 'mk45', 'ml', 'mm', 'mmm', 'mmmm', 'mmmmm', 'mmmmmm', 'mmmmmmm', 'mmsto', 'mn', 'mnth', 'mo', 'moan', 'mob', 'mobcudb', 'mobi', 'mobil', 'mobilesdirect', 'mobilesvari', 'mobileupd8', 'mobno', 'mobsicom', 'mobstorequiz10ppm', 'mode', 'model', 'modelsoni', 'modl', 'modul', 'mofo', 'moji', 'mojibiola', 'mokka', 'molestedsomeon', 'mom', 'moment', 'mon', 'monday', 'mondaynxt', 'moneeppolum', 'money', 'moneya', 'moneyi', 'monkeespeopl', 'monkey', 'monkeyaround', 'monl8rsx', 'mono', 'monoc', 'monster', 'month', 'monthli', 'monthlysubscription50pmsg', 'monthnot', 'mood', 'moon', 'moral', 'moraldont', 'moralon', 'morn', 'mornin', 'morningtak', 'morphin', 'morrow', 'moseley', 'mostli', 'mother', 'motherfuck', 'motherinlaw', 'motiv', 'motor', 'motorola', 'mountain', 'mous', 'mouth', 'move', 'movi', 'moviewat', 'moyep', 'mp3', 'mquiz', 'mr', 'mre', 'mrng', 'mrt', 'mrur', 'ms', 'msg', 'msg150p', 'msging', 'msgrcvd18', 'msgs150p', 'msgsd', 'msgsometext', 'msgsubscript', 'msgticketkioskvalid', 'msgwe', 'msn', 'mssuman', 'mt', 'mtalk', 'mth', 'mtnl', 'mu', 'much', 'muchand', 'muchi', 'muchimped', 'muchxxlov', 'mudyadhu', 'mufti', 'muhommad', 'muht', 'multi', 'multimedia', 'multipli', 'mum', 'mumbai', 'mumha', 'mummi', 'mumtaz', 'mundh', 'munster', 'murali', 'murder', 'mush', 'mushi', 'music', 'must', 'musta', 'musthu', 'mustprovid', 'mutai', 'mutat', 'muz', 'mw', 'mwah', 'my', 'mycallsu', 'mylif', 'mymobi', 'mypar', 'myspac', 'mysteri', 'mytonecomenjoy', 'n', 'n8', 'na', 'naal', 'nacho', 'nag', 'nagar', 'nah', 'nahi', 'nail', 'nake', 'nalla', 'nalli', 'name', 'name1', 'name2', 'namemi', 'nammanna', 'nan', 'nang', 'nanni', 'nap', 'narcot', 'nasdaq', 'naseeb', 'nasti', 'nat', 'natali', 'natalja', 'nation', 'nationwid', 'nattil', 'natuit', 'natur', 'natwest', 'naughti', 'nauseou', 'nav', 'navig', 'nb', 'nbme', 'nd', 'ne', 'near', 'nearbi', 'nearer', 'nearli', 'neces', 'necess', 'necessari', 'necessarili', 'neck', 'necklac', 'ned', 'need', 'needa', 'neededsalari', 'needi', 'needl', 'neekunna', 'neft', 'neg', 'neglect', 'neglet', 'neighbor', 'neither', 'nelson', 'neo69', 'nervou', 'neshanthtel', 'net', 'netcollex', 'netflix', 'neth', 'netno', 'network', 'neva', 'nevamindw', 'never', 'nevil', 'nevr', 'new', 'neway', 'newest', 'newport', 'newquaysend', 'news', 'newsbi', 'newscast', 'newshyp', 'newspap', 'next', 'ngage', 'nh', 'ni8', 'ni8swt', 'nic', 'nice', 'nicenicehow', 'nichol', 'nick', 'nickey', 'nicki', 'nig', 'nigeria', 'nigh', 'night', 'nighter', 'nightnight', 'nightnobodi', 'nightsexcel', 'nightsw', 'nightswt', 'nigpun', 'nigro', 'nike', 'nikiyu4net', 'nimbomson', 'nimya', 'nimyapl', 'ninish', 'nino', 'nipost', 'nit', 'nite', 'nite2', 'nitro', 'nitw', 'nitz', 'njan', 'nmde', 'no', 'no1', 'no165', 'no434', 'no440', 'no762', 'no81151', 'no83355', 'no910', 'nob', 'nobl', 'nobodi', 'nobut', 'noe', 'nofew', 'nohe', 'noi', 'noic', 'nois', 'noisi', 'noit', 'nojst', 'nok', 'nokia', 'nokia150p', 'nokia6600', 'nokia6650', 'nolin', 'nolistened2th', 'non', 'noncomitt', 'none', 'nonenowher', 'nonetheless', 'nookii', 'noon', 'nooooooo', 'noooooooo', 'nope', 'nora', 'norcorp', 'nordstrom', 'norm', 'norm150pton', 'normal', 'north', 'northampton', 'nose', 'nosh', 'nosi', 'note', 'notebook', 'noth', 'nothi', 'nothin', 'notic', 'notif', 'notifi', 'notixiqu', 'nottel', 'nottingham', 'notxtcouk', 'noun', 'novelti', 'novemb', 'now1', 'now4t', 'nowaday', 'nowadayslot', 'nowcan', 'nowi', 'nownyt', 'nowonion', 'noworriesloanscom', 'nowrepli', 'nowsavamobmemb', 'nowsend', 'nowski', 'nowstil', 'nowtc', 'nowus', 'nr31', 'nri', 'nt', 'nte', 'ntswt', 'ntt', 'ntwk', 'nu', 'nuclear', 'nudist', 'nuerologist', 'num', 'number', 'numberpl', 'numberrespect', 'numberso', 'nurs', 'nurseri', 'nurungu', 'nusstu', 'nuther', 'nutter', 'nver', 'nvm', 'nvq', 'nw', 'nxt', 'ny', 'nyc', 'nydc', 'nyt', 'nytec2a3lpmsg150p', 'nytho', 'nyusa', 'nz', 'nìte', 'o2', 'o2coukgam', 'o2fwd', 'oath', 'obedi', 'obes', 'obey', 'object', 'oblising', 'oblivi', 'obvious', 'occas', 'occupi', 'occur', 'oceand', 'oclock', 'octob', 'odalebeku', 'odi', 'ofcours', 'offc', 'offcampu', 'offdam', 'offens', 'offer', 'offerth', 'offic', 'officestil', 'officethenampet', 'officeunderstand', 'officewhat', 'offici', 'offlin', 'ofic', 'oficegot', 'ofsi', 'often', 'oga', 'ogunrind', 'oh', 'oha', 'ohi', 'oi', 'oic', 'oil', 'oja', 'ok', 'okay', 'okcom', 'okday', 'okden', 'okey', 'oki', 'okmail', 'okok', 'okor', 'oktak', 'okthenwhat', 'okvarunnathu', 'ola', 'olag', 'olav', 'olayiwola', 'old', 'ollubut', 'olol', 'olowoyey', 'olymp', 'omg', 'omw', 'onam', 'oncal', 'ondu', 'one', 'onedg', 'oneta', 'oni', 'onionr', 'onit', 'onlin', 'onlinewhi', 'onluy', 'only1mor', 'onlybettr', 'onlydon', 'onlyfound', 'onto', 'onum', 'onward', 'onword', 'ooh', 'oooh', 'oooooh', 'ooooooh', 'oop', 'open', 'openin', 'oper', 'opinion', 'opp', 'opponent', 'opportun', 'opportunityal', 'opportunitypl', 'oppos', 'opposit', 'opt', 'optimist', 'optin', 'option', 'optout', 'or', 'or2optouthv9d', 'or2stoptxt', 'oral', 'orang', 'orangei', 'orc', 'orchard', 'order', 'ore', 'oredi', 'oreo', 'organ', 'organis', 'orh', 'orig', 'origin', 'orno', 'ortxt', 'oru', 'os', 'oscar', 'oso', 'otbox', 'other', 'otherwis', 'othr', 'otsid', 'ou', 'ouch', 'ourback', 'oursso', 'out', 'outag', 'outbid', 'outdoor', 'outfit', 'outfor', 'outgo', 'outhav', 'outif', 'outl8rjust', 'outrag', 'outreach', 'outsid', 'outsomewher', 'outstand', 'outta', 'ovarian', 'overa', 'overdid', 'overdos', 'overemphasiseor', 'overh', 'overtim', 'ovr', 'ovul', 'ovulatewhen', 'ow', 'owe', 'owl', 'own', 'ownyouv', 'owo', 'oxygen', 'oyea', 'oyster', 'oz', 'p', 'pa', 'pace', 'pack', 'packag', 'packalso', 'padhegm', 'page', 'pai', 'paid', 'pain', 'painhop', 'painit', 'paint', 'pale', 'palm', 'pan', 'panalambut', 'panason', 'pandi', 'panic', 'panick', 'panren', 'pansi', 'pant', 'panther', 'panti', 'pap', 'papa', 'paper', 'paperwork', 'paracetamol', 'parachut', 'parad', 'paragon', 'paragraph', 'paranoid', 'parantella', 'parchi', 'parco', 'parent', 'parentnot', 'parentsi', 'pari', 'parisfre', 'parish', 'park', 'park6ph', 'parkin', 'part', 'parti', 'particip', 'particular', 'particularli', 'partner', 'partnership', 'paru', 'pase', 'pass', 'passabl', 'passion', 'passport', 'passthey', 'password', 'passwordsatmsm', 'past', 'pataistha', 'patent', 'path', 'pathaya', 'patient', 'patrick', 'pattern', 'patti', 'paul', 'paus', 'pay', 'payasam', 'payback', 'paye', 'payed2day', 'payment', 'payoh', 'paypal', 'pc', 'pdatenow', 'peac', 'peach', 'peak', 'pear', 'pee', 'peep', 'pehl', 'pei', 'pen', 'penc', 'pend', 'pendent', 'pendingi', 'peni', 'penni', 'peopl', 'per', 'percent', 'percentag', 'perf', 'perfect', 'perform', 'perfum', 'perhap', 'peril', 'period', 'peripher', 'perman', 'permiss', 'perpetu', 'persev', 'persian', 'person', 'person2di', 'personmeet', 'perspect', 'perumbavoor', 'peski', 'pest', 'pete', 'petei', 'petexxx', 'petey', 'peteynoi', 'petrol', 'petrolr', 'pg', 'ph', 'ph08700435505150p', 'ph08704050406', 'pharmaci', 'phase', 'phd', 'phew', 'phil', 'philosoph', 'philosophi', 'phne', 'phoenix', 'phone', 'phone750', 'phonebook', 'phoni', 'photo', 'photoshop', 'php', 'phrase', 'physic', 'piah', 'pic', 'pick', 'pickl', 'picsfree1', 'pictur', 'pictxt', 'pie', 'piec', 'pierr', 'pig', 'piggi', 'pilat', 'pile', 'pillow', 'pimpl', 'pimpleseven', 'pin', 'pink', 'pinku', 'pint', 'pisc', 'piss', 'piti', 'pix', 'pixel', 'pizza', 'pl', 'place', 'placement', 'placeno', 'plaid', 'plan', 'plane', 'planet', 'planeti', 'planettalkinstantcom', 'plate', 'platt', 'play', 'player', 'playerwhi', 'playi', 'playin', 'playng', 'plaza', 'pleas', 'pleasant', 'pleassssssseeeee', 'pleasur', 'plenti', 'plm', 'plough', 'plsi', 'plu', 'plum', 'plumber', 'plumbingremix', 'plural', 'plyr', 'plz', 'pm', 'pmt', 'po', 'po19', 'pobox', 'pobox1', 'pobox11414tcrw1', 'pobox12n146tf15', 'pobox12n146tf150p', 'pobox202', 'pobox334', 'pobox36504w45wq', 'pobox365o4w45wq', 'pobox45w2tg150p', 'pobox75ldns7', 'pobox84', 'poboxox36504w45wq', 'pocay', 'poci', 'pock', 'pocket', 'pocketbabecouk', 'pod', 'poem', 'poet', 'point', 'poke', 'poker', 'pokkiri', 'pole', 'poli', 'polic', 'politician', 'polo', 'poly200p', 'poly3', 'polyc', 'polyh', 'polyph', 'polyphon', 'polytruepixringtonesgam', 'pongal', 'pongaldo', 'ponnungal', 'poo', 'pooki', 'pool', 'poop', 'poor', 'poorli', 'poortiyagi', 'pop', 'popcorn', 'popcornjust', 'porn', 'porridg', 'port', 'portal', 'porteg', 'portion', 'pose', 'posh', 'posibl', 'posit', 'possess', 'possibl', 'possiblehop', 'post', 'postal', 'postcard', 'postcod', 'posterod', 'postpon', 'potato', 'potenti', 'potter', 'pouch', 'pound', 'pour', 'pout', 'power', 'poyyarikaturkolathupalayamunjalur', 'ppl', 'pple', 'pple700', 'ppm', 'ppm150', 'ppt150x3normal', 'prabha', 'prabhaim', 'prabu', 'pract', 'practic', 'practicum', 'practis', 'prais', 'prakasam', 'prakasamanu', 'prakesh', 'prap', 'prasad', 'prasanth', 'prashanthettan', 'pray', 'prayer', 'prayingwil', 'prayr', 'pre', 'prebook', 'predict', 'prefer', 'prem', 'premaricakindli', 'premier', 'premium', 'prepaid', 'prepar', 'prepay', 'prepon', 'preschoolcoordin', 'prescrib', 'prescripiton', 'prescript', 'presenc', 'present', 'presid', 'presley', 'presnt', 'press', 'pressi', 'pressur', 'prestig', 'pretend', 'pretsorginta', 'pretsovru', 'pretti', 'prevent', 'preview', 'previou', 'previous', 'prey', 'price', 'priceso', 'pride', 'priest', 'prin', 'princ', 'princegn', 'princess', 'print', 'printer', 'prior', 'prioriti', 'priscilla', 'privaci', 'privat', 'prix', 'priya', 'prize', 'prizeawait', 'prizeswith', 'prizeto', 'pro', 'prob', 'probabl', 'problem', 'problemat', 'problembut', 'problemfre', 'problemi', 'problm', 'problum', 'probthat', 'process', 'processexcel', 'processit', 'processnetwork', 'prod', 'product', 'prof', 'profession', 'professor', 'profil', 'profit', 'program', 'progress', 'project', 'prolli', 'prometazin', 'promin', 'promis', 'promo', 'promot', 'prompt', 'promptli', 'prone', 'proof', 'proov', 'prop', 'proper', 'properli', 'properti', 'propos', 'propsd', 'prospect', 'protect', 'prove', 'proverb', 'provid', 'provinc', 'proze', 'prsn', 'ps', 'ps3', 'pshewmiss', 'psp', 'psxtra', 'psychiatrist', 'psychic', 'psychologist', 'pt2', 'ptbo', 'pthi', 'pub', 'pubcaf', 'public', 'publish', 'pudunga', 'pull', 'pump', 'punch', 'punish', 'punto', 'puppi', 'pura', 'purchas', 'pure', 'puriti', 'purpleu', 'purpos', 'purs', 'push', 'pushbutton', 'pussi', 'put', 'puttin', 'puzzel', 'puzzl', 'px3748', 'q', 'qatar', 'qatarrakhesh', 'qbank', 'qet', 'qi', 'qing', 'qlynnbv', 'qualiti', 'quarter', 'que', 'queen', 'queri', 'question', 'questionstd', 'quick', 'quickli', 'quiet', 'quit', 'quiteamuz', 'quiz', 'quizclub', 'quizwin', 'quizz', 'quot', 'r', 'r836', 'ra', 'racal', 'race', 'radiat', 'radio', 'rael', 'raglan', 'rahul', 'raiden', 'railway', 'rain', 'rais', 'raj', 'raja', 'rajini', 'rajipl', 'rajitha', 'rajnik', 'rakhesh', 'raksha', 'ralli', 'ralph', 'ramen', 'ran', 'randi', 'random', 'randomli', 'randomlli', 'rang', 'ranjith', 'ranju', 'rape', 'rat', 'rate', 'ratetc', 'rather', 'ratio', 'raviyog', 'rawr', 'ray', 'rayan', 'rayman', 'rcbbattl', 'rcd', 'rct', 'rcv', 'rcvd', 'rd', 'rdi', 'reach', 'react', 'reaction', 'read', 'reader', 'readi', 'readyal', 'real', 'real1', 'reali', 'realis', 'realiti', 'realiz', 'realli', 'reallyne', 'reappli', 'rearrang', 'reason', 'reassur', 'rebel', 'reboot', 'rebtel', 'rec', 'recd', 'recdthirtyeight', 'receipt', 'receiv', 'receivea', 'recent', 'recept', 'recess', 'recharg', 'rechargerakhesh', 'reciev', 'reckon', 'recognis', 'record', 'recount', 'recoveri', 'recpt', 'recreat', 'recycl', 'red', 'redeem', 'redim', 'redr', 'reduc', 'ree', 'ref', 'ref9280114', 'ref9307622', 'refer', 'referin', 'reffer', 'refil', 'reflect', 'reflex', 'reformat', 'refresh', 'refund', 'refundedthi', 'refus', 'reg', 'regard', 'regist', 'registr', 'regret', 'regular', 'reject', 'rel', 'relat', 'relationshipit', 'relax', 'releas', 'reliant', 'reliev', 'religi', 'reloc', 'reltnship', 'rem', 'remain', 'remb', 'rememb', 'rememberi', 'remembr', 'remet', 'remind', 'remov', 'rencontr', 'renew', 'rent', 'rental', 'rentl', 'repair', 'repeat', 'repent', 'replac', 'repli', 'replyb', 'replys150', 'report', 'reppurcuss', 'repres', 'republ', 'request', 'requir', 'reschedul', 'research', 'resend', 'resent', 'reserv', 'reset', 'resid', 'resiz', 'reslov', 'resolut', 'resolv', 'resort', 'respect', 'responcewhat', 'respond', 'respons', 'rest', 'restaur', 'restock', 'restrict', 'restuwud', 'restwish', 'resub', 'resubmit', 'result', 'resum', 'retard', 'retir', 'retriev', 'return', 'reunion', 'reveal', 'revers', 'review', 'revis', 'reward', 'rg21', 'rgd', 'rgent', 'rhode', 'rhythm', 'rice', 'rich', 'riddanc', 'ridden', 'ride', 'right', 'rightio', 'rightli', 'riley', 'rimac', 'ring', 'ringsreturn', 'rington', 'ringtonefrom', 'ringtoneget', 'ringtonek', 'rinu', 'rip', 'rise', 'risk', 'rite', 'ritten', 'river', 'ro', 'road', 'roadsrvx', 'roast', 'rob', 'robinson', 'rock', 'rodds1', 'rodger', 'rofl', 'roger', 'role', 'roll', 'roller', 'romant', 'romcapspam', 'ron', 'room', 'roomat', 'roommat', 'rose', 'rough', 'round', 'rounderso', 'rout', 'row', 'roww1j6hl', 'roww1jhl', 'royal', 'rp176781', 'rpl', 'rpli', 'rr', 'rreveal', 'rs', 'rs5', 'rsi', 'rstm', 'rtking', 'rtm', 'rto', 'ru', 'rub', 'rubber', 'rude', 'rudi', 'rugbi', 'ruin', 'rule', 'rum', 'rumbl', 'rummer', 'rumour', 'run', 'runninglet', 'rupaul', 'rush', 'rv', 'ryan', 'ryder', 's3xi', 's8', 's89', 'sac', 'sachin', 'sachinjust', 'sack', 'sacrific', 'sad', 'sae', 'saeed', 'safe', 'safeti', 'sagamu', 'saibaba', 'said', 'saidif', 'sake', 'salad', 'salam', 'salari', 'sale', 'salesman', 'salespe', 'sall', 'salmon', 'salon', 'salt', 'sam', 'samachara', 'samantha', 'sambarlif', 'sameso', 'samu', 'sandiago', 'sane', 'sang', 'sankranti', 'santa', 'santha', 'sao', 'sapna', 'sar', 'sara', 'sarasota', 'sarcasm', 'sarcast', 'sari', 'saristar', 'sariyag', 'sashimi', 'sat', 'satan', 'sathi', 'sathya', 'satisfi', 'satjust', 'satlov', 'satsgettin', 'satsound', 'satthen', 'saturday', 'satü', 'sauci', 'sausagelov', 'savamob', 'save', 'saw', 'say', 'sayask', 'sayhey', 'sayi', 'sayin', 'sbut', 'sc', 'scalli', 'scammer', 'scarcasim', 'scare', 'scari', 'scenario', 'sceneri', 'sch', 'schedul', 'school', 'scienc', 'scold', 'scool', 'scorabl', 'score', 'scotch', 'scotland', 'scotsman', 'scous', 'scrape', 'scrappi', 'scratch', 'scream', 'screen', 'screwd', 'scroung', 'scrumptiou', 'sculptur', 'sd', 'sday', 'sdryb8i', 'se', 'sea', 'search', 'season', 'seat', 'sec', 'second', 'secondari', 'secret', 'secretari', 'secretli', 'section', 'secur', 'sed', 'see', 'seed', 'seek', 'seeker', 'seem', 'seen', 'seeno', 'sef', 'seh', 'sehwag', 'select', 'self', 'selfindepend', 'selfish', 'selfless', 'sell', 'sem', 'semest', 'semi', 'semiobscur', 'sen', 'send', 'sender', 'sendernam', 'senor', 'senrddnot', 'sens', 'sensesrespect', 'sensibl', 'sensit', 'sent', 'sentdat', 'sentenc', 'senthil', 'senthilhsbc', 'seperated鈥', 'sept', 'septemb', 'serena', 'seri', 'seriou', 'serious', 'serv', 'server', 'servic', 'set', 'settl', 'seven', 'seventeen', 'sever', 'sex', 'sexi', 'sexiest', 'sextextukcom', 'sexual', 'sexychat', 'sez', 'sf', 'sfine', 'sfirst', 'sfrom', 'sh', 'sha', 'shade', 'shadow', 'shag', 'shah', 'shahjahan', 'shakara', 'shake', 'shakespear', 'shall', 'shame', 'shampain', 'shangela', 'shanghai', 'shanilrakhesh', 'shant', 'shape', 'share', 'shatter', 'shave', 'shb', 'shd', 'she', 'sheet', 'sheffield', 'shelf', 'shell', 'shelv', 'sherawat', 'shesil', 'shexi', 'shhhhh', 'shi', 'shifad', 'shija', 'shijutta', 'shinco', 'shindig', 'shine', 'shini', 'ship', 'shirt', 'shit', 'shite', 'shitin', 'shitjustfound', 'shitload', 'shitstorm', 'shivratri', 'shja', 'shld', 'shldxxxx', 'shock', 'shoe', 'shola', 'shoot', 'shop', 'shoppin', 'shopth', 'shopw', 'shoranur', 'shore', 'shoreth', 'short', 'shortag', 'shortcod', 'shorter', 'shortli', 'shot', 'shoul', 'shoulder', 'shouldnt', 'shout', 'shove', 'show', 'shower', 'showr', 'showroomsc', 'shracomorsglsuplt10', 'shrek', 'shrink', 'shrub', 'shu', 'shud', 'shudvetold', 'shuhui', 'shun', 'shut', 'si', 'sian', 'sib', 'sic', 'sick', 'sicomo', 'side', 'sif', 'sigh', 'sight', 'sign', 'signal', 'signific', 'signin', 'siguviri', 'silenc', 'silent', 'silli', 'silver', 'sim', 'simonwatson5120', 'simpl', 'simpler', 'simpli', 'simpson', 'simul', 'sinc', 'sinco', 'sindu', 'sing', 'singapor', 'singl', 'sink', 'sip', 'sipix', 'sir', 'siri', 'sirjii', 'sirsalam', 'sister', 'sit', 'site', 'sitll', 'sitter', 'sittin', 'situat', 'siva', 'sivatat', 'six', 'size', 'sk3', 'sk38xh', 'skalli', 'skateboard', 'skilgm', 'skill', 'skillgam', 'skillgame1winaweek', 'skin', 'skinni', 'skint', 'skip', 'skirt', 'sky', 'skye', 'skype', 'skyve', 'slaaaaav', 'slack', 'slap', 'slave', 'sleep', 'sleepi', 'sleepin', 'sleepingand', 'sleepingwith', 'sleepsweet', 'sleepwellamptak', 'slept', 'slice', 'slide', 'slightli', 'slip', 'slipper', 'slipperi', 'slo', 'slo4msg', 'slob', 'slot', 'slove', 'slow', 'slower', 'slowli', 'slurp', 'sm', 'smack', 'small', 'smaller', 'smart', 'smartcal', 'smarter', 'smartthough', 'smash', 'smear', 'smell', 'smeon', 'smidgin', 'smile', 'smiley', 'smith', 'smithswitch', 'smoke', 'smokin', 'smoothli', 'sms08718727870', 'smsd', 'smsing', 'smsservic', 'smsshsexnetun', 'smth', 'sn', 'snake', 'snap', 'snappi', 'snatch', 'snd', 'sneham', 'snicker', 'sno', 'snog', 'snoringthey', 'snow', 'snowbal', 'snowboard', 'snowman', 'snuggl', 'so', 'soani', 'soc', 'socht', 'social', 'sofa', 'soft', 'softwar', 'soil', 'soire', 'sol', 'soladha', 'sold', 'solihul', 'solv', 'some1', 'somebodi', 'someday', 'someon', 'someonethat', 'someonon', 'someplac', 'somerset', 'someth', 'somethin', 'sometim', 'sometimerakheshvisitor', 'sometm', 'somewhat', 'somewher', 'somewheresomeon', 'somewhr', 'somon', 'somtim', 'sonathaya', 'sonetim', 'song', 'soni', 'sonot', 'sonyericsson', 'soo', 'soon', 'soonc', 'sooner', 'soonlot', 'soonxxx', 'sooo', 'soooo', 'sooooo', 'sopha', 'sore', 'sori', 'sorri', 'sorrow', 'sorrowsi', 'sorryi', 'sorryin', 'sort', 'sorta', 'sortedbut', 'sorydarealyfrm', 'soso', 'soul', 'sound', 'soundtrack', 'soup', 'sourc', 'south', 'southern', 'souveni', 'soz', 'sp', 'space', 'spacebuck', 'spageddi', 'spain', 'spam', 'spanish', 'spare', 'spark', 'sparkl', 'spatula', 'speak', 'spec', 'special', 'specialcal', 'specialis', 'specif', 'specifi', 'speechless', 'speed', 'speedchat', 'spele', 'spell', 'spend', 'spent', 'spi', 'spice', 'spider', 'spiderman', 'spif', 'spile', 'spin', 'spinout', 'spiral', 'spirit', 'spiritu', 'spjanuari', 'spk', 'spl', 'splash', 'splashmobil', 'splat', 'splendid', 'split', 'splle', 'splwat', 'spoil', 'spoilt', 'spoke', 'spoken', 'sponsor', 'spontan', 'spook', 'spoon', 'sporad', 'sport', 'sportsx', 'spose', 'spot', 'spotti', 'spous', 'sppok', 'spreadsheet', 'spree', 'spring', 'sprint', 'sprwm', 'sptv', 'sptyron', 'spunout', 'sq825', 'squat', 'squeeeeez', 'squeez', 'squid', 'squishi', 'sr', 'sri', 'srsli', 'srt', 'ssi', 'ssindia', 'ssnervou', 'st', 'stabil', 'stabl', 'stadium', 'staff', 'staffsciencenusedusgphyhcmkteachingpc1323', 'stage', 'stagwood', 'stair', 'stalk', 'stamp', 'stand', 'standard', 'stapati', 'star', 'stare', 'starer', 'starshin', 'start', 'startedindia', 'starti', 'starv', 'starwars3', 'stash', 'state', 'statement', 'station', 'statu', 'stay', 'stayin', 'std', 'stdtxtrate', 'steak', 'steal', 'steam', 'steamboat', 'steed', 'steer', 'step', 'stereo', 'stereophon', 'sterl', 'sterm', 'steve', 'stevelik', 'stewarts', 'steyn', 'sth', 'sthi', 'stick', 'sticki', 'stifl', 'stil', 'still', 'stillmayb', 'stink', 'stitch', 'stock', 'stockport', 'stolen', 'stomach', 'stomp', 'stone', 'stoner', 'stool', 'stop', 'stop2', 'stop2stop', 'stopbcm', 'stopc', 'stopcost', 'stoptxt', 'stoptxtstop', 'store', 'storelik', 'stori', 'storm', 'str', 'str8', 'straight', 'strain', 'strang', 'stranger', 'strangersaw', 'stream', 'street', 'streetshal', 'stress', 'stressful', 'stretch', 'strewn', 'strict', 'strike', 'string', 'strip', 'stripe', 'stroke', 'strong', 'strongbuy', 'strongli', 'strt', 'strtd', 'struggl', 'stu', 'stubborn', 'stuck', 'studdi', 'student', 'studentfinanci', 'studentsthi', 'studi', 'studio', 'studyn', 'stuf', 'stuff', 'stuff42moro', 'stuffleav', 'stuffwhi', 'stun', 'stupid', 'stupidit', 'style', 'stylish', 'stylist', 'sub', 'subject', 'sublet', 'submit', 'subpoli', 'subscrib', 'subscribe6gbpmnth', 'subscript', 'subscriptn3gbpwk', 'subscrit', 'subsequ', 'subtoitl', 'success', 'suck', 'sucker', 'sudden', 'suddenli', 'sudn', 'sue', 'suffer', 'suffici', 'sugabab', 'suganya', 'sugar', 'sugardad', 'suggest', 'suit', 'suitem', 'sullivan', 'sum', 'sum1', 'sumf', 'summer', 'summon', 'sumthin', 'sumthinxx', 'sun', 'sun0819', 'sunday', 'sundayish', 'sunlight', 'sunni', 'sunoco', 'sunroof', 'sunscreen', 'sunshin', 'suntec', 'sup', 'super', 'superb', 'superior', 'supervisor', 'supli', 'supos', 'suppli', 'supplier', 'support', 'supportprovid', 'supportveri', 'suppos', 'suprem', 'suprman', 'sura', 'sure', 'surf', 'surgic', 'surli', 'surnam', 'surpris', 'surrend', 'surround', 'survey', 'surya', 'sutra', 'sux', 'suzi', 'svc', 'sw7', 'sw73ss', 'swalpa', 'swan', 'swann', 'swap', 'swashbuckl', 'swat', 'swatch', 'sway', 'swayz', 'swear', 'sweater', 'sweatter', 'sweet', 'sweetest', 'sweetheart', 'sweeti', 'swell', 'swhrt', 'swim', 'swimsuit', 'swing', 'swiss', 'switch', 'swollen', 'swoop', 'swt', 'swtheart', 'syd', 'syllabu', 'symbol', 'sympathet', 'symptom', 'sync', 'syria', 'syrup', 'system', 't91', 'ta', 'tabl', 'tablet', 'tackl', 'taco', 'tact', 'tactless', 'tadaaaaa', 'tag', 'tahan', 'tai', 'tait', 'taj', 'taka', 'take', 'takecar', 'taken', 'takenonli', 'takin', 'talent', 'talk', 'talkbut', 'talkin', 'tall', 'tallahasse', 'tallent', 'tamilnaduthen', 'tampa', 'tank', 'tantrum', 'tap', 'tape', 'tariff', 'tarot', 'tarpon', 'tast', 'tat', 'tata', 'tattoo', 'tau', 'taught', 'taunton', 'tax', 'taxi', 'taxless', 'taxt', 'taylor', 'tayseertissco', 'tb', 'tbspersolvo', 'tc', 'tcllc', 'tcrw1', 'tcsbcm4235wc1n3xx', 'tcsc', 'tcsstop', 'tddnewsletteremc1couk', 'tea', 'teach', 'teacher', 'teacoffe', 'team', 'tear', 'teas', 'tech', 'technic', 'technolog', 'tee', 'teenag', 'teeth', 'teethi', 'teethif', 'teju', 'tel', 'telephon', 'teletext', 'tell', 'telli', 'tellmiss', 'telphon', 'telugu', 'telugutht', 'temal', 'temp', 'temper', 'templ', 'ten', 'tenant', 'tendenc', 'tenerif', 'tens', 'tension', 'teresa', 'term', 'terminatedw', 'termsappli', 'terri', 'terribl', 'terrif', 'terrorist', 'tesco', 'tessypl', 'test', 'tex', 'texa', 'texd', 'text', 'text82228', 'textand', 'textbook', 'textbuddi', 'textcomp', 'textin', 'textoper', 'textpod', 'textsweekend', 'tgxxrz', 'th', 'thandiyachu', 'thangam', 'thangamit', 'thank', 'thanks2', 'thanksgiv', 'thanku', 'thankyou', 'thanx', 'thanx4', 'thanxxx', 'thasa', 'that', 'that2worzel', 'thatd', 'thatdont', 'thati', 'thatll', 'thatmum', 'thatnow', 'the4th', 'theacus', 'theater', 'theatr', 'thecd', 'thedailydraw', 'thekingshead', 'theme', 'themob', 'themobhit', 'themobyo', 'themp', 'thenwil', 'theoret', 'theori', 'theplac', 'thepub', 'there', 'theredo', 'theregoodnight', 'therel', 'therer', 'therexx', 'theseday', 'theseyour', 'thesi', 'thesmszonecom', 'thewend', 'theyll', 'theyr', 'thgt', 'thi', 'thia', 'thin', 'thing', 'thinghow', 'think', 'thinkin', 'thinkthi', 'thinl', 'thirunelvali', 'thisdon', 'thk', 'thkin', 'thm', 'thnk', 'thnq', 'thnx', 'tho', 'thoso', 'thot', 'thou', 'though', 'thought', 'thoughtsi', 'thousand', 'thout', 'thread', 'threat', 'three', 'threw', 'thriller', 'throat', 'throw', 'throwin', 'thrown', 'thru', 'thrurespect', 'tht', 'thu', 'thuglyf', 'thur', 'thursday', 'thx', 'ti', 'tick', 'ticket', 'tiempo', 'tiger', 'tight', 'tightli', 'tigress', 'tih', 'tiim', 'til', 'till', 'tim', 'time', 'timedhoni', 'timegud', 'timehop', 'timeslil', 'timey', 'timeyour', 'timi', 'timin', 'tini', 'tip', 'tire', 'tirunelvai', 'tirunelvali', 'tirupur', 'tisscotays', 'titl', 'titleso', 'tiwari', 'tix', 'tiz', 'tke', 'tkt', 'tlk', 'tm', 'tming', 'tmobil', 'tmorrowpl', 'tmr', 'tmrw', 'tmw', 'tnc', 'toa', 'toaday', 'tobacco', 'tobe', 'tocallshal', 'toclaim', 'today', 'todaybut', 'todaydo', 'todayfrom', 'todaygood', 'todayh', 'todaysundaysunday', 'todo', 'tog', 'togeth', 'tohar', 'toilet', 'tok', 'toke', 'token', 'tol', 'told', 'toldsh', 'toledo', 'toler', 'toleratbc', 'toll', 'tom', 'tomarrow', 'tome', 'tomeandsaidthi', 'tomo', 'tomoc', 'tomorro', 'tomorrow', 'tomorrowcal', 'tomorrowtoday', 'tomorw', 'ton', 'tone', 'tones2u', 'tones2youcouk', 'tonesrepli', 'tonex', 'tonght', 'tongu', 'tonight', 'tonit', 'tonitebusi', 'toniteth', 'tonsolitusaswel', 'took', 'tookplac', 'tool', 'toolet', 'tooo', 'toopray', 'toot', 'toothpast', 'tootsi', 'top', 'topic', 'topicsorri', 'toplay', 'toppoli', 'tor', 'torch', 'torrent', 'tortilla', 'tortur', 'tosend', 'toshiba', 'toss', 'tot', 'total', 'tote', 'touch', 'tough', 'toughest', 'tour', 'toward', 'town', 'towncud', 'towndontmatt', 'toxic', 'toyota', 'tp', 'track', 'trackmarqu', 'trade', 'tradit', 'traffic', 'train', 'trainner', 'tram', 'tranquil', 'transact', 'transcrib', 'transfer', 'transferacc', 'transfr', 'transport', 'trash', 'trauma', 'trav', 'travel', 'treacl', 'treadmil', 'treasur', 'treat', 'treatin', 'trebl', 'tree', 'trek', 'trend', 'tri', 'trial', 'trip', 'tripl', 'trishul', 'triumph', 'tron', 'troubl', 'troubleshoot', 'trouser', 'trubl', 'truck', 'true', 'truekdo', 'truffl', 'truli', 'truro', 'trust', 'truth', 'tryin', 'trywal', 'ts', 'tsandc', 'tsc', 'tscs08714740323', 'tscs087147403231winawkage16', 'tshirt', 'tsunami', 'tt', 'ttyl', 'tue', 'tuesday', 'tui', 'tuition', 'tul', 'tulip', 'tund', 'tune', 'tunji', 'turkey', 'turn', 'tuth', 'tv', 'tvhe', 'tvlol', 'twat', 'twelv', 'twenti', 'twice', 'twigg', 'twilight', 'twin', 'twink', 'twitter', 'two', 'tx', 'txt', 'txt250com', 'txtauction', 'txtauctiontxt', 'txtin', 'txting', 'txtjourney', 'txtno', 'txtx', 'tyler', 'type', 'typelyk', 'typic', 'u', 'u2moro', 'u4', 'uawakefeellikw', 'ubandu', 'ubi', 'ucal', 'ufind', 'ugadi', 'ugh', 'ugo', 'uh', 'uhhhhrmm', 'uif', 'uin', 'ujhhhhhhh', 'uk', 'ukmobiled', 'ukp2000', 'ull', 'ultim', 'ultimatum', 'um', 'umma', 'ummmawil', 'ummmmmaah', 'un', 'unabl', 'unbeliev', 'uncl', 'unclaim', 'uncomfort', 'uncondit', 'unconsci', 'unconvinc', 'uncount', 'uncut', 'underdtand', 'understand', 'understood', 'underwear', 'undrstnd', 'undrstndng', 'unemploy', 'unev', 'unfold', 'unfortun', 'unfortuntli', 'unhappi', 'uni', 'unicef', 'uniform', 'unintent', 'uniqu', 'uniquei', 'unit', 'univ', 'univers', 'unknown', 'unless', 'unlik', 'unlimit', 'unmit', 'unnecessarili', 'unni', 'unrecogn', 'unredeem', 'unsecur', 'unsold', 'unsoldmik', 'unsoldnow', 'unspoken', 'unsub', 'unsubscrib', 'unusu', 'uothrwis', 'up', 'up4', 'upcharg', 'upd8', 'updat', 'updatenow', 'upgrad', 'upgrdcentr', 'uphad', 'upload', 'upnot', 'upon', 'upset', 'upseti', 'upsetit', 'upstair', 'upto', 'uptown', 'upyeh', 'ur', 'ure', 'urfeel', 'urgent', 'urgentbut', 'urgentlyit', 'urgh', 'urgnt', 'urgoin', 'urgran', 'urin', 'url', 'urmomi', 'urn', 'urself', 'us', 'usb', 'usc', 'uscedu', 'use', 'useless', 'user', 'usf', 'usget', 'usher', 'uslet', 'usml', 'usno', 'uso', 'usp', 'usual', 'usualiam', 'uteru', 'utter', 'uu', 'uup', 'uv', 'uve', 'uwana', 'uwant', 'uworld', 'uxxxx', 'v', 'vaazhthukk', 'vagu', 'vai', 'vale', 'valentin', 'valid', 'valid12hr', 'valu', 'valuabl', 'valuemorn', 'varaya', 'vargu', 'vari', 'variou', 'varma', 'vasai', 'vat', 'vatian', 'vava', 'vco', 'vday', 'vega', 'veget', 'veggi', 'vehicl', 'velacheri', 'velli', 'velusami', 'venaam', 'venugop', 'verifi', 'version', 'versu', 'vettam', 'vewi', 'via', 'vibrant', 'vibrat', 'vic', 'victor', 'victoria', 'vid', 'video', 'videochat', 'videop', 'videophon', 'videosound', 'videosounds2', 'vidnot', 'view', 'vijay', 'vijaykanth', 'vikki', 'vikkyim', 'vilikkamt', 'vill', 'villa', 'villag', 'vinobanagar', 'violat', 'violenc', 'violet', 'vip', 'virgil', 'virgin', 'virtual', 'visa', 'visionsmscom', 'visit', 'visitne', 'visitor', 'vital', 'vitamin', 'viva', 'vivek', 'vivekanand', 'viveki', 'vl', 'vldo', 'voda', 'vodafon', 'vodka', 'voic', 'voicemail', 'voila', 'volcano', 'vomit', 'vomitin', 'vote', 'voucher', 'voucherstext', 'vpist', 'vpod', 'vri', 'vs', 'vth', 'vtire', 'vu', 'w', 'w111wx', 'w14rg', 'w1a', 'w1j', 'w1t1ji', 'w4', 'w45wq', 'w8in', 'wa', 'wa14', 'waaaat', 'wad', 'wadebridgei', 'wah', 'wahala', 'wahay', 'wahe', 'waheeda', 'wahleykkumshar', 'waht', 'wait', 'waiti', 'waitin', 'waitshould', 'waitu', 'wake', 'wale', 'walik', 'walk', 'walkabout', 'walkin', 'wall', 'wallet', 'wallpap', 'wallpaperal', 'walmart', 'walsal', 'wamma', 'wan', 'wan2', 'wana', 'wanna', 'wannatel', 'want', 'want2com', 'wap', 'waqt', 'warm', 'warn', 'warner', 'warranti', 'warwick', 'washob', 'wasnt', 'wast', 'wat', 'watch', 'watchin', 'watchng', 'wate', 'water', 'watev', 'watevr', 'watll', 'watrdayno', 'watt', 'wave', 'way', 'way2smscom', 'waythi', 'wc', 'wc1n', 'wc1n3xx', 'weak', 'weapon', 'wear', 'weasel', 'weather', 'web', 'web2mobil', 'webadr', 'webeburnin', 'webpag', 'websit', 'websitenow', 'wed', 'weddin', 'weddingfriend', 'wedlunch', 'wednesday', 'wee', 'weed', 'weeddefici', 'week', 'weekday', 'weekend', 'weekli', 'weekstop', 'weigh', 'weight', 'weighthaha', 'weightloss', 'weird', 'weirdest', 'weirdi', 'weirdo', 'weiyi', 'welcom', 'well', 'wellda', 'welli', 'welltak', 'wellyou', 'welp', 'wen', 'wendi', 'wenev', 'went', 'wenwecan', 'wer', 'werear', 'werebor', 'werent', 'wereth', 'wesley', 'west', 'western', 'westlif', 'westonzoyland', 'westshor', 'wet', 'wetherspoon', 'weve', 'wewa', 'whassup', 'what', 'whatev', 'whatsup', 'wheat', 'wheel', 'wheellock', 'when', 'whenev', 'whenevr', 'whenr', 'whenwher', 'where', 'wherear', 'wherebtw', 'wherev', 'wherevr', 'wherr', 'whether', 'whileamp', 'whilltak', 'whisper', 'white', 'whn', 'who', 'whole', 'whore', 'whose', 'whr', 'wi', 'wick', 'wicket', 'wicklow', 'wid', 'widelivecomindex', 'wif', 'wife', 'wifedont', 'wifehow', 'wifi', 'wihtuot', 'wikipediacom', 'wil', 'wild', 'wildest', 'wildlif', 'will', 'willpow', 'win', 'win150ppmx3age16', 'wind', 'windi', 'window', 'wine', 'wing', 'winner', 'winnersclub', 'winterston', 'wipe', 'wipro', 'wiproy', 'wire3net', 'wisdom', 'wise', 'wish', 'wishin', 'wishlist', 'wiskey', 'wit', 'withdraw', 'wither', 'within', 'without', 'witin', 'witot', 'witout', 'wiv', 'wizzl', 'wk', 'wkend', 'wkent150p16', 'wkg', 'wkli', 'wknd', 'wktxt', 'wlcome', 'wld', 'wmlid1b6a5ecef91ff937819firsttrue180430jul05', 'wmlid820554ad0a1705572711firsttru', 'wn', 'wnevr', 'wnt', 'wo', 'woah', 'wocay', 'woke', 'woken', 'woman', 'womdarful', 'women', 'wondar', 'wondarful', 'wonder', 'wont', 'woo', 'wood', 'woodland', 'woohoo', 'woot', 'woould', 'woozl', 'worc', 'word', 'wordcollect', 'wordnot', 'wordsevri', 'wordstart', 'work', 'workag', 'workand', 'workin', 'worklov', 'workout', 'world', 'worldgnun', 'worldmay', 'worldveri', 'worm', 'worri', 'worriedx', 'worryc', 'worryus', 'wors', 'worst', 'worth', 'worthless', 'wot', 'wotu', 'wotz', 'woul', 'would', 'woulda', 'wouldnt', 'wound', 'wow', 'wquestion', 'wrc', 'wreck', 'wrench', 'wright', 'write', 'writh', 'wrk', 'wrki', 'wrkin', 'wrking', 'wrld', 'wrnog', 'wrong', 'wrongli', 'wrongtak', 'wrote', 'ws', 'wt', 'wtc', 'wtf', 'wth', 'wthout', 'wud', 'wudnt', 'wuld', 'wuldnt', 'wun', 'www07781482378com', 'www4tcbiz', 'www80488biz', 'wwwapplausestorecom', 'wwwareyouuniquecouk', 'wwwasjesuscom', 'wwwb4utelecom', 'wwwbridalpetticoatdreamscouk', 'wwwcashbincouk', 'wwwclubmobycom', 'wwwclubzedcouk', 'wwwcnupdatescomnewslett', 'wwwcomuknet', 'wwwdbuknet', 'wwwflirtpartyu', 'wwwfullonsmscom', 'wwwgambtv', 'wwwgetzedcouk', 'wwwidewcom', 'wwwldewcom', 'wwwldewcom1win150ppmx3age16', 'wwwldewcom1win150ppmx3age16subscript', 'wwwldewcomsubs161win150ppmx3', 'wwwmovietriviatv', 'wwwmusictrivianet', 'wwworangecoukow', 'wwwphb1com', 'wwwregalportfoliocouk', 'wwwringtonekingcouk', 'wwwringtonescouk', 'wwwrtfsphostingcom', 'wwwsantacallingcom', 'wwwshortbreaksorguk', 'wwwsmsacubootydeli', 'wwwsmsacugoldvik', 'wwwsmsacuhmmross', 'wwwsmsacunat27081980', 'wwwsmsacunatalie2k9', 'wwwsmsconet', 'wwwtcbiz', 'wwwtelediscountcouk', 'wwwtextcompcom', 'wwwtextpodnet', 'wwwtklscom', 'wwwtxt2shopcom', 'wwwtxt43com', 'wwwtxt82228com', 'wwwtxttowincouk', 'wwwwin82050couk', 'wyli', 'x', 'x2', 'x29', 'x49', 'x49your', 'xafter', 'xam', 'xavier', 'xchat', 'xclusiveclubsaisai', 'xin', 'xma', 'xnet', 'xoxo', 'xt', 'xuhui', 'xx', 'xxsp', 'xxuk', 'xxx', 'xxxmobilemovieclub', 'xxxmobilemovieclubcomnqjkgighjjgcbl', 'xxxx', 'xxxxx', 'xxxxxx', 'xxxxxxx', 'xxxxxxxx', 'xxxxxxxxxxxxxx', 'xy', 'y87', 'ya', 'yago', 'yah', 'yahoo', 'yalrigu', 'yalru', 'yam', 'yan', 'yar', 'yard', 'yavnt', 'yaxx', 'yaxxx', 'yay', 'yck', 'yday', 'ye', 'yeah', 'yeahand', 'year', 'yeesh', 'yeh', 'yell', 'yellow', 'yelowi', 'yen', 'yeovil', 'yep', 'yer', 'yes165', 'yes434', 'yes440', 'yes762', 'yes910', 'yesbut', 'yesfrom', 'yesgauti', 'yesh', 'yesher', 'yesim', 'yesmum', 'yessura', 'yest', 'yesterday', 'yet', 'yetti', 'yetund', 'yi', 'yifeng', 'yiju', 'yijuehotmailcom', 'ym', 'ymca', 'yo', 'yoga', 'yogasana', 'yoher', 'yor', 'yorg', 'youani', 'youcarlo', 'youclean', 'youd', 'youdearwith', 'youdo', 'youhow', 'youi', 'youkwher', 'yould', 'youll', 'youmi', 'youmoney', 'young', 'younger', 'youphon', 'your', 'yourinclus', 'yourjob', 'youso', 'youthat', 'youto', 'youuuuu', 'youv', 'youwanna', 'youwhen', 'yovil', 'yowif', 'yoyyooo', 'yr', 'ystrdayic', 'yummi', 'yummmm', 'yun', 'yunni', 'yuo', 'yuou', 'yup', 'yupz', 'ywhere', 'z', 'zac', 'zaher', 'zealand', 'zebra', 'zed', 'zero', 'zhong', 'zindgi', 'zoe', 'zogtoriu', 'zoom', 'zouk', 'zyada', 'é', 'ü', 'üll', '〨ud'] ###Markdown Apply CountVectorizer to smaller sample ###Code data_sample = data[0:20] count_vect_sample = CountVectorizer(analyzer=clean_text) X_counts_sample = count_vect_sample.fit_transform(data_sample['body_text']) print(X_counts_sample.shape) print(count_vect_sample.get_feature_names()) ###Output (20, 192) ['08002986030', '08452810075over18', '09061701461', '1', '100', '100000', '11', '12', '150pday', '16', '2', '20000', '2005', '21st', '3', '4', '4403ldnw1a7rw18', '4txtú120', '6day', '81010', '87077', '87121', '87575', '9', '900', 'aft', 'aid', 'alreadi', 'alright', 'anymor', 'appli', 'ard', 'around', 'b', 'brother', 'call', 'caller', 'callertun', 'camera', 'cash', 'chanc', 'claim', 'click', 'co', 'code', 'colour', 'comin', 'comp', 'copi', 'cost', 'credit', 'cri', 'csh11', 'cup', 'custom', 'da', 'date', 'dont', 'eg', 'eh', 'england', 'enough', 'entitl', 'entri', 'even', 'fa', 'feel', 'ffffffffff', 'final', 'fine', 'finish', 'first', 'free', 'friend', 'go', 'goalsteam', 'goe', 'gonna', 'gota', 'ha', 'hl', 'home', 'hour', 'httpwap', 'im', 'info', 'ive', 'jackpot', 'joke', 'k', 'kim', 'kl341', 'lar', 'latest', 'lccltd', 'like', 'link', 'live', 'lor', 'lunch', 'macedonia', 'make', 'may', 'meet', 'mell', 'membership', 'messag', 'minnaminungint', 'miss', 'mobil', 'month', 'nah', 'name', 'nation', 'naughti', 'network', 'news', 'next', 'nurungu', 'oh', 'oru', 'patent', 'pay', 'per', 'pobox', 'poboxox36504w45wq', 'pound', 'press', 'prize', 'questionstd', 'r', 'ratetc', 'receiv', 'receivea', 'rememb', 'repli', 'request', 'reward', 'scotland', 'select', 'send', 'serious', 'set', 'six', 'smth', 'soon', 'sooner', 'speak', 'spell', 'stock', 'str', 'stuff', 'sunday', 'talk', 'tc', 'team', 'text', 'think', 'though', 'tkt', 'today', 'tonight', 'treat', 'tri', 'trywal', 'tsandc', 'txt', 'u', 'updat', 'ur', 'urgent', 'use', 'usf', 'v', 'valid', 'valu', 'vettam', 'want', 'wap', 'watch', 'way', 'week', 'wet', 'win', 'winner', 'wkli', 'word', 'wwwdbuknet', 'xxxmobilemovieclub', 'xxxmobilemovieclubcomnqjkgighjjgcbl', 'ye', 'ü'] ###Markdown Vectorizers output sparse matrices_**Sparse Matrix**: A matrix in which most entries are 0. In the interest of efficient storage, a sparse matrix will be stored by only storing the locations of the non-zero elements._ ###Code X_counts_sample X_counts_df = pd.DataFrame(X_counts_sample.toarray()) X_counts_df X_counts_df.columns = count_vect_sample.get_feature_names() X_counts_df ###Output _____no_output_____
.ipynb_checkpoints/Pt. 1 Exploratory Data Analysis (EDA)-checkpoint.ipynb
###Markdown Graduate Admissions EDA ###Code import pandas as pd import numpy as np import sklearn import seaborn as sb import matplotlib as mpl import matplotlib.pyplot as plt grad = pd.read_csv('Admission_Predict_Ver1.1.csv') grad.head() ###Output _____no_output_____ ###Markdown --- Project Description The dataset used in the project uses information on graduate admission and the chance to get admitted from India.It can be found at [Kaggle](https://www.kaggle.com/mohansacharya/graduate-admissions)The dataset contains several parameters which are considered important during the application for Masters Programs.The parameters included are:1) GRE Scores (out of 340) 2) TOEFL Scores (out of 120) 3) University Rating (out of 5) 4) Statement of Purpose (out of 5) 5) Letter of Recommendation Strength (out of 5) 6) Undergraduate GPA (out of 10) 7) Research Experience (either 0 or 1) 8) Chance of Admit (ranging from 0 to 1) This project is splot into three parts:1) Exploratory Data Anaylsis 2) Data Cleaning: Scrubbing the Data 3) Data Analysis/Mining: Modeling the Data This notebook is the first part: *EDA* --- Data Description ###Code grad.shape ###Output _____no_output_____ ###Markdown There are 500 rows with 9 variables. ###Code grad.columns grad.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 500 entries, 0 to 499 Data columns (total 9 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Serial No. 500 non-null int64 1 GRE Score 500 non-null int64 2 TOEFL Score 500 non-null int64 3 University Rating 500 non-null int64 4 SOP 500 non-null float64 5 LOR 500 non-null float64 6 CGPA 500 non-null float64 7 Research 500 non-null int64 8 Chance of Admit 500 non-null float64 dtypes: float64(4), int64(5) memory usage: 35.3 KB ###Markdown All the features are either integers or floating number values. This makes sense since all the featurees are test scores or ratings. Let us explore each feature individually: ###Code grad.describe(include='all') # include='all' is added to include any categorical variables. ###Output _____no_output_____ ###Markdown The table above gives numerical descriptions (min, max, std, etc.) of each variable.The Serial No. is not a consequential feature because a python dataframe has its own row numberings. I may choose to remove this while scrubbing the data.The GRE scores in this dataset is interesting because there are no records of anyone receiving less than 290 points (minimum value). The average GRE score is around [150](https://www.prepscholar.com/gre/blog/average-gre-scores/). This may cause the results to be biased making it inapplicable for people in different regions that may have an average GRE score less than 317.The TOEFL scores also show a similar trend where the average score is higher than the average score of [2019](https://crushthegretest.com/toefl-scoring/:~:text=In%202019%2C%20a%20total%20score,needed%20at%20least%20a%20100.).The origins of university ratings are ambiguous. I have completed this project under the assumption that the rating has been provided by the student/applicant themselves. Thus, this rating may be unreliable and inaccurate causing some bias in the resutlts.SOP is an indicator of the Statement of Purpose and is a value between 1 and 5, inclusive.Similarly, LOR is an indicator of the Letter of Recommendation and is a value between 1 and 5, inclusive.CGPA is the value of the cumulative GPA of the applicants out of 10. The minimum value is approximately 7 which is higher than the mean of the range (5). This is another indicator that the dataset may only be applicable to applicants who graduated from a certain educational board or a specific region.Research shows if the applicant has any research experience. A value of 0 indicates that the applicant does not have any research experience, while a value of 1 shows that they have had research experience.Chance of Admit is a percentage provided by the applicant themselves, as stated by the [author](https://www.kaggle.com/mohansacharya/graduate-admissions/discussion/79063). GoalThe goal of the project is to use machine learning model(s) to understand the importance it places on various features in deciding the chance to get admitted. --- Duplicate & Missing Values ###Code grad.isnull().sum() grad.duplicated().value_counts() ###Output _____no_output_____ ###Markdown There are no NULL and duplicate values.This is good because no "empty" values need to be replaced and there are no duplicate rows/observations. --- Feature Distribution GRE Score ###Code plt.figure(figsize = (10,5)) plt.hist(grad['GRE Score'], bins = 10, facecolor = 'purple', edgecolor = 'black') plt.title('GRE Score Distribution') plt.xlabel('GRE Score') plt.ylabel('Frequency') plt.show() ###Output _____no_output_____ ###Markdown This chart shows the information reflected by the statistical table above. HIgh GRE scores between 310 and 325 are the most common, which is higher than the average score.The graph is bimodal, indicating two peaks. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = 'GRE Score', data = grad, palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown TOEFL Score ###Code plt.figure(figsize = (10,5)) plt.hist(grad['TOEFL Score'], bins = 10, facecolor = 'purple', edgecolor = 'black') plt.title('TOEFL Score Distribution') plt.xlabel('TOEFL Score') plt.ylabel('Frequency') plt.show() ###Output _____no_output_____ ###Markdown This histogram is left-skewed indicating that the frequency of low TOEFL scores is lower than higher TOEFL scores. THis might be indicative of the education level of the applicants recorded in this dataset. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['TOEFL Score'], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown University Rating ###Code grad['University Rating'].value_counts() plt.figure(figsize = (10,5)) grad['University Rating'].value_counts().reindex([1, 2, 3, 4, 5]).plot(kind = 'bar', facecolor = 'purple', edgecolor = 'black') plt.xticks(rotation = 0) plt.xlabel('University Rating') plt.ylabel('Count') plt.show() ###Output _____no_output_____ ###Markdown This is a bell-shaped curve indicating that most people rated universities the mean rating of 3 with fewer people giving extremely high or low ratings. This is intersting because it shows the nature of human cautiousness (since these ratings are provided by the applicants). ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['University Rating'], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown Statement of Purpose (SOP) ###Code grad['SOP'].value_counts() plt.figure(figsize = (10,5)) grad['SOP'].value_counts().reindex([1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]).plot(kind = 'bar', facecolor = 'purple', edgecolor = 'black') plt.xticks(rotation = 0) plt.xlabel('Statement of Purpose Rating') plt.ylabel('Count') plt.show() ###Output _____no_output_____ ###Markdown Fewer people have given low ratings for their statement of purpose. Most people have a realtively high rating between 3.5-4.0. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['SOP'], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown Letter of Recommendation (LOR) ###Code grad['LOR '].value_counts() # NOTE: LOR has a space at the end of its name. Will be renamed in data scrubbing stage. plt.figure(figsize = (10,5)) grad['LOR '].value_counts().reindex([1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]).plot(kind = 'bar', facecolor = 'purple', edgecolor = 'black') plt.xticks(rotation = 0) plt.xlabel('Letter of Recommendation Rating') plt.ylabel('Count') plt.show() ###Output _____no_output_____ ###Markdown This graph appears to be bimodal with two peaks at a rating of 3.0 and 4.0. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['LOR '], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown Cumulative GPA (CGPA) ###Code grad['CGPA'].value_counts() plt.figure(figsize = (10,5)) bin_order = [6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0] plt.hist(grad['CGPA'], bins = bin_order, facecolor = 'purple', edgecolor = 'black') plt.title('CGPA Distribution') plt.xlabel('CGPA') plt.ylabel('Frequency') plt.show() ###Output _____no_output_____ ###Markdown This distribution is slightly left-skewed indicating that most applicants have high CGPAs. In India, the average GPA is [7.0](https://gmatclub.com/forum/how-to-convert-indian-gpa-percentage-to-us-4-pt-gpa-scale-124249.html). This distribution shows that hte applicants in this dataset are above average. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['CGPA'], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown Research ###Code grad['Research'].value_counts() plt.figure(figsize = (10,5)) grad['Research'].value_counts().plot(kind = 'bar', facecolor = 'purple', edgecolor = 'black') plt.xticks(rotation = 0) plt.title('Research Experience Distribution') plt.xlabel('Research Experience') plt.ylabel('Count') plt.xticks(np.arange(2), ['Yes', 'No']) plt.show() ###Output _____no_output_____ ###Markdown This distribution shows that most applicants have research experience prior to applying for the their graduate programs. This may not show the common trend on a global scale, and should be kept in mind if applying this model or dataset to represent a population larger than Indian students. --- Chance of Admit ###Code grad['Chance of Admit '].value_counts() # NOTE: The name of the feature has a space at the end => Will be removed while scrubbing the data. plt.figure(figsize = (10,5)) bin_order = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] plt.hist(grad['Chance of Admit '], bins = bin_order, facecolor = 'purple', edgecolor = 'black') plt.title('Chance of Admit Distribution') plt.xlabel('Chance of Admit') plt.ylabel('Frequency') plt.show() grad['Chance of Admit '].describe() ###Output _____no_output_____ ###Markdown This distribution has an interesting shape where the the frequency of the chance of admit from 30% to 80% is increasing in a step-wise manner, after which it starts decreasing. Further, the mean value of this feature is 72%, implying that Indian students, on average, believe that they have a 72% chance of being admitted. This feature can be explored further by understanding the mentality and confidence of Indian students applying to graduate programs because after 80%, the chance of admit that these students gave themselves starts to decrease. ###Code plt.figure(figsize = (7,10)) sb.boxplot(y = grad['Chance of Admit '], palette = 'Greens') plt.show() ###Output _____no_output_____ ###Markdown None of the variables, except for Chance of Admit, have any outliers. The outlier in the Chance of Admit is clsoe to the minimum value and does not need to be dealt with. Hence, no outliers need to be dealt with. However, if there were any outliers, they could be removed or replaced or two models can be created - one with and one without outliers. Pairplot ###Code sb.pairplot(grad) ###Output _____no_output_____ ###Markdown This pairplot helps in analyzing each of the variables in comparison with each other. --- Multicollinearity Collinearity ###Code grad.corr() ###Output _____no_output_____ ###Markdown Let us look at a heatmap for a cleaer expression of the correlations between the variables. ###Code plt.figure(figsize=(16, 6)) heatmap = sb.heatmap(grad.corr(), vmin=-1, vmax=1, annot=True) heatmap.set_title('Correlation Heatmap', fontdict={'fontsize':12}, pad=12); ###Output _____no_output_____ ###Markdown By looking at the heatmap, the correlation values are easier to understand, i.e., extremely high or low values indicate a large or high degree of correlation.It can be seen that all the variables have a relatively high degree of correlation (> 0.5 or < -0.5) with the chance of admit; mainly GRE score and TOEFL.However, it can be seen that theree is a high degree of multicollinearity between the variables too. Especially between GRE, CGPA, and TOEFL scores.Multicollinearity may result in a biased model. However, dealing with multicollinearity is not mandatory depending on the regression model. If a linear model is being applied, then multicollinearity would result in a biased model. However, when creating a decision tree or random forest regression, then dealing with multicollinearity is not mandatory. If the goal is to simply predict the value of the chance of admit, then dealing with multicollinearity is not mandatory. However, trying to address the individual impacts of the features on the dependent variable would be wrong. VIF ###Code from statsmodels.stats.outliers_influence import variance_inflation_factor # the independent variables: X = grad[['GRE Score', 'TOEFL Score', 'University Rating', 'SOP', 'LOR ', 'CGPA', 'Research']] # VIF dataframe vif = pd.DataFrame() vif["VIF Factor"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])] vif["Features"] = X.columns print(vif) ###Output VIF Factor Features 0 1308.061089 GRE Score 1 1215.951898 TOEFL Score 2 20.933361 University Rating 3 35.265006 SOP 4 30.911476 LOR 5 950.817985 CGPA 6 2.869493 Research
tests/comparisons/cyclops-MB.ipynb
###Markdown mkGPLVM in tensorflowVery easy to use. A few lines is sufficient.This update allow regularization and combining kernels on the same dimension. (What does it mean?)Iteratively find the correct pattern. ###Code %matplotlib inline import pandas as pd from sklearn import preprocessing import matplotlib.pyplot as plt import numpy as np import sklearn as skl from cyclum.models.misc import cyclops from cyclum import writer import cyclum.tuning cell_line = "PC3" ###Output Using TensorFlow backend. ###Markdown mkGPLVM implemented in TensorflowThis is the implementation of mkGPLVM in Tensorflow. Get PC3 data ###Code raw_Y = pd.read_pickle('/home/shaoheng/Documents/data/McDavid/mb_df.pkl').T cpt = pd.read_pickle('/home/shaoheng/Documents/data/McDavid/mb_cpt.pkl').values print("Original dimesion %d cells x %d genes." % raw_Y.shape) print(f"G0/G1 {sum(cpt == 'g0/g1')}, S {sum(cpt == 's')}, G2/M {sum(cpt == 'g2/m')}") #expression_level = np.sum(2**raw_Y, axis=0) #ind = np.argpartition(expression_level.values, -150)[-150:] #genes = raw_Y.columns[np.argpartition(expression_level.values, -6)[-6:]] #Y = raw_Y.loc[:, raw_Y.columns[ind]] #Y.values[:, :] = preprocessing.scale(Y) Y = preprocessing.scale(raw_Y) N, D = Y.shape print('After filtering %d Cells (instances) x %d Genes (features)'%(N, D)) data = cyclops.prep(Y, variance_kept = 0.98) data=skl.preprocessing.scale(data) model = cyclops(data.shape[1]) display(model.show_structure()) model.train(data, epochs=1000, verbose=100, rate=2e-4) pseudotime = model.predict_pseudotime(data) import cyclum.illustration color_map = {"g0/g1": "red", "s": "green", "g2/m": "blue"} cyclum.illustration.plot_round_distr_color(pseudotime, cpt.squeeze(), color_map) flat_embedding = (pseudotime % (2 * np.pi)) / 2 import cyclum.evaluation width = 3.14 / 100 / 2; discrete_time, distr_g0g1 = cyclum.evaluation.periodic_parzen_estimate(flat_embedding[np.squeeze(cpt)=='g0/g1']) plt.bar(discrete_time, distr_g0g1, color='red', alpha=0.5, width = width) discrete_time, distr_s = cyclum.evaluation.periodic_parzen_estimate(flat_embedding[np.squeeze(cpt)=='s']) plt.bar(discrete_time, distr_s, color='green', alpha=0.5, width = width) discrete_time, distr_g2m = cyclum.evaluation.periodic_parzen_estimate(flat_embedding[np.squeeze(cpt)=='g2/m']) plt.bar(discrete_time, distr_g2m, color='blue', alpha=0.5, width = width) correct_prob = cyclum.evaluation.precision_estimate([distr_g0g1, distr_s, distr_g2m], cpt, ['g0/g1', 's', 'g2/m']) dis_score = correct_prob plt.title("Periodic Pseudo-time: Dis %f" % dis_score) plt.xlim([0, np.pi]) ###Output _____no_output_____ ###Markdown Note that this metric, although similar, is not exactly the same as the one we reported using mclust in R.We use a non-parametric parzen window method to estimate the distribution here, while mclust uses a parametric normal mixture. ###Code from cyclum.hdfrw import mat2hdf mat2hdf(pseudotime, '/home/shaoheng/Documents/data/McDavid/mb-cyclops-pseudotime.h5') ###Output _____no_output_____
linear-transformations-images.ipynb
###Markdown Linear transformations with imagesIn this module we will work with linearly aligning images. We'll apply transformations to images, and estimate optimal transformations. Here problems will be nonlinear, and we'll need to use iterative methods. ###Code import numpy as np %matplotlib notebook import matplotlib as mpl import matplotlib.pyplot as plt import os # for file paths import summerschool as ss import nibabel as nib # for loading many common neuroimage formats import scipy.interpolate as spi # use interpolation to deform images ###Output _____no_output_____ ###Markdown Load some data ###Code fname = os.path.join('mouse_images','PMD2052_orig_target_STS_clean.img') img = nib.load(fname) # load the image I = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it # standardize I = (I - np.mean(I))/np.std(I) # downsample so it can run on people's laptops down = 3 I = ss.downsample_image(I,down) # set up a domain, a grid of points describing the locations of each voxel nx = I.shape # number of voxels dx = img.header['pixdim'][1:4]*down # size of each voxel x0 = np.arange(nx[0])*dx[0] x1 = np.arange(nx[1])*dx[1] x2 = np.arange(nx[2])*dx[2] # lets define the origin to be in the middle of our image # linear transformations will be more reasonable this way # i.e. we'll rotate around the middle, instead of rotating around a corner x0 = x0 - np.mean(x0) x1 = x1 - np.mean(x1) x2 = x2 - np.mean(x2) X0,X1,X2 = np.meshgrid(x0,x1,x2,indexing='ij') # this function will show 3 orthogonal slices through the mouse image ss.imshow_slices(x0,x1,x2,I) ###Output _____no_output_____ ###Markdown Transformations act on images through their inverseA simple example is to consider shifting a function in 1D. If $f(x)$ is a function that we want to translate to the right by $T$, we translate it by $f(x - T)$ (NOT $f(x+T)$). Here $-T$ is the inverse of $+T$. In general, if we want to transform a function with a transformation $\varphi$, we use $f(x) \mapsto f(\varphi^{-1}(x))$. Explicit example in 2DWe will consider a simple 2x2 image and the effect of rotation. If you want to rotate your image clockwise, you must rotate your coordinates counterclockwise. This will be derived and illustrated in the lab. Images are deformed by sampling them at new points: interpolationHow do we evaluate $I(\varphi^{-1}(x))$ on a computer? We need to define the grid that $I$ is sampled on. Transform the grid using $\varphi^{-1}$. Then resample $I$ at the new points defined by this transformed grid.This resampling is known as interpolation. Most numerical libaries have built in functions for interpolation, including scipy. ###Code # set some arguments that will be used for interpolation with a dictionary interp_args = { 'method':'linear', # this says how we'd like to do interpolation, linear is fast and smooth 'bounds_error':False, # if we try to sample outside the image, do not raise an error 'fill_value':None # if we try to sample outside the image, we'll return the nearest pixel value } # A 2D example image and a grid defining its sample points I2d = np.array(I[:,:,I.shape[-1]//2]) X02d = X0[:,:,0] X12d = X1[:,:,0] # make a figure nplots = 5 f,ax = plt.subplots(2, nplots, sharex=True, sharey=True) for i in range(nplots): ax_ = ax[:,i] # choose a transformation if i == 0: A = np.eye(3) titlestring = 'identity' elif i == 1: T = np.random.randn(2)*2.0 A = np.array([[1,0,T[0]],[0,1,T[1]],[0,0,1]]) titlestring = 'translation' elif i == 2: theta = np.random.rand()*2.0*np.pi/6.0 A = np.eye(3) A[:2,:2]= [[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]] titlestring = 'rotation' elif i==3: s = np.random.randn()*0.1 + 1.0 A = np.eye(3) A[:2,:2] = np.eye(2)*s titlestring = 'scale' elif i == 4: A = np.eye(3) A[:2,:2] += np.random.randn(2,2)*0.2 titlestring = 'linear' # make a transformed grid # to move the points in the grid we use the forward transformation A AX0 = A[0,0]*X02d + A[0,1]*X12d + A[0,2] AX1 = A[1,0]*X02d + A[1,1]*X12d + A[1,2] stride = 5 ss.plot_grid(AX1, AX0, ax=ax_[0], rstride=stride, cstride=stride, color='r', linewidth=0.5, alpha=0.5) # make a transformed image # to transform the image we use the inverse transformatoin A^{-1} B = np.linalg.inv(A) X0s = B[0,0]*X02d + B[0,1]*X12d + B[0,2] X1s = B[1,0]*X02d + B[1,1]*X12d + B[1,2] # we use the built in interpolation function. # 1. we input our original grid points as a list of 1D vectors # 2. then input our original image # 3. then input our transformed grid points to resample the image at # Note that we need to "stack" this input into a 3D array, # where the first slice is the deformed X grid, and the second slice # is the deformed Y grid. # 4. Last we input our interpolation options dictionary using "**" for "unpacking" AI = spi.interpn([x0,x1],I2d,np.stack([X0s,X1s],axis=-1),**interp_args) ax_[0].imshow(AI, cmap='gray', extent=[x1[1],x1[-1],x0[0],x0[-1]], origin='lower') # make sure you set extent and origin! ax_[0].set_aspect('equal') ax_[0].set_title(titlestring) # let's show the vector field ax_[1].quiver(X12d[::stride,::stride], X02d[::stride,::stride], AX1[::stride,::stride]-X12d[::stride,::stride], AX0[::stride,::stride]-X02d[::stride,::stride]) ax_[1].set_aspect('equal') ax_[1].set_title('vector field') f.suptitle('Illustration of several matrix transformations in 2D') ###Output _____no_output_____ ###Markdown Now we'll show an example transformation in 3D ###Code # construct a transformation A = np.eye(4) A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation A[:3,-1] += np.random.randn(3)*1.0 # a random shift # generate the grid points that are transformed by inputs def sample_points_from_affine(X0,X1,X2,A): # find its inverse, using homogeneous coordinates B = np.linalg.inv(A) # get the sample points by matrix multiplication X0s = B[0,0]*X0 + B[0,1]*X1 + B[0,2]*X2 + B[0,3] X1s = B[1,0]*X0 + B[1,1]*X1 + B[1,2]*X2 + B[1,3] X2s = B[2,0]*X0 + B[2,1]*X1 + B[2,2]*X2 + B[2,3] return X0s,X1s,X2s # this is also defined in the summer school module X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) AI = spi.interpn( [x0,x1,x2], # this labels where in space each voxel is I, # this says the intensity of our image at each voxel np.stack([X0s,X1s,X2s],axis=-1), # this says where we'd like to evaluate the image **interp_args # some more arguments that we defined above ) # now draw it f,ax=plt.subplots(2,3) plt.subplots_adjust(wspace=0.45,hspace=0.35) ss.imshow_slices(x0,x1,x2,I,ax[0]) for a in ax[0]: a.set_title('before') a.set_xlabel('') ss.imshow_slices(x0,x1,x2,AI,ax[1]) for a in ax[1]: a.set_title('random transform') Irandom = AI ###Output _____no_output_____ ###Markdown Computing optimal transformationsAs with points, we will write down a sum of square error cost\begin{align*}E(A) = \int_X \frac{1}{2}(I(A^{-1}x) - J(x))^2 dx\end{align*}As in the point set case we'll take it's gradient with respect to $A$. However, since this problem is nonlinear, we will not be able to explicitly solve for $A$ by setting the result to 0. Instead, we'll iteratively make small improvements to our estimate of $A$ by taking steps in the negative of the gradient direction. This approach to optimization is widely used and is called gradient descent. Optimizing over translationLet's first consider a simpler problem involving translation $T$ only. Our square error cost will be \begin{align*}E(T) = \int_X \frac{1}{2}(I(x - T) - J(x))^2 dx\end{align*}We'll compute directional derivatives in the direction of $\delta T$, and use this to derive the gradient vector. We use the fact that\begin{align*}\frac{d}{d\epsilon}E(T + \epsilon \delta T)\bigg|_{\epsilon} &= (\nabla_T E) ^T \delta A\end{align*}This is just the definition of the directional derivative. It is equal to the gradient dot the direction.We are interested in the left hand side, which is just a derivative of a function with respect to a single scalar variable. We will use the chain rule\begin{align*}.\frac{d}{d\epsilon} E(T + \epsilon \delta T)\bigg|_{\epsilon = 0} &= \frac{d}{d\epsilon} \int_X \frac{1}{2}(I(x - T \epsilon \delta T) - J(x))^2 dx \bigg|_{\epsilon = 0}\\&= \int -[I(x - T) - J(x)] D I(x-T) dx \delta T\end{align*}Note that $DI$ is the image gradient as a 1x3 row vector, and $\nabla I$ the image gradient as a 3x1 column vector.We are free to choose $\delta T$ in whatever way we want, and taking it as each element of a basis gives us the gradient\begin{align*}\nabla E(T) &= \int -[I(x-T) - J(x)]\nabla I(x-T)dx\end{align*}A gradient descent algorithm would then be to choose an initial guess for $T$, choose a small step size $\epsilon$, and repeatedly update by\begin{align*}T \mapsto T - \epsilon \nabla_T E(T) = T - \epsilon \int -[I(x-T) - J(x)]\nabla I(x-T) dx\end{align*} Optimizing over affineNow we're ready to return to the affine transformation $A$. This derivation is more challenging, you may want to skip it and just use the final result.Since $A$ is a matrix, we'll consider an arbitrary perturbation to $A$, $A\mapsto A + \epsilon \delta A$, and take the gradient with respect to $\epsilon$ for any perturbation.\begin{align*}E(A + \epsilon \delta A) = \int_X \frac{1}{2}(I( (A + \epsilon \delta A)^{-1}x) - J(x))^2 dx\end{align*}We will use the fact that\begin{align}\frac{d}{d\epsilon}E(A + \epsilon \delta A) \bigg|_{\epsilon = 0} = \text{trace} \nabla E^T \delta A\end{align}This is just the definition of the directional derivative as the gradient dot the direction.We are interested in the left hand side, which is just a derivative of a function with respect to a single scalar variable. Let's consider this expression using the chain rule, first consider the square term\begin{align*}\frac{d}{d\epsilon}E(A + \epsilon \delta A) \bigg|_{\epsilon = 0} &= \int_X (I((A + \epsilon \delta A)^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\&=\int_X (I(A^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\\end{align*}Note that $DI$ is the image gradient as a 1x3 row vector, and $\nabla I$ the image gradient as a 3x1 column vector.Now consider the image\begin{align*}&= \int_X (I(A^{-1}x) - J(x)) DI((A + \epsilon \delta A)^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}x dx \bigg|_{\epsilon = 0}\\&= \int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}\bigg|_{\epsilon = 0} x dx \\\end{align*}Now the final term depends on taking the derivative of the inverse of a matrix. We can use the matrix by scalar identity, $\frac{d}{dt}M^{-1}(t) = - M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t)$ https://en.wikipedia.org/wiki/Matrix_calculusMatrix-by-scalar_identities .Plugging this in with $\epsilon = 0$ gives the result\begin{align*}\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0} = -\int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) A^{-1}\delta A A^{-1} x dx \end{align*}We can simplify this by recalling that $D[I(A^{-1}x)] = DI(A^{-1}x)A^{-1}$, giving\begin{align*}= -\int_X (I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx \end{align*}Finally to work out the gradient with respect to $A$, we have to write this expression as a gradient, dot $\delta A$. Taking the dot product on matrices using the trace gives\begin{align*}&= -\int_X \text{trace}(I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx \\&= -\int_X \text{trace}A^{-1} x (I(A^{-1}x) - J(x)) D[I(A^{-1}x)] dx \delta A\end{align*}which gives a gradient of \begin{align*}\nabla_A E &= -\int_X (I(A^{-1}x)-J) \nabla[I(A^{-1}x)](A^{-1}x)^Tdx\end{align*} Results of affine gradient calculationThe above derivation gives a gradient of \begin{align*}\nabla_A E &= -\int_X (I(A^{-1}x)-J) \nabla[I(A^{-1}x)](A^{-1}x)^Tdx\end{align*}A gradient descent algorithm would then be to choose an initial guess for $T$, choose a small step size $\epsilon$, and repeatedly update by\begin{align*}A \mapsto A - \epsilon \nabla_A E(A) = T - \epsilon \int_X -(I(A^{-1}x)-J) \nabla[I(A^{-1}x)](A^{-1}x)^T dx\end{align*}We implement this below. ###Code # load a second image to map to fname = os.path.join('mouse_images','PMD3097_orig_target_STS_clean.img') img = nib.load(fname) J = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it J = (J - np.mean(J))/np.std(J) J = ss.downsample_image(J,down) f,ax = plt.subplots(2,3) ss.imshow_slices(x0,x1,x2,J,ax[0]) ''' # note that the human MRI images in this repository have already been affine aligned into MNI space # let's add a small affine transformation and then try to recover it A = np.eye(4) A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation A[:3,-1] += np.random.randn(3)*2.0 # a random shift X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) J = spi.interpn([x0,x1,x2],J,np.stack([X0s,X1s,X2s],axis=-1),**interp_args) ss.imshow_slices(x0,x1,x2,J,ax[1]) ''' ' ' # now optimize over affine transformations # initialize a transformation A = np.eye(4) # choose a gradient descent step size # note that the linear part (L) and the translation part (T) often need to be on very different scales # for human epsilonL = 1.0e-12 epsilonT = 1.0e-9 # for mouse, standardized data epsilonL = 3.0e-5 epsilonT = 3.0e-4 # number of iterations of optimization niter = 25 # initialize some variables we'll display at every iteration EAll = [] # the energy, for plotting f,ax = plt.subplots(3,3) # a figure for plotting plt.subplots_adjust(wspace=0.45,hspace=0.45) # make the figure have a nicer layout for it in range(niter): # find the deformed image, by deforming the grid with the inverse, and using interpolation X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) AI = spi.interpn([x0,x1,x2],I,np.stack([X0s,X1s,X2s],axis=-1),**interp_args) # visualize it, we show the deforming atlas on the first row ss.imshow_slices(x0,x1,x2,AI,ax[0]) # get the error err = AI-J # we show the error on the second row ss.imshow_slices(x0,x1,x2,err,ax[1]) for a in ax[1]: a.set_xlabel('') # find the image gradient. This is the discrete centered difference, with given voxel size AI_0,AI_1,AI_2 = np.gradient(AI,dx[0],dx[1],dx[2]) # calculate energy and plot it E = np.sum(err**2*0.5)*np.prod(dx) EAll.append(E) ax[2,0].cla() ax[2,0].plot(EAll) ax[2,0].set_title('cost') ax[2,0].set_xlabel('iteration') # find the Energy gradient of the linear part using our derivation above gradL = np.empty((3,3)) for i,AI_i in enumerate([AI_0,AI_1,AI_2]): for j,AX_j in enumerate([X0s,X1s,X2s]): gradL[i,j] = -np.sum(err*AI_i*AX_j)*np.prod(dx) # find the Energy gradient of the translation part using our derivation above gradT = np.empty(3) for i,AI_i in enumerate([AI_0,AI_1,AI_2]): gradT[i] = -np.sum(err*AI_i)*np.prod(dx) # update using gradient descent A[:3,:3] -= epsilonL*gradL A[:3,-1] -= epsilonT*gradT # draw it in real time f.canvas.draw() # let's write out the transformation to a text file for the next tutorial with open('affine.txt','wt') as f: for i in range(4): for j in range(4): f.write('{} '.format(A[i,j])) f.write('\n') ###Output _____no_output_____ ###Markdown Linear transformations with imagesIn this module we will work with linearly aligning images. We'll apply transformations to images, and estimate optimal transformations. Here problems will be nonlinear, and we'll need to use iterative methods. ###Code import numpy as np %matplotlib notebook import matplotlib as mpl import matplotlib.pyplot as plt import nibabel as nib import os import summerschool as ss import scipy.interpolate as spi ###Output _____no_output_____ ###Markdown Load some data ###Code fname = os.path.join('mouse_images','PMD2052_orig_target_STS_clean.img') img = nib.load(fname) # load the image I = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it # downsample so it can run on people's laptops down = 3 I = ss.downsample_image(I,down) # get voxeldx = img.header['pixdim'][1:4]*down voxel size and number of voxels # note all the images in this dataset are in MNI space and are the same size and shape nx = I.shape dx = img.header['pixdim'][1:4]*down # set up a domain x0 = np.arange(nx[0])*dx[0] x1 = np.arange(nx[1])*dx[1] x2 = np.arange(nx[2])*dx[2] # lets define the origin to be in the middle of our image # linear transformations will be more reasonable this way x0 = x0 - np.mean(x0) x1 = x1 - np.mean(x1) x2 = x2 - np.mean(x2) X0,X1,X2 = np.meshgrid(x0,x1,x2,indexing='ij') ss.imshow_slices(x0,x1,x2,I) ###Output _____no_output_____ ###Markdown Transformations act on images through their inverse Images are deformed by sampling them at new points: interpolation ###Code interp_args = { 'method':'linear', # this says how we'd like to do interpolation, linear is fast and smooth 'bounds_error':False, # if we try to sample outside the image, do not raise an error 'fill_value':0 # if we try to sample outside the image, we'll return the value 0 } # A 2D example image I2d = np.array(I[:,:,I.shape[-1]//2]) X02d = X0[:,:,0] X12d = X1[:,:,0] # make a figure nplots = 5 f,ax = plt.subplots(2, nplots, sharex=True, sharey=True) for i in range(nplots): ax_ = ax[:,i] # choose a transformation if i == 0: A = np.eye(3) titlestring = 'identity' elif i == 1: T = np.random.randn(2)*2.0 A = np.array([[1,0,T[0]],[0,1,T[1]],[0,0,1]]) titlestring = 'translation' elif i == 2: theta = np.random.rand()*2.0*np.pi/6.0 A = np.eye(3) A[:2,:2]= [[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]] titlestring = 'rotation' elif i==3: s = np.random.randn()*0.1 + 1.0 A = np.eye(3) A[:2,:2] = np.eye(2)*s titlestring = 'scale' elif i == 4: A = np.eye(3) A[:2,:2] += np.random.randn(2,2)*0.2 titlestring = 'linear' # make a transformed grid AX0 = A[0,0]*X02d + A[0,1]*X12d + A[0,2] AX1 = A[1,0]*X02d + A[1,1]*X12d + A[1,2] stride = 5 ss.plot_grid(AX1, AX0, ax=ax_[0], rstride=stride, cstride=stride, color='r', linewidth=0.5, alpha=0.5) # make a transformed image B = np.linalg.inv(A) X0s = B[0,0]*X02d + B[0,1]*X12d + B[0,2] X1s = B[1,0]*X02d + B[1,1]*X12d + B[1,2] AI = spi.interpn([x0,x1],I2d,np.stack([X0s,X1s],axis=-1),**interp_args) ax_[0].imshow(AI, cmap='gray', extent=[x1[1],x1[-1],x0[0],x0[-1]], origin='lower') # make sure you set extent and origin! ax_[0].set_aspect('equal') ax_[0].set_title(titlestring) # let's show the vector field ax_[1].quiver(X12d[::stride,::stride], X02d[::stride,::stride], AX1[::stride,::stride]-X12d[::stride,::stride], AX0[::stride,::stride]-X02d[::stride,::stride]) ax_[1].set_aspect('equal') ax_[1].set_title('vector field') f.suptitle('Illustration of several matrix transformations in 2D') # construct a transformation A = np.eye(4) A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation A[:3,-1] += np.random.randn(3)*1.0 # a random shift def sample_points_from_affine(X0,X1,X2,A): # find its inverse, using homogeneous coordinates B = np.linalg.inv(A) # get the sample points by matrix multiplication X0s = B[0,0]*X0 + B[0,1]*X1 + B[0,2]*X2 + B[0,3] X1s = B[1,0]*X0 + B[1,1]*X1 + B[1,2]*X2 + B[1,3] X2s = B[2,0]*X0 + B[2,1]*X1 + B[2,2]*X2 + B[2,3] return X0s,X1s,X2s # this is defined in the summer school module X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) AI = spi.interpn( [x0,x1,x2], # this labels where in space each voxel is I, # this says the intensity of our image at each voxel np.stack([X0s,X1s,X2s],axis=-1), # this says where we'd like to evaluate the image **interp_args # some more arguments that we defined above ) f,ax=plt.subplots(2,3) plt.subplots_adjust(wspace=0.45,hspace=0.35) ss.imshow_slices(x0,x1,x2,I,ax[0]) for a in ax[0]: a.set_title('before') a.set_xlabel('') ss.imshow_slices(x0,x1,x2,AI,ax[1]) for a in ax[1]: a.set_title('random transform') Irandom = AI ###Output _____no_output_____ ###Markdown Computing optimal transformationsAs with points, we will write down a sum of square error cost\begin{align*}E(A) = \int_X \frac{1}{2}(I(A^{-1}x) - J(x))^2 dx\end{align*}And as before we'll take it's gradient with respect to $A$. Since $A$ is a matrix, we'll consider an arbitrary perturbation to $A$, $A\mapsto A + \epsilon \delta A$, and take the gradient with respect to $\epsilon$ for any perturbation.\begin{align*}E(\epsilon) = \int_X \frac{1}{2}(I( (A + \epsilon \delta A)^{-1}x) - J(x))^2 dx\end{align*}We will use the fact that\begin{align}\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0} = \text{trace} \nabla E^T \delta A\end{align}This is just the definition of the directional derivative, as the gradient dot the directoin.We are interested in\begin{align*}\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0}\end{align*}Let's attack this expression using the chain rule, first attack the square term\begin{align*}&= \int_X (I((A + \epsilon \delta A)^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\&=\int_X (I(A^{-1}x) - J(x)) \frac{d}{d\epsilon} I((A + \epsilon \delta A)^{-1}x)dx \bigg|_{\epsilon = 0}\\\end{align*}Now attack the image\begin{align*}&= \int_X (I(A^{-1}x) - J(x)) DI((A + \epsilon \delta A)^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}x dx \bigg|_{\epsilon = 0}\\&= \int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) \frac{d}{d\epsilon} (A + \epsilon \delta A)^{-1}\bigg|_{\epsilon = 0} x dx \\\end{align*}Now the final term depends on taking the derivative of the inverse of a matrix. Consider an arbitrary matrix $M$ that is a function of a parameter $t$. We can work out the derivative of the inverse by\begin{align*}\frac{d}{dt}M^{-1}(t) &=\frac{d}{dt}\left( M^{-1}(t)M(t)M^{-1}(t) \right)\\&= \frac{d}{dt}M^{-1}(t) M(t) M^{-1}(t) + M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t) + M^{-1}(t)M(t) \frac{d}{dt}M^{-1}(t)\\ &=\frac{d}{dt}\left( M^{-1}(t)M(t)M^{-1}(t) \right)\\&= \frac{d}{dt}M^{-1}(t) + M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t) + \frac{d}{dt}M^{-1}(t)\\\end{align*}Rearranging gives\begin{align*}\frac{d}{dt}M^{-1}(t) = - M^{-1}(t) \frac{d}{dt}M(t) M^{-1}(t)\end{align*}So in our problem we have\begin{align*}\frac{d}{dt}(A + \epsilon \delta A)^{-1} &= -(A + \epsilon \delta A)^{-1} \delta A (A + \epsilon \delta A)^{-1}\end{align*}Plugging this in with $\epsilon = 0$ gives the result\begin{align*}\frac{d}{d\epsilon}E(\epsilon) \bigg|_{\epsilon = 0} = -\int_X (I(A^{-1}x) - J(x)) DI(A^{-1}x) A^{-1}\delta A A^{-1} x dx \end{align*}Finally we can simplify this by recalling that $D[I(A^{-1}x)] = DI(A^{-1}x)A^{-1}$, giving\begin{align*}= -\int_X (I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx \end{align*}Finally to work out the gradient with respect to $A$, we have to write this expression as a gradient, dot $\delta A$. Taking the dot product on matrices using the trace gives\begin{align*}&= -\int_X \text{trace}(I(A^{-1}x) - J(x)) D[I(A^{-1}x)]\delta A A^{-1} x dx \\&= -\int_X \text{trace}A^{-1} x (I(A^{-1}x) - J(x)) D[I(A^{-1}x)] dx \delta A\end{align*}which gives a gradient of \begin{align*}-\int_X (I(A^{-1}x)-J) \nabla[I(A^{-1}x)](A^{-1}x)^Tdx\end{align*}We will use this to build a gradient descent algorithm. This is an iterative method, where we update date our current guess of $A$ by taking a "small step downhill", i.e. a small step in the direction opposite to the gradient. ###Code # load a second image to map to fname = os.path.join('mouse_images','PMD3097_orig_target_STS_clean.img') img = nib.load(fname) J = img.get_data()[:,:,:,0] # note last axes is time, we'd like to remove it J = ss.downsample_image(J,down) f,ax = plt.subplots(2,3) ss.imshow_slices(x0,x1,x2,J,ax[0]) ''' # note that these human MRI images have already been affine aligned into MNI space # let's add a small affine transformation and then try to recover it A = np.eye(4) A[:3,:3] += np.random.randn(3,3)*0.05 # a random deformation A[:3,-1] += np.random.randn(3)*2.0 # a random shift X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) J = spi.interpn([x0,x1,x2],J,np.stack([X0s,X1s,X2s],axis=-1),**interp_args) ss.imshow_slices(x0,x1,x2,J,ax[1]) ''' # initialize a transformation A = np.eye(4) # choose a gradient descent step size # note that the linear part and the translation part often need to be on very different scales # for human epsilonL = 1.0e-12 epsilonT = 1.0e-9 # for mouse epsilonL = 1.0e-8 epsilonT = 1.0e-7 niter = 50 EAll = [] f,ax = plt.subplots(3,3) plt.subplots_adjust(wspace=0.45,hspace=0.45) for it in range(niter): # find the deformed image X0s,X1s,X2s = ss.sample_points_from_affine(X0,X1,X2,A) AI = spi.interpn([x0,x1,x2],I,np.stack([X0s,X1s,X2s],axis=-1),**interp_args) ss.imshow_slices(x0,x1,x2,AI,ax[0]) # get the error err = AI-J ss.imshow_slices(x0,x1,x2,err,ax[1]) for a in ax[1]: a.set_xlabel('') # find the gradient AI_0,AI_1,AI_2 = np.gradient(AI,dx[0],dx[1],dx[2]) # calculate energy E = np.sum(err**2*0.5)*np.prod(dx) EAll.append(E) ax[2,0].cla() ax[2,0].plot(EAll) ax[2,0].set_title('cost') ax[2,0].set_xlabel('iteration') # find the gradient of the linear part gradL = np.empty((3,3)) for i,AI_i in enumerate([AI_0,AI_1,AI_2]): for j,AX_j in enumerate([X0s,X1s,X2s]): gradL[i,j] = -np.sum(err*AI_i*AX_j)*np.prod(dx) # find the gradient of the translation part gradT = np.empty(3) for i,AI_i in enumerate([AI_0,AI_1,AI_2]): gradT[i] = -np.sum(err*AI_i)*np.prod(dx) # update A[:3,:3] -= epsilonL*gradL A[:3,-1] -= epsilonT*gradT f.canvas.draw() # let's write out the transformation for the next tutorial with open('affine.txt','wt') as f: for i in range(4): for j in range(4): f.write('{} '.format(A[i,j])) f.write('\n') ###Output _____no_output_____
module4/s5_model_explorer.ipynb
###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["rue"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['fleuriste'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("pain", "boulanger") model.wv.similarity("maison", "habitation") model.wv.similarity("echevin", "bourgmestre") model.wv.similarity("maison_communale", "commune") model.wv.similarity("vanden_boeynants", "ministre") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("bourgmestre", topn=5) model.wv.most_similar("pain", topn=5) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("metro", topn=5) model.wv.most_similar("rue", topn=5) ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=15) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=5) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/one.txt") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["rue"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['fleuriste'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("rue", "fleuriste") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("rue", topn=10) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("bruxelles") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["budget"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['lois'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("budget", "lois") model.wv.similarity("services", "revenus") model.wv.similarity("ville","politique") model.wv.similarity("hospices","travaux") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("budget", topn=30) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("lois") model.wv.most_similar("services") model.wv.most_similar("revenus") model.wv.most_similar("ville") model.wv.most_similar("politique") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") model["clinique"] model['hospice'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("clinique", "hospice") model.wv.most_similar("hospice", topn=10) model.wv.most_similar("travaux") model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") #TP #Similarity model.wv.similarity("plainte", "travaux_publics") model.wv.similarity("lemonnier", "écrivain") model.wv.similarity("hygiène", "maladie") #Most similar model.wv.most_similar("maladie", topn = 50) model.wv.most_similar("mortalité", topn = 50) model.wv.most_similar("mort", topn = 50) model.wv.most_similar("accouchement", topn = 50) model.wv.most_similar("mortalité", topn = 50) model.wv.most_similar(positive=['échevin', 'femme'], negative=['homme'], topn=30) model.wv.most_similar(positive=['échevin', 'homme'], negative=['femme'], topn=30) model.wv.most_similar(positive=['parc_léopold', 'france', 'paris'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['musée', 'france', 'paris'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['parc', 'france', 'paris'], negative=['bruxelles'], topn=1) ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["rue"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['fleuriste'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("enfant", "mort") model.wv.similarity("enfants", "malades") model.wv.similarity("femmes", "malades") model.wv.similarity("hommes", "malades") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("rue", topn=10) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("bruxelles") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["rue"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['fleuriste'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("rue", "fleuriste") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("rue", topn=10) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("bruxelles") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["droit"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model["enfant"] model["intérêt"] model["finances"] model["projet"] model["établissement"] # Quel est leur similarité ? model.wv.similarity("droit", "enfant") model.wv.similarity("intérêt", "finances") model.wv.similarity("projet", "établissement") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("droit", topn=5) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("enfant", topn=5) model.wv.most_similar("intérêt", topn=5) model.wv.most_similar("finances", topn=6) model.wv.most_similar("projet", topn=5) model.wv.most_similar("établissement", topn=5) ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "journal" ? ###Code model["journal"] ###Output _____no_output_____ ###Markdown Et maison ? ###Code model['maison'] model['avenue'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("journal", "maison") model.wv.similarity("docteur", "professeur") model.wv.similarity("jour", "semaine") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de journal, maison, lundi ? ###Code model.wv.most_similar("journal", topn=10) ###Output _____no_output_____ ###Markdown Et de maison et lundi ? ###Code model.wv.most_similar("maison", topn=10) model.wv.most_similar("lundi", topn=10) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") ###Output _____no_output_____ ###Markdown Comment est représenté le mot "rue" ? ###Code model["imprimerie"] ###Output _____no_output_____ ###Markdown Et fleuriste ? ###Code model['fleuriste'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("agent", "immobilier") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche de rue ? ###Code model.wv.most_similar("location", topn=10) ###Output _____no_output_____ ###Markdown Et de Bruxelles ? ###Code model.wv.most_similar("appartement") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['achat', 'maison'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____ ###Markdown Charger le modèle que nous venons de créer ###Code model = Word2Vec.load("../data/bulletins.model") model["bourgmestre"] model['art'] model ['subside'] model ['crédit'] model ['école'] model ['élève'] ###Output _____no_output_____ ###Markdown Quel est leur similarité ? ###Code model.wv.similarity("bourgmestre", "art") model.wv.similarity("subside", "crédit") model.wv.similarity("vandergeten", "instruction") ###Output _____no_output_____ ###Markdown Quel mot est le plus proche ###Code model.wv.most_similar("bourgmestre", topn=10) model.wv.most_similar("art") model.wv.most_similar("subside") model.wv.most_similar ("crédit") model.wv.most_similar ("école") model.wv.most_similar ("élève") ###Output _____no_output_____ ###Markdown Comment obtenir une ville de France grâce à notre modèle ? ###Code model.wv.most_similar(positive=['bruxelles', 'france'], negative=['belgique'], topn=1) model.wv.most_similar(positive=['bruxelles', 'liege', 'france'], negative=['belgique'], topn=1) ###Output _____no_output_____
Basic Crawling Seminar.ipynb
###Markdown 크롤링(Crawling) : 자동화된 방식으로 웹(web)을 탐색 스크래핑(Scraping) : 테이터를 수집하는 행위 필요한 라이브러리 : requrests, beautifulsoup . Requests : 파이썬에서 웹요청을 보낼 수 있게 해주는 라이브러리 공식 문서 : http://docs.python-requests.org/en/master/ . Beautifulsoup : 웹페이지 파싱 라이브러리 - Parsing : 언어학에서 구문 분석이라고 하며, 컴퓨터 공학에서 문서를 읽고 해석하여 태그명, 속성명, 속성값 및 엘리먼트 내용을 분리하는 것을 의미한다. 공식문서 : http://www.crummy.com/software/BeautifulSoup/bs4/doc/ 1. 간단한 금융 관련 정보 수집 ###Code import requests from bs4 import BeautifulSoup URL = 'https://m.stock.naver.com/index.nhn' # 네이버 증권 response = requests.get(url = URL) # 해당 url에 요청보냄 print(response) # HTTP Status Code print(response.text) # 웹 페이지 확인 soup = BeautifulSoup(response.text, 'html.parser') print(soup) print(soup.find("span")) print(soup.find_all("span")) print(soup.find_all("span",{"class" : "stock_price stock_dn"})) data = soup.find_all("span",{"class" : "stock_price stock_dn"}) get_kospi = data[0].text print("KOSPI : {}".format(get_kospi)) get_kosdaq = data[1].text print("KOSDAQ : {}".format(get_kosdaq)) ###Output KOSPI : 2,208.88 KOSDAQ : 682.92 ###Markdown 2. 네이버 자동차관련 포스트 정보 수집 ###Code import requests from bs4 import BeautifulSoup URL = 'https://post.naver.com/subject/list.nhn?navigationType=push&categoryNo=57&subjectType=CATEGORY&mainMenu=CARGAME' # 네이버 포스트 자동차 response = requests.get(url = URL) soup = BeautifulSoup(response.text, 'html.parser') print(soup.find_all("div",{"class" : "spot_post_name"})) get_title_all = soup.find_all("div",{"class" : "spot_post_name"}) for i in get_title_all: print(i.text) title = [] for i in get_title_all: title.append(i.text.replace('\n','').replace('\t','')) for i in title: print(i) print(len(title)) print(title[0]) print(title[1]) ###Output 18 나의 첫 BMW, 산 거 후회하냐고 물으신다면... 신형 쏘렌토, 2.2 디젤에 8단 습식 DCT 적용 ###Markdown 3. 신상품 정보 수집 및 DB(SQLite3) 활용 ###Code import requests from bs4 import BeautifulSoup URL = 'https://www.eleparts.co.kr/goods_ele/main?code=VC14' # 엘레파츠 테스트/계측기/광학 카테고리 response = requests.get(url = URL) soup = BeautifulSoup(response.text, 'html.parser') print(soup.find_all("h3",{"class" : "photo_box_title"})) get_all_title = soup.find_all("h3",{"class" : "photo_box_title"}) # 상품명 title = [] for i in get_all_title: title.append(i.text) print(title) #print(soup.find_all("a",{"class" : "procBox"})) get_all_title = soup.find_all("a",{"class" : "procBox"}) title =[] # 상품명 exp = [] # 상품설명 price =[] # 상품 가격 img =[] # 상품 이미지 for i in get_all_title: # print(i.text) # print(i.find('img')['src']) # print('*'*100) img.append(i.find('img')['src']) title.append(i.find('h3').text) exp.append(i.find('p').text) price.append(int(i.find('i').text.replace(',','').replace(' ','').replace('원',''))) # 수집한 데이터를 DataFrame 형태로 저장 from pandas import DataFrame result = DataFrame() result['TITLE'] = title result['EXP'] = exp result['PRICE'] = price print(result) # DB에 데이터 저장 import sqlite3 import pandas.io.sql as pd_sql con = sqlite3.connect("Test.db") result.to_sql('items', con, if_exists='append') # TITLE을 기준으로 중복데이터는 제거 sql = "DELETE FROM items WHERE rowid NOT IN (SELECT Max(rowid) FROM items GROUP BY TITLE order by TITLE)" pd_sql.execute(sql, con) con.commit() con.close() # DB에서 데이터 불러오기 import pandas as pd con = sqlite3.connect("Test.db") df = pd.read_sql('select * from items', con=con) con.close() print(df) ###Output index TITLE \ 0 0 BU-P4243-0 1 1 H345313100 2 2 CT2060-25-2 3 3 66.9196-24 4 4 S-0-D-1-G-660 S/C 5 5 PK001 6 6 CL681563 7 7 BU-3110410-0 8 8 BU-P1825-8 9 9 BU-P3788 10 10 BU-P72914-0 11 11 BU-P72914-2 12 12 6096 13 13 T3PP300 14 14 CT4026 15 15 N4822A 16 16 6245-48-02 17 17 CT2521-100-6 18 18 EX60-60 Switching Type Programmable DC Power S... 19 19 EX80-105 Switching Type Programmable DC Power ... 20 20 [BE038] Coms 바나나 케이블, 1Set/악어클립 (Red/Black) 21 21 CT3249-9 22 22 S001 - 스마트폰 현미경 23 23 [DSO Nano v3] 포켓형 컬러 오실로스코프 24 24 FLUKE-17B+ 25 25 FLUKE-101(포켓테스터) 26 26 FLUKE-15B+ 27 27 [에프티랩] 스마트 라돈측정기 라돈아이 [RD200] 28 28 PCB 자 15cm 29 29 USB 전압/전류 측정기(USB2.0 & 3.0 호환) 30 30 HDS-1021M-N 핸디형 디지털 오실로스코프 31 31 멀티메터[MAS838](MASTECH정품) 32 32 HiOKi 3244-60 CARD HiTester 33 33 MT4Y-DV-4N(표시전용) 34 34 MK3003D 정밀급 디지털파워서플라이 35 35 [UW-EAA] Compact 스마트폰 장착 열화상 카메라(안드로이드) EXP PRICE 0 테스트 플러그 & 테스트 잭 DBL BINDING POST BLK CROSS POST 11360 1 디지털 패널 미터 4.5,9-36VDC,20VDC,4-20MA 764080 2 테스트 도선 LEAD 4mm P-P - PVC 0.75 25cm RED 6070 3 BANANA JACK, 4MM, 32A, SCREW, YELLOW 6850 4 접촉 프로브 SERIES S, SIZE 0 PROBE 5 3160 5 테스트 프로브 PROBE ACCESSORIES FOR PP001/PP002 61940 6 BINDING POST, 15A, PANEL, GRN 3200 7 CONN, PLUG, 45A, 600V, BLACK 11960 8 테스트 플러그 & 테스트 잭 STKBL BANANA PLUG, GREY 15A 2220 9 테스트 플러그 & 테스트 잭 18440 10 테스트 플러그 & 테스트 잭 4MM BANANA PLUG TO 2M JACK 4150 11 테스트 플러그 & 테스트 잭 4MM BANANA PLUG TO 2M JACK 4150 12 테스트 플러그 & 테스트 잭 .175 TIP JACK UN-INS 1800 13 테스트 프로브 T3DSO PASSIVE PROBE 300MHz 300V/600V 138590 14 테스트 프로브 HV OPROBE 18 kV 150 MHz-2.0m, BNC(m) 699460 15 테스트 프로브 SOCKETED TIP FOR APPLICATION FIXTURES 128680 16 테스트 도선 MINIGBR W/ST PLUG (SET) 28420 17 테스트 도선 4mmStkShth P-P-SILIC 0.75 100cm BLUE 13360 18 1채널, 0~63.0V/0~63.0A, 3600W, Display Resolutio... 3400000 19 1채널, 0~84.0V/0~110.3A, 8400W, Display Resoluti... 7600000 20 9730 21 CONN BANANA PLUG SLDRLESS WHITE, 바나나 플러그 Conne... 7034 22 배율 : 200 X/해상도 : 적용 스마트 폰의 해상도/전용 App 기본 기능 : ... 12000 23 포켓 사이즈의 32비트 호환 디지털 스토리지 오실로스코프 120000 24 Fluke 10 시리즈는 디지털 멀티미터로 측정하는 대부분의 기능을 포함하고 있는 ... 140000 25 DC 정확도 0.5%, 초소형 초경량의 포켓사이즈 38500 26 Fluke 10 시리즈는 디지털 멀티미터로 측정하는 대부분의 기능을 포함하고 있는 ... 130000 27 라돈 측정, 라돈가스, 라돈 검출기,가정용,유효측정1시간,블루투스 연동 180000 28 PCB 15 센치메터 PCB 참조 자 3200 29 OLED가 부착되어 있어 간편하게 USB만 연결하면 전압,전력 측정가능(최대 7V ... 18000 30 20MHz, 100MS/s, 1채널 (3 in 1 DSO+Multimeter+Cym... 328500 31 디지털멀티메터/1999카운트/DC전압 및 전류, AC전압,저항,온도,다이오드,도통테... 14800 32 충실한 기능의포켓형멀티메터미려한 투명하드케이스 38000 33 DC전압측정 / 자유자재로 다양한 기능설정이 가능한 고정도 측정을 실현한 멀티 판넬... 42000 34 Voltage Range:30V, Current Range:3A, Power Ran... 140000 35 Android, 해상도 206x156, 온도 -40~330ºC, 저전력소모(스마트폰... 300000 ###Markdown 4. 영화 예매순위 ###Code import requests from bs4 import BeautifulSoup URL = 'http://ticket2.movie.daum.net/Movie/MovieRankList.aspx' # 다음 영화 예매 / 영화 예매순위 1~20위 response = requests.get(url = URL) soup = BeautifulSoup(response.text, 'html.parser') print(soup) # print(soup.find_all("strong",{"class" : "tit_join"})) get_all_title = soup.find_all("strong",{"class" : "tit_join"}) # 예매 순위 영화 제목 title = [] for i in get_all_title: title.append(i.text.replace('\r','').replace('\n','').replace(' ','')) print(title) get_all_score = soup.find_all("em",{"class" : "emph_grade"}) # 예매 순위 영화 평점 score = [] for i in get_all_score: score.append(i.text.replace('\r','').replace('\n','').replace(' ','')) print(score) # 수집한 데이터를 DataFrame 형태로 저장 from pandas import DataFrame result = DataFrame() result['TITLE'] = title result['SCORE'] = score print(result) ###Output TITLE SCORE 0 정직한후보 7.8 1 작은아씨들 7.7 2 클로젯 7.2 3 기생충 7.9 4 수퍼소닉 6.9 5 남산의부장들 8.4 6 버즈오브프레이 6.9 7 극장판미니특공대:공룡왕디노 7.9 8 조조래빗 8.5 9 히트맨 6.8 10 극장판원피스스탬피드 7.8 11 지푸라기라도잡고싶은짐승들 8.9 12 인셉션 8.7 13 1917 7.3 14 타오르는여인의초상 8.3 15 이멋진세계에축복을!붉은전설 7.7 16 페인앤글로리 7.6 17 문신을한신부님 8.5 18 스파이지니어스 8.6 19 하이,젝시 8.6 ###Markdown 5. 국내 자동차 판매 순위 ###Code import requests from bs4 import BeautifulSoup URL = 'http://auto.danawa.com/newcar/?Work=record' # 다나와 자동차 response = requests.get(url = URL) soup = BeautifulSoup(response.text, 'html.parser') print(soup) ###Output <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head><meta content="TEXT/HTML; CHARSET=utf-8" http-equiv="CONTENT-TYPE"/><title>Error</title></head><body><h2>Error</h2><table bgcolor="#FEEE7A" border="0" cellpadding="0" cellspacing="0" summary="Error" width="400"><tr><td><table border="0" cellpadding="3" cellspacing="1" summary="Error"><tr align="left" bgcolor="#FBFFDF" valign="top"><td><strong>Error</strong></td></tr><tr bgcolor="#FFFFFF" valign="top"><td>This page can't be displayed. Contact support for additional information.<br/>The incident ID is: 6662400083992615579.</td></tr></table></td></tr></table></body></html> ###Markdown URL은 이상이 없지만, 크롤링 시 에러가 발생했다. 접속을 할 때 어느정도의 시간이 걸리는 것이 확인되어 Selenium을 이용한다. Selenium : 사용자 대신 프로그램이 웹 프로그램을 제어할 수 있게 해주는 라이버러리https://www.seleniumhq.org ###Code import time import requests from bs4 import BeautifulSoup from selenium import webdriver URL = 'http://auto.danawa.com/newcar/?Work=record' # 다나와 자동차 driver = webdriver.Chrome("chromedriver.exe") # 크롬드라이버를 이용해서 크롬 창을 띄운다. driver.get(URL) time.sleep(1) # 페이지가 완전히 오픈될 때까지 기다린다. html = driver.page_source soup = BeautifulSoup(html, 'lxml') driver.quit() print(soup) get_all_title = soup.find_all("td",{"class" : "title"}) # 국산 판매 순위별 차량명 print(get_all_title) data = [] for i in get_all_title: data.append(i.text.replace('\n','').replace('\t','').replace(' ','')) print(data) cars = data[-20:] print(cars) print("<국산차량 판매순위>") 국산차량 = data[-20:-10] print(국산차량) print("*"*130) print("<해외차량 판매순위>") 해외차량 = data[-10:] print(해외차량) ###Output <국산차량 판매순위> ['K5', '포터2', '더뉴그랜저', '쏘나타', '팰리세이드', '봉고3', 'K7', 'QM6', '셀토스', '카니발'] ********************************************************************************************************************************** <해외차량 판매순위> ['E-Class', 'Arteon', 'TheNewS-Class', '5Series', 'TheNewGLC-Class', 'Explorer', 'TheNewCLS', 'Tiguan', 'New6Series', 'TheNewC-Class']
notebooks/conference_notebooks/pycon_nlp/01_pride_and_predjudice.ipynb
###Markdown Pride & Prejudice analysis Real text analysisWe got familiar with Spacy. In the next section we are going to analyse a real text (Pride & Prejudice). We would like to:* Extract the names of all the characters from the book (e.g. Elizabeth, Darcy, Bingley)* Visualize characters' occurences with regards to relative position in the book* Authomatically describe any character from the book* Find out which characters have been mentioned in a context of marriage* Build keywords extraction that could be used to display a word cloud ([example](http://www.cytora.com/data-samples.html)) Load text file ###Code def read_file(file_name): with open(file_name, 'r') as file: return file.read().decode('utf-8') ###Output _____no_output_____ ###Markdown Process full text ###Code import spacy nlp = spacy.load('en') # Process `text` with Spacy NLP Parser text = read_file('data/pride_and_prejudice.txt') processed_text = nlp(text) # How many sentences are in the book (Pride & Prejudice)? sentences = [s for s in processed_text.sents] print(len(sentences)) # Print sentences from index 10 to index 15, to make sure that we have parsed the correct book print(sentences[10:15]) ###Output 6138 ["My dear Mr. Bennet," said his lady to him one day, "have you heard that Netherfield Park is let at last?" , Mr. Bennet replied that he had not. ", But it is," returned she; "for Mrs. Long has just been here, and she told me all about it." , Mr. Bennet made no answer. , "Do you not want to know who has taken it?" cried his wife impatiently. ] ###Markdown Find all the personal names ###Code # Extract all the personal names from Pride & Prejudice and count their occurrences. # Expected output is a list in the following form: [('elizabeth', 622), ('darcy', 312), ('jane', 286), ('bennet', 266) ...]. from collections import Counter, defaultdict def find_character_occurences(doc): """ Return a list of actors from `doc` with corresponding occurences. :param doc: Spacy NLP parsed document :return: list of tuples in form [('elizabeth', 622), ('darcy', 312), ('jane', 286), ('bennet', 266)] """ characters = Counter() for ent in processed_text.ents: if ent.label_ == 'PERSON': characters[ent.lemma_] += 1 return characters.most_common() print(find_character_occurences(processed_text)[:20]) ###Output [(u'elizabeth', 622), (u'darcy', 312), (u'jane', 286), (u'bennet', 266), (u'bingley', 204), (u'wickham', 183), (u'collins', 178), (u'lydia', 162), (u'lizzy', 94), (u'gardiner', 92), (u'lady catherine', 71), (u'kitty', 71), (u'mary', 36), (u'william', 33), (u'hurst', 32), (u'phillips', 30), (u'forster', 26), (u'longbourn', 26), (u'miss bingley', 25), (u'lucas', 21)] ###Markdown Plot characters personal names as a time series ###Code # Matplotlib Jupyter HACK %matplotlib inline import matplotlib import numpy as np import matplotlib.pyplot as plt # Plot characters' mentions as a time series relative to the position of the actor's occurrence in a book. def get_character_offsets(doc): """ For every character in a `doc` collect all the occurences offsets and store them into a list. The function returns a dictionary that has actor lemma as a key and list of occurences as a value for every character. :param doc: Spacy NLP parsed document :return: dict object in form {'elizabeth': [123, 543, 4534], 'darcy': [205, 2111]} """ character_offsets = defaultdict(list) for ent in doc.ents: if ent.label_ == 'PERSON': character_offsets[ent.lemma_].append(ent.start) return dict(character_offsets) character_occurences = get_character_offsets(processed_text) from matplotlib.pyplot import hist from cycler import cycler NUM_BINS = 10 def normalize(occurencies, normalization_constant): return [o / float(len(processed_text)) for o in occurencies] def plot_character_timeseries(character_offsets, character_labels, normalization_constant=None): """ Plot characters' personal names specified in `character_labels` list as time series. :param character_offsets: dict object in form {'elizabeth': [123, 543, 4534], 'darcy': [205, 2111]} :param character_labels: list of strings that should match some of the keys in `character_offsets` :param normalization_constant: int """ x = [character_offsets[character_label] for character_label in character_labels] with plt.style.context('fivethirtyeight'): plt.figure() n, bins, patches = plt.hist(x, NUM_BINS, label=character_labels) plt.clf() ax = plt.subplot(111) for i, a in enumerate(n): ax.plot([float(x) / (NUM_BINS - 1) for x in range(len(a))], a, label=character_labels[i]) matplotlib.rcParams['axes.prop_cycle'] = cycler(color=['r','k','c','b','y','m','g','#54a1FF']) ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) #plot_character_timeseries(character_occurences, ['darcy', 'bingley'], normalization_constant=len(processed_text)) plot_character_timeseries(character_occurences, ['darcy', 'bingley']) ###Output _____no_output_____ ###Markdown Spacy parse tree in action ###Code # Find words (adjectives) that describe Mr. Darcy. def get_character_adjectives(doc, character_lemma): """ Find all the adjectives related to `character_lemma` in `doc` :param doc: Spacy NLP parsed document :param character_lemma: string object :return: list of adjectives related to `character_lemma` """ adjectives = [] for ent in processed_text.ents: if ent.lemma_ == character_lemma: for token in ent.subtree: if token.pos_ == 'ADJ': # Replace with if token.dep_ == 'amod': adjectives.append(token.lemma_) for ent in processed_text.ents: if ent.lemma_ == character_lemma: if ent.root.dep_ == 'nsubj': for child in ent.root.head.children: if child.dep_ == 'acomp': adjectives.append(child.lemma_) return adjectives print(get_character_adjectives(processed_text, 'darcy')) # Find characters that are 'talking', 'saying', 'doing' the most. Find the relationship between # entities and corresponding root verbs. character_verb_counter = Counter() VERB_LEMMA = 'say' for ent in processed_text.ents: if ent.label_ == 'PERSON' and ent.root.head.lemma_ == VERB_LEMMA: character_verb_counter[ent.text] += 1 print(character_verb_counter.most_common(10)) # Find all the characters that got married in the book. # # Here is an example sentence from which this information could be extracted: # # "her mother was talking to that one person (Lady Lucas) freely, # openly, and of nothing else but her expectation that Jane would soon # be married to Mr. Bingley." # ###Output [(u'Elizabeth', 42), (u'Bennet', 30), (u'Jane', 15), (u'Miss Bingley', 9), (u'Lizzy', 6), (u'Gardiner', 5), (u'Lydia', 4), (u'Darcy', 4), (u'Wickham', 4), (u'Bingley', 4)] ###Markdown Extract Keywords ###Code # Extract Keywords using noun chunks from the news article (file 'article.txt'). # Spacy will pick some noun chunks that are not informative at all (e.g. we, what, who). # Try to find a way to remove non informative keywords. article = read_file('data/article.txt') doc = nlp(article) keywords = Counter() for chunk in doc.noun_chunks: if nlp.vocab[chunk.lemma_].prob < - 8: # probablity value -8 is arbitrarily selected threshold keywords[chunk.lemma_] += 1 keywords.most_common(20) ###Output _____no_output_____
colab-example.ipynb
###Markdown [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/ganevgv/colab-example/blob/master/colab-example.ipynb) Setup ###Code # git clone the repo !git clone https://github.com/ganevgv/colab-example.git # change directory %cd ./colab-example # install the requirements !pip install -r requirements.txt ###Output _____no_output_____ ###Markdown Run simple code ###Code from world import World w = World(name='Kind Stranger') w.greet() ###Output Hello, Kind Stranger! Your random number is 0.6779
examples/Notebooks/flopy3_modpath7_create_simulation.ipynb
###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) print('flopy version: {}'.format(flopy.__version__)) if not os.path.exists("data"): os.mkdir("data") # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317. riv_c = 1.e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join('data', 'mp7_ex1_cs') nm = 'ex01_mf6' # Create the Flopy simulation object sim = flopy.mf6.MFSimulation(sim_name=nm, exe_name=mfexe, version='mf6', sim_ws=ws) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=[pd]) # Create the Flopy groundwater flow (gwf) model object model_nam_file = '{}.nam'.format(nm) gwf = flopy.mf6.ModflowGwf(sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='SIMPLE', outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, length_units='FEET', delr=delr, delc=delc, top=top, botm=botm) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(gwf, pname='npf', icelltype=laytyp, k=kh, k33=kv) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf, maxbound=1, stress_period_data={0: wd}) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = '{}.hds'.format(nm) head_record = [headfile] budgetfile = '{}.cbb'.format(nm) budget_record = [budgetfile] saverecord = [('HEAD', 'ALL'), ('BUDGET', 'ALL')] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, 'mf6 model did not run' ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.1.1 06/12/2020 MODFLOW 6 compiled Jun 12 2020 12:02:16 with IFORT compiler (ver. 19.0.5) This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Also refer to the USGS Water Resources Software User Rights Notice for complete use, copyright, and distribution information. Run start date and time (yyyy/mm/dd hh:mm:ss): 2020/06/26 9:39:48 Writing simulation list file: mfsim.lst Using Simulation name file: mfsim.nam Solving: Stress period: 1 Time step: 1 Run end date and time (yyyy/mm/dd hh:mm:ss): 2020/06/26 9:39:48 Elapsed run time: 0.032 Seconds WARNING REPORT: 1. NONLINEAR BLOCK VARIABLE 'OUTER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING OUTER_DVCLOSE TO OUTER_HCLOSE VALUE. 2. LINEAR BLOCK VARIABLE 'INNER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING INNER_DVCLOSE TO INNER_HCLOSE VALUE. Normal termination of simulation. ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]['cellid'] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + '_mp_forward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamf, trackdir='forward', flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Jun 12 2020 12:05:21 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow Particle Summary: 0 particles are pending release. 0 particles remain active. 0 particles terminated at boundary faces. 0 particles terminated at weak sink cells. 0 particles terminated at weak source cells. 1260 particles terminated at strong source/sink cells. 0 particles terminated in cells with a specified zone number. 0 particles were stranded in inactive or dry cells. 0 particles were unreleased. 0 particles have an unknown status. Normal termination. ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + '_mp_backward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamb, trackdir='backward', flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew+nodesr, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Jun 12 2020 12:05:21 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow Particle Summary: 0 particles are pending release. 0 particles remain active. 2750 particles terminated at boundary faces. 0 particles terminated at weak sink cells. 0 particles terminated at weak source cells. 0 particles terminated at strong source/sink cells. 0 particles terminated in cells with a specified zone number. 0 particles were stranded in inactive or dry cells. 0 particles were unreleased. 0 particles have an unknown status. Normal termination. ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + '.mppth') p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + '.mpend') e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ['green', 'orange', 'red'] f, axes = plt.subplots(ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10)) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('Well pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('River pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction='starting', colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction='starting', colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + '.mppth') p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + '.mpend') e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pwb, layer='all', color='blue', lw=0.5, linestyle=':', label='captured by wells') mm.plot_endpoint(ewb, direction='ending') #, colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(prb, layer='all', color='green', lw=0.5, linestyle=':', label='captured by rivers') plt.tight_layout(); ###Output _____no_output_____ ###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) print('flopy version: {}'.format(flopy.__version__)) if not os.path.exists("data"): os.mkdir("data") # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317. riv_c = 1.e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join('data', 'mp7_ex1_cs') nm = 'ex01_mf6' # Create the Flopy simulation object sim = flopy.mf6.MFSimulation(sim_name=nm, exe_name=mfexe, version='mf6', sim_ws=ws) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=[pd]) # Create the Flopy groundwater flow (gwf) model object model_nam_file = '{}.nam'.format(nm) gwf = flopy.mf6.ModflowGwf(sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='SIMPLE', outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, length_units='FEET', delr=delr, delc=delc, top=top, botm=botm) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(gwf, pname='npf', icelltype=laytyp, k=kh, k33=kv) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf, maxbound=1, stress_period_data={0: wd}) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = '{}.hds'.format(nm) head_record = [headfile] budgetfile = '{}.cbb'.format(nm) budget_record = [budgetfile] saverecord = [('HEAD', 'ALL'), ('BUDGET', 'ALL')] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, 'mf6 model did not run' ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.1.0 12/12/2019 MODFLOW 6 compiled Dec 13 2019 12:29:49 with IFORT compiler (ver. 19.0.5) This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Also refer to the USGS Water Resources Software User Rights Notice for complete use, copyright, and distribution information. Run start date and time (yyyy/mm/dd hh:mm:ss): 2019/12/14 15:42:51 Writing simulation list file: mfsim.lst Using Simulation name file: mfsim.nam Solving: Stress period: 1 Time step: 1 Run end date and time (yyyy/mm/dd hh:mm:ss): 2019/12/14 15:42:51 Elapsed run time: 0.033 Seconds Normal termination of simulation. ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]['cellid'] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + '_mp_forward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamf, trackdir='forward', flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Dec 13 2019 12:32:13 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow Particle Summary: 0 particles are pending release. 0 particles remain active. 0 particles terminated at boundary faces. 0 particles terminated at weak sink cells. 0 particles terminated at weak source cells. 1260 particles terminated at strong source/sink cells. 0 particles terminated in cells with a specified zone number. 0 particles were stranded in inactive or dry cells. 0 particles were unreleased. 0 particles have an unknown status. Normal termination. ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + '_mp_backward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamb, trackdir='backward', flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew+nodesr, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Dec 13 2019 12:32:13 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow Particle Summary: 0 particles are pending release. 0 particles remain active. 2750 particles terminated at boundary faces. 0 particles terminated at weak sink cells. 0 particles terminated at weak source cells. 0 particles terminated at strong source/sink cells. 0 particles terminated in cells with a specified zone number. 0 particles were stranded in inactive or dry cells. 0 particles were unreleased. 0 particles have an unknown status. Normal termination. ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + '.mppth') p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + '.mpend') e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ['green', 'orange', 'red'] f, axes = plt.subplots(ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10)) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('Well pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('River pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction='starting', colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction='starting', colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + '.mppth') p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + '.mpend') e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pwb, layer='all', color='blue', lw=0.5, linestyle=':', label='captured by wells') mm.plot_endpoint(ewb, direction='ending') #, colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(prb, layer='all', color='green', lw=0.5, linestyle=':', label='captured by rivers') plt.tight_layout(); ###Output _____no_output_____ ###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join("..", "..")) sys.path.append(fpth) import flopy print(sys.version) print("numpy version: {}".format(np.__version__)) print("matplotlib version: {}".format(mpl.__version__)) print("flopy version: {}".format(flopy.__version__)) if not os.path.isdir("data"): os.makedirs("data", exist_ok=True) # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1.0, 1.0 nlay, nrow, ncol = 3, 21, 20 delr = delc = 500.0 top = 400.0 botm = [220.0, 200.0, 0.0] laytyp = [1, 0, 0] kh = [50.0, 0.01, 200.0] kv = [10.0, 0.01, 20.0] wel_loc = (2, 10, 9) wel_q = -150000.0 rch = 0.005 riv_h = 320.0 riv_z = 317.0 riv_c = 1.0e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join("data", "mp7_ex1_cs") nm = "ex01_mf6" # Create the Flopy simulation object sim = flopy.mf6.MFSimulation( sim_name=nm, exe_name=mfexe, version="mf6", sim_ws=ws ) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis( sim, pname="tdis", time_units="DAYS", nper=nper, perioddata=[pd] ) # Create the Flopy groundwater flow (gwf) model object model_nam_file = "{}.nam".format(nm) gwf = flopy.mf6.ModflowGwf( sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True ) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms( sim, pname="ims", complexity="SIMPLE", outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6, ) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis( gwf, pname="dis", nlay=nlay, nrow=nrow, ncol=ncol, length_units="FEET", delr=delr, delc=delc, top=top, botm=botm, ) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname="ic", strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf( gwf, pname="npf", icelltype=laytyp, k=kh, k33=kv ) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel( gwf, maxbound=1, stress_period_data={0: wd} ) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = "{}.hds".format(nm) head_record = [headfile] budgetfile = "{}.cbb".format(nm) budget_record = [budgetfile] saverecord = [("HEAD", "ALL"), ("BUDGET", "ALL")] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc( gwf, pname="oc", saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record, ) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, "mf6 model did not run" ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha_0... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]["cellid"] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + "_mp_forward" # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7( modelname=mpnamf, trackdir="forward", flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe, ) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Aug 01 2021 12:57:00 with IFORT compiler (ver. 19.10.3) ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + "_mp_backward" # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7( modelname=mpnamb, trackdir="backward", flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew + nodesr, exe_name=mpexe, ) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Aug 01 2021 12:57:00 with IFORT compiler (ver. 19.10.3) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + ".mppth") p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + ".mpend") e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ["green", "orange", "red"] f, axes = plt.subplots( ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10) ) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect("equal") ax.set_title("Well pathlines - Layer {}".format(k + 1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect("equal") ax.set_title("River pathlines - Layer {}".format(k + 1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect("equal") ax.set_title("Well recharge area") mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction="starting", colorbar=True, shrink=0.5) ax = axes[1] ax.set_aspect("equal") ax.set_title("River recharge area") mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction="starting", colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + ".mppth") p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + ".mpend") e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect("equal") ax.set_title("Well recharge area") mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline( pwb, layer="all", color="blue", lw=0.5, linestyle=":", label="captured by wells", ) mm.plot_endpoint(ewb, direction="ending") # , colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect("equal") ax.set_title("River recharge area") mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline( prb, layer="all", color="green", lw=0.5, linestyle=":", label="captured by rivers", ) plt.tight_layout(); ###Output _____no_output_____ ###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) print('flopy version: {}'.format(flopy.__version__)) if not os.path.exists("data"): os.mkdir("data") # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317. riv_c = 1.e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join('data', 'mp7_ex1_cs') nm = 'ex01_mf6' # Create the Flopy simulation object sim = flopy.mf6.MFSimulation(sim_name=nm, exe_name=mfexe, version='mf6', sim_ws=ws) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=[pd]) # Create the Flopy groundwater flow (gwf) model object model_nam_file = '{}.nam'.format(nm) gwf = flopy.mf6.ModflowGwf(sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='SIMPLE', outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, length_units='FEET', delr=delr, delc=delc, top=top, botm=botm) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(gwf, pname='npf', icelltype=laytyp, k=kh, k33=kv) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf, maxbound=1, stress_period_data={0: wd}) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = '{}.hds'.format(nm) head_record = [headfile] budgetfile = '{}.cbb'.format(nm) budget_record = [budgetfile] saverecord = [('HEAD', 'ALL'), ('BUDGET', 'ALL')] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, 'mf6 model did not run' ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.2.0 10/22/2020 MODFLOW 6 compiled Oct 25 2020 16:15:39 with IFORT compiler (ver. 19.0.5) This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Also refer to the USGS Water Resources Software User Rights Notice for complete use, copyright, and distribution information. Run start date and time (yyyy/mm/dd hh:mm:ss): 2020/10/26 15:56:47 Writing simulation list file: mfsim.lst Using Simulation name file: mfsim.nam Solving: Stress period: 1 Time step: 1 Run end date and time (yyyy/mm/dd hh:mm:ss): 2020/10/26 15:56:47 Elapsed run time: 0.029 Seconds WARNING REPORT: 1. NONLINEAR BLOCK VARIABLE 'OUTER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING OUTER_DVCLOSE TO OUTER_HCLOSE VALUE. 2. LINEAR BLOCK VARIABLE 'INNER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING INNER_DVCLOSE TO INNER_HCLOSE VALUE. Normal termination of simulation. ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]['cellid'] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + '_mp_forward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamf, trackdir='forward', flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Oct 25 2020 16:19:48 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + '_mp_backward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamb, trackdir='backward', flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew+nodesr, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Oct 25 2020 16:19:48 with IFORT compiler (ver. 19.0.5) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + '.mppth') p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + '.mpend') e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ['green', 'orange', 'red'] f, axes = plt.subplots(ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10)) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('Well pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('River pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction='starting', colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction='starting', colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + '.mppth') p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + '.mpend') e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pwb, layer='all', color='blue', lw=0.5, linestyle=':', label='captured by wells') mm.plot_endpoint(ewb, direction='ending') #, colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(prb, layer='all', color='green', lw=0.5, linestyle=':', label='captured by rivers') plt.tight_layout(); ###Output _____no_output_____ ###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) print('flopy version: {}'.format(flopy.__version__)) if not os.path.exists("data"): os.mkdir("data") # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317. riv_c = 1.e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join('data', 'mp7_ex1_cs') nm = 'ex01_mf6' # Create the Flopy simulation object sim = flopy.mf6.MFSimulation(sim_name=nm, exe_name=mfexe, version='mf6', sim_ws=ws) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=[pd]) # Create the Flopy groundwater flow (gwf) model object model_nam_file = '{}.nam'.format(nm) gwf = flopy.mf6.ModflowGwf(sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='SIMPLE', outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, length_units='FEET', delr=delr, delc=delc, top=top, botm=botm) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(gwf, pname='npf', icelltype=laytyp, k=kh, k33=kv) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf, maxbound=1, stress_period_data={0: wd}) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = '{}.hds'.format(nm) head_record = [headfile] budgetfile = '{}.cbb'.format(nm) budget_record = [budgetfile] saverecord = [('HEAD', 'ALL'), ('BUDGET', 'ALL')] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, 'mf6 model did not run' ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha_0... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.2.2 07/30/2021 MODFLOW 6 compiled Aug 01 2021 12:51:08 with IFORT compiler (ver. 19.10.3) This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Also refer to the USGS Water Resources Software User Rights Notice for complete use, copyright, and distribution information. Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/08/06 16:21:39 Writing simulation list file: mfsim.lst Using Simulation name file: mfsim.nam Solving: Stress period: 1 Time step: 1 ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]['cellid'] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + '_mp_forward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamf, trackdir='forward', flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Aug 01 2021 12:57:00 with IFORT compiler (ver. 19.10.3) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + '_mp_backward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamb, trackdir='backward', flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew+nodesr, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Aug 01 2021 12:57:00 with IFORT compiler (ver. 19.10.3) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + '.mppth') p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + '.mpend') e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ['green', 'orange', 'red'] f, axes = plt.subplots(ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10)) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('Well pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('River pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction='starting', colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction='starting', colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + '.mppth') p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + '.mpend') e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pwb, layer='all', color='blue', lw=0.5, linestyle=':', label='captured by wells') mm.plot_endpoint(ewb, direction='ending') #, colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(prb, layer='all', color='green', lw=0.5, linestyle=':', label='captured by rivers') plt.tight_layout(); ###Output _____no_output_____ ###Markdown FloPy MODPATH 7 create simulation exampleThis notebook demonstrates how to create a simple forward and backward MODPATH 7 simulation using the `.create_mp7()` method. The notebooks also shows how to create subsets of endpoint output and plot MODPATH results on ModelMap objects. ###Code import sys import os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import platform # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys.version) print('numpy version: {}'.format(np.__version__)) print('matplotlib version: {}'.format(mpl.__version__)) print('flopy version: {}'.format(flopy.__version__)) if not os.path.exists("data"): os.mkdir("data") # define executable names mpexe = "mp7" mfexe = "mf6" if platform.system() == "Windows": mpexe += ".exe" mfexe += ".exe" ###Output _____no_output_____ ###Markdown Flow model data ###Code nper, nstp, perlen, tsmult = 1, 1, 1., 1. nlay, nrow, ncol = 3, 21, 20 delr = delc = 500. top = 400. botm = [220., 200., 0.] laytyp = [1, 0, 0] kh = [50., 0.01, 200.] kv = [10., 0.01, 20.] wel_loc = (2, 10, 9) wel_q = -150000. rch = 0.005 riv_h = 320. riv_z = 317. riv_c = 1.e5 def get_nodes(locs): nodes = [] for k, i, j in locs: nodes.append(k * nrow * ncol + i * ncol + j) return nodes ###Output _____no_output_____ ###Markdown MODPATH 7 using MODFLOW 6 Create and run MODFLOW 6 ###Code ws = os.path.join('data', 'mp7_ex1_cs') nm = 'ex01_mf6' # Create the Flopy simulation object sim = flopy.mf6.MFSimulation(sim_name=nm, exe_name=mfexe, version='mf6', sim_ws=ws) # Create the Flopy temporal discretization object pd = (perlen, nstp, tsmult) tdis = flopy.mf6.modflow.mftdis.ModflowTdis(sim, pname='tdis', time_units='DAYS', nper=nper, perioddata=[pd]) # Create the Flopy groundwater flow (gwf) model object model_nam_file = '{}.nam'.format(nm) gwf = flopy.mf6.ModflowGwf(sim, modelname=nm, model_nam_file=model_nam_file, save_flows=True) # Create the Flopy iterative model solver (ims) Package object ims = flopy.mf6.modflow.mfims.ModflowIms(sim, pname='ims', complexity='SIMPLE', outer_hclose=1e-6, inner_hclose=1e-6, rcloserecord=1e-6) # create gwf file dis = flopy.mf6.modflow.mfgwfdis.ModflowGwfdis(gwf, pname='dis', nlay=nlay, nrow=nrow, ncol=ncol, length_units='FEET', delr=delr, delc=delc, top=top, botm=botm) # Create the initial conditions package ic = flopy.mf6.modflow.mfgwfic.ModflowGwfic(gwf, pname='ic', strt=top) # Create the node property flow package npf = flopy.mf6.modflow.mfgwfnpf.ModflowGwfnpf(gwf, pname='npf', icelltype=laytyp, k=kh, k33=kv) # recharge flopy.mf6.modflow.mfgwfrcha.ModflowGwfrcha(gwf, recharge=rch) # wel wd = [(wel_loc, wel_q)] flopy.mf6.modflow.mfgwfwel.ModflowGwfwel(gwf, maxbound=1, stress_period_data={0: wd}) # river rd = [] for i in range(nrow): rd.append([(0, i, ncol - 1), riv_h, riv_c, riv_z]) flopy.mf6.modflow.mfgwfriv.ModflowGwfriv(gwf, stress_period_data={0: rd}) # Create the output control package headfile = '{}.hds'.format(nm) head_record = [headfile] budgetfile = '{}.cbb'.format(nm) budget_record = [budgetfile] saverecord = [('HEAD', 'ALL'), ('BUDGET', 'ALL')] oc = flopy.mf6.modflow.mfgwfoc.ModflowGwfoc(gwf, pname='oc', saverecord=saverecord, head_filerecord=head_record, budget_filerecord=budget_record) # Write the datasets sim.write_simulation() # Run the simulation success, buff = sim.run_simulation() assert success, 'mf6 model did not run' ###Output writing simulation... writing simulation name file... writing simulation tdis package... writing ims package ims... writing model ex01_mf6... writing model name file... writing package dis... writing package ic... writing package npf... writing package rcha... writing package wel_0... writing package riv_0... INFORMATION: maxbound in ('gwf6', 'riv', 'dimensions') changed to 21 based on size of stress_period_data writing package oc... FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.2.0 10/22/2020 MODFLOW 6 compiled Oct 29 2020 12:19:52 with IFORT compiler (ver. 19.10.3) This software has been approved for release by the U.S. Geological Survey (USGS). Although the software has been subjected to rigorous review, the USGS reserves the right to update the software as needed pursuant to further analysis and review. No warranty, expressed or implied, is made by the USGS or the U.S. Government as to the functionality of the software and related material nor shall the fact of release constitute any such warranty. Furthermore, the software is released on condition that neither the USGS nor the U.S. Government shall be held liable for any damages resulting from its authorized or unauthorized use. Also refer to the USGS Water Resources Software User Rights Notice for complete use, copyright, and distribution information. Run start date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:33:21 Writing simulation list file: mfsim.lst Using Simulation name file: mfsim.nam Solving: Stress period: 1 Time step: 1 Run end date and time (yyyy/mm/dd hh:mm:ss): 2021/02/18 11:33:21 Elapsed run time: 0.044 Seconds WARNING REPORT: 1. NONLINEAR BLOCK VARIABLE 'OUTER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING OUTER_DVCLOSE TO OUTER_HCLOSE VALUE. 2. LINEAR BLOCK VARIABLE 'INNER_HCLOSE' IN FILE 'ex01_mf6.ims' WAS DEPRECATED IN VERSION 6.1.1. SETTING INNER_DVCLOSE TO INNER_HCLOSE VALUE. Normal termination of simulation. ###Markdown Get locations to extract data ###Code nodew = get_nodes([wel_loc]) cellids = gwf.riv.stress_period_data.get_data()[0]['cellid'] nodesr = get_nodes(cellids) ###Output _____no_output_____ ###Markdown Create and run MODPATH 7Forward tracking ###Code # create modpath files mpnamf = nm + '_mp_forward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamf, trackdir='forward', flowmodel=gwf, model_ws=ws, rowcelldivisions=1, columncelldivisions=1, layercelldivisions=1, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Oct 29 2020 12:30:37 with IFORT compiler (ver. 19.10.3) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Backward tracking from well and river locations ###Code # create modpath files mpnamb = nm + '_mp_backward' # create basic forward tracking modpath simulation mp = flopy.modpath.Modpath7.create_mp7(modelname=mpnamb, trackdir='backward', flowmodel=gwf, model_ws=ws, rowcelldivisions=5, columncelldivisions=5, layercelldivisions=5, nodes=nodew+nodesr, exe_name=mpexe) # write modpath datasets mp.write_input() # run modpath mp.run_model() ###Output FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mp7 MODPATH Version 7.2.001 Program compiled Oct 29 2020 12:30:37 with IFORT compiler (ver. 19.10.3) Run particle tracking simulation ... Processing Time Step 1 Period 1. Time = 1.00000E+00 Steady-state flow ###Markdown Load and Plot MODPATH 7 output Forward Tracking Load forward tracking pathline data ###Code fpth = os.path.join(ws, mpnamf + '.mppth') p = flopy.utils.PathlineFile(fpth) pw = p.get_destination_pathline_data(dest_cells=nodew) pr = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load forward tracking endpoint data ###Code fpth = os.path.join(ws, mpnamf + '.mpend') e = flopy.utils.EndpointFile(fpth) ###Output _____no_output_____ ###Markdown Get forward particles that terminate in the well ###Code well_epd = e.get_destination_endpoint_data(dest_cells=nodew) ###Output _____no_output_____ ###Markdown Get particles that terminate in the river boundaries ###Code riv_epd = e.get_destination_endpoint_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Well and river forward tracking pathlines ###Code colors = ['green', 'orange', 'red'] f, axes = plt.subplots(ncols=3, nrows=2, sharey=True, sharex=True, figsize=(15, 10)) axes = axes.flatten() idax = 0 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('Well pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pw, layer=k, color=colors[k], lw=0.75) idax += 1 for k in range(nlay): ax = axes[idax] ax.set_aspect('equal') ax.set_title('River pathlines - Layer {}'.format(k+1)) mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pr, layer=k, color=colors[k], lw=0.75) idax += 1 plt.tight_layout(); ###Output _____no_output_____ ###Markdown Forward tracking endpoints captured by the well and river ###Code f, axes = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10, 5)) axes = axes.flatten() ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(well_epd, direction='starting', colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_endpoint(riv_epd, direction='starting', colorbar=True, shrink=0.5); ###Output _____no_output_____ ###Markdown Backward trackingLoad backward tracking pathlines ###Code fpth = os.path.join(ws, mpnamb + '.mppth') p = flopy.utils.PathlineFile(fpth) pwb = p.get_destination_pathline_data(dest_cells=nodew) prb = p.get_destination_pathline_data(dest_cells=nodesr) ###Output _____no_output_____ ###Markdown Load backward tracking endpoints ###Code fpth = os.path.join(ws, mpnamb + '.mpend') e = flopy.utils.EndpointFile(fpth) ewb = e.get_destination_endpoint_data(dest_cells=nodew, source=True) erb = e.get_destination_endpoint_data(dest_cells=nodesr, source=True) ###Output _____no_output_____ ###Markdown Well backward tracking pathlines ###Code f, axes = plt.subplots(ncols=2, nrows=1, figsize=(10, 5)) ax = axes[0] ax.set_aspect('equal') ax.set_title('Well recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(pwb, layer='all', color='blue', lw=0.5, linestyle=':', label='captured by wells') mm.plot_endpoint(ewb, direction='ending') #, colorbar=True, shrink=0.5); ax = axes[1] ax.set_aspect('equal') ax.set_title('River recharge area') mm = flopy.plot.PlotMapView(model=gwf, ax=ax) mm.plot_grid(lw=0.5) mm.plot_pathline(prb, layer='all', color='green', lw=0.5, linestyle=':', label='captured by rivers') plt.tight_layout(); ###Output _____no_output_____
dev code/graph construction/Identifying & Building the Training Graph.ipynb
###Markdown Collect training and validation papers ###Code all_concepts_edges = list(KG.edges()) all_concepts_edges = [ i for i \ in all_concepts_edges \ if i[0]==i[0] and i[1]==i[1] ] training_papers = [ paper for paper \ in papers_dict \ if papers_dict[paper]<=june_2020 ] validation_papers = [ paper for paper \ in papers_dict \ if papers_dict[paper]>june_2020 ] save_obj(training_papers, "training_papers") save_obj(validation_papers, "validation_papers") ###Output _____no_output_____ ###Markdown Collect training and validation edges ###Code training_edges_pc = edges_pc[edges_pc["src"].isin(training_papers)] training_concepts = list(set(training_edges_pc.dst.values.tolist())) training_papers = list(set(training_edges_pc.src.values.tolist())) training_edges = [] validation_edges = [] for i in range(len(all_concepts_edges)): edge = all_concepts_edges[i] concept0_papers = training_edges_pc[ (training_edges_pc["dst"]==edge[0]) ].src concept1_papers = training_edges_pc[ (training_edges_pc["dst"]==edge[1]) ].src common_papers = set(concept0_papers).intersection(set(concept1_papers)) if common_papers: training_edges.append(edge) else: validation_edges.append(edge) save_obj(training_edges, "training_edges") save_obj(validation_edges, "validation_edges") training_concepts = list(set( [i[0] for i in training_edges] \ +[i[1] for i in training_edges] )) validation_concepts = list(set( [i[0] for i in validation_edges] \ +[i[1] for i in validation_edges] )) save_obj(training_concepts, "training_concepts") save_obj(validation_concepts, "validation_concepts") ###Output _____no_output_____ ###Markdown Create Training Concept Graph ###Code training_KG = nx.Graph() for concept in training_concepts: if concept == concept: training_KG.add_node(concept, node_type = "concept") training_KG.add_edges_from(training_edges) print("Edges: ", len(list(training_KG.edges(data=True)))) print("Nodes: ", len(list(training_KG.nodes(data=True)))) nx.write_gpickle(training_KG, "training_KG_concepts.gpickle") #KG = nx.read_gpickle("training_KG_concepts.gpickle") ###Output _____no_output_____
notebook-samples/.ipynb_checkpoints/lmt-app-history-parsing-checkpoint.ipynb
###Markdown Lockheed App Submissions 2020: Summary This notebook is a quick exercise to look at my Lockheed Martin applicaiton submission history since the beginning of 2020. Some notes about the data:The portion of actually procuring the info from the LMT Careers site isn't executed in this notebook, but some of the processes are noted in the first few cels.The full JSON data output is at the bottom of the notebook.Some of the job titles and locations names and values are reworked for more of a broader picture.Only basic measures are looked at given the sparsity of the data. ###Code %matplotlib inline import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import os import re import json import shlex import base64 import getpass import zipfile import requests import subprocess import pandas as pd from datetime import datetime as dt import seaborn as sns import matplotlib.pyplot as plt sns.set(style="whitegrid") with open(rf"data\lmt-app-data.json") as f: data = f.read() ###Output _____no_output_____ ###Markdown Reformat and Write cUrl Command ~~~python Get curl data and replace the option "compressed" Windows doesn't see to like that.curl_full = """curl 'https://sjobs.brassring.com/TgNewUI/CandidateZone/Ajax/DashboardData' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'RFT: o7n5hgY-1zkKC-6QNih91_iHulRXzntWwaKgSk_3tu8IU4jeMtNSZQqDrCwKvfOXuaf5W10R6P0zBrbpDqU13BODQWDO2vGTAwfcKYTveP0K1zLJCKKNJAm7MzR_Duxg5OSMDw2' -H 'X-Requested-With: XMLHttpRequest' -H 'Origin: https://sjobs.brassring.com' -H 'Connection: keep-alive' -H 'Referer: https://sjobs.brassring.com/TGnewUI/Search/Home/Home?partnerid=25037&siteid=5010' -H 'Cookie: tg_session=^upx5qh9vxWI/cP0/K90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf/uKMJNIpsooK0S4a8EMU=; tg_session_25397_5259=^eARVlSOHbKYKnZYhaeYSbKiW3/ldAc2J/rOVJeBPhZcRmHvSzy5rX4i9KhKlx_slp_rhc_fTKnv_slp_rhc_02WeZ17IFRzY61zRQTxP51XHQkzkuT_slp_rhc_H0Qy1R/o=; tg_rft=^LQ2UYNmOjeBS6hc/OXFk464HSfCdmdpPZrWEDCe3avWrmjISZVl7A+BnX7vwaCkZYWCEeBguXnIJcmiOPaQFzv60Jfq8b6rdacaAzMsPXTQ=; tg_rft_mvc=x8qZpphRcpJnnaWndmc-RLpel9r3KMKdH_7DZZz-q-bi6P3jRl8fIyk07q8KWSk9EV7Q_1PQ98frbm-h5G-IkSC_PmyUEaZTHWkks97yi4WUeCLlWThfEgmBNfRywx_IkK7oMA2; G_ENABLED_IDPS=google; tg_session_25037_5010=^upx5qh9vxWI/cP0/K90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf/uKMJNIpsooK0S4a8EMU=' --data-raw 'ClientId=25037&SiteId=5010&SessionID=%5Eupx5qh9vxWI%2FcP0%2FK90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf%2FuKMJNIpsooK0S4a8EMU%3D&ConfiguredJobTitle=jobtitle&Tab=2'""".strip()curl_full = curl_full.replace(" --compressed","") Write to local drivewith open(rf"{PROJECT_DIR}\data\lmt-curl-cmd.txt", mode='w',) as f: f.write(curl_full) print("\n-H".join(re.split(r"\s+-H", curl_full)))~~~ Output:curl 'https://sjobs.brassring.com/TgNewUI/CandidateZone/Ajax/DashboardData'-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0'-H 'Accept: */*'-H 'Accept-Language: en-US,en;q=0.5'-H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'-H 'RFT: o7n5hgY-1zkKC-6QNih91_iHulRXzntWwaKgSk_3tu8IU4jeMtNSZQqDrCwKvfOXuaf5W10R6P0zBrbpDqU13BODQWDO2vGTAwfcKYTveP0K1zLJCKKNJAm7MzR_Duxg5OSMDw2'-H 'X-Requested-With: XMLHttpRequest'-H 'Origin: https://sjobs.brassring.com'-H 'Connection: keep-alive'-H 'Referer: https://sjobs.brassring.com/TGnewUI/Search/Home/Home?partnerid=25037&siteid=5010'-H 'Cookie: tg_session=^upx5qh9vxWI/cP0/K90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf/uKMJNIpsooK0S4a8EMU=; tg_session_25397_5259=^eARVlSOHbKYKnZYhaeYSbKiW3/ldAc2J/rOVJeBPhZcRmHvSzy5rX4i9KhKlx_slp_rhc_fTKnv_slp_rhc_02WeZ17IFRzY61zRQTxP51XHQkzkuT_slp_rhc_H0Qy1R/o=; tg_rft=^LQ2UYNmOjeBS6hc/OXFk464HSfCdmdpPZrWEDCe3avWrmjISZVl7A+BnX7vwaCkZYWCEeBguXnIJcmiOPaQFzv60Jfq8b6rdacaAzMsPXTQ=; tg_rft_mvc=x8qZpphRcpJnnaWndmc-RLpel9r3KMKdH_7DZZz-q-bi6P3jRl8fIyk07q8KWSk9EV7Q_1PQ98frbm-h5G-IkSC_PmyUEaZTHWkks97yi4WUeCLlWThfEgmBNfRywx_IkK7oMA2; G_ENABLED_IDPS=google; tg_session_25037_5010=^upx5qh9vxWI/cP0/K90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf/uKMJNIpsooK0S4a8EMU=' --data-raw 'ClientId=25037&SiteId=5010&SessionID=%5Eupx5qh9vxWI%2FcP0%2FK90JwtjK75v7SDOLTAxNS2fRZ_slp_rhc_GE5j7_slp_rhc_JsCB55ylgcO3tE1kOouptxqNfy3My6gDwHz0BEf%2FuKMJNIpsooK0S4a8EMU%3D&ConfiguredJobTitle=jobtitle&Tab=2' Run Process to Gather Data ~~~python Run try/except to gather and process application data.try: Tokenize curl command in POSIX format to excuse any percent signs as wildcards. tokens = shlex.split(curl_full, posix=True) p = subprocess.Popen(tokens, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate() except subprocess.CalledProcessError: stdout, stderr = p.communicate() print(stdout, stderr)~~~ Function: Navigate Dictionary ``` pythondef unravel_questions(iterable, **kwargs): """ Function to get certain keywords from subquestions and reuturn a key-value collection. """ ddict = dict() for i in range(len(iterable)): for k, v in iterable[i].items(): if v in kwargs.keys(): term = kwargs[v] val = iterable[i].get("Value") ddict[term] = val return ddict``` Process JSON Response Data into Pandas DataFrame ```python Convert stdout to unicode and restructure as json.try: data_dict = json.loads(data)except NameError: passfinally: data_dict = json.loads(stdout.decode("utf-8")) Application data from user data json resultapp_data = data_dict.get("DashboardData").get("Applications") Get number of current applicaitons that have been submitted.app_cnt = app_data.get("AppliedCount")apps = app_data.get("AppliedJobs") Keywords from each application data set that we want to keepv_kwrds = ( "JobTitle", "ReqId", "Status", ) Date keys to reformat before adding to results collection.dt_kwrds = ( "LastUpdated", "JobSubmissionDate", "ReqStatusDate", ) Keywords and 'normal' names for questions that we want to keep The keys in this collection are used to match values and return values from the 'Value' key in the question collection.q_kwargs = { "formtext13": "Unit", "formtext27": "Location", "autoreq": "AutoReq", }ddict = dict()for ix, app in enumerate(apps): ddict[ix] = dict() for k, v in app.items(): if k in dt_kwrds: ddict[ix][k] = dt.strptime(v, "%d-%b-%Y").strftime("%Y-%m-%d") elif k in v_kwrds: ddict[ix][k] = v Get Quesions and create key-value collection of focus items qs = app.get("Questions") for k, v in unravel_questions(qs, **q_kwargs).items(): ddict[ix][k] = v Write json with open(rf"{PROJECT_DIR}\lmt-app-data.json", mode='w',) as f: f.write(json.dumps(ddict, sort_keys=True, indent = 4)) ``` Create DataFrame From JSON ###Code # Load preprocessed data ddict = json.loads(data) # Date fields dt_cols = [ "LastUpdated", "JobSubmissionDate", "ReqStatusDate", ] # Restructuring data as Pandas DataFrame df = pd.DataFrame([v for v in ddict.values()], index=[i for i in ddict.keys()]) new_order = ['ReqId', 'AutoReq', 'JobTitle', 'Unit', 'Location', 'LastUpdated', 'JobSubmissionDate', 'Status', 'ReqStatusDate', ] df = df.loc[:, new_order] # Replace Locations that have multiple values with 'Multiple' df_loc_cnt = df.loc[:, "Location"].str.split(",", expand=True).count(axis=1) df.loc[df_loc_cnt>1, "Location"] = "Multiple" df.loc[:, "Location"] = df.loc[:, "Location"].str.strip() # Reformat datetime fields to appropriate type df.loc[:, dt_cols] = df.loc[:, dt_cols].apply(lambda x: pd.to_datetime(x, infer_datetime_format=True)) df.sort_values(by=["ReqId","AutoReq"], inplace=True, ignore_index=True) ###Output _____no_output_____ ###Markdown DataFrame info ###Code app_count = df.shape[0] print(f"In total, there are {app_count} application submissions in this dataset.\nBelow is a bit more information about the attributes and overall size of the data.\n\n") print(df.info()) # Clean up job titles titlelist = list(df.loc[:, "JobTitle"].unique()) jtdf = df.loc[:, "JobTitle"].to_frame() jtdf["JobTitleBasic"] = None def update_title(kwrd, repl=None): if not repl is None: jtdf.loc[((jtdf["JobTitle"].str.contains(kwrd))&(jtdf["JobTitleBasic"].isna())),"JobTitleBasic"] = repl else: jtdf.loc[((jtdf["JobTitle"].str.contains(kwrd))&(jtdf["JobTitleBasic"].isna())),"JobTitleBasic"] = kwrd update_title("Data Science Analyst") update_title("Senior Data Analyst") update_title("Data Engineer") update_title("AI Engineer", "Data Scientist / AI Engineer ") update_title("Data Scientist") update_title("Machine Learning") update_title("Software Engineer") update_title("Developer", "Software Developer") # Merge column into new dataframe df2 = df.merge(jtdf.loc[:, "JobTitleBasic"], 'inner', left_index=True, right_index=True) df2["yearmonth"] = df2["JobSubmissionDate"].dt.strftime("%Y-%b") df2["line"] = 1 plt.rcParams["figure.figsize"] = 9,7 jt_ct = jtdf.loc[:, "JobTitleBasic"].value_counts() f, ax = plt.subplots(figsize=(10, 7)) g = sns.barplot(jt_ct.values, jt_ct.index, orient="h", ax=ax) g.set_title("App. Freq. by JobTitle", fontdict={'fontsize': 24,'fontweight' : "bold",}) plt.tight_layout() plt.show() # Crosstab of Location and JobTitle ct = pd.crosstab(df2["JobTitleBasic"], df2["Location"], margins=False) # Plot heatmap f, ax = plt.subplots(figsize=(10, 7)) g = sns.heatmap(ct, cmap=plt.cm.Blues, annot=True, fmt="d", linewidths=.5, ax=ax) bottom, top = ax.get_ylim() g.set_title("JobTitle vs. Location", fontdict={'fontsize': 24,'fontweight' : "bold",}) g.set_ylim(bottom + 0.5, top - 0.5) g.set_xticklabels(g.get_xticklabels(), rotation=45) plt.tight_layout() plt.show() ###Output _____no_output_____ ###Markdown In the above plot, please note that the Multiple category reduces granularity. The Data Engineer role, for instance, is located in Colorado, Connecticut, and New York. ###Code # Plot 3: Days Since Submission distribution today = dt.today() # Job submissions still in the running df_alive = df2.loc[~df2["Status"].str.startswith("No longer"), ["ReqId","JobSubmissionDate", "LastUpdated", "Status"]] # Also tried for a "days since update" attribute, but the data wasn't that much different df_alive["DaysSinceSubmission"] = (dt.today() - df2["JobSubmissionDate"]).dt.days fig, ax = plt.subplots(figsize=(9, 7)) g = sns.violinplot(y="Status", x="DaysSinceSubmission", inner="quartile", data=df_alive, orient="h", hue="Status", legend=None) g.set_title("Days Since App Submission", fontdict={'fontsize': 24,'fontweight' : "bold",}) ax.legend(loc=7) ax.set_xlabel('') plt.tight_layout() plt.show() ###Output _____no_output_____ ###Markdown Summary ###Code df_rejections = df2.loc[df2["Status"].str.startswith("No longer"),:] rej_ct = df_rejections.shape[0] earliest_rem_app_sub_dt = df_alive["JobSubmissionDate"].min() earliest_rem_app_sub_dt = earliest_rem_app_sub_dt.strftime("%Y-%m-%d") # YYYY-MM-DD highest_app_count = jt_ct.nlargest(1).index[0] print(f"App count: {app_count}\nRejections: {rej_ct}\nRemaining: {app_count - rej_ct}") print(f"Earliest Submission Date (remaining apps): {earliest_rem_app_sub_dt}") print(f"JobTitle highest app submission count: '{highest_app_count.strip()}'") ###Output App count: 35 Rejections: 22 Remaining: 13 Earliest Submission Date (remaining apps): 2020-01-28 JobTitle highest app submission count: 'Software Engineer' ###Markdown We can see from the basic metric above there there were 31 total submissions and 14 apps are still active. However, with the earliest app having been submitted in January and three within that time frame, it doesn't seem likely that those will be moving forward. Notably, the job title with the highest application submission count is 'Data Scientist / AI Engineer.' However, given that many of the job titles didn't fit a particualr format, that number could change with a little bit more analysis. Some job titles were very similar, so going the other direction in terms of naming convetion would produce slightly different results, as an example. Raw JSON Data ###Code print(json.dumps(ddict, indent=4, sort_keys=True)) ###Output { "0": { "AutoReq": "527472BR", "JobSubmissionDate": "2020-05-17", "JobTitle": "Senior Software Engineer", "LastUpdated": "2020-05-18", "Location": "Virginia ", "ReqId": 611629, "ReqStatusDate": "2020-05-14", "Status": "Resume Under Review", "Unit": "Rotary and Mission Systems " }, "1": { "AutoReq": "515923BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-05-15", "Location": "Texas", "ReqId": 542029, "ReqStatusDate": "2020-04-28", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "10": { "AutoReq": "515929BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-05-05", "Location": "Texas ", "ReqId": 542034, "ReqStatusDate": "2020-04-28", "Status": "Resume Under Review", "Unit": "Enterprise Operations " }, "11": { "AutoReq": "515924BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-05-05", "Location": "Texas ", "ReqId": 542030, "ReqStatusDate": "2020-04-28", "Status": "Resume Under Review", "Unit": "Enterprise Operations " }, "12": { "AutoReq": "515928BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-05-05", "Location": "Texas ", "ReqId": 542033, "ReqStatusDate": "2020-04-28", "Status": "Resume Under Review", "Unit": "Enterprise Operations " }, "13": { "AutoReq": "517938BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Software Engineer", "LastUpdated": "2020-05-04", "Location": "Colorado ", "ReqId": 544121, "ReqStatusDate": "2020-03-16", "Status": "No longer under consideration for position", "Unit": "Space " }, "14": { "AutoReq": "521987BR", "JobSubmissionDate": "2020-03-26", "JobTitle": "Data Science Analyst Staff / Grand Prairie, TX", "LastUpdated": "2020-04-30", "Location": "Texas", "ReqId": 605503, "ReqStatusDate": "2020-04-30", "Status": "No longer under consideration for position", "Unit": "Missiles and Fire Control" }, "15": { "AutoReq": "521986BR", "JobSubmissionDate": "2020-03-26", "JobTitle": "Data Science Analyst Staff / Grand Prairie, TX", "LastUpdated": "2020-04-30", "Location": "Texas", "ReqId": 605341, "ReqStatusDate": "2020-04-30", "Status": "No longer under consideration for position", "Unit": "Missiles and Fire Control" }, "16": { "AutoReq": "525865BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Senior Data Analyst & Tool Developer", "LastUpdated": "2020-04-29", "Location": "Colorado", "ReqId": 609861, "ReqStatusDate": "2020-04-28", "Status": "No longer under consideration for position", "Unit": "Rotary and Mission Systems" }, "17": { "AutoReq": "506316BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist", "LastUpdated": "2020-04-23", "Location": "California,Colorado,Florida,Maryland,New Jersey,Pennsylvania,Texas,Virginia", "ReqId": 531699, "ReqStatusDate": "2020-04-23", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "18": { "AutoReq": "523116BR", "JobSubmissionDate": "2020-04-22", "JobTitle": "Machine Learning SW Engineer", "LastUpdated": "2020-04-22", "Location": "Connecticut ", "ReqId": 606437, "ReqStatusDate": "2020-04-22", "Status": "Applied", "Unit": "Enterprise Operations " }, "19": { "AutoReq": "523251BR", "JobSubmissionDate": "2020-04-22", "JobTitle": "E1076:Machine Learning Software Engineer Prin", "LastUpdated": "2020-04-22", "Location": "Connecticut ", "ReqId": 606440, "ReqStatusDate": "2020-04-08", "Status": "Applied", "Unit": "Enterprise Operations " }, "2": { "AutoReq": "515122BR", "JobSubmissionDate": "2020-03-10", "JobTitle": "A/AI Machine Learning Eng Stf", "LastUpdated": "2020-05-14", "Location": "New Jersey", "ReqId": 541156, "ReqStatusDate": "2020-04-27", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "20": { "AutoReq": "522925BR", "JobSubmissionDate": "2020-03-26", "JobTitle": "Data Engineer", "LastUpdated": "2020-04-17", "Location": "Colorado, Connecticut, New York", "ReqId": 606479, "ReqStatusDate": "2020-05-11", "Status": "Resume Under Review", "Unit": "Rotary and Mission Systems " }, "21": { "AutoReq": "522231BR", "JobSubmissionDate": "2020-03-26", "JobTitle": "Software Engineer", "LastUpdated": "2020-04-06", "Location": "Colorado", "ReqId": 605762, "ReqStatusDate": "2020-04-06", "Status": "No longer under consideration for position", "Unit": "Space" }, "22": { "AutoReq": "522230BR", "JobSubmissionDate": "2020-03-26", "JobTitle": "Software Engineer", "LastUpdated": "2020-04-06", "Location": "Colorado", "ReqId": 605761, "ReqStatusDate": "2020-04-06", "Status": "No longer under consideration for position", "Unit": "Space" }, "23": { "AutoReq": "512680BR", "JobSubmissionDate": "2020-03-10", "JobTitle": "Orion Senior Software Developer", "LastUpdated": "2020-03-27", "Location": "Colorado, Texas", "ReqId": 538581, "ReqStatusDate": "2020-04-27", "Status": "No longer under consideration for position", "Unit": "Space " }, "24": { "AutoReq": "521030BR", "JobSubmissionDate": "2020-03-10", "JobTitle": "Data Engineer", "LastUpdated": "2020-03-25", "Location": "Texas", "ReqId": 604516, "ReqStatusDate": "2020-04-30", "Status": "No longer under consideration for position", "Unit": "Missiles and Fire Control" }, "25": { "AutoReq": "512772BR", "JobSubmissionDate": "2020-03-10", "JobTitle": "Data Engineer", "LastUpdated": "2020-03-24", "Location": "Florida,Texas", "ReqId": 535791, "ReqStatusDate": "2020-04-24", "Status": "Resume Under Review", "Unit": "Missiles and Fire Control" }, "26": { "AutoReq": "509206BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Senior Data Analyst", "LastUpdated": "2020-03-19", "Location": "Florida", "ReqId": 534562, "ReqStatusDate": "2020-04-01", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "27": { "AutoReq": "506021BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist", "LastUpdated": "2020-03-17", "Location": "California,Colorado,Florida,Pennsylvania", "ReqId": 531640, "ReqStatusDate": "2020-04-28", "Status": "No longer under consideration for position", "Unit": "Space" }, "28": { "AutoReq": "504196BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist", "LastUpdated": "2020-03-16", "Location": "California,Colorado,Florida,Pennsylvania", "ReqId": 529769, "ReqStatusDate": "2020-04-28", "Status": "No longer under consideration for position", "Unit": "Space" }, "29": { "AutoReq": "512660BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-03-02", "Location": "Texas", "ReqId": 538562, "ReqStatusDate": "2020-03-24", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "3": { "AutoReq": "526727BR", "JobSubmissionDate": "2020-05-09", "JobTitle": "AI/ML SW Engineer Sr Stf", "LastUpdated": "2020-05-11", "Location": "Maryland,Pennsylvania,Virginia", "ReqId": 610842, "ReqStatusDate": "2020-05-11", "Status": "No longer under consideration for position", "Unit": "Space" }, "30": { "AutoReq": "512654BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist / AI Engineer", "LastUpdated": "2020-02-28", "Location": "Texas", "ReqId": 538556, "ReqStatusDate": "2020-04-08", "Status": "No longer under consideration for position", "Unit": "Enterprise Operations" }, "31": { "AutoReq": "514059BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Scientist", "LastUpdated": "2020-02-03", "Location": "Virginia ", "ReqId": 540020, "ReqStatusDate": "2020-05-14", "Status": "No longer under consideration for position", "Unit": "Space " }, "32": { "AutoReq": "511406BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Sr. Data Scientist", "LastUpdated": "2020-01-28", "Location": "Texas", "ReqId": 536549, "ReqStatusDate": "2020-03-02", "Status": "Applied", "Unit": "Missiles and Fire Control" }, "33": { "AutoReq": "511467BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Senior Data Analyst", "LastUpdated": "2020-01-28", "Location": "Maryland,New Jersey,Virginia", "ReqId": 537323, "ReqStatusDate": "2020-03-05", "Status": "Applied", "Unit": "Enterprise Operations" }, "34": { "AutoReq": "508734BR", "JobSubmissionDate": "2020-01-28", "JobTitle": "Data Engineer/Data Scientist", "LastUpdated": "2020-01-28", "Location": "Florida,Texas", "ReqId": 534426, "ReqStatusDate": "2020-04-09", "Status": "Applied", "Unit": "Enterprise Operations" }, "4": { "AutoReq": "526726BR", "JobSubmissionDate": "2020-05-09", "JobTitle": "AI/ML SW Engineer Stf", "LastUpdated": "2020-05-11", "Location": "Maryland,Pennsylvania,Virginia", "ReqId": 610841, "ReqStatusDate": "2020-05-11", "Status": "No longer under consideration for position", "Unit": "Space" }, "5": { "AutoReq": "526721BR", "JobSubmissionDate": "2020-05-09", "JobTitle": "AI/ML Software Engineer Sr", "LastUpdated": "2020-05-11", "Location": "Maryland,Pennsylvania,Virginia", "ReqId": 610836, "ReqStatusDate": "2020-05-11", "Status": "No longer under consideration for position", "Unit": "Space" }, "6": { "AutoReq": "526720BR", "JobSubmissionDate": "2020-05-09", "JobTitle": "AI/ML Software Engineer Sr", "LastUpdated": "2020-05-11", "Location": "Maryland,Pennsylvania,Virginia", "ReqId": 610835, "ReqStatusDate": "2020-05-11", "Status": "No longer under consideration for position", "Unit": "Space" }, "7": { "AutoReq": "525659BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Science Analyst Staff / Python / Analytics / Production", "LastUpdated": "2020-05-11", "Location": "Alabama, Arkansas, California, Florida, Massachusetts, Pennsylvania, Texas", "ReqId": 609633, "ReqStatusDate": "2020-05-01", "Status": "Resume Under Review", "Unit": "Missiles and Fire Control" }, "8": { "AutoReq": "525660BR", "JobSubmissionDate": "2020-04-29", "JobTitle": "Data Science Analyst / Python / analystics / Production Manufacturing", "LastUpdated": "2020-05-08", "Location": "Alabama, Arkansas, California, Florida, Massachusetts, Pennsylvania, Texas", "ReqId": 609634, "ReqStatusDate": "2020-04-28", "Status": "Resume Under Review", "Unit": "Missiles and Fire Control" }, "9": { "AutoReq": "521509BR", "JobSubmissionDate": "2020-03-10", "JobTitle": "Flight Software Engineer", "LastUpdated": "2020-05-05", "Location": "Colorado", "ReqId": 605008, "ReqStatusDate": "2020-05-05", "Status": "No longer under consideration for position", "Unit": "Space" } }
QAOA.ipynb
###Markdown QAPLib integration ###Code %%capture #qap_problem = "chr8a" #path_problem = f'QAP_instances/qaplib/{qap_problem}.dat' #path_solution = f'QAP_instances/qaplib/{qap_problem}.sln' """ ### Alternatively, to load planted problems, uncomment the next three lines (and comment the lines above) qap_problem = "problem_1" path_problem = f'QAP_instances/planted/qap-8/{qap_problem}.dat' path_solution = f'QAP_instances/planted/qap-8/{qap_problem}.sln' n, f, d = qap.read_problem_to_lists(path_problem) n, F, D = qap.read_problem_to_matrices(path_problem) solution_config, f_optimal = qap.read_solution(path_solution) print(f"The chosen problem is {qap_problem}, with {n} facilities and {n} locations") print(f"The optimal objective function is {f_optimal}, with optimal configuration {solution_config}") """ def CSVtoNumpyArray(rawdata): """ Input: rawdata = a csv file (insert name as a string) Output: two numpy matrices in a tuple """ data = pd.read_csv(rawdata) #Reads the data in as a pandas object c = data.columns column = int(c[0]) final_data1 = data.iloc[:column,:].values #Sets data into a series of numpy arrays of strings final_data2 = data.iloc[column:,:].values #1 is for the first matrix(loc) and 2 is for the second(flow) #Forms the matrix as a numpy array (easier to work with) instead of an list of lists of strings def string_to_integers(final_data): matrix = [] for j in range(column): string = final_data[j][0] string2 = string.split(" ") emptyarray = [] for i in string2: if i != '': emptyarray.append(int(i)) matrix.append(emptyarray) npmatrix = np.array(matrix) return npmatrix return string_to_integers(final_data1),string_to_integers(final_data2) def qap_value(z, MatrixLoc, MatrixFlow): """ Input: z (list[int]): list of allocations MatrixLoc (numpy array): matrix of distances MatrixFlow (numpy array): matrix of flow Output: float: value of the QAP """ matrix_length = len(MatrixLoc) x = np.reshape(z, (matrix_length,matrix_length)) total = 0 for i in range(matrix_length): for j in range(matrix_length): for k in range(matrix_length): for p in range(matrix_length): total += MatrixLoc[i,j]* MatrixFlow[k,p]*x[i,k]*x[j,p] return total def qap_feasible(x): """ Input: x (numpy.ndarray) : binary string as numpy array. Output: bool: feasible or not. """ n = int(np.sqrt(len(x))) y = np.reshape(x, (n,n)) for i in range(n): if sum(y[i, p] for p in range(n)) != 1: return False for p__ in range(n): if sum(y[i, p__] for i in range(n)) != 1: return False return True def choose_best_feasible(eigenstates): """ Input: eigenstates = dictionary Output: feasible binary 1D numpyarray probability of this answer """ bestinarray = sorted(eigenstates.items(), key=lambda item: item[1])[::-1] feasible = False counter = 0 feasible=False while feasible==False and counter<len(bestinarray): #string to array bestasint = np.array([0]) for i in bestinarray[counter][0]: bestasint = np.hstack((bestasint, int(i))) feasible = qap_feasible(bestasint[1:]) frequency = bestinarray[counter][1] counter += 1 if feasible == False: return feasible else: return bestasint[1:], frequency/total def read_optimal(ins): data = pd.read_csv("initial_point-" + str(ins),header = None) n = len(data[0]) - 1 ans = [] data[0][0] = data[0][0][1:] data[0][n] = data[0][n][:-1] for i in data[0]: r = i.split(" ") for t in r: if t!='': ans.append(float(t)) return np.array(ans) ###Output _____no_output_____ ###Markdown QAOA function ###Code from qiskit.providers.aer import AerSimulator from math import pi def testing_quantum(machine, ins, SPtrial, SHOT, optimal_point, p_depth, number_iterations): """ Input: machine: the name of available machine ins: the QAP instance SPtrial: max_trials for SPSA SHOT: number of shots optimal_point: numpy array of optimal points from simulator p_depth = parametrized p_depth variable 1-n number_iterations: number of iterations for QAOA algorithm Output: outmatrix: 30 * [eigensolution value, time, feasibility] (outfile "thirty_trials-<machine name>-<instance name>.csv") """ #get matrix datamatrix = CSVtoNumpyArray(ins) MatrixLoc = datamatrix[0] MatrixFlow = datamatrix[1] n = len(MatrixLoc) # Create an instance of a model and variables. thename = "qap" + str(n) mdl = Model(name=thename) x = {(i,p): mdl.binary_var(name='x_{0}_{1}'.format(i,p)) for i in range(n) for p in range(n)} # Object function qap_func = mdl.sum(MatrixLoc[i,j]* MatrixFlow[k,p]*x[i,k]*x[j,p] for i in range(n) for j in range(n) for p in range(n) for k in range(n)) mdl.minimize(qap_func) # Constraints for i in range(n): mdl.add_constraint(mdl.sum(x[(i,p)] for p in range(n)) == 1) for p in range(n): mdl.add_constraint(mdl.sum(x[(i,p)] for i in range(n)) == 1) print(mdl.export_to_string()) qubitOp_docplex, offset_docplex = docplex.get_operator(mdl) #Setup QAOA seed = 10598 spsa = SPSA(maxiter=SPtrial) print('num of qubits; ', qubitOp_docplex.num_qubits) #30 trials file = open("thirty_trials-" + str(machine) + "-" + str(ins) ,"w") file.write("value, feasible, frequency, time, iteration" + "\n") ans = np.zeros(5) for i in range(number_iterations): #back to 30 bb backend = Aer.get_backend('aer_simulator') #backend = provider.get_backend(machine) #For Aer simulator, need to pass specific options to the instance quantum_instance = QuantumInstance(backend=backend,seed_simulator=seed, seed_transpiler=seed, skip_qobj_validation = False, shots = SHOT, backend_options = {'max_parallel_threads ':0,'blocking_enable': True, 'blocking_qubits':20}) qaoa = QAOA(qubitOp_docplex,optimizer=spsa, p=p_depth, quantum_instance=quantum_instance,include_custom=True) result = qaoa.run(quantum_instance) #Output processing print(' Eigenstate:', result['eigenstate']) print('QAOA time:', result['optimizer_time']) n = len(list(result['eigenstate'].values())) solution = np.hstack((np.array(list(result['eigenstate'].values())).reshape(n,1), np.array(list(result['eigenstate'].keys())).reshape(n,1))) #solution = solution.astype(np.float64) print(solution) for r in solution: #feasible_val = feasible or not, val_freq = frequency of value # q_time = time to run, i = iteration number redux = np.array(list(r[1])).astype(float) energy_val = qap_value(redux,np.array(MatrixFlow).astype(float),np.array(MatrixLoc).astype(float)) feasible_val = qap_feasible(redux) val_freq = float(r[0]) q_time = result['optimizer_time'] ans = np.vstack((ans,np.array([energy_val, feasible_val,val_freq,q_time,i]))) file.write(str(energy_val) + "," + str(feasible_val) + "," + str(val_freq) + ","+ str(q_time) + "," + str(i) + "\n") return result ###Output _____no_output_____ ###Markdown These are the cells running solutions: ###Code %%capture #3 by 3 thirty trials # this is still pretty buggy!!! import logging logging.basicConfig(level=logging.DEBUG) # log the steps of the algorithm and results import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) machines = 'aer' instances = "made3ez.csv" number_iterations = 30 shots = 1024 #old 1024 optimal_point = read_optimal(instances) ans = testing_quantum(machines, instances, 1, shots, optimal_point, 1, number_iterations) col_list = ["value"," feasible"," frequency"," time"," iteration"] df = pd.read_csv("thirty_trials-aer-made3ez.csv", usecols=col_list) df = df.rename(columns={' feasible': 'feasible', ' frequency': 'frequency',' time':'time',' iteration':'iteration'}) #split the data depending on the iterrations on a for loop df_list = [] for i in range(number_iterations): df_list.append(df[df['iteration'] == i]) #plot as dots of different colors #keys are value, feasible, frequency, time, iteration key1='frequency' key2='value' range_to_plot = 1 for i in range(range_to_plot): plt.scatter(df[key1],df[key2],cmap='coolwarm') plt.xlabel(key1) plt.ylabel(key2) #legend plt.legend(["iteration "+ str(i) for i in range(number_iterations)]) #legend title plt.title('QAOA') plt.show() names = list(ans['eigenstate'].keys()) values = list(ans['eigenstate'].values()) import plotly.graph_objects as go # Specify the plots bar_plots = [ go.Bar(x=names, y=values, name='Data', marker=go.bar.Marker(color='#0343df')), ] # Customise some display properties layout = go.Layout( title=go.layout.Title(text="Frequency of different QAOA measurements", x=0.5), yaxis_title="Frequency", xaxis_tickmode="array", xaxis_tickvals=list(range(len(names))), xaxis_ticktext=tuple(names), ) # Make the multi-bar plot fig = go.Figure(data=bar_plots, layout=layout) # Tell Plotly to render it fig.show() qiskit.__qiskit_version__ ###Output _____no_output_____ ###Markdown Example 02 - Unsupervised Learning - Clustering Quantum Approximate Optimization Algorithm (QAOA) - Proof of Concept*** Thank you to these original authors for making the template Jupyter notebook available to the machine learning community.Peter Wittek and team from the Quantum Machine Learning edx inaugural course. This course will be offered again soon. Check out https://www.edx.org/. References and additional details:https://gitlab.com/qosf/qml-mooc/blob/master/qiskit_version/10_Discrete_Optimization_and_Unsupervised_Learning.ipynb Quantum Computing Framework- [1]IBM QISKit Running the CodeInstalling everything you need on your own laptop takes a little time, so for right now the easiest way to get started is to use a "Binder image". This setup lets you use the code notebooks via the web IMMEDIATELY. I think this is your best approach, for now, because it means you can run the code today to get a feel for how this example of a Quantum Machine Learning algorithm works. In the future, you can follow the full installation process (2 hours) and run your own code. Let's get started. OverviewRun the Jupyter Notebook. If this is your first time using a Jupyter Notebook, select a cell (it will now have a blue border). Now SHIFT then RETURN to run the code on the remote server. The notes below will add explanations and a lot more context to the published notebooks. I thought this was a much more efficient way to help you because you can always link to the newest published code, download it, and use these notes to modify as you wish. Suggestion: Run the code _as is_ the first time. You can then go back and make changes to see how the settings work. Code Block 01In order to cluster some data points, we need to know which ones are close to each other. Let's generate a dataset and assign 2 labels (classes), one red and one green. Clustering very high dimensional data (lots of variables) is a difficult problem for conventional computers, so there is some expectations that quantum machine learning will have some advantage here. This toy problem will give you an example using the QAOA algorithm to find the best cluster. ###Code import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D %matplotlib inline n_instances = 10 class_1 = np.random.rand(n_instances//2, 3)/5 class_2 = (0.6, 0.1, 0.05) + np.random.rand(n_instances//2, 3)/5 data = np.concatenate((class_1, class_2)) colors = ["red"] * (n_instances//2) + ["green"] * (n_instances//2) fig = plt.figure() ax = fig.add_subplot(111, projection='3d', xticks=[], yticks=[], zticks=[]) ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=colors) ###Output _____no_output_____ ###Markdown Code Block 02We are going to use a measure for distance called the Euclidean distance. (There are actually several distance measures (https://en.wikipedia.org/wiki/Norm_(mathematics)). We can calculate all the pairwise distances between the points. ###Code import itertools w = np.zeros((n_instances, n_instances)) for i, j in itertools.product(*[range(n_instances)]*2): w[i, j] = np.linalg.norm(data[i]-data[j]) ###Output _____no_output_____ ###Markdown Code Block 03 Using QAOA to solve to find the best way to cluster the points (optimization)We are going to solve the clustering problem using the QAOA algorithm as the optimization part to get the best answer for how to cluster these points. If we were to use the distance information between the points, we could , draw a graph. The Max Cut approach asked the question, "How can I cut this graph into 2 parts?" The max would be the maximal distances that cross the cut.We'll make use of the built in libraries from QISKit. ###Code from qiskit_aqua import get_aer_backend, QuantumInstance from qiskit_aqua.algorithms import QAOA from qiskit_aqua.components.optimizers import COBYLA from qiskit_aqua.translators.ising import maxcut qubit_operators, offset = maxcut.get_maxcut_qubitops(w) #Setting p=1 to initialize the max-cut problem. p = 1 optimizer = COBYLA() qaoa = QAOA(qubit_operators, optimizer, p, operator_mode='matrix') ###Output _____no_output_____ ###Markdown Here the choice of the classical optimizer `COBYLA` was arbitrary. Let us run this and analyze the solution. This can take a while on a classical simulator. Code Block 04This is the output you should expect. The values will be slightly different but this is how it will look.energy: -0.9232657682915413maxcut objective: -2.5378918584323404solution: [0. 0. 1. 1.]solution objective: 2.9963330796428673 ###Code backend = get_aer_backend('statevector_simulator') quantum_instance = QuantumInstance(backend, shots=100) result = qaoa.run(quantum_instance) x = maxcut.sample_most_likely(result['eigvecs'][0]) graph_solution = maxcut.get_graph_solution(x) print('energy:', result['energy']) print('maxcut objective:', result['energy'] + offset) print('solution:', maxcut.get_graph_solution(x)) print('solution objective:', maxcut.maxcut_value(x, w)) ###Output _____no_output_____ ###Markdown QAOA Homework Quantum Computing FRI Stream Fall 2019 The aim of this project is to use your knowledge of quantum simulation and the quantum approximate optimization algorithm to solve an optimization problem. You will need to figure out how to represent your problem in quantum terms and then use your Hamiltonian to construct the state necessary for QAOA. Use an 8 qubit input space (8 vertices on the graph) and sample across the ranges of the parameters, $\gamma$ and $\beta$, in order to get an idea of where the cost function is the highest and lowest. 1. Choose and describe the problem you'd like to solve: Max-Clique, Weighted Max-Cut, Weighted MAX-SAT, Weighted Graph Coloring, Ising Model Given a graph with weighted edges, is there a subset S of vertices such that the edges connecting S and the complement of S have collective weight of at least W? 2. Cast the problem as an optimization problem. Given a graph with weighted edges, find a subset S of the vertices such that the weight of the edges separating the two subsets is maximized! 3. Write out a general cost function for the problem. This can be the Hamiltonian for the system. $$C=\sum_{i,j} C_{i,j}$$ $$C_{i,j}=\frac{1}{2}({I-Z_{i}Z_{j}})$$ 4. Use your cost function to construct a general constraint operator (called V in the lectures). $$V(\gamma)=e^{-i\gamma\sum_{i,j} \frac{1}{2}(I-Z_{i}Z_{j})}$$ $$V(\gamma)=e^{-i\gamma C}$$$$V(\gamma)=e^{-i\gamma\sum_{i,j} C_{i,j}}$$ Implementation ###Code #Import the necessary tools for the computation from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit from qiskit import execute,Aer from qiskit import* import random as r import numpy as np ###Output _____no_output_____ ###Markdown 5. Write a function to implement V and write a function to implement the driver, W, on your qubit system. ###Code def H(q, qc): qc.h(q[1:]) def v(qc, q, edges, gamma): qc.barrier() for edge in edges: qc.cx(q[edge[1]], q[0]) qc.cx(q[edge[0]], q[0]) #multiply the gamma by the weights qc.u1(gamma * edge[2], q[0]) qc.cx(q[edge[0]], q[0]) qc.cx(q[edge[1]], q[0]) qc.barrier() def w(qc, q, beta): for i in range(1, len(q)): qc.h(i) qc.u1(beta, i) qc.h(i) ###Output _____no_output_____ ###Markdown 6. Prepare the parameters for your simulation. This includes creating a grid of $\gamma$ and $\beta$ parameters. An example of such a grid is given in the assignment slide. Think about how to generate your input space. You will need a graph with 8 vertices and a random assignment of edges. The graph should be connected more fully than a ring but less fully than all-to-all. The edges will determine which qubits you pair up when evaluating your cost function. Make sure to print out the list of edges, so there is a record of your particular graph. You will also need to consider the values you will assign to your qubits. Depending on your choice of problem, you may want to handle the initialization differently. Figure this out now and, perhaps, prepare an array of values you will use in your qubit initialization in the next step. ###Code # for g_row in gamma: # g in g_row: # for beta in b_row: # for b in beta: #put this else wher when you make the circuit def edgy(): edges=[] maxE = (8 *(8-1))//2 numEdges = r.randint(8, maxE) counter =0 i =1 j= 2 #assign a random weight (1, 10) to every combination of edges in a loop for pos in range(8): if i == 8: edges.append([1, i]) else: edges.append([i,j]) i += 1 j += 1 counter += 1 #while loop accounts for all the edges that are not in a closed loop and randomly generates them while counter != numEdges: weight = r.randint(1,10) i= r.randint(1, 8) j = r.randint(1, 8) edge=[i, j] edge.sort() if j != i and edge not in edges: edges.append(edge) counter += 1 edgesF= sorted(edges, key =lambda edge: edge[0]) for edge in edgesF: weight = r.randint(1,10) edge.append(weight) return edgesF def classicalV(bits, prob): count =0 #50 is the number of shots prob = prob / 50 for pos, i in enumerate(bits): while pos < len(bits): j = bits[pos] #the formula is 1/2(1-(-1)^i(-1)^j) where i and j are a comninations of 0,1 that maximizes the value #We do 2^n iterations to find all combinations that work #check to see if this is correct bc technically, you will check all combintations of (i,j) and (j,i); is this not double #counting? if i != j: count += 1 pos+= 1 return count * prob ###Output _____no_output_____ ###Markdown 7. Do the deed! Use your functions to prepare the state at each grid point. Use measurements to evaluate the cost function at each point. Keep track of these values. A loop may be helpful for streamlining your implementation. Your entire quantum circuit should be contained in this step. ###Code gamma,beta = np.mgrid[0:2.1*np.pi:.2*np.pi,0:1.1*np.pi:.2*np.pi] edges = edgy() #print(edges) #print(len(gamma)) #print(gamma) #print(len(beta)) #print(beta) allExVal=[] gamma_list= [value for row in gamma for value in row] beta_list= [value for row in beta for value in row] for g_row, b_row in zip(gamma, beta): for g, b in zip(g_row, b_row): q = QuantumRegister(9) c = ClassicalRegister(9) qbits = [i for i in range(8)] qc = QuantumCircuit(q,c) H(q, qc) v(qc, q, edges, g) w(qc, q, b) qc.measure(q[1:], c[1:]) #probability is the number of times you got that state divided by # of shots(2nd number in dict) #sum over every possibiliity of outcome times probability to get expected outcome; #value of outcome is cost of state; cost of state is classically done by looking at every single egde; #cost = outcome backend = Aer.get_backend('qasm_simulator') job = execute(qc, backend, shots=50) result = job.result() count=result.get_counts(qc) #counts.append(count) exVal = 0; for bits, prob in count.items(): exVal += classicalV(bits, prob) allExVal.append(exVal) print(allExVal) ###Output [18.56, 17.959999999999997, 17.840000000000003, 18.399999999999995, 18.04, 18.599999999999998, 18.44, 17.959999999999997, 17.959999999999997, 17.439999999999998, 17.28, 18.2, 17.72, 18.280000000000005, 18.160000000000007, 16.92, 17.560000000000002, 18.08, 17.919999999999998, 17.680000000000003, 17.64, 17.240000000000002, 18.279999999999998, 17.04, 18.799999999999994, 16.999999999999996, 17.48, 17.52, 17.959999999999997, 17.800000000000004, 18.2, 18.199999999999996, 18.039999999999996, 18.12, 17.720000000000006, 18.599999999999998, 17.72, 17.919999999999995, 17.2, 17.520000000000003, 16.880000000000003, 17.960000000000004, 18.079999999999995, 18.599999999999998, 17.24, 16.92, 18.0, 17.919999999999998, 17.759999999999994, 17.159999999999997, 17.72, 17.479999999999997, 18.24, 17.560000000000002, 17.64, 17.599999999999998, 17.640000000000004, 16.760000000000005, 17.999999999999996, 18.159999999999997, 18.24, 17.839999999999996, 17.2, 18.119999999999997, 18.799999999999994, 18.360000000000003] ###Markdown 8. Plot your results. Creativity is welcome, but one option is a multidimensional histogram with the cost function as the height and the location dependent on the parameter grid. ###Code qc.draw() #uuhhhhh not sure about how to implement a histogram? import matplotlib.pyplot as plt from mpl_toolkits import mplot3d X=np.array(gamma_list) Y=np.array(beta_list) Z=np.array(allExVal) fig = plt.figure() ax = plt.axes(projection='3d') ax.plot_trisurf(X, Y, Z, linewidth=0, antialiased=False) ax.set_title('Expectation Values for Gamma & Beta') ax.set_xlabel('Gamma') ax.set_ylabel('Beta') ###Output _____no_output_____ ###Markdown Quantum Approximate Optimization Algorithm (QAOA) ###Code %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister # import math lib from math import pi # Loading your IBM Q account(s) IBMQ.load_accounts() ###Output _____no_output_____ ###Markdown ![image.png](attachment:image.png) ###Code # To use local qasm simulator backend = Aer.get_backend('qasm_simulator') qr = QuantumRegister(5, name="qr") # create Quantum Register called "cr" with 4 qubits cr = ClassicalRegister(5, name="cr") # Creating Quantum Circuit called "qc" involving your Quantum Register "qr" # and your Classical Register "cr" qc = QuantumCircuit(qr, cr, name="QAOA_Algorithm") qc.h(qr) qc.barrier() qc.cx(qr[0],qr[1]) qc.rz(pi/4, qr[1]) qc.cx(qr[0],qr[1]) qc.barrier() qc.cx(qr[1],qr[2]) qc.rz(pi/4, qr[2]) qc.cx(qr[1],qr[2]) qc.barrier() qc.cx(qr[2],qr[3]) qc.rz(pi/4, qr[3]) qc.cx(qr[2],qr[3]) qc.barrier() qc.cx(qr[3],qr[4]) qc.rz(pi/4, qr[4]) qc.cx(qr[3],qr[4]) qc.barrier() qc.cx(qr[1],qr[3]) qc.rz(pi/4, qr[3]) qc.cx(qr[1],qr[3]) qc.barrier() qc.cx(qr[0],qr[4]) qc.rz(pi/4, qr[4]) qc.cx(qr[0],qr[4]) qc.barrier() qc.rx(-pi/4, qr) qc.barrier() # To measure the whole quantum register qc.measure(qr, cr) circuit_drawer(qc, output='mpl') job = execute(qc, backend=backend, shots=8000,) result = job.result() print(result.get_counts(qc)) plot_histogram(result.get_counts()) import operator temp = result.get_counts(qc) sorted_result = sorted(temp.items(), key=operator.itemgetter(1)) sorted_result ###Output _____no_output_____
courses/machine_learning/datasets/create_datasets.ipynb
###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 13.0,-73.98526,40.759847,-73.998788,40.717047,1,0 12.0,-73.980122,40.754532,-74.00972,40.725982,3,1 11.3,-73.98218,40.727914,-73.959318,40.771487,3,2 7.5,-73.98715,40.751422,-73.988353,40.743075,2,3 9.0,-74.003855,40.74205,-73.985272,40.760585,3,4 13.7,-73.985041,40.73229,-73.967768,40.692949,1,5 11.5,-73.993317,40.71965,-73.944692,40.718173,1,6 11.5,-74.001225,40.725435,-73.987053,40.750883,5,7 11.0,-73.972728,40.74918,-73.997678,40.725742,5,8 15.0,-73.985387,40.727413,-73.949052,40.773221,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 90361 Mar 16 07:08 taxi-test.csv -rw-r--r-- 1 root root 426304 Mar 16 07:08 taxi-train.csv -rw-r--r-- 1 root root 91178 Mar 16 07:08 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 3.3,-74.000315,40.743001,-73.993222,40.743035,1,0 6.5,-73.964189,40.767874,-73.955273,40.783162,1,1 10.9,-73.976996,40.751248,-73.961803,40.776758,1,2 18.5,-73.958089,40.760627,-74.009293,40.734084,1,3 6.1,-73.985568,40.73495,-73.991165,40.748913,5,4 9.3,-73.854578,40.832925,-73.848145,40.833923,1,5 8.0,-73.991682,40.738685,-74.006665,40.727197,5,6 12.1,-73.978531,40.788128,-74.000565,40.737345,1,7 7.5,-73.9789,40.777355,-73.98188,40.766605,5,8 10.0,-73.999286,40.719861,-74.012138,40.701702,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.5574862933877607/km Train RMSE = 6.832614774697732 Valid RMSE = 5.58442972708239 Test RMSE = 6.057465304773869 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.026346679177248 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np import shutil ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` LIMIT 10 """ client = bigquery.Client() trips = client.query(sql).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1 """ trips = client.query(sql).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 """ trips = client.query(sql).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2010-04-29 12:28:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.figure(figsize=(10,8)) plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 21.0,-73.975305,40.790067,-73.996612,40.733275,1,0 12.0,-73.993325,40.736502,-73.969148,40.752752,5,1 9.0,-73.982121,40.778384,-73.972623,40.796093,1,2 5.3,-73.997942,40.735735,-73.98547,40.738608,2,3 10.5,-73.986543,40.730283,-74.006965,40.705447,1,4 25.7,-73.956644,40.771152,-74.005279,40.74028,1,5 13.7,-73.962352,40.758807,-73.941687,40.811947,1,6 8.5,-73.97510528564453,40.7363166809082,-73.98577117919922,40.755611419677734,3,7 5.7,-73.96476,40.773025,-73.964673,40.77295,1,8 6.6,-73.992046,40.751358,-74.003362,40.737756,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 85534 Oct 19 21:23 taxi-test.csv -rw-r--r-- 1 root root 402804 Oct 19 21:23 taxi-train.csv -rw-r--r-- 1 root root 85997 Oct 19 21:23 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %%bash head taxi-train.csv ###Output 9.0,-73.93219757080078,40.79558181762695,-73.93547058105469,40.80010986328125,1,0 4.5,-73.967703,40.756252,-73.972677,40.747745,1,1 30.5,-73.86369323730469,40.76985168457031,-73.8174819946289,40.664794921875,1,2 4.5,-73.969182,40.766816,-73.962413,40.778255,1,3 5.7,-73.975688,40.751843,-73.97884,40.744205,1,4 20.5,-73.993289,40.752283,-73.940769,40.788656,1,5 4.1,-73.944658,40.779262,-73.954415,40.781145,1,6 11.5,-73.834687,40.717252,-73.83961,40.752702,1,7 6.9,-73.987127,40.738842,-73.969777,40.759165,1,8 4.9,-74.008033,40.722897,-74.000918,40.728945,5,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.6002738988685428/km Train RMSE = 7.593609093225721 Valid RMSE = 5.440351676399091 Test RMSE = 9.328946890495182 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key, EXTRACT(DAYOFWEEK FROM pickup_datetime)*1.0 AS dayofweek, EXTRACT(HOUR FROM pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) < 2".format(base_query) else: query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) = {1}".format(base_query, phase) else: query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), {1})) = {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = client.query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 7.4158766166380445 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np import shutil ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` LIMIT 10 """ client = bigquery.Client() trips = client.query(sql).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 """ trips = client.query(sql).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 """ trips = client.query(sql).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2010-04-29 12:28:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.figure(figsize=(10,8)) plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 21.0,-73.975305,40.790067,-73.996612,40.733275,1,0 12.0,-73.993325,40.736502,-73.969148,40.752752,5,1 9.0,-73.982121,40.778384,-73.972623,40.796093,1,2 5.3,-73.997942,40.735735,-73.98547,40.738608,2,3 10.5,-73.986543,40.730283,-74.006965,40.705447,1,4 25.7,-73.956644,40.771152,-74.005279,40.74028,1,5 13.7,-73.962352,40.758807,-73.941687,40.811947,1,6 8.5,-73.97510528564453,40.7363166809082,-73.98577117919922,40.755611419677734,3,7 5.7,-73.96476,40.773025,-73.964673,40.77295,1,8 6.6,-73.992046,40.751358,-74.003362,40.737756,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 85534 Oct 19 21:23 taxi-test.csv -rw-r--r-- 1 root root 402804 Oct 19 21:23 taxi-train.csv -rw-r--r-- 1 root root 85997 Oct 19 21:23 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %%bash head taxi-train.csv ###Output 9.0,-73.93219757080078,40.79558181762695,-73.93547058105469,40.80010986328125,1,0 4.5,-73.967703,40.756252,-73.972677,40.747745,1,1 30.5,-73.86369323730469,40.76985168457031,-73.8174819946289,40.664794921875,1,2 4.5,-73.969182,40.766816,-73.962413,40.778255,1,3 5.7,-73.975688,40.751843,-73.97884,40.744205,1,4 20.5,-73.993289,40.752283,-73.940769,40.788656,1,5 4.1,-73.944658,40.779262,-73.954415,40.781145,1,6 11.5,-73.834687,40.717252,-73.83961,40.752702,1,7 6.9,-73.987127,40.738842,-73.969777,40.759165,1,8 4.9,-74.008033,40.722897,-74.000918,40.728945,5,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.6002738988685428/km Train RMSE = 7.593609093225721 Valid RMSE = 5.440351676399091 Test RMSE = 9.328946890495182 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key, EXTRACT(DAYOFWEEK FROM pickup_datetime)*1.0 AS dayofweek, EXTRACT(HOUR FROM pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) < 2".format(base_query) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) = {1}".format(base_query, phase) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), {1}) = {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = client.query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 7.4158766166380445 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 56.8,-73.981978,40.725422,-73.790372,40.643927,1,0 9.5,-73.975295,40.752457,-73.983147,40.72823,1,1 9.0,-73.96871,40.761032,-73.955596,40.783619,2,2 6.5,-73.976582,40.7806,-73.982427,40.769627,1,3 4.1,-73.9978,40.7567,-73.9901,40.7522,2,4 8.1,-73.977158,40.758883,-74.00551,40.740361,2,5 26.67,-73.885272,40.773025,-73.984643,40.758213,1,6 12.5,-73.983319,40.760634,-74.017155,40.709309,1,7 18.5,-73.90839,40.848737,-73.90839,40.848737,3,8 9.3,-73.979945,40.730363,-73.971058,40.758992,2,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 91076 Jan 22 17:06 taxi-test.csv -rw-r--r-- 1 root root 426370 Jan 22 17:06 taxi-train.csv -rw-r--r-- 1 root root 90397 Jan 22 17:06 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 10.9,-73.97489,40.759088,-73.970657,40.796762,1,0 10.9,-73.996542,40.74797,-73.975082,40.787575,1,1 14.5,-73.879478,40.724003,-73.853958,40.716368,1,2 13.0,-73.97418975830078,40.78383255004883,-73.99554443359375,40.749813079833984,1,3 4.9,-73.975884,40.765513,-73.98107,40.765778,1,4 5.0,-73.998785,40.739953,-73.999444,40.747482,1,5 7.5,-74.002011,40.750752,-73.983832,40.773732,1,6 20.5,-73.95597,40.771925,-73.925827,40.768997,1,7 10.0,-73.992727,40.723397,-73.995695,40.741075,6,8 6.5,-73.985705,40.741277,-74.001407,40.737087,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.5734704317375945/km Train RMSE = 5.614370018489976 Valid RMSE = 6.064356515662454 Test RMSE = 10.319840728012329 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.026346679177248 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` LIMIT 10 """ client = bigquery.Client() trips = client.query(sql).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 """ trips = client.query(sql).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 """ trips = client.query(sql).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == pd.Timestamp('2010-04-29 12:28:00')] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.figure(figsize=(10,8)) plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 21.0,-73.975305,40.790067,-73.996612,40.733275,1,0 12.0,-73.993325,40.736502,-73.969148,40.752752,5,1 9.0,-73.982121,40.778384,-73.972623,40.796093,1,2 5.3,-73.997942,40.735735,-73.98547,40.738608,2,3 10.5,-73.986543,40.730283,-74.006965,40.705447,1,4 25.7,-73.956644,40.771152,-74.005279,40.74028,1,5 13.7,-73.962352,40.758807,-73.941687,40.811947,1,6 8.5,-73.97510528564453,40.7363166809082,-73.98577117919922,40.755611419677734,3,7 5.7,-73.96476,40.773025,-73.964673,40.77295,1,8 6.6,-73.992046,40.751358,-74.003362,40.737756,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 85534 Oct 19 21:23 taxi-test.csv -rw-r--r-- 1 root root 402804 Oct 19 21:23 taxi-train.csv -rw-r--r-- 1 root root 85997 Oct 19 21:23 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 9.0,-73.93219757080078,40.79558181762695,-73.93547058105469,40.80010986328125,1,0 4.5,-73.967703,40.756252,-73.972677,40.747745,1,1 30.5,-73.86369323730469,40.76985168457031,-73.8174819946289,40.664794921875,1,2 4.5,-73.969182,40.766816,-73.962413,40.778255,1,3 5.7,-73.975688,40.751843,-73.97884,40.744205,1,4 20.5,-73.993289,40.752283,-73.940769,40.788656,1,5 4.1,-73.944658,40.779262,-73.954415,40.781145,1,6 11.5,-73.834687,40.717252,-73.83961,40.752702,1,7 6.9,-73.987127,40.738842,-73.969777,40.759165,1,8 4.9,-74.008033,40.722897,-74.000918,40.728945,5,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.6002738988685428/km Train RMSE = 7.593609093225721 Valid RMSE = 5.440351676399091 Test RMSE = 9.328946890495182 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key, EXTRACT(DAYOFWEEK FROM pickup_datetime)*1.0 AS dayofweek, EXTRACT(HOUR FROM pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) < 2".format(base_query) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) = {1}".format(base_query, phase) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), {1}) = {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = client.query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 7.4158766166380445 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at $45 and $50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print cols # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1)))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print "{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-train.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print "Rate = ${0}/km".format(rate) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np import shutil ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` LIMIT 10 """ client = bigquery.Client() trips = client.query(sql).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1 """ trips = client.query(sql).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 100000)) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 """ trips = client.query(sql).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2010-04-29 12:28:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.figure(figsize=(10,8)) plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 21.0,-73.975305,40.790067,-73.996612,40.733275,1,0 12.0,-73.993325,40.736502,-73.969148,40.752752,5,1 9.0,-73.982121,40.778384,-73.972623,40.796093,1,2 5.3,-73.997942,40.735735,-73.98547,40.738608,2,3 10.5,-73.986543,40.730283,-74.006965,40.705447,1,4 25.7,-73.956644,40.771152,-74.005279,40.74028,1,5 13.7,-73.962352,40.758807,-73.941687,40.811947,1,6 8.5,-73.97510528564453,40.7363166809082,-73.98577117919922,40.755611419677734,3,7 5.7,-73.96476,40.773025,-73.964673,40.77295,1,8 6.6,-73.992046,40.751358,-74.003362,40.737756,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 85534 Oct 19 21:23 taxi-test.csv -rw-r--r-- 1 root root 402804 Oct 19 21:23 taxi-train.csv -rw-r--r-- 1 root root 85997 Oct 19 21:23 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %%bash head taxi-train.csv ###Output 9.0,-73.93219757080078,40.79558181762695,-73.93547058105469,40.80010986328125,1,0 4.5,-73.967703,40.756252,-73.972677,40.747745,1,1 30.5,-73.86369323730469,40.76985168457031,-73.8174819946289,40.664794921875,1,2 4.5,-73.969182,40.766816,-73.962413,40.778255,1,3 5.7,-73.975688,40.751843,-73.97884,40.744205,1,4 20.5,-73.993289,40.752283,-73.940769,40.788656,1,5 4.1,-73.944658,40.779262,-73.954415,40.781145,1,6 11.5,-73.834687,40.717252,-73.83961,40.752702,1,7 6.9,-73.987127,40.738842,-73.969777,40.759165,1,8 4.9,-74.008033,40.722897,-74.000918,40.728945,5,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.6002738988685428/km Train RMSE = 7.593609093225721 Valid RMSE = 5.440351676399091 Test RMSE = 9.328946890495182 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key, EXTRACT(DAYOFWEEK FROM pickup_datetime)*1.0 AS dayofweek, EXTRACT(HOUR FROM pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) < 2".format(base_query) else: query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 4)) = {1}".format(base_query, phase) else: query = "{0} AND ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), {1})) = {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = client.query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 7.4158766166380445 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print cols # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1)))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print "{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-train.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print "Rate = ${0}/km".format(rate) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code from google.cloud import bigquery import seaborn as sns import matplotlib.pyplot as plt import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` LIMIT 10 """ client = bigquery.Client() trips = client.query(sql).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 """ trips = client.query(sql).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code sql = """ SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 """ trips = client.query(sql).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", fit_reg=False, ci=None, truncate=True, data=trips) ax.figure.set_size_inches(10, 8) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == pd.Timestamp('2010-04-29 12:28:00')] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.figure(figsize=(10,8)) plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output /usr/local/envs/py3env/lib/python3.5/site-packages/matplotlib/font_manager.py:1320: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext])) ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print (cols) # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 21.0,-73.975305,40.790067,-73.996612,40.733275,1,0 12.0,-73.993325,40.736502,-73.969148,40.752752,5,1 9.0,-73.982121,40.778384,-73.972623,40.796093,1,2 5.3,-73.997942,40.735735,-73.98547,40.738608,2,3 10.5,-73.986543,40.730283,-74.006965,40.705447,1,4 25.7,-73.956644,40.771152,-74.005279,40.74028,1,5 13.7,-73.962352,40.758807,-73.941687,40.811947,1,6 8.5,-73.97510528564453,40.7363166809082,-73.98577117919922,40.755611419677734,3,7 5.7,-73.96476,40.773025,-73.964673,40.77295,1,8 6.6,-73.992046,40.751358,-74.003362,40.737756,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 85534 Oct 19 21:23 taxi-test.csv -rw-r--r-- 1 root root 402804 Oct 19 21:23 taxi-train.csv -rw-r--r-- 1 root root 85997 Oct 19 21:23 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %%bash head taxi-train.csv ###Output 9.0,-73.93219757080078,40.79558181762695,-73.93547058105469,40.80010986328125,1,0 4.5,-73.967703,40.756252,-73.972677,40.747745,1,1 30.5,-73.86369323730469,40.76985168457031,-73.8174819946289,40.664794921875,1,2 4.5,-73.969182,40.766816,-73.962413,40.778255,1,3 5.7,-73.975688,40.751843,-73.97884,40.744205,1,4 20.5,-73.993289,40.752283,-73.940769,40.788656,1,5 4.1,-73.944658,40.779262,-73.954415,40.781145,1,6 11.5,-73.834687,40.717252,-73.83961,40.752702,1,7 6.9,-73.987127,40.738842,-73.969777,40.759165,1,8 4.9,-74.008033,40.722897,-74.000918,40.728945,5,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print ("{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name)) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print ("Rate = ${0}/km".format(rate)) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.6002738988685428/km Train RMSE = 7.593609093225721 Valid RMSE = 5.440351676399091 Test RMSE = 9.328946890495182 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(CAST(pickup_datetime AS STRING), CAST(pickup_longitude AS STRING), CAST(pickup_latitude AS STRING), CAST(dropoff_latitude AS STRING), CAST(dropoff_longitude AS STRING)) AS key, EXTRACT(DAYOFWEEK FROM pickup_datetime)*1.0 AS dayofweek, EXTRACT(HOUR FROM pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) < 2".format(base_query) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 4) = {1}".format(base_query, phase) else: query = "{0} AND MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), {1}) = {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = client.query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 7.4158766166380445 ###Markdown Explore and create ML datasets In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the charge is much higher than expected.Let's start off with the Python imports that we need. ###Code import datalab.bigquery as bq import seaborn as sns import pandas as pd import numpy as np import shutil %%javascript $.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js') ###Output _____no_output_____ ###Markdown Extract sample data from BigQuery The dataset that we will use is a BigQuery public dataset. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is one billion, and then switch to the Preview tab to look at a few rows.Let's write a SQL query to pick up interesting fields from the dataset. ###Code %sql --module afewrecords SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] LIMIT 10 trips = bq.Query(afewrecords).to_dataframe() trips ###Output _____no_output_____ ###Markdown Let's increase the number of records so that we can do some neat graphs. There is no guarantee about the order in which records are returned, and so no guarantee about which records get returned if we simply increase the LIMIT. To properly sample the dataset, let's use the HASH of the pickup time and return 1 in 100,000 records -- because there are 1 billion records in the data, we should get back approximately 10,000 records if we do this. ###Code %sql --module afewrecords2 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE ABS(HASH(pickup_datetime)) % $EVERY_N == 1 trips = bq.Query(afewrecords2, EVERY_N=100000).to_dataframe() trips[:10] ###Output _____no_output_____ ###Markdown Exploring data Let's explore this dataset and clean it up as necessary. We'll use the Python Seaborn package to visualize graphs and Pandas to do the slicing and filtering. ###Code ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown Hmm ... do you see something wrong with the data that needs addressing?It appears that we have a lot of invalid data that is being coded as zero distance and some fare amounts that are definitely illegitimate. Let's remove them from our analysis. We can do this by modifying the BigQuery query to keep only trips longer than zero miles and fare amounts that are at least the minimum cab fare ($2.50).Note the extra WHERE clauses. ###Code %sql --module afewrecords3 SELECT pickup_datetime, pickup_longitude, pickup_latitude, dropoff_longitude, dropoff_latitude, passenger_count, trip_distance, tolls_amount, fare_amount, total_amount FROM [nyc-tlc:yellow.trips] WHERE (ABS(HASH(pickup_datetime)) % $EVERY_N == 1 AND trip_distance > 0 AND fare_amount >= 2.5) trips = bq.Query(afewrecords3, EVERY_N=100000).to_dataframe() ax = sns.regplot(x="trip_distance", y="fare_amount", ci=None, truncate=True, data=trips) ###Output _____no_output_____ ###Markdown What's up with the streaks at \$45 and \$50? Those are fixed-amount rides from JFK and La Guardia airports into anywhere in Manhattan, i.e. to be expected. Let's list the data to make sure the values look reasonable.Let's examine whether the toll amount is captured in the total amount. ###Code tollrides = trips[trips['tolls_amount'] > 0] tollrides[tollrides['pickup_datetime'] == '2012-09-05 15:45:00'] ###Output _____no_output_____ ###Markdown Looking a few samples above, it should be clear that the total amount reflects fare amount, toll and tip somewhat arbitrarily -- this is because when customers pay cash, the tip is not known. So, we'll use the sum of fare_amount + tolls_amount as what needs to be predicted. Tips are discretionary and do not have to be included in our fare estimation tool.Let's also look at the distribution of values within the columns. ###Code trips.describe() ###Output _____no_output_____ ###Markdown Hmm ... The min, max of longitude look strange.Finally, let's actually look at the start and end of a few of the trips. ###Code def showrides(df, numlines): import matplotlib.pyplot as plt lats = [] lons = [] for iter, row in df[:numlines].iterrows(): lons.append(row['pickup_longitude']) lons.append(row['dropoff_longitude']) lons.append(None) lats.append(row['pickup_latitude']) lats.append(row['dropoff_latitude']) lats.append(None) sns.set_style("darkgrid") plt.plot(lons, lats) showrides(trips, 10) showrides(tollrides, 10) ###Output _____no_output_____ ###Markdown As you'd expect, rides that involve a toll are longer than the typical ride. Quality control and other preprocessing We need to some clean-up of the data:New York city longitudes are around -74 and latitudes are around 41.We shouldn't have zero passengers.Clean up the total_amount column to reflect only fare_amount and tolls_amount, and then remove those two columns.Before the ride starts, we'll know the pickup and dropoff locations, but not the trip distance (that depends on the route taken), so remove it from the ML datasetDiscard the timestampWe could do preprocessing in BigQuery, similar to how we removed the zero-distance rides, but just to show you another option, let's do this in Python. In production, we'll have to carry out the same preprocessing on the real-time input data. This sort of preprocessing of input data is quite common in ML, especially if the quality-control is dynamic. ###Code def preprocess(trips_in): trips = trips_in.copy(deep=True) trips.fare_amount = trips.fare_amount + trips.tolls_amount del trips['tolls_amount'] del trips['total_amount'] del trips['trip_distance'] del trips['pickup_datetime'] qc = np.all([\ trips['pickup_longitude'] > -78, \ trips['pickup_longitude'] < -70, \ trips['dropoff_longitude'] > -78, \ trips['dropoff_longitude'] < -70, \ trips['pickup_latitude'] > 37, \ trips['pickup_latitude'] < 45, \ trips['dropoff_latitude'] > 37, \ trips['dropoff_latitude'] < 45, \ trips['passenger_count'] > 0, ], axis=0) return trips[qc] tripsqc = preprocess(trips) tripsqc.describe() ###Output _____no_output_____ ###Markdown The quality control has removed about 300 rows (11400 - 11101) or about 3% of the data. This seems reasonable.Let's move on to creating the ML datasets. Create ML datasets Let's split the QCed data randomly into training, validation and test sets. ###Code shuffled = tripsqc.sample(frac=1) trainsize = int(len(shuffled['fare_amount']) * 0.70) validsize = int(len(shuffled['fare_amount']) * 0.15) df_train = shuffled.iloc[:trainsize, :] df_valid = shuffled.iloc[trainsize:(trainsize+validsize), :] df_test = shuffled.iloc[(trainsize+validsize):, :] df_train.describe() df_valid.describe() df_test.describe() ###Output _____no_output_____ ###Markdown Let's write out the three dataframes to appropriately named csv files. We can use these csv files for local training (recall that these files represent only 1/100,000 of the full dataset) until we get to point of using Dataflow and Cloud ML. ###Code def to_csv(df, filename): outdf = df.copy(deep=False) outdf.loc[:, 'key'] = np.arange(0, len(outdf)) # rownumber as key # reorder columns so that target is first column cols = outdf.columns.tolist() cols.remove('fare_amount') cols.insert(0, 'fare_amount') print cols # new order of columns outdf = outdf[cols] outdf.to_csv(filename, header=False, index_label=False, index=False) to_csv(df_train, 'taxi-train.csv') to_csv(df_valid, 'taxi-valid.csv') to_csv(df_test, 'taxi-test.csv') !head -10 taxi-valid.csv ###Output 6.0,-74.013667,40.713935,-74.007627,40.702992,2,0 9.3,-74.007025,40.730305,-73.979111,40.752267,1,1 6.9,-73.9664,40.7598,-73.9864,40.7624,1,2 36.8,-73.961938,40.773337,-73.86582,40.769607,1,3 6.5,-73.989408,40.735895,-73.9806,40.745115,1,4 5.5,-73.983033,40.739107,-73.979105,40.74436,6,5 4.9,-73.983879,40.761266,-73.982485,40.768045,1,6 5.3,-73.991107,40.733908,-73.991082,40.74567,3,7 12.0,-73.96837,40.762312,-73.999902,40.720617,1,8 6.9,-73.97555,40.776823,-73.960875,40.770087,1,9 ###Markdown Verify that datasets exist ###Code !ls -l *.csv ###Output -rw-r--r-- 1 root root 88622 Feb 26 02:34 taxi-test.csv -rw-r--r-- 1 root root 417222 Feb 26 02:34 taxi-train.csv -rw-r--r-- 1 root root 88660 Feb 26 02:34 taxi-valid.csv ###Markdown We have 3 .csv files corresponding to train, valid, test. The ratio of file-sizes correspond to our split of the data. ###Code %bash head taxi-train.csv ###Output 12.0,-73.987625,40.750617,-73.971163,40.78518,1,0 4.5,-73.96362,40.774363,-73.953485,40.772665,1,1 4.5,-73.989649,40.756633,-73.985597,40.765662,1,2 10.0,-73.9939498901,40.7275238037,-74.0065841675,40.7442398071,1,3 2.5,-73.950223,40.66896,-73.948112,40.668872,6,4 7.3,-73.98511,40.742173,-73.96586,40.759668,4,5 8.1,-73.997638,40.720887,-74.012937,40.716323,2,6 41.5,-74.004283,40.740476,-73.897273,40.817774,2,7 5.3,-73.984345,40.755862,-73.98152,40.750347,1,8 13.5,-73.9615020752,40.7683258057,-73.9846801758,40.7363166809,1,9 ###Markdown Looks good! We now have our ML datasets and are ready to train ML models, validate them and evaluate them. Benchmark Before we start building complex ML models, it is a good idea to come up with a very simple model and use that as a benchmark.My model is going to be to simply divide the mean fare_amount by the mean trip_distance to come up with a rate and use that to predict. Let's compute the RMSE of such a model. ###Code import datalab.bigquery as bq import pandas as pd import numpy as np import shutil def distance_between(lat1, lon1, lat2, lon2): # haversine formula to compute distance "as the crow flies". Taxis can't fly of course. dist = np.degrees(np.arccos(np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1)))) * 60 * 1.515 * 1.609344 return dist def estimate_distance(df): return distance_between(df['pickuplat'], df['pickuplon'], df['dropofflat'], df['dropofflon']) def compute_rmse(actual, predicted): return np.sqrt(np.mean((actual-predicted)**2)) def print_rmse(df, rate, name): print "{1} RMSE = {0}".format(compute_rmse(df['fare_amount'], rate*estimate_distance(df)), name) FEATURES = ['pickuplon','pickuplat','dropofflon','dropofflat','passengers'] TARGET = 'fare_amount' columns = list([TARGET]) columns.extend(FEATURES) # in CSV, target is the first column, after the features columns.append('key') df_train = pd.read_csv('taxi-train.csv', header=None, names=columns) df_valid = pd.read_csv('taxi-valid.csv', header=None, names=columns) df_test = pd.read_csv('taxi-test.csv', header=None, names=columns) rate = df_train['fare_amount'].mean() / estimate_distance(df_train).mean() print "Rate = ${0}/km".format(rate) print_rmse(df_train, rate, 'Train') print_rmse(df_valid, rate, 'Valid') print_rmse(df_test, rate, 'Test') ###Output Rate = $2.58056321263/km Train RMSE = 6.78227475714 Valid RMSE = 6.78227475714 Test RMSE = 5.56794896998 ###Markdown Benchmark on same datasetThe RMSE depends on the dataset, and for comparison, we have to evaluate on the same dataset each time. We'll use this query in later labs: ###Code def create_query(phase, EVERY_N): """ phase: 1=train 2=valid """ base_query = """ SELECT (tolls_amount + fare_amount) AS fare_amount, CONCAT(STRING(pickup_datetime), STRING(pickup_longitude), STRING(pickup_latitude), STRING(dropoff_latitude), STRING(dropoff_longitude)) AS key, DAYOFWEEK(pickup_datetime)*1.0 AS dayofweek, HOUR(pickup_datetime)*1.0 AS hourofday, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, FROM [nyc-tlc:yellow.trips] WHERE trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 """ if EVERY_N == None: if phase < 2: # training query = "{0} AND ABS(HASH(pickup_datetime)) % 4 < 2".format(base_query) else: query = "{0} AND ABS(HASH(pickup_datetime)) % 4 == {1}".format(base_query, phase) else: query = "{0} AND ABS(HASH(pickup_datetime)) % {1} == {2}".format(base_query, EVERY_N, phase) return query query = create_query(2, 100000) df_valid = bq.Query(query).to_dataframe() print_rmse(df_valid, 2.56, 'Final Validation Set') ###Output Final Validation Set RMSE = 8.02608564676
notebooks/4.1.2.1_CO2_Emissionen_Vergleich_OIB_RL6.ipynb
###Markdown [Inhaltsverzeichnis](../AP4.ipynb) | [ next](wohin?) 4.1.1 CO2 Emissionen 4.1.1.1 Vergleich zu OIB RL 6 ###Code # OPTIONAL: Load the "autoreload" extension so that code can change from importlib import reload %load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loaded %autoreload 2 %matplotlib inline from FLUCCOplus.notebooks import * import FLUCCOplus.electricitymap as elmap OIB_RL6 = [ ["Jänner" , 1.98, 1.46, 0.52, 332], ["Februar" , 1.97, 1.42, 0.55, 322], ["März" , 1.89, 1.28, 0.61, 288], ["April" , 1.73, 1.03, 0.7, 230], ["Mai" , 1.61, 0.85, 0.76, 182], ["Juni" , 1.60, 0.83, 0.77, 179], ["Juli" , 1.58, 0.82, 0.76, 178], ["August" , 1.62, 0.85, 0.77, 182], ["September", 1.73, 1.03, 0.70, 227], ["Oktober" , 1.88, 1.26, 0.62, 284], ["November" , 1.94, 1.38, 0.56, 308], ["Dezember" , 1.96,1.42, 0.54, 318] ] df_OIB_RL6 = pd.DataFrame(OIB_RL6, columns = ["month","fPE","fPE,n.ern", "fPE,ern" , "fCO2eq" ]) oib_co2 = df_OIB_RL6["fCO2eq"] df_2015_2019 = elmap.read_interim("em_common_15-19.csv") rs = df_2015_2019.resample("D").mean() from FLUCCOplus.plots import plot_OIBCO2_comparison, emissionyear fig = plot_OIBCO2_comparison(rs, oib_co2, [2015, 2016, 2017, 2018, 2019]) fig.savefig("../data/processed/figures/OIBCO2Vergleich", dpi=config.DPI, bbox_inches = 'tight') ###Output C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) ###Markdown Annual Carbon Emission Averages ###Code avg = elmap.annual_emissions() avg.plot(kind="bar", color=["blue", "blue", "blue","blue","lightblue","turquoise","cyan","red"]) data = elmap.fetch_common() numerical = ["carbon_intensity_avg"] titles = ["CO2 Intensität [gCO2eq/kWh]"] data = data[numerical] sns.set(style="whitegrid", palette=sns.cubehelix_palette(8), context="talk") fig, ax = plt.subplots(1,2, figsize=(16,6)) for col, var in enumerate(numerical): sns.lineplot(x=data.index.month, y=var, data=data, hue=data.index.year, ax=ax[0]); avg.plot(kind="bar", color=["blue", "blue", "blue","blue","lightblue","turquoise","cyan","red"], ax=ax[1]) ax[col].set(xlabel="Monat",ylabel=titles) ax[0].set_ylim(0,350) ax[1].set_ylim(0,350) from FLUCCOplus.plots import plot_HDW fig, ax = plt.subplots(1, 1, figsize=(12,5)) oib19 = pd.Series([227 for m in df_2015_2019.index.month], df_2015_2019.index) oib19.plot(color="darkred", linewidth=3, ax=ax) fig = plot_HDW(df=df_2015_2019, fig=fig, ax=ax, legend=["OIB RL6 2019","Hourly","Daily average", "Weekly average"]) ax.set_ylim(0,400) fig.savefig("../data/processed/figures/Emissions_HDW_2019", dpi=config.DPI, bbox_inches = 'tight') ###Output _____no_output_____ ###Markdown [Inhaltsverzeichnis](../AP4.ipynb) | [ next](wohin?) 4.1.1 CO2 Emissionen 4.1.1.1 Vergleich zu OIB RL 6 ###Code # OPTIONAL: Load the "autoreload" extension so that code can change from importlib import reload %load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loaded %autoreload 2 %matplotlib inline from FLUCCOplus.notebooks import * import FLUCCOplus.electricitymap as elmap OIB_RL6 = [ ["Jänner" , 1.98, 1.46, 0.52, 332], ["Februar" , 1.97, 1.42, 0.55, 322], ["März" , 1.89, 1.28, 0.61, 288], ["April" , 1.73, 1.03, 0.7, 230], ["Mai" , 1.61, 0.85, 0.76, 182], ["Juni" , 1.60, 0.83, 0.77, 179], ["Juli" , 1.58, 0.82, 0.76, 178], ["August" , 1.62, 0.85, 0.77, 182], ["September", 1.73, 1.03, 0.70, 227], ["Oktober" , 1.88, 1.26, 0.62, 284], ["November" , 1.94, 1.38, 0.56, 308], ["Dezember" , 1.96,1.42, 0.54, 318] ] df_OIB_RL6 = pd.DataFrame(OIB_RL6, columns = ["month","fPE","fPE,n.ern", "fPE,ern" , "fCO2eq" ]) oib_co2 = df_OIB_RL6["fCO2eq"] df_2015_2019 = elmap.read_interim("em_common_15-19.csv") rs = df_2015_2019.resample("D").mean() from FLUCCOplus.plots import plot_OIBCO2_comparison, emissionyear fig = plot_OIBCO2_comparison(rs, oib_co2, [2015, 2016, 2017, 2018, 2019]) fig.savefig("../data/processed/figures/OIBCO2Vergleich", dpi=config.DPI, bbox_inches = 'tight'); ###Output C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) C:\Users\Simon Schneider\PycharmProjects\FLUCCOplus\FLUCCOplus\plots.py:51: FutureWarning: weekofyear and week have been deprecated, please use DatetimeIndex.isocalendar().week instead, which returns a Series. To exactly reproduce the behavior of week and weekofyear and return an Index, you may call pd.Int64Index(idx.isocalendar().week) sns.lineplot(x=rs.index.week, y=var, data=rs, color="black", ax=ax, ci=99.9) ###Markdown Annual Carbon Emission Averages ###Code avg = elmap.annual_emissions() avg.plot(kind="bar", color=["blue", "blue", "blue","blue","lightblue","turquoise","cyan","red"]) data = elmap.fetch_common() numerical = ["carbon_intensity_avg"] titles = ["CO2 Intensität [gCO2eq/kWh]"] data = data[numerical] sns.set(style="whitegrid", palette=sns.cubehelix_palette(8), context="talk") fig, ax = plt.subplots(1,2, figsize=(16,6)) for col, var in enumerate(numerical): sns.lineplot(x=data.index.month, y=var, data=data, hue=data.index.year, ax=ax[0]); avg.plot(kind="bar", color=["blue", "blue", "blue","blue","lightblue","turquoise","cyan","red"], ax=ax[1]) ax[col].set(xlabel="Monat",ylabel=titles) ax[0].set_ylim(0,350) ax[1].set_ylim(0,350) from FLUCCOplus.plots import plot_HDW fig, ax = plt.subplots(1, 1, figsize=(12,5)) oib19 = pd.Series([227 for m in df_2015_2019.index.month], df_2015_2019.index) oib19.plot(color="darkred", linewidth=3, ax=ax) fig = plot_HDW(df=df_2015_2019, fig=fig, ax=ax, legend=["OIB RL6 2019","Hourly","Daily average", "Weekly average"]) ax.set_ylim(0,400) fig.savefig("../data/processed/figures/Emissions_HDW_2019", dpi=config.DPI, bbox_inches = 'tight') ###Output _____no_output_____
projects/neurons/neurons_videos.ipynb
###Markdown Overview videos Video: Steinmetz dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="WXn4-FpVaOo", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Stringer dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="78GSgf6Dkkk", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Allen Institute dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="3YP-GYvYnuA", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Overview videos Video: Steinmetz dataset ###Code # @title Video: Steinmetz dataset from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="WXn4-FpVaOo", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Stringer dataset ###Code # @title Video: Large-scale calcium imaging from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="78GSgf6Dkkk", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Allen Institute dataset ###Code # @title Video: Large-scale calcium imaging from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="3YP-GYvYnuA", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Overview videos Video: Steinmetz dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="WXn4-FpVaOo", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Stringer dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="78GSgf6Dkkk", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Allen Institute dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1KL411W7bY", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="3YP-GYvYnuA", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Overview videos Video: Steinmetz dataset ###Code # @title Video: Steinmetz dataset from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="WXn4-FpVaOo", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Large-scale calcium imaging ###Code # @title Video: Large-scale calcium imaging from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="78GSgf6Dkkk", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Overview videos Video: Steinmetz dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="WXn4-FpVaOo", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Stringer dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="78GSgf6Dkkk", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____ ###Markdown Video: Allen Institute dataset ###Code # @markdown from ipywidgets import widgets out2 = widgets.Output() with out2: from IPython.display import IFrame class BiliVideo(IFrame): def __init__(self, id, page=1, width=400, height=300, **kwargs): self.id=id src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page) super(BiliVideo, self).__init__(src, width, height, **kwargs) video = BiliVideo(id="BV1KL411W7bY", width=730, height=410, fs=1) print('Video available at https://www.bilibili.com/video/{0}'.format(video.id)) display(video) out1 = widgets.Output() with out1: from IPython.display import YouTubeVideo video = YouTubeVideo(id="3YP-GYvYnuA", width=730, height=410, fs=1, rel=0) print('Video available at https://youtube.com/watch?v=' + video.id) display(video) out = widgets.Tab([out1, out2]) out.set_title(0, 'Youtube') out.set_title(1, 'Bilibili') display(out) ###Output _____no_output_____
Reto2/Genera_Entregable_Reto2A.ipynb
###Markdown Notebook para generar csv con texto extraido de la imagen **Hackaton RIIAA 2021 Reto 2** Segmentacion y Reconocimiento de Texto en un Documento **Equipo:** Pista latente ML **Integrantes:** - Andrea Berenice Ek Hobak - Gabriela Marali Mundo Cortes - Mario Xavier Canche Uc - Myrna Citlali Castillo Silva - Ramon Sidonio Aparicio Garcia Montamos carpeta en Drive ###Code # Montamos el Drive al Notebook from google.colab import drive drive.mount('/content/drive', force_remount=True) # Verificamos el directorio en el que nos encontramos !pwd !ls # Cambiamos de directorio al Drive import os os.chdir("drive/My Drive/Hackaton2021/codigo/Entregables/Reto2") !ls ###Output Genera_Entregable_Reto2A.ipynb output StepByStep_Reto2A.ipynb model __pycache__ TextRecognition.py ###Markdown Instalamos las librerias ###Code # Instalamos Tesseract !sudo apt install tesseract-ocr # Instalamos tesseract para python !pip install pytesseract # Instalamos pylsd, it is the python bindings for LSD - Line Segment Detector !pip install ocrd-fork-pylsd ###Output _____no_output_____ ###Markdown Descargamos y copiamos el BEST MODEL LSTM ###Code # Descargar el mejor modelo del github de tesseract # https://github.com/tesseract-ocr/tessdata_best # Eliminamos el modelo default %rm /usr/share/tesseract-ocr/4.00/tessdata/eng.traineddata # Copiamos el modelo descargado %cp model/eng.traineddata /usr/share/tesseract-ocr/4.00/tessdata/ ###Output _____no_output_____ ###Markdown Cargamos las librerias ###Code # Cargamos las librerias import numpy as np # Cargamos nuestro script de segmentacion y extraccion de texto from TextRecognition import get_text import pandas as pd from os import listdir ###Output _____no_output_____ ###Markdown Cargamos las rutas de las imagenes a procesar ###Code # Rutas de las imagenes path_dir = '../../../Datos - Hackathon JusticIA/Evaluacion/Reto2' archivos = listdir(path_dir) archivos ###Output _____no_output_____ ###Markdown Procesamos las imágenes, extraemos el texto y guardamos en un csv ###Code # Nombre del csv de salida con los resultados archivo_out = "output/Evaluacion_Reto2A.csv" data = [] # Iteramos todos los archivos a procesar for i, archivo in enumerate(archivos): # Creamos el path de la imagen file_name = path_dir + '/' + archivo print("-- procesando: ", file_name, "\t\t ", 100*(i+1)/len(archivos) , " %") # Extraemos el texto de la imagen output_text = get_text(file_name, view=True) data.append([file_name,output_text]) print("-- Finalizado con exito!!! 100%") # Convertimos DataFrame y Guardamos output = pd.DataFrame(data, columns=["filename","text"]) output.to_csv(archivo_out, index=False) print("-- Guardado exitosamente!!!") ###Output _____no_output_____ ###Markdown Cargamos el csv con los resultados de evaluación ###Code df = pd.read_csv(archivo_out) df ###Output _____no_output_____
localization_along_line.ipynb
###Markdown Under construction... Kinematic bicycle modelThe dynamic system equations are given by$\dot X=f(x,y,\psi)=\begin{pmatrix} \dot x \\ \dot y \\ \dot \psi\end{pmatrix}=\begin{pmatrix} v \cos( \delta + \psi) \\ v \sin( \delta + \psi) \\ v / l_r \sin( \delta ), \\\end{pmatrix}$with the state vector$ X = [ x, y, \psi ]^T $.Herein, $x$ and $y$ denote the coordinates of the vehicle front axle in cartesian space and $\psi$ the vehicle body orientation angle. The system inputs are the steering angle $\delta$ and the vehicle velocity $v$. Finally, the parameter $l_r$ denotes the wheelbase, which is the length in-between front and rear axle. ###Code x, y, v, delta, psi, l_r, T_s, n = sp.symbols('x y v delta psi l_r T_s n') x_dot = v * sp.cos( delta + psi ) y_dot = v * sp.sin( delta + psi ) psi_dot = v / l_r * sp.sin( delta ) # system function f f = sp.Matrix([ x_dot, y_dot, psi_dot ]) # state vector X_bic = sp.Matrix( [ x, y, psi ]) # input vector U_bic = sp.Matrix( [ delta, v ]) f ###Output _____no_output_____ ###Markdown Discretization of the continunous modelBy applying Euler-forward discretization$ {X}[k+1] = \underbrace{ {X}[k] + T_s \dot{X} }_{f_{dscr}} $,the continuous system is time-discretized with the sampling time $T_s$ yielding the discrete system funtion $f_{dscr}$. ###Code # apply Euler forward f_dscr = sp.Matrix( [x,y,psi]) + T_s * f f_dscr ###Output _____no_output_____ ###Markdown Analytically compute the Jacobian matricesA linearization of the non-linear system function around a dynamic set point is calculated by deriving the jacobian matrices w.r.t. the state vector $X$ and each system input $\delta$ and $v$:continuous case $ A = \frac{ \partial f }{ \partial X}, \qquad B = \frac{ \partial f }{ \partial [ \delta, v ]^T }, $discrete-time case$ A_{dscr} = \frac{ \partial f_{dscr} }{ \partial X}, \qquad B_{dscr} = \frac{ \partial f_{dscr} }{ \partial [ \delta, v ]^T }, $ ###Code # continuous system matrices A = f.jacobian(X_bic) B = f.jacobian(U_bic) # discrete system matrices A_dscr = f_dscr.jacobian(X_bic) B_dscr = f_dscr.jacobian(U_bic) A_dscr B_dscr ###Output _____no_output_____ ###Markdown Create functions that generate the matrices A, B, and the system function fCreate python functions with which the symbolically dervied matrices and system function can be evaluated. ###Code variables = (T_s,l_r, x,y,psi,v,delta) array2mat = [{'ImmutableDenseMatrix': np.matrix}, 'numpy'] A_dscr_fn = lambdify( variables, A_dscr, modules=array2mat) B_dscr_fn = lambdify( variables, B_dscr, modules=array2mat) f_dscr_fn = lambdify( variables, f_dscr, modules=array2mat) A_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1) B_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1) f_dscr_fn(0.01, 3.0, 0.1,0.2,0.4,10,0.1) ###Output _____no_output_____ ###Markdown Run a simulation to generate test dataSet-up a simulation of a vehicle (bicycle model). The vehicle is controlled to follow a given path. In addition, an intended lateral distance $\Delta l$ is modulated by applying a pre-defined profile to the reference $\Delta l_r$. ###Code path_transform = pt.LateralPathTransformer(wheelbase=3.0) lateral_profile = mp.generate_one_dimensional_motion(Ts=Ts, T_phase1=1, T_phase2=3, T_phase3=1, T_phase4=3, T_phase5=1) mp.plot_lateral_profile(lateral_profile) output_path = path_transform.run_lateral_path_transformer( track_data, lateral_profile ) plt.figure(figsize=(8,4), dpi=100) plt.plot( output_path['X'], output_path['Y']+0.1 ) plt.plot( track_data['X'], track_data['Y'] ) plt.legend(['manipulated (output) path', 'original (input) path']) plt.grid() plt.xlabel('x [m]') plt.ylabel('y [m]') plt.show() output_path.keys() ###Output _____no_output_____ ###Markdown Add noise to the model (sensing noise)Simulate measurement noise which is, e.g., introduced by GPS. ###Code # X/Y positioning noise (normal distribution) N = len( output_path['X'] ) eta_x = np.random.normal(0, 0.1, N) * 1 eta_y = np.random.normal(0, 0.1, N) * 1 x_meas = eta_x + output_path['X'] y_meas = eta_y + output_path['Y'] psi_meas = output_path['V_PSI'] psi_dot_meas = output_path['V_PSI_DOT'] v_meas = output_path['V_VELOCITY'] plt.figure(figsize=(12,8), dpi=70) plt.plot(x_meas, y_meas) plt.plot(track_data['X'], track_data['Y']) plt.show() plt.figure(figsize=(12,8), dpi=70) plt.plot(psi_meas) plt.show() ###Output _____no_output_____ ###Markdown Extended Kalman filterThe extended Kalman filter is applied to the linearized model descibed by the matrices $A_{dscr}$ and $B_{dscr}$ and given the system function $f_{dscr}$. The simulated data serves as measured data and is the input to the filter. ###Code f_dscr A_dscr B_dscr ###Output _____no_output_____ ###Markdown The implemented filter in form of a loop ###Code l_r = 3.0 # allocate space to store the filter results results = {'delta' : np.zeros(N), 'x' : np.zeros(N), 'y' : np.zeros(N), 'psi' : np.zeros(N) } # the guess/estimate of the initial states X = np.matrix([ [0.5], [0.5], [0.1] ]) P = np.matrix([ [0.1, 0, 0 ], [0, 0.1, 0 ], [0, 0, 0.1 ] ]) # covariance of the noise w addtitive to the states Q = 0.00001*np.matrix([ [1, 0, 0 ], [0, 1, 0 ], [0, 0, 1 ] ]) # covariance of the noise v in the measured system output signal R = np.matrix([ [0.1, 0 ], [0 , 0.1 ] ]) for i in range(0,N): # measured input signals v = v_meas[i] x = x_meas[i] y = y_meas[i] psi_dot = psi_dot_meas[i] # compute steering angle by the inverse for the vehicle orientation change delta = math.asin( psi_dot * l_r / v ) # system output vector (x, y) z = np.matrix([ [x], [y] ]) # pridiction step using the non-linear model (f_dscr) # x(k-1|k-1) --> x(k|k-1) X[0] = X[0] + Ts * ( v * math.cos( X[2] + delta ) ) X[1] = X[1] + Ts * ( v * math.sin( X[2] + delta ) ) X[2] = X[2] + Ts * ( v / l_r * math.sin(delta) ) # optionally use the auto-generated python function for evaluation # X = f_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta ) # evaluate jacobi matrices A_dscr and B_dscr F = np.matrix([ [1, 0, -Ts*v*math.sin(delta+X[2]) ], [0, 1, Ts*v*math.cos(delta+X[2]) ], [0, 0, 1 ] ]) # optionally use the auto-generated python function for evaluation # F = A_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta ) B = np.matrix([ [-Ts*v*math.sin(delta+X[2]), Ts*math.cos(delta+X[2]) ], [ Ts*v*math.cos(delta+X[2]), Ts*math.sin(delta+X[2]) ], [Ts*v/l_r * math.cos(delta), Ts/l_r * math.sin(delta) ] ]) # optionally use the auto-generated python function for evaluation # B = B_dscr_fn( Ts, l_r, float(X[0]), float(X[1]), float(X[2]), v, delta ) # the system output matrix: returns X and Y when multiplied with the state vector X # which are compared to the measurements H = np.matrix([ [1,0,0], [0,1,0] ]) # prdicted state covariance P(k|k-1) P = F*P*F.transpose() + Q # estimation output residual vector e = z - H*X # Kalman gain S = H*P*H.transpose() + R K = P*H.transpose() * np.linalg.inv( S ) # post priori state X(k|k) X = X + K*e # post priori covariance P = (np.eye(3) - K*H) * P # store results results['delta'][i] = delta results['x'][i] = X[0] results['y'][i] = X[1] results['psi'][i] = X[2] # show results plt.figure(figsize=(12,8), dpi=79) #plt.plot(x_meas, y_meas, '+') plt.plot(output_path['X'], output_path['Y'], 'g') plt.plot(results['x'], results['y'], 'r') plt.show() plt.figure(figsize=(12,8), dpi=70) plt.plot(results['psi']) plt.plot(output_path['V_PSI'], 'g') plt.show() ###Output _____no_output_____
TP2/Matias/10_XGBoost_TFIDF.ipynb
###Markdown Ajustando hiper-parametros (usando 748 feature-words): - n_estimators=50, max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=1, alpha=0 SCORE: 0.761029 - n_estimators=50, max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=1, alpha=0 SCORE: 0.767332 - n_estimators=100, max_depth=7, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=1, alpha=0 SCORE: 0.769958 - n_estimators=100, max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=1, alpha=0 SCORE: 0.773634 - n_estimators=100, max_depth=15, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=1, alpha=0 SCORE: 0.773786 - n_estimators=100, max_depth=13, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=0.1, alpha=0 SCORE: 0.777311 - n_estimators=100, max_depth=13, learning_rate=0.1, subsample=1, colsample_bytree=0.3, lambda=0.1, alpha=0 SCORE: 0.775210 - n_estimators=200, max_depth=9, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=0.5, alpha=0 SCORE: 0.777836 - n_estimators=200, max_depth=13, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=0.1, alpha=0 SCORE: 0.783088 - n_estimators=200, max_depth=13, learning_rate=0.1, subsample=1, colsample_bytree=0.7, lambda=0.1, alpha=0 SCORE: 0.787815 - n_estimators=200, max_depth=15, learning_rate=0.1, subsample=1, colsample_bytree=0.5, lambda=0.1, alpha=0 SCORE: 0.785189 - n_estimators=250, max_depth=13 u 11, learning_rate=0.1, subsample=1, colsample_bytree=0.7, lambda=0.1, alpha=0 SCORE: 0.790966 - n_estimators=250, max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.7, lambda=0.1, alpha=0.1 SCORE: 0.789391 ###Code model = xgb.XGBClassifier(n_estimators=250, objective='binary:logistic', max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.7, reg_lambda=0.1, n_jobs=1) model.fit(X_train, y_train) y_test_hat = model.predict(X_test) print("Accuracy score: %f" % (accuracy_score(y_test, y_test_hat))) model_xgb.score(X_test, y_test)*100 #usando kfold y stratified kfold model_xgb = xgb.XGBClassifier(n_estimators=250, objective='binary:logistic', max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.5, reg_lambda=0.1, n_jobs=1) kfold = KFold(n_splits=6, random_state=100) resultados = cross_val_score(model_xgb, X_train, y_train, cv=kfold) print("Accuracy: %f" % (resultados.mean()*100)) kfold = StratifiedKFold(n_splits=8, random_state=134) resultados = cross_val_score(model_xgb, X_train, y_train, cv=kfold) print("Accuracy: %f" % (resultados.mean()*100)) X_test = test_tfidf model = xgb.XGBClassifier(n_estimators=250, objective='binary:logistic', max_depth=11, learning_rate=0.1, subsample=1, colsample_bytree=0.7, reg_lambda=0.1, n_jobs=1) model.fit(X_train, y_train) y_pred = model.predict(X_test) y_pred test["target"] = y_pred test[["id_original","target"]] test[["id_original","target"]].rename(columns={"id_original":"id"}).to_csv("../data/pred4_XGB_Tfidf", index=False) ###Output _____no_output_____
docs/New-Dataset-Template.ipynb
###Markdown General template for create a new dataset from scratchThis example creates the same raw dataset as in the [`Add-csv-template.ipynb`](https://cookiecutter-easydata.readthedocs.io/en/latest/Add-csv-template/) example, but does it completely generally without using the `workflow` helper function. Any (non-derived) dataset can be added in this way.We'll use this as an example of a non-manual download. Basic imports ###Code %load_ext autoreload %autoreload 2 # Basic utility functions import logging import os import pathlib from src.log import logger from src import paths from src.utils import list_dir from functools import partial # data functions from src.data import DataSource, Dataset, TransformerGraph from src import workflow # Optionally set to debug log level logger.setLevel(logging.DEBUG) ###Output _____no_output_____ ###Markdown Create a DataSource ###Code ds_name = 'covid-19-epidemiology-raw' dsrc = DataSource(ds_name) url = 'https://storage.googleapis.com/covid19-open-data/v2/epidemiology.csv' filename = 'epidemiology.csv' # path relative to paths['raw_data_path'] for the file license = """ [CC-BY 4.0](https://github.com/GoogleCloudPlatform/covid-19-open-data/blob/main/output/CC-BY) """ metadata = """ The epidemiology table from Google's [COVID-19 Open-Data dataset](https://github.com/GoogleCloudPlatform/covid-19-open-data). The full dataset contains datasets of daily time-series data related to COVID-19 for over 20,000 distinct locations around the world. The data is at the spatial resolution of states/provinces for most regions and at county/municipality resolution for many countries such as Argentina, Brazil, Chile, Colombia, Czech Republic, Mexico, Netherlands, Peru, United Kingdom, and USA. All regions are assigned a unique location key, which resolves discrepancies between ISO / NUTS / FIPS codes, etc. The different aggregation levels are: 0: Country 1: Province, state, or local equivalent 2: Municipality, county, or local equivalent 3: Locality which may not follow strict hierarchical order, such as "city" or "nursing homes in X location" There are multiple types of data: Outcome data Y(i,t), such as cases, tests, hospitalizations, deaths and recoveries, for region i and time t Static covariate data X(i), such as population size, health statistics, economic indicators, geographic boundaries Dynamic covariate data X(i,t), such as mobility, search trends, weather, and government interventions The data is drawn from multiple sources, as listed below, and stored in separate tables as CSV files grouped by context, which can be easily merged due to the use of consistent geographic (and temporal) keys as it is done for the main table. One of these files is the epidemiology.csv file used here. """ ###Output _____no_output_____ ###Markdown This example uses `add_url`, but there are other options such as `add_manual_download` and `add_google_drive`. ###Code dsrc.add_url(url=url, file_name=filename, unpack_action='copy') dsrc.add_metadata(contents=metadata, force=True) dsrc.add_metadata(contents=license, kind='LICENSE', force=True) dsrc.file_dict ###Output _____no_output_____ ###Markdown Create a process functionBy default, we recommend that you use the `process_extra_files` functionality and then use a transformer function to create a derived dataset, but you can optionally create your own. ###Code from src.data.extra import process_extra_files process_function = process_extra_files process_function_kwargs = {'file_glob':'*.csv', 'do_copy': True, 'extra_dir': ds_name+'.extra', 'extract_dir': ds_name} help(process_function) dsrc.process_function = partial(process_function, **process_function_kwargs) workflow.add_datasource(dsrc) workflow.datasource_catalog()[ds_name] %%time dsrc.fetch() %%time dsrc.unpack() ###Output _____no_output_____ ###Markdown Create a Dataset from the DataSource ###Code from src.data import TransformerGraph paths['catalog_path'] dag = TransformerGraph(catalog_path=paths['catalog_path']) dag.sources workflow.datasource_catalog(keys_only=True) dag.add_source(output_dataset=ds_name, datasource_name=ds_name, force=True) workflow.dataset_catalog(keys_only=True) %%time ds = Dataset.from_catalog(ds_name) %%time ds = Dataset.load(ds_name) print(ds.metadata) print(ds.LICENSE) ds.EXTRA ds.extra_file('epidemiology.csv') ds.data is None ds.target is None ###Output _____no_output_____ ###Markdown General template for create a new dataset from scratchThis example creates the same raw dataset as in the [`Add-csv-template.ipynb`](https://cookiecutter-easydata.readthedocs.io/en/latest/Add-csv-template/) example, but does it completely generally without using a function from `helpers`. Any (non-derived) dataset can be added in this way.We'll use this as an example of a non-manual download. Basic imports ###Code %load_ext autoreload %autoreload 2 # Basic utility functions import logging import os import pathlib from pprint import pprint from src.log import logger from src import paths from src.utils import list_dir from functools import partial # data functions from src.data import DataSource, Dataset, DatasetGraph, Catalog from src import helpers # Optionally set to debug log level logger.setLevel(logging.DEBUG) ###Output _____no_output_____ ###Markdown Create a DataSource ###Code ds_name = 'covid-19-epidemiology-raw' dsrc = DataSource(ds_name) url = 'https://storage.googleapis.com/covid19-open-data/v2/epidemiology.csv' filename = 'epidemiology.csv' # path relative to paths['raw_data_path'] for the file license = """ [CC-BY 4.0](https://github.com/GoogleCloudPlatform/covid-19-open-data/blob/main/output/CC-BY) """ metadata = """ The epidemiology table from Google's [COVID-19 Open-Data dataset](https://github.com/GoogleCloudPlatform/covid-19-open-data). The full dataset contains datasets of daily time-series data related to COVID-19 for over 20,000 distinct locations around the world. The data is at the spatial resolution of states/provinces for most regions and at county/municipality resolution for many countries such as Argentina, Brazil, Chile, Colombia, Czech Republic, Mexico, Netherlands, Peru, United Kingdom, and USA. All regions are assigned a unique location key, which resolves discrepancies between ISO / NUTS / FIPS codes, etc. The different aggregation levels are: 0: Country 1: Province, state, or local equivalent 2: Municipality, county, or local equivalent 3: Locality which may not follow strict hierarchical order, such as "city" or "nursing homes in X location" There are multiple types of data: Outcome data Y(i,t), such as cases, tests, hospitalizations, deaths and recoveries, for region i and time t Static covariate data X(i), such as population size, health statistics, economic indicators, geographic boundaries Dynamic covariate data X(i,t), such as mobility, search trends, weather, and government interventions The data is drawn from multiple sources, as listed below, and stored in separate tables as CSV files grouped by context, which can be easily merged due to the use of consistent geographic (and temporal) keys as it is done for the main table. One of these files is the epidemiology.csv file used here. """ ###Output _____no_output_____ ###Markdown This example uses `add_url`, but there are other options such as `add_manual_download` and `add_google_drive`. ###Code dsrc.add_url(url=url, file_name=filename, unpack_action='copy') dsrc.add_metadata(contents=metadata, force=True) dsrc.add_metadata(contents=license, kind='LICENSE', force=True) dsrc.file_dict ###Output _____no_output_____ ###Markdown Create a process functionBy default, we recommend that you use the `process_extra_files` functionality and then use a transformer function to create a derived dataset, but you can optionally create your own. ###Code from src.data.extra import process_extra_files process_function = process_extra_files process_function_kwargs = {'file_glob':'*.csv', 'do_copy': True, 'extra_dir': ds_name+'.extra', 'extract_dir': ds_name} help(process_function) dsrc.process_function = partial(process_function, **process_function_kwargs) dsrc.update_catalog() dsc = Catalog.load('datasources') dsc[ds_name] %%time dsrc.fetch() %%time dsrc.unpack() ###Output _____no_output_____ ###Markdown Create a Dataset from the DataSource ###Code from src.data import DatasetGraph paths['catalog_path'] dag = DatasetGraph(catalog_path=paths['catalog_path']) dag.sources dsc = Catalog.load('datasources'); dsc dag.add_source(output_dataset=ds_name, datasource_name=ds_name, overwrite_catalog=True) dc = Catalog.load('datasets'); dc %%time ds = Dataset.from_catalog(ds_name) %%time ds = Dataset.load(ds_name) pprint(ds.metadata) print(ds.LICENSE) ds.EXTRA ds.extra_file('epidemiology.csv') ds.data is None ds.target is None ###Output _____no_output_____ ###Markdown General template for create a new dataset from scratchThis example creates the same raw dataset as in the [`Add-csv-template.ipynb`](https://cookiecutter-easydata.readthedocs.io/en/latest/Add-csv-template/) example, but does it completely generally without using the `workflow` helper function. Any (non-derived) dataset can be added in this way.We'll use this as an example of a non-manual download. Basic imports ###Code %load_ext autoreload %autoreload 2 # Basic utility functions import logging import os import pathlib from src.log import logger from src import paths from src.utils import list_dir from functools import partial # data functions from src.data import DataSource, Dataset, TransformerGraph from src import workflow # Optionally set to debug log level logger.setLevel(logging.DEBUG) ###Output _____no_output_____ ###Markdown Create a DataSource ###Code ds_name = 'covid-19-epidemiology-raw' dsrc = DataSource(ds_name) url = 'https://storage.googleapis.com/covid19-open-data/v2/epidemiology.csv' filename = 'epidemiology.csv' # path relative to paths['raw_data_path'] for the file license = """ [CC-BY 4.0](https://github.com/GoogleCloudPlatform/covid-19-open-data/blob/main/output/CC-BY) """ metadata = """ The epidemiology table from Google's [COVID-19 Open-Data dataset](https://github.com/GoogleCloudPlatform/covid-19-open-data). The full dataset contains datasets of daily time-series data related to COVID-19 for over 20,000 distinct locations around the world. The data is at the spatial resolution of states/provinces for most regions and at county/municipality resolution for many countries such as Argentina, Brazil, Chile, Colombia, Czech Republic, Mexico, Netherlands, Peru, United Kingdom, and USA. All regions are assigned a unique location key, which resolves discrepancies between ISO / NUTS / FIPS codes, etc. The different aggregation levels are: 0: Country 1: Province, state, or local equivalent 2: Municipality, county, or local equivalent 3: Locality which may not follow strict hierarchical order, such as "city" or "nursing homes in X location" There are multiple types of data: Outcome data Y(i,t), such as cases, tests, hospitalizations, deaths and recoveries, for region i and time t Static covariate data X(i), such as population size, health statistics, economic indicators, geographic boundaries Dynamic covariate data X(i,t), such as mobility, search trends, weather, and government interventions The data is drawn from multiple sources, as listed below, and stored in separate tables as CSV files grouped by context, which can be easily merged due to the use of consistent geographic (and temporal) keys as it is done for the main table. One of these files is the epidemiology.csv file used here. """ ###Output _____no_output_____ ###Markdown This example uses `add_url`, but there are other options such as `add_manual_download` and `add_google_drive`. ###Code dsrc.add_url(url=url, file_name=filename, unpack_action='copy') dsrc.add_metadata(contents=metadata, force=True) dsrc.add_metadata(contents=license, kind='LICENSE', force=True) dsrc.file_dict ###Output _____no_output_____ ###Markdown Create a process functionBy default, we recommend that you use the `process_extra_files` functionality and then use a transformer function to create a derived dataset, but you can optionally create your own. ###Code from src.data.extra import process_extra_files process_function = process_extra_files process_function_kwargs = {'file_glob':'*.csv', 'do_copy': True, 'extra_dir': ds_name+'.extra', 'extract_dir': ds_name} help(process_function) dsrc.process_function = partial(process_function, **process_function_kwargs) workflow.add_datasource(dsrc) workflow.datasource_catalog(keys_only=False)[ds_name] %%time dsrc.fetch() %%time dsrc.unpack() ###Output _____no_output_____ ###Markdown Create a Dataset from the DataSource ###Code from src.data import TransformerGraph paths['catalog_path'] dag = TransformerGraph(catalog_path=paths['catalog_path']) dag.sources workflow.datasource_catalog(keys_only=True) dag.add_source(output_dataset=ds_name, datasource_name=ds_name, force=True) workflow.dataset_catalog(keys_only=True) %%time ds = Dataset.from_catalog(ds_name) %%time ds = Dataset.load(ds_name) print(ds.metadata) print(ds.LICENSE) ds.EXTRA ds.extra_file('epidemiology.csv') ds.data is None ds.target is None ###Output _____no_output_____
docs/examples/click_events.ipynb
###Markdown ipyregulartablehttps://github.com/jpmorganchase/ipyregulartable ###Code import ipyregulartable as rt w = rt.RegularTableWidget(rt.NumpyDataModel()) w import ipywidgets as ipy out = ipy.Output() out def on_click(widget, coords): with out: print("clicked: ({},{})".format(coords[0], coords[1])) w.on_click(on_click) ###Output _____no_output_____
lab7/.ipynb_checkpoints/DATA3401.2021.Fall.Lab7-checkpoint.ipynb
###Markdown Lab 7 &ndash; DATA 3401 (Fall 2021) Lab Date: 11/5 Due Date 11/12 (before the beginning of lab) Lab DescriptionThe purpose of this lab is for you to become more familiar with numpy and matplotlib Exercise 1On the same plot, graph the functions $y=\sin x$, $y=\cos x$, and $y = \begin{cases} 1, x \geq0\\ 0, x<0\end{cases}$ on the interval $[-2\pi,2\pi]$.1. Make sure the curves have different colors1. Add a legend and label each curve appropriately ###Code # Write your solution here ###Output _____no_output_____ ###Markdown Exercise 21. Write a function that rolls a dice `n` times for a given integer `n` and computes a *running percentage* of times each number is rolled ( of times 1 has been rolled)/( of rolls so far) and so on. That is, at the `i`-th roll, you should compute ( of 1s)/i, ( of 2s)/i, ... and store these values.1. Modify this function to take in a probability distribution over the 6 numbers of the form `p=np.array([p1,p2,p3,p4,p5,p6])` and roll a dice `n` times with these probabilities1. Run your function from part 1 with $n=1000$ and graph the rolling averages for all numbers vs. `i in range(n)`1. Run your function from part 2 with $n=1000$ and $p= [.2,.1,.2,.1..1,.3]$1. Use the plots above to justify that the first dice is fair and the second is unfair ###Code # Write your functions here #Test your functions here ###Output _____no_output_____ ###Markdown Exercise 3Plot the 2-variable function $\sin(10(x^2+y^2))/10$ for $x\in[-1,1]$ and $y\in[-1,1]$ ###Code # Write your solution here ###Output _____no_output_____ ###Markdown Background: Central Limit TheoremIn probability theory, the central limit theorem (CLT) establishes that, when independent random variables are added together, their properly normalized sum tends toward a normal distribution (informally a “bell curve”) even if the original variables themselves are not normally distributed. To understand this theorem, suppose you generate 100 uniform random numbers and sum them to get a single number. Then you repeat this procedure 1000 times to get 1000 of these sums of 100 uniform random numbers. The CLT theorem implies that if you plot a histogram of the values of these 1000 sums, then the resulting distribution looks very much like the Gaussian bell-shaped function. The larger the number of these sums (for example, 100000 instead of 1000 sums), the more the resulting distribution will look like a Gaussian. Here we want to see this theorem in action. Exercise 4Consider that a person is standing on the real line at a given point $x_0$. The person then goes on a "random walk", meaning that they first take a step of size 1 in a random direction (so after this step they are either standing at $x_0+1$ or $x_0-1$), then they take another step of size 1 in a random direction (after the second step they are standing at one of $x_0-2, x_0,$ or $x_0+2$), and they continue this process for $n$ steps. At each stage, the person flips a fair coin to decide which direction to go in.1. Write a function `RandomWalk(num_steps,start_position)`, that takes the number of steps `num_steps` for a random walk and the `start_position` of the random walk on the real line (so a float), and returns the location of the final step of the random walker.2. Write another function `SimulateRandomWalk(num_sims,num_steps,start_position)` that simulates num_sims number of random walks, each of which contains `num_steps` steps and starts at `start_position`. Then, this function calls `RandomWalk()` repeatedly for `num_sims` times and finally returns a vector of size `num_sim` containing the final locations of all of the `num_sims` simulated random-walks.3. Now write a script that plots the output of `SimulateRandomWalk(num_sims = 10000, num_steps = 10, start_position = 0)` in a histogram4. Interpret your results ###Code # Write your functions here # Test your functions here ###Output _____no_output_____
titan.ipynb
###Markdown Importing an edge list into Titan 0.9.0-M1(Berkeley DB) w/TP3 Gremlin Server 3.0.0-M7 and Python ###Code from datetime import datetime from gizmo import AsyncGremlinClient def build_schema(): script = """ mgmt = g.openManagement(); uniqueId = mgmt.makePropertyKey('uniqueId').dataType(Integer.class).make(); mgmt.buildIndex('byId', Vertex.class).addKey(uniqueId).unique().buildCompositeIndex(); mgmt.makeEdgeLabel('collabs').make(); mgmt.commit();""" gc = AsyncGremlinClient() t = gc.s(script, consumer=lambda x: print("Commited tx with response code: {}".format(x.status_code))) t.execute() def load_edges(): start = datetime.now() script = """ getOrCreate = { id -> def n = g.V().has('uniqueId', id) if (n.hasNext()) {n.next()} else {g.addVertex("uniqueId", id)} } new File('social_net.txt').eachLine { (source, target) = it.split('\t').collect(getOrCreate) source.addEdge('collabs', target) } g.tx().commit()""" gc = AsyncGremlinClient() t = gc.s(script, consumer=lambda x: print("Commited tx with response code: {}".format(x.status_code))) t.execute() print("Loaded in {}".format(datetime.now() - start)) def count_nodes(gc): t = gc.s("g.V().count()", collect=False, consumer=lambda x: print(x)) t.execute() def count_edges(gc): t = gc.s("g.E().count()", collect=False, consumer=lambda x: print(x)) t.execute() build_schema() load_edges() gc = AsyncGremlinClient() count_nodes(gc) count_edges(gc) print("{} edges per second".format(47594 / 17.949)) ###Output 2651.62404590785 edges per second
_downloads/c28a82d8c305922b22bbcd4ea97c8df1/Net_Subgraph.ipynb
###Markdown Net file========This is the Net file for the subgraph problem: state and output transition function definition ###Code import tensorflow as tf import numpy as np def weight_variable(shape, nm): # function to initialize weights initial = tf.truncated_normal(shape, stddev=0.1) tf.summary.histogram(nm, initial, collections=['always']) return tf.Variable(initial, name=nm) class Net: # class to define state and output network def __init__(self, input_dim, state_dim, output_dim): # initialize weight and parameter self.EPSILON = 0.00000001 self.input_dim = input_dim self.state_dim = state_dim self.output_dim = output_dim self.state_input = self.input_dim - 1 + state_dim # removing the id_ dimension #### TO BE SET ON A SPECIFIC PROBLEM self.state_l1 = 15 self.state_l2 = self.state_dim self.output_l1 = 10 self.output_l2 = self.output_dim def netSt(self, inp): with tf.variable_scope('State_net'): layer1 = tf.layers.dense(inp, self.state_l1, activation=tf.nn.tanh) layer2 = tf.layers.dense(layer1, self.state_l2, activation=tf.nn.tanh) return layer2 def netOut(self, inp): layer1 = tf.layers.dense(inp, self.output_l1, activation=tf.nn.tanh) layer2 = tf.layers.dense(layer1, self.output_l2, activation=tf.nn.softmax) return layer2 def Loss(self, output, target, output_weight=None): # method to define the loss function #lo = tf.losses.softmax_cross_entropy(target, output) output = tf.maximum(output, self.EPSILON, name="Avoiding_explosions") # to avoid explosions xent = -tf.reduce_sum(target * tf.log(output), 1) lo = tf.reduce_mean(xent) return lo def Metric(self, target, output, output_weight=None): # method to define the evaluation metric correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(target, 1)) metric = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) return metric ###Output _____no_output_____
01-python-intro/aula-01/Aula 01.ipynb
###Markdown [**Py-Intro**] Aula 01 Instalando Python, introdução a bibliotecas e estruturas de dados O que você vai aprender nesta aula?Após o término da aula você terá aprendido:- Informações úteis sobre a linguagem Python- Instalar o python- O que é o Jupyter Notebook, como instalá-lo e rodá-lo - Usar o ambiente virtual- Instalar bibliotecas- Acessar páginas usando Python- Estruturas de dados do Python: listas e dicionários Sobre a linguagem PythonSe você já conhece a linguagem e está animado em aprendê-la já pode seguir para a próxima seção.Se, mesmo assim, você ainda estiver curioso para saber mais sobre Python fique convidado a ler os próximos parágrafos.Python é uma linguagem simples, enxuta e poderosa. Com poucas linhas e sintaxe clara é possível executar tarefas complexas. Essa característica se dá, pois os tipos de dados de alto nível permitem fazer operações complexas de uma única vez, além de não ser necessário declarar variáveis ou tipos dos argumentos.Python vem com pilhas inclusas. Em sua biblioteca padrão há soluções para diversos tipos de problemas recorrentes, como:- Interface gráfica (tkinter)- Internet (requisições HTTP, email, sockets etc.)- Data, hora e calendário- Acesso a arquivos e pastas- Execução de outras aplicações/processos- E muito mais: https://docs.python.org/3/library/A linguagem foi criada em 1991 e desde então vem crescendo constantemente ano a ano, tanto no quesito de número de usuário quanto em atualizações e melhorias do interpretador e da linguagem em si. Atualmente Python está na versão 3.5 que trouxe várias features interessantes que podem ser conferidas [aqui](https://docs.python.org/3.5/whatsnew/changelog.html).Muitas empresas como Google, Facebook, Mozilla, Microsoft, Intel, IBM, Globo e Magazine Luiza usam Python em produtos como Instagram, YouTube e o g1 (portal de notícias da globo).*PS: Dica para vida: os patrocinadores de grandes eventos como, por exemplo PyCon [2015](https://us.pycon.org/2015/) e [2016](https://us.pycon.org/2016/), usam e estão patrocinando a linguagem. E isso também vale para **qualquer outra tecnlogia**.*Python é uma linguagem interpretada, ou seja, seu código-fonte executado diretamente pelo interpretador, sem precisar de compilar o programa em instruções de linguagem de máquina.*PS: para agilizar a execução de módulos o interpretador do Python cria caches. Para saber mais, veja: [“Compiled” Python files](https://docs.python.org/3/tutorial/modules.htmlcompiled-python-files)*Por ser interpretada a Python ganha diversas vantagens, como:- Ganho de tempo por não precisar compilar/linkar o programa- Interpretador pode ser usado de forma interativa tornando possível realizar testes e experimentos- Este "caderno" - o jupyter notebookA linguagem possui 20 príncipios que guiam seu desenvolvimento e podem ser conferidos rodando o seguinte comando: ###Code import this ###Output The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ###Markdown Agora é hora de por as mãos na massa! Vamos do começo: Instalando o Python 3.5Caso você já tenha o Python 3.5 siga para a próxima sessão! Debian e derivados (ubuntu, mint etc.) $ sudo apt-get install python3.5 Windows e OS Xhttps://www.python.org/downloads/Caso você esteja usando o windows não esqueça de marcar a opção: "Add Python.exe to Path", como mostrado na seguinte imagem:![Instalando o Python no Windows](http://tutorial.djangogirls.org/pt/python_installation/images/add_python_to_windows_path.png)(imagem retirada do [Django Girls Tutorial](http://tutorial.djangogirls.org/pt/)) Virtualenv (Ambiente virtual)O virtualenv é uma ferramenta que serve para manter as dependências de projetos diferentes em pastas separadas, desse modo é possível trabalhar me um projeto usando, por exemplo, o Django 1.9 enquanto se mantém um projeto antigo que usa a versão 1.5 do framework.O virtualenv cria uma pasta contendo todas as dependências que um projeto Python necessita.O virtualenv já vem instalado no Python 3.5, para criar um novo ambiente faça: Linux e Mac $ python3.5 -m venv env WindowsAbra o programa de linha de comando do Windows e digite o comando abaixo. Isso pode ser feito apertando o `botão do windows + R`, digitando `cmd` e apertando ENTER. > C:\Python3.5\python -m venv envEsse comando criará uma pasta chamada **env/** contendo os executáveis do Python e uma cópia do pip para instalar outros pacotes. Vale lembrar que o nome do ambiente virtual **env** pode ser trocado por qualquer outro.Para usar o virtualenv é necessário antes que ele seja ativado: Linux e Mac $ source env/bin/activate Windows > env\Scripts\activate Para sair de um ambiente virtual use o comando `deactivate`. Agora nosso ambiente virtual está pronto para ser usado! Instalando pacotes com o pipO pip permite instalar pacotes Python (listados no [PyPI: the Python Package Index](http://pypi.python.org/)) de forma fácil. O pip significa "**p**ip **i**nstall **packages**" (ou pip instala pacotes).Por exemplo, vamos instalar a biblioteca requests que usaremos mais para frente nesta aula: (env) $ pip install requests Jupyter NotebookO Jupyter Notebook é uma aplicação web que permite a criação e compatilhamento de documentos (notebooks) que contém código ao vivo, equações, visualizações e textos explanatórios. Ele é muito utilizado para transformação de dados, modelagem estatística, simulação numérica, aprendizado de máquina e ensino.Para rodá-lo em sua máquina é preciso: instalar, rodar o servidor e acessr pelo navegador! É mais simples do que parece, vamos fazer esses passos. InstalandoVamos instalar o jupyter notebook executando o seguinte comando: (env) $ pip install jupyter[notebook] No linuxCaso não seja possível instalar o jupyter[notebook] rode:``` $ sudo apt-get install build-essential python3.5-dev (env) $ pip install --upgrade pip (env) $ pip install jupyter[notebook]``` RodandoNão esqueça de baixar este documento (Aula01.ipynb) e rodar o jupyter notebook na **mesma pasta**.Para rodá-lo e tornar possivel o acesso do notebook pelo navegador, execute o seguinte comando: (env) $ jupyter notebookAgora é só acessar a página http://localhost:8888/notebooks (que deve ter sido aberta automaticamente) e abrir o notebook Aula01.ipynb que já estamos prontos para codificar!Para rodar um código específico clique na caixa do código e pressione CTRL+Enter Acessando páginas webNosso primeiro exemplo será criar o código de uma aplicação que nos permite baixar o código-fonte de sites.Para isso vamos usar a biblioteca `requests` que foi instalada em um passo anterior (caso você não tenha instalado rode `pip install requests`).Primeiro preciamos importar a `requests`: ###Code import requests ###Output _____no_output_____ ###Markdown Agora vamos fazer uma requisição HTTP ao Github para baixar o conteúdo do repositório deste curso (através da URL https://github.com/lamenezes/python-intro): ###Code url = 'https://github.com/lamenezes/python-intro' # não é necessário declarar variáveis em python response = requests.get(url) # e nem especificar seu tipo response.status_code ###Output _____no_output_____ ###Markdown 200 é o código de resposta que informa que a requisição foi bem sucedida (ou OK).*PS: No curso de Desenvolvimento Web com Django será explicado com calma como funciona o protocolo HTTP.*Agora vamos analisar os cabeçalhos dessa resposta: ###Code print(response.headers) ###Output {'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Served-By': 'b437fa0c9608399c74bf50b5c3f52799', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'logged_in=no; domain=.github.com; path=/; expires=Tue, 06 May 2036 01:53:29 -0000; secure; HttpOnly, _gh_sess=eyJzZXNzaW9uX2lkIjoiM2RkNGU5ZTFkMmU5YmE4ZGFmZTEwOTFlNWI5YjEwMzciLCJzcHlfcmVwbyI6ImxhbWVuZXplcy9weXRob24taW50cm8iLCJzcHlfcmVwb19hdCI6MTQ2MjQ5OTYwOSwiX2NzcmZfdG9rZW4iOiJWWHJaMGRBeFZjT0ZDZGtQcDRyd04wZzZ4ZktaRTJENFM0MlJYalJ6dVNVPSIsImZsYXNoIjp7ImRpc2NhcmQiOlsiYW5hbHl0aWNzX2xvY2F0aW9uIl0sImZsYXNoZXMiOnsiYW5hbHl0aWNzX2xvY2F0aW9uIjoiLzx1c2VyLW5hbWU%2BLzxyZXBvLW5hbWU%2BIn19fQ%3D%3D--db707e407a9cbccdacd5c699d8f9c721cfe0668b; path=/; secure; HttpOnly', 'X-Content-Type-Options': 'nosniff', 'X-UA-Compatible': 'IE=Edge,chrome=1', 'Date': 'Fri, 06 May 2016 01:53:29 GMT', 'Server': 'GitHub.com', 'X-XSS-Protection': '1; mode=block', 'Content-Encoding': 'gzip', 'X-Request-Id': '20221edde149239d2d332bace865ce62', 'Vary': 'X-PJAX, Accept-Encoding', 'X-GitHub-Request-Id': 'BADFDA80:6458:5105BD3:572BF919', 'X-Runtime': '0.049845', 'X-Frame-Options': 'deny', 'Public-Key-Pins': 'max-age=5184000; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains', 'Content-Security-Policy': "default-src 'none'; base-uri 'self'; block-all-mixed-content; child-src render.githubusercontent.com; connect-src 'self' uploads.github.com status.github.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com api.braintreegateway.com client-analytics.braintreegateway.com wss://live.github.com; font-src assets-cdn.github.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: assets-cdn.github.com identicons.github.com www.google-analytics.com collector.githubapp.com *.gravatar.com *.wp.com checkout.paypal.com *.githubusercontent.com; media-src 'none'; object-src assets-cdn.github.com; plugin-types application/x-shockwave-flash; script-src assets-cdn.github.com; style-src 'unsafe-inline' assets-cdn.github.com", 'Status': '200 OK'} ###Markdown O atributo headers de response (`response.headers`) nos trouxe os cabeçalhos em forma de um dicionário (ou dict). O dict é uma estrutura de dados do Python utilizada para armazenar informações na forma de chave e valor envoltas por chaves {}. Dicts serão explicados mais para frente.Por motivos técnicos a saída foi apresentada em um formato difícil de ler, para melhorá-la podemos fazer um pequeno workaround: ###Code dict(response.headers) ###Output _____no_output_____ ###Markdown Para acessar um cabeçalho específico por sua chave fazemos: ###Code response.headers['content-type'] response.headers['date'] response.text[:1000] # retorna os 1000 primeiros caracteres do conteúdo da resposta ###Output _____no_output_____ ###Markdown Como visto anteriormente a biblioteca requests permite o envio de requisições HTTP de maneira extremamante fácil. Para obter mais informações sobre a `requests` acesse a [doumentação oficial](http://docs.python-requests.org/en/master/).Agora que já aprendemos o básico podemos partir para um exemplo mais interessante. Acessando os dados da API do githubO Github oferece uma API que fornece dados de seus repositórios públicos. São dadas informações como quantos projetos estão cadastrados na plataforma, quantos contribuidores trabalharam em quais repositórios, a quais organizações essas fazem parte e muito mais. (mais informações na [documentação oficial](https://developer.github.com/v3/))O acesso aos dados dessa API é feito através do envio de requisições HTTP para diferentes caminhos na URL base https://api.github.com/. Caso você queira testar a API, pode acessar o link anterior pelo navegador e mudar a URL manualmente, porém nosso foco aqui será usar a biblioteca `requests` para pegar esses dados.Todas as respostas da API são em formato JSON. O JSON siginifca JavaScript Object Notation e pronuncia-se "djêizon" e é um formato fácil de processar e simples de utilizar. Para mais informações sobre o JSON acesse a [página oficial](http://json.org/). Falaremos mais sobre JSON no decorrer do curso, mas fique tranquilo que não segredo há algum nesse assunto.Vamos testar a API e pegar os repositórios de um usuário específico através da URL https://api.github.com/users/lamenezes/repos: ###Code response = requests.get('https://api.github.com/users/lamenezes/repos') response.status_code response.text[:1000] # pegando os primeiros 1000 caracters do conteúdo da resposta ###Output _____no_output_____ ###Markdown A resposta trouxe todos os repositórios do usuário `lamenezes` em uma string no padrão JSON.Essa string não é interessante para nós, pois é difícil acessar dados específicos do JSON através dela. Seria muito melhor para nós se essa resposta fosse traduzida para um dicionário do Python (que possui sintaxe muito parecida com o JSON).Normalmente teríamos que importar a biblioteca json e realizar a conversão, no pior caso poderia ser necessário escrever um parser específico para tratar casos especiais.No entanto, a biblioteca `requests` já faz esse trabalho para nós: ###Code repositorios = response.json() repo = repositorios[0] # pegando apenas o primeiro repositório por brevidade repo ###Output _____no_output_____ ###Markdown A resposta nos trouxe uma `lista` de `dicionários` com as informações dos repositórios do usuário `lamenezes`. Agora fica a dúvida: o que exatamente é uma lista e um dicionário? ListasListas, como o próprio nome sugere, são estruturas de dados mutáveis que armanzenam listas de valores. Os valores da lista são acessados pelo número relativo a sua posição.Ao invés de gastar dedos digitando mais sobre o que é uma lista é mais fácil demonstrá-la: ###Code numeros = [1, 2.5, 3, 4.5, 5] numeros numeros[0] numeros[3] numeros[-1] # -1 acessa o último elemento da lista! ###Output _____no_output_____ ###Markdown Listas podem armazenar qualquer tipo de dados: ###Code lista = ['foobar', False, ['a', 'b', 'c'], {'foo': 'bar'}, 10, -0.5] lista ###Output _____no_output_____ ###Markdown Fazemos assim para verificar se um elemento faz parte de uma lista: ###Code 'foobar' in lista 'abc' in lista -0.5 in lista ###Output _____no_output_____ ###Markdown Para saber o tamanho de uma lista basta usar a função `len()`: ###Code len(lista) len(lista[2]) # o segundo elemento da lista é uma lista com 3 elementos! len(numeros) ###Output _____no_output_____ ###Markdown Para remover elementos de uma lista existe a palavra reservada `del` que é utilizada assim: ###Code lista del lista[3] lista del lista[-1] # remove último elemento lista ###Output _____no_output_____ ###Markdown Iterar uma lista é simples: ###Code for numero in numeros: print(numero) ###Output 1 2.5 3 4.5 5 ###Markdown O for do Python, diferentemente de outras linguagens como C e Java, faz o controle dos índices internamente.Vamos fazer mais um exemplo para deixar claro: ###Code numeros = range(1, 11) # cria uma lista de números de 1 a 10 list(numeros) for numero in numeros: print(numero ** 2) # numero elevado a segunda potência ###Output 1 4 9 16 25 36 49 64 81 100 ###Markdown A função range(inicio, fim) cria listas de valores no intervalo de inicio até fim - 1. Ao lidar com intervalos no python o primeiro número é sempre incluso e o último excluído. Segue alguns exemplos de uso da função range() ###Code list(range(10)) # números de 0 a 9 list(range(10, 20)) # números de 10 a 19 list(range(10, 21)) # números de 10 a 20 ###Output _____no_output_____ ###Markdown ExercícioCrie uma lista de números de 2 a 8 e imprima cada número vezes pi. Substiua os ... por código python. ###Code from math import pi numeros = ... # crie a lista de números de 2 a 8 for numero in numeros: print( ... ) # imprime o número vezes pi ###Output _____no_output_____ ###Markdown ExercicioCrie uma lista de preços de produtos em dólar (somente números) e imprima seu valor convertido para reais. ###Code taxa_dolar = 3.53 # mude esse valor caso o valor do dólar tenha mudado preços = ... # python 3 permite declarar variáveis com acentos for preço in preço: print(...) ###Output _____no_output_____ ###Markdown DicionáriosDicionários são estruturas de dados utilizadas para armazenar conjuntos de chaves e valores. Em algumas linguagens também são conhecidos como mapaemento.A diferança de uso entre lista e dicionáro é que o último é acessado por *chaves* e não pela *posição*. As chaves podem ser inteiros, strings, booleanos e tuplas (este será visto na próxima aula).A seguir temos alguns simples exemplos de uso de diconários.Criar um dict é simples: ###Code notas = {'joao': 5, 'maria': 9, 'ana': 7} notas ###Output _____no_output_____ ###Markdown Para acessar os elementos basta usar sua chave: ###Code notas['ana'] notas['joao'] ###Output _____no_output_____ ###Markdown Para alterar algum valor fazemos: ###Code notas['joao'] = 6.5 notas notas['ana'] = 7.5 notas ###Output _____no_output_____ ###Markdown Verificamos se uma chave existe no dicionário da seguinte maneira: ###Code 'joao' in notas # verifica se o valor é uma chave do dicionário 'joana' in notas 'ana' in notas ###Output _____no_output_____ ###Markdown Para acessar somente as chaves fazemos: ###Code list(notas.keys()) ###Output _____no_output_____ ###Markdown Para acessar somente os valores: ###Code list(notas.values()) ###Output _____no_output_____ ###Markdown Para ter uma lista contendo as chaves e valores: ###Code list(notas.items()) ###Output _____no_output_____ ###Markdown Para iterar dicionáros é preciso ter cuidado. Por padrão as chaves do dicionário são iteradas: ###Code for chave in notas: print(chave) ###Output maria joao ana ###Markdown Caso você queira imprimir os valores é preciso usar `notas.values()`: ###Code for valor in notas.values(): print(valor) ###Output 9 6.5 7.5 ###Markdown Para iterar tanto a chave quanto o valor use a função `notas.items()` como mostrado a seguir: ###Code for chave, valor in notas.items(): print(chave, valor) ###Output maria 9 joao 6.5 ana 7.5 ###Markdown Para ficar mais claro podemos mudar os nomes das variáveis e para ficar mais inteligível formatar a saída: ###Code for nome, nota in notas.items(): print('{0} tirou {1}.'.format(nome.capitalize(), nota)) list(notas.items()) ###Output _____no_output_____ ###Markdown Como visto acima o `notas.items()` retorna uma lista de chaves e valores. Por esse motivo a cada iteração temos acesso a cada chave e valor do dicionário `notas`, tornando possível essa iteração mais simples e semântica. Agora que já temos uma noção das estruturas de dados utilizadas, podemos continuar a visualizar as informações dos repositórios do github:*PS: relaxe, pois nas próximas aulas veremos a fundo essas estruturas!* De volta à API do githubAnteriormente realizamos uma requisição à API do github para pegar os repositórios do usuário `lamenezes` e armazenamos a resposta na variável `response`. Essa variável ainda está disponível para nós, o que nos permite continuar nosso exemplo anterior: ###Code repositorios = response.json() # lista de dicionários com dados de cada repositório repo = repositorios[11] # vamos analisar o décimo primeiro repositório repo repo['full_name'] repo['description'] repo['created_at'] # data de criação repo['html_url'] # URL da página principal do repositório ###Output _____no_output_____ ###Markdown Também temos os dados do dono (owner) do repositório: ###Code dono = repo['owner'] dono['login'] ###Output _____no_output_____ ###Markdown `'owner'` é um dicionário dentro do dicionário do repositório (sim, é possível guardar dicionários dentro de dicionários)Também podemos acessar as informações diretamente sem recorrer à variável intermediária `dono`: ###Code repo['owner']['login'] ###Output _____no_output_____ ###Markdown Exercicios- Quantos repositórios o usuário `lamenezes` possui?Lembrando que esses repositórios estão armazenados na lista `repositorios` ###Code # digite o código aqui ###Output _____no_output_____ ###Markdown - Imprima as URLs de todos os repositórios ###Code # digite o código aqui ###Output _____no_output_____ ###Markdown Para os próximos exercícios será necessáro pegar os repositórios do usuário `gvanrossum`. Use a biblioteca requests e faça uma requição à API do github (https://api.github.com/) como demostrado anteriormente. ###Code response = ... response.status_code # status_code deve ser 200 ###Output _____no_output_____ ###Markdown Agora pegue o conteúdo da resposta em formato JSON e atribua à variável `repos`: ###Code repos = ... len(repos) # esta linha deve retornar 5 ###Output _____no_output_____ ###Markdown - Imprima o nome e descrição de todos os repositórios do `gvanrossum`: ###Code import requests response = requests.get('https://api.github.com/users/gvanrossum/repos') repositorios = response.json() for repositorio in repositorios: print(repositorio['full_name'], repositorio['description']) ###Output (u'gvanrossum/500lines', u'500 Lines or Less') (u'gvanrossum/asyncio', u'This project is the asyncio module for Python 3.3. Since Python 3.4, asyncio is part of the standard library.') (u'gvanrossum/ballot-box', u'Automatically exported from code.google.com/p/ballot-box') (u'gvanrossum/mypy', u'Optional static typing for Python') (u'gvanrossum/path-pep', u'PEP for a file system path protocol in Python') (u'gvanrossum/pyxl3', u'A Python 3 extension for writing structured and reusable inline HTML.') ###Markdown - Quantos forks o repositório gvanrossum/asyncio possui? ###Code # digite o código aqui ###Output _____no_output_____ ###Markdown - Qual o link do perfil do dono dos repositórios? ###Code # digite o código aqui ###Output _____no_output_____
notebooks/Fig_08_S06_InSAR_vs_GPS.ipynb
###Markdown Comparing InSAR with GPS + Figure 8 - Comparing InSAR Time-series with GPS Time-series on Sierra Negra caldera.+ Figure S6 - Coherence matrix for all GPS sites ###Code %matplotlib inline import os import pickle from dateutil.relativedelta import relativedelta import numpy as np from matplotlib import pyplot as plt, ticker from mintpy.defaults.plot import * from mintpy.objects import ifgramStack from mintpy.utils import readfile, plot as pp, utils as ut, network as pnet from mintpy.objects.gps import GPS from mintpy.objects.insar_vs_gps import insar_vs_gps from mintpy import view work_dir = os.path.expanduser('~/Documents/Paper/2019_MintPy/figs_src/insar_vs_gps') os.chdir(work_dir) print('Go to directory: '+work_dir) # GPS site_names = ['GV{:02d}'.format(i) for i in [1] + np.arange(3,11).tolist()] gps_dir = os.path.expanduser('~/data/Galapagos/GPS') ref_site = 'GV01' gps_loc_file = os.path.join(gps_dir, 'loc.txt') start_date = '20141101' end_date = '20180625' # InSAR proj_dir = os.path.expanduser('~/insarlab/Galapagos/GalapagosSenDT128/mintpy') out_file = 'mintpy.pickle' ts_file = os.path.join(proj_dir, 'timeseries_ECMWF_ramp_demErr.h5') geom_file = os.path.join(proj_dir, 'inputs/geometryRadar.h5') temp_coh_file = os.path.join(proj_dir, 'temporalCoherence.h5') ## PySAR vs GIAnT #out_file = 'mintpy_m.pickle'; ts_file = os.path.join(proj_dir, '../giant/mintpy/timeseries_ECMWF_ramp_demErr.h5') #out_file = 'g-sbas.pickle'; ts_file = os.path.join(proj_dir, '../giant/Stack/LS-PARAMS.h5') #out_file = 'g-nsbas.pickle'; ts_file = os.path.join(proj_dir, '../giant/Stack/NSBAS-PARAMS.h5') #out_file = 'g-timefun.pickle'; ts_file = os.path.join(proj_dir, '../giant/Stack/TS-PARAMS.h5') ###Output Go to directory: /Users/yunjunz/Documents/Paper/2019_MintPy/figs_src/insar_vs_gps ###Markdown Read / Generate and Save data ###Code if not os.path.isfile(out_file): obj = insar_vs_gps(ts_file, geom_file, temp_coh_file, site_names, gps_dir, ref_site=ref_site, start_date=start_date, end_date=end_date) obj.open() with open(out_file, 'wb') as f: pickle.dump(obj.ds, f) print('saved to pickle file {}.'.format(out_file)) ds = dict(obj.ds) else: with open(out_file, 'rb') as f: ds = pickle.load(f) print('read from pickle file {}.'.format(out_file)) ###Output reading GPS GV10 reading InSAR acquisition 98/98 with linear interpolation reading temporal coherence reference insar and gps to a common date saved to pickle file mintpy.pickle. ###Markdown Fig. 8b - Displacement Time-series from InSAR and GPS ###Code fig, ax = plt.subplots(figsize=(4, 6)) site2plot = insar_vs_gps.sort_by_velocity(ds) for i in range(len(site2plot)): site = ds[site2plot[i]] ax = insar_vs_gps.plot_one_site(ax, site, offset=0.3*i) # axis format yr_list = [i.year + (i.timetuple().tm_yday - 1)/365.25 for i in site['insar_datetime']] ax, t0, t1 = pp.auto_adjust_xaxis_date(ax, yr_list) #ax.set_xlim(t0, t1+relativedelta(months=12)) ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) ax.tick_params(which='both', direction='in', labelsize=font_size, bottom=True, top=True, left=True, right=True) ax.set_xlabel('Time [years]', fontsize=font_size) ax.set_ylabel('LOS Displacement [m]', fontsize=font_size) ax.annotate(r'$RMSE$ / $R^2$ / $\gamma_{temp}$', xy=(1.03, -0.01), xycoords='axes fraction', fontsize=font_size, color='k') ax.annotate(' [cm]', xy=(1.03, -0.05), xycoords='axes fraction', fontsize=font_size, color='k') # legend handles, labels = ax.get_legend_handles_labels() ax.legend([handles[-1], handles[0]], ['GPS', 'InSAR'], loc='upper left', bbox_to_anchor=(0.03, 0.93), fontsize=font_size) # output out_fig = os.path.abspath('insar_vs_gps_point_ts.png') #plt.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=fig_dpi) print('save figure to file', out_fig) plt.show() ###Output save figure to file /Users/yunjunz/Documents/Paper/2019_MintPy/figs_src/insar_vs_gps/insar_vs_gps_point_ts.png ###Markdown Fig. 8a - InSAR velocity map with GPS location on Sierra Negra ###Code vel_file = os.path.join(proj_dir, 'geo/geo_velocity_masked.h5') dem_file = os.path.join(proj_dir, '../DEM/demLat_S02_N01_Lon_W092_W090.dem.wgs84') ts_file = os.path.join(proj_dir, 'geo/geo_timeseries_ECMWF_ramp_demErr.h5') mask_file = os.path.join(proj_dir, 'geo/geo_maskTempCoh.h5') fig, ax = plt.subplots(figsize=(5, 3)) # call view.py functions to plot InSAR background cmd = 'view.py {} 20180619 --ref-date 20141213 --dem {} --dem-nocontour -m {} '.format(ts_file, dem_file, mask_file) cmd += '--sub-lat -0.86 -0.77 --sub-lon -91.19 -91.07 -u m --vlim -0.4 2.5 ' cmd += '--lalo-step 0.05 --lalo-loc 1 0 1 0 --scalebar 0.2 0.85 0.05 ' cmd += '--fontsize 12 --notitle --dpi 600 --noverbose ' cmd += '--cbar-nbins 6 --cbar-ext both --nomultilook ' cmd += '--show-gps --gps-comp enu2los --ref-gps GV01 ' print(cmd) d_v, atr, inps = view.prep_slice(cmd) inps.cbar_label = 'LOS Displacement [m]' ax, inps, im, cbar = view.plot_slice(ax, d_v, atr, inps) # output out_fig = os.path.abspath('insar_vs_gps_map.png') #plt.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=fig_dpi) print('save figure to {}'.format(out_fig)) plt.show() ## test - plot single station timeseries - InSAR vs GPS site = ds['GV09'] fig, ax = plt.subplots(figsize=(5, 3)) ax = insar_vs_gps.plot_one_site(ax, site, offset=0) ax.tick_params(which='both', direction='in', top=True, bottom=True, left=True, right=True) #plt.savefig('{}-{}.jpg'.format(site, ref_site), bbox_inches='tight', transparent=True, dpi=fig_dpi) plt.show() ###Output _____no_output_____ ###Markdown Fig. S6 - Coherence Matrix of InSAR observation on GPS sites ###Code def get_site_coherence_matrix(site='GV01'): gps_obj = GPS(site, data_dir=gps_dir) gps_obj.open(print_msg=False) ifg_file = os.path.join(proj_dir, 'inputs/ifgramStack.h5') geom_file = os.path.join(proj_dir, 'inputs/geometryRadar.h5') stack_obj = ifgramStack(ifg_file) stack_obj.open(print_msg=False) date12_list_all = stack_obj.get_date12_list(dropIfgram=True) coord = ut.coordinate(stack_obj.metadata, lookup_file=geom_file) y, x = coord.geo2radar(gps_obj.site_lat, gps_obj.site_lon, print_msg=False)[0:2] box = (x, y, x+1, y+1) dset_list = ['coherence-{}'.format(i) for i in date12_list_all] coh = np.squeeze(readfile.read(ifg_file, datasetName=dset_list, box=box, print_msg=False)[0]) print('lat/lon: {:.4f}/{:.4f}, y/x: {}/{}'.format(gps_obj.site_lat, gps_obj.site_lon, y, x)) coh_date12_list = list(np.array(date12_list_all)[np.array(coh) >= 0.25]) date12_to_drop = sorted(list(set(date12_list_all) - set(coh_date12_list))) coh_mat = pnet.coherence_matrix(date12_list_all, coh.tolist()) A = stack_obj.get_design_matrix4timeseries(date12_list = coh_date12_list)[0] if np.linalg.matrix_rank(A) < A.shape[1]: print('Singular design matrix!') return coh_mat gps_sites = ['GV{:02d}'.format(i) for i in [1] + np.arange(3,11).tolist()] fig, axs = plt.subplots(nrows=3, ncols=3, figsize=[9, 9], sharex=True, sharey=True) for i in range(len(gps_sites)): ax = axs.flatten()[i] site = gps_sites[i] coh_mat = get_site_coherence_matrix(site) im = ax.imshow(coh_mat, cmap='jet', vmin=0., vmax=1.) ax.tick_params(which='both', direction='in', labelsize=font_size, bottom=True, top=True, left=True, right=True) ax.annotate(site, xy=(0.4, 0.8), color='k', xycoords='axes fraction', fontsize=font_size) axs[1,0].set_ylabel('Image Number', fontsize=font_size) axs[2,1].set_xlabel('Image Number', fontsize=font_size) # colorbar fig.subplots_adjust(right=0.93) cax = fig.add_axes([0.94, 0.4, 0.01, 0.2]) cbar = plt.colorbar(im, cax=cax) cbar.set_label('Coherence', fontsize=font_size) fig.subplots_adjust(wspace=0.03, hspace=0.05) # output out_fig = os.path.abspath('insar_vs_gps_coh_mat.png') #plt.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=fig_dpi) print('save figure to file', out_fig) plt.show() ## Stats insar_vs_gps.print_stats(ds) ###Output GV01, rmse: 0.0 cm, r_square: 0.00, temp_coh: 0.99 GV03, rmse: 0.8 cm, r_square: 1.00, temp_coh: 1.00 GV04, rmse: 0.4 cm, r_square: 1.00, temp_coh: 1.00 GV05, rmse: 1.5 cm, r_square: 1.00, temp_coh: 1.00 GV06, rmse: 0.6 cm, r_square: 1.00, temp_coh: 1.00 GV07, rmse: 0.6 cm, r_square: 1.00, temp_coh: 0.99 GV08, rmse: 1.1 cm, r_square: 1.00, temp_coh: 0.96 GV09, rmse: 1.9 cm, r_square: 1.00, temp_coh: 0.96 GV10, rmse: 3.8 cm, r_square: 0.72, temp_coh: 0.62
Geometry/Euclid/Chapter13_SimilarTriangles.ipynb
###Markdown Chapter 13 - Similar Triangles$\def\Line1{\buildrel\longleftrightarrow\over{1}}$$\def\Segment1{\overline{1}}$ Definition - Similar Triangles> Two triangles are **similar** if there is a positive real number $k$ such that the length of each side of one triangle is $k$ times the length of each corresponding side of the other triangle. The constant $k$ is called the **ratio of similitude** and the symbol '$\sim$' denotes similarity: $\triangle ABC \sim \triangle DEF$. Theorem 13-1> If two triangles are each similar to a third triangle, then they are similar to each other. Definition - Proportion> A **proportion** is a statement of equality between two ratios.That's a curious definition. It appears to be the *mathematical* definition; others more loosely treat it as a synonym for the ratio itself. Anyway, it follows that triangles are similar iff their corresponding sides are proportional. Theorem 13-2> If two sides of one right triangle are proportional to the corresponding two sides of a second right triangle, then the triangles are similar. Theorem 13-3> Two triangles are similar if and only if their corresponding angles are congruent. Theorem 13-4> If two triangles have two angles of one congruent respectively to two angles of the other, then the triangles are similar. Theorem 13-5> If an acute angle of one right triangle is congruent to the corresponding acute angle of a second right triangle, then the triangles are similar.So many little "theorems" when one can simply look, add angles, figure it out. Theorem madness? Definition - Altitude> A segment is an **altitude** of a triangle if1. One endpoint is a vertex of the triangle;2. The other endpoint is on the *line* containing the side opposite the vertex;3. The segment is perpendicular to the line containing the side opposite the vertex. Theorem 13-6> Altitudes to a pair of corresponding sides in similar triangles are in the same ratio as the corresponding sides of the triangle. Theorem 13-7> If two pairs of corresponding sides of two triangles are proportional and if the *included angles* are congruent, then the triangles are similar. Theorem 13-8> The altitude to the hypotenuse of a right triangle forms two similar triangles, each similar to the original triangle. Definition - Geometric Mean> If $b=c$ in the proportion >> $$ {a\over b} = {c\over d},$$>> then $b$ is called the **geometric mean** between $a$ and $d$. Corollary 13-8.1> In any right triangle, the length of the altitude to the hypotenuse is the geometric mean between the length of the segments it determines on the hypotenuse. Corollary 13-8.2> In any right triangle with an altitude to the hypotenuse, the length of each leg of the triangle is the geometric mean between the length of the entire hypotenuse and the length of the segment of the hypotenuse intersecting that leg.Got all that? Just remember Theorem 13-8 and look at relationships for a given situation. Theorem 13-9> A line segment whose endpoints are on two sides of a triangle and which is parallel to the third side divides these two sides proportionally.That is straightforward. Its converse would make Theorem 13-10 trivial at best so let's do that first. Program - Similar Triangles ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt #- Draw a triangle and transversal. A = [6, 5]; B = [0, 0]; C = [10, 0]; D = [3.6, 3]; E = [7.6, 3] points = np.array([A, B, C, D, E], np.float) segment = np.array([D, E], np.float) triangle = np.array([A, B, C, A], np.float) plt.plot(points[:,0], points[:,1], 'ro') plt.plot(segment[:,0], segment[:,1], 'g') plt.plot(triangle[:,0], triangle[:,1]) fs = 16 plt.text(5.8, 5.3, 'A', fontsize=fs) plt.text(-.8, -.2, 'B', fontsize=fs) plt.text(10.3, -.2, 'C', fontsize=fs) plt.text(2.7, 2.8, 'D', fontsize=fs) plt.text(8, 2.8, 'E', fontsize=fs) #- Jupyter runs show() by default? #- Only if plt.isinteractive() == True. #- And this is so on this machine. #-plt.grid(True) #-plt.axis([-1, 11, -1, 6]) plt.axis('off') plt.show() ###Output _____no_output_____ ###Markdown Theorem 13-9.1 [dek]> (Converse of Theorem 13-9): A line segment with endpoints on two sides of a triangle that divides these two sides proportionally is parallel to the third side.Perhaps the abstraction in this text feels forced because we are not studying *non*-Euclidean geometry where notions of *betweenness* may be defined but have less "obvious" meaning from simple diagrams. OK, "by the book." Proof> 1. Consider triangle $\triangle ABC$ with line segment $\Segment{DE}$ whose endpoints touch side $\Segment{AB}$ at point $D$ and side $\Segment{AC}$ at point $E$. (*Given*.)> 2. Segment $\Segment{DE}$ divides sides proportionally (*given*, [Definition of proportion](Definition---Proportion)) so that>> $$ {\;\;\Segment{AD}\;\;\over\Segment{AB}} = {\;\;\Segment{AE}\;\;\over\Segment{AC}}. $$>> 3. Triangle $\triangle ADE$ is similar to $\triangle ABC$. ([Theorem 13-7](Theorem-13-7).)> 4. Corresponding angles of triangles $\triangle ADE$ and $\triangle ABC$ are congruent. ([Theorem 13-3](Theorem-13-3).)> 5. Considering $\Line{AB}$ as transversal where segments $\Segment{AB}$, $\Segment{DE}$, and $\Segment{BC}$ are extended to lines ([Axiom 2 (inspirational only)](Chapter02_HistoricalGeometry.ipynbAxiom-2---Segments-and-Lines), [Definition of segment](Chapter09_Betweenness.ipynbDefinition---Line-Segment), [Definition of polygon as segments](Chapter10_Angles.ipynbDefinition---Polygon), [Definition of triangle as polygon](Chapter10_Angles.ipynbDefinition---Triangle)), congruence of corresponding angles $\angle ABC$ and $\angle ADE$ implies $\Segment{DE} \Vert \Segment{BC}.$ ([Theorem 11-2](Chapter11_ParallelLines.ipynbTheorem-11-2).)Now *that* is anal. It is also a good exercise. Repeat. Theorem 13-10> The line segment joining the midpoints of two sides of a triangle is parallel to the third side and its length is equal to one-half the length of the third side. ###Code #- For centering plots, this is borrowed from the lovely creation of #- Cameron Davidson-Pilon at https://stackoverflow.com/questions/18380168. from IPython.core.display import HTML HTML(""" <style> .output_png { display: table-cell; text-align: center; vertical-align: middle; } </style> """) ###Output _____no_output_____
ibm/circuit_optimization/Challenge4_CircuitDecomposition.ipynb
###Markdown Exercise 4: Circuit DecompositionWow! If you managed to solve the first three exercises, congratulations! The fourth problem is supposed to puzzle even the quantum experts among you, so don’t worry if you cannot solve it. If you can, hats off to you!You may recall from your quantum mechanics course that quantum theory is unitary. Therefore, the evolution of any (closed) system can be described by a unitary. But given an arbitrary unitary, can you actually implement it on your quantum computer?**"A set of quantum gates is said to be universal if any unitary transformation of the quantum data can be efficiently approximated arbitrarily well as a sequence of gates in the set."** (https://qiskit.org/textbook/ch-algorithms/defining-quantum-circuits.html)Every gate you run on the IBM Quantum Experience is transpiled into single qubit rotations and CNOT (CX) gates. We know that these constitute a universal gate set, which implies that any unitary can be implemented using only these gates. However, in general it is not easy to find a good decomposition for an arbitrary unitary. Your task is to find such a decomposition.You are given the following unitary: ###Code from may4_challenge.ex4 import get_unitary U = get_unitary() print("U has shape", U.shape) ###Output U has shape (16, 16) ###Markdown What circuit would make such a complicated unitary?Is there some symmetry, or is it random? We just updated Qiskit with the introduction of a quantum circuit library (https://github.com/Qiskit/qiskit-terra/tree/master/qiskit/circuit/library). This library gives users access to a rich set of well-studied circuit families, instances of which can be used as benchmarks (quantum volume), as building blocks in building more complex circuits (adders), or as tools to explore quantum computational advantage over classical computation (instantaneous quantum polynomial complexity circuits). ###Code from qiskit import QuantumCircuit from may4_challenge.ex4 import check_circuit, submit_circuit ###Output _____no_output_____ ###Markdown **Using only single qubit rotations and CNOT gates, find a quantum circuit that approximates that unitary $U$ by a unitary $V$ up to an error $\varepsilon = 0.01$, such that $\lVert U - V\rVert_2 \leq \varepsilon$ !** Note that the norm we are using here is the spectral norm, $\qquad \lVert A \rVert_2 = \max_{\lVert \psi \rVert_2= 1} \lVert A \psi \rVert$.This can be seen as the largest scaling factor that the matrix $A$ has on any initial (normalized) state $\psi$. One can show that this norm corresponds to the largest singular value of $A$, i.e., the square root of the largest eigenvalue of the matrix $A^\dagger A$, where $A^{\dagger}$ denotes the conjugate transpose of $A$.**When you submit a circuit, we remove the global phase of the corresponding unitary $V$ before comparing it with $U$ using the spectral norm. For example, if you submit a circuit that generates $V = \text{e}^{i\theta}U$, we remove the global phase $\text{e}^{i\theta}$ from $V$ before computing the norm, and you will have a successful submission. As a result, you do not have to worry about matching the desired unitary, $U$, up to a global phase.**As the single-qubit gates have a much higher fidelity than the two-qubit gates, we will look at the number of CNOT-gates, $n_{cx}$, and the number of u3-gates, $n_{u3}$, to determine the cost of your decomposition as $$\qquad \text{cost} = 10 \cdot n_{cx} + n_{u3}$$Try to optimize the cost of your decomposition. **Note that you will need to ensure that your circuit is composed only of $u3$ and $cx$ gates. The exercise is considered correctly solved if your cost is smaller than 1600.**---For useful tips to complete this exercise as well as pointers for communicating with other participants and asking questions, please take a look at the following [repository](https://github.com/qiskit-community/may4_challenge_exercises). You will also find a copy of these exercises, so feel free to edit and experiment with these notebooks.--- ###Code from qiskit.visualization import plot_state_city from qiskit.compiler import transpile import numpy as np plot_state_city(U, title="U") from scipy.linalg import hadamard h = hadamard(4, dtype=complex) h = np.kron(h,h) print(h.shape) t = np.dot(np.dot(h, U), np.linalg.inv(h)) diag = np.diag(t) test = np.eye(16) * diag test = test / np.linalg.det(test) print(np.linalg.det(test)) plot_state_city(test, title="transformed U") ##### build your quantum circuit here angles = [104, 52, 100, 97, 109, 65, 114, 100] qc = QuantumCircuit(4) qc.h([0,1,2,3]) qc.iso(test, [0,1,2,3], []) qc.h([0,1,2,3]) # apply operations to your quantum circuit here res = transpile(qc, basis_gates=['u3','cx'], optimization_level=2) print({op for op in res.count_ops()}, res.depth()) res.draw('mpl') ##### check your quantum circuit by running the next line check_circuit(res) ###Output Circuit stats: ||U-V||_2 = 7.915118600606424e-15 (U is the reference unitary, V is yours, and the global phase has been removed from both of them). Cost is 147 Great! Your circuit meets all the constrains. Your score is 147. The lower, the better! Feel free to submit your answer and remember you can re-submit a new circuit at any time! ###Markdown You can check whether your circuit is valid before submitting it with `check_circuit(qc)`. Once you have a valid solution, please submit it by running the following cell (delete the `` before `submit_circuit`). You can re-submit at any time. ###Code # Send the circuit as the final answer, can re-submit at any time submit_circuit(res) ###Output _____no_output_____
relation_extraction/merge_sources_infoboxes.ipynb
###Markdown Load data Load data into a dataframe to identify all the possible relationships that exist in the dataset from infoboxes ###Code def load_infoboxes(): with open("info/infoboxes.wikia.json", "r") as r: infobox_wikia = json.load(r) with open("info/infoboxes.gamepedia.json", "r") as r: infobox_gamepedia = json.load(r) types = [] i = 0 for k in infobox_wikia: for relation in infobox_wikia[k]: values = infobox_wikia[k][relation] for value in values: types.append([k, relation, value[1], value[0], "wikia"]) for k in infobox_gamepedia: for relation in infobox_gamepedia[k]: values = infobox_gamepedia[k][relation] for value in values: types.append([k, relation, value[1], value[0], "gamepedia"]) infobox = pd.DataFrame(types, columns=["page", "relation", "type", "value", "source"]) return infobox infobox = load_infoboxes() infobox.relation.value_counts().describe() ###Output _____no_output_____ ###Markdown Filter out rows with properties having less than `counts` ###Code counts = 10 def filter_(infobox, counts): filtered = infobox.groupby('relation').filter(lambda x: len(x) >= counts) return filtered filtered = filter_(infobox, counts) filtered.relation.value_counts().iloc[:5] ###Output _____no_output_____ ###Markdown Genders Let's start with genders ###Code genders = infobox[(infobox["relation"] == "GENDER")].copy() \ .drop(["relation"], axis=1).set_index("page") genders.columns = ["type","gender", "source"] def get_tag(r): if r["type"] == "string": return None soup = BeautifulSoup(r["gender"], "lxml") return soup.body.next.name genders["tag"] = genders.apply(get_tag,axis=1) print(genders.info()) genders.sample(5) ###Output _____no_output_____ ###Markdown Select properties where there are no `sup` or `br` tags, and inspect the remaining to see if they are valuable ###Code genders = genders[(genders["tag"] != "sup") & (genders["tag"] != "br")] genders.tag.value_counts() ###Output _____no_output_____ ###Markdown Seems like there is nothing valuable, so let's use only the strings properties, we'll need to clean them a bit though. ###Code genders = genders[(genders["type"] == "string")] print(genders.info()) def get_gender(values): if len(values) == 1: value = list(values)[0] if value == 'Male' or value == 'Female': return value return 'Undefined' merged_genders = genders.groupby(genders.index)['gender'].apply(set).apply(get_gender) merged_genders.to_csv("info/genders.csv") ###Output _____no_output_____ ###Markdown ```CREATE (:Gender {value:'Male'}), (:Gender {value:'Female'}), (:Gender {value:'Undefined'})``` ```LOAD CSV FROM 'file:///genders.csv' AS line WITH lineMATCH (p:Resource{url:line[0]}) MATCH (g:Gender{value:line[1]})MERGE (p)-[:IsA]->(g)``` First appereance ###Code infobox = load_infoboxes() first_appereance = infobox[(infobox["relation"] == "FIRST_APPEARANCE")].copy() \ .drop(["relation"], axis=1).set_index("page") first_appereance.columns = ["type","first", "source"] ###Output _____no_output_____ ###Markdown Get links ###Code def get_link(r): if r["type"] == "string": return np.nan soup = BeautifulSoup(r["first"], "lxml") anchor = soup.find('a') if not anchor: return np.nan href = anchor.get('href') if not href: return np.nan pound = href.find("#") return href if pound == -1 else href[:pound] first_appereance["link"] = first_appereance.apply(get_link, axis=1) year_re = re.compile(r"^(\.\./)?([0-9]{4}.+[\.html])") def get_first_appereance(values): page:str = None year:str = None for s in values: s_results = year_re.search(s) if s_results: year = s_results.group(2) else: if s.startswith("../"): page = s[3:] else: page = s return [page, year] first_appereance = first_appereance[pd.notna(first_appereance["link"])] appereances = first_appereance.groupby(first_appereance.index)['link'].apply(set).apply(get_first_appereance) appereances = pd.DataFrame(appereances.values.tolist(), index=appereances.index, columns=["entity","year"]) appereances[~pd.isna(appereances.entity)].to_csv("info/first_appereance.csv") ###Output _____no_output_____ ###Markdown ```LOAD CSV WITH HEADERS FROM 'file:///first_appereance.csv' AS line WITH lineMATCH (p1:Resource{url:line.page}) MATCH (p2:Resource{url:line.entity}) MERGE (p1)-[:FirstAppereance]->(p2)``` Other appereances ###Code infobox = load_infoboxes() infobox = filter_(infobox, 30) appereances_rels = ["GAME", "APPEARANCES", "APPEARS_IN", "OTHER_MEDIA"] other_appereances = infobox[infobox.relation.isin(appereances_rels)] def get_tag(r): if r["type"] == "string": return None soup = BeautifulSoup(r["value"], "lxml") return soup.body.next.name other_appereances["tag"] = other_appereances.apply(get_tag, axis=1) other_appereances.sample(5) ###Output _____no_output_____ ###Markdown Discard string and br ###Code other_appereances = other_appereances[(~pd.isna(other_appereances.tag)) & (other_appereances.tag != "br")] other_appereances.tag.value_counts() year_re = re.compile(r"^(\.\./)?([0-9]{4}.+[\.html])") def get_non_year_link(anchor): page = anchor.get("href") if page: if year_re.search(page): return None if page.startswith("../"): page = page[3:] return page return None def get_from_i(i_tags): links = set() for i in i_tags: anchor = i.find('a') if anchor: page = get_non_year_link(anchor) if page: links.add(page) return links def get_appereances(row): tag = row["tag"] soup = BeautifulSoup(row["value"], "lxml") links = set() if tag == "i": i_tags = soup.findAll('i') links.update(get_from_i(i_tags)) if tag == "div": i_tags = soup.findAll('i',recursive=False) if len(i_tags) > 0: links.update(get_from_i(i_tags)) else: anchors = soup.findAll('a') for anchor in anchors: page = get_non_year_link(anchor) if page: links.add(page) if tag == "a": anchors = soup.findAll('a') for anchor in anchors: page = get_non_year_link(anchor) if page: links.add(page) return links #other_appereances[(other_appereances["tag"] == "i")].apply(get_appereances, axis=1) other_appereances["apps"] = other_appereances.apply(get_appereances, axis=1) from itertools import chain final_appereances = pd.DataFrame({ "page": np.repeat(other_appereances.page.values, other_appereances.apps.str.len()), "source": np.repeat(other_appereances.source.values, other_appereances.apps.str.len()), "appereance": list(chain.from_iterable(other_appereances.apps))}) final_appereances.info() final_appereances.to_csv("info/other_appereances.csv") ###Output _____no_output_____ ###Markdown ```LOAD CSV WITH HEADERS FROM 'file:///other_appereances.csv' AS line WITH lineMATCH (p1:Resource{url:line.page}) MATCH (p2:Resource{url:line.appereance}) MERGE (p1)-[:AppearsIn]->(p2)``` Location ###Code infobox = load_infoboxes() list(infobox.relation.unique()) locations = infobox[infobox.relation.isin(["LOCATION", "COUNTRY", "REGION", "HOMELAND", "HOMETOWN", "PLACE"])] def get_tag(r): if r["type"] == "string": return None soup = BeautifulSoup(r["value"], "lxml") return soup.body.next.name locations["tag"] = locations.apply(get_tag, axis=1) ###Output _____no_output_____ ###Markdown Discard strings and brs, again ###Code locations = locations[(~pd.isna(locations.tag)) & (locations.tag != "br")] print(locations.type.value_counts()) locations.sample(10) ###Output _____no_output_____
examples/step_by_step_swa.ipynb
###Markdown Data Preparation- load `train` and `test` subsets (CIFAR-10)- split `train` into `train` + `valid` (80/20%, stratified split on labels)- create data generators (with `keras.preprocessing.image.ImageDataGenerator`): - one ImageDataGenerator with data augmentation (horizontal flips, random translations) for train set - three ImageDataGenerator without data augmentation for train, valid and test subset - why `train` ? : to fit Batch Norm statistics without augmentation ###Code print("... loading CIFAR10 dataset ...") (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() y_train = np.squeeze(y_train) y_test = np.squeeze(y_test) x_train, y_train = shuffle(x_train, y_train) x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, stratify=y_train, random_state=51) # cast samples and labels x_train = x_train.astype(np.float32) / 255. x_val = x_val.astype(np.float32) / 255. x_test = x_test.astype(np.float32) / 255. y_train = y_train.astype(np.int32) y_val = y_val.astype(np.int32) y_test = y_test.astype(np.int32) print("\tTRAIN - images {} | {} - labels {} - {}".format(x_train.shape, x_train.dtype, y_train.shape, y_train.dtype)) print("\tVAL - images {} | {} - labels {} - {}".format(x_val.shape, x_val.dtype, y_val.shape, y_val.dtype)) print("\tTEST - images {} | {} - labels {} - {}\n".format(x_test.shape, x_test.dtype, y_test.shape, y_test.dtype)) generator_aug = tf.keras.preprocessing.image.ImageDataGenerator(width_shift_range=8, height_shift_range=8, fill_mode='constant', cval=0.0, horizontal_flip=True) generator = tf.keras.preprocessing.image.ImageDataGenerator() # python iterator object that yields augmented samples iterator_train_aug = generator_aug.flow(x_train, y_train, batch_size=BATCH_SIZE) # python iterators object that yields not augmented samples iterator_train = generator.flow(x_train, y_train, batch_size=BATCH_SIZE) iterator_valid = generator.flow(x_val, y_val, batch_size=BATCH_SIZE) iterator_test = generator.flow(x_test, y_test, batch_size=BATCH_SIZE) # test x, y = iterator_train_aug.next() img = x[0]*255 print("x : {} | {}".format(x.shape, x.dtype)) print("y : {} | {}".format(y.shape, y.dtype)) plt.figure(figsize=(6,6)) plt.imshow(img.astype(np.uint8)) ###Output x : (16, 32, 32, 3) | float32 y : (16,) | int32 ###Markdown Build a network with MovingFreeBatchNorm ###Code from swa_tf import moving_free_batch_norm, StochasticWeightAveraging config = tf.ConfigProto() config.allow_soft_placement = True config.gpu_options.allow_growth = True sess = tf.Session(config=config) with tf.name_scope('inputs'): batch_x = tf.placeholder(shape=[None, 32, 32, 3], dtype=tf.float32) batch_y = tf.placeholder(shape=[None, ], dtype=tf.int64) is_training_bn = tf.placeholder(shape=[], dtype=tf.bool) use_moving_statistics = tf.placeholder(shape=[], dtype=tf.bool) learning_rate = tf.placeholder(shape=[], dtype=tf.float32) # network similar to a VGG11 with tf.name_scope('network'): x = tf.layers.conv2d(batch_x, filters=64, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.max_pooling2d(x, pool_size=2, strides=2, data_format='channels_last', padding='same') x = tf.layers.conv2d(x, filters=128, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.max_pooling2d(x, pool_size=2, strides=2, data_format='channels_last', padding='same') x = tf.layers.conv2d(x, filters=256, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.conv2d(x, filters=256, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.max_pooling2d(x, pool_size=2, strides=2, data_format='channels_last', padding='same') x = tf.layers.conv2d(x, filters=512, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.conv2d(x, filters=512, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.max_pooling2d(x, pool_size=2, strides=2, data_format='channels_last', padding='same') x = tf.layers.conv2d(x, filters=512, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) x = tf.layers.conv2d(x, filters=512, kernel_size=3, strides=1, use_bias=True, activation=tf.nn.relu, data_format='channels_last', padding='same') x = moving_free_batch_norm(x, axis=-1, training=is_training_bn, use_moving_statistics=use_moving_statistics, momentum=0.99) # Global Average Pooling x = tf.reduce_mean(x, axis=[1, 2]) logits = tf.layers.dense(x, units=10, use_bias=True) model_vars = tf.trainable_variables() pprint(model_vars) # operations to update moving averages in batch norm layers # to run before updating weights ! (with tf.control_dependencies()) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) # operations to updates (mean, variance, n) in batch norm layers update_bn_ops = tf.get_collection('UPDATE_BN_OPS') # operations to reset (mean, variance, n) to zero reset_bn_ops = tf.get_collection('RESET_BN_OPS') pprint(update_ops) pprint(update_bn_ops) pprint(reset_bn_ops) # group these operations update_ops = tf.group(*update_ops) update_bn_ops = tf.group(*update_bn_ops) reset_bn_ops = tf.group(*reset_bn_ops) with tf.name_scope('loss'): loss_tf = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=batch_y)) acc_tf = tf.reduce_mean(tf.cast(tf.equal(batch_y, tf.argmax(logits, axis=1)), dtype=tf.float32)) with tf.name_scope('optimizer'): opt = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9) with tf.control_dependencies([update_ops,]): train_op = opt.minimize(loss_tf, var_list=model_vars) with tf.name_scope('SWA'): swa = StochasticWeightAveraging() swa_op = swa.apply(var_list=model_vars) # Make backup variables with tf.variable_scope('BackupVariables'): backup_vars = [tf.get_variable(var.op.name, dtype=var.value().dtype, trainable=False, initializer=var.initialized_value()) for var in model_vars] # operation to assign SWA weights to model swa_to_weights = tf.group(*(tf.assign(var, swa.average(var).read_value()) for var in model_vars)) # operation to store model into backup variables save_weight_backups = tf.group(*(tf.assign(bck, var.read_value()) for var, bck in zip(model_vars, backup_vars))) # operation to get back values from backup variables to model restore_weight_backups = tf.group(*(tf.assign(var, bck.read_value()) for var, bck in zip(model_vars, backup_vars))) global_init_op = tf.global_variables_initializer() sess.run(global_init_op) ###Output _____no_output_____ ###Markdown Set Learning rate policy ###Code def get_learning_rate(step, epoch, steps_per_epoch): if epoch < EPOCHS_BEFORE_SWA: return ALPHA1_LR if step > int(0.9 * EPOCHS * steps_per_epoch): return ALPHA2_LR length_slope = int(0.9 * EPOCHS * steps_per_epoch) - EPOCHS_BEFORE_SWA * steps_per_epoch re return ALPHA1_LR - ((ALPHA1_LR - ALPHA2_LR) / length_slope) * (step - EPOCHS_BEFORE_SWA * steps_per_epoch) steps_per_epoch_train = iterator_train.n//BATCH_SIZE all_steps = [] all_lr = [] step = 0 for epoch in range(EPOCHS): for _ in range(steps_per_epoch_train): all_steps.append(step) all_lr.append(get_learning_rate(step, epoch, steps_per_epoch_train)) step += 1 plt.figure(figsize=(16,4)) plt.plot(all_steps, all_lr) ###Output _____no_output_____ ###Markdown Launch traninig - create a function to fit statistics with train subset- create a function to run inference on [train/]val/test subsets (with/without moving statistics- create a function to run inference with SWA weights ###Code steps_per_epoch_train = int(ceil(iterator_train.n/BATCH_SIZE)) steps_per_epoch_val = int(ceil(iterator_valid.n/BATCH_SIZE)) steps_per_epoch_test = int(ceil(iterator_test.n/BATCH_SIZE)) def fit_bn_statistics(): sess.run(reset_bn_ops) feed_dict = {is_training_bn: True, use_moving_statistics: True} for _ in range(steps_per_epoch_train): x, y = iterator_train.next() feed_dict[batch_x] = x sess.run(update_bn_ops, feed_dict=feed_dict) def inference(iterator, with_moving_statistics=True): feed_dict = {is_training_bn: False, use_moving_statistics: with_moving_statistics} all_acc = [] all_loss = [] nb_steps = int(ceil(iterator.n/BATCH_SIZE)) for _ in range(nb_steps): x, y = iterator.next() feed_dict[batch_x] = x feed_dict[batch_y] = y acc_v, loss_v = sess.run([acc_tf, loss_tf], feed_dict=feed_dict) all_acc.append(acc_v) all_loss.append(loss_v) return np.mean(all_acc), np.mean(all_loss) %%time # test your random model ? acc, loss = inference(iterator_valid, with_moving_statistics=True) print("Random model : acc={:.5f} loss={:.5f}".format(acc, loss)) %%time # now fit batch norm statistics and make inference again fit_bn_statistics() acc, loss = inference(iterator_valid, with_moving_statistics=False) print("Random model : acc={:.5f} loss={:.5f}".format(acc, loss)) feed_dict_train = {is_training_bn: True, use_moving_statistics: True} step = 0 start = time() acc_train = [] loss_train = [] acc_val = [] loss_val = [] acc_val_bn = [] loss_val_bn = [] acc_val_swa = [] loss_val_swa = [] for epoch in range(EPOCHS): acc = [] loss = [] for _ in range(steps_per_epoch_train): feed_dict_train[learning_rate] = get_learning_rate(step, epoch, steps_per_epoch_train) x, y = iterator_train_aug.next() feed_dict_train[batch_x] = x feed_dict_train[batch_y] = y acc_v, loss_v, _ = sess.run([acc_tf, loss_tf, train_op], feed_dict=feed_dict_train) acc.append(acc_v) loss.append(loss_v) step += 1 acc = np.mean(acc) loss = np.mean(loss) acc_train.append((epoch,acc)) loss_train.append((epoch,loss)) print("TRAIN @ EPOCH {} : acc={:.5f} loss={:.5f} in {:.3f} s".format(epoch, acc, loss, time()-start)) acc, loss = inference(iterator_valid, with_moving_statistics=True) acc_val.append((epoch,acc)) loss_val.append((epoch,loss)) print("VALID @ EPOCH {} : acc={:.5f} loss={:.5f} in {:.3f} s".format(epoch, acc, loss, time()-start)) # now fit batch norm statistics and make inference again fit_bn_statistics() acc, loss = inference(iterator_valid, with_moving_statistics=False) acc_val_bn.append((epoch,acc)) loss_val_bn.append((epoch,loss)) print("VALID updated bn @ EPOCH {} : acc={:.5f} loss={:.5f} in {:.3f} s".format(epoch, acc, loss, time()-start)) if epoch >= EPOCHS_BEFORE_SWA: sess.run(swa_op) if epoch > EPOCHS_BEFORE_SWA: sess.run(save_weight_backups) sess.run(swa_to_weights) fit_bn_statistics() acc, loss = inference(iterator_valid, with_moving_statistics=False) acc_val_swa.append((epoch,acc)) loss_val_swa.append((epoch,loss)) print("VALID with SWA @ EPOCH {} : acc={:.5f} loss={:.5f} in {:.3f} s".format(epoch, acc, loss, time()-start)) sess.run(restore_weight_backups) ###Output TRAIN @ EPOCH 0 : acc=0.33632 loss=1.80784 in 555.822 s VALID @ EPOCH 0 : acc=0.32030 loss=2.26033 in 585.007 s VALID updated bn @ EPOCH 0 : acc=0.43340 loss=1.51867 in 734.108 s TRAIN @ EPOCH 1 : acc=0.49085 loss=1.41674 in 1245.526 s VALID @ EPOCH 1 : acc=0.52660 loss=1.38642 in 1274.491 s VALID updated bn @ EPOCH 1 : acc=0.55820 loss=1.22307 in 1426.498 s TRAIN @ EPOCH 2 : acc=0.57248 loss=1.20919 in 1924.985 s VALID @ EPOCH 2 : acc=0.42920 loss=1.87827 in 1950.423 s VALID updated bn @ EPOCH 2 : acc=0.62640 loss=1.07354 in 2082.893 s TRAIN @ EPOCH 3 : acc=0.62680 loss=1.07984 in 2599.358 s VALID @ EPOCH 3 : acc=0.56520 loss=1.39566 in 2627.226 s VALID updated bn @ EPOCH 3 : acc=0.65010 loss=1.01985 in 2783.791 s TRAIN @ EPOCH 4 : acc=0.66347 loss=0.97796 in 3320.516 s VALID @ EPOCH 4 : acc=0.64350 loss=1.03858 in 3349.541 s VALID updated bn @ EPOCH 4 : acc=0.68600 loss=0.90761 in 3498.834 s TRAIN @ EPOCH 5 : acc=0.70213 loss=0.87313 in 4008.384 s VALID @ EPOCH 5 : acc=0.74610 loss=0.73422 in 4034.948 s VALID updated bn @ EPOCH 5 : acc=0.73470 loss=0.76876 in 4178.613 s TRAIN @ EPOCH 6 : acc=0.74235 loss=0.75533 in 4689.395 s VALID @ EPOCH 6 : acc=0.59010 loss=1.41301 in 4717.241 s VALID updated bn @ EPOCH 6 : acc=0.74260 loss=0.75759 in 4870.484 s VALID with SWA @ EPOCH 6 : acc=0.76910 loss=0.67760 in 5019.735 s TRAIN @ EPOCH 7 : acc=0.77425 loss=0.66192 in 5509.414 s VALID @ EPOCH 7 : acc=0.79820 loss=0.58907 in 5535.178 s VALID updated bn @ EPOCH 7 : acc=0.79040 loss=0.61905 in 5668.677 s VALID with SWA @ EPOCH 7 : acc=0.78510 loss=0.63085 in 5808.475 s
Use-case_Cancer_detection/Cancer_encoder_e3-SelectedFeautures-Benign.ipynb
###Markdown Imports ###Code import random import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from graphs import plot_correlation_matrix import torch from torchvision import datasets, transforms #quanutm lib import pennylane as qml from pennylane import numpy as np from pennylane.optimize import AdamOptimizer import torch from torchvision import datasets, transforms import sys sys.path.append("..") # Adds higher directory to python modules path from qencode.initialize import setAB_amplitude, setAux, setEnt from qencode.encoders import e3_enhance from qencode.training_circuits import swap_t from qencode.qubits_arrangement import QubitsArrangement from qencode.utils.mnist import get_dataset ###Output _____no_output_____ ###Markdown Data ###Code df=pd.read_csv("cancer.csv", nrows=500) df.head() diagnosis=[] for d in df.diagnosis: if d=="M": diagnosis.append(1.0) else: diagnosis.append(0.0) df["diagnosis"]=diagnosis print('Benign: ', df['diagnosis'].value_counts()[0]) print('Malign: ', df['diagnosis'].value_counts()[1]) df.info() df.describe() #Data seams pretty clean without any nan value ## engineering two new features to have 32 feutures that can be encoded om 5 qubits. over_average = [] under_average = [] mean = {} std = {} for col in df: if col not in ["id","diagnosis" ]: mean[col]=df[col].mean() std[col]=df[col].std() for index,row in df.iterrows(): o_average=0 u_average=0 for col in df: if col not in ["id","diagnosis" ]: if row[col]> mean[col]+2* std[col]: o_average = o_average + 1 if row[col]< mean[col]+2* std[col]: u_average= u_average + 1 over_average.append(o_average) under_average.append(u_average) df["over_average"] = over_average df["under_average"] = under_average df.head() plot_correlation_matrix(df, "Original") df = df.sample(frac=1) fraud_df = df.loc[df['diagnosis'] == 0][:195] non_fraud_df = df.loc[df['diagnosis'] == 1] normal_distributed_df = pd.concat([fraud_df, non_fraud_df]) sub_sample_df = normal_distributed_df.sample(frac=1, random_state=42) sub_sample_df.head() sub_sample_corr = sub_sample_df.corr() plot_correlation_matrix(sub_sample_corr, "Sub Sample Correlation Matrix") for col in df: if col not in ["id","diagnosis" ]: df[col]=df[col]/df[col].max() df.describe() def find_strongest_correlations(dataframe, qubits): class_correlations = dataframe.loc['diagnosis', :] class_correlations = class_correlations.drop(index = 'diagnosis') feature_list = list(class_correlations.index) correlation_list = [class_correlations[x] for x in feature_list] features = [] correlations = [] for i in range(int(qubits/2)): correlations.append(max(correlation_list)) features.append(feature_list[correlation_list.index(max(correlation_list))]) del feature_list[correlation_list.index(max(correlation_list))] del correlation_list[correlation_list.index(max(correlation_list))] correlations.append(min(correlation_list)) features.append(feature_list[correlation_list.index(min(correlation_list))]) del feature_list[correlation_list.index(min(correlation_list))] del correlation_list[correlation_list.index(min(correlation_list))] return features, correlations print(find_strongest_correlations(sub_sample_corr, 8)) feature_list, correlations = find_strongest_correlations(sub_sample_corr, 8) malign=df[df["diagnosis"]==0][feature_list] malign.head() benign=df[df["diagnosis"]!=0][feature_list] benign.head() input_data=malign.to_numpy() input_data ###Output _____no_output_____ ###Markdown Training node ###Code shots = 2500 nr_trash=2 nr_latent=1 nr_ent=0 spec = QubitsArrangement(nr_trash, nr_latent, nr_swap=1, nr_ent=nr_ent) print("Qubits:", spec.qubits) #set up the device dev = qml.device("default.qubit", wires=spec.num_qubits) nr_layers = 4 @qml.qnode(dev) def training_circuit_example(init_params, encoder_params, reinit_state, x): # Initialization setAB_amplitude(spec, init_params) setAux(spec, reinit_state) #encoder for params in encoder_params: e3_enhance(params, float(x), spec) #swap test swap_t(spec) return [qml.probs(i) for i in spec.swap_qubits] ###Output _____no_output_____ ###Markdown Training parameters ###Code epochs = 500 learning_rate = 0.0003 batch_size = 5 num_samples = 0.8 # proportion of the data used for training beta1 = 0.9 beta2 = 0.999 opt = AdamOptimizer(learning_rate, beta1=beta1, beta2=beta2) def fid_func(output): # Implemented as the Fidelity Loss # output[0] because we take the probability that the state after the # SWAP test is ket(0), like the reference state fidelity_loss = 1 / output[0] return fidelity_loss def cost(encoder_params, X): reinit_state = [0 for i in range(2 ** len(spec.aux_qubits))] reinit_state[0] = 1.0 loss = 0.0 for x in X: output = training_circuit_example(init_params=x[0], encoder_params=encoder_params, reinit_state=reinit_state,x=x[0][1])[0] f = fid_func(output) loss = loss + f return loss / len(X) def fidelity(encoder_params, X): reinit_state = [0 for _ in range(2 ** len(spec.aux_qubits))] reinit_state[0] = 1.0 loss = 0.0 for x in X: output = training_circuit_example(init_params=x[0], encoder_params=encoder_params, reinit_state=reinit_state,x=x[0][1])[0] f = output[0] loss = loss + f return loss / len(X) def iterate_batches(X, batch_size): random.shuffle(X) batch_list = [] batch = [] for x in X: if len(batch) < batch_size: batch.append(x) else: batch_list.append(batch) batch = [] if len(batch) != 0: batch_list.append(batch) return batch_list training_data = [ torch.tensor([input_data[i]]) for i in range(int(len(input_data)*num_samples))] test_data = [torch.tensor([input_data[i]]) for i in range(int(len(input_data)*num_samples),len(input_data))] batches=iterate_batches(training_data, batch_size) X_training = training_data X_tes = test_data # initialize random encoder parameters nr_encod_qubits = len(spec.trash_qubits) + len(spec.latent_qubits) nr_par_encoder = nr_layers * 2 * nr_encod_qubits + 2 * len(spec.trash_qubits) encoder_params = np.random.uniform(size=(1, nr_par_encoder), requires_grad=True) ###Output _____no_output_____ ###Markdown training ###Code np_benign = benign.to_numpy() benign_data = [ torch.tensor([np_benign[i]]) for i in range(len(benign.to_numpy()))] loss_hist=[] fid_hist=[] loss_hist_test=[] fid_hist_test=[] benign_fid=[] for epoch in range(epochs): batches = iterate_batches(X=training_data, batch_size=batch_size) for xbatch in batches: encoder_params = opt.step(cost, encoder_params, X=xbatch) if epoch%5 == 0: loss_training = cost(encoder_params, X_training ) fidel = fidelity(encoder_params, X_training ) loss_hist.append(loss_training) fid_hist.append(fidel) print("Epoch:{} | Loss:{} | Fidelity:{}".format(epoch, loss_training, fidel)) loss_test = cost(encoder_params, X_tes ) fidel = fidelity(encoder_params, X_tes ) loss_hist_test.append(loss_test) fid_hist_test.append(fidel) print("Test-Epoch:{} | Loss:{} | Fidelity:{}".format(epoch, loss_test, fidel)) b_fidel = fidelity(encoder_params, benign_data ) benign_fid.append(b_fidel) print("malign fid:{}".format(b_fidel)) experiment_parameters={"autoencoder":"e2","params":encoder_params} f=open("Cancer_encoder_e3-SelectedFeautures-Benign/params"+str(epoch)+".txt","w") f.write(str(experiment_parameters)) f.close() ###Output C:\Users\tomut\anaconda3\envs\qhack2022\lib\site-packages\pennylane\math\multi_dispatch.py:63: UserWarning: Contains tensors of types {'torch', 'autograd'}; dispatch will prioritize TensorFlow and PyTorch over autograd. Consider replacing Autograd with vanilla NumPy. warnings.warn( ###Markdown Rezults ###Code import matplotlib.pyplot as plt fig = plt.figure() plt.plot([x for x in range(0,len(loss_hist)*5,5)],np.array(fid_hist),label="train fid") plt.plot([x for x in range(0,len(loss_hist)*5,5)],np.array(fid_hist_test),label="test fid") plt.plot([x for x in range(0,len(loss_hist)*5,5)],np.array(benign_fid),label="malign fid") plt.legend() plt.title("Malign 3-1-3->compression fidelity e3",) plt.xlabel("epoch") plt.ylabel("fid") print("fidelity:",fid_hist[-1]) fig = plt.figure() plt.plot([x for x in range(0,len(loss_hist)*5,5)],np.array(loss_hist),label="train loss") plt.plot([x for x in range(0,len(loss_hist)*5,5)],np.array(loss_hist_test),label="test loss") plt.legend() plt.title("Benign 3-1-3->compression loss e3",) plt.xlabel("epoch") plt.ylabel("loss") print("loss:",loss_hist[-1]) name = "Cancer_encoder_e3" Circuit_prop={ "shots":shots, "nr_trash":nr_trash, "nr_latent":nr_latent ,"nr_ent":nr_ent } Training_param = { "num_samples" : num_samples, "batch_size" :batch_size, "epochs" :epochs, "learning_rate" : learning_rate , "beta1" : beta1, "beta2 ":beta2, "optimizer":"Adam"} performance={"loss_hist":loss_hist, "fid_hist":fid_hist, "loss_hist_test":loss_hist_test, "fid_hist_test":fid_hist_test, "encoder_params":encoder_params} experiment_data={"Circuit_prop":Circuit_prop, "Training_param":Training_param, "performance:":performance, "Name":name} """ # open file for writing f = open(name+".txt","w") f.write( str(experiment_data) ) """ ###Output _____no_output_____ ###Markdown Benign performance ###Code np_benign = benign.to_numpy() benign_data = [ torch.tensor([np_benign[i]]) for i in range(len(benign.to_numpy()))] loss = cost(encoder_params, benign_data ) fidel = fidelity(encoder_params, benign_data ) print("Benign results:") print("fidelity=",fidel) print("loss=",loss) ###Output C:\Users\tomut\anaconda3\envs\qhack2022\lib\site-packages\pennylane\math\multi_dispatch.py:63: UserWarning: Contains tensors of types {'torch', 'autograd'}; dispatch will prioritize TensorFlow and PyTorch over autograd. Consider replacing Autograd with vanilla NumPy. warnings.warn( ###Markdown Classifyer ###Code beningn_flist=[] for b in benign_data: f=fidelity(encoder_params, [b]) beningn_flist.append(f.item()) print(min(beningn_flist)) print(max(beningn_flist)) malign_flist=[] for b in training_data: f=fidelity(encoder_params, [b]) malign_flist.append(f.item()) print(min(malign_flist)) print(max(malign_flist)) beningn_flist plt.hist(beningn_flist, bins = 100 ,label="malign", color = "skyblue",alpha=0.4) plt.hist(malign_flist, bins =100 ,label="benign",color = "red",alpha=0.4) plt.title("Compression fidelity",) plt.legend() plt.show() split=0.985 print("split:",split) b_e=[] for i in beningn_flist: if i<split: b_e.append(1) else: b_e.append(0) ab_ac=sum(b_e)/len(b_e) print("malign classification accuracy:",ab_ac) m_e=[] for i in malign_flist: if i>split: m_e.append(1) else: m_e.append(0) am_ac=sum(m_e)/len(m_e) print("benign classification accuracy:",am_ac) t_ac=(sum(b_e)+sum(m_e))/(len(b_e)+len(m_e)) print("total accuracy:",t_ac) ###Output split: 0.985 malign classification accuracy: 0.7589743589743589 benign classification accuracy: 0.8155737704918032 total accuracy: 0.7904328018223234
notebooks/TextProtoNetFinal.ipynb
###Markdown Load mini newsgroup dataset ###Code text_vectors = pickle.load(open('../data/mini_newsgroup_vectors.pkl','rb')) mini_df = pickle.load(open('../data/mini_newsgroup_data.pkl','rb')) #mini_df, text_vectors = get_mini_dataset(samples_per_class = 30, embebeddings = 'BERT') ###Output _____no_output_____ ###Markdown Complete protonet pipeline ###Code class ProtoNetText(torch.nn.Module): def __init__(self, embedding_size, hidden_size, proto_dim): super(ProtoNetText, self).__init__() self.embed_size = embedding_size self.proto_dim = proto_dim self.hidden_size = hidden_size self.l1 = torch.nn.Linear(self.embed_size, self.hidden_size) self.rep_block =torch.nn.Sequential(*[torch.nn.BatchNorm1d(hidden_size), torch.nn.Linear(self.hidden_size, self.hidden_size)]) self.final = torch.nn.Linear(self.hidden_size, self.proto_dim) def forward(self, x): return self.final(self.rep_block(self.l1(x))) # x_latent, q_latent, labels_onehot, num_classes, num_support, num_queries class ProtoLoss(torch.nn.Module): def __init__(self, num_classes, num_support, num_queries, ndim): super(ProtoLoss,self).__init__() self.num_classes = num_classes self.num_support = num_support self.num_queries = num_queries self.ndim = ndim def euclidean_distance(self, a, b): N, D = a.shape[0], a.shape[1] M = b.shape[0] a = torch.repeat_interleave(a.unsqueeze(1), repeats = M, dim = 1) b = torch.repeat_interleave(b.unsqueeze(0), repeats = N, dim = 0) return 1.*torch.sum(torch.pow((a-b), 2),2) def forward(self, x, q, labels_onehot): protox = torch.mean(1.*x.reshape([self.num_classes,self.num_support,self.ndim]),1) dists = self.euclidean_distance(protox, q) logpy = torch.log_softmax(-1.*dists,0).transpose(1,0).view(self.num_classes,self.num_queries,self.num_classes) ce_loss = -1. * torch.mean(torch.mean(logpy * labels_onehot.float(),1)) accuracy = torch.mean((torch.argmax(labels_onehot.float(),-1).float() == torch.argmax(logpy,-1).float()).float()) return ce_loss, accuracy n_way = 5 k_shot = 5 proto_dim = 32 n_query = 2 n_meta_test_way = 5 k_meta_test_shot = 5 n_meta_test_query = 2 num_epochs = 20 num_episodes = 200 hidden_dim = 100 embed_size = 768 model_text = ProtoNetText(embed_size, hidden_dim, proto_dim) optimizer_text = torch.optim.Adam(model_text.parameters(), lr=1e-4) criterion = ProtoLoss(n_way, k_shot, n_query, proto_dim) text_generator_ = TextGenerator(mini_df, n_way, k_shot+n_query, n_meta_test_way, k_meta_test_shot+n_meta_test_query) def get_latents(x,y, embed_size, n_way, n_query, k_shot): x_support, x_query = x[:,:,:k_shot,:], x[:,:,k_shot:,:] y_support, y_query = y[:,:,:k_shot,:], y[:,:,k_shot:,:] labels_onehot = y_query.reshape(n_way, n_query, n_way) support_input_t = torch.Tensor(x_support).view(-1, embed_size) query_input_t = torch.Tensor(x_query).view(-1, embed_size) return support_input_t, query_input_t, labels_onehot def get_latents_new(x,y, embed_size, n_way, n_query, k_shot): lookup_dict = {i:np.where(y.reshape(-1,n_way)[:,i] == 1.)[0] for i in range(n_way)} lookup_list = np.ravel([lookup_dict[i] for i in range(n_way)]) ### x_shuffle = x.reshape(-1, embed_size)[lookup_list].reshape(1, n_way, n_query+k_shot, embed_size) y_shuffle = y.reshape(-1, n_way)[lookup_list].reshape(1, n_way, n_query+k_shot, n_way) ### x_support, x_query = x_shuffle[:,:,:k_shot,:], x_shuffle[:,:,k_shot:,:] y_support, y_query = y_shuffle[:,:,:k_shot,:], y_shuffle[:,:,k_shot:,:] labels_onehot = y_query.reshape(n_way, n_query, n_way) support_input_t = torch.Tensor(x_support).view(-1, embed_size) query_input_t = torch.Tensor(x_query).view(-1, embed_size) return support_input_t, query_input_t, labels_onehot for ep in range(num_epochs): print(f'Epoch: {ep}') for epi in range(num_episodes): x, y = text_generator_.sample_batch('meta_train', 1, shuffle = True) support_input_t, query_input_t, labels_onehot = get_latents_new(x,y, embed_size, n_way, n_query, k_shot) x_latent = model_text(support_input_t) q_latent = model_text(query_input_t) # Compute and print loss loss, accuracy = criterion(x_latent, q_latent, torch.tensor(labels_onehot)) optimizer_text.zero_grad() loss.backward() optimizer_text.step() if epi % 50 == 0: with torch.no_grad(): valid_x, valid_y = text_generator_.sample_batch('meta_val', 1, shuffle = True) support_input_valid, query_input_valid, labels_onehot_valid = get_latents_new(valid_x,valid_y, embed_size, n_way, n_query, k_shot) x_latent_valid = model_text(support_input_valid) q_latent_valid = model_text(query_input_valid) # Compute and print loss valid_loss, valid_acc = criterion(x_latent_valid, q_latent_valid, torch.tensor(labels_onehot_valid)) print(f'Epoc {ep}/{num_epochs} Episode {epi}/{num_episodes}, Validation Accuracy: {round(valid_acc.item(),3)}, Validation Loss: {round(valid_loss.item(),3)}') print('Testing ... . . . .. . . . ') meta_test_accuracies = [] for epi in range(1000): test_x, test_y = text_generator_.sample_batch('meta_test', 1, shuffle = True) support_input_test, query_input_test, labels_onehot_test = get_latents_new(test_x,test_y, embed_size, n_way, n_query, k_shot) with torch.no_grad(): x_latent_test = model_text(support_input_test) q_latent_test = model_text(query_input_test) # Compute and print loss test_loss, test_acc = criterion(x_latent_test, q_latent_test, torch.tensor(labels_onehot_valid)) if (epi + 1) % 50 == 0: print(f'Meta test Episode {epi}/{1000}, Test Accuracy: {round(test_acc.item(),3)}, Test Loss: {round(test_loss.item(),3)}') meta_test_accuracies.append(test_acc) avg_acc = np.mean(meta_test_accuracies) stds = np.std(meta_test_accuracies) print('Average Meta-Test Accuracy: {:.5f}, Meta-Test Accuracy Std: {:.5f}'.format(avg_acc, stds)) ###Output Average Meta-Test Accuracy: 0.83860, Meta-Test Accuracy Std: 0.22740
notebooks/trade_demo/demo/Data Owner - Italy.ipynb
###Markdown Loading the dataset ###Code data = pd.read_csv("../datasets/it - feb 2021.csv")[0:100] data.head() ###Output /Users/areopagus/opt/anaconda3/envs/syft/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3444: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False. exec(code_obj, self.user_global_ns, self.user_ns) ###Markdown Logging into the domain ###Code it = sy.login(email="[email protected]", password="changethis", port=8082) ###Output WARNING: CHANGE YOUR USERNAME AND PASSWORD!!! Anyone can login as an admin to your node right now because your password is still the default PySyft username and password!!! Connecting to http://localhost:8082... done! Logging into competent_hassabis... done! ###Markdown Upload the dataset to Domain node ###Code # We will upload only the first few rows # All these three columns are of `int` type # NOTE: casting this tensor as np.int32 is REALLY IMPORTANT. We need to create flags for this or something data_batch = ((np.array(list(data['Trade Value (US$)'])) / 100000)[0:10]).astype(np.int32) trade_partners = ((list(data['Partner'])))[0:10] entities = list() for i in range(len(trade_partners)): entities.append(DataSubject(name="Other Asia, nes")) # Upload a private dataset to the Domain object, as the root owner sampled_italy_dataset = sy.Tensor(data_batch) sampled_italy_dataset.public_shape = sampled_italy_dataset.shape sampled_italy_dataset = sampled_italy_dataset.private(0, 3, entities="bob").tag("trade_flow") it.load_dataset( assets={"Italy Trade": sampled_italy_dataset}, name="Italy Trade Data - First few rows", description="""A collection of reports from iStat's statistics bureau about how much it thinks it imports and exports from other countries.""", ) it.datasets ###Output _____no_output_____ ###Markdown Create a Data Scientist User ###Code it.users.create( **{ "name": "Sheldon Cooper", "email": "[email protected]", "password": "bazinga", "budget":200 } ) ###Output _____no_output_____ ###Markdown Accept/Deny Requests to the Domain ###Code it.requests.pandas it.requests[-1].accept() ###Output _____no_output_____ ###Markdown Loading the dataset ###Code data = pd.read_csv("../datasets/it - feb 2021.csv")[0:100] data.head() ###Output /Users/areopagus/opt/anaconda3/envs/syft/lib/python3.9/site-packages/IPython/core/interactiveshell.py:3444: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False. exec(code_obj, self.user_global_ns, self.user_ns) ###Markdown Logging into the domain ###Code it = sy.login(email="[email protected]", password="changethis", port=8082) ###Output WARNING: CHANGE YOUR USERNAME AND PASSWORD!!! Anyone can login as an admin to your node right now because your password is still the default PySyft username and password!!! Connecting to http://localhost:8082... done! Logging into competent_hassabis... done! ###Markdown Upload the dataset to Domain node ###Code # We will upload only the first few rows # All these three columns are of `int` type # NOTE: casting this tensor as np.int32 is REALLY IMPORTANT. We need to create flags for this or something data_batch = ((np.array(list(data['Trade Value (US$)'])) / 100000)[0:10]).astype(np.int32) trade_partners = ((list(data['Partner'])))[0:10] entities = list() for i in range(len(trade_partners)): entities.append(Entity(name="Other Asia, nes")) # Upload a private dataset to the Domain object, as the root owner sampled_italy_dataset = sy.Tensor(data_batch) sampled_italy_dataset.public_shape = sampled_italy_dataset.shape sampled_italy_dataset = sampled_italy_dataset.private(0, 3, entities="bob").tag("trade_flow") it.load_dataset( assets={"Italy Trade": sampled_italy_dataset}, name="Italy Trade Data - First few rows", description="""A collection of reports from iStat's statistics bureau about how much it thinks it imports and exports from other countries.""", ) it.datasets ###Output _____no_output_____ ###Markdown Create a Data Scientist User ###Code it.users.create( **{ "name": "Sheldon Cooper", "email": "[email protected]", "password": "bazinga", "budget":200 } ) ###Output _____no_output_____ ###Markdown Accept/Deny Requests to the Domain ###Code it.requests.pandas it.requests[-1].accept() ###Output _____no_output_____ ###Markdown Loading the dataset ###Code data = pd.read_csv("../datasets/it - feb 2021.csv")[0:100] data.head() ###Output /Users/andrewliamtrask/opt/anaconda3/envs/syft/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3169: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False. has_raised = await self.run_ast_nodes(code_ast.body, cell_name, ###Markdown Logging into the domain ###Code it = sy.login(email="[email protected]", password="changethis", port=8082) ###Output Connecting to http://localhost:8082... done! Logging into italy... done! ###Markdown Upload the dataset to Domain node ###Code # We will upload only the first few rows # All these three columns are of `int` type # NOTE: casting this tensor as np.int32 is REALLY IMPORTANT. We need to create flags for this or something data_batch = ((np.array(list(data['Trade Value (US$)'])) / 100000)[0:10]).astype(np.int32) trade_partners = ((list(data['Partner'])))[0:10] entities = list() for i in range(len(trade_partners)): entities.append(Entity(name="Other Asia, nes")) # Upload a private dataset to the Domain object, as the root owner sampled_italy_dataset = sy.Tensor(data_batch) sampled_italy_dataset.public_shape = sampled_italy_dataset.shape sampled_italy_dataset = sampled_italy_dataset.private(0, 3, entities=entities[0]).tag("trade_flow") it.load_dataset( assets={"Italy Trade": sampled_italy_dataset}, name="Italy Trade Data - First few rows", description="""A collection of reports from iStat's statistics bureau about how much it thinks it imports and exports from other countries.""", ) it.datasets ###Output _____no_output_____ ###Markdown Create a Data Scientist User ###Code it.users.create( **{ "name": "Sheldon Cooper", "email": "[email protected]", "password": "bazinga", "budget":200 } ) ###Output _____no_output_____ ###Markdown Accept/Deny Requests to the Domain ###Code it.requests.pandas it.requests[-1].accept() ###Output _____no_output_____ ###Markdown Loading the dataset ###Code data = pd.read_csv("../datasets/it - feb 2021.csv")[0:100] data.head() ###Output /Users/andrewliamtrask/opt/anaconda3/envs/syft/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3169: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False. has_raised = await self.run_ast_nodes(code_ast.body, cell_name, ###Markdown Logging into the domain ###Code it = sy.login(email="[email protected]", password="changethis", port=8082) ###Output Connecting to http://localhost:8082... done! Logging into istat... done! ###Markdown Upload the dataset to Domain node ###Code # We will upload only the first few rows # All these three columns are of `int` type # NOTE: casting this tensor as np.int32 is REALLY IMPORTANT. We need to create flags for this or something data_batch = ((np.array(list(data['Trade Value (US$)'])) / 100000)[0:10]).astype(np.int32) trade_partners = ((list(data['Partner'])))[0:10] entities = list() for i in range(len(trade_partners)): entities.append(Entity(name="Other Asia, nes")) # Upload a private dataset to the Domain object, as the root owner sampled_italy_dataset = sy.Tensor(data_batch) sampled_italy_dataset.public_shape = sampled_italy_dataset.shape sampled_italy_dataset = sampled_italy_dataset.private(0, 3, entities=entities[0]).tag("trade_flow") it.load_dataset( assets={"Italy Trade": sampled_italy_dataset}, name="Italy Trade Data - First few rows", description="""A collection of reports from iStat's statistics bureau about how much it thinks it imports and exports from other countries.""", ) it.datasets ###Output _____no_output_____ ###Markdown Create a Data Scientist User ###Code it.users.create( **{ "name": "Sheldon Cooper", "email": "[email protected]", "password": "bazinga", "budget":200 } ) ###Output _____no_output_____ ###Markdown Accept/Deny Requests to the Domain ###Code it.requests.pandas it.requests[-1].accept() ###Output _____no_output_____ ###Markdown Loading the dataset ###Code data = pd.read_csv("../datasets/it - feb 2021.csv")[0:100] data.head() ###Output /Users/andrewliamtrask/opt/anaconda3/envs/syft/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3169: DtypeWarning: Columns (14) have mixed types.Specify dtype option on import or set low_memory=False. has_raised = await self.run_ast_nodes(code_ast.body, cell_name, ###Markdown Logging into the domain ###Code it = sy.login(email="[email protected]", password="changethis", port=8082) ###Output Connecting to http://localhost:8082... done! Logging into italy... done! ###Markdown Upload the dataset to Domain node ###Code # We will upload only the first few rows # All these three columns are of `int` type # NOTE: casting this tensor as np.int32 is REALLY IMPORTANT. We need to create flags for this or something data_batch = ((np.array(list(data['Trade Value (US$)'])) / 100000)[0:10]).astype(np.int32) trade_partners = ((list(data['Partner'])))[0:10] entities = list() for i in range(len(trade_partners)): entities.append(Entity(name="Other Asia, nes")) # Upload a private dataset to the Domain object, as the root owner sampled_italy_dataset = sy.Tensor(data_batch) sampled_italy_dataset.public_shape = sampled_italy_dataset.shape sampled_italy_dataset = sampled_italy_dataset.private(0, 3, entity=entities[0]).tag("trade_flow") it.load_dataset( assets={"Italy Trade": sampled_italy_dataset}, name="Italy Trade Data - First few rows", description="""A collection of reports from iStat's statistics bureau about how much it thinks it imports and exports from other countries.""", ) it.datasets ###Output _____no_output_____ ###Markdown Create a Data Scientist User ###Code it.users.create( **{ "name": "Sheldon Cooper", "email": "[email protected]", "password": "bazinga", "budget":200 } ) ###Output _____no_output_____ ###Markdown Accept/Deny Requests to the Domain ###Code it.requests.pandas it.requests[-1].accept() ###Output _____no_output_____
Task_3/hindi_hindi/.ipynb_checkpoints/Task-3_hindi_preprocess-checkpoint.ipynb
###Markdown Pre-process Hindi hate-speechThis notebook does all the pre-processing on the Hindi hate-speech data, including:- Removing user-tagging,- Removing stopwords,- Removing punctuations,- Removing urls,- Replacing numbers,- Forming phrases (disabled), Input: Train and test Hindi hatespeech datasets. Output: csv-files containing the ready-to-train and ready-to-test data Import libraries ###Code # Imports import re import string import json from datetime import datetime from collections import defaultdict, Counter import numpy as np import pandas as pd import matplotlib.pyplot as plt from tqdm import tqdm from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score device = 'cpu' import random random.seed(26) np.random.seed(62) ###Output _____no_output_____ ###Markdown Load data ###Code hindi_train_df = pd.read_csv('../../data/hindi_hatespeech.tsv', sep='\t') hindi_test_df = pd.read_csv('../../data/hasoc2019_hi_test_gold_2919.tsv', sep='\t') train_sentences = hindi_train_df['text'] test_sentences = hindi_test_df['text'] ###Output _____no_output_____ ###Markdown Clean texts ###Code # remove user taggings user_tag_pattern = re.compile(r'\@\w*') def remove_tagging(sentence): return re.sub(user_tag_pattern, ' ', sentence) # remove punctuations and urls http_re = re.compile('http://[^ ]*') https_re = re.compile('https://[^ ]*') punctuation = string.punctuation[:2] + string.punctuation[3:] translator = str.maketrans(punctuation, ' '*len(punctuation)) def remove_punc_and_urls(s): s = re.sub(http_re, ' ', s) s = re.sub(https_re, ' ', s) s = s.translate(translator) return s # substitute numbers # when there is a number in the string: # if that number is 0 or 1 or 2, then there is no change. # else, that number is substituted by a word describing how many digits it has. def substitute_number(x): x = x.group(0) if x in {'0', '1', '2'}: return x return '{}_digits_number'.format(len(x)) # stopwords Hindi stopwords = ['अंदर', 'अत', 'अदि', 'अप', 'अपना', 'अपनि', 'अपनी', 'अपने', 'अभि', 'अभी', 'आदि', 'आप', 'इंहिं', 'इंहें', 'इंहों', 'इतयादि', 'इत्यादि', 'इन', 'इनका', 'इन्हीं', 'इन्हें', 'इन्हों', 'इस', 'इसका', 'इसकि', 'इसकी', 'इसके', 'इसमें', 'इसि', 'इसी', 'इसे', 'उंहिं', 'उंहें', 'उंहों', 'उन', 'उनका', 'उनकि', 'उनकी', 'उनके', 'उनको', 'उन्हीं', 'उन्हें', 'उन्हों', 'उस', 'उसके', 'उसि', 'उसी', 'उसे', 'एक', 'एवं', 'एस', 'एसे', 'ऐसे', 'ओर', 'और', 'कइ', 'कई', 'कर', 'करता', 'करते', 'करना', 'करने', 'करें', 'कहते', 'कहा', 'का', 'काफि', 'काफ़ी', 'कि', 'किंहें', 'किंहों', 'कितना', 'किन्हें', 'किन्हों', 'किया', 'किर', 'किस', 'किसि', 'किसी', 'किसे', 'की', 'कुछ', 'कुल', 'के', 'को', 'कोइ', 'कोई', 'कोन', 'कोनसा', 'कौन', 'कौनसा', 'गया', 'घर', 'जब', 'जहाँ', 'जहां', 'जा', 'जिंहें', 'जिंहों', 'जितना', 'जिधर', 'जिन', 'जिन्हें', 'जिन्हों', 'जिस', 'जिसे', 'जीधर', 'जेसा', 'जेसे', 'जैसा', 'जैसे', 'जो', 'तक', 'तब', 'तरह', 'तिंहें', 'तिंहों', 'तिन', 'तिन्हें', 'तिन्हों', 'तिस', 'तिसे', 'तो', 'था', 'थि', 'थी', 'थे', 'दबारा', 'दवारा', 'दिया', 'दुसरा', 'दुसरे', 'दूसरे', 'दो', 'द्वारा', 'न', 'नहिं', 'नहीं', 'ना', 'निचे', 'निहायत', 'नीचे', 'ने', 'पर', 'पहले', 'पुरा', 'पूरा', 'पे', 'फिर', 'बनि', 'बनी', 'बहि', 'बही', 'बहुत', 'बाद', 'बाला', 'बिलकुल', 'भि', 'भितर', 'भी', 'भीतर', 'मगर', 'मानो', 'मे', 'में', 'यदि', 'यह', 'यहाँ', 'यहां', 'यहि', 'यही', 'या', 'यिह', 'ये', 'रखें', 'रवासा', 'रहा', 'रहे', 'ऱ्वासा', 'लिए', 'लिये', 'लेकिन', 'व', 'वगेरह', 'वरग', 'वर्ग', 'वह', 'वहाँ', 'वहां', 'वहिं', 'वहीं', 'वाले', 'वुह', 'वे', 'वग़ैरह', 'संग', 'सकता', 'सकते', 'सबसे', 'सभि', 'सभी', 'साथ', 'साबुत', 'साभ', 'सारा', 'से', 'सो', 'हि', 'ही', 'हुअ', 'हुआ', 'हुइ', 'हुई', 'हुए', 'हे', 'हें', 'है', 'हैं', 'हो', 'होता', 'होति', 'होती', 'होते', 'होना', 'होने'] def clean_texts(sentences): # tags sentences = [remove_tagging(sentence) for sentence in sentences] # lower case sentences = [sentence.lower() for sentence in sentences] # remove punctuations and urls sentences = [remove_punc_and_urls(sentence) for sentence in sentences] # substitute numbers sentences = [re.sub('\\b[0-9]+\\b', substitute_number, sentence) for sentence in sentences] # remove stopwords sentences = [[word for word in sentence.split() if word not in stopwords] for sentence in sentences] return sentences # perform cleaning train_sentences = clean_texts(train_sentences) train_texts = [' '.join(l) for l in train_sentences] hindi_train_df['text'] = train_texts test_sentences = clean_texts(test_sentences) test_texts = [' '.join(l) for l in test_sentences] hindi_test_df['text'] = test_texts # exclude empty sentences hindi_train_df = hindi_train_df[hindi_train_df['text'].str.len() != 0].reset_index(drop=True) hindi_test_df = hindi_test_df[hindi_test_df['text'].str.len() != 0].reset_index(drop=True) ###Output _____no_output_____ ###Markdown Form phrases ###Code # count 2-grams two_grams = [] for sentence in hindi_train_df['text']: words = sentence.split() two_grams.extend([(words[i], words[i+1]) for i in range(len(words)-1)]) gram_counter = Counter(two_grams) print('some most-common 2-grams:') print(gram_counter.most_common(5)) # plot 2-gram frequencies fig, ax = plt.subplots(figsize=(15, 8)) ax.hist(gram_counter.values(), bins=gram_counter.most_common(1)[0][1]) ax.set_title('2-grams counter histogram') ax.set_xlabel('2-grams counter') ax.set_ylabel('no. 2-grams') ax.set_yscale('log') # at first, we choose threshold = 10, i.e. 2-grams that appear at least 10 times are considered phrases # however, this doesn't increase accuracy. Maybe because the dataset is too small that statistic inferences are not sound. # So, we disable 2-grams by setting threshold to 100, i.e. no 2-grams are formed. two_grams_threshold_occurences = 100 phrases = [grams for grams in gram_counter if gram_counter[grams] >= two_grams_threshold_occurences] ###Output _____no_output_____ ###Markdown Vocab and Word int transformation ###Code def split_sentence(sentence): words = sentence.split() splitted = [] i = 0 while i < len(words): if (i < len(words) - 1 and (words[i], words[i+1]) in phrases): splitted.append('_'.join((words[i], words[i+1]))) i += 2 else: splitted.append(words[i]) i += 1 return splitted train_sentences = [split_sentence(sentence) for sentence in hindi_train_df['text']] test_sentences = [split_sentence(sentence) for sentence in hindi_test_df['text']] flattened_words = [word for sentence in train_sentences for word in sentence] V = list(set(flattened_words)) vocab_size = len(V) print(f'vocab_size: {vocab_size}') word_to_int = {} int_to_word = {} for i, word in enumerate(V): word_to_int[word] = i int_to_word[i] = word # save dicts for transformation word <-> int with open('save/hindi_word_to_int_dict.json', 'w') as f: json.dump(word_to_int, f) with open('save/hindi_int_to_word_dict.json', 'w') as f: json.dump(int_to_word, f) # save word-counter for sampling word_counter = Counter(flattened_words) with open('save/hindi_word_counter.json', 'w') as f: json.dump(word_counter, f) train_sentences = [[word_to_int[word] for word in sentence] for sentence in train_sentences] test_sentences = [[word_to_int[word] for word in sentence if word in word_to_int] for sentence in test_sentences] # exclude empty sentences train_texts = [' '.join([str(v) for v in l]) for l in train_sentences] hindi_train_df['text'] = train_texts hindi_train_df = hindi_train_df[hindi_train_df['text'].str.len() != 0].reset_index(drop=True) test_texts = [' '.join([str(v) for v in l]) for l in test_sentences] hindi_test_df['text'] = test_texts hindi_test_df = hindi_test_df[hindi_test_df['text'].str.len() != 0].reset_index(drop=True) hindi_train_df.rename(columns={'text':'sentence'}, inplace=True) hindi_test_df.rename(columns={'text':'sentence'}, inplace=True) ###Output _____no_output_____ ###Markdown Save output ###Code display(hindi_train_df.head()) display(hindi_test_df.head()) hindi_train_df.to_csv('save/hindi_train_preprocessed.csv', index=False) hindi_test_df.to_csv('save/hindi_test_preprocessed.csv', index=False) ###Output _____no_output_____
huanghaiguang_code/ex1-linear regression/1.linear_regreesion_v1.ipynb
###Markdown linear regreesion(线性回归)注意:python版本为3.6,安装TensorFlow的方法:pip install tensorflow ###Code import pandas as pd import seaborn as sns sns.set(context="notebook", style="whitegrid", palette="dark") import matplotlib.pyplot as plt import tensorflow as tf import numpy as np df = pd.read_csv('ex1data1.txt', names=['population', 'profit'])#读取数据并赋予列名 df.head()#看前五行 df.info() ###Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 97 entries, 0 to 96 Data columns (total 2 columns): population 97 non-null float64 profit 97 non-null float64 dtypes: float64(2) memory usage: 1.6 KB ###Markdown *** 看下原始数据 ###Code sns.lmplot('population', 'profit', df, size=6, fit_reg=False) plt.show() def get_X(df):#读取特征 # """ # use concat to add intersect feature to avoid side effect # not efficient for big dataset though # """ ones = pd.DataFrame({'ones': np.ones(len(df))})#ones是m行1列的dataframe data = pd.concat([ones, df], axis=1) # 合并数据,根据列合并 return data.iloc[:, :-1].as_matrix() # 这个操作返回 ndarray,不是矩阵 def get_y(df):#读取标签 # '''assume the last column is the target''' return np.array(df.iloc[:, -1])#df.iloc[:, -1]是指df的最后一列 def normalize_feature(df): # """Applies function along input axis(default 0) of DataFrame.""" return df.apply(lambda column: (column - column.mean()) / column.std())#特征缩放 ###Output _____no_output_____ ###Markdown 多变量的假设 h 表示为:\\[{{h}_{\theta }}\left( x \right)={{\theta }_{0}}+{{\theta }_{1}}{{x}_{1}}+{{\theta }_{2}}{{x}_{2}}+...+{{\theta }_{n}}{{x}_{n}}\\] 这个公式中有n+1个参数和n个变量,为了使得公式能够简化一些,引入${{x}_{0}}=1$,则公式转化为: 此时模型中的参数是一个n+1维的向量,任何一个训练实例也都是n+1维的向量,特征矩阵X的维度是 m*(n+1)。 因此公式可以简化为:${{h}_{\theta }}\left( x \right)={{\theta }^{T}}X$,其中上标T代表矩阵转置。 ###Code def linear_regression(X_data, y_data, alpha, epoch, optimizer=tf.train.GradientDescentOptimizer):# 这个函数是旧金山的一个大神Lucas Shen写的 # placeholder for graph input X = tf.placeholder(tf.float32, shape=X_data.shape) y = tf.placeholder(tf.float32, shape=y_data.shape) # construct the graph with tf.variable_scope('linear-regression'): W = tf.get_variable("weights", (X_data.shape[1], 1), initializer=tf.constant_initializer()) # n*1 y_pred = tf.matmul(X, W) # m*n @ n*1 -> m*1 loss = 1 / (2 * len(X_data)) * tf.matmul((y_pred - y), (y_pred - y), transpose_a=True) # (m*1).T @ m*1 = 1*1 opt = optimizer(learning_rate=alpha) opt_operation = opt.minimize(loss) # run the session with tf.Session() as sess: sess.run(tf.global_variables_initializer()) loss_data = [] for i in range(epoch): _, loss_val, W_val = sess.run([opt_operation, loss, W], feed_dict={X: X_data, y: y_data}) loss_data.append(loss_val[0, 0]) # because every loss_val is 1*1 ndarray if len(loss_data) > 1 and np.abs(loss_data[-1] - loss_data[-2]) < 10 ** -9: # early break when it's converged # print('Converged at epoch {}'.format(i)) break # clear the graph tf.reset_default_graph() return {'loss': loss_data, 'parameters': W_val} # just want to return in row vector format data = pd.read_csv('ex1data1.txt', names=['population', 'profit'])#读取数据,并赋予列名 data.head()#看下数据前5行 ###Output _____no_output_____ ###Markdown 计算代价函数$$J\left( \theta \right)=\frac{1}{2m}\sum\limits_{i=1}^{m}{{{\left( {{h}_{\theta }}\left( {{x}^{(i)}} \right)-{{y}^{(i)}} \right)}^{2}}}$$其中:\\[{{h}_{\theta }}\left( x \right)={{\theta }^{T}}X={{\theta }_{0}}{{x}_{0}}+{{\theta }_{1}}{{x}_{1}}+{{\theta }_{2}}{{x}_{2}}+...+{{\theta }_{n}}{{x}_{n}}\\] ###Code X = get_X(data) print(X.shape, type(X)) y = get_y(data) print(y.shape, type(y)) #看下数据维度 theta = np.zeros(X.shape[1])#X.shape[1]=2,代表特征数n def lr_cost(theta, X, y): # """ # X: R(m*n), m 样本数, n 特征数 # y: R(m) # theta : R(n), 线性回归的参数 # """ m = X.shape[0]#m为样本数 inner = X @ theta - y # R(m*1),X @ theta等价于X.dot(theta) # 1*m @ m*1 = 1*1 in matrix multiplication # but you know numpy didn't do transpose in 1d array, so here is just a # vector inner product to itselves square_sum = inner.T @ inner cost = square_sum / (2 * m) return cost lr_cost(theta, X, y)#返回theta的值 ###Output _____no_output_____ ###Markdown batch gradient decent(批量梯度下降)$${{\theta }_{j}}:={{\theta }_{j}}-\alpha \frac{\partial }{\partial {{\theta }_{j}}}J\left( \theta \right)$$ ###Code def gradient(theta, X, y): m = X.shape[0] inner = X.T @ (X @ theta - y) # (m,n).T @ (m, 1) -> (n, 1),X @ theta等价于X.dot(theta) return inner / m def batch_gradient_decent(theta, X, y, epoch, alpha=0.01): # 拟合线性回归,返回参数和代价 # epoch: 批处理的轮数 # """ cost_data = [lr_cost(theta, X, y)] _theta = theta.copy() # 拷贝一份,不和原来的theta混淆 for _ in range(epoch): _theta = _theta - alpha * gradient(_theta, X, y) cost_data.append(lr_cost(_theta, X, y)) return _theta, cost_data #批量梯度下降函数 epoch = 500 final_theta, cost_data = batch_gradient_decent(theta, X, y, epoch) final_theta #最终的theta cost_data # 看下代价数据 # 计算最终的代价 lr_cost(final_theta, X, y) ###Output _____no_output_____ ###Markdown visualize cost data(代价数据可视化) ###Code ax = sns.tsplot(cost_data, time=np.arange(epoch+1)) ax.set_xlabel('epoch') ax.set_ylabel('cost') plt.show() #可以看到从第二轮代价数据变换很大,接下来平稳了 b = final_theta[0] # intercept,Y轴上的截距 m = final_theta[1] # slope,斜率 plt.scatter(data.population, data.profit, label="Training data") plt.plot(data.population, data.population*m + b, label="Prediction") plt.legend(loc=2) plt.show() ###Output _____no_output_____ ###Markdown 3- 选修章节 ###Code raw_data = pd.read_csv('ex1data2.txt', names=['square', 'bedrooms', 'price']) raw_data.head() ###Output _____no_output_____ ###Markdown 标准化数据最简单的方法是令: 其中 是平均值,sn 是标准差。 ###Code def normalize_feature(df): # """Applies function along input axis(default 0) of DataFrame.""" return df.apply(lambda column: (column - column.mean()) / column.std()) data = normalize_feature(raw_data) data.head() ###Output _____no_output_____ ###Markdown 2. multi-var batch gradient decent(多变量批量梯度下降) ###Code X = get_X(data) print(X.shape, type(X)) y = get_y(data) print(y.shape, type(y))#看下数据的维度和类型 alpha = 0.01#学习率 theta = np.zeros(X.shape[1])#X.shape[1]:特征数n epoch = 500#轮数 final_theta, cost_data = batch_gradient_decent(theta, X, y, epoch, alpha=alpha) sns.tsplot(time=np.arange(len(cost_data)), data = cost_data) plt.xlabel('epoch', fontsize=18) plt.ylabel('cost', fontsize=18) plt.show() final_theta ###Output _____no_output_____ ###Markdown 3. learning rate(学习率) ###Code base = np.logspace(-1, -5, num=4) candidate = np.sort(np.concatenate((base, base*3))) print(candidate) epoch=50 fig, ax = plt.subplots(figsize=(16, 9)) for alpha in candidate: _, cost_data = batch_gradient_decent(theta, X, y, epoch, alpha=alpha) ax.plot(np.arange(epoch+1), cost_data, label=alpha) ax.set_xlabel('epoch', fontsize=18) ax.set_ylabel('cost', fontsize=18) ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) ax.set_title('learning rate', fontsize=18) plt.show() ###Output _____no_output_____ ###Markdown 4. normal equation(正规方程)正规方程是通过求解下面的方程来找出使得代价函数最小的参数的:$\frac{\partial }{\partial {{\theta }_{j}}}J\left( {{\theta }_{j}} \right)=0$ 。 假设我们的训练集特征矩阵为 X(包含了${{x}_{0}}=1$)并且我们的训练集结果为向量 y,则利用正规方程解出向量 $\theta ={{\left( {{X}^{T}}X \right)}^{-1}}{{X}^{T}}y$ 。上标T代表矩阵转置,上标-1 代表矩阵的逆。设矩阵$A={{X}^{T}}X$,则:${{\left( {{X}^{T}}X \right)}^{-1}}={{A}^{-1}}$梯度下降与正规方程的比较:梯度下降:需要选择学习率α,需要多次迭代,当特征数量n大时也能较好适用,适用于各种类型的模型 正规方程:不需要选择学习率α,一次计算得出,需要计算${{\left( {{X}^{T}}X \right)}^{-1}}$,如果特征数量n较大则运算代价大,因为矩阵逆的计算时间复杂度为O(n3),通常来说当n小于10000 时还是可以接受的,只适用于线性模型,不适合逻辑回归模型等其他模型 ###Code # 正规方程 def normalEqn(X, y): theta = np.linalg.inv(X.T@X)@X.T@y#X.T@X等价于X.T.dot(X) return theta final_theta2=normalEqn(X, y)#感觉和批量梯度下降的theta的值有点差距 final_theta2 ###Output _____no_output_____ ###Markdown run the tensorflow graph over several optimizer ###Code X_data = get_X(data) print(X_data.shape, type(X_data)) y_data = get_y(data).reshape(len(X_data), 1) # special treatment for tensorflow input data print(y_data.shape, type(y_data)) epoch = 2000 alpha = 0.01 optimizer_dict={'GD': tf.train.GradientDescentOptimizer, 'Adagrad': tf.train.AdagradOptimizer, 'Adam': tf.train.AdamOptimizer, 'Ftrl': tf.train.FtrlOptimizer, 'RMS': tf.train.RMSPropOptimizer } results = [] for name in optimizer_dict: res = linear_regression(X_data, y_data, alpha, epoch, optimizer=optimizer_dict[name]) res['name'] = name results.append(res) ###Output _____no_output_____ ###Markdown 画图 ###Code fig, ax = plt.subplots(figsize=(16, 9)) for res in results: loss_data = res['loss'] # print('for optimizer {}'.format(res['name'])) # print('final parameters\n', res['parameters']) # print('final loss={}\n'.format(loss_data[-1])) ax.plot(np.arange(len(loss_data)), loss_data, label=res['name']) ax.set_xlabel('epoch', fontsize=18) ax.set_ylabel('cost', fontsize=18) ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) ax.set_title('different optimizer', fontsize=18) plt.show() ###Output _____no_output_____
ANN/ANN.ipynb
###Markdown Data Pre Processing ###Code X = df.iloc[:, 3:-1].values y = df.iloc[:, -1].values X[:5] X.shape from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder ct = ColumnTransformer([("encoder", OneHotEncoder(), [1, 2])], remainder = "passthrough") X = ct.fit_transform(X) X.shape X[:5] from sklearn.model_selection import train_test_split X= X[:, 1:] # to remove the dummy variable trap X.shape X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) X_train.shape y_train.shape from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) X_train[:5] ###Output _____no_output_____ ###Markdown Making the ANN Model ###Code from keras.models import Sequential from keras.layers import Dense model = Sequential() model.add(Dense(100, input_dim = 12, activation = "relu")) model.add(Dense(500, activation = "relu")) model.add(Dense(1, activation = "sigmoid")) model.compile(optimizer = "adam", loss = "binary_crossentropy", metrics = ["accuracy"]) """Adam is the stochastic gradient descent optimizer that will be used to update the weights""" model.fit(X_train, y_train, batch_size = 10, epochs = 50) y_pred = model.predict(X_test) y_pred = y_pred > 0.5 y_pred[:5] from sklearn.metrics import confusion_matrix import seaborn as sns cm = confusion_matrix(y_test, y_pred) cm ###Output _____no_output_____ ###Markdown Artificial Neural Network: ###Code from google.colab import drive drive.mount('/content/drive') # importing packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as stats from sklearn.preprocessing import MinMaxScaler, StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix, accuracy_score, classification_report # Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout import warnings warnings.filterwarnings('ignore') # reading the dataset df = pd.read_csv("/content/drive/MyDrive/Deep Learning/Churn_Modelling.csv") df.head() # check if there is any null value df.isnull().sum().sum() ###Output _____no_output_____ ###Markdown Data preprocessing: ###Code # checking how many unique value in that columnn for replacing df.Geography.unique() # replacing categorical value with numerical values df['Geography'] = df['Geography'].replace(['France', 'Spain', 'Germany'], [0,1,2]) df['Gender'] = df['Gender'].replace(['Male', 'Female'], [0, 1]) # drop unwanted columns df = df.drop(['RowNumber', 'CustomerId', 'Surname'], axis=1) df.Exited.value_counts() df.head() X = df.drop(columns='Exited') y = df['Exited'] # split dataset into train and test dataset X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) ###Output _____no_output_____ ###Markdown Feature scaling: ###Code scaler = MinMaxScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.fit_transform(X_test) ###Output _____no_output_____ ###Markdown Initialising the ANN: ###Code # initialising the model model = Sequential() # Adding the input layer (first hidden layer) model.add(Dense(units=10, kernel_initializer='he_uniform', activation='relu', input_dim = 10)) # Adding the another input layer (second hidden layer) model.add(Dense(units=20, kernel_initializer='he_uniform', activation='relu')) # for 2nd hidden layer dont use input_dim # Adding the another input layer (third hidden layer) model.add(Dense(units=10, kernel_initializer='he_uniform', activation='relu')) # for 3rd hidden layer dont use input_dim # Adding the output layer model.add(Dense(units = 1, kernel_initializer = 'glorot_uniform', activation = 'sigmoid')) # compile the ANN model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Fitting the ANN to the Training set Model = model.fit(X_train, y_train, validation_split=0.1, epochs=10, batch_size=100, ) # list all data in history print(Model.history.keys()) # summarize history for accuracy plt.plot(Model.history['accuracy']) plt.plot(Model.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.show() # summarize history for loss plt.plot(Model.history['loss']) plt.plot(Model.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.show() # fitting the test dataset y_pred = model.predict(X_test) y_pred = y_pred > 0.5 # confusion matrix print(f"Confusion matrix:\n {confusion_matrix(y_pred, y_test)}") # classification report print(f"Classification report:\n {classification_report(y_pred, y_test)}") ###Output Confusion matrix: [[1563 320] [ 32 85]] Classification report: precision recall f1-score support False 0.98 0.83 0.90 1883 True 0.21 0.73 0.33 117 accuracy 0.82 2000 macro avg 0.59 0.78 0.61 2000 weighted avg 0.93 0.82 0.87 2000 ###Markdown HyperParameter tunning: ###Code from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import GridSearchCV from keras.models import Sequential from keras.layers import Dense, Activation, Embedding, Flatten, LeakyReLU, BatchNormalization, Dropout from keras.activations import relu, sigmoid def create_model(layer, activation, kernel): model = Sequential() for i, nodes in enumerate(layer): if i == 0: model.add(Dense(nodes, input_dim=X_train.shape[1])) model.add(Activation(activation)) else: model.add(Dense(nodes), kernel_initializer=kernel) model.add(Activation(activation)) model.add(Dense(units=1, activation='sigmoid', kernel_initializer="glorot_uniform")) # this one is output layer so we use sigmoid af model.compile(optimizer='adam', loss="binary_crossentropy", metrics=['accuracy']) return model # creating an object for previous function model = KerasClassifier(build_fn=create_model) layers = [[20], [40, 20], [40, 20, 10]] activations = ['relu', 'sigmoid'] kernel = [['he_uniform', 'he_normal'], ['glorot_uniform', 'glorot_normal']] para_grid = dict(layer=layers, activation=activations, kernel=kernel) grid = GridSearchCV(model, para_grid, cv=5) # fitting dataset with created model grid.fit(X_train, y_train, validation_split=0.3, validation_data=(X_test, y_test), epochs=10) print(grid.best_params_, grid.best_score_) ###Output {'activation': 'relu', 'kernel': ['he_uniform', 'he_normal'], 'layer': [20]} 0.8108749985694885 ###Markdown HyperParameter Tunnig using KerasTunner: ###Code # !pip install keras_tuner from tensorflow import keras from keras import Sequential from keras.layers import Dense, Activation from keras_tuner import RandomSearch def create_model(hp): model = Sequential() for i in range(hp.Int("num_layer", 2, 20)): model.add(Dense(units= hp.Int("units_" + str(i), min_value=32, max_value=512, step=32), activation='ELU', kernel_initializer='he_uniform', input_dim=X_train.shape[1])) model.add(Dense(units=1, activation="sigmoid")) model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', [1e-2, 1e-3, 1e-4])), loss='binary_crossentropy', metrics=['accuracy']) return model tuner = RandomSearch(hypermodel=create_model, objective="val_accuracy", max_trials=5, executions_per_trial=3, directory='Log', project_name='HyperTuning') tuner.search(X_train, y_train, epochs=10, validation_split=0.3) model = tuner.get_best_models(num_models=1)[0] model.summary() Model = model.fit(X_train, y_train, epochs=10, validation_split=0.3, validation_data=(X_test, y_test)) print(Model.history.keys()) # summarize history for accuracy plt.plot(Model.history['accuracy']) plt.plot(Model.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.show() # summarize history for loss plt.plot(Model.history['loss']) plt.plot(Model.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.show() # fitting the test dataset y_pred = model.predict(X_test) y_pred = y_pred > 0.5 # confusion matrix print(f"Confusion matrix:\n {confusion_matrix(y_pred, y_test)}") # classification report print(f"Classification report:\n {classification_report(y_pred, y_test)}") ###Output Confusion matrix: [[1533 224] [ 62 181]] Classification report: precision recall f1-score support False 0.96 0.87 0.91 1757 True 0.45 0.74 0.56 243 accuracy 0.86 2000 macro avg 0.70 0.81 0.74 2000 weighted avg 0.90 0.86 0.87 2000 ###Markdown Sample Code from the documentation ###Code from tensorflow import keras import numpy as np (x, y), (x_test, y_test) = keras.datasets.mnist.load_data() x_train = x[:-10000] x_val = x[-10000:] y_train = y[:-10000] y_val = y[-10000:] x_train = np.expand_dims(x_train, -1).astype("float32") / 255.0 x_val = np.expand_dims(x_val, -1).astype("float32") / 255.0 x_test = np.expand_dims(x_test, -1).astype("float32") / 255.0 num_classes = 10 y_train = keras.utils.to_categorical(y_train, num_classes) y_val = keras.utils.to_categorical(y_val, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) from tensorflow.keras import layers from keras_tuner import RandomSearch def build_model(hp): model = keras.Sequential() model.add(layers.Flatten()) model.add( layers.Dense( units=hp.Int("units", min_value=32, max_value=512, step=32), activation="relu", ) ) model.add(layers.Dense(10, activation="softmax")) model.compile( optimizer=keras.optimizers.Adam( hp.Choice("learning_rate", values=[1e-2, 1e-3, 1e-4]) ), loss="categorical_crossentropy", metrics=["accuracy"], ) return model tuner = RandomSearch( build_model, objective="val_accuracy", max_trials=3, executions_per_trial=2, overwrite=True, directory="my_dir", project_name="helloworld", ) tuner.search_space_summary() tuner.search(x_train, y_train, epochs=2, validation_data=(x_val, y_val)) model = tuner.get_best_models(num_models=1)[0] Model = model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val)) Model.history.keys() # summarize history for accuracy plt.plot(Model.history['accuracy']) plt.plot(Model.history['val_accuracy']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='lower right') plt.show() # summarize history for loss plt.plot(Model.history['loss']) plt.plot(Model.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper right') plt.show() ###Output _____no_output_____
book/tools-for-mathematics/03-calculus/tutorial/.main.md.bcp.ipynb
###Markdown TutorialWe will solve the following problem using a computer to assist with the technical aspects:```{admonition} ProblemConsider the function $f(x)= \frac{24 x \left(a - 4 x\right) + 2 \left(a - 8 x\right) \left(b - 4 x\right)}{\left(b - 4 x\right)^{4}}$1. Given that $\frac{df}{dx}|_{x=0}=0$, $\frac{d^2f}{dx^2}|_{x=0}=-1$ and that $b>0$ find the values of $a$ and $b$.2. For the specific values of $a$ and $b$ find: 1. $\lim_{x\to 0}f(x)$; 2. $\lim_{x\to \infty}f(x)$; 3. $\int f(x) dx$; 4. $\int_{5}^{20} f(x) dx$.```Sympy is once again the library we will use for this.We will start by creating a variable `expression` that has the value of the expression of $f(x)$: ###Code import sympy as sym x = sym.Symbol("x") a = sym.Symbol("a") b = sym.Symbol("b") expression = (24 * x * (a - 4 * x) + 2 * (a - 8 * x) * (b - 4 * x)) / ((b - 4 * x) ** 4) expression ###Output _____no_output_____ ###Markdown now we can will use `sympy.diff` to calculate the derivative. This tool takes two inputs:- the first is the expression we are differentiating. Essentially this is the numerator of $\frac{df}{dx}$.- the first is the variable we are differentiating for. Essentially this is the denominator of $\frac{df}{dx}$.```{attention}We have imported `import sympy as sym` so we are going to write `sym.diff`:``` ###Code derivative = sym.diff(expression, x) derivative ###Output _____no_output_____ ###Markdown Let us factorise that to make it slightly clearer: ###Code sym.factor(derivative) ###Output _____no_output_____ ###Markdown We will now create the first equation, which is obtained by substituting $x=0$in to the value of the derivative and equating that to $0$: ###Code first_equation = sym.Eq(derivative.subs({x: 0}), 0) first_equation ###Output _____no_output_____ ###Markdown We will factor that equation: ###Code sym.factor(first_equation) ###Output _____no_output_____ ###Markdown Now we are going to create the second equation, substituting $x=0$ in to thevalue of the second derivative. We calculate the second derivative by passing athird (optional) input to `sym.diff`: ###Code second_derivative = sym.diff(expression, x, 2) second_derivative ###Output _____no_output_____ ###Markdown We equate this expression to $-1$: ###Code second_equation = sym.Eq(second_derivative.subs({x: 0}), -1) second_equation ###Output _____no_output_____ ###Markdown Now to solve the first equation to obtain a value for $a$: ###Code sym.solveset(first_equation, a) ###Output _____no_output_____ ###Markdown Now to substitute that value for $a$ and solve the second equation for $b$: ###Code second_equation = second_equation.subs({a: b / 3}) second_equation sym.solveset(second_equation, b) ###Output _____no_output_____ ###Markdown Recalling the question we know that $b>0$ thus: $b = 2\sqrt{2}\sqrt[4]{3}$ and$a=\frac{2\sqrt{2}\sqrt[4]{3}}{3}$.We will substitute these values back and finish the question: ###Code expression = expression.subs( {a: 2 * sym.sqrt(2) * sym.root(3, 4) / 3, b: 2 * sym.sqrt(2) * sym.root(3, 4)} ) expression ###Output _____no_output_____ ###Markdown ```{attention}We are using the `sym.root` command for the generic $n$th root.```We can confirm our findings: ###Code sym.diff(expression, x).subs({x: 0}) sym.diff(expression, x, 2).subs({x: 0}) ###Output _____no_output_____ ###Markdown Now we will calculate the limits using `sym.limit`, this takes 3 inputs:- The expression we are taking the limit of.- The variable that is changing.- The value that the variable is tending towards. ###Code sym.limit(expression, x, 0) sym.limit(expression, x, sym.oo) ###Output _____no_output_____ ###Markdown Now we are going to calculate the **indefinite** integral using`sympy.integrate`. This tool takes 2 inputs as:- the first is the expression we're integrating. This is the $f$ in $\int_a^b f dx$.- the second is the remaining information needed to calculate the integral: $x$. ###Code sym.factor(sym.integrate(expression, x)) ###Output _____no_output_____ ###Markdown If we want to calculate a **definite** integral then instead of passing thesingle variable we pass a tuple which contains the variable as well as thebounds of integration: ###Code sym.factor(sym.integrate(expression, (x, 5, 20))) ###Output _____no_output_____ ###Markdown TutorialWe will solve the following problem using a computer to assist with the technical aspects:```{admonition} ProblemConsider the function $f(x)= \frac{24 x \left(a - 4 x\right) + 2 \left(a - 8 x\right) \left(b - 4 x\right)}{\left(b - 4 x\right)^{4}}$1. Given that $\frac{df}{dx}|_{x=0}=0$, $\frac{d^2f}{dx^2}|_{x=0}=-1$ and that $b>0$ find the values of $a$ and $b$.2. For the specific values of $a$ and $b$ find: 1. $\lim_{x\to 0}f(x)$; 2. $\lim_{x\to \infty}f(x)$; 3. $\int f(x) dx$; 4. $\int_{5}^{20} f(x) dx$.```Sympy is once again the library we will use for this.We will start by creating a variable `expression` that has the value of the expression of $f(x)$: ###Code import sympy as sym x = sym.Symbol("x") a = sym.Symbol("a") b = sym.Symbol("b") expression = (24 * x * (a - 4 * x) + 2 * (a - 8 * x) * (b - 4 * x)) / ((b - 4 * x) ** 4) expression ###Output _____no_output_____ ###Markdown now we can will use `sympy.diff` to calculate the derivative. This tool takes two inputs:- the first is the expression we are differentiating. Essentially this is the numerator of $\frac{df}{dx}$.- the first is the variable we are differentiating for. Essentially this is the denominator of $\frac{df}{dx}$.```{attention}We have imported `import sympy as sym` so we are going to write `sym.diff`:``` ###Code derivative = sym.diff(expression, x) derivative ###Output _____no_output_____ ###Markdown Let us factorise that to make it slightly clearer: ###Code sym.factor(derivative) ###Output _____no_output_____ ###Markdown We will now create the first equation, which is obtained by substituting $x=0$in to the value of the derivative and equating that to $0$: ###Code first_equation = sym.Eq(derivative.subs({x: 0}), 0) first_equation ###Output _____no_output_____ ###Markdown We will factor that equation: ###Code sym.factor(first_equation) ###Output _____no_output_____ ###Markdown Now we are going to create the second equation, substituting $x=0$ in to thevalue of the second derivative. We calculate the second derivative by passing athird (optional) input to `sym.diff`: ###Code second_derivative = sym.diff(expression, x, 2) second_derivative ###Output _____no_output_____ ###Markdown We equate this expression to $-1$: ###Code second_equation = sym.Eq(second_derivative.subs({x: 0}), -1) second_equation ###Output _____no_output_____ ###Markdown Now to solve the first equation to obtain a value for $a$: ###Code sym.solveset(first_equation, a) ###Output _____no_output_____ ###Markdown Now to substitute that value for $a$ and solve the second equation for $b$: ###Code second_equation = second_equation.subs({a: b / 3}) second_equation sym.solveset(second_equation, b) ###Output _____no_output_____ ###Markdown Recalling the question we know that $b>0$ thus: $b = 2\sqrt{2}\sqrt[4]{3}$ and$a=\frac{2\sqrt{2}\sqrt[4]{3}}{3}$.We will substitute these values back and finish the question: ###Code expression = expression.subs( {a: 2 * sym.sqrt(2) * sym.root(3, 4) / 3, b: 2 * sym.sqrt(2) * sym.root(3, 4)} ) expression ###Output _____no_output_____ ###Markdown ```{attention}We are using the `sym.root` command for the generic $n$th root.```We can confirm our findings: ###Code sym.diff(expression, x).subs({x: 0}) sym.diff(expression, x, 2).subs({x: 0}) ###Output _____no_output_____ ###Markdown Now we will calculate the limits using `sym.limit`, this takes 3 inputs:- The expression we are taking the limit of.- The variable that is changing.- The value that the variable is tending towards. ###Code sym.limit(expression, x, 0) sym.limit(expression, x, sym.oo) ###Output _____no_output_____ ###Markdown Now we are going to calculate the **indefinite** integral using`sympy.integrate`. This tool takes 2 inputs as:- the first is the expression we're integrating. This is the $f$ in $\int_a^b f dx$.- the second is the remaining information needed to calculate the integral: $x$. ###Code sym.factor(sym.integrate(expression, x)) ###Output _____no_output_____ ###Markdown If we want to calculate a **definite** integral then instead of passing thesingle variable we pass a tuple which contains the variable as well as thebounds of integration: ###Code sym.factor(sym.integrate(expression, (x, 5, 20))) ###Output _____no_output_____
WF_inpaint/WF_inpaint_unet_train.ipynb
###Markdown Wavefront set inpainting In this notebook we are implementing a Wavefront set inpainting algorithm based on a hallucination network ###Code %matplotlib inline import os os.environ["CUDA_VISIBLE_DEVICES"]="0" # Import the needed modules from data.data_factory import generate_data_WFinpaint, DataGenerator_WFinpaint from ellipse.ellipseWF_factory import plot_WF import matplotlib.pyplot as plt import numpy.random as rnd import numpy as np import odl import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Data generator ###Code batch_size = 1 size = 256 nClasses = 180 lowd = 40 y_arr, x_true_arr = generate_data_WFinpaint(batch_size, size, nClasses, lowd) plt.figure(figsize=(6,6)) plt.axis('off') plot_WF(y_arr[0,:,:,0]) plt.figure(figsize=(6,6)) plt.axis('off') plot_WF(x_true_arr[0,:,:,0]) ###Output _____no_output_____ ###Markdown Load the model ###Code # Tensorflow and seed seed_value = 0 import random random.seed(seed_value) import tensorflow as tf tf.set_random_seed(seed_value) # Importing relevant keras modules from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger from tensorflow.keras.models import load_model from shared.shared import create_increasing_dir import pickle # Import model and custom losses from models.unet import UNet from models.losses import CUSTOM_OBJECTS # Parameters for the training learning_rate = 1e-3 loss = 'mae' batch_size = 50 epoches = 10000 pretrained = 0 # path_to_model_dir = './models/unets_WFinpaint/training_0' # Data generator size = 256 nClasses = 180 lowd = 40 train_gen = DataGenerator_WFinpaint(batch_size, size, nClasses, lowd) val_gen = DataGenerator_WFinpaint(batch_size, size, nClasses, lowd) if pretrained==0: # Create a fresh model print("Create a fresh model") unet = UNet() model = unet.create_model( img_shape = (size, size, 1) , loss = loss, learning_rate = learning_rate) path_to_training = create_increasing_dir('./models/unets_WFinpaint', 'training') print("Save training in {}".format(path_to_training)) path_to_model_dir = path_to_training else: print("Use trained model as initialization:") print(path_to_model_dir+"/weights.hdf5") model = load_model(path_to_model_dir+"/weights.hdf5", custom_objects=CUSTOM_OBJECTS) path_to_training = path_to_model_dir # Callbacks for saving model context = { "loss": loss, "batch_size": batch_size, "learning_rate": learning_rate, "path_to_model_dir": path_to_model_dir, } path_to_context = path_to_training+'/context.log' with open(path_to_context, 'wb') as dict_items_save: pickle.dump(context, dict_items_save) print("Save training context to {}".format(path_to_context)) # Save architecture model_json = model.to_json() path_to_architecture = path_to_training + "/model.json" with open(path_to_architecture, "w") as json_file: json_file.write(model_json) print("Save model architecture to {}".format(path_to_architecture)) # Checkpoint for trained model checkpoint = ModelCheckpoint( path_to_training+'/weights.hdf5', monitor='val_loss', verbose=1, save_best_only=True) csv_logger = CSVLogger(path_to_training+'/training.log') callbacks_list = [checkpoint, csv_logger] model.fit_generator(train_gen,epochs=epoches, steps_per_epoch=5600 // batch_size, callbacks=callbacks_list, validation_data=val_gen, validation_steps= 2000// batch_size) ###Output Epoch 1/10000
assignments/assignment_2/Assignment_2_Prediction_sprint_starter.ipynb
###Markdown Predicting Regions and the Nomad Score In the first assignment you were working with the city and trips data from Nomadlist, exploring city-characteristics, latent grouping and popularity of resulting clusters over time.In this assignment you are going to work again with the city data, however now you will be exploring supervised learning to predict the Region (aka. continent given city-characteristics) and the Nomad Score.- The first is a classification problem like in the wine-presentation in class (there are a number of descrete classes and you need to predict which one it is)- The second is a regression problem where you will have to estimate a continuous value.Data has been preprocessed for you and you don't have to worry about that. We also imputed missing values and handled outliers.However, you will have to perform feature scaling (normalization, standardization).**While the outputs are preserved, many parts of the starter code have been replaced with \*\*\*\* that you have to complete **You tasks are (Aside from completing this notebook)- Add min 2 further algorithms (2 for classification, 2 for regression)- Can you increase the accuracy on the test-set (classification to aroung 90% and regression to R2 ~ 0.55)- Explain what you observe and what that means. - Interpret the results. - You may add visualisations if you find it helpful. ###Code # Loading necessary libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # Loading the data (we will now load the Data directly from the web) # If you want you can still use the usual way, downloading the data first cities_url = 'https://github.com/SDS-AAU/M1-2018/raw/master/assignments/assignment_2/cities_predict.csv' cities_predict = pd.read_csv(cities_url) # Checking the variables cities_predict.info() # Exploring the data (a bit) cities_predict.describe() ###Output _____no_output_____ ###Markdown As you can see, all variables but "region", "country" and "place_slug" are already nummerical floats.Remember that you can select the these using iloc indexer**To keep thigns easy and avoid confusion: Please do not use the Nomad Score as an input for any models**Also, the data is on very different scales (see means and std differences), and thus should be scaled. ###Code # We extract all nummerical values only_nummerical = cities_predict.iloc[:,:28] # We extract the regions column (that we want to predict) region = cities_predict.iloc[:,29] # We extract the nomad_score column (that we want to predict) nomad_score = cities_predict.iloc[:,28] print('### Nummerical values ###') print(only_nummerical.head(3)) print('### Regions ###') print(region.head(3)) print('### Nomad Score ###') print(nomad_score.head(3)) ###Output ### Nummerical values ### 1br_studio_rent_in_center adult_nightlife air_quality_(year-round) \ 0 492.0 4.0 42.0 1 223.0 3.0 19.0 2 503.0 2.0 68.0 airbnb_(monthly) cashless_society coca-cola coffee cost_of_living \ 0 946.0 1.000000 0.70 1.40 3.0 1 976.0 1.000000 0.63 1.11 3.0 2 1312.0 1.616589 0.54 0.70 3.0 cost_of_living_for_expat cost_of_living_for_local ... nightlife \ 0 961.0 626.0 ... 3.0 1 697.0 349.0 ... 3.0 2 1064.0 631.0 ... 2.0 peace quality_of_life racial_tolerance religious_government \ 0 2.0 3.0 1.000000 0.0 1 2.0 3.0 1.935908 0.0 2 1.0 3.0 1.277287 1.0 safe_tap_water safety startup_score traffic_safety walkability 0 0.0 1.0 3.0 4.0 4.0 1 0.0 2.0 3.0 4.0 4.0 2 0.0 3.0 2.0 1.0 1.0 [3 rows x 28 columns] ### Regions ### 0 Latin America 1 Latin America 2 Middle East Name: region, dtype: object ### Nomad Score ### 0 4.03 1 4.51 2 4.45 Name: nomad_score, dtype: float64 ###Markdown Since you are not expected to use the Nomad Score for Region-prediction, we can use the same inputs for the classification and the regression exercise below. Therefore, we can feature-scale it already at this point. Here, for the sake of simplicity we standardize all variables but you may experiment with leaving out dummy variables (0/1). ###Code # We use the standard scaler here but you can experiment with other approaches to that from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaled_inputs = scaler.fit_transform(*****) ###Output _____no_output_____ ###Markdown Classification of regionsIn the following you will be using various classification models to predict the region for each city given only the nummerical variables in cities_predict ###Code X = scaled_inputs # Encoding categorical data from sklearn.preprocessing import LabelEncoder # Define the label encoder to transform region names to numbers labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(*****) # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(*****, y, test_size = 0.2, random_state = 21) # We first import and train a Logistic Regression from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() classifier.fit(*****, y_train) # Applying k-Fold Cross Validation from sklearn.model_selection import cross_val_score accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv = 10) print(accuracies.mean()) print(accuracies.std()) # Check the accuracy of the model classifier.score(X_test, y_test) # Predicting the test set results from the test-set inputs y_pred = classifier.predict(*****) # Transforming nummerical labels back to Region-names true_regions = labelencoder_y.inverse_transform(y_test) predicted_regions = labelencoder_y.inverse_transform(*****) # Creating a pandas DataFrame and cross-tabulation df = pd.DataFrame({'true_regions': true_regions, 'predicted_regions': predicted_regions}) pd.crosstab(*****, df.predicted_regions) ###Output _____no_output_____ ###Markdown *Predicting* the Nomad ScoreIn the following we will try to predict the nomad score (a continuous variable) ###Code # Our inputs are still the same X = ***** # Our output is the Nomad Score y = nomad_score # Splitting the dataset into the Training set and Test set (since we have a new output variable) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, *****, test_size = 0.2, random_state = 21) # Let's fit a simple linear regression model from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(*****, *****) ###Output _____no_output_____ ###Markdown k-fold cross-validation is different with regression problemsoften you will see people using the r2_score (the more the better) and the RMSERoot Mean Square Error (the lower the better)For a regression probme sklearn will perform k-fold cross validation and return the predicted values (for each slice)Using those and the real values (y_train) you can calculate r2_scores and RMSE ###Code from sklearn.model_selection import cross_val_predict from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error predictions = cross_val_predict(estimator = regressor, X = X_train, y = y_train, cv = 10) # RMSE (np.sqrt stands for quare-root) print(np.sqrt(mean_squared_error(y_train, predictions))) # r2_scores print(r2_score(y_train, predictions)) # Scoring the regressor (r2-score) on the test-set regressor.score(X_test, y_test) # Predicting from the held back X_test y_pred = regressor.predict(*****) sns.regplot(y_test, y_pred) ###Output _____no_output_____
networkx_and_protein_interactions.ipynb
###Markdown Networkx and protein:protein interaction data Ribosomal protein interactions in NetworkxThis notebook will be using data from a paper on protein networks in the eukaryotic ribosome. The original structure for this is pdb code 4v88 which has both the large (L) and small (S) subunits. The ribosome is basically an RNA machine for making proteins using the amino-acids provided by tRNAs. Protein decorate and stabilize the outside of the RNA - they also make contact with each other - very often through elongated projections that have been likened to the communicating extensions of neurones. The data in this notebook are from the analysis of these extensions in the 4v88 data by Poirot and Timsit (2016, Neuron-Like Networks Between Ribosomal Proteins Within the Ribosome. Sci Rep. 2016;6:26485. https://doi.org/10.1038/srep26485) Although it is interesting to look at the protein:protein interactions that they study in detail - it is important to remember that the ribosome is mainly RNA. You can see the structure if you load the 4v88 into ICM browser or at the PDBe webpage https://pdbe.org/4v88. If you do you will see how the proteins decorate the outer surface of the subunits. And that there is a cleft between the two subunits that allows the mRNA access to the active site. Because of this cleft, relatively few proteins from the small subunit can reach those in the large subunit. The tables of interactions have been turned into the python data structures below. Here is the network of contacts mentioned in the paper above (extracted from their tables S3 and S4). Many proteins have several contacts through elongated extensions. ###Code # run this cell to load the table_of_contacts dictionary table_of_contacts = {"eL13" : ["eL15", "eL18", "eL36", "uL15", "uL29", "uL4"], "eL14" : ["eL20", "eL6", "uL13", "uL6"], "eL15" : ["eL36", "eL42", "eL8", "uL2", "uL29", "uL4"], "eL18" : ["uL15", "uL30", "uL4"], "eL19" : ["eS7"], "eL20" : ["eL21", "uL13", "uL16", "uL30", "uL4", "uL6"], "eL21" : ["eL29", "uL16", "uL18", "uL30", "uL4"], "eL24" : ["eS6", "uL14", "uL3"], "eL27" : ["eL30", "eL34", "eL8"], "eL30" : ["eL34", "eL43"], "eL32" : ["eL33", "eL6", "uL15"], "eL33" : ["eL6", "uL13", "uL22"], "eL34" : ["eL39"], "eL36" : ["eL8", "uL15"], "eL37" : ["eL39", "uL29", "uL4"], "eL39" : ["uL23", "uL24"], "eL40" : ["uL6"], "eL42" : ["uL15", "uL5"], "eL43" : ["uL2"], "eL8" : ["uL2", "uL23"], "eS10" : ["eS12", "uS14", "uS3"], "eS12" : ["eS31"], "eS17" : ["uS2", "uS3"], "eS19" : ["uS13", "uS9"], "eS21" : ["eS24", "eS27", "eS4", "eS6", "uS2", "uS4", "uS5", "uS8"], "eS24" : ["eS4", "eS6", "uS4"], "eS25" : ["uS13", "uS7", "uS9"], "eS27" : ["uS15", "uS8"], "eS28" : ["eS30", "uS12", "uS4", "uS7"], "eS30" : ["uS12", "uS4"], "eS4" : ["eS6", "uS17", "uS4"], "eS6" : ["uL3"], "eS7" : ["uS15", "uS8"], "eS8" : ["uS17"], "uL13" : ["uL3", "uL6"], "uL14" : ["uL3"], "uL16" : ["uL18"], "uL18" : ["uL5"], "uL23" : ["uL29"], "uL24" : ["uL4"], "uL30" : ["uL4"], "uS10" : ["uS14", "uS3", "uS9"], "uS12" : ["uS17", "uS8"], "uS13" : ["uS19"], "uS14" : ["uS3"], "uS15" : ["uS17", "uS8"], "uS17" : ["uS8"], "uS2" : ["uS5"], "uS3" : ["uS5"], "uS4" : ["uS5", "uS8"], "uS5" : ["uS8"], "uS7" : ["uS9"], "GBP" : ["uS9", "uS12", "eS17"], "STM1" : ["uS12", "uS19", "eS31" ],} # run this cell to import networkx and pyplot import networkx as nx import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown The protein interactions will be treated as reciprocal and so an undirected graph is used. ###Code # run this cell to create (an empty) nx.Graph called contacts_graph contacts_graph = nx.Graph() ###Output _____no_output_____ ###Markdown The individual proteins can be added as nodes from the `table_of_contacts` dictionary keys ###Code # run this cell add the individual proteins as nodes of protein_graph contacts_graph.add_nodes_from(table_of_contacts.keys()) ###Output _____no_output_____ ###Markdown Running `nx.info` shows that after this the graph is a series of nodes that are not yet connected ###Code # run this cell to get basic info on contacts_graph print(nx.info(contacts_graph)) ###Output _____no_output_____ ###Markdown Then the contacts from the network are added as edges. ###Code # Then we determine the edges on the nodes for protein, interacting_proteins in table_of_contacts.items(): for contact in interacting_proteins: contacts_graph.add_edge(protein, contact) ###Output _____no_output_____ ###Markdown After we have add the edges it can be noted that there are edges and that the number of nodes in the graph has increased (question: why is this so?). ###Code # run this cell to get basic info on contacts_graph print(nx.info(contacts_graph)) ###Output _____no_output_____ ###Markdown Lets try drawing the graph in two ways: ###Code nx.draw_random(contacts_graph,node_color='r',) nx.draw_circular(contacts_graph,node_color='y') ###Output _____no_output_____ ###Markdown Neither one of those representations showed the effect of the cleft between the small and the large subunit. One approach is to apply a force to the nodes. The nodes are treated as if each edge was a little spring. This can untangle them.This has to be done iteratively. And like the random approach it can vary from run to run.But it should separate out the clusters of nodes for the two subunits.If not then try altering the constant k or the number of interations. ###Code nx.draw_spring(contacts_graph, k=0.80, iterations=30, with_labels=True, node_color='c',) ###Output _____no_output_____ ###Markdown Note that each time the cell is run a different diagram is produced.You should be able to see a separation between the small and large subunits. But it would be much clearer if the small and large subunits had distinct colors. The following cell has incomplete code to acheive this. ###Code # TASK! # complete code to draw diagram with small and large nodes different colors plt.figure(figsize=(10,10)) pos_spring = nx.spring_layout(contacts_graph) small_node_list = [label for label in set(contacts_graph) if 'S' in label] nx.draw_networkx_nodes(contacts_graph, pos=pos_spring, nodelist=small_node_list, node_color='pink') nx.draw_networkx_edges(contacts_graph, pos=pos_spring, alpha=0.5) # complete code drawing the other 'large' nodes and labelling all nodes plt.axis('off') ###Output _____no_output_____ ###Markdown Question: there is one subunit called `GBP` (short for Guanine binding protein) that is does not have `S` or `L` in its name. In our first attempt at a diagram we grouped this with the large subunits. Draw a second diagram including GBP with the small subunits. Does it make more sense to included GBP with the small or with the large subunits? ###Code # your turn draw a network diagram colouring the small and large # subunits in different colours including GBP as a small subunit ###Output _____no_output_____ ###Markdown Degree of the networkThis is a useful metrix to understand how connected a network is. ###Code n = contacts_graph.number_of_nodes() print(n) e = contacts_graph.number_of_edges() print(e) ###Output _____no_output_____ ###Markdown We can calculate the average degree by multipling twice the number of edges by the number of nodes. Why twice?Remember that each edge connects two nodes so will contribute to the degree of both. ###Code print('Average degree', 2*e/n) ###Output _____no_output_____ ###Markdown The average degree of a network is included in the short summary of information of a graph provided by the function `nx.info`: ###Code print(nx.info(contacts_graph)) ###Output _____no_output_____ ###Markdown The network density compares this number of edges with the maximum possible. ###Code nx.density(contacts_graph) # run this cell to print out the degree for each node in contact_graphs print(contacts_graph.degree) ###Output _____no_output_____ ###Markdown This can be sorted to find the best connected nodes. ###Code nodes_by_degree = sorted(contacts_graph.degree, key=lambda x: x[1], reverse=True) print(nodes_by_degree) ###Output _____no_output_____ ###Markdown The top of the list shows that there are well connected nodes in both the large and the small subunit. Networkx has a degree histogram function. The cell below shows that for a bin of 1 (it can be good to increase the bin size for larger graphs). ###Code bin=1 degree_freq = nx.degree_histogram(contacts_graph) degrees = range(len(degree_freq)) plt.figure(figsize=(12, 8)) plt.plot(degrees[bin:], degree_freq[bin:],'go-') plt.xlabel('Degree') plt.ylabel('Frequency') ###Output _____no_output_____ ###Markdown The neighbours of particular nodes can be obtained. Here is one of the best connected nodes from the sorted degree dictionary earlier. ###Code list(contacts_graph.neighbors('eS21')) ###Output _____no_output_____ ###Markdown Now write code to work to find the node with the highest degree that has any contacts with the other subunit. ###Code # code to find the nodes with the highest degree that have any contacts with the other subunit. ###Output _____no_output_____ ###Markdown Advanced exercise colour network by degreeThis is a slightly tricky, see https://stackoverflow.com/a/28916094 for hint CliquesCliques are also called 'complete' subgraphs. These are complete groups of nodes where each one is joined to each of the others. You can see that some of the best connected nodes are also members of multiple larger cliques. ###Code list(nx.find_cliques(contacts_graph)) ###Output _____no_output_____ ###Markdown It is interesting to compare a network with an artificial one made in some random way. The original of this is the Erdox-Renyi graph. This is made for the given number of nodes and the probability of edge formation. Conveniently this is the graph density. Our network had 68 nodes and an approximate density of 0.055.Of course this will give a different graph every time it is run. ###Code E = nx.erdos_renyi_graph(68,0.055) nx.draw_spring(E,k=0.80,iterations=50, with_labels=True, node_color='r',) ###Output _____no_output_____ ###Markdown You may see that a low density has a fairly high chance of having disconnected components.The ribosome did in fact have several disconnect components that were present in the paper's data table but which was editted out for simplicity in the plots for this notebook. We can plot the degree histogram of the random graph for comparison with the ribosome protein one. ###Code bin=1 degree_freq = nx.degree_histogram(E) degrees = range(len(degree_freq)) plt.figure(figsize=(12, 8)) plt.plot(degrees[bin:], degree_freq[bin:],'go-') plt.xlabel('Degree') plt.ylabel('Frequency') ###Output _____no_output_____ ###Markdown The Watts-Strogatz graph is a special kind of random artificial graph. This is made for the given number of nodes and a starting number of edges (k). But then the connections are re-wired to attempt to add a 'small world' connectivity to the network. The parameter p controls the rewiring. So here is a small world network the same size as our ribosomal one. This version enforces a connected graph. ###Code S = nx.connected_watts_strogatz_graph(68, k=4, p=0.5) nx.draw_spring(S,k=0.80,iterations=50, with_labels=True, node_color='g',) bin=1 degree_freq = nx.degree_histogram(S) degrees = range(len(degree_freq)) plt.figure(figsize=(12, 8)) plt.plot(degrees[bin:], degree_freq[bin:],'go-') plt.xlabel('Degree') plt.ylabel('Frequency') ###Output _____no_output_____
final_project/working/playground_toplevel.ipynb
###Markdown Table of Contents1&nbsp;&nbsp;Setup1.1&nbsp;&nbsp;Let's set up some common file paths2&nbsp;&nbsp;Behavior2.1&nbsp;&nbsp;Extract sync time stamps2.2&nbsp;&nbsp;Extract some trial features so we can analyze all of this neural data...3&nbsp;&nbsp;Spikes3.1&nbsp;&nbsp;Turn spike times into trains and firing rates3.2&nbsp;&nbsp;Chop 1 kHz spike data into trials and downsample, aligned to event timestamps extracted from behavior4&nbsp;&nbsp;LFP4.1&nbsp;&nbsp;Bandpass and smooth LFP in standard frequency windows, and align to sync points (leave at 1 kHz)4.2&nbsp;&nbsp;Downsample chopped LFP5&nbsp;&nbsp;Visualization5.1&nbsp;&nbsp;Let's check out spikes synced to the start of the trial5.2&nbsp;&nbsp;Let's check out some LFP magnitudes and phases synced to the start of the trial Skeleton for final project... Setup Let's set up some common file paths ###Code %%writefile process_behavior.py import mat73 import h5py from collections import defaultdict import numpy as np import pandas as pd import scipy.signal as signal import scipy.ndimage as ndimage import scipy.stats as stats # import dask.array as da %%writefile process_neural.py import mat73 import h5py from collections import defaultdict import numpy as np import pandas as pd import scipy.signal as signal import scipy.ndimage as ndimage import scipy.stats as stats # import dask.array as da from os.path import join as pjoin import glob import matplotlib.pyplot as plt from importlib import reload data_dir = "data_clean" session = "George00_rec14_01282021" bhv_fnames = sorted(glob.glob(pjoin(data_dir, session + "*bhv*"))) # could be >1 spk_fname = glob.glob(pjoin(data_dir, session + "*units*"))[0] # expect 1 lfp_fname = glob.glob(pjoin(data_dir, session + "*LFP*"))[0] # expect 1 # to save time for the demo, let's restrict everthing to a few exciting channels: fun_channels = [107, 110, 112] ###Output _____no_output_____ ###Markdown Behavior Extract sync time stampsFor each session, we want to pull out snippets around task events. Two standard sync points are the start (pictures are displayed on the screen) and end (animal makes a selection with a lever movement) of each trial. This function could be customized easily-- we just need a vector of time stamps (in seconds) to align the neural data. ###Code %%writefile -a process_behavior.py def load_raw_bhv(bhv_fnames): """ Load raw bhv (.bhv2 saved as .mat) into dict; consolidate if split across multiple files (assume alpha order) Parameters: ---------- bhv_fnames : list File path(s) for behavior data Returns: ------- bhv_data : dict All task data """ bhv_data = defaultdict(list) for f in bhv_fnames: print(f) data = mat73.loadmat(f) data_vars = data["bhvdata"].keys() for v in data_vars: bhv_data[v] += data["bhvdata"][v] return bhv_data def load_pl2_codes(spk_fname): """ Load task event codes and corresponding time stamps from raw spk (.pl2 saved as .mat). Parameters: ---------- spk_fname : string File path for spk data Returns: ------- pl2_codes : dict Event codes and timestamps from whole session """ pl2_codes = mat73.loadmat(spk_fname, \ only_include=["event_codes", "event_ts"]) return pl2_codes %%writefile -a process_behavior.py def get_trial_events(bhv_data, pl2_codes, event): """ For each trial in bhv_data, pull time for this event code (-1 if doesn't exist) Parameters: ---------- bhv_data : dict All task data pl2_codes : dict Event codes and timestamps from whole session event : int Event code word Returns: ------- timestamps : np vector Timestamps corresponding to event within each trial (or -1) """ # cut up trials by default start and stop codes start_code = 9 stop_code = 18 trial_start = np.where(pl2_codes["event_codes"] == start_code)[0] trial_stop = np.where(pl2_codes["event_codes"] == stop_code)[0] # check that we have the same number of trials from bhv and pl2 data ntr = len(bhv_data["Trial"]) if trial_start.shape[0] != ntr or trial_stop.shape[0] != ntr: raise ValueError("oops! mismatched bhv2 and pl2 trial counts") # cycle through all trials, save event time (if exists) timestamps = -1 * np.ones(ntr) for tr in range(ntr): # restrict to event codes in this trial codes = pl2_codes["event_codes"][trial_start[tr] : trial_stop[tr]] ts = pl2_codes["event_ts"][trial_start[tr] : trial_stop[tr]] idx = np.where(codes == event)[0] if idx.shape[0] == 1: timestamps[tr] = ts[idx] return timestamps from process_behavior import * # load bhv data for this session bhv_data = load_raw_bhv(bhv_fnames) # load spk events for this session pl2_codes = load_pl2_codes(spk_fname) # get time stamps for pictures and lever responses ts_pics = get_trial_events(bhv_data, pl2_codes, 20) ts_left = get_trial_events(bhv_data, pl2_codes, 23) ts_right = get_trial_events(bhv_data, pl2_codes, 24) fig = plt.figure() ax = fig.add_subplot(1, 3, 1) ax.hist(ts_pics) ax = fig.add_subplot(1, 3, 2) ax.hist(ts_left) ax = fig.add_subplot(1, 3, 3) ax.hist(ts_right) ###Output _____no_output_____ ###Markdown Extract some trial features so we can analyze all of this neural data... Spikes Turn spike times into trains and firing ratesThe raw data contains spike times at 40 kHz for each neuron. While this is an efficient way to store data, it's often more convenient to visualize/to analyses on spike trains (e.g. 0 0 1 1 0 0 1 0) or smoothed firing rates (trains with 50ms boxcar smoothing) at 1 kHz. ###Code %%writefile -a process_neural.py def process_raw_spk(spk_fname, channels=-1): """ Load raw spk (.pl2 saved as .mat) Parameters: ---------- spk_fname : string Path file for raw spk data channels : list Integers, restrict processing to these channel numbers; if -1, use all channels Returns: ------- raster : np array spike trains, nunits x ntimes fr : np array firing rates, nunits x ntimes unit_meta : pd table meta data; each row corresponds to row in raster and fr """ # load spk data data = mat73.loadmat(spk_fname) # get unique unit names if channels==-1: unit_names = [u[0] for u in data["unit_names"]] else: unit_names = [u[0] for u in data["unit_names"] if int(u[0][8:11]) in channels] nunits = len(unit_names) # restrict data to channels # get last spike time in entire session, +1 second last_spk = [data[u][-1] for u in unit_names] max_t = 1 + max(last_spk) ts = np.arange(np.round(1000 * max_t)) # ms, corresponding time vector ntimes = len(ts) # get spike trains for all units raster = get_raster(data, unit_names, ntimes) # smooth spike trains into firig rates fr = get_fr(raster) # save some meta data for each unit mean_fr = [len(data[u])/max_t for u in unit_names] channel = [int(u.replace("SPK_SPKC","")[:3]) for u in unit_names] unit_meta = pd.DataFrame({"ID" : unit_names, "channel" : channel, "mean_fr" : mean_fr}) return raster, fr, unit_meta def get_raster(data, unit_names, ntimes): """ Turn spike times into trains, for all units in data. Parameters: ---------- data : dict spk data, with unit spike times plus some meta data unit_names : list of strings unit names ntimes : int index of max time point Returns: ------- raster : 2D np array units x time, spikes @ 1 kHz """ nunits = len(unit_names) raster = np.empty((nunits, ntimes)) for u in range(nunits): raster[u, :] = ts_to_train(data[unit_names[u]], ntimes) return raster def get_fr(raster): """ Turn raster (for units x entire session) into firing rates. Parameters: ---------- raster : 2D np array units x time, spikes @ 1 kHz Returns: ------- fr : 2D np array units x time, firing rates @ 1kHz (per ms; *1000 to get Hz) """ fr = np.empty(raster.shape) for u in range(raster.shape[0]): fr[u, :] = train_to_fr(raster[u, :]) return fr def ts_to_train(timestamps, ntimes): """ Turn spike timestamps into a spike train. Parameters: ---------- timestamps : np vector Times this unit fired, in sec ntimes : int Max time index Returns: ------- train : np vector 1 or 0 to indicate spike in that time window """ # make train of same size train = np.zeros((1, ntimes)) # set train = 1 at closest time stamp timestamps_ms = np.round(1000 * timestamps).astype(int) train[:, timestamps_ms] = 1 return train def train_to_fr(train): """ Turn spike train into firing rate. Note: can also use this to smooth LFP magnitude! Parameters: ---------- train : np vector 1 or 0 to indicate spike in that time window Returns: ------- train_smoothed : np vector train with 50 ms boxcar smoothing """ # define boxcar smooth box = signal.boxcar(49) / 49 # apply smoothing train_smoothed = np.convolve(train, box, "same") return train_smoothed %%time import process_neural raster, fr, unit_meta = process_neural.process_raw_spk(spk_fname, fun_channels) unit_meta ###Output _____no_output_____ ###Markdown Chop 1 kHz spike data into trials and downsample, aligned to event timestamps extracted from behaviorUsing the time stamps pulled from the behavior, we can look at the same time period across all trials synced to specific events (e.g. start or end of trial). ###Code %%writefile -a process_neural.py # chop up long neural data into trials def chop(long_brain, sync_points, window): """ Chop up 2 hr session into snippets around sync points. Parameters: ---------- long_brain : 2D np array units x time (e.g. spike train, LFP magnitude) sync_points : np vector sync points across session, e.g. start time for all trials window : tuple (2 element) time window around sync point (in seconds) Returns: ------- chopped_brain : 3D np array sync_points x time x units """ # number of units nunits = long_brain.shape[0] # time window index t_idx = np.arange(window[0] * 1000, window[1] * 1000) # use ms! nt = t_idx.shape[0] # sync point index sync_idx = np.round(sync_points * 1000) # use ms! sync_idx[sync_idx == -1000] = -1 # manual fix; these trials are missing events nsync = sync_idx.shape[0] # make index matrix tile_time = np.tile(t_idx.reshape(1, -1), (nsync, 1)) tile_sync = np.tile(sync_idx.reshape(-1, 1), (1, nt)) long_idx = (tile_time + tile_sync).astype(int) long_idx[tile_sync == -1] = -1 # same manual fix # chop up each unit... chopped_brain = np.empty((nsync, nt, nunits)) for u in range(nunits): chopped_brain[:, :, u] = long_brain[u, :][long_idx] if nunits == 1: chopped_brain = np.squeeze(chopped_brain) return chopped_brain %%writefile -a process_neural.py # smooth chooped neural data def sliding_avg(data, ts, time_range, window, step=0.25): """ Downsample by averaging in window offset by step (window fraction) along axis=1 (time). Assume data @ 1 kHz, and window given in seconds; step is fraction of window. TODO: make this more flexible for other units; will still run right now but results could be incorrect... Parameters: ---------- data : 3D np array sync points x time x units, sampled at 1 kHz ts : np vector timestamps corresponding to time axis in data, assume seconds time_range : tuple restricted time range from full ts window : float size of averging window step : float offset between averaging windows, given by fraction of window; must be >0, and 1 = no overlap. Returns: ------- """ # check that step makes sense... if step <= 0 or step > 1: raise ValueError("Bad choice for sliding window average! " +\ "step' is fraction of window, must be > 0 and <= 1") # check that time range makes sense... if time_range[0] >= time_range[1]: raise ValueError("Bad choice for sliding window average! " +\ "'time_range' is not sensible") adjusted_time_range = np.array([ np.max([time_range[0], ts[0]]), np.min([time_range[1], ts[-1]])]) # get size of data nsync, ntimes, nunits = data.shape # set window and offset sizes, in ms window_ms = np.round(1000 * window) offset_ms = np.round(window_ms * step) # find midpoints for averaging windows start_idx = np.floor(np.argmin(np.abs(ts - adjusted_time_range[0])) + window_ms/2) stop_idx = np.ceil(1 + np.argmin(np.abs(ts - adjusted_time_range[1])) - window_ms/2) mid_idx = np.arange(start_idx, stop_idx, offset_ms).astype(int) mid_times = ts[mid_idx] # do sliding averages data_smooth = np.empty((nsync, len(mid_idx), nunits)) t_idx = np.arange(-np.floor(window_ms / 2), np.ceil(window_ms / 2)).astype(int) for i in range(len(mid_idx)): data_smooth[:, i, :] = data[:, mid_idx[i] + t_idx, :].mean(axis=1) return mid_times, data_smooth reload(process_neural) %%time train_chopped = process_neural.chop(raster, ts_pics, (-1, 1)) fr_chopped = process_neural.chop(fr, ts_pics, (-1, 1)) %%time # smooth firing rates with 500ms sliding windows, from -2 to 2 sec around sync point ts = np.arange(-1, 1, 0.001) mid_times_500ms, data_smooth_500ms = process_neural.sliding_avg(fr_chopped, ts, (-1, 1), 0.5) %%time # smooth firing rates with 200ms sliding windows, from -1 to 1 sec around sync point mid_times_200ms, data_smooth_200ms = process_neural.sliding_avg(fr_chopped, ts, (-1, 1), 0.2) ###Output CPU times: user 337 ms, sys: 46.3 ms, total: 383 ms Wall time: 389 ms ###Markdown LFP Bandpass and smooth LFP in standard frequency windows, and align to sync points (leave at 1 kHz) ###Code %%writefile -a process_neural.py def process_raw_lfp(lfp_fname, sync_point, time_range, channels): """ Load raw lfp (.pl2 saved as .mat) Parameters: ---------- lfp_fname : string Path file for raw lfp data sync_point : np vector Times to sync across session (e.g. trial start) time_range : 2 element tuple Time range around sync points, in sec channels : list Integers; restrict to these channels; -1 = all Returns: ------- band_mag_chopped_np : list of 3D np arrays with each bandpass magnitude; sync_points x time x channels band_phs_chopped_np : list of 3D np arrays with each bandpass phase; sync_points x time x channels ts_chopped : np vector time for data chopped at sync_points, in sec lfp_meta : pd table meta data; each row corresponds to LFP channel """ # get channel names f = h5py.File(lfp_fname, "r") channel_names = [key for key in f.keys() if key.find("FP") == 0] if channels!=-1: channel_names = [ch for ch in channel_names if int(ch[2:]) in channels] # get lfp time data = mat73.loadmat(lfp_fname, only_include="lfp_ts") ts_long = data["lfp_ts"]/1000 # time in seconds # make notch filters notch_hz = [60, 120, 180] # Hz notch_filts = [signal.iirnotch(n, n, 1000) for n in notch_hz] # make bandpass filters band_hz = [[2, 4], [4, 8], [8, 12], [12, 30], [30, 60], [70, 200]] # Hz band_names = ["delta", "theta", "alpha", "beta", "gamma", "high gamma"] band_filts = [signal.firwin(1000, [b[0], b[1]], pass_zero=False, fs=1000) for b in band_hz] # get chopped time index ts_chopped = np.arange(time_range[0], time_range[1], 0.001) # init dicts to keep track of all channels band_mag_chopped = dict() band_phs_chopped = dict() for b in band_names: band_mag_chopped[b] = [None] * len(channel_names) band_phs_chopped[b] = [None] * len(channel_names) # get bandpassed signal and chop into trials for ch in range(len(channel_names)): # TODO: PARALLELIZE! print('working on band pass...' + channel_names[ch]) # load, notch, and bandpass this channel mag, phs = get_bandpassed(channel_names[ch], lfp_fname, ts_long, notch_filts, band_filts) # chop by sync points mag_chopped = [chop(m.reshape(1, -1), sync_point, time_range) for m in mag] phs_chopped = [chop(p.reshape(1, -1), sync_point, time_range) for p in phs] # slot in results for b in range(len(band_names)): band_mag_chopped[band_names[b]][ch] = mag_chopped[b] band_phs_chopped[band_names[b]][ch] = phs_chopped[b] # cat all channels together for 3D array: sync_points x time x channels band_mag_chopped_np = [np.stack(band_mag_chopped[b], axis=2) for b in band_names] band_phs_chopped_np = [np.stack(band_phs_chopped[b], axis=2) for b in band_names] # save meta data for these channels lfp_meta = pd.DataFrame({"ID" : channel_names}) return band_mag_chopped_np, band_phs_chopped_np, ts_chopped def get_bandpassed(chname, fname, ts, notch_filts, band_filts): """ Get mag and phase for bandpassed LFP channel. Parameters: ---------- chname : string channel ID lfp_name : string path to LFP data ts : np vector time stamps for LFP timeseries (in seconds) notch_filts : list notch filters band_filts : list bandpass filters Returns: ------- mag : list np vectors with magntiude of signal in each band_filts phs : list np vectors with phase of signal in each band_filt """ # load lfp channel data = mat73.loadmat(fname, only_include=chname) channel = data[chname] # apply notch filters serially for notch in notch_filts: channel = signal.filtfilt(notch[0], notch[1], channel) # apply each band pass separately # TODO: parallelize these steps by band! bandpassed = [signal.filtfilt(band, 1, channel) for band in band_filts] # get analytic signal analytic = [signal.hilbert(b) for b in bandpassed] # get magnitude, smooth with 50ms boxcar mag_raw = [train_to_fr(np.abs(a)) for a in analytic] mag = [stats.zscore(m) for m in mag_raw] # get phase phs = [np.angle(a) for a in analytic] return mag, phs reload(process_neural) %%time mag_chopped, phs_chopped, ts_chopped = process_neural.process_raw_lfp(lfp_fname, ts_pics, (-1, 1), fun_channels) ###Output working on band pass...FP107 working on band pass...FP110 working on band pass...FP112 CPU times: user 1min 53s, sys: 18.3 s, total: 2min 11s Wall time: 2min 15s ###Markdown Downsample chopped LFP ###Code %%time # smooth firing rates with 500ms sliding windows, from -2 to 2 sec around sync point mid_times_100ms, theta_smooth_100ms = process_neural.sliding_avg(mag_chopped[1], ts_chopped, (-1, 1), 0.1) %%time # smooth firing rates with 200ms sliding windows, from -1 to 1 sec around sync point mid_times_200ms, beta_smooth_200ms = process_neural.sliding_avg(mag_chopped[0], ts_chopped, (-1, 1), 0.2) ###Output CPU times: user 210 ms, sys: 4.68 ms, total: 215 ms Wall time: 222 ms ###Markdown Visualization Let's check out spikes synced to the start of the trial ###Code unit_names = unit_meta.ID fig = plt.figure(figsize=(8, 20)) t_idx = np.arange(-1000, 1000) for u in range(len(unit_names)): ax = fig.add_subplot(len(unit_names), 1, u + 1) ax.plot(t_idx, 1000*np.mean(fr_chopped[:, :, u], axis=0)) y = ax.get_ylim() new_y = (0, y[1]) ax.plot(np.array([0, 0]), new_y, "k") ax.plot(np.array([-750, -750]), new_y, "k:") ax.set_ylabel("firing rate (Hz)\n"+unit_names[u]) ax.set_xlabel("Time from sync (ms)") ###Output _____no_output_____ ###Markdown Let's check out some LFP magnitudes and phases synced to the start of the trial ###Code # phase fig, ax = plt.subplots() ax.imshow(phs_chopped[1][:, :, 0], cmap="hot") # mag fig = plt.figure() ax = fig.add_subplot(2, 1, 1) ax.imshow(theta_smooth_100ms[:, :, 0], cmap="hot", aspect="auto") ax.set_xticks(np.arange(8, 75, 10)) ax.set_xticklabels(np.round(mid_times_100ms[np.arange(8, 75, 10)], 3)) ax.set_xlabel("Time from pics (ms)") ax.set_ylabel("Trials") ax = fig.add_subplot(2, 1, 2) ax.plot(mid_times_100ms, np.mean(theta_smooth_100ms[:, :, 0], axis=0)) ax.set_xlabel("Time from pics (ms)") ax.set_ylabel("theta magnitude (st dev)") fig = plt.figure() ax = fig.add_subplot(2, 1, 1) ax.imshow(beta_smooth_200ms[:, :, 0], cmap="hot", aspect="auto") ax.set_xticks(np.arange(3, 35, 5)) ax.set_xticklabels(np.round(mid_times_200ms[np.arange(3, 35, 5)], 3)) ax.set_xlabel("Time from pics (ms)") ax.set_ylabel("Trials") ax = fig.add_subplot(2, 1, 2) ax.plot(mid_times_200ms, np.mean(beta_smooth_200ms[:, :, 0], axis=0)) ax.set_xlabel("Time from pics (ms)") ax.set_ylabel("beta magnitude (st dev)") ###Output _____no_output_____
assignment2/.ipynb_checkpoints/FullyConnectedNets-checkpoint.ipynb
###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output ('X_train: ', (49000, 3, 32, 32)) ('y_train: ', (49000,)) ('X_val: ', (1000, 3, 32, 32)) ('y_val: ', (1000,)) ('X_test: ', (1000, 3, 32, 32)) ('y_test: ', (1000,)) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing affine_forward function: difference: 9.769849468192957e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_backward function: dx error: 5.399100368651805e-11 dw error: 9.904211865398145e-11 db error: 2.4122867568119087e-11 ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 5e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.999999798022158e-08 ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.2756349136310288e-12 ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print('Testing affine_relu_forward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward: dx error: 2.299579177309368e-11 dw error: 8.162011105764925e-11 db error: 7.826724021458994e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.999602749096233 dx error: 1.4021566006651672e-09 Testing softmax_loss: loss: 2.302545844500738 dx error: 9.384673161989355e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.83e-08 W2 relative error: 3.12e-10 b1 relative error: 9.83e-09 b2 relative error: 4.33e-10 Running numeric gradient check with reg = 0.7 W1 relative error: 2.53e-07 W2 relative error: 2.85e-08 b1 relative error: 1.56e-08 b2 relative error: 7.76e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## solver = Solver(model, data, update_rule='sgd', optim_config={'learning_rate': 1e-3,}, lr_decay=0.9, batch_size=100, num_epochs=10, num_train_samples=1000, num_val_samples=None, print_every=100, verbose=True ) solver.train() ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Running check with reg = 0 Initial loss: 2.3004790897684924 W1 relative error: 1.48e-07 W2 relative error: 2.21e-05 W3 relative error: 3.53e-07 b1 relative error: 5.38e-09 b2 relative error: 2.09e-09 b3 relative error: 5.80e-11 Running check with reg = 3.14 Initial loss: 7.052114776533016 W1 relative error: 1.04e-08 W2 relative error: 6.87e-08 W3 relative error: 1.32e-08 b1 relative error: 1.48e-08 b2 relative error: 1.72e-09 b3 relative error: 1.80e-10 ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } # for i in range(2**32): # weight_scale = 1e-2 # #weight_scale = 10**np.random.uniform(-1.9,-2.1,1)[0] # learning_rate = 1e-2 # #learning_rate = 10**np.random.uniform(-1.9,-2.1,1)[0] # np.random.seed(i) # model = FullyConnectedNet([100, 100], # weight_scale=weight_scale, dtype=np.float64) # solver = Solver(model, small_data, # print_every=10, num_epochs=20, batch_size=25, # update_rule='sgd', # optim_config={ # 'learning_rate': learning_rate, # }, # verbose=False # ) # solver.train() # if solver.train_acc_history[-1]>0.8: # print("train_acc {},\t val_acc {},\t weight_scale {:.3E},\t learning_rate {:.3E}". # format(solver.train_acc_history[-1],solver.val_acc_history[-1],weight_scale,learning_rate)) # if solver.train_acc_history[-1]==1.0: # break weight_scale = 1e-2 learning_rate = 1e-2 np.random.seed(75) model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output (Iteration 1 / 40) loss: 2.326632 (Epoch 0 / 20) train acc: 0.240000; val_acc: 0.097000 (Epoch 1 / 20) train acc: 0.420000; val_acc: 0.156000 (Epoch 2 / 20) train acc: 0.580000; val_acc: 0.170000 (Epoch 3 / 20) train acc: 0.460000; val_acc: 0.116000 (Epoch 4 / 20) train acc: 0.560000; val_acc: 0.179000 (Epoch 5 / 20) train acc: 0.680000; val_acc: 0.150000 (Iteration 11 / 40) loss: 1.017769 (Epoch 6 / 20) train acc: 0.740000; val_acc: 0.195000 (Epoch 7 / 20) train acc: 0.780000; val_acc: 0.165000 (Epoch 8 / 20) train acc: 0.860000; val_acc: 0.190000 (Epoch 9 / 20) train acc: 0.880000; val_acc: 0.178000 (Epoch 10 / 20) train acc: 0.940000; val_acc: 0.192000 (Iteration 21 / 40) loss: 0.256519 (Epoch 11 / 20) train acc: 0.980000; val_acc: 0.190000 (Epoch 12 / 20) train acc: 1.000000; val_acc: 0.194000 (Epoch 13 / 20) train acc: 0.960000; val_acc: 0.198000 (Epoch 14 / 20) train acc: 0.960000; val_acc: 0.199000 (Epoch 15 / 20) train acc: 1.000000; val_acc: 0.194000 (Iteration 31 / 40) loss: 0.106696 (Epoch 16 / 20) train acc: 1.000000; val_acc: 0.199000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.187000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.191000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.196000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.190000 ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 2.5e-2 weight_scale = 3e-2 np.random.seed(109) model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() # for i in range(2**32-1): # np.random.seed() # # weight_scale = 10**np.random.uniform(-1.5,-2,1)[0] # weight_scale = 3e-2 # # learning_rate = 10**np.random.uniform(-1.5,-1.7,1)[0] # learning_rate = 2.5e-2 # np.random.seed(i) # model = FullyConnectedNet([100, 100, 100, 100], # weight_scale=weight_scale, dtype=np.float64) # solver = Solver(model, small_data, # print_every=10, num_epochs=20, batch_size=25, # update_rule='sgd', # optim_config={ # 'learning_rate': learning_rate, # }, # verbose=False # ) # solver.train() # if solver.train_acc_history[-1]>0.9: # print("seed {},\t train_acc {},\t val_acc {},\t weight_scale {:.3E},\t learning_rate {:.3E}". # format(i, solver.train_acc_history[-1],solver.val_acc_history[-1],weight_scale,learning_rate)) # if solver.train_acc_history[-1]==1.0: # break ###Output (Iteration 1 / 40) loss: 2.281482 (Epoch 0 / 20) train acc: 0.280000; val_acc: 0.117000 (Epoch 1 / 20) train acc: 0.220000; val_acc: 0.111000 (Epoch 2 / 20) train acc: 0.380000; val_acc: 0.128000 (Epoch 3 / 20) train acc: 0.420000; val_acc: 0.123000 (Epoch 4 / 20) train acc: 0.440000; val_acc: 0.151000 (Epoch 5 / 20) train acc: 0.540000; val_acc: 0.141000 (Iteration 11 / 40) loss: 1.402726 (Epoch 6 / 20) train acc: 0.580000; val_acc: 0.154000 (Epoch 7 / 20) train acc: 0.740000; val_acc: 0.132000 (Epoch 8 / 20) train acc: 0.760000; val_acc: 0.163000 (Epoch 9 / 20) train acc: 0.560000; val_acc: 0.141000 (Epoch 10 / 20) train acc: 0.660000; val_acc: 0.145000 (Iteration 21 / 40) loss: 1.224340 (Epoch 11 / 20) train acc: 0.920000; val_acc: 0.162000 (Epoch 12 / 20) train acc: 0.900000; val_acc: 0.166000 (Epoch 13 / 20) train acc: 0.880000; val_acc: 0.170000 (Epoch 14 / 20) train acc: 0.960000; val_acc: 0.192000 (Epoch 15 / 20) train acc: 0.960000; val_acc: 0.185000 (Iteration 31 / 40) loss: 0.233385 (Epoch 16 / 20) train acc: 1.000000; val_acc: 0.176000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.165000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.172000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.182000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.178000 ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:Deeper network is harder to train, 5-layer net generally needs a larger learning rate than that of 3-layer net Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output next_w error: 8.882347033505819e-09 velocity error: 4.269287743278663e-09 ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output running with sgd (Iteration 1 / 200) loss: 2.687828 (Epoch 0 / 5) train acc: 0.100000; val_acc: 0.116000 (Iteration 11 / 200) loss: 2.196025 (Iteration 21 / 200) loss: 2.156361 (Iteration 31 / 200) loss: 2.049217 (Epoch 1 / 5) train acc: 0.268000; val_acc: 0.226000 (Iteration 41 / 200) loss: 2.061375 (Iteration 51 / 200) loss: 2.006791 (Iteration 61 / 200) loss: 1.850594 (Iteration 71 / 200) loss: 1.806012 (Epoch 2 / 5) train acc: 0.357000; val_acc: 0.280000 (Iteration 81 / 200) loss: 1.775465 (Iteration 91 / 200) loss: 1.879534 (Iteration 101 / 200) loss: 1.814402 (Iteration 111 / 200) loss: 1.940679 (Epoch 3 / 5) train acc: 0.375000; val_acc: 0.319000 (Iteration 121 / 200) loss: 1.722141 (Iteration 131 / 200) loss: 1.807578 (Iteration 141 / 200) loss: 1.538005 (Iteration 151 / 200) loss: 1.681432 (Epoch 4 / 5) train acc: 0.391000; val_acc: 0.324000 (Iteration 161 / 200) loss: 1.624718 (Iteration 171 / 200) loss: 1.744549 (Iteration 181 / 200) loss: 1.619233 (Iteration 191 / 200) loss: 1.653390 (Epoch 5 / 5) train acc: 0.433000; val_acc: 0.324000 running with sgd_momentum (Iteration 1 / 200) loss: 2.649435 (Epoch 0 / 5) train acc: 0.124000; val_acc: 0.133000 (Iteration 11 / 200) loss: 2.238804 (Iteration 21 / 200) loss: 1.878914 (Iteration 31 / 200) loss: 2.017657 (Epoch 1 / 5) train acc: 0.315000; val_acc: 0.283000 (Iteration 41 / 200) loss: 1.930940 (Iteration 51 / 200) loss: 1.788876 (Iteration 61 / 200) loss: 1.858269 (Iteration 71 / 200) loss: 1.629427 (Epoch 2 / 5) train acc: 0.341000; val_acc: 0.298000 (Iteration 81 / 200) loss: 1.802349 (Iteration 91 / 200) loss: 1.952752 (Iteration 101 / 200) loss: 1.638477 (Iteration 111 / 200) loss: 1.542045 (Epoch 3 / 5) train acc: 0.430000; val_acc: 0.329000 (Iteration 121 / 200) loss: 1.586084 (Iteration 131 / 200) loss: 1.438590 (Iteration 141 / 200) loss: 1.452670 (Iteration 151 / 200) loss: 1.750090 (Epoch 4 / 5) train acc: 0.485000; val_acc: 0.334000 (Iteration 161 / 200) loss: 1.469777 (Iteration 171 / 200) loss: 1.433315 (Iteration 181 / 200) loss: 1.302100 (Iteration 191 / 200) loss: 1.290339 (Epoch 5 / 5) train acc: 0.509000; val_acc: 0.330000 ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output next_w error: 1.139887467333134e-07 v error: 4.208314038113071e-09 m error: 4.214963193114416e-09 ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output running with adam (Iteration 1 / 200) loss: 2.830611 (Epoch 0 / 5) train acc: 0.129000; val_acc: 0.131000 (Iteration 11 / 200) loss: 2.191021 (Iteration 21 / 200) loss: 1.863545 (Iteration 31 / 200) loss: 1.972974 (Epoch 1 / 5) train acc: 0.350000; val_acc: 0.311000 (Iteration 41 / 200) loss: 1.940997 (Iteration 51 / 200) loss: 1.655523 (Iteration 61 / 200) loss: 1.607249 (Iteration 71 / 200) loss: 1.792493 (Epoch 2 / 5) train acc: 0.463000; val_acc: 0.350000 (Iteration 81 / 200) loss: 1.403197 (Iteration 91 / 200) loss: 1.375531 (Iteration 101 / 200) loss: 1.563954 (Iteration 111 / 200) loss: 1.629518 (Epoch 3 / 5) train acc: 0.501000; val_acc: 0.351000 (Iteration 121 / 200) loss: 1.492458 (Iteration 131 / 200) loss: 1.389919 (Iteration 141 / 200) loss: 1.194321 (Iteration 151 / 200) loss: 1.251646 (Epoch 4 / 5) train acc: 0.536000; val_acc: 0.376000 (Iteration 161 / 200) loss: 1.443759 (Iteration 171 / 200) loss: 1.423801 (Iteration 181 / 200) loss: 1.029904 (Iteration 191 / 200) loss: 1.161216 (Epoch 5 / 5) train acc: 0.609000; val_acc: 0.380000 running with rmsprop (Iteration 1 / 200) loss: 2.515828 (Epoch 0 / 5) train acc: 0.128000; val_acc: 0.156000 (Iteration 11 / 200) loss: 2.089124 (Iteration 21 / 200) loss: 2.013535 (Iteration 31 / 200) loss: 1.983893 (Epoch 1 / 5) train acc: 0.395000; val_acc: 0.318000 (Iteration 41 / 200) loss: 1.738965 (Iteration 51 / 200) loss: 1.673837 (Iteration 61 / 200) loss: 1.573545 (Iteration 71 / 200) loss: 1.850876 (Epoch 2 / 5) train acc: 0.412000; val_acc: 0.331000 (Iteration 81 / 200) loss: 1.664159 (Iteration 91 / 200) loss: 1.611881 (Iteration 101 / 200) loss: 1.467152 (Iteration 111 / 200) loss: 1.519640 (Epoch 3 / 5) train acc: 0.483000; val_acc: 0.366000 (Iteration 121 / 200) loss: 1.499417 (Iteration 131 / 200) loss: 1.572730 (Iteration 141 / 200) loss: 1.408224 (Iteration 151 / 200) loss: 1.304816 (Epoch 4 / 5) train acc: 0.552000; val_acc: 0.366000 (Iteration 161 / 200) loss: 1.546324 (Iteration 171 / 200) loss: 1.514354 (Iteration 181 / 200) loss: 1.371683 (Iteration 191 / 200) loss: 1.283015 (Epoch 5 / 5) train acc: 0.543000; val_acc: 0.368000 ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ from time import time checkpoint = r"./FullyConnectedNets/checkpoint" best_val_acc = -1 for learning_rate in [1e-3,5e-3,1e-2]: for weight_scale in [5e-3,5e-2]: # learning_rate = 1e-3 # weight_scale = 5e-2 # hyperparam hidden_dims = [128, 64, 32, 32] np.random.seed(0) beta1 = 0.9 beta2 = 0.99 # train model = FullyConnectedNet(hidden_dims, input_dim=3 * 32 * 32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=weight_scale, dtype=np.float32, seed=None) solver = Solver(model, data, print_every=100, num_epochs=20, batch_size=100, update_rule='adam', lr_decay = 0.95, optim_config={ 'learning_rate': learning_rate, 'beta1':beta1, 'beta2':beta2, 'epsilon':1e-8 }, verbose = True, # checkpoint_name = checkpoint checkpoint_name = None ) start_time = time() solver.train() print("Training_time {:.2f},\t train_acc {},\t val_acc {},\t weight_scale {:.3E},\t learning_rate {:.3E}". format(time()-start_time, solver.train_acc_history[-1], solver.val_acc_history[-1], weight_scale, learning_rate)) if solver.val_acc_history[-1]>best_val_acc: best_val_acc = solver.val_acc_history[-1] best_model = model ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in data.iteritems(): print '%s: ' % k, v.shape ###Output X_val: (1000, 3, 32, 32) X_train: (49000, 3, 32, 32) X_test: (1000, 3, 32, 32) y_val: (1000,) y_train: (49000,) y_test: (1000,) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print 'Testing affine_forward function:' print 'difference: ', rel_error(out, correct_out) ###Output _____no_output_____ ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print 'Testing affine_backward function:' print 'dx error: ', rel_error(dx_num, dx) print 'dw error: ', rel_error(dw_num, dw) print 'db error: ', rel_error(db_num, db) ###Output _____no_output_____ ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 1e-8 print 'Testing relu_forward function:' print 'difference: ', rel_error(out, correct_out) ###Output _____no_output_____ ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 1e-12 print 'Testing relu_backward function:' print 'dx error: ', rel_error(dx_num, dx) ###Output _____no_output_____ ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print 'Testing affine_relu_forward:' print 'dx error: ', rel_error(dx_num, dx) print 'dw error: ', rel_error(dw_num, dw) print 'db error: ', rel_error(db_num, db) ###Output _____no_output_____ ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print 'Testing svm_loss:' print 'loss: ', loss print 'dx error: ', rel_error(dx_num, dx) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print '\nTesting softmax_loss:' print 'loss: ', loss print 'dx error: ', rel_error(dx_num, dx) ###Output _____no_output_____ ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-2 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print 'Testing initialization ... ' W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print 'Testing test-time forward pass ... ' model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print 'Testing training loss (no regularization)' y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print 'Running numeric gradient check with reg = ', reg model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])) ###Output _____no_output_____ ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## pass ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print 'Running check with reg = ', reg model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print 'Initial loss: ', loss for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])) ###Output _____no_output_____ ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 learning_rate = 1e-4 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-5 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print 'next_w error: ', rel_error(next_w, expected_next_w) print 'velocity error: ', rel_error(expected_velocity, config['velocity']) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print 'running with ', update_rule model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.iteritems(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print 'next_w error: ', rel_error(expected_next_w, next_w) print 'cache error: ', rel_error(expected_cache, config['cache']) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print 'next_w error: ', rel_error(expected_next_w, next_w) print 'v error: ', rel_error(expected_v, config['v']) print 'm error: ', rel_error(expected_m, config['m']) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print 'running with ', update_rule model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.iteritems(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ pass ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(X_test), axis=1) y_val_pred = np.argmax(best_model.loss(X_val), axis=1) print 'Validation set accuracy: ', (y_val_pred == y_val).mean() print 'Test set accuracy: ', (y_test_pred == y_test).mean() ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in data.iteritems(): print '%s: ' % k, v.shape ###Output X_val: (1000, 3, 32, 32) X_train: (49000, 3, 32, 32) X_test: (1000, 3, 32, 32) y_val: (1000,) y_train: (49000,) y_test: (1000,) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print 'Testing affine_forward function:' print 'difference: ', rel_error(out, correct_out) ###Output Testing affine_forward function: difference: 9.76985004799e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print 'Testing affine_backward function:' print 'dx error: ', rel_error(dx_num, dx) print 'dw error: ', rel_error(dw_num, dw) print 'db error: ', rel_error(db_num, db) ###Output Testing affine_backward function: dx error: 8.70343193229e-11 dw error: 1.62832772237e-10 db error: 1.13058234449e-11 ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 1e-8 print 'Testing relu_forward function:' print 'difference: ', rel_error(out, correct_out) ###Output Testing relu_forward function: difference: 4.99999979802e-08 ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 1e-12 print 'Testing relu_backward function:' print 'dx error: ', rel_error(dx_num, dx) ###Output Testing relu_backward function: dx error: 3.27561650574e-12 ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print 'Testing affine_relu_forward:' print 'dx error: ', rel_error(dx_num, dx) print 'dw error: ', rel_error(dw_num, dw) print 'db error: ', rel_error(db_num, db) ###Output Testing affine_relu_forward: dx error: 4.40464890754e-11 dw error: 2.69130122664e-09 db error: 4.30416354926e-11 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print 'Testing svm_loss:' print 'loss: ', loss print 'dx error: ', rel_error(dx_num, dx) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print '\nTesting softmax_loss:' print 'loss: ', loss print 'dx error: ', rel_error(dx_num, dx) ###Output Testing svm_loss: loss: 8.9984194169 dx error: 1.40215660067e-09 Testing softmax_loss: loss: 2.30242746395 dx error: 9.37675762138e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-2 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print 'Testing initialization ... ' W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print 'Testing test-time forward pass ... ' model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print 'Testing training loss (no regularization)' y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 # assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print 'Running numeric gradient check with reg = ', reg model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.83e-08 W2 relative error: 3.30e-10 b1 relative error: 6.19e-09 b2 relative error: 2.53e-10 Running numeric gradient check with reg = 0.7 W1 relative error: 2.53e-07 W2 relative error: 2.85e-08 b1 relative error: 1.09e-09 b2 relative error: 7.76e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code # model = TwoLayerNet() # solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## N = data['X_train'].shape[0] D = np.prod(data['X_train'].shape[1:]) H = 50 C = 10 std = 1e-2 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std, reg = 0.5) solver = Solver(model, data, update_rule='sgd', optim_config={ 'learning_rate': 1e-3, }, lr_decay=0.95, num_epochs=10, batch_size=100, print_every=100) solver.train() print solver.best_val_acc ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print 'Running check with reg = ', reg model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print 'Initial loss: ', loss for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print '%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])) ###Output _____no_output_____ ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 learning_rate = 1e-4 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-5 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print 'next_w error: ', rel_error(next_w, expected_next_w) print 'velocity error: ', rel_error(expected_velocity, config['velocity']) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print 'running with ', update_rule model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.iteritems(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print 'next_w error: ', rel_error(expected_next_w, next_w) print 'cache error: ', rel_error(expected_cache, config['cache']) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print 'next_w error: ', rel_error(expected_next_w, next_w) print 'v error: ', rel_error(expected_v, config['v']) print 'm error: ', rel_error(expected_m, config['m']) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print 'running with ', update_rule model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.iteritems(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ pass ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(X_test), axis=1) y_val_pred = np.argmax(best_model.loss(X_val), axis=1) print 'Validation set accuracy: ', (y_val_pred == y_val).mean() print 'Test set accuracy: ', (y_test_pred == y_test).mean() ###Output _____no_output_____ ###Markdown Multi-Layer Fully Connected NetworkIn this exercise, you will implement a fully connected network with an arbitrary number of hidden layers. Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the network initialization, forward pass, and backward pass. Throughout this assignment, you will be implementing layers in `cs231n/layers.py`. You can re-use your implementations for `affine_forward`, `affine_backward`, `relu_forward`, `relu_backward`, and `softmax_loss` from Assignment 1. For right now, don't worry about implementing dropout or batch/layer normalization yet, as you will add those features later. ###Code # Setup cell. import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams["figure.figsize"] = (10.0, 8.0) # Set default size of plots. plt.rcParams["image.interpolation"] = "nearest" plt.rcParams["image.cmap"] = "gray" %load_ext autoreload %autoreload 2 def rel_error(x, y): """Returns relative error.""" return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR-10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(f"{k}: {v.shape}") ###Output X_train: (49000, 3, 32, 32) y_train: (49000,) X_val: (1000, 3, 32, 32) y_val: (1000,) X_test: (1000, 3, 32, 32) y_test: (1000,) ###Markdown Initial Loss and Gradient CheckAs a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. This is a good way to see if the initial losses seem reasonable.For gradient checking, you should expect to see errors around 1e-7 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print("Running check with reg = ", reg) model = FullyConnectedNet( [H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64 ) loss, grads = model.loss(X, y) print("Initial loss: ", loss) # Most of the errors should be on the order of e-7 or smaller. # NOTE: It is fine however to see an error for W2 on the order of e-5 # for the check when reg = 0.0 for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print(f"{name} relative error: {rel_error(grad_num, grads[name])}") ###Output Running check with reg = 0 Initial loss: 0.0 Running check with reg = 3.14 Initial loss: 0.0 ###Markdown As another sanity check, make sure your network can overfit on a small dataset of 50 images. First, we will try a three-layer network with 100 units in each hidden layer. In the following cell, tweak the **learning rate** and **weight initialization scale** to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { "X_train": data["X_train"][:num_train], "y_train": data["y_train"][:num_train], "X_val": data["X_val"], "y_val": data["y_val"], } weight_scale = 1e-2 # Experiment with this! learning_rate = 1e-4 # Experiment with this! model = FullyConnectedNet( [100, 100], weight_scale=weight_scale, dtype=np.float64 ) solver = Solver( model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule="sgd", optim_config={"learning_rate": learning_rate}, ) solver.train() plt.plot(solver.loss_history) plt.title("Training loss history") plt.xlabel("Iteration") plt.ylabel("Training loss") plt.grid(linestyle='--', linewidth=0.5) plt.show() ###Output _____no_output_____ ###Markdown Now, try to use a five-layer network with 100 units on each layer to overfit on 50 training examples. Again, you will have to adjust the learning rate and weight initialization scale, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 2e-3 # Experiment with this! weight_scale = 1e-5 # Experiment with this! model = FullyConnectedNet( [100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64 ) solver = Solver( model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={'learning_rate': learning_rate}, ) solver.train() plt.plot(solver.loss_history) plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.grid(linestyle='--', linewidth=0.5) plt.show() ###Output _____no_output_____ ###Markdown Inline Question 1: Did you notice anything about the comparative difficulty of training the three-layer network vs. training the five-layer network? In particular, based on your experience, which network seemed more sensitive to the initialization scale? Why do you think that is the case? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochastic gradient descent. See the Momentum Update section at http://cs231n.github.io/neural-networks-3/sgd for more information.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {"learning_rate": 1e-3, "velocity": v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) # Should see relative errors around e-8 or less print("next_w error: ", rel_error(next_w, expected_next_w)) print("velocity error: ", rel_error(expected_velocity, config["velocity"])) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('Running with ', update_rule) model = FullyConnectedNet( [100, 100, 100, 100, 100], weight_scale=5e-2 ) solver = Solver( model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={'learning_rate': 5e-3}, verbose=True, ) solvers[update_rule] = solver solver.train() fig, axes = plt.subplots(3, 1, figsize=(15, 15)) axes[0].set_title('Training loss') axes[0].set_xlabel('Iteration') axes[1].set_title('Training accuracy') axes[1].set_xlabel('Epoch') axes[2].set_title('Validation accuracy') axes[2].set_xlabel('Epoch') for update_rule, solver in solvers.items(): axes[0].plot(solver.loss_history, label=f"loss_{update_rule}") axes[1].plot(solver.train_acc_history, label=f"train_acc_{update_rule}") axes[2].plot(solver.val_acc_history, label=f"val_acc_{update_rule}") for ax in axes: ax.legend(loc="best", ncol=4) ax.grid(linestyle='--', linewidth=0.5) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.**NOTE:** Please implement the _complete_ Adam update rule (with the bias correction mechanism), not the first simplified version mentioned in the course notes. [1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('Running with ', update_rule) model = FullyConnectedNet( [100, 100, 100, 100, 100], weight_scale=5e-2 ) solver = Solver( model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={'learning_rate': learning_rates[update_rule]}, verbose=True ) solvers[update_rule] = solver solver.train() print() fig, axes = plt.subplots(3, 1, figsize=(15, 15)) axes[0].set_title('Training loss') axes[0].set_xlabel('Iteration') axes[1].set_title('Training accuracy') axes[1].set_xlabel('Epoch') axes[2].set_title('Validation accuracy') axes[2].set_xlabel('Epoch') for update_rule, solver in solvers.items(): axes[0].plot(solver.loss_history, label=f"{update_rule}") axes[1].plot(solver.train_acc_history, label=f"{update_rule}") axes[2].plot(solver.val_acc_history, label=f"{update_rule}") for ax in axes: ax.legend(loc='best', ncol=4) ax.grid(linestyle='--', linewidth=0.5) plt.show() ###Output _____no_output_____ ###Markdown Inline Question 2:AdaGrad, like Adam, is a per-parameter optimization method that uses the following update rule:```cache += dw**2w += - learning_rate * dw / (np.sqrt(cache) + eps)```John notices that when he was training a network with AdaGrad that the updates became very small, and that his network was learning slowly. Using your knowledge of the AdaGrad update rule, why do you think the updates would become very small? Would Adam have the same issue? Answer: [FILL THIS IN] Train a Good Model!Train the best fully connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully connected network.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional networks rather than fully connected networks.**Note:** You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # find batch/layer normalization and dropout useful. Store your best model in # # the best_model variable. # ################################################################################ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test Your Model!Run your best model on the validation and test sets. You should achieve at least 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures. In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive dout (derivative of loss with respect to outputs) and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch/Layer Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) data['X_train'].shape ###Output _____no_output_____ ###Markdown Affine layer: forwardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around e-9 or less. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output _____no_output_____ ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around e-10 or less print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) from itertools import product input_tuple = (1,4,6,8) input_gen = [range(i) for i in input_tuple] for item in product(*input_gen): print(item) ###Output (0, 0, 0, 0) (0, 0, 0, 1) (0, 0, 0, 2) (0, 0, 0, 3) (0, 0, 0, 4) (0, 0, 0, 5) (0, 0, 0, 6) (0, 0, 0, 7) (0, 0, 1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3, 4, 3) (0, 3, 4, 4) (0, 3, 4, 5) (0, 3, 4, 6) (0, 3, 4, 7) (0, 3, 5, 0) (0, 3, 5, 1) (0, 3, 5, 2) (0, 3, 5, 3) (0, 3, 5, 4) (0, 3, 5, 5) (0, 3, 5, 6) (0, 3, 5, 7) ###Markdown ReLU activation: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be on the order of e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.999999798022158e-08 ###Markdown ReLU activation: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be on the order of e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.2756349136310288e-12 ###Markdown Inline Question 1: We've only asked you to implement ReLU, but there are a number of different activation functions that one could use in neural networks, each with its pros and cons. In particular, an issue commonly seen with activation functions is getting zero (or close to zero) gradient flow during backpropagation. Which of the following activation functions have this problem? If you consider these functions in the one dimensional case, what types of input would lead to this behaviour?1. Sigmoid2. ReLU3. Leaky ReLU Answer:[FILL THIS IN] "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) # Relative error should be around e-10 or less print('Testing affine_relu_forward and affine_relu_backward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward and affine_relu_backward: dx error: 1.1201273579643519e-10 dw error: 7.891560739288794e-11 db error: 8.826753728926603e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be around the order of e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be close to 2.3 and dx error should be around e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.999602749096233 dx error: 1.4021566006651672e-09 Testing softmax_loss: loss: 2.302545844500738 dx error: 9.384673161989355e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 #assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' # Errors should be around e-7 or less # Code not working with regularization, abandoning and moving forward, some changes need to be made in the initial gradients # passed in the regularized case for reg in [0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0 W1 relative error: 1.83e-08 W2 relative error: 3.25e-10 b1 relative error: 6.55e-09 b2 relative error: 4.33e-10 Running numeric gradient check with reg = 0.7 W1 relative error: 2.53e-07 W2 relative error: 7.98e-08 b1 relative error: 1.56e-08 b2 relative error: 9.09e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code # Unable to get solver to work on present hardware, abandoned efforts for now model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** D,H,C,std = 32*32*3, 100, 10, 1e-3 num_train=2000 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solver = Solver(model, small_data, update_rule='sgd', optim_config={ 'learning_rate': 1e-3, }, lr_decay=0.95, num_epochs=10, batch_size=20, print_every=1, verbose=True) solver.train() # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch/layer normalization; we will add those features soon. Initial loss and gradient checkAs a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-7 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) # Most of the errors should be on the order of e-7 or smaller. # NOTE: It is fine however to see an error for W2 on the order of e-5 # for the check when reg = 0.0 for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Running check with reg = 0 Initial loss: 2.3004790897684924 W1 relative error: 1.48e-07 W2 relative error: 2.21e-05 W3 relative error: 3.53e-07 b1 relative error: 5.38e-09 b2 relative error: 2.09e-09 b3 relative error: 5.80e-11 Running check with reg = 3.14 Initial loss: 7.052114776533016 W1 relative error: 1.00e+00 W2 relative error: 1.00e+00 W3 relative error: 1.00e+00 b1 relative error: 1.48e-08 b2 relative error: 1.72e-09 b3 relative error: 1.80e-10 ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. In the following cell, tweak the **learning rate** and **weight initialization scale** to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 # Experiment with this! learning_rate = 1e-4 # Experiment with this! model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again, you will have to adjust the learning rate and weight initialization scale, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 2e-3 # Experiment with this! weight_scale = 1e-5 # Experiment with this! model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline Question 2: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? In particular, based on your experience, which network seemed more sensitive to the initialization scale? Why do you think that is the case? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochastic gradient descent. See the Momentum Update section at http://cs231n.github.io/neural-networks-3/sgd for more information.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) # Should see relative errors around e-8 or less print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output next_w error: 8.882347033505819e-09 velocity error: 4.269287743278663e-09 ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 5e-3, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.items(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label="loss_%s" % update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label="train_acc_%s" % update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label="val_acc_%s" % update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.**NOTE:** Please implement the _complete_ Adam update rule (with the bias correction mechanism), not the first simplified version mentioned in the course notes. [1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output next_w error: 0.08408732754034352 v error: 4.208314038113071e-09 m error: 4.214963193114416e-09 ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Inline Question 3:AdaGrad, like Adam, is a per-parameter optimization method that uses the following update rule:```cache += dw**2w += - learning_rate * dw / (np.sqrt(cache) + eps)```John notices that when he was training a network with AdaGrad that the updates became very small, and that his network was learning slowly. Using your knowledge of the AdaGrad update rule, why do you think the updates would become very small? Would Adam have the same issue? Answer: [FILL THIS IN] Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # find batch/layer normalization and dropout useful. Store your best model in # # the best_model variable. # ################################################################################ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test your model!Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output ('X_train: ', (49000, 3, 32, 32)) ('y_train: ', (49000,)) ('X_val: ', (1000, 3, 32, 32)) ('y_val: ', (1000,)) ('X_test: ', (1000, 3, 32, 32)) ('y_test: ', (1000,)) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing affine_forward function: difference: 9.769847728806635e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_backward function: dx error: 5.399100368651805e-11 dw error: 9.904211865398145e-11 db error: 2.4122867568119087e-11 ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 5e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.999999798022158e-08 ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.2756349136310288e-12 ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print('Testing affine_relu_forward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward: dx error: 6.750562121603446e-11 dw error: 8.162015570444288e-11 db error: 7.826724021458994e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.999602749096233 dx error: 1.4021566006651672e-09 Testing softmax_loss: loss: 2.302545844500738 dx error: 9.384673161989355e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.22e-08 W2 relative error: 3.48e-10 b1 relative error: 6.55e-09 b2 relative error: 4.33e-10 Running numeric gradient check with reg = 0.7 W1 relative error: 8.18e-07 W2 relative error: 7.98e-08 b1 relative error: 1.09e-09 b2 relative error: 7.76e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## solver = Solver(model, data, update_rule='sgd', optim_config={ 'learning_rate': 1.1e-3, }, lr_decay=0.95, num_epochs=10, batch_size=100, print_every=100) solver.train() ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Running check with reg = 0 Initial loss: 2.3004790897684924 W1 relative error: 1.48e-07 W2 relative error: 2.21e-05 W3 relative error: 3.53e-07 b1 relative error: 5.38e-09 b2 relative error: 2.09e-09 b3 relative error: 5.80e-11 Running check with reg = 3.14 Initial loss: 7.052114776533016 W1 relative error: 3.90e-09 W2 relative error: 6.87e-08 W3 relative error: 2.13e-08 b1 relative error: 1.48e-08 b2 relative error: 1.72e-09 b3 relative error: 1.57e-10 ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1.1e-2 learning_rate = 6e-3 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output (Iteration 1 / 40) loss: 2.389972 (Epoch 0 / 20) train acc: 0.160000; val_acc: 0.101000 (Epoch 1 / 20) train acc: 0.260000; val_acc: 0.122000 (Epoch 2 / 20) train acc: 0.440000; val_acc: 0.163000 (Epoch 3 / 20) train acc: 0.460000; val_acc: 0.167000 (Epoch 4 / 20) train acc: 0.480000; val_acc: 0.180000 (Epoch 5 / 20) train acc: 0.640000; val_acc: 0.175000 (Iteration 11 / 40) loss: 1.088475 (Epoch 6 / 20) train acc: 0.720000; val_acc: 0.196000 (Epoch 7 / 20) train acc: 0.700000; val_acc: 0.187000 (Epoch 8 / 20) train acc: 0.780000; val_acc: 0.189000 (Epoch 9 / 20) train acc: 0.900000; val_acc: 0.206000 (Epoch 10 / 20) train acc: 0.880000; val_acc: 0.187000 (Iteration 21 / 40) loss: 0.587452 (Epoch 11 / 20) train acc: 0.920000; val_acc: 0.206000 (Epoch 12 / 20) train acc: 0.940000; val_acc: 0.192000 (Epoch 13 / 20) train acc: 0.940000; val_acc: 0.203000 (Epoch 14 / 20) train acc: 1.000000; val_acc: 0.203000 (Epoch 15 / 20) train acc: 0.980000; val_acc: 0.196000 (Iteration 31 / 40) loss: 0.251101 (Epoch 16 / 20) train acc: 0.980000; val_acc: 0.187000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.213000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.208000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.188000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.199000 ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-1 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output (Iteration 1 / 40) loss: 166.501707 (Epoch 0 / 20) train acc: 0.220000; val_acc: 0.116000 (Epoch 1 / 20) train acc: 0.240000; val_acc: 0.083000 (Epoch 2 / 20) train acc: 0.160000; val_acc: 0.104000 (Epoch 3 / 20) train acc: 0.520000; val_acc: 0.106000 (Epoch 4 / 20) train acc: 0.700000; val_acc: 0.131000 (Epoch 5 / 20) train acc: 0.700000; val_acc: 0.116000 (Iteration 11 / 40) loss: 4.414592 (Epoch 6 / 20) train acc: 0.840000; val_acc: 0.114000 (Epoch 7 / 20) train acc: 0.880000; val_acc: 0.108000 (Epoch 8 / 20) train acc: 0.900000; val_acc: 0.109000 (Epoch 9 / 20) train acc: 0.960000; val_acc: 0.114000 (Epoch 10 / 20) train acc: 0.980000; val_acc: 0.127000 (Iteration 21 / 40) loss: 0.261098 (Epoch 11 / 20) train acc: 1.000000; val_acc: 0.126000 (Epoch 12 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 13 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 14 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 15 / 20) train acc: 1.000000; val_acc: 0.125000 (Iteration 31 / 40) loss: 0.000594 (Epoch 16 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.125000 ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:Training a five-layer is more difficult, the reason can be explained. The five layer net need a bigger weight-scale so that the weight will not decrease to zero as there are five layers, a small weight scale will result in a zero weight. Also, there should be a higher learning rate since we initialized the weight with higher weight scale. In a nutshell, three layer network is more robust than the five layer network. Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output next_w error: 8.882347033505819e-09 velocity error: 4.269287743278663e-09 ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output running with sgd (Iteration 1 / 200) loss: 2.559978 (Epoch 0 / 5) train acc: 0.103000; val_acc: 0.108000 (Iteration 11 / 200) loss: 2.291086 (Iteration 21 / 200) loss: 2.153591 (Iteration 31 / 200) loss: 2.082693 (Epoch 1 / 5) train acc: 0.277000; val_acc: 0.242000 (Iteration 41 / 200) loss: 2.004171 (Iteration 51 / 200) loss: 2.010409 (Iteration 61 / 200) loss: 2.023753 (Iteration 71 / 200) loss: 2.026621 (Epoch 2 / 5) train acc: 0.352000; val_acc: 0.312000 (Iteration 81 / 200) loss: 1.807163 (Iteration 91 / 200) loss: 1.914256 (Iteration 101 / 200) loss: 1.920494 (Iteration 111 / 200) loss: 1.708877 (Epoch 3 / 5) train acc: 0.399000; val_acc: 0.316000 (Iteration 121 / 200) loss: 1.701111 (Iteration 131 / 200) loss: 1.769697 (Iteration 141 / 200) loss: 1.788898 (Iteration 151 / 200) loss: 1.816437 (Epoch 4 / 5) train acc: 0.426000; val_acc: 0.318000 (Iteration 161 / 200) loss: 1.632105 (Iteration 171 / 200) loss: 1.901174 (Iteration 181 / 200) loss: 1.543618 (Iteration 191 / 200) loss: 1.706021 (Epoch 5 / 5) train acc: 0.441000; val_acc: 0.324000 running with sgd_momentum (Iteration 1 / 200) loss: 3.153778 (Epoch 0 / 5) train acc: 0.105000; val_acc: 0.093000 (Iteration 11 / 200) loss: 2.145874 (Iteration 21 / 200) loss: 2.032562 (Iteration 31 / 200) loss: 1.985848 (Epoch 1 / 5) train acc: 0.311000; val_acc: 0.281000 (Iteration 41 / 200) loss: 1.882354 (Iteration 51 / 200) loss: 1.855372 (Iteration 61 / 200) loss: 1.649133 (Iteration 71 / 200) loss: 1.806432 (Epoch 2 / 5) train acc: 0.415000; val_acc: 0.324000 (Iteration 81 / 200) loss: 1.907840 (Iteration 91 / 200) loss: 1.510681 (Iteration 101 / 200) loss: 1.546872 (Iteration 111 / 200) loss: 1.512047 (Epoch 3 / 5) train acc: 0.434000; val_acc: 0.321000 (Iteration 121 / 200) loss: 1.677301 (Iteration 131 / 200) loss: 1.504686 (Iteration 141 / 200) loss: 1.633253 (Iteration 151 / 200) loss: 1.745081 (Epoch 4 / 5) train acc: 0.460000; val_acc: 0.353000 (Iteration 161 / 200) loss: 1.485411 (Iteration 171 / 200) loss: 1.610416 (Iteration 181 / 200) loss: 1.528331 (Iteration 191 / 200) loss: 1.447238 (Epoch 5 / 5) train acc: 0.515000; val_acc: 0.384000 ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output next_w error: 1.1395691798535431e-07 v error: 4.208314038113071e-09 m error: 4.214963193114416e-09 ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output running with adam (Iteration 1 / 200) loss: 3.476928 (Epoch 0 / 5) train acc: 0.143000; val_acc: 0.114000 (Iteration 11 / 200) loss: 2.089203 (Iteration 21 / 200) loss: 2.211850 (Iteration 31 / 200) loss: 1.786014 (Epoch 1 / 5) train acc: 0.393000; val_acc: 0.340000 (Iteration 41 / 200) loss: 1.743812 (Iteration 51 / 200) loss: 1.752165 (Iteration 61 / 200) loss: 2.095686 (Iteration 71 / 200) loss: 1.489003 (Epoch 2 / 5) train acc: 0.411000; val_acc: 0.357000 (Iteration 81 / 200) loss: 1.546641 (Iteration 91 / 200) loss: 1.412223 (Iteration 101 / 200) loss: 1.401821 (Iteration 111 / 200) loss: 1.521807 (Epoch 3 / 5) train acc: 0.494000; val_acc: 0.368000 (Iteration 121 / 200) loss: 1.237183 (Iteration 131 / 200) loss: 1.466022 (Iteration 141 / 200) loss: 1.284994 (Iteration 151 / 200) loss: 1.466689 (Epoch 4 / 5) train acc: 0.529000; val_acc: 0.383000 (Iteration 161 / 200) loss: 1.405442 (Iteration 171 / 200) loss: 1.270982 (Iteration 181 / 200) loss: 1.276394 (Iteration 191 / 200) loss: 1.170272 (Epoch 5 / 5) train acc: 0.582000; val_acc: 0.375000 running with rmsprop (Iteration 1 / 200) loss: 2.589166 (Epoch 0 / 5) train acc: 0.119000; val_acc: 0.146000 (Iteration 11 / 200) loss: 2.032921 (Iteration 21 / 200) loss: 1.897278 (Iteration 31 / 200) loss: 1.770793 (Epoch 1 / 5) train acc: 0.381000; val_acc: 0.320000 (Iteration 41 / 200) loss: 1.895732 (Iteration 51 / 200) loss: 1.681091 (Iteration 61 / 200) loss: 1.487204 (Iteration 71 / 200) loss: 1.629973 (Epoch 2 / 5) train acc: 0.429000; val_acc: 0.350000 (Iteration 81 / 200) loss: 1.506686 (Iteration 91 / 200) loss: 1.610742 (Iteration 101 / 200) loss: 1.486124 (Iteration 111 / 200) loss: 1.559454 (Epoch 3 / 5) train acc: 0.492000; val_acc: 0.359000 (Iteration 121 / 200) loss: 1.496860 (Iteration 131 / 200) loss: 1.531552 (Iteration 141 / 200) loss: 1.550195 (Iteration 151 / 200) loss: 1.657838 (Epoch 4 / 5) train acc: 0.533000; val_acc: 0.354000 (Iteration 161 / 200) loss: 1.603105 (Iteration 171 / 200) loss: 1.405372 (Iteration 181 / 200) loss: 1.503740 (Iteration 191 / 200) loss: 1.385278 (Epoch 5 / 5) train acc: 0.531000; val_acc: 0.374000 ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ candidate_model = FullyConnectedNet([110, 90, 80, 55, 35],use_batchnorm=True) solver = Solver(model, data, num_epochs=3, batch_size=100, update_rule='adam', lr_decay=0.95, optim_config={ 'learning_rate': 1.25e-3 }, verbose=True) solver.train() best_model=model ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output (Iteration 1 / 1470) loss: 1.255119 (Epoch 0 / 3) train acc: 0.510000; val_acc: 0.489000 (Iteration 11 / 1470) loss: 1.296680 (Iteration 21 / 1470) loss: 1.192920 (Iteration 31 / 1470) loss: 1.356403 (Iteration 41 / 1470) loss: 1.450162 (Iteration 51 / 1470) loss: 1.352361 (Iteration 61 / 1470) loss: 1.452622 (Iteration 71 / 1470) loss: 1.742419 (Iteration 81 / 1470) loss: 1.387779 (Iteration 91 / 1470) loss: 1.235722 (Iteration 101 / 1470) loss: 1.223463 (Iteration 111 / 1470) loss: 1.204351 (Iteration 121 / 1470) loss: 1.274440 (Iteration 131 / 1470) loss: 1.443667 (Iteration 141 / 1470) loss: 1.557244 (Iteration 151 / 1470) loss: 1.507762 (Iteration 161 / 1470) loss: 1.402859 (Iteration 171 / 1470) loss: 1.352709 (Iteration 181 / 1470) loss: 1.591012 (Iteration 191 / 1470) loss: 1.320171 (Iteration 201 / 1470) loss: 1.370028 (Iteration 211 / 1470) loss: 1.287614 (Iteration 221 / 1470) loss: 1.444363 (Iteration 231 / 1470) loss: 1.515921 (Iteration 241 / 1470) loss: 1.425471 (Iteration 251 / 1470) loss: 1.419631 (Iteration 261 / 1470) loss: 1.389137 (Iteration 271 / 1470) loss: 1.354317 (Iteration 281 / 1470) loss: 1.251382 (Iteration 291 / 1470) loss: 1.371885 (Iteration 301 / 1470) loss: 1.270136 (Iteration 311 / 1470) loss: 1.399744 (Iteration 321 / 1470) loss: 1.306225 (Iteration 331 / 1470) loss: 1.287472 (Iteration 341 / 1470) loss: 1.235509 (Iteration 351 / 1470) loss: 1.127496 (Iteration 361 / 1470) loss: 1.088960 (Iteration 371 / 1470) loss: 1.334902 (Iteration 381 / 1470) loss: 1.309166 (Iteration 391 / 1470) loss: 1.294806 (Iteration 401 / 1470) loss: 1.405872 (Iteration 411 / 1470) loss: 1.144848 (Iteration 421 / 1470) loss: 1.431228 (Iteration 431 / 1470) loss: 1.432815 (Iteration 441 / 1470) loss: 1.269809 (Iteration 451 / 1470) loss: 1.307780 (Iteration 461 / 1470) loss: 1.154359 (Iteration 471 / 1470) loss: 1.241469 (Iteration 481 / 1470) loss: 1.296518 (Epoch 1 / 3) train acc: 0.532000; val_acc: 0.474000 (Iteration 491 / 1470) loss: 1.380197 (Iteration 501 / 1470) loss: 1.071784 (Iteration 511 / 1470) loss: 1.572163 (Iteration 521 / 1470) loss: 1.239836 (Iteration 531 / 1470) loss: 1.384518 (Iteration 541 / 1470) loss: 1.228213 (Iteration 551 / 1470) loss: 1.096374 (Iteration 561 / 1470) loss: 1.470497 (Iteration 571 / 1470) loss: 1.250940 (Iteration 581 / 1470) loss: 1.353175 (Iteration 591 / 1470) loss: 1.145201 (Iteration 601 / 1470) loss: 1.168023 (Iteration 611 / 1470) loss: 1.228427 (Iteration 621 / 1470) loss: 1.403929 (Iteration 631 / 1470) loss: 1.159926 (Iteration 641 / 1470) loss: 1.226549 (Iteration 651 / 1470) loss: 1.178523 (Iteration 661 / 1470) loss: 1.035305 (Iteration 671 / 1470) loss: 1.346632 (Iteration 681 / 1470) loss: 1.395745 (Iteration 691 / 1470) loss: 1.229570 (Iteration 701 / 1470) loss: 1.338360 (Iteration 711 / 1470) loss: 1.251767 (Iteration 721 / 1470) loss: 1.246045 (Iteration 731 / 1470) loss: 1.112513 (Iteration 741 / 1470) loss: 1.424588 (Iteration 751 / 1470) loss: 1.440604 (Iteration 761 / 1470) loss: 1.387747 (Iteration 771 / 1470) loss: 1.140629 (Iteration 781 / 1470) loss: 1.224130 (Iteration 791 / 1470) loss: 1.346648 (Iteration 801 / 1470) loss: 1.325408 (Iteration 811 / 1470) loss: 1.324718 (Iteration 821 / 1470) loss: 1.170531 (Iteration 831 / 1470) loss: 1.346244 (Iteration 841 / 1470) loss: 1.361335 (Iteration 851 / 1470) loss: 1.349992 (Iteration 861 / 1470) loss: 1.231973 (Iteration 871 / 1470) loss: 1.179989 (Iteration 881 / 1470) loss: 1.220583 (Iteration 891 / 1470) loss: 1.288694 (Iteration 901 / 1470) loss: 1.223916 (Iteration 911 / 1470) loss: 1.423210 (Iteration 921 / 1470) loss: 1.072923 (Iteration 931 / 1470) loss: 1.313484 (Iteration 941 / 1470) loss: 1.343974 (Iteration 951 / 1470) loss: 1.124586 (Iteration 961 / 1470) loss: 1.212551 (Iteration 971 / 1470) loss: 1.357401 (Epoch 2 / 3) train acc: 0.537000; val_acc: 0.502000 (Iteration 981 / 1470) loss: 1.252190 (Iteration 991 / 1470) loss: 1.144704 (Iteration 1001 / 1470) loss: 1.086922 (Iteration 1011 / 1470) loss: 1.479917 (Iteration 1021 / 1470) loss: 1.339453 (Iteration 1031 / 1470) loss: 1.452438 (Iteration 1041 / 1470) loss: 1.269570 (Iteration 1051 / 1470) loss: 1.208998 (Iteration 1061 / 1470) loss: 1.061687 (Iteration 1071 / 1470) loss: 1.098533 (Iteration 1081 / 1470) loss: 1.183815 (Iteration 1091 / 1470) loss: 1.473674 (Iteration 1101 / 1470) loss: 1.447442 (Iteration 1111 / 1470) loss: 1.383107 (Iteration 1121 / 1470) loss: 1.283444 (Iteration 1131 / 1470) loss: 1.267458 (Iteration 1141 / 1470) loss: 1.433082 (Iteration 1151 / 1470) loss: 1.199462 (Iteration 1161 / 1470) loss: 1.148968 (Iteration 1171 / 1470) loss: 1.327744 (Iteration 1181 / 1470) loss: 1.288653 (Iteration 1191 / 1470) loss: 1.324469 (Iteration 1201 / 1470) loss: 1.350509 (Iteration 1211 / 1470) loss: 1.297907 (Iteration 1221 / 1470) loss: 1.103106 (Iteration 1231 / 1470) loss: 1.237737 (Iteration 1241 / 1470) loss: 1.096059 (Iteration 1251 / 1470) loss: 1.167147 (Iteration 1261 / 1470) loss: 1.179331 (Iteration 1271 / 1470) loss: 1.282875 (Iteration 1281 / 1470) loss: 1.131993 (Iteration 1291 / 1470) loss: 1.278347 (Iteration 1301 / 1470) loss: 1.286642 (Iteration 1311 / 1470) loss: 1.338922 (Iteration 1321 / 1470) loss: 1.237961 (Iteration 1331 / 1470) loss: 1.252740 (Iteration 1341 / 1470) loss: 1.099167 (Iteration 1351 / 1470) loss: 1.342164 (Iteration 1361 / 1470) loss: 1.190391 (Iteration 1371 / 1470) loss: 1.096161 (Iteration 1381 / 1470) loss: 1.192773 (Iteration 1391 / 1470) loss: 1.449880 (Iteration 1401 / 1470) loss: 1.211215 (Iteration 1411 / 1470) loss: 1.170545 (Iteration 1421 / 1470) loss: 1.126908 (Iteration 1431 / 1470) loss: 1.062201 (Iteration 1441 / 1470) loss: 1.204969 (Iteration 1451 / 1470) loss: 1.113733 (Iteration 1461 / 1470) loss: 1.078027 (Epoch 3 / 3) train acc: 0.587000; val_acc: 0.516000 ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output Validation set accuracy: 0.516 Test set accuracy: 0.496 ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures. In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive dout (derivative of loss with respect to outputs) and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch/Layer Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output _____no_output_____ ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around e-9 or less. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output _____no_output_____ ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around e-10 or less print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output _____no_output_____ ###Markdown ReLU activation: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be on the order of e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output _____no_output_____ ###Markdown ReLU activation: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be on the order of e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output _____no_output_____ ###Markdown Inline Question 1: We've only asked you to implement ReLU, but there are a number of different activation functions that one could use in neural networks, each with its pros and cons. In particular, an issue commonly seen with activation functions is getting zero (or close to zero) gradient flow during backpropagation. Which of the following activation functions have this problem? If you consider these functions in the one dimensional case, what types of input would lead to this behaviour?1. Sigmoid2. ReLU3. Leaky ReLU Answer:[FILL THIS IN] "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) # Relative error should be around e-10 or less print('Testing affine_relu_forward and affine_relu_backward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output _____no_output_____ ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be around the order of e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be close to 2.3 and dx error should be around e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output _____no_output_____ ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' # Errors should be around e-7 or less for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output _____no_output_____ ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch/layer normalization; we will add those features soon. Initial loss and gradient checkAs a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-7 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) # Most of the errors should be on the order of e-7 or smaller. # NOTE: It is fine however to see an error for W2 on the order of e-5 # for the check when reg = 0.0 for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output _____no_output_____ ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. In the following cell, tweak the **learning rate** and **weight initialization scale** to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 # Experiment with this! learning_rate = 1e-4 # Experiment with this! model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again, you will have to adjust the learning rate and weight initialization scale, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 2e-3 # Experiment with this! weight_scale = 1e-5 # Experiment with this! model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline Question 2: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? In particular, based on your experience, which network seemed more sensitive to the initialization scale? Why do you think that is the case? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochastic gradient descent. See the Momentum Update section at http://cs231n.github.io/neural-networks-3/sgd for more information.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) # Should see relative errors around e-8 or less print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 5e-3, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in solvers.items(): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label="loss_%s" % update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label="train_acc_%s" % update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label="val_acc_%s" % update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.**NOTE:** Please implement the _complete_ Adam update rule (with the bias correction mechanism), not the first simplified version mentioned in the course notes. [1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Inline Question 3:AdaGrad, like Adam, is a per-parameter optimization method that uses the following update rule:```cache += dw**2w += - learning_rate * dw / (np.sqrt(cache) + eps)```John notices that when he was training a network with AdaGrad that the updates became very small, and that his network was learning slowly. Using your knowledge of the AdaGrad update rule, why do you think the updates would become very small? Would Adam have the same issue? Answer: [FILL THIS IN] Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # find batch/layer normalization and dropout useful. Store your best model in # # the best_model variable. # ################################################################################ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test your model!Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output ('X_val: ', (1000, 3, 32, 32)) ('X_train: ', (49000, 3, 32, 32)) ('X_test: ', (1000, 3, 32, 32)) ('y_val: ', (1000,)) ('y_train: ', (49000,)) ('y_test: ', (1000,)) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing affine_forward function: difference: 9.76985004799e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_backward function: dx error: 6.98634850437e-11 dw error: 9.90402358399e-11 db error: 7.73697883449e-12 ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 5e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.99999979802e-08 ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.27563491363e-12 ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print('Testing affine_relu_forward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward: dx error: 3.14347471369e-11 dw error: 1.4861238458e-10 db error: 7.82672402146e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.9996027491 dx error: 1.40215660067e-09 Testing softmax_loss: loss: 2.3025458445 dx error: 9.38467316199e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.52e-08 W2 relative error: 3.37e-10 b1 relative error: 8.37e-09 b2 relative error: 8.99e-11 Running numeric gradient check with reg = 0.7 W1 relative error: 2.53e-07 W2 relative error: 7.98e-08 b1 relative error: 1.56e-08 b2 relative error: 9.09e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## solver = Solver(model, data, verbose=True) ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output _____no_output_____ ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 learning_rate = 1e-4 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-5 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ pass ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____ ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive derivative of loss with respect to outputs and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output ('y_val: ', (1000,)) ('y_test: ', (1000,)) ('X_test: ', (1000, 3, 32, 32)) ('y_train: ', (49000,)) ('X_train: ', (49000, 3, 32, 32)) ('X_val: ', (1000, 3, 32, 32)) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around 1e-9. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing affine_forward function: difference: 9.76984946819e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around 1e-10 print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_backward function: dx error: 5.39910036865e-11 dw error: 9.9042118654e-11 db error: 2.41228675681e-11 ###Markdown ReLU layer: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be around 5e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.99999979802e-08 ###Markdown ReLU layer: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be around 3e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.27563491363e-12 ###Markdown "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) print('Testing affine_relu_forward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward: dx error: 2.29957917731e-11 dw error: 8.16201110576e-11 db error: 7.82672402146e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be 1e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be 2.3 and dx error should be 1e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.9996027491 dx error: 1.40215660067e-09 Testing softmax_loss: loss: 2.3025458445 dx error: 9.38467316199e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Testing initialization ... Testing test-time forward pass ... Testing training loss (no regularization) Running numeric gradient check with reg = 0.0 W1 relative error: 1.83e-08 W2 relative error: 3.12e-10 b1 relative error: 9.83e-09 b2 relative error: 4.33e-10 Running numeric gradient check with reg = 0.7 W1 relative error: 2.53e-07 W2 relative error: 2.85e-08 b1 relative error: 1.56e-08 b2 relative error: 7.76e-10 ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## model.reg = 1e-2 solver = Solver(model, data, update_rule='sgd', optim_config={ 'learning_rate': 2e-3, }, lr_decay=0.9, num_epochs=10, batch_size=100, print_every=100) solver.train() print('The best accuracy on the validation set is ', solver.best_val_acc) ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-6 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output Running check with reg = 0 Initial loss: 2.30047908977 W1 relative error: 1.48e-07 W2 relative error: 2.21e-05 W3 relative error: 3.53e-07 b1 relative error: 5.38e-09 b2 relative error: 2.09e-09 b3 relative error: 5.80e-11 Running check with reg = 3.14 Initial loss: 7.05211477653 W1 relative error: 7.36e-09 W2 relative error: 6.87e-08 W3 relative error: 3.48e-08 b1 relative error: 1.48e-08 b2 relative error: 1.72e-09 b3 relative error: 1.80e-10 ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. You will need to tweak the learning rate and initialization scale, but you should be able to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 learning_rate = 1e-2 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output (Iteration 1 / 40) loss: 2.363364 (Epoch 0 / 20) train acc: 0.180000; val_acc: 0.108000 (Epoch 1 / 20) train acc: 0.320000; val_acc: 0.127000 (Epoch 2 / 20) train acc: 0.440000; val_acc: 0.172000 (Epoch 3 / 20) train acc: 0.500000; val_acc: 0.184000 (Epoch 4 / 20) train acc: 0.540000; val_acc: 0.181000 (Epoch 5 / 20) train acc: 0.740000; val_acc: 0.190000 (Iteration 11 / 40) loss: 0.839976 (Epoch 6 / 20) train acc: 0.740000; val_acc: 0.187000 (Epoch 7 / 20) train acc: 0.740000; val_acc: 0.183000 (Epoch 8 / 20) train acc: 0.820000; val_acc: 0.177000 (Epoch 9 / 20) train acc: 0.860000; val_acc: 0.200000 (Epoch 10 / 20) train acc: 0.920000; val_acc: 0.191000 (Iteration 21 / 40) loss: 0.337174 (Epoch 11 / 20) train acc: 0.960000; val_acc: 0.189000 (Epoch 12 / 20) train acc: 0.940000; val_acc: 0.180000 (Epoch 13 / 20) train acc: 1.000000; val_acc: 0.199000 (Epoch 14 / 20) train acc: 1.000000; val_acc: 0.199000 (Epoch 15 / 20) train acc: 1.000000; val_acc: 0.195000 (Iteration 31 / 40) loss: 0.075911 (Epoch 16 / 20) train acc: 1.000000; val_acc: 0.182000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.201000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.207000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.185000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.192000 ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 1e-3 weight_scale = 1e-1 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output (Iteration 1 / 40) loss: 166.501707 (Epoch 0 / 20) train acc: 0.220000; val_acc: 0.116000 (Epoch 1 / 20) train acc: 0.240000; val_acc: 0.083000 (Epoch 2 / 20) train acc: 0.160000; val_acc: 0.104000 (Epoch 3 / 20) train acc: 0.520000; val_acc: 0.106000 (Epoch 4 / 20) train acc: 0.700000; val_acc: 0.131000 (Epoch 5 / 20) train acc: 0.700000; val_acc: 0.116000 (Iteration 11 / 40) loss: 4.414592 (Epoch 6 / 20) train acc: 0.840000; val_acc: 0.114000 (Epoch 7 / 20) train acc: 0.880000; val_acc: 0.108000 (Epoch 8 / 20) train acc: 0.900000; val_acc: 0.109000 (Epoch 9 / 20) train acc: 0.960000; val_acc: 0.114000 (Epoch 10 / 20) train acc: 0.980000; val_acc: 0.127000 (Iteration 21 / 40) loss: 0.261098 (Epoch 11 / 20) train acc: 1.000000; val_acc: 0.126000 (Epoch 12 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 13 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 14 / 20) train acc: 1.000000; val_acc: 0.124000 (Epoch 15 / 20) train acc: 1.000000; val_acc: 0.125000 (Iteration 31 / 40) loss: 0.000594 (Epoch 16 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 17 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 18 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 19 / 20) train acc: 1.000000; val_acc: 0.125000 (Epoch 20 / 20) train acc: 1.000000; val_acc: 0.125000 ###Markdown Inline question: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? Answer:* more sensitive to weight initialization and learning rate Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochstic gradient descent.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than 1e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate':1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.[1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation; you should see errors less than 1e-7 from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation; you should see errors around 1e-7 or less from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # batch normalization and dropout useful. Store your best model in the # # best_model variable. # ################################################################################ best_val_acc = -1 for learning_rate in [0.05]: for d_o in [0.75]: model = FullyConnectedNet([500], weight_scale=1e-1, dtype=np.float64, dropout=d_o, use_batchnorm=True) solver = Solver(model, data, print_every=100, num_epochs=10, batch_size=100, update_rule='adam', optim_config={ 'learning_rate': 1e-2, } ) solver.train() if solver.best_val_acc > best_val_acc: best_val_acc = solver.best_val_acc best_model = model print('learning_rate: %f, drop_out: %f, val_acc: %f, best_acc: %f' % (learning_rate, d_o, solver.best_val_acc, best_val_acc)) ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output (Iteration 1 / 4900) loss: 2.960609 (Epoch 0 / 10) train acc: 0.155000; val_acc: 0.174000 (Iteration 101 / 4900) loss: 1.897698 (Iteration 201 / 4900) loss: 1.745199 (Iteration 301 / 4900) loss: 1.779455 (Iteration 401 / 4900) loss: 1.623549 (Epoch 1 / 10) train acc: 0.463000; val_acc: 0.479000 (Iteration 501 / 4900) loss: 1.751377 (Iteration 601 / 4900) loss: 1.347028 (Iteration 701 / 4900) loss: 1.556822 (Iteration 801 / 4900) loss: 1.437655 (Iteration 901 / 4900) loss: 1.510858 (Epoch 2 / 10) train acc: 0.506000; val_acc: 0.489000 (Iteration 1001 / 4900) loss: 1.486659 (Iteration 1101 / 4900) loss: 1.255050 (Iteration 1201 / 4900) loss: 1.255031 (Iteration 1301 / 4900) loss: 1.484685 (Iteration 1401 / 4900) loss: 1.473559 (Epoch 3 / 10) train acc: 0.539000; val_acc: 0.482000 (Iteration 1501 / 4900) loss: 1.631843 (Iteration 1601 / 4900) loss: 1.383923 (Iteration 1701 / 4900) loss: 1.258491 ###Markdown Test you modelRun your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output Validation set accuracy: 0.521 Test set accuracy: 0.508 ###Markdown Fully-Connected Neural NetsIn the previous homework you implemented a fully-connected two-layer neural network on CIFAR-10. The implementation was simple but not very modular since the loss and gradient were computed in a single monolithic function. This is manageable for a simple two-layer network, but would become impractical as we move to bigger models. Ideally we want to build networks using a more modular design so that we can implement different layer types in isolation and then snap them together into models with different architectures.In this exercise we will implement fully-connected networks using a more modular approach. For each layer we will implement a `forward` and a `backward` function. The `forward` function will receive inputs, weights, and other parameters and will return both an output and a `cache` object storing data needed for the backward pass, like this:```pythondef layer_forward(x, w): """ Receive inputs x and weights w """ Do some computations ... z = ... some intermediate value Do some more computations ... out = the output cache = (x, w, z, out) Values we need to compute gradients return out, cache```The backward pass will receive upstream derivatives and the `cache` object, and will return gradients with respect to the inputs and weights, like this:```pythondef layer_backward(dout, cache): """ Receive dout (derivative of loss with respect to outputs) and cache, and compute derivative with respect to inputs. """ Unpack cache values x, w, z, out = cache Use values in cache to compute derivatives dx = Derivative of loss with respect to x dw = Derivative of loss with respect to w return dx, dw```After implementing a bunch of layers this way, we will be able to easily combine them to build classifiers with different architectures.In addition to implementing fully-connected networks of arbitrary depth, we will also explore different update rules for optimization, and introduce Dropout as a regularizer and Batch/Layer Normalization as a tool to more efficiently optimize deep networks. ###Code # As usual, a bit of setup from __future__ import print_function import time import numpy as np import matplotlib.pyplot as plt from cs231n.classifiers.fc_net import * from cs231n.data_utils import get_CIFAR10_data from cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array from cs231n.solver import Solver %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython %load_ext autoreload %autoreload 2 def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Load the (preprocessed) CIFAR10 data. %reload_ext autoreload data = get_CIFAR10_data() for k, v in list(data.items()): print(('%s: ' % k, v.shape)) ###Output ('X_train: ', (49000, 3, 32, 32)) ('y_train: ', (49000,)) ('X_val: ', (1000, 3, 32, 32)) ('y_val: ', (1000,)) ('X_test: ', (1000, 3, 32, 32)) ('y_test: ', (1000,)) ###Markdown Affine layer: fowardOpen the file `cs231n/layers.py` and implement the `affine_forward` function.Once you are done you can test your implementaion by running the following: ###Code # Test the affine_forward function num_inputs = 2 input_shape = (4, 5, 6) output_dim = 3 input_size = num_inputs * np.prod(input_shape) weight_size = output_dim * np.prod(input_shape) x = np.linspace(-0.1, 0.5, num=input_size).reshape(num_inputs, *input_shape) w = np.linspace(-0.2, 0.3, num=weight_size).reshape(np.prod(input_shape), output_dim) b = np.linspace(-0.3, 0.1, num=output_dim) out, _ = affine_forward(x, w, b) correct_out = np.array([[ 1.49834967, 1.70660132, 1.91485297], [ 3.25553199, 3.5141327, 3.77273342]]) # Compare your output with ours. The error should be around e-9 or less. print('Testing affine_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing affine_forward function: difference: 9.769849468192957e-10 ###Markdown Affine layer: backwardNow implement the `affine_backward` function and test your implementation using numeric gradient checking. ###Code # Test the affine_backward function np.random.seed(231) x = np.random.randn(10, 2, 3) w = np.random.randn(6, 5) b = np.random.randn(5) dout = np.random.randn(10, 5) dx_num = eval_numerical_gradient_array(lambda x: affine_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_forward(x, w, b)[0], b, dout) _, cache = affine_forward(x, w, b) dx, dw, db = affine_backward(dout, cache) # The error should be around e-10 or less print('Testing affine_backward function:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_backward function: dx error: 5.399100368651805e-11 dw error: 9.904211865398145e-11 db error: 2.4122867568119087e-11 ###Markdown ReLU activation: forwardImplement the forward pass for the ReLU activation function in the `relu_forward` function and test your implementation using the following: ###Code # Test the relu_forward function x = np.linspace(-0.5, 0.5, num=12).reshape(3, 4) out, _ = relu_forward(x) correct_out = np.array([[ 0., 0., 0., 0., ], [ 0., 0., 0.04545455, 0.13636364,], [ 0.22727273, 0.31818182, 0.40909091, 0.5, ]]) # Compare your output with ours. The error should be on the order of e-8 print('Testing relu_forward function:') print('difference: ', rel_error(out, correct_out)) ###Output Testing relu_forward function: difference: 4.999999798022158e-08 ###Markdown ReLU activation: backwardNow implement the backward pass for the ReLU activation function in the `relu_backward` function and test your implementation using numeric gradient checking: ###Code np.random.seed(231) x = np.random.randn(10, 10) dout = np.random.randn(*x.shape) dx_num = eval_numerical_gradient_array(lambda x: relu_forward(x)[0], x, dout) _, cache = relu_forward(x) dx = relu_backward(dout, cache) # The error should be on the order of e-12 print('Testing relu_backward function:') print('dx error: ', rel_error(dx_num, dx)) ###Output Testing relu_backward function: dx error: 3.2756349136310288e-12 ###Markdown Inline Question 1: We've only asked you to implement ReLU, but there are a number of different activation functions that one could use in neural networks, each with its pros and cons. In particular, an issue commonly seen with activation functions is getting zero (or close to zero) gradient flow during backpropagation. Which of the following activation functions have this problem? If you consider these functions in the one dimensional case, what types of input would lead to this behaviour?1. Sigmoid2. ReLU3. Leaky ReLU Answer:[FILL THIS IN] "Sandwich" layersThere are some common patterns of layers that are frequently used in neural nets. For example, affine layers are frequently followed by a ReLU nonlinearity. To make these common patterns easy, we define several convenience layers in the file `cs231n/layer_utils.py`.For now take a look at the `affine_relu_forward` and `affine_relu_backward` functions, and run the following to numerically gradient check the backward pass: ###Code from cs231n.layer_utils import affine_relu_forward, affine_relu_backward np.random.seed(231) x = np.random.randn(2, 3, 4) w = np.random.randn(12, 10) b = np.random.randn(10) dout = np.random.randn(2, 10) out, cache = affine_relu_forward(x, w, b) dx, dw, db = affine_relu_backward(dout, cache) dx_num = eval_numerical_gradient_array(lambda x: affine_relu_forward(x, w, b)[0], x, dout) dw_num = eval_numerical_gradient_array(lambda w: affine_relu_forward(x, w, b)[0], w, dout) db_num = eval_numerical_gradient_array(lambda b: affine_relu_forward(x, w, b)[0], b, dout) # Relative error should be around e-10 or less print('Testing affine_relu_forward and affine_relu_backward:') print('dx error: ', rel_error(dx_num, dx)) print('dw error: ', rel_error(dw_num, dw)) print('db error: ', rel_error(db_num, db)) ###Output Testing affine_relu_forward and affine_relu_backward: dx error: 2.299579177309368e-11 dw error: 8.162011105764925e-11 db error: 7.826724021458994e-12 ###Markdown Loss layers: Softmax and SVMYou implemented these loss functions in the last assignment, so we'll give them to you for free here. You should still make sure you understand how they work by looking at the implementations in `cs231n/layers.py`.You can make sure that the implementations are correct by running the following: ###Code np.random.seed(231) num_classes, num_inputs = 10, 50 x = 0.001 * np.random.randn(num_inputs, num_classes) y = np.random.randint(num_classes, size=num_inputs) dx_num = eval_numerical_gradient(lambda x: svm_loss(x, y)[0], x, verbose=False) loss, dx = svm_loss(x, y) # Test svm_loss function. Loss should be around 9 and dx error should be around the order of e-9 print('Testing svm_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) dx_num = eval_numerical_gradient(lambda x: softmax_loss(x, y)[0], x, verbose=False) loss, dx = softmax_loss(x, y) # Test softmax_loss function. Loss should be close to 2.3 and dx error should be around e-8 print('\nTesting softmax_loss:') print('loss: ', loss) print('dx error: ', rel_error(dx_num, dx)) ###Output Testing svm_loss: loss: 8.999602749096233 dx error: 1.4021566006651672e-09 Testing softmax_loss: loss: 2.302545844500738 dx error: 9.384673161989355e-09 ###Markdown Two-layer networkIn the previous assignment you implemented a two-layer neural network in a single monolithic class. Now that you have implemented modular versions of the necessary layers, you will reimplement the two layer network using these modular implementations.Open the file `cs231n/classifiers/fc_net.py` and complete the implementation of the `TwoLayerNet` class. This class will serve as a model for the other networks you will implement in this assignment, so read through it to make sure you understand the API. You can run the cell below to test your implementation. ###Code np.random.seed(231) N, D, H, C = 3, 5, 50, 7 X = np.random.randn(N, D) y = np.random.randint(C, size=N) std = 1e-3 model = TwoLayerNet(input_dim=D, hidden_dim=H, num_classes=C, weight_scale=std) print('Testing initialization ... ') W1_std = abs(model.params['W1'].std() - std) b1 = model.params['b1'] W2_std = abs(model.params['W2'].std() - std) b2 = model.params['b2'] assert W1_std < std / 10, 'First layer weights do not seem right' assert np.all(b1 == 0), 'First layer biases do not seem right' assert W2_std < std / 10, 'Second layer weights do not seem right' assert np.all(b2 == 0), 'Second layer biases do not seem right' print('Testing test-time forward pass ... ') model.params['W1'] = np.linspace(-0.7, 0.3, num=D*H).reshape(D, H) model.params['b1'] = np.linspace(-0.1, 0.9, num=H) model.params['W2'] = np.linspace(-0.3, 0.4, num=H*C).reshape(H, C) model.params['b2'] = np.linspace(-0.9, 0.1, num=C) X = np.linspace(-5.5, 4.5, num=N*D).reshape(D, N).T scores = model.loss(X) correct_scores = np.asarray( [[11.53165108, 12.2917344, 13.05181771, 13.81190102, 14.57198434, 15.33206765, 16.09215096], [12.05769098, 12.74614105, 13.43459113, 14.1230412, 14.81149128, 15.49994135, 16.18839143], [12.58373087, 13.20054771, 13.81736455, 14.43418138, 15.05099822, 15.66781506, 16.2846319 ]]) scores_diff = np.abs(scores - correct_scores).sum() assert scores_diff < 1e-6, 'Problem with test-time forward pass' print('Testing training loss (no regularization)') y = np.asarray([0, 5, 1]) loss, grads = model.loss(X, y) correct_loss = 3.4702243556 assert abs(loss - correct_loss) < 1e-10, 'Problem with training-time loss' model.reg = 1.0 loss, grads = model.loss(X, y) correct_loss = 26.5948426952 assert abs(loss - correct_loss) < 1e-10, 'Problem with regularization loss' # Errors should be around e-7 or less for reg in [0.0, 0.7]: print('Running numeric gradient check with reg = ', reg) model.reg = reg loss, grads = model.loss(X, y) for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output _____no_output_____ ###Markdown SolverIn the previous assignment, the logic for training models was coupled to the models themselves. Following a more modular design, for this assignment we have split the logic for training models into a separate class.Open the file `cs231n/solver.py` and read through it to familiarize yourself with the API. After doing so, use a `Solver` instance to train a `TwoLayerNet` that achieves at least `50%` accuracy on the validation set. ###Code model = TwoLayerNet() solver = None ############################################################################## # TODO: Use a Solver instance to train a TwoLayerNet that achieves at least # # 50% accuracy on the validation set. # ############################################################################## pass ############################################################################## # END OF YOUR CODE # ############################################################################## # Run this cell to visualize training loss and train / val accuracy plt.subplot(2, 1, 1) plt.title('Training loss') plt.plot(solver.loss_history, 'o') plt.xlabel('Iteration') plt.subplot(2, 1, 2) plt.title('Accuracy') plt.plot(solver.train_acc_history, '-o', label='train') plt.plot(solver.val_acc_history, '-o', label='val') plt.plot([0.5] * len(solver.val_acc_history), 'k--') plt.xlabel('Epoch') plt.legend(loc='lower right') plt.gcf().set_size_inches(15, 12) plt.show() ###Output _____no_output_____ ###Markdown Multilayer networkNext you will implement a fully-connected network with an arbitrary number of hidden layers.Read through the `FullyConnectedNet` class in the file `cs231n/classifiers/fc_net.py`.Implement the initialization, the forward pass, and the backward pass. For the moment don't worry about implementing dropout or batch/layer normalization; we will add those features soon. Initial loss and gradient check As a sanity check, run the following to check the initial loss and to gradient check the network both with and without regularization. Do the initial losses seem reasonable?For gradient checking, you should expect to see errors around 1e-7 or less. ###Code np.random.seed(231) N, D, H1, H2, C = 2, 15, 20, 30, 10 X = np.random.randn(N, D) y = np.random.randint(C, size=(N,)) for reg in [0, 3.14]: print('Running check with reg = ', reg) model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C, reg=reg, weight_scale=5e-2, dtype=np.float64) loss, grads = model.loss(X, y) print('Initial loss: ', loss) # Most of the errors should be on the order of e-7 or smaller. # NOTE: It is fine however to see an error for W2 on the order of e-5 # for the check when reg = 0.0 for name in sorted(grads): f = lambda _: model.loss(X, y)[0] grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5) print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name]))) ###Output _____no_output_____ ###Markdown As another sanity check, make sure you can overfit a small dataset of 50 images. First we will try a three-layer network with 100 units in each hidden layer. In the following cell, tweak the learning rate and initialization scale to overfit and achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a three-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } weight_scale = 1e-2 learning_rate = 1e-4 model = FullyConnectedNet([100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Now try to use a five-layer network with 100 units on each layer to overfit 50 training examples. Again you will have to adjust the learning rate and weight initialization, but you should be able to achieve 100% training accuracy within 20 epochs. ###Code # TODO: Use a five-layer Net to overfit 50 training examples by # tweaking just the learning rate and initialization scale. num_train = 50 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } learning_rate = 2e-3 weight_scale = 1e-5 model = FullyConnectedNet([100, 100, 100, 100], weight_scale=weight_scale, dtype=np.float64) solver = Solver(model, small_data, print_every=10, num_epochs=20, batch_size=25, update_rule='sgd', optim_config={ 'learning_rate': learning_rate, } ) solver.train() plt.plot(solver.loss_history, 'o') plt.title('Training loss history') plt.xlabel('Iteration') plt.ylabel('Training loss') plt.show() ###Output _____no_output_____ ###Markdown Inline Question 2: Did you notice anything about the comparative difficulty of training the three-layer net vs training the five layer net? In particular, based on your experience, which network seemed more sensitive to the initialization scale? Why do you think that is the case? Answer:[FILL THIS IN] Update rulesSo far we have used vanilla stochastic gradient descent (SGD) as our update rule. More sophisticated update rules can make it easier to train deep networks. We will implement a few of the most commonly used update rules and compare them to vanilla SGD. SGD+MomentumStochastic gradient descent with momentum is a widely used update rule that tends to make deep networks converge faster than vanilla stochastic gradient descent. See the Momentum Update section at http://cs231n.github.io/neural-networks-3/sgd for more information.Open the file `cs231n/optim.py` and read the documentation at the top of the file to make sure you understand the API. Implement the SGD+momentum update rule in the function `sgd_momentum` and run the following to check your implementation. You should see errors less than e-8. ###Code from cs231n.optim import sgd_momentum N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) v = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-3, 'velocity': v} next_w, _ = sgd_momentum(w, dw, config=config) expected_next_w = np.asarray([ [ 0.1406, 0.20738947, 0.27417895, 0.34096842, 0.40775789], [ 0.47454737, 0.54133684, 0.60812632, 0.67491579, 0.74170526], [ 0.80849474, 0.87528421, 0.94207368, 1.00886316, 1.07565263], [ 1.14244211, 1.20923158, 1.27602105, 1.34281053, 1.4096 ]]) expected_velocity = np.asarray([ [ 0.5406, 0.55475789, 0.56891579, 0.58307368, 0.59723158], [ 0.61138947, 0.62554737, 0.63970526, 0.65386316, 0.66802105], [ 0.68217895, 0.69633684, 0.71049474, 0.72465263, 0.73881053], [ 0.75296842, 0.76712632, 0.78128421, 0.79544211, 0.8096 ]]) # Should see relative errors around e-8 or less print('next_w error: ', rel_error(next_w, expected_next_w)) print('velocity error: ', rel_error(expected_velocity, config['velocity'])) ###Output _____no_output_____ ###Markdown Once you have done so, run the following to train a six-layer network with both SGD and SGD+momentum. You should see the SGD+momentum update rule converge faster. ###Code num_train = 4000 small_data = { 'X_train': data['X_train'][:num_train], 'y_train': data['y_train'][:num_train], 'X_val': data['X_val'], 'y_val': data['y_val'], } solvers = {} for update_rule in ['sgd', 'sgd_momentum']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': 1e-2, }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown RMSProp and AdamRMSProp [1] and Adam [2] are update rules that set per-parameter learning rates by using a running average of the second moments of gradients.In the file `cs231n/optim.py`, implement the RMSProp update rule in the `rmsprop` function and implement the Adam update rule in the `adam` function, and check your implementations using the tests below.**NOTE:** Please implement the _complete_ Adam update rule (with the bias correction mechanism), not the first simplified version mentioned in the course notes. [1] Tijmen Tieleman and Geoffrey Hinton. "Lecture 6.5-rmsprop: Divide the gradient by a running average of its recent magnitude." COURSERA: Neural Networks for Machine Learning 4 (2012).[2] Diederik Kingma and Jimmy Ba, "Adam: A Method for Stochastic Optimization", ICLR 2015. ###Code # Test RMSProp implementation from cs231n.optim import rmsprop N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) cache = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'cache': cache} next_w, _ = rmsprop(w, dw, config=config) expected_next_w = np.asarray([ [-0.39223849, -0.34037513, -0.28849239, -0.23659121, -0.18467247], [-0.132737, -0.08078555, -0.02881884, 0.02316247, 0.07515774], [ 0.12716641, 0.17918792, 0.23122175, 0.28326742, 0.33532447], [ 0.38739248, 0.43947102, 0.49155973, 0.54365823, 0.59576619]]) expected_cache = np.asarray([ [ 0.5976, 0.6126277, 0.6277108, 0.64284931, 0.65804321], [ 0.67329252, 0.68859723, 0.70395734, 0.71937285, 0.73484377], [ 0.75037008, 0.7659518, 0.78158892, 0.79728144, 0.81302936], [ 0.82883269, 0.84469141, 0.86060554, 0.87657507, 0.8926 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('cache error: ', rel_error(expected_cache, config['cache'])) # Test Adam implementation from cs231n.optim import adam N, D = 4, 5 w = np.linspace(-0.4, 0.6, num=N*D).reshape(N, D) dw = np.linspace(-0.6, 0.4, num=N*D).reshape(N, D) m = np.linspace(0.6, 0.9, num=N*D).reshape(N, D) v = np.linspace(0.7, 0.5, num=N*D).reshape(N, D) config = {'learning_rate': 1e-2, 'm': m, 'v': v, 't': 5} next_w, _ = adam(w, dw, config=config) expected_next_w = np.asarray([ [-0.40094747, -0.34836187, -0.29577703, -0.24319299, -0.19060977], [-0.1380274, -0.08544591, -0.03286534, 0.01971428, 0.0722929], [ 0.1248705, 0.17744702, 0.23002243, 0.28259667, 0.33516969], [ 0.38774145, 0.44031188, 0.49288093, 0.54544852, 0.59801459]]) expected_v = np.asarray([ [ 0.69966, 0.68908382, 0.67851319, 0.66794809, 0.65738853,], [ 0.64683452, 0.63628604, 0.6257431, 0.61520571, 0.60467385,], [ 0.59414753, 0.58362676, 0.57311152, 0.56260183, 0.55209767,], [ 0.54159906, 0.53110598, 0.52061845, 0.51013645, 0.49966, ]]) expected_m = np.asarray([ [ 0.48, 0.49947368, 0.51894737, 0.53842105, 0.55789474], [ 0.57736842, 0.59684211, 0.61631579, 0.63578947, 0.65526316], [ 0.67473684, 0.69421053, 0.71368421, 0.73315789, 0.75263158], [ 0.77210526, 0.79157895, 0.81105263, 0.83052632, 0.85 ]]) # You should see relative errors around e-7 or less print('next_w error: ', rel_error(expected_next_w, next_w)) print('v error: ', rel_error(expected_v, config['v'])) print('m error: ', rel_error(expected_m, config['m'])) ###Output _____no_output_____ ###Markdown Once you have debugged your RMSProp and Adam implementations, run the following to train a pair of deep networks using these new update rules: ###Code learning_rates = {'rmsprop': 1e-4, 'adam': 1e-3} for update_rule in ['adam', 'rmsprop']: print('running with ', update_rule) model = FullyConnectedNet([100, 100, 100, 100, 100], weight_scale=5e-2) solver = Solver(model, small_data, num_epochs=5, batch_size=100, update_rule=update_rule, optim_config={ 'learning_rate': learning_rates[update_rule] }, verbose=True) solvers[update_rule] = solver solver.train() print() plt.subplot(3, 1, 1) plt.title('Training loss') plt.xlabel('Iteration') plt.subplot(3, 1, 2) plt.title('Training accuracy') plt.xlabel('Epoch') plt.subplot(3, 1, 3) plt.title('Validation accuracy') plt.xlabel('Epoch') for update_rule, solver in list(solvers.items()): plt.subplot(3, 1, 1) plt.plot(solver.loss_history, 'o', label=update_rule) plt.subplot(3, 1, 2) plt.plot(solver.train_acc_history, '-o', label=update_rule) plt.subplot(3, 1, 3) plt.plot(solver.val_acc_history, '-o', label=update_rule) for i in [1, 2, 3]: plt.subplot(3, 1, i) plt.legend(loc='upper center', ncol=4) plt.gcf().set_size_inches(15, 15) plt.show() ###Output _____no_output_____ ###Markdown Inline Question 3:AdaGrad, like Adam, is a per-parameter optimization method that uses the following update rule:```cache += dw**2w += - learning_rate * dw / (np.sqrt(cache) + eps)```John notices that when he was training a network with AdaGrad that the updates became very small, and that his network was learning slowly. Using your knowledge of the AdaGrad update rule, why do you think the updates would become very small? Would Adam have the same issue? Answer: Train a good model!Train the best fully-connected model that you can on CIFAR-10, storing your best model in the `best_model` variable. We require you to get at least 50% accuracy on the validation set using a fully-connected net.If you are careful it should be possible to get accuracies above 55%, but we don't require it for this part and won't assign extra credit for doing so. Later in the assignment we will ask you to train the best convolutional network that you can on CIFAR-10, and we would prefer that you spend your effort working on convolutional nets rather than fully-connected nets.You might find it useful to complete the `BatchNormalization.ipynb` and `Dropout.ipynb` notebooks before completing this part, since those techniques can help you train powerful models. ###Code best_model = None ################################################################################ # TODO: Train the best FullyConnectedNet that you can on CIFAR-10. You might # # find batch/layer normalization and dropout useful. Store your best model in # # the best_model variable. # ################################################################################ pass ################################################################################ # END OF YOUR CODE # ################################################################################ ###Output _____no_output_____ ###Markdown Test your model!Run your best model on the validation and test sets. You should achieve above 50% accuracy on the validation set. ###Code y_test_pred = np.argmax(best_model.loss(data['X_test']), axis=1) y_val_pred = np.argmax(best_model.loss(data['X_val']), axis=1) print('Validation set accuracy: ', (y_val_pred == data['y_val']).mean()) print('Test set accuracy: ', (y_test_pred == data['y_test']).mean()) ###Output _____no_output_____
notebooks/individual-dashboards/erroranalysis-dashboard/erroranalysis-dashboard-regression-boston-housing.ipynb
###Markdown Analyze Errors and Explore Interpretability of ModelsThis notebook demonstrates how to use the Responsible AI Widget's Error Analysis dashboard to understand a model trained on the regression boston housing dataset. The goal of this sample notebook is to predict housing prices with scikit-learn and explore model errors and explanations:1. Train an SVM classification model using Scikit-learn2. Run Interpret-Community's 'explain_model' globally and locally to generate model explanations.3. Visualize model errors and global and local explanations with the Error Analysis visualization dashboard. Install Required Packages ###Code # %pip install --upgrade interpret-community # %pip install --upgrade raiwidgets ###Output _____no_output_____ ###Markdown Import required packages ###Code from sklearn.datasets import load_boston from sklearn import svm # Imports for SHAP MimicExplainer with LightGBM surrogate model from interpret.ext.blackbox import MimicExplainer from interpret.ext.glassbox import LGBMExplainableModel ###Output _____no_output_____ ###Markdown Load the wine data ###Code boston = load_boston() X = boston['data'] y = boston['target'] feature_names = boston['feature_names'] # Split data into train and test from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0) ###Output _____no_output_____ ###Markdown Train a SVM classification model ###Code clf = svm.SVR(gamma=0.001, C=100.) model = clf.fit(X_train, y_train) # Notice the model makes a fair amount of error print("average abs error on test dataset: " + str(sum(abs(model.predict(X_test) - y_test))/y_test.shape[0])) ###Output _____no_output_____ ###Markdown Load simple ErrorAnalysis view without explanations ###Code from raiwidgets import ErrorAnalysisDashboard predictions = model.predict(X_test) ErrorAnalysisDashboard(dataset=X_test, true_y=y_test, features=feature_names, pred_y=predictions, model_task='regression') ###Output _____no_output_____ ###Markdown Train a surrogate model to explain the original blackbox model ###Code from interpret_community.common.constants import ModelTask # Train the LightGBM surrogate model using MimicExplaner model_task = ModelTask.Regression explainer = MimicExplainer(model, X_train, LGBMExplainableModel, augment_data=True, max_num_of_augmentations=10, features=feature_names, model_task=model_task) ###Output _____no_output_____ ###Markdown Generate global explanationsExplain overall model predictions (global explanation) ###Code # Passing in test dataset for evaluation examples - note it must be a representative sample of the original data # X_train can be passed as well, but with more examples explanations will take longer although they may be more accurate global_explanation = explainer.explain_global(X_test) # Print out a dictionary that holds the sorted feature importance names and values print('global importance rank: {}'.format(global_explanation.get_feature_importance_dict())) ###Output _____no_output_____ ###Markdown Visualize Analyze model errors and explanations using Error Analysis dashboard ###Code from raiwidgets import ErrorAnalysisDashboard ErrorAnalysisDashboard(global_explanation, model, dataset=X_test, true_y=y_test, model_task='regression') ###Output _____no_output_____
TFUG_17Apr22_Graph_Classification_GNN.ipynb
###Markdown Graph Classification Code Example Shyam Sundaram, Thejas Sairam, Shrikumar ShankarReference provided below in the references section Installing required Libaries ###Code # Install required packages. !pip install -q torch-scatter -f https://pytorch-geometric.com/whl/torch-1.10.0+cu113.html !pip install -q torch-sparse -f https://pytorch-geometric.com/whl/torch-1.10.0+cu113.html !pip install -q git+https://github.com/rusty1s/pytorch_geometric.git ###Output _____no_output_____ ###Markdown Graph Classification using Graph Neural NetworksIn this session we will have a closer look at how to apply **Graph Neural Networks (GNNs) to the task of graph classification**.Graph classification refers to the problem of classifiying entire graphs (in contrast to nodes), given a **dataset of graphs**, based on some structural graph properties.Here, we want to embed entire graphs, and we want to embed those graphs in such a way, that all the structural information of the graphs are captured by the GNNs ![Graph Classification Image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfAAAAF+CAYAAAB9FkhOAAAKtWlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgP970xstEAEpoXekCASQEnro0sECIQkQSowJQcWuiCuwooiIgLqgiyIKrkqRVUQsWFgUG1g3iCio62LBhsq7gUfYfe+8986bcyb/dybzz8z/3zvnzAWA/JQtFGbCSgBkCbJFEf5e9Lj4BDruKUADDUAFrsCEzRELmeHhwQCR6fXv8uEugGTrLStZrH///7+KMpcn5gAAhSOczBVzshA+iWg3RyjKBgC1DrEbLMsWyvgAwqoipECEW2WcOsXdMk6eYumkT1SEN8LvAcCT2WxRKgBkWS56DicViUOmI2wj4PIFCMvyunPS2FyEtyFsmZW1RManETZN/kuc1L/FTJbHZLNT5Tx1lknB+/DFwkz2iv/zOv63ZGVKpnMYIEpOEwVEIKu67N4ylgTJWZAcGjbNfO6k/ySnSQKip5kj9k6YZi7bJ0i+NzM0eJpT+H4seZxsVtQ0i5ZEyOPzxL6R08wWzeSSZEQz5Xl5LHnM3LSo2GnO4ceETrM4IzJoxsdbbhdJIuQ1p4j85GfMEv/lXHyW3D87LSpAfkb2TG08cZy8Bi7Px1duF0TLfYTZXvL4wsxwuT8v019uF+dEyvdmIy/b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BTAAAAAElFTkSuQmCC) The most common task for graph classification is **molecular property prediction**, in which molecules are represented as graphs (refer image below). Let's take an example and try to solve this class of problem.![molecule_graph.svg](data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIgogICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIgogICB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c29kaXBvZGk9Imh0dHA6Ly9zb2RpcG9kaS5zb3VyY2Vmb3JnZS5uZXQvRFREL3NvZGlwb2RpLTAuZHRkIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgd2lkdGg9IjMwMy4xMnB0IgogICBoZWlnaHQ9IjEwOHB0IgogICB2aWV3Qm94PSIwIDAgMzAzLjEyIDEwOCIKICAgdmVyc2lvbj0iMS4yIgogICBpZD0ic3ZnMjEwIgogICBzb2RpcG9kaTpkb2NuYW1lPSJtb2xlY3VsZV9ncmFwaC5zdmciCiAgIGlua3NjYXBlOnZlcnNpb249IjEuMC4xICgwNzY3ZjgzMDJhLCAyMDIwLTEwLTE3KSI+CiAgPG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhMjE0Ij4KICAgIDxyZGY6UkRGPgogICAgICA8Y2M6V29yawogICAgICAgICByZGY6YWJvdXQ9IiI+CiAgICAgICAgPGRjOmZvcm1hdD5pbWFnZ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MCwwLjcxNjMxMiwwLDApIgogICAgICAgICBpZD0icGF0aDIwNSIgLz4KICAgIDwvZz4KICA8L2c+Cjwvc3ZnPgo=)The TU Dortmund University has collected a wide range of different graph classification datasets, known as the [**TUDatasets**](https://chrsmrrs.github.io/datasets/), which are also accessible via [`torch_geometric.datasets.TUDataset`](https://pytorch-geometric.readthedocs.io/en/latest/modules/datasets.htmltorch_geometric.datasets.TUDataset) in PyTorch Geometric.Let's load and inspect one of the smaller ones, the **MUTAG dataset**: Importing Libraries ###Code import torch from torch_geometric.datasets import TUDataset ###Output _____no_output_____ ###Markdown Importing and Understanding DatasetThe MUTAG Dataset is a collection of nitroaromatic compounds and the goal is to predict their **mutagenicity** (susceptible to Mutation or not) on **Salmonella typhimurium.** Input graphs are used to represent chemical compounds, where vertices stand for atoms and are labeled by the atom type (represented by one-hot encoding), while edges between vertices represent bonds between the corresponding atoms. It includes 188 samples of chemical compounds with 7 discrete node labels (C, N, O, F, I, Cl, Br) and the task is to classify each graph into one out of two classes. **1 indicating mutagenicity** and **0 meaning no mutagenicity.** **Some Additional Data Points [Ref 2]**> * Graph contains 188 graphs with 18 nodes and 20 edges on average for each graph. * The graph nodes have 7 different labels/atom types, and the binary graph labels represent “their mutagenic effect on a specific gram negative bacterium” (the specific meaning of the labels are not too important here). ###Code # Importing Dataset using the TUDataset Library of Pytorch Geometric dataset = TUDataset(root='data/TUDataset', name='MUTAG') #Get Basic Information about the dataset print() print(f'Dataset: {dataset}:') print('====================') print(f'Number of graphs: {len(dataset)}') print(f'Number of features: {dataset.num_features} (One hot encoded)') print(f'Number of classes: {dataset.num_classes} (1: Mutagenicity, 0: No mutagenicity)') ###Output Dataset: MUTAG(188): ==================== Number of graphs: 188 Number of features: 7 (One hot encoded) Number of classes: 2 (1: Mutagenicity, 0: No mutagenicity) ###Markdown By Inspecting the first Graph object we can see that the graph has * **17 nodes/atoms (7-dimensional since features are one hot encoded)** and **38 edges**. * And it comes with **exactly one label (`y=[1]`)**.* Has **no isolated nodes** i.e. all nodes are connected.* Has **no self loops** (No atom can be connected to itself) ###Code # Get the first graph object/Molecule. data = dataset[0] #Prints information about the data tensor of 1st Graph object print(data) print('=============================================================') # Gather some statistics about the first graph. print(f'Number of nodes: {data.num_nodes}') print(f'Number of edges: {data.num_edges}') print(f'Average node degree: {data.num_edges / data.num_nodes:.2f}') print(f'Has isolated nodes: {data.has_isolated_nodes()}') print(f'Has self-loops: {data.has_self_loops()}') print(f'Is undirected: {data.is_undirected()}') ###Output Data(edge_index=[2, 38], x=[17, 7], edge_attr=[38, 4], y=[1]) ============================================================= Number of nodes: 17 Number of edges: 38 Average node degree: 2.24 Has isolated nodes: False Has self-loops: False Is undirected: True ###Markdown Visual representation of 17x7 node features.**Node Labels*** 0: C* 1: N* 2: O* 3: F* 4: I* 5: Cl* 6: Br![Node_labels.PNG](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdwAAAFrCAYAAAB7bDg4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAChzSURBVHhe7Z3PqipZlod9jx7VOzjp8wD9CD2yoUc5broeoHBSgxo5zbYEsRVBTDNNMyPNFkFEEUEEy8JJzu9rrI4df3SHEWqE59492Ov7YJHl8dSVb5+lv/hnrNqXL1/kW9ff//73wp9rqT/9+d/UV9G6aCnt/Y8//kU/11K2f+1yucj5fJbT6STH41EOh4Ps93vZ7Xay2WxkvV7LarWS5XIpi8VC5vO5BEEgs9lMptOpTCYTGY/HMhqNZDgcymAwkF6vJ91uVzqdjrTbbfn+++9VV1EAaauidaEoitJUTvZwzQuJ1CiKoihKYcUQuBRFURT1TSuGwKUoiqKob1oxBC5FURRFfdOKIXApiqIo6ptWDIFLURRFUd+0YioGbl8atZrUm9uC5x6X94H7R00+wnWpJfVdUPA7ntcfrdj9I/xv0fM+V+qu9e9/7x8U/I6GCr6L/bW9B1of2b9/LVyHot/zue7fA60wE7K/E1M6cLfNevgPNaQZ/pf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KXhBv8brgQ1f7xG85+L5jSckgtgv7HH/9S/qUC97PlfeC+wPuGewH++GsGf/xTCFwH0HD4awZ//DVj+xO4DqDh8NcM/vhrxvYncB1Aw+GvGfzx14ztX7tcLnI+n+V0OsnxeJTD4SD7/V52u51sNhtZr9eyWq1kuVzKYrGQ+XwuQRDIbDaT6XQqk8lExuOxjEYjGQ6HMhgMpNfrSbfblU6nI+12Owpc86IURVEUpbXYw3WAWWjN4I+/ZvDHP0bk/wFRdI+ygN3hvAAAAABJRU5ErkJggg==) ###Code print(data.x) ###Output tensor([[1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0., 0.]]) ###Markdown Visual Representation of Edge Index![Edge index.PNG](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAt0AAABBCAYAAAANDBjjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABYlSURBVHhe7V3bcSM3sN1UbhoM4IbCBG4i+nXJKisAfysQl//232nwDjDAEINpNLobjaEonlN1SssB+0w/AWi9Vf7133//3TL/+uuv7c8awo4m7PR8Zc2///779s8//7gyaFLvGiHqTq9ZCU16zUpo0mtWQpNesxKa9JqVz6a5u3T/+eef2581hB1N2On5ypr/83//O4XUu0aIutNrVkKTXrMSmvSaldCk16yEJr1m5bNp/vr8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FX3G4a6pqxGHuZol2puiBLNrpLlkcJgeew1mxjjQmoKYHzibc2tEaA2eDxtOq1E/H+fF3vZlzrnpGHsNdc/XmvYz9fSeT5hRo5n3pfEaLVCcKzJNe93vGNMMz+NP70v313WfbK64+8Cqw5DZHPd2q3+9BgqQJfKInV1ohmK3k//mPepnAO9r227NrcjOGJ+m7hyonG1+x56gh5nDXlPeZxzaue73UwtnaXI1lWB6jeqaxA1Yf1GeH3sJfsY40JpEza17j8KOw1k1WsSIfreeDyVOqNGG/syeFzuluT6bc246xm7t+Q09X/j1nebpPb8+862Rv6b9zpfR9nN7FnNPnytyzRL8+gxNwaV7HfTd7X0hJbhzMCansGGKewgsNfFq2z642fdlEpOwf58xvpTYu81sP0soGmWXS65RJsUnGGoKh9irOLQbXACv2Y6Pw0FzQ28w2zhH037xyDijRnHjLjS/ZeyKGeOw95Pbl4yzqbDjML9GnT1ZOLePrVEnhgLTY+c0p5ybM2K39rzUF35v3WuGtPX0+nhojc7QFN/5OjUSnisqzQ2auvtoBpv4s33plmPvoBywo/HT7ThA0xfQ9AU0fQFNX0DTF9D0xStr4tKtAOxoWO04QNMX0PQFNH0BTV9A0xfQ9MUra+LSrQDsaFjtOEDTF9D0BTR9AU1fQNMX0PTFK2vi0q0A7GhY7ThA0xfQ9AU0fQFNX0DTF9D0xStrbpfuz8/P28fHx+39/T1eusMCCIIgCIIgCII+DJd5/E23ALCjYbXjAE1fQNMX0PQFNH0BTV9A0xfQxD8vEQF2NKx2HKDpC2j6Apq+gKYvoOkLaPoCmrfb/wMuW6AK/SEprQAAAABJRU5ErkJggg==) **Note*** **Here Column 0 represents Edge 0 indicating Node 0 is connected to Node 1** and so on.* Since there are 38 edges for 1st Graph/Molecule, we have 38 columns.* Also Notice, since 1st Graph/Molecule has 17 Nodes/atoms, the values in edge index range from **0 to 16.** ###Code print(data.edge_index) ###Output tensor([[ 0, 0, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 11, 11, 12, 12, 12, 13, 13, 14, 14, 14, 15, 16], [ 1, 5, 0, 2, 1, 3, 2, 4, 9, 3, 5, 6, 0, 4, 4, 7, 6, 8, 7, 9, 13, 3, 8, 10, 9, 11, 10, 12, 11, 13, 14, 8, 12, 12, 15, 16, 14, 14]]) ###Markdown Visual Representation of Molecule 1Using the Node Labels and Edge Index mentioned above, this is the rough structure of Graph/Molecule 1.![Molecule 1 Rough Structure.PNG](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAyQAAAHxCAYAAACcZnixAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAHtwSURBVHhe7d0PfBx1nfj/aZum/5I2UKHkeydiaprIIf6owt2BOaqJjVKT4KnhaNOAGqk9NVpLYiNp1RYCxdT1VIKcoq05SFtPTfx3iDZUE5AmCBSoJJXyp4CgEtsSSwwE3795z+7aNDNps5vZ3Zmd1/PxeD86O5ud+Yg7n/m8dz5/DAEAAACAFCEhAQAAAJAyJCQAAAAAUoaEBAAAAEDKkJAAAAAASBkSEgAAAAApQ0ICAAAAIGVISAAAAACkDAkJAAAAkALDw8PS0dEhqz7+CVn63g/I2f/8Nlnw+jfIjDlZVuj2ogveJksq3i+1tbXS3t5ufSbdkJAAAAAASTI4OCgtLS1yYel7ZGpGhmS/ZYnMqrlOjKu/JcZ1PxGj5T4xbn86HLqt+/S9D14rp7z17eZnpluf1WPosdIBCQkAAACQYCMjI7Lh2iaZOTdHTi1dLsbaW8W47Skx2g/HFvoZ87NZ77zcOlZTU5N1bD8jIQEAAAASqKn5S5Jzeq5kvuMyMb58t3OiEU/osS6+TOaefoaEQqHI2fyHhAQAAABIgIGBAVlySbnMu2iZGF/c5ZxUuBHmsfUcei49p9+QkAAAAAAu6+rqktPOeoPMrFzrnEQkIt63xjqnnttPSEgAAAAAF7W2tloD1o01tzgnDokM85x6bi2DX5CQAAAAAC7p7OyUKVOnin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pJAAAAAFKGhAQAAABAypCQAAAAAEgZEhIAAAAAKUNCAgAAACBlSEgAAAAApAwJCQAAAIAUEfn/AfBpNLDeCekkAAAAAElFTkSuQmCC) Train and Test Split PyTorch Geometric provides some useful utilities for working with graph datasets, *e.g.*, we can shuffle the dataset and use **the first 150 graphs as training graphs, while using the remaining ones for testing** ###Code #Shuffling Dataset torch.manual_seed(12345) dataset = dataset.shuffle() #Splitting into train and test dataset # First 150 -> Train # Remaining (38) -> Test train_dataset = dataset[:150] test_dataset = dataset[150:] print(f'Number of training graphs: {len(train_dataset)}') print(f'Number of test graphs: {len(test_dataset)}') ###Output Number of training graphs: 150 Number of test graphs: 38 ###Markdown Mini-batching of graphsSince graphs in graph classification datasets are usually small, a good idea is to **batch the graphs** before inputting them into a Graph Neural Network to guarantee full GPU utilization.We encounter a problem with batching **N(=64)** graphs. Each graph in the batch can have a different number of nodes and edges, and hence we would require a lot of padding to obtain a single tensor.Pytorch Geometric opts an approach in which * the **adjacency matrices are stacked in a diagonal fashion (creating a giant graph that holds multiple isolated subgraphs)**, * node and target features are simply concatenated in the node dimension **Description**>* X1: Features of 1st Graph/Molecule* A1: Adjacency Matrix (Graph Structure) of 1st Graph/Molecule* X2: Features of 2nd Graph/Molecule* A1: Adjacency Matrix (Graph Structure) of 2nd Graph/Molecule* X'1: Label predicted by GNN for 1st Graph/Molecule* X'2: Label predicted by GNN for 2nd Graph/Molecule* **The Adjacency Matrices** of 1st and 2nd Graph/Molecule are **stacked Diagonally*** **Features** are represented as **Vectors** and passed into the GNN ![Graph Mini-batching.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABJIAAAELCAYAAACCvKwzAAAKtWlDQ1BJQ0MgUHJvZmlsZQAASImVlwdUU+kSgP970xstEAEpoXekCASQEnro0sECIQkQSowJQcWuiCuwooiIgLqgiyIKrkqRVUQsWFgUG1g3iCio62LBhsq7gUfYfe+8986bcyb/dybzz8z/3zvnzAWA/JQtFGbCSgBkCbJFEf5e9Lj4B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jlFiERABERABERABERABERCB0iagYNulfX1VOxEoOALdqwMbf7Pnt+3Nhc+GKlvbJp3spMEXWNPhLezII4+0adOm2dSpU239+vW2detWmzRpkk2ePNn69Olj++23n7csdwuRz9bMDMU4mHhL5UZbumGhdW25e3CXfouACIiACIiACIiACIiACJQpASmSyvTCq9oikE8Cx+w51tZvXWPvL3srqWK0atTOzhtydXVA4xZe+mbNmtmoUaOM6U0//fRT++9//2sLFiywXbt2GTNX8Ne2bVsbPny4DR482Jo0aZLUeUot0bqtq9Ku0rptq62rSZGUNkhlIAIiIAIiIAIiIAIiIAIlQkCKpBK5kKqGCBQTgbp16tlZg35uuy3oY6/Oe8S2VcUORtu/w352Uv+LrEWj1rWqWLduXevfv7/3t3z5ck+h9MEHH9j27ds9Nzfc3V5//XUbOHCgp1Tq3LlzrTxKcQMWWijWFi1cbJbmTPRcK4kIiIAIiIAIiIAIiIAIiIAIOAJSJDkSWoqACOScwEEVx9u+XQ+xaV9MsBf/+5jtbLTNGjdrZB1bdrWKNv1sYKeRhitcMtKxY0cbM2aMHXbYYfb+++97SqVVq1Z5gbhxg+OvZ8+enttbv379InGWksm70NPs3LnTvvzyS5s3b5739/nnnxvbdnStjhlVkV7pWzdun14GOloEREAEREAEREAEREAERKCkCEiRVFKXU5URgeIj0KxhSxvV61h755GPvVhHxDf61v7fSrkijRs3tv33399TGH322WeeQmn27Nme29vChQuNvxYtWtiwYcO8P9aLUdasWRNRHM2fP99jF6xHww2tbYctCW5O+nfLRm2tU/PuSadXQhEQAREQAREQAREQAREQgdInIEVS6V9j1VAEioJA06ZNPWXIli2x3dzCVIRA27179/b+1q5da1OmTLHp06cb+W/YsMEmTJhgEydO9NziUF716NEj6exXbV5iHy1/175YP882bl9njes3tQ7Nulm/9sOsV5v+SecTJuG2bdsMhZGzOoo1Qx2WWdR79913t4qKCvv7tF945QxzLpd2eLfD3KqWIiACSRLgWfULEwFIREAEREAERCBbBILtTLAdytZ5lW95E5Aiqbyvv2ovAgVDwAXE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+SYgu7h8XwGdXwREQAREQAREoKwIONc2Kj1+/PiyqrsqKwIiIAIiEI6Av53wtx/hclFqEcgsgTrV/pZfOVxmNl/lJgIiIAIiIAIiIAIiEIUAn14uxkWdOnVs+/btVr9+OCNxjpOIgAgUF4Fi7HbpXZPePZbuNa+srLSGDRtGYiQReFvXJPVrInapswvey7JISp2ljhQBERABERABERCB0AT4kD3qqKO84/gw+/LLL0PnoQNEQAREQARKnwDtg+vA025IEVL617xYaihFUrFcKZVTBERABERABESgZAicffbZkbq89NJLkXWtiIAIiIAIiIAj4G8f/O2G26+lCOSLgFzb8kVe5xUBERABERABEShbAitXrrQOHTp49d93331typQpZctCFRcBERABEYhOYPjw4TZ16lRv54oVK6x9+/bRE2qrCOSYgBRJOQau04mACIiACIiACIgArgouThJL4mDIZUH3hQiIgAiIgCNAO0H8POIiIYqP5MhoWQgE5NpWCFdBZRABERABERABESgrAiiNjj76aK/OdA4WLVpUVvVXZUVABERABOIToF1wSiTaCw02xOelvbklIEVSbnnrbCIgAiIgAiIgAiLgEbjkkksiJB5//PHIulZEQAREQAREwN8u+NsLkRGBQiAg17ZCuAoqgwiIgAiIgAiIQNkR2Lhxo7Vo0cKr99ChQ23atGllx0AVFgEREAERiE5g2LBhNn36dG/nhg0brHnz5tETaqsI5IGAFEl5gK5TioAIiIAIiIAIiAAE2rRpY2vXrvVcFqqqquS6oNtCBERABETAiI9Ur149b9m6dWtbs2aNqIhAQRGQa1tBXQ4VRgREQAREQAREoJwI/O53v/OqS6cBRZJEBERABERABGgPaBcQ106IiggUEgFZJBXS1VBZREAEREAEREAEyorAqlWrItM5L1iwwHr27FlW9VdlRUAEREAEahNYuHChVVRUeDtWrlxp7dq1q51IW0QgjwRkkZRH+Dq1CIiACIiACIhAeROgc4DbAtKyZcvyhqHai4AIiIAIeARce0D7ICWSbopCJCBFUiFeFZVJBERABERABESgbAjcdtttXl1XrFhRNnVWRUVABERABGITcO2Bax9ip9QeEcgPAbm25Ye7zioCIiACIiACIiACHgFiYdSvX9+WL19uHTp0EBUREAEREIEyJ4AiqWPHjlZZWekF3S5zHKp+ARKQIqkAL4qKJAIiIAIiIAIiUF4EduzYYQ0aNCivSqu2IiACIiACMQmoXYiJRjsKgIAUSQVwEVQEERABERABERABERABERABERABERABESgGAoqRVAxXSWUUAREQAREQAREQAREQAREQAREQAREQgQIgIEVSAVwEFUEEREAEREAEREAEREAEREAEREAEREAEioHA/wep0TACdfCiagAAAABJRU5ErkJggg==) PyTorch Geometric automatically takes care of **batching multiple graphs into a single giant graph** with the help of the [`torch_geometric.data.DataLoader`](https://pytorch-geometric.readthedocs.io/en/latest/modules/data.htmltorch_geometric.data.DataLoader) class:Here, we opt for a `batch_size` of 64, leading to 3 (randomly shuffled) mini-batches, containing all $2 \cdot 64+22 = 150$ graphs.Furthermore, each `Batch` object is equipped with a `batch` **vector**, which maps each node to its respective graph in the batch:$$\textrm{batch} = [ 0, \ldots, 0, 1, \ldots, 1, 2, \ldots ]$$ ###Code #Library for batching Graphs from torch_geometric.loader import DataLoader #Batching train and test dataset train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False) #Creates 3 set of batches with 64 graphs each for step, data in enumerate(train_loader): print(f'Step {step + 1}:') print('=======') print(f'Number of graphs in the current batch: {data.num_graphs}') print(data) print() ###Output Step 1: ======= Number of graphs in the current batch: 64 DataBatch(edge_index=[2, 2636], x=[1188, 7], edge_attr=[2636, 4], y=[64], batch=[1188], ptr=[65]) Step 2: ======= Number of graphs in the current batch: 64 DataBatch(edge_index=[2, 2506], x=[1139, 7], edge_attr=[2506, 4], y=[64], batch=[1139], ptr=[65]) Step 3: ======= Number of graphs in the current batch: 22 DataBatch(edge_index=[2, 852], x=[387, 7], edge_attr=[852, 4], y=[22], batch=[387], ptr=[23]) ###Markdown Lets take an example of Batch 1 and understand its attributes * **Number of graphs in the current batch:** 64* **edge_index**=[2, 2636] (Contains edges of all 64 graphs present in Batch 1)* **x**=[1188, 7] (Contains nodes of all 64 graphs present in Batch 1)* **y**=[64] (Labels of all 64 graphs)* **batch**=[1188] (Refer cell below to understand) ###Code #Batch object for Mini-Batch Number 1 # 0 Indicates Node/Atom is of 1st Graph/Molecule of Batch 1, 1 Indicates Node/Atom is of 2nd Graph/Molecule etc. data.batch[:350] ###Output _____no_output_____ ###Markdown Creating a Graph Neural NetworkThe final architecture for applying GNNs to the task of graph classification looks as follows and allows for complete end-to-end training![GDN architecture.PNG](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA5AAAAF5CAYAAADpmMVHAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAEQQSURBVHhe7d3Bkdy8dsVxheAQXKUEHIJ32r4QvNXOGXitlUPwUkuH4IUCcAQqh+AQPr8j6VhXZy7YaAy7h+T8f1UoTYMkCKLvJYDR954+/AUAAAAAwAQ2kAAAAACAKWwgAQAAAABT2EACAAAAAKawgQQAAAAATGEDCQAAAACYwgYSAAAAADCFDSQAAAAAYAobSAAAAADAFDaQAAAAAIApbCABAAAAAFPYQAIAAAAAprCBBAAAAABMYQMJAAAAAJjCBhIAAAAAMIUNJAAAAABgChtIAAAAAMAUNpAAAAAAgClsIAEAeANfv37968OHD399//79Vw0AAMfHBhIACi3oa/n06dOvI6+njYLa/PLly6+aNd54fPv27VfNc9Rxcfn8+fOvo29H46C+aFzekmLlnn689QbS8VjLnt/nXt+L8kXtsNEGgGNgAwkAf+fFfG7uPn78+KP+Xm6v8oL9tQvqt9h47NX319L3o++k8kbl2RvqyuOjTeTsLx3e4ns0b8ry+1Rdju+MR34v7isA4Bh4IwPA32mBmptH07F7/2bGm4OrOPIG8gjUL20c7/ne32oDufVd+tgoF0aO+r0AAPbHBhLAu3drIa/NY10ca6OgBbOKrlPJ46538d/C6Oe6cPcxXe9zfdyfVWrf/Dc7rlP/6rkq9R7Zn64t/5nHTXU61m06xGNYuc7t1X7rT5fufvW4N+91jFx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etY0AKv1+UWcxtwv26z6HlK+VOpbhSvXTszfK+tPFhtG+fCBvJAugm1S1ZNYluTaDfJqi7brjxxexE885IYTaa6Ll9kwJGwoAWep8st5jbgfo7fjEPlRZ1DnHOjuavb5LluK8Z1XDm3xTmHa+MbPpDRb21c73IreUeTbH25dPzCcbk1UXaT7OgZgCNxrFeemGtMs6AFXo+5DdjPaD5QfY3zLV08u05/djKPaqnXdHmK62EDeTCjF8NreIE6einsSX2/NZkDb62bPMX1LixogX0wtwH7eFQsai67NefNeESu43jYQB6Mkm7v39zohfCsZObFgbNgQQs8D3MbsA/PM3v+8lBz1h7zCb/YfD/YQB7MI14Mz+IXB3AGLGiB52FuA/ajueuI73/NgXv8LSaOjzcigHeJBS0AAMD9WIEAAAAAAKawgQQAAAAATGEDCQAAAACYwgYSAAAAADCFDSQAAAAAYAobSAAAAADAFDaQAAAAAIApbCABAAAAAFPYQAIAAAAAprCBBAAAAABMYQMJAAAAAJjCBhIAAAAAMIUNJAAAAABgChtIAAAAAMAUNpAAAAAAgClsIAEAAAAAU9hAAgAAAACmsIEEAAAAAExhAwkAAAAAmMIGEgAAAAAwhQ0kAAAAAGAKG0gAAAAAwBQ2kAAAAACAKWwgAQAAAABT2EACAAAAAKawgQQAAAAATGEDCQAAAACYwgYSAAAAADCFDSQAAAAAYMJff/0frerbDM2ExeMAAAAASUVORK5CYII=) ###Code from torch.nn import Linear import torch.nn.functional as F from torch_geometric.nn import GraphConv from torch_geometric.nn import global_mean_pool class GCN(torch.nn.Module): def __init__(self, hidden_channels): super(GCN, self).__init__() torch.manual_seed(12345) self.conv1 = GraphConv(dataset.num_node_features, hidden_channels) self.conv2 = GraphConv(hidden_channels, hidden_channels) self.conv3 = GraphConv(hidden_channels, hidden_channels) self.lin = Linear(hidden_channels, dataset.num_classes) def forward(self, x, edge_index, batch): # 1. Obtain node embeddings x = self.conv1(x, edge_index) x = x.relu() x = self.conv2(x, edge_index) x = x.relu() x = self.conv3(x, edge_index) # 2. Readout layer x = global_mean_pool(x, batch) # [batch_size, hidden_channels] # 3. Apply a final classifier x = F.dropout(x, p=0.5, training=self.training) x = self.lin(x) return x model = GCN(hidden_channels=64) print(model) ###Output GCN( (conv1): GraphConv(7, 64) (conv2): GraphConv(64, 64) (conv3): GraphConv(64, 64) (lin): Linear(in_features=64, out_features=2, bias=True) ) ###Markdown Training Graph Neural NetworkTraining a GNN for graph classification usually follows the steps mentioned below:1. Embed each node by performing multiple rounds of message passing2. Aggregate node embeddings into a unified graph embedding (**readout layer**)3. Train a final classifier on the graph embeddingThere exists multiple **readout layers** in literature, but the most common one is to simply take the average of node embeddings.PyTorch Geometric provides this functionality via [`torch_geometric.nn.global_mean_pool`](https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.htmltorch_geometric.nn.glob.global_mean_pool), which takes in the node embeddings of all nodes in the mini-batch to compute a graph embedding of size `[batch_size, hidden_channels]` for each graph in the batch.Here, we make use of the [`GraphConv`](https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.htmltorch_geometric.nn.conv.GraphConv) with $\mathrm{ReLU}(x) = \max(x, 0)$ activation for obtaining localized node embeddings, before we apply our final classifier on top of a graph readout layer.**Every atom (Node for a graph object) gets an embedding and overall average across all the atom embedding gets computed which becomes the molecule embedding value.** ###Code #Instantiating a model model = GCN(hidden_channels=64) #Creating Optimizer with Learning rate 0.01 optimizer = torch.optim.Adam(model.parameters(), lr=0.01) #Criteria for Loss calculation criterion = torch.nn.CrossEntropyLoss() def train(): """ Function to train the GCN Model Does the following steps 1. Iterate in batches over the training dataset 2. Perform a single forward pass 3. Compute the Cross Entropy Loss 4. Derive Gradients 5. Update parameters based on gradients 6. Clear Gradients """ model.train() # Iterate in batches over the training dataset. for data in train_loader: # Perform a single forward pass. out = model(data.x, data.edge_index, data.batch) # Compute the loss. loss = criterion(out, data.y) # Derive gradients. loss.backward() # Update parameters based on gradients. optimizer.step() # Clear gradients. optimizer.zero_grad() def test(loader): """ Function to Test the model Does the following steps 1. Iterate in batched over the training/test dataset 2. Get predictions 3. Get the class with highest probability 4. Check against ground-truth labels 5. Derive ratio of correct predictions (accuracy) """ model.eval() correct = 0 for data in loader: # Iterate in batches over the training/test dataset. out = model(data.x, data.edge_index, data.batch) pred = out.argmax(dim=1) # Use the class with highest probability. correct += int((pred == data.y).sum()) # Check against ground-truth labels. return correct / len(loader.dataset) # Derive ratio of correct predictions. ###Output _____no_output_____ ###Markdown **Note**> * The Number of Epochs has been chosen randomly* In each Epoch the model is trained on the 3 Mini-batches ###Code for epoch in range(1, 171): train() train_acc = test(train_loader) test_acc = test(test_loader) print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Test Acc: {test_acc:.4f}') ###Output Epoch: 001, Train Acc: 0.7333, Test Acc: 0.7895 Epoch: 002, Train Acc: 0.6467, Test Acc: 0.7368 Epoch: 003, Train Acc: 0.6467, Test Acc: 0.7368 Epoch: 004, Train Acc: 0.6467, Test Acc: 0.7368 Epoch: 005, Train Acc: 0.6467, Test Acc: 0.7368 Epoch: 006, Train Acc: 0.6533, Test Acc: 0.7368 Epoch: 007, Train Acc: 0.7333, Test Acc: 0.8158 Epoch: 008, Train Acc: 0.7267, Test Acc: 0.8158 Epoch: 009, Train Acc: 0.7867, Test Acc: 0.8421 Epoch: 010, Train Acc: 0.7733, Test Acc: 0.8158 Epoch: 011, Train Acc: 0.7733, Test Acc: 0.7895 Epoch: 012, Train Acc: 0.7933, Test Acc: 0.8421 Epoch: 013, Train Acc: 0.7733, Test Acc: 0.8421 Epoch: 014, Train Acc: 0.7733, Test Acc: 0.7895 Epoch: 015, Train Acc: 0.7933, Test Acc: 0.8421 Epoch: 016, Train Acc: 0.7667, Test Acc: 0.7632 Epoch: 017, Train Acc: 0.7933, Test Acc: 0.8421 Epoch: 018, Train Acc: 0.7867, Test Acc: 0.7895 Epoch: 019, Train Acc: 0.7867, Test Acc: 0.7895 Epoch: 020, Train Acc: 0.8133, Test Acc: 0.8421 Epoch: 021, Train Acc: 0.8000, Test Acc: 0.7632 Epoch: 022, Train Acc: 0.7933, Test Acc: 0.8421 Epoch: 023, Train Acc: 0.8133, Test Acc: 0.8421 Epoch: 024, Train Acc: 0.8667, Test Acc: 0.7368 Epoch: 025, Train Acc: 0.8467, Test Acc: 0.7632 Epoch: 026, Train Acc: 0.8400, Test Acc: 0.7368 Epoch: 027, Train Acc: 0.8400, Test Acc: 0.7632 Epoch: 028, Train Acc: 0.8133, Test Acc: 0.8421 Epoch: 029, Train Acc: 0.9067, Test Acc: 0.7632 Epoch: 030, Train Acc: 0.8800, Test Acc: 0.7895 Epoch: 031, Train Acc: 0.8600, Test Acc: 0.7632 Epoch: 032, Train Acc: 0.9133, Test Acc: 0.7895 Epoch: 033, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 034, Train Acc: 0.8933, Test Acc: 0.8158 Epoch: 035, Train Acc: 0.9200, Test Acc: 0.8684 Epoch: 036, Train Acc: 0.9000, Test Acc: 0.7368 Epoch: 037, Train Acc: 0.9267, Test Acc: 0.8684 Epoch: 038, Train Acc: 0.9400, Test Acc: 0.8684 Epoch: 039, Train Acc: 0.9133, Test Acc: 0.7632 Epoch: 040, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 041, Train Acc: 0.9133, Test Acc: 0.7368 Epoch: 042, Train Acc: 0.9067, Test Acc: 0.8421 Epoch: 043, Train Acc: 0.9133, Test Acc: 0.8421 Epoch: 044, Train Acc: 0.9267, Test Acc: 0.8684 Epoch: 045, Train Acc: 0.9067, Test Acc: 0.8158 Epoch: 046, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 047, Train Acc: 0.9200, Test Acc: 0.8158 Epoch: 048, Train Acc: 0.9333, Test Acc: 0.8421 Epoch: 049, Train Acc: 0.9333, Test Acc: 0.8684 Epoch: 050, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 051, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 052, Train Acc: 0.9333, Test Acc: 0.8421 Epoch: 053, Train Acc: 0.9333, Test Acc: 0.8421 Epoch: 054, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 055, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 056, Train Acc: 0.9333, Test Acc: 0.8421 Epoch: 057, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 058, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 059, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 060, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 061, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 062, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 063, Train Acc: 0.9267, Test Acc: 0.8684 Epoch: 064, Train Acc: 0.9333, Test Acc: 0.8421 Epoch: 065, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 066, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 067, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 068, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 069, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 070, Train Acc: 0.9133, Test Acc: 0.8158 Epoch: 071, Train Acc: 0.9467, Test Acc: 0.8421 Epoch: 072, Train Acc: 0.9400, Test Acc: 0.8421 Epoch: 073, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 074, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 075, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 076, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 077, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 078, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 079, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 080, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 081, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 082, Train Acc: 0.9400, Test Acc: 0.8947 Epoch: 083, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 084, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 085, Train Acc: 0.9333, Test Acc: 0.8947 Epoch: 086, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 087, Train Acc: 0.9200, Test Acc: 0.8158 Epoch: 088, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 089, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 090, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 091, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 092, Train Acc: 0.9267, Test Acc: 0.8421 Epoch: 093, Train Acc: 0.9267, Test Acc: 0.8158 Epoch: 094, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 095, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 096, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 097, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 098, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 099, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 100, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 101, Train Acc: 0.9400, Test Acc: 0.8684 Epoch: 102, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 103, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 104, Train Acc: 0.9267, Test Acc: 0.8684 Epoch: 105, Train Acc: 0.9267, Test Acc: 0.7895 Epoch: 106, Train Acc: 0.8333, Test Acc: 0.7632 Epoch: 107, Train Acc: 0.9267, Test Acc: 0.8684 Epoch: 108, Train Acc: 0.8800, Test Acc: 0.7895 Epoch: 109, Train Acc: 0.8867, Test Acc: 0.8158 Epoch: 110, Train Acc: 0.9133, Test Acc: 0.8684 Epoch: 111, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 112, Train Acc: 0.9267, Test Acc: 0.7895 Epoch: 113, Train Acc: 0.9133, Test Acc: 0.8421 Epoch: 114, Train Acc: 0.9400, Test Acc: 0.8421 Epoch: 115, Train Acc: 0.9333, Test Acc: 0.7632 Epoch: 116, Train Acc: 0.9267, Test Acc: 0.7895 Epoch: 117, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 118, Train Acc: 0.9200, Test Acc: 0.8158 Epoch: 119, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 120, Train Acc: 0.9333, Test Acc: 0.8684 Epoch: 121, Train Acc: 0.9467, Test Acc: 0.8421 Epoch: 122, Train Acc: 0.9467, Test Acc: 0.8421 Epoch: 123, Train Acc: 0.9400, Test Acc: 0.8421 Epoch: 124, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 125, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 126, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 127, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 128, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 129, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 130, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 131, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 132, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 133, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 134, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 135, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 136, Train Acc: 0.9333, Test Acc: 0.7895 Epoch: 137, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 138, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 139, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 140, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 141, Train Acc: 0.9400, Test Acc: 0.8421 Epoch: 142, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 143, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 144, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 145, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 146, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 147, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 148, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 149, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 150, Train Acc: 0.9333, Test Acc: 0.8158 Epoch: 151, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 152, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 153, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 154, Train Acc: 0.9200, Test Acc: 0.7632 Epoch: 155, Train Acc: 0.9267, Test Acc: 0.7895 Epoch: 156, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 157, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 158, Train Acc: 0.9400, Test Acc: 0.7895 Epoch: 159, Train Acc: 0.9333, Test Acc: 0.7895 Epoch: 160, Train Acc: 0.9467, Test Acc: 0.7895 Epoch: 161, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 162, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 163, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 164, Train Acc: 0.9400, Test Acc: 0.7895 Epoch: 165, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 166, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 167, Train Acc: 0.9467, Test Acc: 0.8158 Epoch: 168, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 169, Train Acc: 0.9400, Test Acc: 0.8158 Epoch: 170, Train Acc: 0.9467, Test Acc: 0.8158
docs/memo/notebooks/tutorials/2_pipeline_lesson3/.ipynb_checkpoints/notebook-checkpoint.ipynb
###Markdown FactorsA factor is a function from an asset and a moment in time to a number.```F(asset, timestamp) -> float```In Pipeline, [Factors](https://www.quantopian.com/helpquantopian_pipeline_factors_Factor) are the most commonly-used term, representing the result of any computation producing a numerical result. Factors require a column of data and a window length as input.The simplest factors in Pipeline are [built-in Factors](https://www.quantopian.com/helpbuilt-in-factors). Built-in Factors are pre-built to perform common computations. As a first example, let's make a factor to compute the average close price over the last 10 days. We can use the `SimpleMovingAverage` built-in factor which computes the average value of the input data (close price) over the specified window length (10 days). To do this, we need to import our built-in `SimpleMovingAverage` factor and the [USEquityPricing dataset](https://www.quantopian.com/helpimporting-datasets). ###Code from zipline.pipeline import Pipeline from zipline.component.research import run_pipeline # New from the last lesson, import the USEquityPricing dataset. from zipline.pipeline.data import USEquityPricing # New from the last lesson, import the built-in SimpleMovingAverage factor. from zipline.pipeline.factors import SimpleMovingAverage ###Output _____no_output_____ ###Markdown Creating a FactorLet's go back to our `make_pipeline` function from the previous lesson and instantiate a `SimpleMovingAverage` factor. To create a `SimpleMovingAverage` factor, we can call the `SimpleMovingAverage` constructor with two arguments: inputs, which must be a list of `BoundColumn` objects, and window_length, which must be an integer indicating how many days worth of data our moving average calculation should receive. (We'll discuss `BoundColumn` in more depth later; for now we just need to know that a `BoundColumn` is an object indicating what kind of data should be passed to our Factor.).The following line creates a `Factor` for computing the 10-day mean close price of securities. ###Code mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) ###Output _____no_output_____ ###Markdown It's important to note that creating the factor does not actually perform a computation. Creating a factor is like defining the function. To perform a computation, we need to add the factor to our pipeline and run it. Adding a Factor to a PipelineLet's update our original empty pipeline to make it compute our new moving average factor. To start, let's move our factor instantatiation into `make_pipeline`. Next, we can tell our pipeline to compute our factor by passing it a `columns` argument, which should be a dictionary mapping column names to factors, filters, or classifiers. Our updated `make_pipeline` function should look something like this: ###Code def make_pipeline(): mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) return Pipeline( columns={ '10_day_mean_close': mean_close_10 } ) ###Output _____no_output_____ ###Markdown To see what this looks like, let's make our pipeline, run it, and display the result. ###Code result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-05') result ###Output _____no_output_____ ###Markdown Now we have a column in our pipeline output with the 10-day average close price for all 8000+ securities (display truncated). Note that each row corresponds to the result of our computation for a given security on a given date stored. The `DataFrame` has a [MultiIndex](http://pandas.pydata.org/pandas-docs/version/0.16.2/advanced.html) where the first level is a datetime representing the date of the computation and the second level is an [Equity](http://localhost:3000/helpapi-sidinfo) object corresponding to the security. For example, the first row (`2015-05-05 00:00:00+00:00`, `Equity(2 [AA])`) will contain the result of our `mean_close_10` factor for AA on May 5th, 2015.If we run our pipeline over more than one day, the output looks like this. ###Code result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-07') result ###Output _____no_output_____ ###Markdown Note: factors can also be added to an existing `Pipeline` instance using the `Pipeline.add` method. Using `add` looks something like this: >>> my_pipe = Pipeline() >>> f1 = SomeFactor(...) >>> my_pipe.add(f1) LatestThe most commonly used built-in `Factor` is `Latest`. The `Latest` factor gets the most recent value of a given data column. This factor is common enough that it is instantiated differently from other factors. The best way to get the latest value of a data column is by getting its `.latest` attribute. As an example, let's update `make_pipeline` to create a latest close price factor and add it to our pipeline: ###Code def make_pipeline(): mean_close_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10) latest_close = USEquityPricing.close.latest return Pipeline( columns={ '10_day_mean_close': mean_close_10, 'latest_close_price': latest_close } ) ###Output _____no_output_____ ###Markdown And now, when we make and run our pipeline again, there are two columns in our output dataframe. One column has the 10-day mean close price of each security, and the other has the latest close price. ###Code result = run_pipeline(make_pipeline(), '2015-05-05', '2015-05-05') result.head(5) ###Output _____no_output_____ ###Markdown `.latest` can sometimes return things other than `Factors`. We'll see examples of other possible return types in later lessons. Default InputsSome factors have default inputs that should never be changed. For example the [VWAP built-in factor](https://www.quantopian.com/helpbuilt-in-factors) is always calculated from `USEquityPricing.close` and `USEquityPricing.volume`. When a factor is always calculated from the same `BoundColumns`, we can call the constructor without specifying `inputs`. ###Code from zipline.pipeline.factors import VWAP vwap = VWAP(window_length=10) ###Output _____no_output_____
solution/02_conditionals_exercise.ipynb
###Markdown 1. `if-elif-else`Fill missing pieces (`____`) of the following code such that prints make sense. ###Code name = 'John Doe' if len(name) > 20: print('Name "{}" is more than 20 chars long'.format(name)) length_description = 'long' elif len(name) > 15: print('Name "{}" is more than 15 chars long'.format(name)) length_description = 'semi long' elif len(name) > 10: print('Name "{}" is more than 10 chars long'.format(name)) length_description = 'semi long' elif len(name) == 8 or len(name) == 9 or len(name) == 10: print('Name "{}" is 8, 9 or 10 chars long'.format(name)) length_description = 'semi short' else: print('Name "{}" is a short name'.format(name)) length_description = 'short' assert length_description == 'semi short' ###Output _____no_output_____
examples/Example_Alternative_Growth_Fit.ipynb
###Markdown Example Alternative Growth FitPlease first see the other Jupyter Notebook, explaining the basics of accessing mycelyso's HDF5 files.Furthermore, this file assumes the `output.h5` described in the other notebook to be present in the current directory.Within this notebook, we will fit the mycelium length data using a third-party library, [*croissance*](https://github.com/biosustain/croissance) (DOI: [10.5281/zenodo.229905](https://dx.doi.org/10.5281/zenodo.229905) by Lars Schöning (2017)). Please install the current version off github first: ```pip install https://github.com/biosustain/croissance/archive/master.zip```First, some general setup … ###Code %matplotlib inline %config InlineBackend.figure_formats=['svg'] import pandas pandas.options.display.max_columns = None import numpy as np import warnings import croissance from croissance.figures import PDFWriter as CroissancePDFWriter from matplotlib import pyplot class OutputInstead: @classmethod def savefig(cls, fig): pyplot.gcf().set_size_inches(10, 12) pyplot.show() # croissance's PDFWriter is supposed to write to a PDF # but we want an inline figure, so we mock some bits CroissancePDFWriter.doc = OutputInstead CroissancePDFWriter._include_shifted_exponentials = False def display_result(result, name="Mycelium Length"): return CroissancePDFWriter.write(CroissancePDFWriter, name, result) warnings.simplefilter(action='ignore', category=FutureWarning) pyplot.rcParams.update({ 'figure.figsize': (10, 6), 'svg.fonttype': 'none', 'font.sans-serif': 'Arial', 'font.family': 'sans-serif', 'image.cmap': 'gray_r', 'image.interpolation': 'none' }) ###Output _____no_output_____ ###Markdown Opening the HDF5 fileWe will load the `output.h5` using `pandas.HDFStore` … ###Code store = pandas.HDFStore('output.h5', 'r') root = store.get_node('/') for image_file in root.results: print(image_file) for position in image_file: print(position) break ###Output /results/mycelyso_S_lividans_TK24_Complex_Medium_nd046_138_ome_tiff (Group) '' /results/mycelyso_S_lividans_TK24_Complex_Medium_nd046_138_ome_tiff/pos_000000000_t_Collected (Group) '' ###Markdown and load the first growth curve ###Code result_table_collected = store[position.result_table_collected._v_pathname] timepoint = result_table_collected.timepoint / (60*60) length = result_table_collected.graph_edge_length pyplot.title('Length over Time') pyplot.xlabel('Time [h]') pyplot.ylabel('Length [µm]') pyplot.plot(timepoint, length) ###Output _____no_output_____ ###Markdown Here, we will use the third party tool `croissance` to fit the data to an exponential growth model: ###Code curve = pandas.Series(data=np.array(length), index=np.array(timepoint)) estimator = croissance.Estimator() result = estimator.growth(curve) # print(result) print(result.growth_phases) ###Output [GrowthPhase(start=9.928127173487246, end=22.594538504723342, slope=0.36693539043981077, intercept=3.1588539520729086, n0=-25.525547240977755, attributes={'SNR': 172.5009988033075, 'rank': 100.0})] ###Markdown And furthermore use its plotting functionality to show the results: ###Code print("Growth rate as determined by croissance µ=%.2f" % (result.growth_phases[0].slope,)) display_result(result) ###Output Growth rate as determined by croissance µ=0.37
WorldBank/WorldBank_Most_populated_countries.ipynb
###Markdown WorldBank - Most populated countries **Tags:** worldbank opendata **Author:** [Jeremy Ravenel](https://www.linkedin.com/in/ACoAAAJHE7sB5OxuKHuzguZ9L6lfDHqw--cdnJg/) **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development Input Import library ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown Model Lets search the file frome gdrive ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown Stock the data in a variable ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown Fonction ###Code firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown Output Display plot ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown **On va chercher le fichier depuis GDrive** ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown **On stock la data dans une variable** ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown **On fait la tambouille** ###Code # Utilisation de Plotly, c'est bo! firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown **On crée le schema** ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Tags:** worldbank opendata **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development Input Import library ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown Model Lets search the file frome gdrive ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown Stock the data in a variable ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown Fonction ###Code firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown Output Display plot ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Tags:** worldbank opendata snippet plotly matplotlib **Author:** [Jeremy Ravenel](https://www.linkedin.com/in/ACoAAAJHE7sB5OxuKHuzguZ9L6lfDHqw--cdnJg/) **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development Input Import library ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown Model Lets search the file frome gdrive ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown Stock the data in a variable ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown Fonction ###Code firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown Output Display plot ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Tags:** worldbank opendata **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development Input Import library ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown Model Lets search the file frome gdrive ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown Stock the data in a variable ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown Fonction ###Code firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown Output Display plot ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Tags:** worldbank opendata snippet plotly matplotlib **Author:** [Jeremy Ravenel](https://www.linkedin.com/in/ACoAAAJHE7sB5OxuKHuzguZ9L6lfDHqw--cdnJg/) **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development Input Import library ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown Model Lets search the file frome gdrive ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown Stock the data in a variable ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown Fonction ###Code firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown Output Display plot ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____ ###Markdown WorldBank - Most populated countries **Notebook d'exemple pour classer les pays les plus peuplés** **Sources:**OECD -> Organisation for economic co-operation and Development ###Code import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import requests import io import numpy as np import plotly.graph_objects as go import plotly.express as px from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials from pandas import DataFrame import plotly.graph_objects as go ###Output _____no_output_____ ###Markdown **On va chercher le fichier depuis GDrive** ###Code auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth) downloaded = drive.CreateFile({'id':"1FjX4NTIq1z3zS9vCdAdpddtj9mKa0wIW"}) # replace the id with id of file you want to access downloaded.GetContentFile('POP_PROJ_20042020112713800.csv') ###Output _____no_output_____ ###Markdown **On stock la data dans une variable** ###Code data = pd.read_csv("POP_PROJ_20042020112713800.csv", usecols=["Country", "Time", "Value"]) data.rename(columns = {'Country':'COUNTRY', 'Time':'TIME', 'Value':'VALUE'}, inplace = True) data ###Output _____no_output_____ ###Markdown **On fait la tambouille** ###Code # Utilisation de Plotly, c'est bo! firstOccur = [] secondOccur = [] firstYear = 2000 secondYear = 2030 def tambouille_first(number1): first = [] for index, row in data.iterrows(): if(row["TIME"] == number1): first.append(row) first = DataFrame(first) first = first.sort_values(by ="VALUE",ascending=True) first = first.tail(10) return first def tambouille_second(number2): second = [] for index, row in data.iterrows(): if(row["TIME"] == number2): second.append(row) second = DataFrame(second) second =second.sort_values(by ="VALUE",ascending=True) second = second.tail(10) return second firstOccur = tambouille_first(firstYear) secondOccur = tambouille_second(secondYear) firstOccur ###Output _____no_output_____ ###Markdown **On crée le schema** ###Code fig = go.Figure(data=[ go.Bar(name=str(firstYear), y=firstOccur["COUNTRY"], x=firstOccur["VALUE"],orientation='h'), go.Bar(name=str(secondYear), y=secondOccur["COUNTRY"], x=secondOccur["VALUE"],orientation='h'), ]) fig.update_layout(title_text="TOP 10 des pays les plus peuplés en 2000 avec prévision 2030", annotations=[ dict( x=1, y=-0.15, showarrow=False, text="Source : OECD -> 2019", xref="paper", yref="paper" )]) fig.show() ###Output _____no_output_____
src/notebook/Figure - GOSemSim human.ipynb
###Markdown init metadata ###Code colors = { "L3E1_f1": "tab:blue", "L3E1_f2": "tab:olive", "L3E_f1Alt": "navy", "L3E_f2Alt": "gold", "L3": "tab:orange", "CN": "tab:green", "CRA": "tab:red", "CH2": "tab:brown", "Sim": "tab:purple", "rand": "tab:grey", "countP4": "black" } methods = ["commonNeighbor", "L3Normalizing", "CRA", "Sim", "CH2_L3", "random", "countP4", "L3E1_f1", "L3E1_f2", "L3E_f1Alt", "L3E_f2Alt"] methods_map = ["CN", "L3", "CRA", "Sim", "CH2", "rand", "countP4", "L3E1_f1", "L3E1_f2", "L3E_f1Alt", "L3E_f2Alt"] abbrev_map = ["CN", "L3", "CRA", "Sim", "CH2", "rand", "no.\n of $P_{4}$", "L3E'\n($f_{1}$)", "L3E'\n($f_{2}$)", "L3E\n($f_{1}$)", "L3E\n($f_{2}$)"] label_map = ["CN", "L3", "CRA", "Sim", "CH2", "rand", "no. of $P_{4}$", "L3E'($f_{1}$)", "L3E'($f_{2}$)", "L3E($f_{1}$)", "L3E($f_{2}$)"] methods_names = dict(zip(methods, methods_map)) abbrevs = dict(zip(methods_map, abbrev_map)) labels = dict(zip(methods_map, label_map)) ###Output _____no_output_____ ###Markdown parse predicted PPIs & GOSemSim scores ###Code # parse ppi of different predictor & ds into one data structure methods = ["commonNeighbor", "L3Normalizing", "CRA", "Sim", "CH2_L3", "L3E1_f1", "L3E1_f2", "random"] ds_names = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] topPPIs = {} for randSz in range(50, 100, 10): topPPIs[randSz] = defaultdict(dict) for method in methods: for ds in ds_names: if randSz == 50: filename = "./linkPred_out_reduced/{}_{}_topPPI.json".format(method, ds) else: filename = "./linkPred_out_reduced/{}_{}_randSz{}_topPPI.json".format(method, ds, randSz) with open(filename, "r") as f: tmpPPIs = json.loads(f.read()) topPPIs[randSz][method][ds] = [] for trial in range(len(tmpPPIs)): topPPIs[randSz][method][ds].append(["\t".join(i) for i in tmpPPIs[trial]]) # structure: topPPIs = {'commonNeighbor': ['bioGRID': [[ppi1, ppi2], ...], ...], ...} print(topPPIs[70]['commonNeighbor']['bioGRID_human'][0][0:10]) GO_PPIMap, GO_scoreMap = [], [] fNames = set() for file in os.listdir("./GOSemSim_out"): fNames.add(file.split(" _")[0]) for file in fNames: if not ('human' in file or 'HuRI' in file): continue with open("./GOSemSim_out/{} _PPI.json".format(file), "r") as f: readPPIs = json.loads(f.read()) GO_PPIMap += readPPIs with open("./GOSemSim_out/{} _GOSemSim.json".format(file), "r") as f: readScores = json.loads(f.read()) GO_scoreMap += readScores GOSemSimMap = {} for i in range(len(GO_PPIMap)): if GO_PPIMap[i][0] is None or GO_PPIMap[i][1] is None: continue GOSemSimMap["\t".join(GO_PPIMap[i])] = GO_scoreMap[i] print(list(GOSemSimMap.keys())[0:10]) print(list(GOSemSimMap.values())[0:10]) print(list(GOSemSimMap.values()).count(None), len(list(GOSemSimMap.values()))) ###Output ['CYSRT1\tHOXA1', 'CYSRT1\tKRTAP5-9', 'KRTAP10-8\tKRTAP5-9', 'KRTAP10-8\tCREB5', 'CYSRT1\tKRTAP4-2', 'CYSRT1\tADAMTSL4', 'CYSRT1\tLCE5A', 'CYSRT1\tCATSPER1', 'CYSRT1\tLCE3D', 'LCE2B\tKRTAP10-8'] [0.604, 1, 1, 0.571, 1, 0.709, 1, 0.713, 1, 0.893] 9204397 25421487 ###Markdown Get GOSemSim scores of PPIs into df ###Code # construct df for plotting df_dict = defaultdict(list) ds_names = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] for randSz in range(50, 100, 10): for method in methods: for ds in ds_names: for trial in range(len(topPPIs[randSz][method][ds])): for i in range(len(topPPIs[randSz][method][ds][trial])): topPPI = topPPIs[randSz][method][ds][trial][i] df_dict['randSz'].append(randSz) df_dict['ds'].append(ds) df_dict['trial'].append(trial) df_dict['rank'].append(i) if topPPI in GOSemSimMap: df_dict["score"].append(GOSemSimMap[topPPI]) else: df_dict["score"].append(np.nan) df_dict["predictor"].append(methods_names[method]) df = pd.DataFrame(df_dict) df ###Output _____no_output_____ ###Markdown Get data for plotting ###Code # get top 10% score group by method & ds, avg across trial, ignore NaN topTenPPIs = df.copy() topTenPPIs.drop(columns=['rank'], inplace=True) topTenPPIs # create dict of sorted mean GOSemSim scores & conf interval meanScore_dict, std_dict, score_dict = {}, {}, {} for randSz in range(50, 100, 10): meanScore_dict[randSz], std_dict[randSz], score_dict[randSz] = defaultdict(dict), defaultdict(dict), defaultdict(dict) for ds in set(topTenPPIs['ds']): # get mean GOSemSim & conf Int for each predictor for predictor in set(topTenPPIs[(topTenPPIs['ds'] == ds) & (topTenPPIs['randSz'] == randSz)]['predictor']): tmpMean = [] for trial in range(10): curScores = np.asarray(topTenPPIs[(topTenPPIs['randSz'] == randSz) & (topTenPPIs['ds'] == ds) & (topTenPPIs['predictor'] == predictor) & (topTenPPIs['trial'] == trial)]['score']) curScores = curScores[~np.isnan(curScores)] tmpMean.append(np.mean(curScores)) score_dict[randSz][ds][predictor] = tmpMean meanScore_dict[randSz][ds][predictor] = np.mean(tmpMean) std_dict[randSz][ds][predictor] = np.std(tmpMean) meanScore_dict[randSz][ds] = dict(sorted(meanScore_dict[randSz][ds].items(), key=lambda item: item[1])[::-1]) tmp = {} for predictor in meanScore_dict[randSz][ds]: tmp[predictor] = std_dict[randSz][ds][predictor] std_dict[randSz][ds] = tmp print(meanScore_dict) print("") print(std_dict) with open("./GOSemSim_out/score_dict_human.pkl", "wb") as f: pickle.dump(score_dict, f, protocol=pickle.HIGHEST_PROTOCOL) with open("./GOSemSim_out/meanScore_dict_human.pkl", "wb") as f: pickle.dump(meanScore_dict, f, protocol=pickle.HIGHEST_PROTOCOL) with open("./GOSemSim_out/std_dict_human.pkl", "wb") as f: pickle.dump(std_dict, f, protocol=pickle.HIGHEST_PROTOCOL) meanScore_dict, std_dict, score_dict = {}, {}, {} with open("./GOSemSim_out/score_dict_human.pkl", "rb") as f: score_dict = pickle.load(f) with open("./GOSemSim_out/meanScore_dict_human.pkl", "rb") as f: meanScore_dict = pickle.load(f) with open("./GOSemSim_out/std_dict_human.pkl", "rb") as f: std_dict = pickle.load(f) ###Output _____no_output_____ ###Markdown Create figure ###Code # AUC of scatter plot auc_map = {} dss = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] for ds in dss: auc_map[ds] = defaultdict(list) for method in ["CN", "L3", "CRA", "Sim", "CH2", "L3E1_f1", "L3E1_f2", "rand"]: for trial in range(10): X = [randSz/100 for randSz in range(50, 100, 10)] Y = [score_dict[randSz][ds][method][trial] for randSz in range(50, 100, 10)] auc_map[ds][method].append(metrics.auc(X, Y)) sorted_mean_auc, err_auc = {}, {} for ds in auc_map: sorted_mean_auc[ds], err_auc[ds] = {}, {} for method in auc_map[ds]: sorted_mean_auc[ds][method] = np.mean(auc_map[ds][method]) err_auc[ds][method] = np.std(auc_map[ds][method]) sorted_mean_auc[ds] = dict(sorted(sorted_mean_auc[ds].items(), key=lambda item: item[1])) print(sorted_mean_auc) ###Output {'bioGRID_human': {'rand': 0.2218861590254846, 'Sim': 0.22946251015703162, 'L3': 0.23490298270589208, 'CH2': 0.23519644032105594, 'L3E1_f1': 0.2407029051849467, 'L3E1_f2': 0.24310716392637172, 'CN': 0.2482183267556095, 'CRA': 0.2518762058249358}, 'STRING_human': {'rand': 0.21121019291797505, 'Sim': 0.2675246521854112, 'L3E1_f2': 0.26805878502826136, 'L3E1_f1': 0.26862192675032304, 'CRA': 0.2705929162177353, 'L3': 0.2730882615149211, 'CH2': 0.27489813621658454, 'CN': 0.27918234502489836}, 'MINT_human': {'Sim': 0.206105583905103, 'CH2': 0.22246066393732583, 'L3': 0.227288989262611, 'L3E1_f2': 0.22877616980165866, 'L3E1_f1': 0.23296246611352617, 'rand': 0.2381712464345644, 'CN': 0.2597615177052422, 'CRA': 0.2666939570393292}, 'HuRI': {'rand': 0.2790394270878197, 'Sim': 0.3194658556835702, 'L3E1_f2': 0.3229866000461464, 'L3': 0.3231298742955334, 'L3E1_f1': 0.3235365522251835, 'CH2': 0.3238424031072784, 'CRA': 0.32509627330562596, 'CN': 0.3270458664724549}} ###Markdown gridspec ###Code plt.rc('axes', titlesize=20) plt.rc('axes', labelsize=22) plt.rc('xtick', labelsize=17) plt.rc('ytick', labelsize=15) plt.rc('legend', fontsize=18) plt.rcParams["font.family"] = "Times New Roman" hatches = ['', '\\', '\\', '\\', '\\', '\\', '\\/', '\\/'] fig = plt.figure(constrained_layout=True, figsize=(12, 7)) widths = [4,1,4,1] heights = [1,1] spec = fig.add_gridspec(ncols=4, nrows=2, width_ratios=widths, height_ratios=heights) lineAxes = [fig.add_subplot(spec[0, 0]), fig.add_subplot(spec[1, 0]) , fig.add_subplot(spec[0, 2]), fig.add_subplot(spec[1, 2])] barAxes = [fig.add_subplot(spec[0, 1]), fig.add_subplot(spec[1, 1]) , fig.add_subplot(spec[0, 3]), fig.add_subplot(spec[1, 3])] # lineAxes dss = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] dsNames = ['BioGRID', 'STRING', 'MINT', 'HuRI'] for i in range(len(dss)): ds = dss[i] print(ds) ax = lineAxes[i] for method in ["CN", "L3", "CRA", "Sim", "CH2", "L3E1_f1", "L3E1_f2"]: ax.errorbar([randSz for randSz in range(50, 100, 10)] , [meanScore_dict[randSz][ds][method] for randSz in range(50, 100, 10)] , fmt='--', color=colors[method] , yerr=np.transpose(np.asarray( [std_dict[randSz][ds][method] for randSz in range(50, 100, 10)] ))) ax.scatter([randSz for randSz in range(50, 100, 10)] , [meanScore_dict[randSz][ds][method] for randSz in range(50, 100, 10)] , s=5, color=colors[method]) ax.set_xlabel("% of PPIs Sampled") #ax.ticklabel_format(style='sci', scilimits=(0,0), axis='y') ax.set_xticks([randSz for randSz in range(50, 100, 10)]) ax.set_ylabel("GOSemSim Score") ax.set_title("b{}) {} Human".format(i+1, dsNames[i])) # barAxes xlims = [[0.2, 0.26], [0.2, 0.3], [0.2, 0.28], [0.27, 0.33]] for i in range(len(dss)): ds = dss[i] ax = barAxes[i] pos = [0,1.5,2.5,3.5,4.5,5.5,7,8] xtick = [k for k in list(sorted_mean_auc[ds].keys()) if k not in ['rand', 'CRA', 'CN']] xtick = ['rand'] + xtick + [k for k in list(sorted_mean_auc[ds].keys()) if k in ['CRA', 'CN']] #xtick = [k for k in list(sorted_mean_auc[ds])] ax.barh(pos, [sorted_mean_auc[ds][x] for x in xtick] , xerr=[err_auc[ds][x] for x in xtick] , color=[colors[x] for x in xtick] , tick_label=[labels[x] for x in xtick] , edgecolor='white', capsize=5) for j, patch in enumerate(ax.patches): patch.set_hatch(hatches[j]) ax.set_xlim(xlims[i]) if i != 1: ax.set_xticks([xlims[i][0], xlims[i][0]+0.05]) else: ax.set_xticks([xlims[i][0], xlims[i][0]+0.1]) plt.savefig("./img_experiments/GOSemSimComplete_human.png", dpi=300) plt.show() plt.rc('axes', titlesize=20) plt.rc('axes', labelsize=22) plt.rc('xtick', labelsize=17) plt.rc('ytick', labelsize=15) plt.rc('legend', fontsize=18) plt.rcParams["font.family"] = "Times New Roman" hatches = ['', '\\', '\\', '\\', '\\', '\\', '\\/', '\\/'] fig = plt.figure(constrained_layout=True, figsize=(12, 7)) widths = [4,1,4,1] heights = [1,1] spec = fig.add_gridspec(ncols=4, nrows=2, width_ratios=widths, height_ratios=heights) lineAxes = [fig.add_subplot(spec[0, 0]), fig.add_subplot(spec[0, 2]) , fig.add_subplot(spec[1, 0]), fig.add_subplot(spec[1, 2])] barAxes = [fig.add_subplot(spec[0, 1]), fig.add_subplot(spec[0, 3]) , fig.add_subplot(spec[1, 1]), fig.add_subplot(spec[1, 3])] # lineAxes dss = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] dsNames = ['BioGRID', 'STRING', 'MINT', 'HuRI'] for i in range(len(dss)): ds = dss[i] print(ds) ax = lineAxes[i] for method in ["CN", "L3", "CRA", "Sim", "CH2", "L3E1_f1", "L3E1_f2", "rand"]: ax.errorbar([randSz for randSz in range(50, 0, -10)] , [meanScore_dict[randSz][ds][method] for randSz in range(50, 100, 10)] , fmt='--', color=colors[method] , yerr=np.transpose(np.asarray( [std_dict[randSz][ds][method] for randSz in range(50, 100, 10)] ))) ax.scatter([randSz for randSz in range(50, 0, -10)] , [meanScore_dict[randSz][ds][method] for randSz in range(50, 100, 10)] , s=5, color=colors[method]) ax.set_xlabel("% of PPIs Removed") #ax.ticklabel_format(style='sci', scilimits=(0,0), axis='y') ax.set_xticks([randSz for randSz in range(50, 0, -10)]) ax.set_xlim(ax.get_xlim()[::-1]) ax.set_ylabel("GOSemSim Score") ax.set_title("b{}) {} Human".format(i+1, dsNames[i])) # barAxes xlims = [[0.2, 0.26], [0.2, 0.3], [0.2, 0.28], [0.27, 0.33]] for i in range(len(dss)): ds = dss[i] ax = barAxes[i] pos = [0,1.5,2.5,3.5,4.5,5.5,7,8] xtick = [k for k in list(sorted_mean_auc[ds].keys()) if k not in ['rand', 'CRA', 'CN']] xtick = ['rand'] + xtick + [k for k in list(sorted_mean_auc[ds].keys()) if k in ['CRA', 'CN']] #xtick = [k for k in list(sorted_mean_auc[ds])] ax.barh(pos, [sorted_mean_auc[ds][x] for x in xtick] , xerr=[err_auc[ds][x] for x in xtick] , color=[colors[x] for x in xtick] , tick_label=[labels[x] for x in xtick] , edgecolor='white', capsize=5) for j, patch in enumerate(ax.patches): patch.set_hatch(hatches[j]) ax.set_xlim(xlims[i]) if i != 1: ax.set_xticks([xlims[i][0], xlims[i][0]+0.05]) else: ax.set_xticks([xlims[i][0], xlims[i][0]+0.1]) plt.savefig("./img_experiments/GOSemSimComplete_wRand_human.png", dpi=300) plt.show() ###Output bioGRID_human STRING_human MINT_human HuRI ###Markdown p-val ###Code # p val # sample to do: top 2 both to third, between top 2 dss = ['bioGRID_human', 'STRING_human', 'MINT_human', 'HuRI'] pairs = [ [['L3E1_f1', 'L3E1_f2']] , [['L3E1_f1', 'L3E1_f2']] , [['L3', 'CH2'], ['L3E1_f1', 'rand']] , [['L3E1_f1', 'CH2']] ] for i in range(len(dss)): ds = dss[i] for pair in pairs[i]: pop1 = auc_map[ds][pair[0]] pop2 = auc_map[ds][pair[1]] pVal = stats.ttest_ind(pop1, pop2)[1] print("{}: {} {}: {}".format(ds, pair[0], pair[1], pVal)) ###Output bioGRID_human: L3E1_f1 L3E1_f2: 1.0129383570465726e-06 STRING_human: L3E1_f1 L3E1_f2: 0.00024842058042032184 MINT_human: L3 CH2: 9.913791795924306e-09 MINT_human: L3E1_f1 rand: 4.791768868667057e-05 HuRI: L3E1_f1 CH2: 0.15938934762146173
ProcessorVectorizer.ipynb
###Markdown Check the Connection and the Number of Vectors ###Code from elasticsearch import Elasticsearch ES_SERVER = "10.94.253.5" index_doc = 'november2019' index_vec = 'recent_vectors' es = Elasticsearch(ES_SERVER) print(es.count(index=index_vec, body={'query': {'match_all': {}}})) ###Output {'count': 6272, '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0}} ###Markdown Define Queries and Embed them into the Same Vector Space ###Code from ProcessorVectorizer import Vectorizer vt = Vectorizer('muse', '../../models/muse') queries = ['Coronavirus prevention is important.', 'Data privacy was compromised.'] query_vectors = vt.vectorize(queries) ###Output _____no_output_____ ###Markdown View Results ###Code for query_text, query_vector in zip(queries, query_vectors): # Perform the cosine similarity query query = { "script_score": { "query": { "match_all": {} }, "script": { "source": "cosineSimilarity(params.query_vector, 'vector') + 1.0", "params": { "query_vector": query_vector } } } } body = { "query": query, "size" : 100} response = es.search(index=index_vec, body=body, request_timeout=120) # Evaluate the search if response['hits']['total']['value']: _id = response['hits']['hits'][0]['_id'] _score = response['hits']['hits'][0]['_score'] text = es.get(index=index_doc, id=_id)['_source']['article']['maintext'] print(f'Query text: {query_text}\nScore: {_score}\n\n{text}\n\n{"=" * 50}\n') ###Output Query text: Coronavirus prevention is important. Score: 1.4756657 The estimated number of coronavirus deaths fluctuate depending on prior data. Current estimations in the US went up to a little less than 66,000 by August on Tuesday. Experts say these numbers depend on social distancing being maintained till then. States like Georgia recently announced lifts on their stay-at-home orders beginning this week. The exact revised death estimate of the impact of the coronavirus outbreak in the United States is 74,073. ================================================== Query text: Data privacy was compromised. Score: 1.3049575 Полиция задержала мошенников, которые продавали бесплатные цифровые пропуска. Бизнес подозреваемые наладили в мессенджере. Через канал предлагали получить цифровой пропуск для передвижения по Москве и области. У покупателя запрашивали паспортные данные и регистрационный номер машины. За свои услуги мошенники просили 3,5 тыс. рублей. После оплаты они переставали выходить на связь. ==================================================
toolkit/xnlp/Explanations Analysis - Probs Development 20190203.ipynb
###Markdown LOC type entities - analysis ###Code loc_group_explanations = explanations[explanations['entity_type'] == "LOC"].drop(["sentence_idx", "entity_type", "entity_start", "entity_end"], axis=1) loc_group_explanations.columns loc_group_explanations['Loc'].clip(lower=-1.0, upper=1, inplace=False) len(morpho_tag_to_id) loc_group_explanations.size for idx, morpho_tag in enumerate(list(morpho_tag_to_id.keys())): if idx % 9 == 0: fig = plt.figure(int(idx/9)) rem = idx % 9 plt.subplot(3, 3, rem+1) print(morpho_tag) # sns.violinplot(data=list(loc_group_explanations[morpho_tag].clip(lower=-0.5, upper=0.5))) data = loc_group_explanations[morpho_tag].dropna().clip(lower=-0.5, upper=0.5) print(data) if data.size > 0: sns.distplot(data) plt.show() loc_group_explanations mean_loc_group_explanations = loc_group_explanations.mean() mean_loc_group_explanations.sort_values(ascending=False) loc_group_explanations['Loc'].sort_values()[:10] loc_group_explanations['Loc'].sort_values(ascending=False)[:10] loc_group_explanations.hist(['Loc'], range=[-1, 1], bins=100) loc_group_explanations.hist(['Loc'], range=[-0.015, 0.015], bins=100) loc_group_explanations['Loc'].value_counts().sort_values(ascending=False) [(loc_group_explanations['Loc'][loc_group_explanations['Loc'] < 0]).mean(), (loc_group_explanations['Loc'][loc_group_explanations['Loc'] >= 0]).mean()] loc_group_explanations.hist(['Loc^DB'], range=[-1, 1]) loc_group_explanations.hist(['Loc']) loc_group_explanations.hist(['Loc^DB']) loc_group_explanations.hist(['Loc'], range=[-5000, -10], bins=100) loc_group_explanations.hist(['Loc'], range=[1, 1000], bins=100) loc_group_explanations['Loc'][loc_group_explanations['Loc'] < 0].count() loc_group_explanations['Loc'][loc_group_explanations['Loc'] >= 0].count() for morpho_tag in ['Loc', 'Loc^DB']: below_zero = loc_group_explanations[morpho_tag][loc_group_explanations[morpho_tag] < 0].count() above_zero = loc_group_explanations[morpho_tag][loc_group_explanations[morpho_tag] >= 0].count() print(morpho_tag, below_zero, above_zero) ###Output Loc 2681 1818 Loc^DB 653 523 ###Markdown ORG type entities - analysis ###Code org_group_explanations = explanations[explanations['entity_type'] == "ORG"].drop(["sentence_idx", "entity_type", "entity_start", "entity_end"], axis=1) org_group_explanations.mean().sort_values(ascending=False) ###Output _____no_output_____ ###Markdown PER type entities - analysis ###Code per_group_explanations = explanations[explanations['entity_type'] == "PER"].drop(["sentence_idx", "entity_type", "entity_start", "entity_end"], axis=1) per_group_explanations.mean().sort_values(ascending=False) !pwd !ls ../../explanations-for-ner-train-finnish-201901* tmp = list(range(10)) tmp np.reshape(tmp, (2, 5)) ###Output _____no_output_____ ###Markdown Probabilities Analysis ###Code lines = [] raw_data_records = [] with open(files["finnish_model_10_size"]["raw_data"], "r") as f: lines = f.readlines() for line in lines: first_part, second_part, third_part, fourth_part = line.strip().split("\t") size_x, size_y, *conf_data = [int(float(x)) for x in first_part.split(" ")] C = np.reshape(conf_data, (size_x, size_y)) size_x, size_y, *probs_data = [float(x) for x in second_part.split(" ")] P = np.reshape(probs_data, (int(size_x), int(size_y))) target_class_index = int(third_part) n_morpho_tags, *morpho_tag_ids = [int(x) for x in fourth_part.split(" ")] record = (C, P, target_class_index, n_morpho_tags, morpho_tag_ids) raw_data_records.append(record) raw_data_records[0] raw_data_records[0][1].sum(axis=1) ###Output _____no_output_____ ###Markdown single C and P ###Code C = raw_data_records[0][0] P = raw_data_records[0][1] target_class_index = raw_data_records[0][2] n_morpho_tags = raw_data_records[0][3] morpho_tag_ids_per_sentence = raw_data_records[0][4] P[:, target_class_index] C morpho_tag_ids_per_sentence plt.scatter(x=range(0, 12), y=P[:, target_class_index]) records[0] ###Output _____no_output_____ ###Markdown all over the file ###Code from collections import defaultdict zero_centered_Ps = defaultdict(list) indexed_Cs = defaultdict(list) for i in range(len(raw_data_records)): C = raw_data_records[i][0] P = raw_data_records[i][1] target_class_index = raw_data_records[i][2] n_morpho_tags = raw_data_records[i][3] morpho_tag_ids_per_sentence = raw_data_records[i][4] target_entity_type = records[i][1] unperturbated_configuration = [0]*n_morpho_tags for morpho_tag_id in morpho_tag_ids_per_sentence: unperturbated_configuration[morpho_tag_id] = 1 indexed_C = [0]*n_morpho_tags for idx in range(len(indexed_C)): indexed_C[idx] = list(unperturbated_configuration) for idx in range(len(indexed_C)): for morpho_tag_idx, morpho_tag_id in enumerate(morpho_tag_ids_per_sentence): if idx == morpho_tag_id and indexed_C[idx][morpho_tag_id] == 1: indexed_C[idx][morpho_tag_id] = -1 indexed_Cs[target_entity_type] += [np.array(indexed_C)] zero_centered_P = [0.0]*n_morpho_tags for morpho_tag_id, diff_value in zip(morpho_tag_ids_per_sentence, list(P[:, target_class_index]-P[0,target_class_index])): zero_centered_P[morpho_tag_id] = diff_value zero_centered_Ps[target_entity_type] += zero_centered_P for target_entity_type in zero_centered_Ps.keys(): zero_centered_Ps[target_entity_type] = np.reshape(zero_centered_Ps[target_entity_type], (-1, n_morpho_tags)) indexed_Cs[target_entity_type] = np.array(indexed_Cs[target_entity_type]) zero_centered_Ps['ORG'][0] plt.imshow(indexed_Cs['ORG'][0]) plt.scatter(x=range(n_morpho_tags), y=zero_centered_Ps['ORG'][0]) indexed_Cs['ORG'][0].shape len(indexed_Cs['ORG']) plt.imshow(indexed_Cs['ORG'][1]) plt.scatter(x=range(n_morpho_tags), y=zero_centered_Ps['ORG'][1]) plt.figure(figsize=(20, 10)) for sample_idx in range(len(indexed_Cs['ORG'])): plt.subplot(len(indexed_Cs['ORG']), 2, sample_idx*2+1) plt.imshow(indexed_Cs['ORG'][sample_idx]) plt.subplot(len(indexed_Cs['ORG']), 2, sample_idx*2+2) plt.scatter(x=range(n_morpho_tags), y=zero_centered_Ps['ORG'][sample_idx]) zero_centered_Ps['ORG'][0].shape indexed_Cs['ORG'][0][0] indexed_Cs['ORG'][0][1] indexed_Cs['ORG'][0][2] indexed_Cs['ORG'][0][3] indexed_Cs['ORG'][0][4] indexed_Cs['ORG'][0][5] indexed_Cs['ORG'][0][10] plt.figure(figsize=(20, 10)) plt.imshow(zero_centered_Ps['ORG'], cmap="PiYG", vmin=-0.5, vmax=0.5) plt.colorbar() plt.imshow(zero_centered_Ps['PER']) plt.colorbar() a = np.array(range(10)) np.concatenate((a, a)) ###Output _____no_output_____
docs/notebooks/DDM_starting-point-bias_hierarchical_fitting.ipynb
###Markdown Parameter recovery of the hierarchical DDM with starting point bias ###Code import rlssm import pandas as pd ###Output _____no_output_____ ###Markdown Simulate group data ###Code from rlssm.random import simulate_hier_ddm data = simulate_hier_ddm(n_trials=200, n_participants=10, gen_mu_drift=.6, gen_sd_drift=.1, gen_mu_threshold=.5, gen_sd_threshold=.1, gen_mu_ndt=0, gen_sd_ndt=.01, gen_mu_rel_sp=.1, gen_sd_rel_sp=.01) data.head() data.groupby('participant').describe()[['rt', 'accuracy']] ###Output _____no_output_____ ###Markdown Initialize the model ###Code model = rlssm.DDModel(hierarchical_levels = 2, starting_point_bias=True) ###Output Using cached StanModel ###Markdown Fit ###Code # sampling parameters n_iter = 5000 n_chains = 2 n_thin = 1 model_fit = model.fit( data, thin = n_thin, iter = n_iter, chains = n_chains, verbose = False) ###Output Fitting the model using the priors: drift_priors {'mu_mu': 1, 'sd_mu': 5, 'mu_sd': 0, 'sd_sd': 5} threshold_priors {'mu_mu': 1, 'sd_mu': 3, 'mu_sd': 0, 'sd_sd': 3} ndt_priors {'mu_mu': 1, 'sd_mu': 1, 'mu_sd': 0, 'sd_sd': 1} rel_sp_priors {'mu_mu': 0, 'sd_mu': 1, 'mu_sd': 0, 'sd_sd': 1} ###Markdown get Rhat ###Code model_fit.rhat.describe() ###Output _____no_output_____ ###Markdown calculate wAIC ###Code model_fit.waic ###Output _____no_output_____ ###Markdown Posteriors ###Code model_fit.samples.describe() import seaborn as sns sns.set(context = "talk", style = "white", palette = "husl", rc={'figure.figsize':(15, 8)}) ###Output _____no_output_____ ###Markdown Here we plot the estimated posterior distributions against the generating parameters, to see whether the model parameters are recovering well: ###Code g = model_fit.plot_posteriors(height=5, show_intervals='HDI') for i, ax in enumerate(g.axes.flatten()): ax.axvline(data[['drift', 'threshold', 'ndt', 'rel_sp']].mean().values[i], color='grey', linestyle='--') ###Output _____no_output_____
python/algobox/jupyter/status-services.ipynb
###Markdown Prices ###Code analysis = QuickAnalysis(algobox_client=api_client) overview = analysis.day_overview(instrument_id=INSTRUMENT_DAX, date=get_last_trading_day()) if overview.plot is not None: overview.plot.show() ###Output _____no_output_____ ###Markdown Datacollector ###Code datacollector_client = DataCollectorClient() ###Output _____no_output_____ ###Markdown Connections ###Code print_connections(datacollector_client) ###Output _____no_output_____ ###Markdown Last tick ###Code prices_stage_client = datacollector_client.pricestages_client pices_count = prices_stage_client.count_prices(INSTRUMENT_DAX) last_price = prices_stage_client.find_last_price(INSTRUMENT_DAX) print('Prices in stage [%d], last price [%r], time [%s].' % (pices_count, last_price, datetime.utcfromtimestamp(last_price.time / 1000))) ###Output _____no_output_____ ###Markdown Connections ###Code print_connections(api_client) ###Output Connection [oanda-demo:oanda], status [DISCONNECTED], subscriptions ['DE30_EUR'] ###Markdown Strategies ###Code print_strategies(api_client) print_strategies_history(api_client) ###Output _____no_output_____
EI_model_phase_plane.ipynb
###Markdown Let's try to plot the phase portrait and bifurcation diagram of the E-I model.Do this bit without the noise ###Code # let's get what we need together from __future__ import division import PyDSTool as dst import numpy as np from matplotlib import pyplot as plt %matplotlib inline import pandas import scipy.io as si import brian2 # we must give a name DSargs = dst.args(name='E-I_model') # parameters DSargs.pars = { 'tau_NMDA': 0.06, 'tau_GABA': 0.005, 'a_E': 270., 'b_E': 108., 'd_E': 0.154, 'a_I': 615, 'b_I': 177, 'd_I': 0.087, 'gam': 0.641, 'g_Eself': 0.52, 'g_IE': 0.25, 'g_EI': - 0.35, 'g_Iself': - 0.2, 'I_0': 0.31, 'I_ext': 0} DSargs.pars = { # Time constants 'tau_NMDA': 0.06 * brian2.second, # s 'tau_AMPA': 0.002 * brian2.second, # s 'tau_GABA': 0.005 * brian2.second, # s 'tau_rates': 0.002 * brian2.second, # s # f-I curve parameters - E populations 'a_E': 270., # Hz/nA 'b_E': 108., # Hz 'd_E': 0.154, # s 'gam': 0.641, # unitless # f-I curve parameters - I populations 'c_I': 330, # Hz/nA 'r0_I': -95, # Hz # Strength of connections from E cells 'g_E_self': 0.4 , # nA - from E to E 'g_IE': 0.23, # nA - from E to I # Strength of connections from I cells 'g_I_self': -0.15, # nA - from I to I 'g_EI': -0.3, # nA - from I to E # Background inputs 'I0_E': 0.31 * brian2.nA, # nA - background onto E population 'I0_I': 0.22 * brian2.nA, # nA - background onto I population # # Noise std dev # 'std_noise': 0.01 * brian2.nA, # nA - standard deviation of noise input # # initial values # 'r0_E': 5 * brian2.Hz, # # stimulus strength 'I_ext': 0 } # auxiliary functions: fI curve and recurrent current DSargs.fnspecs = { 'fI_E': (['I'], '(a_E*I-b_E)/(1.0 - exp(-d_E*(a_E*I-b_E)))'), 'fI_I': (['I'], 'c_I*I + r0_I'), 'recCurrE': (['x', 'y'], 'g_E_self*x + g_EI*y + I0_E'), 'recCurrI': (['x', 'y'], 'g_I_self*x + g_IE*y + I0_I') } # rhs of the differential equations DSargs.varspecs = {'S_NMDA': '(-S_NMDA/tau_NMDA + gam*(1.0 - S_NMDA)*fI_E(recCurrE(S_NMDA,S_GABA) + I_ext))', 'S_GABA': ' -S_GABA/tau_GABA + fI_I(recCurrI(S_GABA,S_NMDA))'} # initial conditions DSargs.ics = {'S_NMDA': 0.1, 'S_GABA': 0.1} # set the range of integration DSargs.tdomain = [0,10] # variable domain for the phase plane analysis DSargs.xdomain = {'S_GABA': [0,1], 'S_NMDA': [0,1]} # variable domain for the phase plane analysis DSargs.pdomain = {'I_ext': [0,0.3] } # Create the model object dmModel = dst.Vode_ODEsystem(DSargs) # Open a figure and plot the vector field from PyDSTool.Toolbox import phaseplane as pp pp.plot_PP_vf(dmModel,'S_GABA','S_NMDA',N=14, scale_exp=-1) # Find the fixed points fp_coord = pp.find_fixedpoints(dmModel,n=6,eps=1e-8) # Find and plot the nullclines nulls_x, nulls_y = pp.find_nullclines(dmModel, 'S_NMDA', 'S_GABA', n=3, eps=1e-8,max_step=0.01,fps=fp_coord) plt.plot(nulls_x[:,1], nulls_x[:,0],'b') plt.plot(nulls_y[:,1], nulls_y[:,0],'g') # Compute the jacobian to determine the stability of the fixed points jac, new_fnspecs = \ dst.prepJacobian(dmModel.funcspec._initargs['varspecs'], ['S_GABA', 'S_NMDA'], dmModel.funcspec._initargs['fnspecs']) scope = dst.copy(dmModel.pars) scope.update(new_fnspecs) jac_fn = dst.expr2fun(jac, ensure_args=['t'], **scope) # add fixed points to the phase portrait for i in range(0,len(fp_coord)): fp = pp.fixedpoint_2D(dmModel,dst.Point(fp_coord[i]), jac = jac_fn, eps=1e-8) pp.plot_PP_fps(fp) # compute an example trajectory traj = dmModel.compute('trajectory1') pts = traj.sample() plt.plot(pts['S_GABA'],pts['S_NMDA'],'r-o') ###Output _____no_output_____ ###Markdown Now let's sketch the bifurcation diagram ###Code # Set the lower bound of the control (bifurcation) parameter dmModel.set(pars = {'g_Eself': 0.45}) # initial conditions # Close to one of the steady states dmModel.set(ics = {'S_NMDA': 0.01, 'S_GABA': 0.01}) # Set up continuation class PC = dst.ContClass(dmModel) # Equilibrium point curve (EP-C). The branch is labeled EQ1: PCargs = dst.args(name='EQ1', type='EP-C') PCargs.freepars = ['g_Eself'] # control parameter PCargs.MaxNumPoints = 1000 PCargs.MaxStepSize = 1e-4 PCargs.MinStepSize = 1e-5 PCargs.StepSize = 1e-3 PCargs.LocBifPoints = ['all'] #['LP','BP'] # detect limit and saddle-node bifurcation types PCargs.SaveEigen = True # to determine the stability of branches PC.newCurve(PCargs) PC['EQ1'].forward() PC['EQ1'].display(['g_Eself','S_NMDA'], stability=True, figure=1) ###Output Warning: Detection of all points not implemented for curve EP-C.
detection/detector_eval/mdv4_eval.ipynb
###Markdown MegaDetector v4 experiments - evaluationFor MDv2 results, some locations in its training set are in this test set (MDv4 test set). ###Code mdv4boxes_label_path = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Databases/query_results/bboxes_20200123.json' res_dir = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/MegaDetectorEval/megadetectorv4/mdv4_results' test_set_res_paths = { 'No transfer learning': '6851_detections_mdv4_nococo_run4_step840k_on_test_20200322221838.json', 'No transfer learning with hard negatives': '3438_detections_mdv4_nococo_run5_step1040k_on_test_20200322221923.json', 'Hard negatives from 1.5 epoch with augmentation': '9048_detections_mdv4_hardneg_run4_step1260k_on_test_20200322221759.json', 'Hard negatives from 2.5 epoch': '9158_detections_mdv4_hardneg_run3_step960k_on_test_20200322221633.json', 'Hard negatives from 1.5 epoch': '3998_detections_mdv4_hardneg_run2_step1080k_on_test_20200322221449.json', 'Hard negatives from start': '1838_detections_mdv4_hardneg_run1_step1010k_on_test_20200322221339.json', 'Augmentation - orientation': '3858_detections_mdv4_aug_run5_step820k_on_test_20200313071922.json', 'Augmentation - orientation and color': '8411_detections_mdv4_aug_run4_step1160k_on_test_20200313071808.json', 'MDv4 baseline': '5247_detections_mdv4_baseline_run12_step520k_on_test_20200310001011.json', 'MDv4 baseline preliminary': '8542_detections_mdv4_baseline_run5_step735902_on_test_20200310014304.json', 'MDv3': '8583_detections_mdv3_on_test_20200310002010.json', 'MDv2': '1983_detections_mdv2_on_test_20200310004514.json' } out_dir = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/MegaDetectorEval/megadetectorv4' ###Output _____no_output_____ ###Markdown Matching label and predicted boxes ###Code test_set_res = {} for checkpoint_name, out_name in test_set_res_paths.items(): with open(os.path.join(res_dir, out_name)) as f: test_set_res[checkpoint_name] = json.load(f)['images'] print('{}, number of results: {}'.format(checkpoint_name, len(test_set_res[checkpoint_name]))) # for numerical IDs from output files of the API, and names in the MegaDB label_map_name_to_id = { 'animal': 1, 'person': 2, 'vehicle': 3 } test_set_res['MDv4 baseline'][100] # not used test_set = set([i['file'].split('/')[-1].split('.jpg')[0] for i in test_set_res['MDv4 baseline']]) len(test_set) with open(mdv4boxes_label_path) as f: mdv4boxes_labels = json.load(f) len(mdv4boxes_labels) mdv4boxes_labels[100] mdv4boxes_labels_dict = {} for i in mdv4boxes_labels: if i['download_id'] in test_set: mdv4boxes_labels_dict[i['download_id']] = i print(len(mdv4boxes_labels_dict)) mdv4boxes_labels_dict['zsl_borneo+88b7a35a-3f14-11ea-97a2-9801a7a664ab'] ###Output _____no_output_____ ###Markdown Compute metrics ###Code checkpoint_metrics = {} for checkpoint_name, detection_res in test_set_res.items(): print(checkpoint_name) per_image_gts, per_image_detections = detector_eval.get_per_image_gts_and_detections( mdv4boxes_labels_dict, detection_res, label_map_name_to_id) print('Lengths of per_image_gts is {}, per_image_detections is {}'.format( len(per_image_gts), len(per_image_detections))) per_cat_metrics = detector_eval.compute_precision_recall_bbox(per_image_detections, per_image_gts, 3, matching_iou_threshold=0.5) checkpoint_metrics[checkpoint_name] = per_cat_metrics print('one_class average precision is {}'.format(per_cat_metrics['one_class']['average_precision'])) print('-----------') ###Output _____no_output_____ ###Markdown Plot precision-recall ###Code categories = { 1: 'animal', 2: 'person', 3: 'vehicle', 'one_class': 'one class' } for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): print(checkpoint_name) average_precision_category = [] for cat in categories: print(cat) ave_prec = per_cat_metrics[cat]['average_precision'] print(ave_prec) if cat in [1, 2, 3] and ave_prec > 0: average_precision_category.append(ave_prec) mAP = sum(average_precision_category) / len(average_precision_category) print('mAP is {}'.format(mAP)) print('-----------') runs_to_show = ['MDv4 baseline', 'MDv3', 'MDv2'] # Create two subplots sharing x axis fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(6, 3), dpi=200, tight_layout=True) for cat, cat_label, ax in zip([1, 2], ['animal', 'person'], [ax1, ax2]): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in ['MDv4 baseline', 'MDv3', 'MDv2']: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=1) _, _ = ax.set_xlim(left=0.0, right=1.0) _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='upper center', bbox_to_anchor=(0.5, 0.108), ncol=3) runs_to_show = ['Augmentation - orientation', 'Augmentation - orientation and color', 'Hard negatives from start', 'Hard negatives from 1.5 epoch', 'Hard negatives from 2.5 epoch', 'Hard negatives from 1.5 epoch with augmentation', 'MDv4 baseline'] fig = plt.figure(figsize=(5, 6), dpi=200) for cat, cat_label in zip([1, 2, 3], ['animal', 'person', 'vehicle']): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue bbox = [0.1, -0.4 * cat, 0.5, 0.3] ax = fig.add_axes(bbox) _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=0.5) _, _ = ax.set_xlim(left=0.0, right=1.0) _, _ = ax.set_ylim(bottom=0.0, top=1.0) if cat == 3: _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='upper center', bbox_to_anchor=(0.35, 1.5), fontsize='small') runs_to_show = ['Augmentation - orientation', 'Augmentation - orientation and color', 'Hard negatives from start', 'Hard negatives from 1.5 epoch', 'Hard negatives from 2.5 epoch', 'Hard negatives from 1.5 epoch with augmentation', 'MDv4 baseline'] fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(3, 8), dpi=150) for cat, cat_label, ax in zip([1, 2, 3], ['animal', 'person', 'vehicle'], [ax1, ax2, ax3]): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=0.5) _, _ = ax.set_xlim(left=0.0, right=1.0) _, _ = ax.set_ylim(bottom=0.0, top=1.0) if cat == 3: _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='center', bbox_to_anchor=(0.5, 0.1), fontsize='x-small') cat_to_fig = {} for cat, cat_label in categories.items(): fig = matplotlib.figure.Figure(figsize=(3, 3), dpi=150) ax = fig.add_axes((0, 0, 1, 1)) for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=1) _ = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), shadow=False, ncol=2) _, _ = ax.set_xlim(left=0.0, right=1.0) _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) cat_to_fig[cat] = fig cat_to_fig[1] cat_to_fig[1].savefig('/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Docs/MDv4_MSJAR/visuals/prec_recall_baseline_animal.png') cat_to_fig[2] cat_to_fig[2].savefig('/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Docs/MDv4_MSJAR/visuals/prec_recall_baseline_person.png') cat_to_fig[3] cat_to_fig['one_class'] ###Output _____no_output_____ ###Markdown Number of true and false positives ###Code for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue print('\n{}'.format(checkpoint_name)) for category, metrics in per_cat_metrics.items(): print('category: {}'.format(category)) for score_threshold in [0.5, 0.8, 0.9, 0.97]: total_tp = 0 total_fp = 0 for score, tp_fp in zip(metrics['scores'], metrics['tp_fp']): if score > score_threshold: if tp_fp == 1: total_tp += 1 else: total_fp += 1 ratio = total_tp/total_fp if total_fp > 0 else None print(' score_threshold: {}, tp: {}, fp: {}, tp:fp ratio: {}'.format( score_threshold, total_tp, total_fp, ratio)) ###Output _____no_output_____ ###Markdown Visualize some results ###Code test_im_dir = '/Users/siyuyang/Source/temp_data/CameraTrap/samples/mdv4_test' runs_to_compare = ['MDv4 baseline', 'Augmentation - orientation and color'] results_to_compare = {} test_set_files = set() for run_name in runs_to_compare: res = test_set_res[run_name] im_id_to_res = {} for r in res: download_id = r['file'].split('/')[-1].split('.jpg')[0] test_set_files.add(download_id) im_id_to_res[download_id] = r results_to_compare[run_name] = im_id_to_res diff_threshold = 0.6 very_diff_entries = [] for download_id in test_set_files: conf_scores = [] for run_name in runs_to_compare: conf_scores.append(results_to_compare[run_name][download_id]['max_detection_conf']) if max(conf_scores) - min(conf_scores) > diff_threshold: very_diff_entries.append(download_id) len(very_diff_entries) sas_token = os.environ['SAS_TOKEN'] blob_service = BlobServiceClient( account_url='cameratrapsc.blob.core.windows.net', credential=sas_token) samples = sample(test_set_files, 40) test_im_dir = '/Users/siyuyang/Source/temp_data/CameraTrap/samples/mdv4_test_samples_2' container_client = blob_service.get_container_client('megadetectorv4-artifacts') for i in samples: if not os.path.exists(os.path.join(test_im_dir, '{}.jpg'.format(i))): with open(os.path.join(test_im_dir, '{}.jpg'.format(i)), 'wb') as f: container_client.download_blob('mdv4_images/test/' + i + '.jpg').readinto(f) label_map = { '1': 'animal', '2': 'person', '3': 'vehicle' # will be available in megadetector v4 } confidence_threshold = 0.5 for download_id in samples: print('\n{}'.format(download_id)) print('ground truth') image = viz_utils.resize_image(viz_utils.open_image(os.path.join(test_im_dir, '{}.jpg'.format(download_id))), 600) gt_bbox = mdv4boxes_labels_dict[download_id]['bbox'] viz_utils.render_megadb_bounding_boxes(gt_bbox, image) image for run_name in runs_to_compare: print(run_name, results_to_compare[run_name][download_id]['max_detection_conf']) detections = results_to_compare[run_name][download_id]['detections'] # need to reload the image for each rendering image = viz_utils.resize_image(viz_utils.open_image(os.path.join(test_im_dir, '{}.jpg'.format(download_id))), 600) viz_utils.DetectorUtils.render_detection_bounding_boxes(detections, image, label_map=label_map, confidence_threshold=confidence_threshold) image ###Output _____no_output_____ ###Markdown MegaDetector v4 experiments - evaluationFor MDv2 results, some locations in its training set are in this test set (MDv4 test set). ###Code mdv4boxes_label_path = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Databases/query_results/bboxes_20200123.json' res_dir = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/MegaDetectorEval/megadetectorv4/mdv4_results' test_set_res_paths = { 'No transfer learning': '6851_detections_mdv4_nococo_run4_step840k_on_test_20200322221838.json', 'No transfer learning with hard negatives': '3438_detections_mdv4_nococo_run5_step1040k_on_test_20200322221923.json', 'Hard negatives from 1.5 epoch with augmentation': '9048_detections_mdv4_hardneg_run4_step1260k_on_test_20200322221759.json', 'Hard negatives from 2.5 epoch': '9158_detections_mdv4_hardneg_run3_step960k_on_test_20200322221633.json', 'Hard negatives from 1.5 epoch': '3998_detections_mdv4_hardneg_run2_step1080k_on_test_20200322221449.json', 'Hard negatives from start': '1838_detections_mdv4_hardneg_run1_step1010k_on_test_20200322221339.json', 'Augmentation - orientation': '3858_detections_mdv4_aug_run5_step820k_on_test_20200313071922.json', 'Augmentation - orientation and color': '8411_detections_mdv4_aug_run4_step1160k_on_test_20200313071808.json', 'MDv4 baseline': '5247_detections_mdv4_baseline_run12_step520k_on_test_20200310001011.json', 'MDv4 baseline preliminary': '8542_detections_mdv4_baseline_run5_step735902_on_test_20200310014304.json', 'MDv3': '8583_detections_mdv3_on_test_20200310002010.json', 'MDv2': '1983_detections_mdv2_on_test_20200310004514.json' } out_dir = '/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/MegaDetectorEval/megadetectorv4' ###Output _____no_output_____ ###Markdown Matching label and predicted boxes ###Code test_set_res = {} for checkpoint_name, out_name in test_set_res_paths.items(): with open(os.path.join(res_dir, out_name)) as f: test_set_res[checkpoint_name] = json.load(f)['images'] print('{}, number of results: {}'.format(checkpoint_name, len(test_set_res[checkpoint_name]))) # for numerical IDs from output files of the API, and names in the MegaDB label_map_name_to_id = { 'animal': 1, 'person': 2, 'vehicle': 3 } test_set_res['MDv4 baseline'][100] # not used test_set = set([i['file'].split('/')[-1].split('.jpg')[0] for i in test_set_res['MDv4 baseline']]) len(test_set) with open(mdv4boxes_label_path) as f: mdv4boxes_labels = json.load(f) len(mdv4boxes_labels) mdv4boxes_labels[100] mdv4boxes_labels_dict = {} for i in mdv4boxes_labels: if i['download_id'] in test_set: mdv4boxes_labels_dict[i['download_id']] = i print(len(mdv4boxes_labels_dict)) mdv4boxes_labels_dict['zsl_borneo+88b7a35a-3f14-11ea-97a2-9801a7a664ab'] ###Output _____no_output_____ ###Markdown Compute metrics ###Code checkpoint_metrics = {} for checkpoint_name, detection_res in test_set_res.items(): print(checkpoint_name) per_image_gts, per_image_detections = detector_eval.get_per_image_gts_and_detections( mdv4boxes_labels_dict, detection_res, label_map_name_to_id) print('Lengths of per_image_gts is {}, per_image_detections is {}'.format( len(per_image_gts), len(per_image_detections))) per_cat_metrics = detector_eval.compute_precision_recall_bbox(per_image_detections, per_image_gts, 3, matching_iou_threshold=0.5) checkpoint_metrics[checkpoint_name] = per_cat_metrics print('one_class average precision is {}'.format(per_cat_metrics['one_class']['average_precision'])) print('-----------') ###Output _____no_output_____ ###Markdown Plot precision-recall ###Code categories = { 1: 'animal', 2: 'person', 3: 'vehicle', 'one_class': 'one class' } for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): print(checkpoint_name) average_precision_category = [] for cat in categories: print(cat) ave_prec = per_cat_metrics[cat]['average_precision'] print(ave_prec) if cat in [1, 2, 3] and ave_prec > 0: average_precision_category.append(ave_prec) mAP = sum(average_precision_category) / len(average_precision_category) print('mAP is {}'.format(mAP)) print('-----------') runs_to_show = ['MDv4 baseline', 'MDv3', 'MDv2'] # Create two subplots sharing x axis fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(6, 3), dpi=200, tight_layout=True) for cat, cat_label, ax in zip([1, 2], ['animal', 'person'], [ax1, ax2]): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in ['MDv4 baseline', 'MDv3', 'MDv2']: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=1) _, _ = ax.set_xlim(left=0.0, right=1.0) _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='upper center', bbox_to_anchor=(0.5, 0.108), ncol=3) runs_to_show = ['Augmentation - orientation', 'Augmentation - orientation and color', 'Hard negatives from start', 'Hard negatives from 1.5 epoch', 'Hard negatives from 2.5 epoch', 'Hard negatives from 1.5 epoch with augmentation', 'MDv4 baseline'] fig = plt.figure(figsize=(5, 6), dpi=200) for cat, cat_label in zip([1, 2, 3], ['animal', 'person', 'vehicle']): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue bbox = [0.1, -0.4 * cat, 0.5, 0.3] ax = fig.add_axes(bbox) _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=0.5) _, _ = ax.set_xlim(left=0.0, right=1.0) _, _ = ax.set_ylim(bottom=0.0, top=1.0) if cat == 3: _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='upper center', bbox_to_anchor=(0.35, 1.5), fontsize='small') runs_to_show = ['Augmentation - orientation', 'Augmentation - orientation and color', 'Hard negatives from start', 'Hard negatives from 1.5 epoch', 'Hard negatives from 2.5 epoch', 'Hard negatives from 1.5 epoch with augmentation', 'MDv4 baseline'] fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, sharex=True, figsize=(3, 8), dpi=150) for cat, cat_label, ax in zip([1, 2, 3], ['animal', 'person', 'vehicle'], [ax1, ax2, ax3]): for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=0.5) _, _ = ax.set_xlim(left=0.0, right=1.0) _, _ = ax.set_ylim(bottom=0.0, top=1.0) if cat == 3: _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) lines, labels = fig.axes[-1].get_legend_handles_labels() _ = fig.legend(lines, labels, loc='center', bbox_to_anchor=(0.5, 0.1), fontsize='x-small') cat_to_fig = {} for cat, cat_label in categories.items(): fig = matplotlib.figure.Figure(figsize=(3, 3), dpi=150) ax = fig.add_axes((0, 0, 1, 1)) for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue _ = ax.plot(per_cat_metrics[cat]['recall'], per_cat_metrics[cat]['precision'], label=checkpoint_name, linewidth=1) _ = ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.2), shadow=False, ncol=2) _, _ = ax.set_xlim(left=0.0, right=1.0) _ = ax.set_xlabel('Recall') _ = ax.set_ylabel('Precision') _ = ax.set_title('category: ' + cat_label) cat_to_fig[cat] = fig cat_to_fig[1] cat_to_fig[1].savefig('/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Docs/MDv4_MSJAR/visuals/prec_recall_baseline_animal.png') cat_to_fig[2] cat_to_fig[2].savefig('/Users/siyuyang/OneDrive - Microsoft/AI4Earth/CameraTrap/Docs/MDv4_MSJAR/visuals/prec_recall_baseline_person.png') cat_to_fig[3] cat_to_fig['one_class'] ###Output _____no_output_____ ###Markdown Number of true and false positives ###Code for checkpoint_name, per_cat_metrics in checkpoint_metrics.items(): if checkpoint_name not in runs_to_show: continue print('\n{}'.format(checkpoint_name)) for category, metrics in per_cat_metrics.items(): print('category: {}'.format(category)) for score_threshold in [0.5, 0.8, 0.9, 0.97]: total_tp = 0 total_fp = 0 for score, tp_fp in zip(metrics['scores'], metrics['tp_fp']): if score > score_threshold: if tp_fp == 1: total_tp += 1 else: total_fp += 1 ratio = total_tp/total_fp if total_fp > 0 else None print(' score_threshold: {}, tp: {}, fp: {}, tp:fp ratio: {}'.format( score_threshold, total_tp, total_fp, ratio)) ###Output _____no_output_____ ###Markdown Visualize some results ###Code test_im_dir = '/Users/siyuyang/Source/temp_data/CameraTrap/samples/mdv4_test' runs_to_compare = ['MDv4 baseline', 'Augmentation - orientation and color'] results_to_compare = {} test_set_files = set() for run_name in runs_to_compare: res = test_set_res[run_name] im_id_to_res = {} for r in res: download_id = r['file'].split('/')[-1].split('.jpg')[0] test_set_files.add(download_id) im_id_to_res[download_id] = r results_to_compare[run_name] = im_id_to_res diff_threshold = 0.6 very_diff_entries = [] for download_id in test_set_files: conf_scores = [] for run_name in runs_to_compare: conf_scores.append(results_to_compare[run_name][download_id]['max_detection_conf']) if max(conf_scores) - min(conf_scores) > diff_threshold: very_diff_entries.append(download_id) len(very_diff_entries) sas_token = os.environ['SAS_TOKEN'] blob_service = BlockBlobService( account_name='cameratrapsc', sas_token=sas_token ) samples = sample(test_set_files, 40) test_im_dir = '/Users/siyuyang/Source/temp_data/CameraTrap/samples/mdv4_test_samples_2' for i in samples: if not os.path.exists(os.path.join(test_im_dir, '{}.jpg'.format(i))): _ = blob_service.get_blob_to_path('megadetectorv4-artifacts', 'mdv4_images/test/' + i + '.jpg', os.path.join(test_im_dir, '{}.jpg'.format(i))) label_map = { '1': 'animal', '2': 'person', '3': 'vehicle' # will be available in megadetector v4 } confidence_threshold = 0.5 for download_id in samples: print('\n{}'.format(download_id)) print('ground truth') image = viz_utils.resize_image(viz_utils.open_image(os.path.join(test_im_dir, '{}.jpg'.format(download_id))), 600) gt_bbox = mdv4boxes_labels_dict[download_id]['bbox'] viz_utils.render_megadb_bounding_boxes(gt_bbox, image) image for run_name in runs_to_compare: print(run_name, results_to_compare[run_name][download_id]['max_detection_conf']) detections = results_to_compare[run_name][download_id]['detections'] # need to reload the image for each rendering image = viz_utils.resize_image(viz_utils.open_image(os.path.join(test_im_dir, '{}.jpg'.format(download_id))), 600) viz_utils.DetectorUtils.render_detection_bounding_boxes(detections, image, label_map=label_map, confidence_threshold=confidence_threshold) image ###Output _____no_output_____
Grab-Cut/Assignment3-Version1.ipynb
###Markdown Energy function and grabcut algorithm ###Code import numpy as np import cv2 import igraph as ig from sklearn.mixture import GaussianMixture from random import randint # Class that defines the grabcut algorithm class grabCut: def __init__(self,boundBox = [0, 0, 0, 0]): self.background = 0 self.foreground = 1 self.source = 0 self.tank = 0 self.toBeForegroundPix = 3 self.tobeBackgroundPix = 2 self.gamma = 50 # Suggested in the paper self.image = 0 self.lVal = 0 self.uVal = 0 self.uLVal = 0 self.uRVal = 0 self.indexCalc = 0 self.indexesFg = 0 self.indexesBg = 0 self.iterCount = 3 self.Kgmms = 5 self.tmp = False self.tmp1 = False self.rows = 0 self.cols = 0 # High level grabcut function def algo(self,img, mask, bbox, Kgmms=5, iterCounts=3): self.rows, self.cols = img[:, :, 2].shape self.source = self.cols * self.rows self.image = img.astype(np.float64) self.indexCalc = np.zeros((self.rows, self.cols), dtype=np.uint32) self.tank = self.source + 1 self.iterCounts = iterCounts mask[bbox[1]:bbox[1] + bbox[3], bbox[0]:bbox[0] + bbox[2]] = self.toBeForegroundPix self.Kgmms = Kgmms self.indexesBg = np.where(np.logical_or(mask == self.background, mask == self.tobeBackgroundPix)) self.indexesFg = np.where(np.logical_or(mask == self.foreground, mask == self.toBeForegroundPix)) self.lVal = np.zeros((self.rows, self.cols - 1)) self.uVal = np.zeros((self.rows - 1, self.cols)) self.uLVal = np.zeros((self.rows - 1, self.cols - 1)) self.uRVal = np.zeros((self.rows - 1, self.cols - 1)) backgroud_gmm = GaussianMixture(n_components = self.Kgmms) foregroud_gmm = GaussianMixture(n_components = self.Kgmms) mask = self.weightsCap(backgroud_gmm, foregroud_gmm, mask) return np.where((mask == 1) + (mask == 3), 255, 0).astype('uint8') # Defining the Source-sink graph function def stGraphFun(self, backgroud_gmm, foregroud_gmm, mask): edges, capacity = [], [] # t-links indexLik = np.where(np.logical_or(mask.reshape(-1) == self.tobeBackgroundPix, mask.reshape(-1) == self.toBeForegroundPix)) edges.extend(list(zip([self.source] * indexLik[0].size, indexLik[0]))) D = backgroud_gmm.score_samples(self.image.reshape(-1, 3)[indexLik]) D = -D capacity.extend(D.tolist()) edges.extend(list(zip([self.tank] * indexLik[0].size, indexLik[0]))) D = foregroud_gmm.score_samples(self.image.reshape(-1, 3)[indexLik]) D = -D capacity.extend(D.tolist()) edges.extend(list(zip([self.source] * self.indexesBg[0].size, self.indexesBg[0]))) edges.extend(list(zip([self.tank] * self.indexesBg[0].size, self.indexesBg[0]))) capacity.extend([0] * self.indexesBg[0].size) capacity.extend([9 * self.gamma] * self.indexesBg[0].size) edges.extend(list(zip([self.source] * self.indexesFg[0].size, self.indexesFg[0]))) edges.extend(list(zip([self.tank] * self.indexesFg[0].size, self.indexesFg[0]))) capacity.extend([9 * self.gamma] * self.indexesFg[0].size) capacity.extend([0] * self.indexesFg[0].size) # n-links img_indexes = np.arange(self.rows * self.cols, dtype=np.uint32).reshape(self.rows, self.cols) capacity.extend(self.lVal.reshape(-1).tolist()) capacity.extend(self.uVal.reshape(-1).tolist()) capacity.extend(self.uLVal.reshape(-1).tolist()) capacity.extend(self.uRVal.reshape(-1).tolist()) edges.extend(list(zip(img_indexes[:, 1:].reshape(-1), img_indexes[:, :-1].reshape(-1)))) edges.extend(list(zip(img_indexes[1:, :].reshape(-1), img_indexes[:-1, :].reshape(-1)))) edges.extend(list(zip(img_indexes[1:, 1:].reshape(-1), img_indexes[:-1, :-1].reshape(-1)))) edges.extend(list(zip(img_indexes[1:, :-1].reshape(-1), img_indexes[:-1, 1:].reshape(-1)))) graph = ig.Graph(2 + self.cols * self.rows) graph.add_edges(edges) return graph, capacity # Function to assign the weights of to the graph. And the gmm components def weightsCap(self, backgroud_gmm, foregroud_gmm, mask): for num in range(self.iterCounts): backgroud_gmm.fit(self.image[self.indexesBg]) foregroud_gmm.fit(self.image[self.indexesFg]) self.indexCalc[self.indexesBg] = backgroud_gmm.predict(self.image[self.indexesBg]) self.indexCalc[self.indexesFg] = foregroud_gmm.predict(self.image[self.indexesFg]) backgroud_gmm.fit(self.image[self.indexesBg], self.indexCalc[self.indexesBg]) foregroud_gmm.fit(self.image[self.indexesFg], self.indexCalc[self.indexesFg]) graph, capacity = self.stGraphFun(backgroud_gmm,foregroud_gmm, mask) img_indexes = np.arange(self.rows * self.cols, dtype=np.uint32).reshape(self.rows, self.cols) indexLik = np.where(np.logical_or(mask == self.tobeBackgroundPix, mask == self.toBeForegroundPix)) mincut = graph.st_mincut(self.source, self.tank, capacity) mask[indexLik] = np.where(np.isin(img_indexes[indexLik], mincut.partition[0]),self.toBeForegroundPix, self.tobeBackgroundPix) print("done Iteration Number :",num) return mask ###Output _____no_output_____ ###Markdown Interface function ###Code class EventHandler: """ Class for handling user input during segmentation iterations """ def __init__(self, flags, img, _mask, colors): self.FLAGS = flags self.ix = -1 self.iy = -1 self.img = img self.img2 = self.img.copy() self._mask = _mask self.COLORS = colors @property def image(self): return self.img @image.setter def image(self, img): self.img = img @property def mask(self): return self._mask @mask.setter def mask(self, _mask): self._mask = _mask @property def flags(self): return self.FLAGS @flags.setter def flags(self, flags): self.FLAGS = flags def handler(self, event, x, y, flags, param): # Draw the rectangle first if event == cv2.EVENT_RBUTTONDOWN: self.FLAGS['DRAW_RECT'] = True self.ix, self.iy = x,y elif event == cv2.EVENT_MOUSEMOVE: if self.FLAGS['DRAW_RECT'] == True: self.img = self.img2.copy() cv2.rectangle(self.img, (self.ix, self.iy), (x, y), self.COLORS['BLUE'], 2) self.FLAGS['RECT'] = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y)) self.FLAGS['rect_or_mask'] = 0 elif event == cv2.EVENT_RBUTTONUP: self.FLAGS['DRAW_RECT'] = False self.FLAGS['rect_over'] = True cv2.rectangle(self.img, (self.ix, self.iy), (x, y), self.COLORS['BLUE'], 2) self.FLAGS['RECT'] = (min(self.ix, x), min(self.iy, y), abs(self.ix - x), abs(self.iy - y)) self.FLAGS['rect_or_mask'] = 0 # Draw strokes for refinement if event == cv2.EVENT_LBUTTONDOWN: if self.FLAGS['rect_over'] == False: print('Draw the rectangle first.') else: self.FLAGS['DRAW_STROKE'] = True cv2.circle(self.img, (x,y), 3, self.FLAGS['value']['color'], -1) cv2.circle(self._mask, (x,y), 3, self.FLAGS['value']['val'], -1) elif event == cv2.EVENT_MOUSEMOVE: if self.FLAGS['DRAW_STROKE'] == True: cv2.circle(self.img, (x, y), 3, self.FLAGS['value']['color'], -1) cv2.circle(self._mask, (x, y), 3, self.FLAGS['value']['val'], -1) elif event == cv2.EVENT_LBUTTONUP: if self.FLAGS['DRAW_STROKE'] == True: self.FLAGS['DRAW_STROKE'] = False cv2.circle(self.img, (x, y), 3, self.FLAGS['value']['color'], -1) cv2.circle(self._mask, (x, y), 3, self.FLAGS['value']['val'], -1) def run(filename: str): """ Main loop that implements GrabCut. Input ----- filename (str) : Path to image """ COLORS = { 'BLACK' : [0,0,0], 'RED' : [0, 0, 255], 'GREEN' : [0, 255, 0], 'BLUE' : [255, 0, 0], 'WHITE' : [255,255,255] } DRAW_BG = {'color' : COLORS['BLACK'], 'val' : 0} DRAW_FG = {'color' : COLORS['WHITE'], 'val' : 1} FLAGS = { 'RECT' : (0, 0, 1, 1), 'DRAW_STROKE': False, # flag for drawing strokes 'DRAW_RECT' : False, # flag for drawing rectangle 'rect_over' : False, # flag to check if rectangle is drawn 'rect_or_mask' : -1, # flag for selecting rectangle or stroke mode 'value' : DRAW_FG, # drawing strokes initialized to mark foreground } img = cv2.imread(filename) img2 = img.copy() mask = np.zeros(img.shape[:2], dtype = np.uint8) # mask is a binary array with : 0 - background pixels # 1 - foreground pixels output = np.zeros(img.shape, np.uint8) # output image to be shown # Input and segmentation windows cv2.namedWindow('Input Image') cv2.namedWindow('Segmented output') EventObj = EventHandler(FLAGS, img, mask, COLORS) cv2.setMouseCallback('Input Image', EventObj.handler) cv2.moveWindow('Input Image', img.shape[1] + 10, 90) while(1): img = EventObj.image mask = EventObj.mask FLAGS = EventObj.flags cv2.imshow('Segmented image', output) cv2.imshow('Input Image', img) k = cv2.waitKey(1) # key bindings if k == 27: # esc to exit break elif k == ord('0'): # Strokes for background FLAGS['value'] = DRAW_BG # mask=np.zeros((img2[:2]),dtype=np.uint8) # mask=np.where() # mask2 = np.where((mask == 1), 255, 0).astype('uint8') elif k == ord('1'): # FG drawing FLAGS['value'] = DRAW_FG print('FLAGS[VALUE] foreground',FLAGS['value']) elif k == ord('r'): # reset everything FLAGS['RECT'] = (0, 0, 1, 1) FLAGS['DRAW_STROKE'] = False FLAGS['DRAW_RECT'] = False FLAGS['rect_or_mask'] = -1 FLAGS['rect_over'] = False FLAGS['value'] = DRAW_FG img = img2.copy() mask = np.zeros(img.shape[:2], dtype = np.uint8) EventObj.image = img EventObj.mask = mask output = np.zeros(img.shape, np.uint8) elif k == 13: # Press carriage return to initiate segmentation #-------------------------------------------------# # Implement GrabCut here. # # Function should return a mask which can be used # # to segment the original image as shown on L90 # #-------------------------------------------------# EventObj.flags = FLAGS h,w=np.array(img).shape[0],np.array(img).shape[1] # print(FLAGS['RECT']) v1,v2,v3,v4=FLAGS['RECT'] # print(h,w) # print(v1,v3) gCt=grabCut() bbox=FLAGS['RECT'] EventObj.mask = gCt.algo(img, EventObj.mask, bbox, iterCounts = 3, Kgmms=5) # print("bbox output=",np.where(EventObj.mask==2)) imgc = img.copy() out = cv2.bitwise_and(imgc, imgc, mask=EventObj.mask) # print("maks inside=",EventObj.mask) output=out plt.imshow(cv2.cvtColor(output,cv2.COLOR_BGR2RGB)) plt.title("Segmented Image") # print("iters: ", 1, "num_comps: ", 3) # plt.subplot(1, 2, 2) # plt.axis('off') # plt.imshow(cv2.cvtColor(out, cv2.COLOR_BGR2RGB)) # plt.title("Output") # # return mask2,img2 if __name__ == '__main__': filename = '../images/teddy.jpg' # Path to image file run(filename) # print(mask) # plt.imshow(img2) cv2.destroyAllWindows() if __name__ == '__main__': filename = '../images/flower.jpg' # Path to image file run(filename) # print(mask) # plt.imshow(img2) cv2.destroyAllWindows() if __name__ == '__main__': filename = '../images/person4.jpg' # Path to image file run(filename) # print(mask) # plt.imshow(img2) cv2.destroyAllWindows() if __name__ == '__main__': filename = '../images/banana2.jpg' # Path to image file run(filename) # print(mask) # plt.imshow(img2) cv2.destroyAllWindows() if __name__ == '__main__': filename = '../images/sheep.jpg' # Path to image file run(filename) # print(mask) # plt.imshow(img2) cv2.destroyAllWindows() ###Output done Iteration Number : 0 done Iteration Number : 1 done Iteration Number : 2
stock_predictor/dashboard.ipynb
###Markdown Welcome to the stock market prediction application! Click inside the cell below and click the run button at the top to run the program! Alternatively, you can press shift+enter after clicking into the cell below ###Code %run user_interface.ipynb ###Output Enter your choice for what you'd like to do: 1. Run LSTM program on a stock of your choice 2. See current generated models of stocks created in models folder 3. Exit Program 1 Note: Stock data is pulled from yahoo finance. Available stock choices can be found on finance.yahoo.com Enter stock symbol for the stock you'd like to see data on: (Ex: GOOG for Google, AAPL for Apple): AAPL The raw dataset from yahoo finance contains the following:
docs/deep_learning/practical_pytorch/pytorch_gradients.ipynb
###Markdown PyTorch Fundamentals 2. Tensors with Gradients Creating Tensor with Gradients- A Variable wraps a Tensor- Allows accumulation of gradients ###Code import torch a = torch.ones((2, 2), requires_grad=True) a a.requires_grad # Not a variable no_gradient = torch.ones(2, 2) no_gradient.requires_grad # Behaves similarly to tensors b = torch.ones((2, 2), requires_grad=True) print(a + b) print(torch.add(a, b)) print(a * b) print(torch.mul(a, b)) ###Output tensor([[ 1., 1.], [ 1., 1.]]) tensor([[ 1., 1.], [ 1., 1.]]) ###Markdown Manually and Automatically Calculating Gradients **What exactly is `requires_grad`?**- Allows calculation of gradients w.r.t. the variable $$y_i = 5(x_i+1)^2$$ ###Code x = torch.ones(2, requires_grad=True) x ###Output _____no_output_____ ###Markdown $$y_i\bigr\rvert_{x_i=1} = 5(1 + 1)^2 = 5(2)^2 = 5(4) = 20$$ ###Code y = 5 * (x + 1) ** 2 y ###Output _____no_output_____ ###Markdown **Backward should be called only on a scalar (i.e. 1-element tensor) or with gradient w.r.t. the variable**- Let's reduce y to a scalar then... $$o = \frac{1}{2}\sum_i y_i$$ ###Code o = (1/2) * torch.sum(y) o ###Output _____no_output_____ ###Markdown **Recap `y` equation**: $y_i = 5(x_i+1)^2$ **Recap `o` equation**: $o = \frac{1}{2}\sum_i y_i$ **Substitute `y` into `o` equation**: $o = \frac{1}{2} \sum_i 5(x_i+1)^2$ $$\frac{\partial o}{\partial x_i} = \frac{1}{2}[10(x_i+1)]$$ $$\frac{\partial o}{\partial x_i}\bigr\rvert_{x_i=1} = \frac{1}{2}[10(1 + 1)] = \frac{10}{2}(2) = 10$$ ###Code o.backward() x.grad x.requires_grad y.requires_grad o.requires_grad ###Output _____no_output_____
src/investmentstk/templates/stop_loss_report.ipynb
###Markdown Calculate a trailing stop loss using the ATR indicator Imports ###Code # %load_ext dotenv # %dotenv ../.env # %load_ext autoreload # %autoreload 2 import logging from IPython.display import display, Markdown, HTML from investmentstk.figures import candlestick from investmentstk.figures.common import show_figure from investmentstk.formulas.average_true_range import atr_stop_loss_from_asset from investmentstk.models.asset import Asset from investmentstk.strategy.brito_trend_following import PERIODICITY_PER_BROKER from investmentstk.utils.calendar import is_last_bar_closed ###Output _____no_output_____ ###Markdown Input ###Code assets = "AV:5442,AV:5537,CMC:X-ABDOR,CMC:X-AAOTG".split(",") show_all = False display(HTML('<style>div.output_area .rendered_html table.dataframe { margin: auto; }</style>')) logging.getLogger("investmentstk").setLevel(logging.CRITICAL) # Set this to True when running locally to get interactive charts # When publishing the notebook on GitHub, we need static images IS_INTERACTIVE = True for asset in assets: asset = Asset.from_id(asset) # Hide asset if it's not time to update it's stop loss if not show_all: resolution = PERIODICITY_PER_BROKER[asset.source] if not is_last_bar_closed(resolution): continue display(Markdown(f'# {asset.name}')) dataframe = atr_stop_loss_from_asset(asset) dataframe = dataframe[-100:] figure = candlestick.generate_figure(dataframe, asset) figure.update_layout(width=950, height=600) show_figure(figure, interactive=IS_INTERACTIVE) dataframe['stop_change'] = dataframe['stop'] - dataframe['stop'].shift(1) dataframe['stop_change_pct'] = dataframe['stop_change'] / dataframe['close'] * 100 dataframe.loc[dataframe['stop_change'] > 0, 'stop_change_direction'] = '↗️️' dataframe.loc[dataframe['stop_change'] < 0, 'stop_change_direction'] = '↘️️' dataframe.loc[dataframe['stop_change'] == 0, 'stop_change_direction'] = '=️️' dataframe = dataframe.round({'atr': 3, 'stop_distance': 2, 'stop_change': 2, 'stop_change_pct': 2}) dataframe['stop_change'] = dataframe['stop_change'].astype(str) dataframe['stop_change'].replace(['0', '0.0'], '', inplace=True) dataframe['stop_change_pct'] = dataframe['stop_change_pct'].astype(str) dataframe['stop_change_pct'].replace(['0', '0.0'], '', inplace=True) display(dataframe.drop(['open', 'high', 'low'], axis=1).tail()) ###Output _____no_output_____
examples/hgcal/02_dwc_cross_check.ipynb
###Markdown DWC Profile and Coordinate Cross-checkThis example shows how to quickly extrackt MIP spectra for muon runs in a given HGC layer.First, we do the necessary imports. [Pandas](https://pandas.pydata.org/) for managing data, [NumPy](http://www.numpy.org/) for numerical operations, and [matplotlib](https://matplotlib.org/) to show plots: ###Code import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm ###Output _____no_output_____ ###Markdown Also, we should import the [HGC testbeam package](https://github.com/guitargeek/geeksw/blob/master/geeksw/hgcal/testbeam.py) to load data the test beam data very easily: ###Code import geeksw.hgcal.testbeam as hgc ###Output _____no_output_____ ###Markdown Read in the HGC and DWC (Delay Wire Chamber) data for a muon run: ###Code df_hgc = hgc.load_run(700, columns=["event", "rechit_detid", "rechit_amplitudeHigh", "rechit_layer", "rechit_y"]) df_hgc.event = df_hgc.event.astype(np.uint64) df_hgc.dtypes df_hgc = df_hgc.set_index(["event", "rechit_detid"]) df_dwc = hgc.load_run(700, key="trackimpactntupler/impactPoints", columns=["event", "dwcReferenceType", "impactX_HGCal_layer_2", "impactY_HGCal_layer_2"] ).set_index("event") df = df_hgc.join(df_dwc, how="inner", lsuffix="_hgc", rsuffix="_dwc") ###Output _____no_output_____ ###Markdown We want to select only the best track measurements where all DWCs were contributing: ###Code df_sel_1 = df.query("dwcReferenceType == 15") ###Output _____no_output_____ ###Markdown Check if the profile looks like we would expect from a beam spot: ###Code plt.hist2d(df_sel_1.impactX_HGCal_layer_2, df_sel_1.impactY_HGCal_layer_2, bins=50, norm=LogNorm()) plt.xlabel("impactX_HGCal_layer_2") plt.ylabel("impactY_HGCal_layer_2") plt.colorbar() plt.show() ###Output _____no_output_____ ###Markdown Next we want to look at the correlation between DWC and HGC measurements in layer 2. We restrict our selection even further this time and only look at well-measured HGC hits: ###Code df_sel_2 = df.query("dwcReferenceType == 15 and rechit_amplitudeHigh > 30 and rechit_layer == 2") ###Output _____no_output_____ ###Markdown Plot the y-position of the DWC track extrapolated to the HGCY layer 2 versus the actual y-position of the HGC rechit in layer 2 above a certain threshold in amplitude. ###Code plt.hist2d(df_sel_2.rechit_y, df_sel_2.impactY_HGCal_layer_2, bins=50, norm=LogNorm()) plt.xlabel("rechit_y") plt.ylabel("impactY_HGCal_layer_2") plt.colorbar() plt.show() ###Output _____no_output_____
2018-spring/seminars/DL18_seminar7_adversarialX/DL18_seminar7.ipynb
###Markdown Adversarial X**Разработчик: Алексей Умнов** Adversarial examples (0.2 балла)В этом разделе мы будем создавать adversarial примеры для типичной архитектуры сетей. Для начала нужно сделать простую сверточную сеть для классификации (2-3 слоя) и обучить ее до нормального качества (>98%). Для экономии времени не нужно обучать ее слишком много эпох как мы это делали ранее.*Упражнение.* Можете попробовать дома обучить сеть до сходимости и сравнить, какой из вариантов более уязвим к таким атакам. ###Code %matplotlib inline import matplotlib.pyplot as plt import numpy as np from IPython.display import clear_output import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torchvision.datasets as dsets import torchvision.transforms as transforms import torch.optim as optim from torch.utils.data.sampler import Sampler, BatchSampler from torch.nn.modules.loss import MSELoss input_size = 784 num_classes = 10 batch_size = 256 train_dataset = dsets.MNIST(root='./MNIST/', train=True, transform=transforms.ToTensor(), download=True) test_dataset = dsets.MNIST(root='./MNIST/', train=False, transform=transforms.ToTensor()) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=False) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) class ConvNet(nn.Module): # YOUR CODE from tqdm import trange def train_epoch(model, optimizer, batchsize=32): loss_log, acc_log = [], [] model.train() for _, (x_batch, y_batch) in zip(trange(len(train_loader)), train_loader): data = Variable(x_batch) target = Variable(y_batch) optimizer.zero_grad() output = model(data) pred = torch.max(output, 1)[1].data.numpy() acc = np.mean(pred == y_batch) acc_log.append(acc) loss = F.nll_loss(output, target) loss.backward() optimizer.step() loss = loss.data[0] loss_log.append(loss) return loss_log, acc_log def test(model): loss_log, acc_log = [], [] model.eval() for batch_num, (x_batch, y_batch) in enumerate(test_loader): data = Variable(x_batch) target = Variable(y_batch) output = model(data) loss = F.nll_loss(output, target) pred = torch.max(output, 1)[1].data.numpy() acc = np.mean(pred == y_batch) acc_log.append(acc) loss = loss.data[0] loss_log.append(loss) return loss_log, acc_log def plot_history(train_history, val_history, title='loss'): plt.figure() plt.title('{}'.format(title)) plt.plot(train_history, label='train', zorder=1) points = np.array(val_history) plt.scatter(points[:, 0], points[:, 1], marker='+', s=180, c='orange', label='val', zorder=2) plt.xlabel('train steps') plt.legend(loc='best') plt.grid() plt.show() def train(model, opt, n_epochs): train_log, train_acc_log = [], [] val_log, val_acc_log = [], [] batchsize = 32 for epoch in range(n_epochs): train_loss, train_acc = train_epoch(model, opt, batchsize=batchsize) val_loss, val_acc = test(model) train_log.extend(train_loss) train_acc_log.extend(train_acc) steps = train_dataset.train_labels.shape[0] / batch_size val_log.append((steps * (epoch + 1), np.mean(val_loss))) val_acc_log.append((steps * (epoch + 1), np.mean(val_acc))) clear_output() plot_history(train_log, val_log) plot_history(train_acc_log, val_acc_log, title='accuracy') print("Final error: {:.2%}".format(1 - val_acc_log[-1][1])) %%time model = ConvNet() opt = torch.optim.RMSprop(model.parameters(), lr=0.001) train(model, opt, 5) ###Output _____no_output_____ ###Markdown Теперь возьмем несколько изображений, которые мы будем пытаться искажать. ###Code import torchvision inputs, labels = iter(test_loader).next() inputs = inputs[:4] labels = labels[:4] def imshow(images): img = images img = torchvision.utils.make_grid(img) npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.axis('off') plt.show() imshow(inputs) print(labels.numpy()) ###Output _____no_output_____ ###Markdown Реализуйте простой способ adversarial-атаки: сделайте шаг градиентного подъема по входам (изображениям) для увеличения ошибки классификации. Подберите шаг, чтобы значения предсказания уже начинали меняться, но визуально цифра мало менялась (т.е. вы бы по-прежнему ее распознали как ту же цифру с высокой уверенностью). ###Code def corrupt_simple(inputs, labels, model, weight): # YOUR CODE HERE return corrupted_inputs corrupted_inputs = corrupt_simple(inputs, labels, model, <WEIGHT>) imshow(corrupted_inputs.data) outputs = model(corrupted_inputs) _, predicted = torch.max(outputs.data, 1) print(predicted.numpy()) ###Output _____no_output_____ ###Markdown Видно, что в таком подходе приходится уже сильно исказить изображение, чтобы ответы начали меняться. Если вместо градиента использовать только его знак (по каждой координате), то результаты получаются лучше. Реализуйте такой метод. ###Code def corrupt_sign(inputs, labels, model, weight): # YOUR CODE HERE return corrupted_inputs corrupted_inputs = corrupt_sign(inputs, labels, model, <WEIGHT>) imshow(corrupted_inputs.data) outputs = model(corrupted_inputs) _, predicted = torch.max(outputs.data, 1) print(predicted.numpy()) ###Output _____no_output_____ ###Markdown Теперь посмотрим как сильно меняется точность на всей выборке. ###Code def evaluate_network_attack(net, corrupt_function, weight): class_correct = list(0. for i in range(10)) class_total = list(0. for i in range(10)) for data in test_loader: images, labels = data images = corrupt_function(images, labels, net, weight) outputs = net(images) _, predicted = torch.max(outputs.data, 1) c = (predicted == labels).squeeze() for i in range(4): label = labels[i] class_correct[label] += c[i] class_total[label] += 1 print('Accuracy %d %% \n' % (100 * sum(class_correct) / sum(class_total))) for i in range(10): print('Accuracy of %2s : %2d %%' % ( i, 100 * class_correct[i] / class_total[i])) evaluate_network_attack(model, corrupt_simple, 1000) evaluate_network_attack(model, corrupt_sign, 0.2) ###Output _____no_output_____ ###Markdown Adversarial networks (0.8 балла)На этом семинаре мы поработаем с adversarial-архитектурами. Мы не будем обучать полноценную генеративную модель (GAN), так как это потребует много времени, а вместо этого вернемся к задаче повышения разрешения изображений и попробуем улучшить нашу модель с помощью advesarial-подхода (получится упрощенный SRGAN).Как мы обсуждали ранее, MSE хоть и является простой и удобной метрикой, она плохо отражает визуальные характеристики изображений. Поэтому мы добавим дискриминатор, который будет пытаться отличить изображения высокого качества от наших результатов, и в модели повышающей разрешение будем пытаться его обмануть.Если это записать строго, то у нас будут две сети: $D$ - дискриминатор и $E$ - сеть, повышающая разрешение, и оптимизировать мы для них будем следующие целевые функции соответсвенно:$$ \min_D \bigl[ \mathrm{BCE}(D(E(x_l)), 0) + \mathrm{BCE}(D(x_h), 1) \bigr],$$$$ \min_E \bigl[ \| E(x_l) - x_h \|_2^2 - \lambda \cdot \mathrm{BCE}(D(E(x_l)), 0) \bigr],$$где $BCE(l, y)$ - бинарная кросс-энтропия между ответами $l$ и метками $y$, $x_l$ - изображения низкого качества, $x_h$ - изображения высокого качества.*Упражнение.* Почему в целевой функции для $D$ нет компоненты $\mathrm{BCE}(D(x_h), 1)$? Для начала продублируем код с позапрошлого семинара, чтобы у нас была сеть для сравнения. Используйте архитектуру с двумя сверточными слоями для простоты. ###Code train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=False) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) n_kernels = 5 class SuperResolutionNetwork(nn.Module): # YOUR CODE srcnn = SuperResolutionNetwork() from tqdm import trange def low_res_and_high_res(images_batch): result = images_batch.clone() low_res_transform = transforms.Resize((14,14)) high_res_transform = transforms.Resize((28,28)) toTensorTransform = transforms.ToTensor() toImageTransform = transforms.ToPILImage() for i in range(images_batch.size()[0]): result[i] = toTensorTransform(high_res_transform(low_res_transform(toImageTransform(images_batch[i])))) return result def train_epoch(model, optimizer, batchsize=32): loss_log = [] model.train() for _, (x_batch_base, _) in zip(trange(len(train_loader)), train_loader): x_batch = x_batch_base.float() data = Variable(low_res_and_high_res(x_batch)) target = Variable(x_batch) optimizer.zero_grad() output = model(data) loss = F.mse_loss(output, target) loss.backward() optimizer.step() loss = loss.data.cpu()[0] loss_log.append(loss) return loss_log def test(model): loss_log = [] model.eval() for batch_num, (x_batch, y_batch) in enumerate(test_loader): x_batch = x_batch.float() data = Variable(low_res_and_high_res(x_batch)) target = Variable(x_batch) output = model(data) loss = F.mse_loss(output, target) loss = loss.data.cpu()[0] loss_log.append(loss) return loss_log def plot_history(train_history, val_history, title='loss'): plt.figure() plt.title('{}'.format(title)) plt.plot(train_history, label='train', zorder=1) points = np.array(val_history) plt.scatter(points[:, 0], points[:, 1], marker='+', s=180, c='orange', label='val', zorder=2) plt.xlabel('train steps') plt.legend(loc='best') plt.grid() plt.show() def train(model, opt, n_epochs): train_log = [] val_log = [] for epoch in range(n_epochs): train_loss = train_epoch(model, opt, batchsize=batch_size) val_loss = test(model) train_log.extend(train_loss) steps = train_dataset.train_labels.shape[0] / batch_size val_log.append((steps * (epoch + 1), np.mean(val_loss))) clear_output() plot_history(train_log, val_log) %%time opt = torch.optim.Adam(srcnn.parameters(), lr=0.005) train(srcnn, opt, 3) test_images = test_dataset.test_data.float() / 255 test_images_blurred = low_res_and_high_res(test_images[:100].view(-1,1,28,28)) result_cnn = srcnn(Variable(test_images_blurred)) examplesCount = 6 plt.figure(figsize=[5, 10]) for i in range(examplesCount): plt.subplot(examplesCount, 3, i * 3 + 1) plt.title("Original") plt.imshow(test_images[i].numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.subplot(examplesCount, 3, i * 3 + 2) mse = np.mean((test_images[i].numpy() - result_cnn[i].data.numpy())**2) plt.title("CNN, MSE={:.2}".format(mse)) plt.imshow(result_cnn[i].data.numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.subplot(examplesCount, 3, i * 3 + 3) mse = np.mean((test_images[i].numpy() - test_images_blurred[i].numpy())**2) plt.title("LQ, MSE={:.2}".format(mse)) plt.imshow(test_images_blurred[i].numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.tight_layout() ###Output _____no_output_____ ###Markdown Теперь переходим к adversarial модели. Создайте простую сеть (2-3 слоя) для бинарной классификации изображений. ###Code class DiscriminatorNetwork(nn.Module): # YOUR CODE HERE srgan = SuperResolutionNetwork() disc = DiscriminatorNetwork() ###Output _____no_output_____ ###Markdown При оптимизации adversarial-архитектур возникает дополнительная сложность - сети необходимо оптимизировать поочередно. Иногда для них приходится подбирать оптимальное соотношение числа шагов, но мы ограничимся вариантом 1:1. Допишите недостающий код оптимизации ниже. ###Code train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=False) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) from tqdm import trange def low_res_and_high_res(images_batch): result = images_batch.clone() low_res_transform = transforms.Resize((14,14)) high_res_transform = transforms.Resize((28,28)) toTensorTransform = transforms.ToTensor() toImageTransform = transforms.ToPILImage() for i in range(images_batch.size()[0]): result[i] = toTensorTransform(high_res_transform(low_res_transform(toImageTransform(images_batch[i])))) return result DISC_LOSS_WEIGHT = 0.1 def losses(model, disc, x_batch): data = Variable(low_res_and_high_res(x_batch)) target = Variable(x_batch) output = model(data) # YOUR CODE return disc_loss, model_loss def train_epoch(model, disc, m_opt, d_opt, batchsize=32): d_loss_log = [] m_loss_log = [] model.train() for batch_num, (x_batch_base, _) in zip(trange(len(train_loader)), train_loader): x_batch = x_batch_base.float() d_loss, m_loss = losses(model, disc, x_batch) # YOUR CODE d_loss_log.append(d_loss.data[0]) m_loss_log.append(m_loss.data[0]) return d_loss_log, m_loss_log def test(model, disc): d_loss_log = [] m_loss_log = [] model.eval() for batch_num, (x_batch, y_batch) in enumerate(test_loader): d_loss, m_loss = losses(model, disc, x_batch) d_loss_log.append(d_loss.data[0]) m_loss_log.append(m_loss.data[0]) return d_loss_log, m_loss_log def plot_history(train_history, val_history, title='loss'): plt.figure(figsize=(8, 4)) plt.subplot(1, 2, 1) plt.plot(train_history[0], label='train', zorder=1) points = np.array(val_history) plt.scatter(points[:, 0], points[:, 1], marker='+', s=180, c='orange', label='val', zorder=2) plt.title('Discriminator loss') plt.xlabel('train steps') plt.legend(loc='best') plt.grid() plt.subplot(1, 2, 2) plt.plot(train_history[1], label='train', zorder=1) points = np.array(val_history) plt.scatter(points[:, 0], points[:, 2], marker='+', s=180, c='orange', label='val', zorder=2) plt.title('Model loss') plt.xlabel('train steps') plt.legend(loc='best') plt.grid() plt.show() def train(model, disc, m_opt, d_opt, n_epochs): train_log = [[], []] val_log = [] for epoch in range(n_epochs): train_loss = train_epoch(model, disc, m_opt, d_opt, batchsize=batch_size) val_loss = test(model, disc) train_log[0].extend(train_loss[0]) train_log[1].extend(train_loss[1]) steps = train_dataset.train_labels.shape[0] / batch_size val_log.append((steps * (epoch + 1), np.mean(val_loss[0]), np.mean(val_loss[1]))) clear_output() plot_history(train_log, val_log) ###Output _____no_output_____ ###Markdown Теперь запустим оптимизацию. Большая проблема при работе с adversarial-моделями - в том, что по графикам оптимизации мало чего понятно. То есть по ним можно увидеть какое-то совсем плохое поведение и, возможно, найти ошибки в коде, но вот понять, дообучилась ли сеть, или ее еще стоит пообучать, часто нельзя. Обычно все метрики просто колеблются вокруг константы, но при этом сеть обучается (по очереди происходит небольшое улучшение дискриминатора, а потом оно тут же убирается основной сетью).Обучите сеть на 2-3 эпохах и добейтесь, чтобы влияние adversarial-потерь было заметно (на примерах ниже). Для этого потребуется, чтобы качество дискриминатора не ушло совсем в 0. Возможно, придется немного поиграться с параметрами.Потом дома можно оставить обучение на 5-10 эпох и увидеть изменения в качестве.Также обратите внимание, что MSE для adversarial-архитектуры выходит хуже, чем обычной. Но мы так и планировали сделать - ведь MSE плохо оценивает визуальное качество. ###Code %%time m_opt = torch.optim.Adam(srgan.parameters(), lr=0.005) d_opt = torch.optim.Adam(disc.parameters(), lr=0.005) train(srgan, disc, m_opt, d_opt, 3) test_images = test_dataset.test_data.float() / 255 test_images_blurred = low_res_and_high_res(test_images[:100].view(-1,1,28,28)) result_cnn = srcnn(Variable(test_images_blurred)) result_gan = srgan(Variable(test_images_blurred)) examplesCount = 6 rows, cols = examplesCount, 4 plt.figure(figsize=[7, 10]) for i in range(examplesCount): plt.subplot(rows, cols, i * cols + 1) plt.title("Original") plt.imshow(test_images[i].numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.subplot(rows, cols, i * cols + 2) mse = np.mean((test_images[i].numpy() - result_gan[i].data.numpy())**2) plt.title("GAN+MSE, MSE={:.2}".format(mse)) plt.title(mse) plt.imshow(result_gan[i].data.numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.subplot(rows, cols, i * cols + 3) mse = np.mean((test_images[i].numpy() - result_cnn[i].data.numpy())**2) plt.title("MSE, MSE={:.2}".format(mse)) plt.title(mse) plt.imshow(result_cnn[i].data.numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.subplot(rows, cols, i * cols + 4) mse = np.mean((test_images[i].numpy() - test_images_blurred[i].numpy())**2) plt.title("LQ, MSE={:.2}".format(mse)) plt.title(mse) plt.imshow(test_images_blurred[i].numpy().reshape([28, 28]), cmap='gray') plt.xticks([]) plt.yticks([]) plt.tight_layout() ###Output _____no_output_____
day001/array.ipynb
###Markdown 多次元配列 ###Code import numpy as np A = np.array([1,2,3,4]) print(A) np.ndim(A) A.shape A.shape[0] ###Output _____no_output_____ ###Markdown ニューラルネットワークの内積 ###Code X = np.array([1.0,0.5]) W1 = np.array([[0.1,0.3,0.5], [0.2,0.4,0.6]]) B1 = np.array([0.1,0.2,0.3]) A1 = np.dot(X, W1) + B1 def sigmoid(x): return 1 / (1 + np.exp(-x)) Z1 = sigmoid(A1) print(Z1) ###Output [0.57444252 0.66818777 0.75026011] ###Markdown ソフトマックス関数eはネイピア数 (2.7182....) $$ y_k = \frac{exp(a_k)}{\sum_{i=1}^{n}exp(a_i)}$$ ###Code def softmax(a): exp_a = np.exp(a) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y ###Output _____no_output_____ ###Markdown オーバーフロー対策 ###Code def softmax(a): c = np.max(a) exp_a = np.exp(a - c) #オーバーフロー対策 sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return y ###Output _____no_output_____
Day 5 - Introduction to Scikit Learn/Introduction to Scikit Learn.ipynb
###Markdown Introduction to Scikit-Learn Adapted by [Nimblebox Inc.](https://www.nimblebox.ai/) from [Data-X](https://datax.berkeley.edu/). Our predictive machine learning models perform two types of tasks:* __CLASSIFICATION__:LABELS ARE DISCRETE VALUES.Here the model is trained to classify each instance into a set of predefined discrete classes.On inputting a feature vector into the model, the trained model is able to predict a class of that instance.Eg: We train our model using income and expenditure data of bank customers using __defaulter or non-defaulter__ as labels. When we input income and expenditure data of any customer in this model, it will predict whether the customer is going to default or not.* __REGRESSION__:LABELS ARE CONTINUOUS VALUES.Here the model is trained to predict a continuous value for each instance.On inputting a feature vector into the model, the trained model is able to predict a continuous value for that instance.Eg: We train our model using income and expenditure data of bank customers using __default amount__ as the label. This model when input with income and expenditure data of any customer will be able to predict the default amount the customer might end up with. Machine learning model building steps -> Understanding the data: Understand your dataset using graphs, descriptive analysis etc. -> Cleaning the data: Removing outliers, Imputation of Null values, Removing null values -> Building the model: Build using appropriate algorithms -> Testing and iteration: Having testing outcomes and improve through each iteration What is scikit-learn?* Scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python* This library is built upon SciPy (Scientific Python)* The library is focused on modeling data. It is not focused on loading, manipulating and summarizing data * We can do supervised and unsupervised learning with Scikit-learn * __TO GET STARTED:__:We will use python library -SCIKIT-LEARN for our classification and regression models.1. Install numpy, scipy, scikit-learn.2. Download the dataset provided and save it in your current working directory.3. In the following sections you will: 3.1 Read the dataset into the python program. 3.2 Look into the dataset characteristics, check for feature type - categorical or numerical. 3.3 Find feature distributions to check sufficiency of data. 3.4 Divide the dataset into training and validation subsets. 3.5 Fit models with training data using scikit-learn library. 3.6 Calculate training error,this gives you the idea of bias in your model. 3.7 Test model prediction accuracy using validation data,this gives you bias and variance error in the model. 3.8 Report model performance on validation data using different metrics. 3.9 Save the model parameters in a pickle file so that it can be used for test data. ###Code import numpy as np import pandas as pd import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown ASSUMPTIONS:- **Problem**: 'Iris 'setosa' species has medicinal benefits and we want to make the process of identifying an iris species scalable' - **Type**: Classification- **Data**: Flower morphology data collected by floriculture department Understanding the data ###Code file_path='iris_classification.csv' data=pd.read_csv(file_path) # lets us look at the data data.head(5) # lets us check unique labels: data['species'].value_counts() from sklearn.utils import shuffle # SHUFFLE data instances to randomize the distribution of different classes # Check if data has any NAN values, you can choose to drop NAN # containing rows or replace NAN values with mean. median,or any assumed value. data= shuffle(data).reset_index(drop=True) print('Number of NaNs in the dataframe:\n',data.isnull().sum()) data.head() # Our functions take in features and labels as arrays so we need to separate them # GET FEATURES X FROM THE DATA X=data.iloc[:,:-1] X.head() # GET LABELS Y FROM THE DATA Y=data['species'] print (Y.value_counts()) #gives the count of each label in the dataset print ('''\nWe will map our class labels to integers and then use in modeling. The mapping is:'versicolor': 0, 'virginica': 1,'setosa' :2 \n''') Y=Y.map({'versicolor': 0, 'virginica': 1,'setosa' :2}) print (Y.value_counts()) #gives the count of each label in the dataset Y.head() # should do sanity check on data often print("Feature vector shape=", X.shape) print("Class shape=", Y.shape) # More summary about our data data.describe() # Get feature distribution of each continuous valued feature (sepal_length and sepal_width) data.hist(figsize=(15,5)) plt.show() # Check feature distribution of each class, to get an overview of feature and class relationshhip, # also useful in validating data print(data.groupby('species').count()) data.groupby('species').hist(figsize=(10,5)) plt.show() ###Output sepal_length sepal_width species setosa 50 50 versicolor 50 50 virginica 50 50 ###Markdown Cleaning the modelWe do not have any NA values in the dataset- Use Pandas functions to remove na values, **Sklearn.preprocessing.Imputer** to impute the missing values.- Scaling the variables using **sklearn.preprocessing.StandardScaler** - The standard score of a sample x is calculated as: z = (x - u) / s- Scaling using Sklearn Min Max scaler - X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min Building the Model USE SKLEARN INBUILT FUNCTION TO BUILD A LOGISTIC REGRESSION MODELFor Details check :http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.htmlsklearn.linear_model.LogisticRegression.fitOur Hypothesis : Species of Iris is dependent on sepal length and width of the flower. In order to check the validity of our trained model, we keep a part of our dataset hidden from the model during training, called __Test data__.Test data labels are predicted using the trained model and compared with the actual labels of the data.This gives us the idea about how well the model can be trusted for its predictive power. We split our data into train/test -* __Training set__ : The sample of data used to fit your model.* __Test set__ : The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset. ![image.png](attachment:image.png) * __Validation set__: The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters![image.png](attachment:image.png) K-folds Cross Validation![image.png](attachment:image.png) Also, if our data set is small we will have fewer examples for validation.This will not give us a a good estimatiion of model error.We can use k-fold crossvalidation in such situations.In k-fold cross-validation, the shuffled training data is partitioned into k disjoint sets and the model is trained on k −1 sets and validated on the kth set. This process is repeated k times with each setchosen as the validation set once. The cross-validation accuracy is reported as the average accuracyof the k iterations ###Code # Split data into training and test set using sklearn function from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=100) print ('Number of samples in training data:',len(x_train)) print ('Number of samples in test data:',len(x_test)) ###Output Number of samples in training data: 120 Number of samples in test data: 30 ###Markdown Train our Logistic Regression Model ###Code from sklearn import linear_model # Name our logistic regression object LogisticRegressionModel = linear_model.LogisticRegression(solver = 'newton-cg', multi_class='multinomial') # we create an instance of logistic Regression Classifier and fit the data. print ('Training a logistic Regression Model..') LogisticRegressionModel.fit(x_train, y_train) ###Output Training a logistic Regression Model.. ###Markdown TRAINING ACCURACY ###Code # TRAINING ACCURACY training_accuracy=LogisticRegressionModel.score(x_train,y_train) print ('Training Accuracy:',training_accuracy) # Lets us see how it is done ab-initio. Estimate prediction error logically for each sample # and save it in an array called Loss_Array # this line below will predict a category for every row in x_train predicted_label = LogisticRegressionModel.predict(x_train) def find_error(actual_label,predicted_label): '''actual_label= label in data predicted_label= label predicted by the model ''' Loss_Array = np.zeros(len(actual_label)) #create an empty array to store loss values # print(Loss_Array) for i,value in enumerate(actual_label): if value == predicted_label[i]: Loss_Array[i] = 0 else: Loss_Array[i] = 1 print ("Y-actualLabel Z-predictedLabel Error \n") for i,value in enumerate(actual_label): print (value,"\t\t" ,predicted_label[i],"\t\t",Loss_Array[i]) error_rate=np.average(Loss_Array) print ("\nThe error rate is ", error_rate) print ('\nThe accuracy of the model is ',1-error_rate ) find_error(y_train,predicted_label) ###Output Y-actualLabel Z-predictedLabel Error 1 1 0.0 2 2 0.0 1 0 1.0 2 2 0.0 1 1 0.0 2 2 0.0 2 2 0.0 0 1 1.0 1 1 0.0 2 2 0.0 0 1 1.0 1 1 0.0 2 2 0.0 2 2 0.0 2 2 0.0 1 1 0.0 1 1 0.0 0 1 1.0 0 0 0.0 0 0 0.0 2 2 0.0 2 2 0.0 0 1 1.0 1 0 1.0 1 0 1.0 1 1 0.0 0 1 1.0 0 0 0.0 0 0 0.0 2 2 0.0 2 2 0.0 0 0 0.0 1 0 1.0 0 0 0.0 0 0 0.0 0 0 0.0 1 1 0.0 1 1 0.0 0 0 0.0 2 2 0.0 2 2 0.0 1 1 0.0 1 1 0.0 2 2 0.0 1 0 1.0 0 0 0.0 0 0 0.0 1 1 0.0 2 2 0.0 1 1 0.0 0 0 0.0 2 2 0.0 0 1 1.0 0 0 0.0 0 0 0.0 0 0 0.0 2 2 0.0 2 2 0.0 2 2 0.0 1 1 0.0 1 1 0.0 2 2 0.0 1 0 1.0 1 0 1.0 2 2 0.0 0 0 0.0 0 0 0.0 0 0 0.0 1 0 1.0 2 2 0.0 0 0 0.0 0 0 0.0 1 0 1.0 2 2 0.0 2 2 0.0 0 0 0.0 0 0 0.0 1 1 0.0 0 0 0.0 0 0 0.0 1 0 1.0 0 1 1.0 2 2 0.0 2 2 0.0 2 2 0.0 0 0 0.0 1 1 0.0 0 0 0.0 1 0 1.0 0 0 0.0 0 0 0.0 2 2 0.0 1 1 0.0 1 1 0.0 2 2 0.0 0 0 0.0 0 0 0.0 2 2 0.0 2 2 0.0 0 0 0.0 0 1 1.0 2 2 0.0 2 2 0.0 0 1 1.0 1 1 0.0 0 0 0.0 2 2 0.0 2 2 0.0 1 1 0.0 1 1 0.0 2 2 0.0 2 2 0.0 1 0 1.0 1 1 0.0 0 0 0.0 2 2 0.0 2 2 0.0 1 0 1.0 0 0 0.0 2 2 0.0 The error rate is 0.18333333333333332 The accuracy of the model is 0.8166666666666667 ###Markdown Testing the model ###Code # TEST ACCURACY: # we will find accuracy of the model # using data that was not used for training the model test_accuracy=LogisticRegressionModel.score(x_test,y_test) print('Accuracy of the model on unseen test data: ',test_accuracy) ###Output Accuracy of the model on unseen test data: 0.7666666666666667 ###Markdown Accuracy can be misleading!Other measures of performance - Confusion matrix, Precision, Recall Confusion matrix What is a confusion matrix?A confusion matrix is a table that is often used to describe the performance of a classification model on a set of test data for which the true values are known.![image.png](attachment:image.png) Precision Precision (P) is defined as the number of true positives (T_p) over the number of true positives plus the number of false positives (F_p)![image.png](attachment:image.png) Recall Recall (R) is defined as the number of true positives (T_p) over the number of true positives plus the number of false negatives (F_n)![image.png](attachment:image.png) ###Code from sklearn.metrics import confusion_matrix y_true = y_test y_pred = LogisticRegressionModel.predict(x_test) ConfusionMatrix=pd.DataFrame(confusion_matrix(y_true, y_pred),columns=['Predicted 0','Predicted 1','Predicted 2'],index=['Actual 0','Actual 1','Actual 2']) print ('Confusion matrix of test data is: \n',ConfusionMatrix) from sklearn.metrics import precision_score print("Average precision for the 3 classes is - ", precision_score(y_true, y_pred, average = None) ) from sklearn.metrics import recall_score print("Average recall for the 3 classes is - ", recall_score(y_true, y_pred, average = None) ) # PLOT THE DECISION BOUNDARIES: # 1.create meshgrid of all points between ''' For that we will create a mesh between [x_min, x_max]x[y_min, y_max]. We will choose a 2d vector space ranging from values +- 0.5 from our min and max values of sepal_length and sepal_width. Then we will divide that whole region in a grid of 0.02 units cell size. ''' h = 0.02 # step size in the mesh x_min = X['sepal_length'].min() - .5 x_max = X['sepal_length'].max() + .5 y_min = X['sepal_width'].min() - .5 y_max = X['sepal_width'].max() + .5 # print x_min, x_max, y_min, y_max sepal_length_range = np.arange(x_min, x_max, h) sepal_width_range = np.arange(y_min, y_max, h) # Create datapoints for the mesh sepal_length_values, sepal_width_values = np.meshgrid(sepal_length_range, sepal_width_range) # Predict species for the fictious data in meshgrid predicted_species = LogisticRegressionModel.predict(np.c_[sepal_length_values.ravel(), sepal_width_values.ravel()]) print ('Finished predicting species') # another approach is to make an array Z2 which has all the predicted values in (xr,yr). predicted_species2= np.arange(len(sepal_length_range)*len(sepal_width_range)).reshape(len(sepal_length_range),len(sepal_width_range)) for yni in range(len(sepal_width_range)): for xni in range(len(sepal_length_range)): # print (xni, yni, LogisticRegressionModel.predict([[xr[xni],yr[yni]]])) predicted_species2[xni,yni] =LogisticRegressionModel.predict([[sepal_length_range[xni],sepal_width_range[yni]]]) print ('Finished predicted_species2') # Put the result into a color plot predicted_species = predicted_species.reshape(sepal_length_values.shape) plt.figure(figsize=(7,7)) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species , cmap=plt.cm.Paired) plt.title('Decision Boundaries and Class Regions identified by the trained model ') #plt.colorbar() plt.show() # Plot also the training points fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,7)) plt.subplot(1,2,1) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species , cmap=plt.cm.Paired) plt.scatter(X['sepal_length'], X['sepal_width'], c=Y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') #plt.colorbar() plt.xlim(sepal_length_values.min(),sepal_length_values.max()) plt.ylim(sepal_width_values.min(), sepal_width_values.max()) plt.xticks(()) plt.yticks(()) plt.title('ACTUAL data points on colored decision regions of the model ') # Put the result into a color plot of decison boundary plt.subplot(1,2,2) plt.title('PREDICTED labels of points on colored decision regions of the model ') plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() label=np.unique(y_test) plt.scatter(x_train['sepal_length'], x_train['sepal_width'], c=predicted_label, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(sepal_length_values.min(),sepal_length_values.max()) plt.ylim(sepal_width_values.min(), sepal_width_values.max()) plt.xticks(()) plt.yticks(()) plt.show() fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,7)) plt.subplot(1,2,1) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() label=np.unique(y_test) plt.title('TEST DATA -ACTUAL LABELS') # Plot also the training points plt.scatter(x_test['sepal_length'], x_test['sepal_width'], c=y_test,label=np.unique(y_test), edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.subplot(1,2,2) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() # Plot also the training points plt.scatter(x_test['sepal_length'], x_test['sepal_width'], c=LogisticRegressionModel.predict(x_test), edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.title('TEST DATA -PREDICTED LABELS') plt.show() ###Output _____no_output_____ ###Markdown Simple Linear Regression Example__Linear regression__ is a predictive modeling technique for predicting a numeric response variable based on features. "Linear" in the name linear regression refers to the fact that this method fits a model where response bears linear relationship with features. (ie Z is proportional to first power of x)__Z = X0 + a(X1) + b(X2) +.... where:__ Z: predicted response X0: intercept a,b,..: Coefficients of X1,X2.. If Y is the actual response and Z is the predicted response, __Y-Z= Residual__ Average Residual defines model performance,residual equal to zero represents a perfect fit model. ###Code '''Source: Scikit learn Code source: Jaques Grobler License: BSD 3 clause''' from sklearn import linear_model example_dff = pd.DataFrame(np.random.randint(0,100,size=(100, 1)),columns=['X']) example_dff['C']=5.1*example_dff['X'] # example_dff['C']=5.1*example_dff['X']**2 # FEATURES X_reg=example_dff[['X']] # Y Y_reg=example_dff['C'] # Create linear regression object LinearRegressionModel= linear_model.LinearRegression() # Train the model using the training sets LinearRegressionModel.fit(X_reg, Y_reg) Z_reg=LinearRegressionModel.predict(X_reg) # The coefficients print('Coefficients:', LinearRegressionModel.coef_) # The mean squared error print("Mean squared error:",np.mean((Z_reg - Y_reg) ** 2)) # Plot outputs plt.scatter(X_reg['X'], Y_reg, color='red') plt.plot(X_reg['X'], Z_reg, color='blue', linewidth=3) plt.xlabel('X') plt.ylabel('Y') plt.title('Linear Regression using data with one feature -X') plt.xticks(()) plt.yticks(()) plt.show() ###Output Coefficients: [5.1] Mean squared error: 0.0 ###Markdown With scaling: ###Code from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(X) X_scaled = scaler.transform(X) x_train_s, x_test_s, y_train, y_test = train_test_split(X_scaled, Y, test_size=0.2, random_state=100) # Name our logistic regression object LogisticRegressionModel_s = linear_model.LogisticRegression(solver = 'newton-cg', multi_class='multinomial') # we create an instance of logistic Regression Classifier and fit the data. print ('Training a logistic Regression Model..') LogisticRegressionModel_s.fit(x_train_s, y_train) training_accuracy_s=LogisticRegressionModel_s.score(x_train_s,y_train) print ('Training Accuracy:',training_accuracy_s) test_accuracy_s=LogisticRegressionModel_s.score(x_test_s,y_test) print('Accuracy of the model on unseen test data: ',test_accuracy_s) ###Output Training a logistic Regression Model.. Training Accuracy: 0.8166666666666667 Accuracy of the model on unseen test data: 0.7666666666666667 ###Markdown No difference! Some models/datasets do vastly change when scaling is applied (ex: neural networks, datasets with vastly different ranges in different columns) ###Code np.unique(Y) ###Output _____no_output_____ ###Markdown Introduction to Scikit-Learn Adapted by [Nimblebox Inc.](https://www.nimblebox.ai/) from [Data-X](https://datax.berkeley.edu/). Our predictive machine learning models perform two types of tasks:* __CLASSIFICATION__:LABELS ARE DISCRETE VALUES.Here the model is trained to classify each instance into a set of predefined discrete classes.On inputting a feature vector into the model, the trained model is able to predict a class of that instance.Eg: We train our model using income and expenditure data of bank customers using __defaulter or non-defaulter__ as labels. When we input income and expenditure data of any customer in this model, it will predict whether the customer is going to default or not.* __REGRESSION__:LABELS ARE CONTINUOUS VALUES.Here the model is trained to predict a continuous value for each instance.On inputting a feature vector into the model, the trained model is able to predict a continuous value for that instance.Eg: We train our model using income and expenditure data of bank customers using __default amount__ as the label. This model when input with income and expenditure data of any customer will be able to predict the default amount the customer might end up with. Machine learning model building steps -> Understanding the data: Understand your dataset using graphs, descriptive analysis etc. -> Cleaning the data: Removing outliers, Imputation of Null values, Removing null values -> Building the model: Build using appropriate algorithms -> Testing and iteration: Having testing outcomes and improve through each iteration What is scikit-learn?* Scikit-learn provides a range of supervised and unsupervised learning algorithms via a consistent interface in Python* This library is built upon SciPy (Scientific Python)* The library is focused on modeling data. It is not focused on loading, manipulating and summarizing data * We can do supervised and unsupervised learning with Scikit-learn * __TO GET STARTED:__:We will use python library -SCIKIT-LEARN for our classification and regression models.1. Install numpy, scipy, scikit-learn.2. Download the dataset provided and save it in your current working directory.3. In the following sections you will: 3.1 Read the dataset into the python program. 3.2 Look into the dataset characteristics, check for feature type - categorical or numerical. 3.3 Find feature distributions to check sufficiency of data. 3.4 Divide the dataset into training and validation subsets. 3.5 Fit models with training data using scikit-learn library. 3.6 Calculate training error,this gives you the idea of bias in your model. 3.7 Test model prediction accuracy using validation data,this gives you bias and variance error in the model. 3.8 Report model performance on validation data using different metrics. 3.9 Save the model parameters in a pickle file so that it can be used for test data. ###Code import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown ASSUMPTIONS:- **Problem**: 'Iris 'setosa' species has medicinal benefits and we want to make the process of identifying an iris species scalable' - **Type**: Classification- **Data**: Flower morphology data collected by floriculture department Understanding the data ###Code data=sns.load_dataset('iris') # lets us look at the data data.head(5) # lets us check unique labels: data['species'].value_counts() from sklearn.utils import shuffle # SHUFFLE data instances to randomize the distribution of different classes # Check if data has any NAN values, you can choose to drop NAN # containing rows or replace NAN values with mean. median,or any assumed value. data= shuffle(data).reset_index(drop=True) print('Number of NaNs in the dataframe:\n',data.isnull().sum()) data.head() # Our functions take in features and labels as arrays so we need to separate them # GET FEATURES X FROM THE DATA X=data.iloc[:,:-1] X.head() # GET LABELS Y FROM THE DATA Y=data['species'] print (Y.value_counts()) #gives the count of each label in the dataset print ('''\nWe will map our class labels to integers and then use in modeling. The mapping is:'versicolor': 0, 'virginica': 1,'setosa' :2 \n''') Y=Y.map({'versicolor': 0, 'virginica': 1,'setosa' :2}) print (Y.value_counts()) #gives the count of each label in the dataset Y.head() # should do sanity check on data often print("Feature vector shape=", X.shape) print("Class shape=", Y.shape) # More summary about our data data.describe() # Get feature distribution of each continuous valued feature (sepal_length and sepal_width) data.hist(figsize=(15,5)) plt.show() # Check feature distribution of each class, to get an overview of feature and class relationshhip, # also useful in validating data print(data.groupby('species').count()) data.groupby('species').hist(figsize=(10,5)) plt.show() ###Output sepal_length sepal_width petal_length petal_width species setosa 50 50 50 50 versicolor 50 50 50 50 virginica 50 50 50 50 ###Markdown Interactive plots using Plotly ###Code !pip install plotly==4.9.0 data.head() import plotly.express as px fig = px.scatter(data, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width']) fig.show() fig = px.bar(data, x="sepal_width", y="sepal_length", color="species", barmode="group") fig.show() ###Output _____no_output_____ ###Markdown Cleaning the modelWe do not have any NA values in the dataset- Use Pandas functions to remove na values, **Sklearn.preprocessing.Imputer** to impute the missing values.- Scaling the variables using **sklearn.preprocessing.StandardScaler** - The standard score of a sample x is calculated as: z = (x - u) / s- Scaling using Sklearn Min Max scaler - X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min Building the Model USE SKLEARN INBUILT FUNCTION TO BUILD A LOGISTIC REGRESSION MODELFor Details check :http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.htmlsklearn.linear_model.LogisticRegression.fitOur Hypothesis : Species of Iris is dependent on sepal length and width of the flower. In order to check the validity of our trained model, we keep a part of our dataset hidden from the model during training, called __Test data__.Test data labels are predicted using the trained model and compared with the actual labels of the data.This gives us the idea about how well the model can be trusted for its predictive power. We split our data into train/test -* __Training set__ : The sample of data used to fit your model.* __Test set__ : The sample of data used to provide an unbiased evaluation of a final model fit on the training dataset. ![image.png](attachment:image.png) * __Validation set__: The sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model hyperparameters![image.png](attachment:image.png) K-folds Cross Validation![image.png](attachment:image.png) Also, if our data set is small we will have fewer examples for validation.This will not give us a a good estimatiion of model error.We can use k-fold crossvalidation in such situations.In k-fold cross-validation, the shuffled training data is partitioned into k disjoint sets and the model is trained on k −1 sets and validated on the kth set. This process is repeated k times with each setchosen as the validation set once. The cross-validation accuracy is reported as the average accuracyof the k iterations ###Code # Split data into training and test set using sklearn function from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=100) print ('Number of samples in training data:',len(x_train)) print ('Number of samples in test data:',len(x_test)) ###Output Number of samples in training data: 120 Number of samples in test data: 30 ###Markdown Train our Logistic Regression Model ###Code from sklearn import linear_model # Name our logistic regression object LogisticRegressionModel = linear_model.LogisticRegression(solver = 'newton-cg', multi_class='multinomial') # we create an instance of logistic Regression Classifier and fit the data. print ('Training a logistic Regression Model..') LogisticRegressionModel.fit(x_train, y_train) ###Output Training a logistic Regression Model.. ###Markdown TRAINING ACCURACY ###Code # TRAINING ACCURACY training_accuracy=LogisticRegressionModel.score(x_train,y_train) print ('Training Accuracy:',training_accuracy) # Lets us see how it is done ab-initio. Estimate prediction error logically for each sample # and save it in an array called Loss_Array # this line below will predict a category for every row in x_train predicted_label = LogisticRegressionModel.predict(x_train) def find_error(actual_label,predicted_label): '''actual_label= label in data predicted_label= label predicted by the model ''' Loss_Array = np.zeros(len(actual_label)) #create an empty array to store loss values # print(Loss_Array) for i,value in enumerate(actual_label): if value == predicted_label[i]: Loss_Array[i] = 0 else: Loss_Array[i] = 1 print ("Y-actualLabel Z-predictedLabel Error \n") for i,value in enumerate(actual_label): print (value,"\t\t" ,predicted_label[i],"\t\t",Loss_Array[i]) error_rate=np.average(Loss_Array) print ("\nThe error rate is ", error_rate) print ('\nThe accuracy of the model is ',1-error_rate ) find_error(y_train,predicted_label) ###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ing the model ###Code # TEST ACCURACY: # we will find accuracy of the model # using data that was not used for training the model test_accuracy=LogisticRegressionModel.score(x_test,y_test) print('Accuracy of the model on unseen test data: ',test_accuracy) ###Output Accuracy of the model on unseen test data: 0.9333333333333333 ###Markdown Accuracy can be misleading!Other measures of performance - Confusion matrix, Precision, Recall Confusion matrix What is a confusion matrix?A confusion matrix is a table that is often used to describe the performance of a classification model on a set of test data for which the true values are known.![image.png](attachment:image.png) Precision Precision (P) is defined as the number of true positives (T_p) over the number of true positives plus the number of false positives (F_p)![image.png](attachment:image.png) Recall Recall (R) is defined as the number of true positives (T_p) over the number of true positives plus the number of false negatives (F_n)![image.png](attachment:image.png) ###Code from sklearn.metrics import confusion_matrix y_true = y_test y_pred = LogisticRegressionModel.predict(x_test) ConfusionMatrix=pd.DataFrame(confusion_matrix(y_true, y_pred),columns=['Predicted 0','Predicted 1','Predicted 2'],index=['Actual 0','Actual 1','Actual 2']) print ('Confusion matrix of test data is: \n',ConfusionMatrix) from sklearn.metrics import precision_score print("Average precision for the 3 classes is - ", precision_score(y_true, y_pred, average = None) ) from sklearn.metrics import recall_score print("Average recall for the 3 classes is - ", recall_score(y_true, y_pred, average = None) ) from sklearn.metrics import classification_report print(classification_report(y_true, y_pred)) # PLOT THE DECISION BOUNDARIES: # 1.create meshgrid of all points between ''' For that we will create a mesh between [x_min, x_max]x[y_min, y_max]. We will choose a 2d vector space ranging from values +- 0.5 from our min and max values of sepal_length and sepal_width. Then we will divide that whole region in a grid of 0.02 units cell size. ''' h = 0.02 # step size in the mesh x_min = X['sepal_length'].min() - .5 x_max = X['sepal_length'].max() + .5 y_min = X['sepal_width'].min() - .5 y_max = X['sepal_width'].max() + .5 # print x_min, x_max, y_min, y_max sepal_length_range = np.arange(x_min, x_max, h) sepal_width_range = np.arange(y_min, y_max, h) # Create datapoints for the mesh sepal_length_values, sepal_width_values = np.meshgrid(sepal_length_range, sepal_width_range) # create a 2 feature regression model LogisticRegressionModel.fit(x_train[['sepal_length','sepal_width']], y_train) # Predict species for the fictious data in meshgrid predicted_species = LogisticRegressionModel.predict(np.c_[sepal_length_values.ravel(), sepal_width_values.ravel()]) print ('Finished predicting species') # another approach is to make an array Z2 which has all the predicted values in (xr,yr). predicted_species2= np.arange(len(sepal_length_range)*len(sepal_width_range)).reshape(len(sepal_length_range),len(sepal_width_range)) for yni in range(len(sepal_width_range)): for xni in range(len(sepal_length_range)): # print (xni, yni, LogisticRegressionModel.predict([[xr[xni],yr[yni]]])) predicted_species2[xni,yni] =LogisticRegressionModel.predict([[sepal_length_range[xni],sepal_width_range[yni]]]) print ('Finished predicted_species2') # Put the result into a color plot predicted_species = predicted_species.reshape(sepal_length_values.shape) plt.figure(figsize=(7,7)) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species , cmap=plt.cm.Paired) plt.title('Decision Boundaries and Class Regions identified by the trained model ') #plt.colorbar() plt.show() # Plot also the training points fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,7)) plt.subplot(1,2,1) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species , cmap=plt.cm.Paired) plt.scatter(X['sepal_length'], X['sepal_width'], c=Y, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') #plt.colorbar() plt.xlim(sepal_length_values.min(),sepal_length_values.max()) plt.ylim(sepal_width_values.min(), sepal_width_values.max()) plt.xticks(()) plt.yticks(()) plt.title('ACTUAL data points on colored decision regions of the model ') # Put the result into a color plot of decison boundary plt.subplot(1,2,2) plt.title('PREDICTED labels of points on colored decision regions of the model ') plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() label=np.unique(y_test) plt.scatter(x_train['sepal_length'], x_train['sepal_width'], c=predicted_label, edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.xlim(sepal_length_values.min(),sepal_length_values.max()) plt.ylim(sepal_width_values.min(), sepal_width_values.max()) plt.xticks(()) plt.yticks(()) plt.show() fig, ax = plt.subplots(nrows=1,ncols=2,figsize=(15,7)) plt.subplot(1,2,1) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() label=np.unique(y_test) plt.title('TEST DATA -ACTUAL LABELS') # Plot also the training points plt.scatter(x_test['sepal_length'], x_test['sepal_width'], c=y_test,label=np.unique(y_test), edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.subplot(1,2,2) plt.pcolormesh(sepal_length_values,sepal_width_values,predicted_species, cmap=plt.cm.Paired) #plt.colorbar() # Plot also the training points plt.scatter(x_test['sepal_length'], x_test['sepal_width'], c=LogisticRegressionModel.predict(x_test[['sepal_length','sepal_width']]), edgecolors='k', cmap=plt.cm.Paired) plt.xlabel('Sepal length') plt.ylabel('Sepal width') plt.title('TEST DATA -PREDICTED LABELS') plt.show() ###Output _____no_output_____ ###Markdown Simple Linear Regression Example__Linear regression__ is a predictive modeling technique for predicting a numeric response variable based on features. "Linear" in the name linear regression refers to the fact that this method fits a model where response bears linear relationship with features. (ie Z is proportional to first power of x)__Z = X0 + a(X1) + b(X2) +.... where:__ Z: predicted response X0: intercept a,b,..: Coefficients of X1,X2.. If Y is the actual response and Z is the predicted response, __Y-Z= Residual__ Average Residual defines model performance,residual equal to zero represents a perfect fit model. ###Code '''Source: Scikit learn Code source: Jaques Grobler License: BSD 3 clause''' from sklearn import linear_model example_dff = pd.DataFrame(np.random.randint(0,100,size=(100, 1)),columns=['X']) example_dff['C']=5.1*example_dff['X'] # example_dff['C']=5.1*example_dff['X']**2 # FEATURES X_reg=example_dff[['X']] # Y Y_reg=example_dff['C'] # Create linear regression object LinearRegressionModel= linear_model.LinearRegression() # Train the model using the training sets LinearRegressionModel.fit(X_reg, Y_reg) Z_reg=LinearRegressionModel.predict(X_reg) # The coefficients print('Coefficients:', LinearRegressionModel.coef_) # The mean squared error print("Mean squared error:",np.mean((Z_reg - Y_reg) ** 2)) # Plot outputs plt.scatter(X_reg['X'], Y_reg, color='red') plt.plot(X_reg['X'], Z_reg, color='blue', linewidth=3) plt.xlabel('X') plt.ylabel('Y') plt.title('Linear Regression using data with one feature -X') plt.xticks(()) plt.yticks(()) plt.show() ###Output Coefficients: [5.1] Mean squared error: 1.168919100999296e-26 ###Markdown With scaling: ###Code from sklearn.preprocessing import StandardScaler,MinMaxScaler scaler = StandardScaler() scaler.fit(X) X_scaled = scaler.transform(X) scaler_mm = MinMaxScaler() scaler_mm.fit(X) X_scaled_mm = scaler.transform(X) x_train_s, x_test_s, y_train, y_test = train_test_split(X_scaled, Y, test_size=0.2, random_state=100) # Name our logistic regression object LogisticRegressionModel_s = linear_model.LogisticRegression(solver = 'newton-cg', multi_class='multinomial') # we create an instance of logistic Regression Classifier and fit the data. print ('Training a logistic Regression Model..') LogisticRegressionModel_s.fit(x_train_s, y_train) training_accuracy_s=LogisticRegressionModel_s.score(x_train_s,y_train) print ('Training Accuracy:',training_accuracy_s) test_accuracy_s=LogisticRegressionModel_s.score(x_test_s,y_test) print('Accuracy of the model on unseen test data: ',test_accuracy_s) ###Output Training a logistic Regression Model.. Training Accuracy: 0.975 Accuracy of the model on unseen test data: 0.9666666666666667 ###Markdown No difference! Some models/datasets do vastly change when scaling is applied (ex: neural networks, datasets with vastly different ranges in different columns) ###Code np.unique(Y) ###Output _____no_output_____ ###Markdown Let's train a regression model to predict 'petal_width' on the iris dataset ###Code x_train, x_test, y_train, y_test = train_test_split(X[['sepal_length','sepal_width','petal_length']], X['petal_width'], test_size=0.2, random_state=100) # Create linear regression object LinearRegressionModel= linear_model.LinearRegression() # Train the model using the training sets LinearRegressionModel.fit(x_train, y_train) preds=LinearRegressionModel.predict(x_test) # The coefficients print('Coefficients:', LinearRegressionModel.coef_) # The mean squared error print("Mean squared error:",np.mean((preds - y_test) ** 2)) ###Output Coefficients: [-0.15843222 0.22329056 0.5047472 ] Mean squared error: 0.055370759091792385
notebooks/fgv_classes/professor_hitoshi/aula 3 - sckitlearn - parte I.ipynb
###Markdown Machine Learning - Parte I Vamos começar a falar sobre os algoritmos de machine learning, começando por um de regressão. Regressão linear é um algoritmo largamente utilizado, tendo já completado dois séculos de existência desde que sua primeira forma de utilização foi publicada no começo do século XIX. Apesar de não ser o que conduz ao melhor modelo, daremos os primeiros passos para entender:* métricas de desempenho de modelos, ou seja como comparar modelos* estratégias de validação: separação entre treino e testeAlém disso, introduziremos uma notação comum a todos os algoritmos da seguinte maneira:* $X$ : matriz de features* $y$ : vetor com os objetivos da predição Regressão ****** Fornecidos $x$ and $y$, o objetivo da regressão linear é: Criar um modelo preditivo para predizer o $y$ a partir de $x_i$ Modelar a importancia entre cada variável dependente $x_i$ e $y$ Nem todos os $x_i$ tem relação com $y$ Quais $x_i$ que mais contribuem para determinar $y$? recap***[Regressão Linear](http://en.wikipedia.org/wiki/Linear_regression) é um metodo para modelar a relação entre um conjunto de variaveis independentes $x$ (explanatórias, features, preditores) e uma variável dependente $Y$. Esse metodo assume que $x$ tem uma relação linear com $y$. $$ y = \beta_0 + \beta_1 x + \epsilon$$one $\epsilon$ refere-se a um erro. * $\beta_0$ é a intercepto do modelo* O objetivo será estimar os coeficientes (e.g. $\beta_0$ and $\beta_1$). Representamos as estimativas com o "chapeu" em cima da letra. $$ \hat{\beta}_0, \hat{\beta}_1 $$* Uma vez obtido a estimativa dos coeficientes $\hat{\beta}_0$ and $\hat{\beta}_1$, podemos usar para predizer novos valores de $Y$$$\hat{y} = \hat{\beta}_0 + \hat{\beta}_1 x_1$$* Regressão Linear Multipla é quando há mais de uma variavel independente * $x_1$, $x_2$, $x_3$, $\ldots$$$ y = \beta_0 + \beta_1 x_1 + \ldots + \beta_p x_p + \epsilon$$ ###Code import numpy as np import pandas as pd from pandas import Series,DataFrame import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') %matplotlib inline from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression # from sklearn.cross_validation import train_test_split from sklearn.model_selection import train_test_split ###Output _____no_output_____ ###Markdown Importando o dataset: ###Code boston = load_boston() print(boston.DESCR) ###Output .. _boston_dataset: Boston house prices dataset --------------------------- **Data Set Characteristics:** :Number of Instances: 506 :Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target. :Attribute Information (in order): - CRIM per capita crime rate by town - ZN proportion of residential land zoned for lots over 25,000 sq.ft. - INDUS proportion of non-retail business acres per town - CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise) - NOX nitric oxides concentration (parts per 10 million) - RM average number of rooms per dwelling - AGE proportion of owner-occupied units built prior to 1940 - DIS weighted distances to five Boston employment centres - RAD index of accessibility to radial highways - TAX full-value property-tax rate per $10,000 - PTRATIO pupil-teacher ratio by town - B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town - LSTAT % lower status of the population - MEDV Median value of owner-occupied homes in $1000's :Missing Attribute Values: None :Creator: Harrison, D. and Rubinfeld, D.L. This is a copy of UCI ML housing dataset. https://archive.ics.uci.edu/ml/machine-learning-databases/housing/ This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University. The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic prices and the demand for clean air', J. Environ. Economics & Management, vol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics ...', Wiley, 1980. N.B. Various transformations are used in the table on pages 244-261 of the latter. The Boston house-price data has been used in many machine learning papers that address regression problems. .. topic:: References - Belsley, Kuh & Welsch, 'Regression diagnostics: Identifying Influential Data and Sources of Collinearity', Wiley, 1980. 244-261. - Quinlan,R. (1993). Combining Instance-Based and Model-Based Learning. In Proceedings on the Tenth International Conference of Machine Learning, 236-243, University of Massachusetts, Amherst. Morgan Kaufmann. ###Markdown Carregando o dataframe ###Code # carregando o df boston_df = pd.DataFrame(boston.data) # nome das colunas boston_df.columns = boston.feature_names ###Output _____no_output_____ ###Markdown Explorando o dataframe ###Code boston_df.sample(5) boston_df.plot(kind='scatter', x = 'RM', y = 'AGE') sns.jointplot(data=boston_df, x = 'RM', y = 'AGE', kind = 'hex') sns.jointplot(data=boston_df, x = 'RM', y = 'AGE', kind = 'kde') # introduzindo a coluna de precos boston_df['Preco'] = boston.target boston_df.sample(5) # Histograma dos preços (alvo da predição) plt.hist(boston_df['Preco'], bins = 50); # Nome dos eixos plt.xlabel('Precos in $1000s'); plt.ylabel('Numero de towns'); boston_df_sample = boston_df.sample(frac = 0.1) # Plotando a coluna #5 (RM) # plt.scatter(boston_df['RM'], boston_df['Preco']) sns.jointplot(data = boston_df, x = 'RM', y = 'Preco', kind = 'hex'); #label plt.ylabel('Precos em $1000s'); plt.xlabel('Media da qtd de comodos por habitacao'); ###Output _____no_output_____ ###Markdown Problema de negócio: Quero predizer o preço. Se eu tivesse somente uma feature...(e usando scipy) ###Code # como seria... sns.lmplot('RM', 'Preco', data=boston_df, fit_reg=True) # Tentem isso tambem... # sns.jointplot('RM', 'Preco', data=boston_df, kind = 'reg') ###Output _____no_output_____ ###Markdown Objetivo: encontrar os "melhores" $a$ e $b$ $y = a.x + b$onde* $y$ : preço* $x$ : qtd média de quartos ###Code from scipy import stats import numpy as np X = boston_df.RM y = boston_df.Preco a, b, r_value, p_value, std_err = stats.linregress(X,y) inclinacao, intercepto = a, b print (inclinacao) print (intercepto) quartos = np.array(X) precos = np.array(y) pred = a * quartos + b # RMSE rmse = np.sqrt(np.mean((pred - precos) ** 2)) print ('RMSE =', rmse) np.sqrt(np.mean((pred - precos) ** 2)) ###Output _____no_output_____ ###Markdown Uma interpretação do RMSE ###Code r = 6 p = a * r + b print ('Para uma cidade (town) cuja media de comodos é', r, 'comodos...') print ('o preço previsto será %.2f, e ...'% p) print ('... em 68%% das observações, o preco fica entre %.2f e %.2f.' % (p - rmse, p + rmse)) print ('... em 95%% das observações, o preco fica entre %.2f e %.2f.' % (p - 2*rmse, p + 2*rmse)) ###Output Para uma cidade (town) cuja media de comodos é 6 comodos... o preço previsto será 19.94, e ... ... em 68% das observações, o preco fica entre 13.34 e 26.55. ... em 95% das observações, o preco fica entre 6.74 e 33.15. ###Markdown Como encontrar os "melhores" $a$ e $b$?** => Metodo dos minimos quadrados **In English: Least Squares Method.Como seaborn encontra a linha acima? ###Code from IPython.display import Image url = 'http://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Linear_least_squares_example2.svg/220px-Linear_least_squares_example2.svg.png' Image(url) ###Output _____no_output_____ ###Markdown Pergunta: qual a melhor linha azul que representa o conjunto de pontos vermelhos? Resposta: a que minimiza a soma dos quadrados das linhas verdes (o erro) \begin{equation*}MSE\quad = \frac { 1 }{ n } \sum _{ i=0 }^{ n-1 }{ { { (\hat { { y }^{ (i) } } } }-{ y }^{ (i) })^{ 2 } } \quad \end{equation*} \begin{equation*}RMSE\quad = \sqrt { \frac { 1 }{ n } \sum _{ i\quad =\quad 0 }^{ n-1 }{ { { (\hat { { y }^{ (i) } } } }-{ y }^{ (i) })^{ 2 } } } \quad \end{equation*} agora com multiplas variáveis ###Code # primeira observação: boston_df.iloc[0] ###Output _____no_output_____ ###Markdown Notação:$x^{(0)}_{CRIM} = 0.00632$$x^{(0)}_{ZN} = 18.00000$$x^{(0)}_{LSTAT} = 4.98$$y^{(0)} = 24$ A principal "jogada" da regressão linear é considerar que cada feature contribui linearmente na composição do preço:$\hat{y^{(i)}} = a_{CRIM}.x^{(i)}_{CRIM} + a_{ZN}.x^{(i)}_{ZN} + ... + a_{LSTAT}.x^{(i)}_{LSTAT} + b$, para $i = 0, 1, 2,..., n-1$ e o objetivo será encontrar $a_{CRIM}, a_{ZN}, ...,a_{LSTAT}, b$ que minimizam o erro Numa forma matricial, podemos re-escrever o problema da seguinte maneira:\begin{equation*}\mathbf{X}.\mathbf{a} = \hat{\mathbf{y}}\end{equation*}\begin{equation*}\mathbf{X} = \begin{bmatrix}x^{(0)}_{CRIM} & x^{(0)}_{ZN} & ... & x^{(0)}_{LSTAT} & 1 \\x^{(1)}_{CRIM} & x^{(1)}_{ZN} & ... & x^{(1)}_{LSTAT} & 1 \\... & ... & ... & ...\\x^{(n-1)}_{CRIM} & x^{(n-1)}_{ZN} & ... & x^{(n-1)}_{LSTAT} & 1 \\\end{bmatrix}\end{equation*}\begin{equation*}\mathbf{a} = \begin{bmatrix}a_{CRIM} \\a_{ZN} \\... \\a_{LSTAT}\\b \\\end{bmatrix}\end{equation*}\begin{equation*}\mathbf{y} = \begin{bmatrix}\hat{y^{(0)}} \\\hat{y^{(1)}} \\... \\\hat{y^{(n-1)}}\\\end{bmatrix}\end{equation*} Engenharia e seleção de features... ###Code sns.pairplot(data=boston_df.iloc[:,:4]) boston_df.columns ###Output _____no_output_____ ###Markdown treinamento e predição com sklearn começam aqui... ###Code # Regressão linear - sklearn import sklearn from sklearn.linear_model import LinearRegression lreg = LinearRegression() ###Output _____no_output_____ ###Markdown Funções utilizadas:* `lreg.fit()` : para treinar o modelo* `lreg.predict()` : predição do valor, segundo um modelo treinado* `lreg.score()` : retorna o coeficiente de determinação (R^2), uma medida de quão bem o modelo captura as observações. ###Code # Separando as matrizes X (features) e y (labels) X = boston_df.drop('Preco', axis = 1) y = boston_df.Preco lreg.fit(X, y) lreg.intercept_ lreg.coef_ print ('Valor do coeficiente b, tambem chamado de intercept:', lreg.intercept_) # Vamos agora ver os coeficientes: coeff_df = DataFrame(boston_df.columns) coeff_df.columns = ['Features'] # coluna com os coeficientes coeff_df["Estimativa dos coeficientes"] = pd.Series(lreg.coef_) # mostra coeficientes coeff_df coeff_df.set_index('Features').plot(kind = 'bar', figsize = (12, 8)) # calibrando os coeficientes pelo valor medio da variavel coeff_df.set_index('Features', inplace = True) coeff_df = pd.concat([coeff_df, boston_df.mean()], axis = 1).rename(columns = {0: 'media'}) coeff_df['coef_vezes_media'] = coeff_df['Estimativa dos coeficientes'] * coeff_df.media coeff_df.coef_vezes_media.plot(kind = 'bar', figsize = (12, 8)) boston_df.head(3) #lreg = LinearRegression() #lreg.fit(X, y) lreg.predict(X) print("Treinei com X: RMSE com y: %.2f" % np.sqrt(np.mean((y - lreg.predict(X)) ** 2))) from sklearn.metrics import mean_squared_error np.sqrt(mean_squared_error(y, lreg.predict(X))) ###Output _____no_output_____ ###Markdown Treinamento e Validação Objetivo de separar os dados em treinamento e teste*** No exemplo acima: Treinamos e testamos na mesma base É esperado que as predições sobre essa base sejam boas, mas e quanto a novos dados? sim novos dados Um solução seria repartir dados, reservando uma parte para teste e treinando o modelo no restante isso se chama validação cruzada *** ###Code from sklearn.model_selection import train_test_split # Repartindo o dados em treinamento e validação X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state = 999, test_size = 0.25) # quais são os shapes de cada parte print(X_train.shape, X_valid.shape, y_train.shape, y_valid.shape) set(X_train.index) & set(X_valid.index) ###Output _____no_output_____ ###Markdown Predição de preços ###Code # recriando o objeto lreg = LinearRegression() # treinando de novo, mas somente com os dados de treinamento lreg.fit(X_train,y_train) # Predição das observações de validação pred_train = lreg.predict(X_train) pred_valid = lreg.predict(X_valid) print("Treinei com X_train: RMSE com y_train: %.2f" % np.sqrt(np.mean((y_train - pred_train) ** 2))) print("Treinei com X_train, RMSE sobre X_valid e y_valid: %.2f" % np.sqrt( np.mean((y_valid - pred_valid) ** 2)) ) # R^2 desse fit lreg.score(X_valid, y_valid) ###Output _____no_output_____
intro-to-python/1-say-hi-to-python.ipynb
###Markdown Intro to Python: From 'Hello World' to Basic Scientific Computing A few general notes: Coding is a skill just like playing an instrument, knitting, or wood-carving. It takes a lot of practice to become proficient, especially to the point where you're making things that are pretty. However, the key thing to remember is... all practice is good practice, and it's just software. You literally cannot harm your computer by writing bad python code. You might accidentally shut it down by generating an infinite loop... but 'oh well, try again after it reboots.' **Be tenacious, practice a lot, and make cool things.** Python is neat Python is very popular; it's the second most [common language on github](https://octoverse.github.com/)More than that, python was built to have a more friendly learning curve and has a ton of packages that allow it to be used for just about any project you can think of. Python is used by the [biggest tech companies](https://realpython.com/world-class-companies-using-python/) in the world. Here are some things I've built with python:- A program that learns to generate random faces.- A parachute that auto-pilots itself back to a fixed point.- Web apps that gather data from users on Amazon Turk.- A model that learns to win Atari games.- Scripts to automate photo processing.- A program that recognizes voice commands.- A personal website. First thing's first, RTFM: Read the *Fun* Manual!Python has truly fantastic docs. I've worked in data science since 2011 and I still refer to these docs multiple times a week. Don't be afraid to use them! Find them [here](https://docs.python.org/3/). The Library Reference and Tutorial are probably the most helpful.Frequent reference to documentation is the sign of a mature, capable programmer.An attitude that "I'm better than someone who needs to look things up." is a sign of someone with a lot to learn. Our WorkflowIt's rare that two people who write code use exactly the same programming languages, packages, text editors, and other tools.**There are many paths up the mountain.** Today, you'll learn one path that I've found to be generally accessible and powerful. As you learn, remember that this is not the only way to do these things. JupyterAt the core of our workflow is Jupyter. Jupyter is a common interface to many of the tools you will use to develop useful, readable, reproducable code. Jupyter works in the browser, so it's a flexible tool that we can access from nearly any modern computer. Starting Jupyter*Windows*:Find and open the program Anaconda Prompt, which we just installed. You will use this in place of the Terminal program in Mac/Linux instructions.*Mac/Linux*:On Mac and Linux, we will run things from the Terminal. This is a program that allows you to enter and execute text commands.Test out everything by typing `jupyter lab` into the Terminal and hitting enter. File SystemThe first thing you see when you navigate to the jupyter server is the file view. Here, you can navigate the filesystem and even modify it. Three ways to run code InterpreterPython is an "interpreted" language. This means that when your code is executed, each line is read by the computer and evaluated before the next line is read in. This is different from "compiled" languages where an entire program is read all at once and then compiled before it can be executed.Becaue python is interpreted, we have a lot of freedom to tinker around. We can run a line of code, see what happens, and if it doesn't do what we want, we can edit the line and run it again.To see this in action, we'll use jupyter to open a new terminal.We can then run standard unix commands like `whoami`.To start the python interpreter, type `python` and hit enter **we code**Okay, now we're going to write our first program!In the interpreter, type `print("Hey, there, world!")` and then hit enter.What happens?**you code**Now, change that line to say something else and re-run it. Okay, last thing is that you can leave the interpreter by typing `quit()` and then hitting enter. ScriptThe interpreter is great for testing things out but after you run things they just... dissapear. For the times when you want to preserve code to be re-run again, you can save it in a script. Let's use jupyter to open a new text file. You can create new files through the same menu you used to create a terminal. Name the file something like `script.py`. Now put the following code into the file:```pythonhello_message = "Hello, world!"full_message = hello_message + " Great to meet you!"print(full_message)```Now we can run the file by going back to our terminal and entering `python script.py`. Did that not work?- Make sure you're not still in the python interpreter. If your prompt still looks like `>>>` then you need to exit the interpreter with `quit()`.- Make sure your file is in the same folder as your terminal. Some handy terminal commands: - `ls` lists all the files and folders where you're at. - `pwd` prints the path to where you're at now. - `cd` is used to change directories. What is an iPython Notebook/Jupyter Notebook?What we're using today is an iPython notebook. It allows us to work in an interactive bunch of cells where we can write **real** Python code and then execute it on the fly. Memory persists across cells - meaning I can write a function in one cell and use it in another. We'll talk more about that later. The main controls to remember is that you can hit `shift+enter` to run a cell once you type in your code. You can also switch cells to 'Markdown' mode which allows you to write notes/text like I'm using here. You can also include images and stuff. You can learn more about 'Markdown' here: https://blog.ghost.org/markdown/ Hello World Pt 2Now, let's run our Hello World example the easy way: in the jupyter notebook ###Code print('Hello World') print("hello world") ###Output hello world ###Markdown Other handy things you can do in notebooks: - Tab completion: type most of a variable and then hit tab. Never have another typo!- Built-in documentation: use shift-tab when you're inside a function to see the documentation for that function.Try them! Let's check which python version we have.You can run short command line statements in jupyter by using the `!` magic (see below) ###Code # can access command line from Jupyter !python -V ###Output Python 3.6.5 :: Anaconda, Inc.
docs/.ipynb_checkpoints/page2-checkpoint.ipynb
###Markdown Intro이번 장에서는 제어문, 클래스, 패키지에 대해 공부합니다. - 직선적인 프로그램만으로 데이터를 다루는 데에는 한계가 있습니다. 제어문은 조건, 반복 등의 흐름 제어를 통해 효율적이고 유연한 프로그래밍을 가능하게 합니다. 앞으로도 계속해서 사용하게 될 문법이므로 조건문과 반복문은 충분히 연습해야 합니다. - 객체 지향 프로그래밍과 클래스는 파이썬의 핵심이지만, 아직 깊게 이해할 필요는 없습니다. 이번 장에서는 클래스의 개념과 기본적인 구조를 파악하는 것을 목적으로 합니다.- 패키지 역시 앞으로 파이썬을 사용하면서 계속해서 마주칠 개념입니다. 패키지의 기본적인 개념과 pip, conda를 활용하여 패키지를 설치/삭제하는 방법을 알면 충분합니다. 1. 조건문조건문은 프로그래밍 흐름에서 가지를 치는 역할을 합니다. 즉 주어진 조건을 판단하여 상황마다 다른 코드가 실행되도록 만드는 것이 조건문의 역할입니다. 파이썬의 조건문은 `if`, `else`, `elif` 의 세 가지 구문으로 이루어집니다. 이 구문들을 차례대로 살펴보겠습니다. 1.1. if ###Code if 조건: 조건이 True일 때 실행할 코드 # 들여쓰기 필수!! ###Output _____no_output_____ ###Markdown **`if` 는 조건과 함께 사용하며, 주어진 조건이 `True`일 때 이하의 코드를 실행합니다. 조건은 `True`/`False`로 진리값을 명확하게 판단할 수 있는 연산이어야 합니다.** `if` 문의 기본적인 구조는 위와 같습니다. `if` 다음 조건을 걸고 콜론을 적은 후, 다음 줄부터 조건이 참일 때 실행할 코드를 적어주면 됩니다. ###Code score = 90 if score >= 60: # score >= 60: 참이므로 다음 코드 실행 print("Pass") ###Output Pass ###Markdown 위 예시는 점수가 60점 이상이면 패스를 출력하는 조건문입니다. 첫 줄에서는 `score` 변수에 `90`을 할당합니다. `if` 문에서 `score >= 60`을 판단하고, 만약 참이라면 `"Pass"`를 프린트합니다. 조건이 참이므로 다음 코드를 실행하였습니다. 1.2. else ###Code if 조건: 조건이 참일 때 실행할 코드 # 들여쓰기 필수!! else: 조건이 거짓일 때 실행할 코드 # 들여쓰기 필수!! ###Output _____no_output_____ ###Markdown 조건이 참일 때만 조작이 필요하다면, `if` 만 사용해도 충분합니다. 하지만 조건이 거짓일 때도 그에 맞는 조작이 필요하다면, `else` 를 함께 사용합니다. **`if` 이하의 코드는 조건이 참일 때 실행되고, `else` 이하의 코드는 조건이 거짓일 때 실행됩니다. `else` 다음에는 조건을 붙이지 않습니다!** ###Code def pnp(score): if score >= 60: return("Pass") else: return("Non-Pass") pnp(score=1000) ###Output _____no_output_____ ###Markdown 위의 코드에서는 `pnp` 라는 함수 안에 조건문을 집어넣었습니다. 함수는 `score`라는 인자를 받으며, `score`가 `60`보다 크거나 같으면 `"Pass"`를 반환하고, 그렇지 않으면 `"Non-Pass"`를 반환합니다. - `pnp(60)`을 실행하면 함수는 `60 >= 60`을 판단합니다. 이 결과가 참이므로 `if` 이하의 코드인 `return("Pass")`가 실행되고, 함수는 종료됩니다. - `pnp(50)`을 실행하면 함수는 `50 >= 60`을 판단합니다. 결과가 거짓이므로 `if` 이하의 코드를 건너뛰고, `else` 로 넘어갑니다. 따라서 `return("Non-Pass")`가 실행됩니다. 1.3. elif ###Code if 조건 1: 조건 1이 True일 때 실행할 코드 elif 조건 2: 조건 1이 False 이고 조건 2가 True일 때 실행할 코드 elif 조건 3: 조건 1, 조건 2가 False 이고 조건 3가 True일 때 실행할 코드 . . . else: 모든 조건들이 False일 때 실행할 코드 ###Output _____no_output_____ ###Markdown 학생에게 A부터 F까지의 성적을 매기려고 하는 경우에는, `if` 와 `else` 만으로는 힘듭니다. 먼저 학생의 성적이 F인지 아닌지를 판단하고, F가 아닌 경우 D인지 아닌지 판단하고 이러한 과정을 A까지 반복해야 합니다. **`elif` 를 사용하면 이런 다중 분기를 손쉽게 구현할 수 있습니다.** `elif` 를 활용한 조건문의 구조는 위와 같습니다. `if` 문부터 순차적으로 조건을 판단하고, 거짓이면 다음 `elif`로 넘어가는 방식입니다. ###Code def grade(score): if score >= 90: return("A") elif score >= 80: # score >= 90 이 거짓: score >= 80 & score < 90 return("B") elif score >= 70: # score >= 80 이 거짓: score >= 70 & score < 80 return("C") elif score >= 60: # score >= 70 이 거짓: score >= 60 & score < 70 return("D") else: # score >= 60 이 거짓: score < 60 return("F") grade(89) grade(80) grade(70) grade(60) grade(50) ###Output _____no_output_____ ###Markdown 위의 코드는 점수에 따라 학점을 매기는 함수를 구현한 예시입니다. 가장 먼저 90점 이상인지를 판단하고, 이 결과가 거짓이면 다음 `elif` 로 넘어가서 80점 이상인지를 판단합니다. 이러한 과정을 60점까지 반복하고 나머지 경우에는 F를 반환합니다. **예제 1.1. 주어진 파일 이름 문자열의 확장자가 `.csv`, `.json`, `.xlsx` 중 하나이면 `True` 아니면 `False` 를 반환하는 함수를 작성하세요. 이후 이 함수를 `filelist` 에 매핑하세요.** ###Code filelist = [ "data.csv", "자기소개서.hwp", "졸업학점계산기.xlsx", "기말보고서.docx", "apiKey.json" ] def myFunction(filename): ext = filename.split(".")[-1] return ext in ["csv","json","xlsx"] list(map(myFunction, filelist)) [True, False, True, False, True] ###Output _____no_output_____ ###Markdown **풀이**1. 파일의 확장자를 판단하는 함수를 작성합니다. - 먼저 파일 이름에서 확장자를 분리해내야 합니다. 확장자는 파일 이름의 가장 마지막에 `.확장자` 형식으로 붙습니다. 따라서 파일 이름을 `.`을 기준으로 스플릿해준 후에, 결과로 나온 리스트의 마지막 요소를 인덱싱하면 확장자를 추출할 수 있습니다. - 확장자를 분리해냈으면 이 확장자가 `csv`, `xlsx`, `json` 중 하나에 속하는지 판단하면 됩니다. 조건문을 사용할 수도 있지만, `in` 연산을 사용해서 한번에 처리할 수도 있습니다. 확장자가 `["csv", "xlsx", "json"]` 중 하나에 속하면 `True`, 아니면 `False`를 반환합니다. 2. 만든 함수를 리스트에 매핑합니다. ###Code filelist = ["data.csv", "자기소개서.hwp", "졸업학점계산기.xlsx", "기말보고서.docx", "apiKey.json"] ###Output _____no_output_____ ###Markdown **조건문으로 구현한 함수** ###Code def myFunction(filename): ext = filename.split(".")[-1] if ext == "csv": return True elif ext == "xlsx": return True elif ext == "json": return True else: return False ###Output _____no_output_____ ###Markdown **`in` 연산으로 구현한 함수** ###Code def myFunction(filename): ext = filename.split(".")[-1] return ext in ["csv","xlsx","json"] result = list(map(myFunction,filelist)) print(result) ###Output [True, False, True, False, True] ###Markdown 2. 반복문 2.1. for in 반복문 for in 반복문의 구조 ###Code for 변수 in 리스트/튜플/...: 작업할코드 # 들여쓰기 필수! ###Output _____no_output_____ ###Markdown `for in` 반복문은 파이썬에서 가장 흔하게 사용되는 반복문이며, **리스트처럼 일정한 순서와 길이를 갖는 객체의 요소들에 같은 작업을 반복적으로 적용합니다.** 아래 예시 코드를 보겠습니다. **`for in` 반복문** **반복문을 풀어낸 코드** ###Code i = 1 print(i) i = 2 print(i) i = 3 print(i) ###Output 1 2 3 ###Markdown `for i in [1,2,3]`에서 `i`는 변수입니다. **반복문 `for i in [1,2,3]` 는 변수 `i`에 리스트 `[1,2,3]`의 요소들인 `1, 2, 3`을 순차적으로 할당합니다.** 즉 루프의 첫 번째 바퀴에서는 `i=1` 이 되고, 따라서 `print(i)`의 결과로 `1`이 출력됩니다. 루프의 두 번째, 세 번째 바퀴에서는 각각 `i=2`, `i=3`이 되고, 따라서 `print(i)`의 결과로 `2,3`이 출력됩니다. 함수를 만들 때와 마찬가지로, 콜론 이후의 절에서는 반드시 들여쓰기를 해주어야 합니다. **예제 2.1. 다음 코드를 반복문으로 구현해보세요** ###Code number = 100 print(number < 200) number = 200 print(number < 200) number = 300 print(number < 200) for number in [100, 200, 300]: print(number) ###Output 100 200 300 ###Markdown **풀이**위 코드에서는 number 변수에 100, 200, 300을 할당하면서 number < 200 연산을 동일하게 수행하고 있습니다. 따라서 100, 200, 300 을 리스트로 만들고 for 문을 적용하면 문제를 해결할 수 있습니다. ###Code for number in [100, 200, 300]: print(number < 200) ###Output True False False ###Markdown for i in range(n)`for in` 반복문은 `range(a,b)` 함수와 함께 사용되는 경우가 많습니다. `range(a,b)` 함수는 `a`부터 `b`까지의 정수 구간을 생성하는 함수이며, `b`는 구간에 포함되지 않습니다. `range(a)`와 같이 쓰면 `0`부터 `a`까지의 정수 구간을 생성하며, 역시 `a`는 구간에 포함되지 않습니다. ###Code for i in range(1,3): print(i) for i in range(3): print(i) ###Output 0 1 2 ###Markdown `for 변수 in 리스트` 와 같은 형태의 반복문에서 반드시 지정한 변수를 활용할 필요는 없습니다. 반복문은 반복하는 변수 `i`와 관계없는 작업을 단순히 `n`번 반복하기 위해 사용하기도 합니다. 아래 예시 코드를 보겠습니다. `for i in range(3)` 이라는 코드는 루프마다 `i=0`, `i=1`, `i=2`을 할당합니다. 하지만 실제 반복문 안에서 실행되는 코드는 `print("Hello world")` 로 `i`와는 전혀 관계가 없습니다. ###Code for i in range(1,10): print("Hello world") ###Output Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world Hello world ###Markdown **예제 2.2. for 반복문과 range 함수를 활용하여 1부터 100까지 자연수의 합을 구하세요** ###Code result = 0 # 반복문 밖의 변수 > 최종결과 저장 for i in range(1,101): result = result + i result ###Output _____no_output_____ ###Markdown **풀이**이번 문제를 풀기 위해서는 약간의 테크닉이 필요합니다. 먼저 반복문 바깥에 `result`라는 변수를 만들고 `0`을 할당합니다. 이후 `1`부터 `100`까지의 숫자를 차례대로 `result` 변수에 더해주면 합을 구할 수 있습니다. 반복문 외부에 결과를 저장할 변수를 만들고 루프를 돌면서 변수를 업데이트하는 기법은 자주 쓰이므로 기억해두면 좋습니다. ###Code result = 0 for i in range(1,101): result = result + i print(result) ###Output 5050 ###Markdown **예제 2.3. for 반복문과 range 함수를 활용하여 1\*\*2, 2\*\*2, 3\*\*2, ..., 10000\*\*2을 포함하는 리스트를 만들어보세요.** ###Code result = [] for i in range(1,10001): result.append(i**2) result ###Output _____no_output_____ ###Markdown **풀이**최종적으로 만들 결과물이 리스트이기 때문에, 반복문 밖에 빈 리스트를 생성합니다. 이후 `range(1,10001)` 를 이용해 구간을 생성하고, 루프를 돌면서 `i**2` 를 리스트에 추가해줍니다. 결과의 출력은 생략하겠습니다. ###Code mylist = [] for i in range(1,10001): mylist.append(i**2) ###Output _____no_output_____ ###Markdown List Comprehension위의 예제에서는 빈 리스트에 `append` 메소드를 반복적하여 리스트를 만들어 보았습니다. 이번에는 **List comprehension**이라는 기법을 사용하여 리스트를 만들어볼 것입니다. 아래는 지금까지 해왔던 방식으로 `0`부터 `9`까지의 숫자를 제곱한 리스트를 만드는 코드입니다. ###Code mylist = [] for i in range(10): mylist.append(i**2) [i ** 2 for i in range(10)] ###Output _____no_output_____ ###Markdown 아래는 리스트 컴프리헨션을 활용한 예시 코드입니다. **리스트 컴프리헨션은 대괄호 `[]`안에 연산과 반복문을 함께 적습니다. 반복되는 변수를 활용한 연산이 나오고, 이후에 반복문이 나온다는 점을 유의하세요.** 복잡해보일 수 있는 구조이지만, 콜론 뒤에 나오던 연산 과정이 앞으로 당겨졌을 뿐입니다. 리스트 컴프리헨션을 사용하면 `append`를 사용하는 것보다 더 간결하고 빠른 코드를 작성할 수 있습니다다. ###Code [연산 for 변수 in 리스트] # 리스트 컴프리헨션의 구조 mylist = [i**2 for i in range(10)] # 연산: i ** 2, 반복문: for i in range(10) print(mylist) ###Output [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ###Markdown **예제 2.4. 리스트 컴프리헨션을 사용하여 구구단 6단 리스트를 만드세요** ###Code [i * 6 for i in range(1,10)] [6, 12, 18, 24, 30, 36, 42, 48, 54] ###Output _____no_output_____ ###Markdown **풀이**구구단은 6\*1, 6\*2, ..., 6\*9 와 같이 진행됩니다. 즉 `6 * i`를 `i=1`부터 `i=9`까지 반복하면 구구단 6단을 만들 수 있습니다. 이 때 연산은 `6 * i`가 되고, 리스트는 `[1,2,...,9]`가 될 것입니다. 따라서 다음과 같은 코드를 사용하여 구구단 6단의 리스트를 만들 수 있습니다. ###Code [6 * i for i in range(1,10)] ###Output _____no_output_____ ###Markdown 2.2. while 반복문 ###Code while 조건: 조건이 참인 동안 실행할 코드 ###Output _____no_output_____ ###Markdown `while` 반복문은 `for in` 반복문과 달리, 조건과 함께 사용됩니다. `while` 이후의 조건이 참인 동안 조건 이후의 코드를 계속해서 수행하게 됩니다. ###Code while True: print("Press I + I to escape") ###Output _____no_output_____ ###Markdown 위 예시 코드에서는 조건이 `True`입니다. 즉 해당 반복문은 사용자가 멈추지 않는 이상 무한히 반복됩니다. `while` 반복문은 자주 사용하지는 않지만, 알아둘 필요는 있습니다. 2.3. 반복문 안에서의 흐름 제어반복문 안에 추가적으로 흐름을 제어하는 명령어들을 배치할 수 있습니다. `continue` 는 즉시 다음 바퀴로 넘어가는 명령어이고, `break` 는 반복을 멈추는 명령어입니다. 역시 자주 쓰이지는 않지만 알아둘 필요는 없습니다.명령어|기능---|---`continue`|즉시 다음 바퀴로 넘어감`break`|반복 정지, 다음 코드로 넘어감 **`continue`** ###Code for i in range(10): if i < 5: continue # 다음 바퀴로 넘어감 print(i) ###Output 5 6 7 8 9 ###Markdown **`break`** ###Code for i in range(10): if i == 5: break print(i) ###Output 0 1 2 3 4 ###Markdown 3. 객체 지향 프로그래밍과 클래스파이썬은 대표적인 객체 지향 프로그래밍 언어이며, 객체 지향과 클래스는 파이썬을 배우면서 언젠가는 짚고 넘어가야 하는 부분입니다. 하지만 객체 지향과 클래스가 단번에 이해할 수 있는 개념은 아닙니다. 사실 프로그래밍을 배운다는 것이 모든 스킬을 선형적으로 습득해가는 과정이 절대 아니기 때문에, 지금 이해가 가지 않는다고 해서 조급해할 필요는 없습니다. 또한 지금은 개발을 목적으로 파이썬을 배우는 것아 아니므로 클래스를 꼭 자유자재로 다룰 수 있어야 하는 것도 아닙니다. 만들어진 클래스의 구조를 이해하고 활용할 수 있는 정도면 충분합니다. 3.1. 클래스, 객체, 인스턴스프로그램은 수많은 명령어들로 이루어집니다. 하지만 객체 지향 프로그래밍에서는 명령어가 아닌 객체들이 프로그램의 중심이 됩니다. 객체란 마치 현실 세계에 존재하는 사물들과 유사한 것입니다. 현실 세계의 사물들은 특정한 속성을 갖고, 스스로 행동하거나 다른 사물들에 의해서 조작될 수 있습니다. 예를 들어 사람은 이름과 나이를 속성으로 가질 수 있고, 인사를 하는 등 행동을 할 수 있습니다. 인사를 할 수 있는 사람을 간단한 파이썬 프로그램으로 구현해보면 다음과 같습니다. 코드 해설을 모두 이해할 필요는 없고, 다만 우리가 현실세계의 사람을 모방해서 사람과 같은 속성을 갖고, 사람처럼 행동하는 무언가를 만들었다는 사실을 주목해주시면 됩니다. ###Code class person: def __init__(self, name, age): # person 클래스의 속성을 정의 self.name = name self.age = age def sayhello(self): print("Hello!") superson = person(name="손흥민", age=28) # 손흥민을 닮은 객체를 만들어봐요! superson.name # 속성 superson.age # 속성 superson.sayhello() # 메소드(행동) ###Output Hello! ###Markdown 가장 먼저 `class` 명령어를 사용해서 `person` 클래스를 만들었습니다. `superson = person(name="손흥민",age=28)` 은 이름이 `"손흥민"` 이고 나이가 `28` 인 사람을 만들어서 `superson`이라는 변수에 저장한 것입니다. 이제 파이썬 세상에서 `superson` 은 이름과 나이를 갖는 사람처럼 취급될 수 있습니다. `superson.name`, `supserson.age` 를 통해서 `superson`의 이름과 나이라는 속성에 접근할 수 있고, `superson.sayhello()` 를 통해서 인사를 하는 행동을 구현할 수도 있습니다. 클래스와 객체/인스턴스 구분하기- 클래스: 객체/인스턴스를 찍어내는 틀이자 객체/인스턴스가 속하는 그룹- 객체/인스턴스: 클래스에 의해 만들어진 존재, 대상**클래스는 객체가 속하는 그룹이자 객체를 찍어내는 틀입니다.** `person` 클래스를 구현해놓으면 서로 다른 속성을 갖는 여러 사람들을 손쉽게 만들어낼 수 있습니다. 아래는 `person` 클래스를 가지고 서로 다른 이름과 나이를 갖는 객체들을 만드는 예시입니다. 각자 다른 이름과 나이를 갖기는 하지만, 이들은 모두 `person` 클래스에 속하며, 일정한 속성과 메소드들을 공유합니다. ###Code supserson = person(name="손흥민", age=27) yoonaqueen = person(name="김연아", age=29) psy = person(name="박재상", age=41) yoonaqueen.sayhello() import pandas as pd data = pd.DataFrame({ "이름":["손흥민","김연아","싸이"], "나이":[27,29,41] }) data.나이 ###Output _____no_output_____ ###Markdown **클래스를 사용해서 만들어낸 실제 대상을 객체 혹은 인스턴스라고 부릅니다.** 객체와 인스턴스는 엄밀하게 구분하기도 하지만, 여기에서는 구분 없이 사용하겠습니다. 위의 예제에서 `person` 클래스를 사용해서 만든 `superson`, `yoonaqueen`, `psy` 가 모두 인스턴스입니다. 3.2. 클래스 만들기 class 명령어이제 본격적으로 클래스를 만드는 방법을 다뤄보겠습니다. 우선 아무것도 없는 빈 클래스를 만들어보겠습니다. 클래스를 만들 때는 class 라는 명령어를 사용합니다. `class 클래스이름:` 과 같이 적어주면 클래스를 생성할 수 있습니다. 아무 것도 포함하는 것이 없는 클래스를 만들기 위해 콜론 이후에는 `pass` 를 적어줍니다. 빈 클래스를 통해서도 인스턴스들을 찍어낼 수 있습니다. ###Code class person: pass superson = person() ###Output _____no_output_____ ###Markdown 클래스에 속성 부여하기하지만 위와 같은 클래스는 아무 속성도 갖지 않고, 아무런 행동도 할 수 없습니다. 이제부터는 속성을 갖는 `person` 클래스를 만들어보도록 하겠습니다. 클래스에 속성을 부여하기 위해서는, 클래스 안에 `__init__` 함수를 정의해야 합니다. **`__init__ ` 함수는 초기화, 혹은 시작을 뜻하며 클래스가 필수적으로 가져야 할 속성들을 정의합니다.** __init__ 함수의 기본적인 구조는 다음과 같습니다. ###Code def __init__(self, name, age, ...): self.name = name self.age = age ... ###Output _____no_output_____ ###Markdown **`__init__` 함수는 `self`, `속성` 이라는 두 종류의 매개변수를 갖습니다. `self` 는 클래스에 의해 생성될 인스턴스를 가리키며, 클래스 안에서 정의되는 모든 함수에 반드시 포함되어야 하는 매개변수입니다.** `self` 이후의 매개변수들은 자신이 원하는 속성들을 표현할 수 있는 변수 이름들을 나열해주시면 됩니다. 만약 `person` 클래스에 `name`과 `age`라는 속성을 정의하고 싶다면 우선 `self`, `name`, `age`라는 세 가지 매개변수를 갖는 `__init__` 함수를 클래스 안에 정의해야 합니다. 즉 우선 다음과 같이 써야 합니다. ###Code class person: def __init__(self, name, age): ###Output _____no_output_____ ###Markdown 이제 `__init__` 함수의 내부를 살펴볼 차례입니다. `__init__` 함수의 내부 구조는 간단하지만, 처음 보면 당황스러울 수 있습니다. 자신이 정의하려는 속성들을 `self.속성 = 속성`과 같이 차례로 할당해주면 됩니다. `self` 는 클래스에 의해 생성될 인스턴스라고 언급하였습니다. 따라서 `self.name` 코드는 새로 만들 인스턴스의 `name` 속성에 `name` 값을 할당하며, `self.age` 코드는 새로 만들 인스턴스의 `age` 속성에 `age` 값을 할당합니다. `name` 값과 `age` 값은 사용자가 인스턴스를 생성할 때 지정하기 때문에, 실제로 인스턴스를 생성하는 코드를 함께 봐야 이해하기 쉽습니다. 예를 들어 지금까지 만든 `person` 클래스로 `superson`이라는 인스턴스를 만든다면, `person` 클래스와 `__init__` 함수 내부에서는 다음과 같은 일이 발생할 것입니다. ###Code class person: def __init__(son, name, age): self.name = name # 인스턴스의 name 속성 = name 에 들어있는 값 self.age = age # 인스턴스의 age 속성 = age 에 들어있는 값 superson = person(name="손흥민", age=28) psy = person(name='박재상', age=40) ################## __init__ 함수 내부에서의 가상의 작용 ####################### __init__(self=superson, name="손흥민", age=28): superson.name = "손흥민" # superson.name 에는 "손흥민" 할당 superson.age = 28 # superson.age 에는 28 할당 ############################################################################### ###Output _____no_output_____ ###Markdown 클래스에 메소드 부여하기일정한 속성을 갖는 클래스를 생성했다면 이제는 메소드, 즉 행동을 정의해볼 차례입니다. 메소드는 역시 클래스 안에 함수로 정의하며, 자신이 원하는 이름으로 함수를 만들어주면 됩니다. 반드시 `self`를 매개변수로 갖는다는 점이 일반적인 함수와 다릅니다. ###Code def 메소드명(self, 인자1, 인자2, ...): 연산 return 결과물 ###Output _____no_output_____ ###Markdown 간단하게 매개변수 없이 `"Hello"` 를 프린트하는 `sayhello` 메소드를 정의해보겠습니다. 메소드는 만들어진 인스턴스 이름 뒤에 점을 짝고 사용하면 됩니다. ###Code class person: def __init__(self, name, age): self.name = name self.age = age def sayhello(self): print("Hello!") superson = person(name="손흥민", age=28) psy = person(name='박재상', age = 40) psy.sayhello() ###Output Hello! ###Markdown 이번에는 매개변수와 반환을 갖는 `run` 메소드를 정의해보겠습니다. 우선 추가적으로 사람이 1초 동안 달릴 수 있는 거리를 `speed` 라는 속성으로 정의합니다. `__init__` 함수에 `speed`와 관련된 코드를 추가해줍니다. 다음으로 매개변수 `t`를 받아서 `t`초 동안 달린 거리를 반환하는 `run` 메소드를 정의합니다. 인스턴스의 속도는 `self.speed`에 저장될 것이므로, `self.speed * t`를 계산하면 해당 인스턴스가 `t`초 동안 달린 거리를 구할 수 있습니다. 이 결과를 반환값으로 지정합니다. ###Code class person: def __init__(self, name, age, speed): self.name = name # 이름 self.age = age # 나이 self.speed = speed # 인스턴스의 속도 def sayhello(self): print("Hello!") def run(self, t): return self.speed * t # 인스턴스의 속도로 t초간 달린 거리 ###Output _____no_output_____ ###Markdown 이제 평범한 사람과 손흥민 선수가 같이 달려보겠습니다. 손흥민 선수는 1초에 100미터를 뛰는 스피드를 가졌고, 평범한 사람은 1초에 10미터를 뛰는 스피드를 가졌습니다. 사실 성인 남성 중에서도 굉장히 잘 뛰는 편인데, 손흥민 선수가 1000미터를 뛸 동안 평범한 사람은 100미터 밖에 뛰지 못했습니다. ###Code superson = person(name="손흥민", age=28, speed=100) superson.run(t=10) normal_guy = person(name="김철수", age=20, speed=10) normal_guy.run(t=10) ###Output _____no_output_____ ###Markdown 3. 패키지 3.1. 모듈패키지를 다루기 전에, 먼저 모듈이라는 개념에 대해 알아보겠습니다. 모듈은 함수나 변수, 클래스 등을 모아놓은 파일입니다. 즉 모듈은 결국 이미 만들어진 파이썬 코드들입니다. 모듈의 가장 큰 특징은 다른 프로그램에서 손쉽게 재사용할 수 있다는 점입니다. 따라서 다른 사람들이 작성한 코드들을 가져다 쓸 수도 있고, 자신이 작성한 코드를 모듈화해서 보관하였다가 나중에 재사용하는 것도 가능합니다. 일단 간단한 모듈을 만들어보면서 자세히 알아보겠습니다. 모듈은 파이썬 파일 `.py` 로 저장할 것이므로 주피터 노트북이 아닌 다른 에디터에서 코드를 작성하시기 바랍니다. ###Code def add(a,b): return a + b def sub(a,b): return a - b ###Output _____no_output_____ ###Markdown 위와 같이 덧셈, 뺄셈을 실행하는 간단한 함수 두 개를 정의하고, `mod1.py`라는 이름으로 주피터 노트북이 실행되고 있는 디렉토리에 저장합니다. 이제 파이썬에서 우리가 작성한 `mod1` 모듈을 불러와서 사용할 수 있습니다. ###Code import mod1 mod1.add(3,4) mod1.sub(5,1) ###Output _____no_output_____ ###Markdown `import` 문은 만들어진 모듈을 현재 파이썬 프로그램에 불러오는 구문입니다. `import mod1` 을 실행하면, `mod1` 모듈 안에 들어있는 `add` 함수와 `sub` 함수를 사용할 수 있게 됩니다. 모듈 안에 들어있는 함수나 클래스를 사용하려면 `모듈명.함수명()`, `모듈명.클래스멍()` 과 같이 모듈 이름 뒤에 점을 찍고 함수를 호출하면 됩니다. 즉 `mod1.add(3,4)` 는 `mod1` 모듈 안에 들어있는 `add` 함수를 실행하는 코드입니다. ###Code import mod1 as m from mod1 import add ###Output _____no_output_____ ###Markdown `import` 는 다양한 방식으로 실행할 수 있습니다. 첫 줄은 `mod1` 모듈을 `m`이라는 별칭(aliasing)로 불러오는 코드입니다. 이 경우 `m.add()`와 같이 자신이 지정한 이름으로 모듈을 사용할 수 있습니니다. 둘째 줄은 모듈로부터 특정한 함수만 불러오는 코드입니다. 때에 따라 모듈 전체를 프로그램에 불러올 필요가 없을 수도 있습니다. 이런 경우에는 `from 모듈명 import 함수/클래스` 와 같이 필요한 함수나 패키지를 특정하여 불러올 수도 있습니다. 이 경우, 모듈명을 생략하고 `add()`를 사용해서 즉시 `mod1` 모듈의 `add` 함수를 사용할 수 있습니다. 3.2. 패키지패키지는 계층적인 구조(디렉토리)로 관리되는 모듈들의 모음입니다. 즉 패키지 역시 사실은 파이썬 코드들의 모음입니다. 다음과 같은 구조로 된 패키지를 살펴보겠습니다. 물론 실제 `pandas` 패키지는 이와 동일하게 생기지는 않았습니다. `pandas` 패키지의 실제 구조는 [판다스 깃허브](https://github.com/pandas-dev/pandas)에서 확인할 수 있습니다. ###Code pandas/ __init__.py core/ __init__.py series.py frame.py io/ __init__.py api.py html.py ###Output _____no_output_____ ###Markdown `.py` 확장자가 붙은 파일은 파이썬 모듈이고, 확장자가 없고 /가 붙은 파일은 디렉토리 입니다. 즉 가장 상위에 `pandas` 라는 루트 디렉토리가 존재하고, 이 아래에 `\__init\__.py` 파일과 `core, io` 서브 디렉토리가 존재합니다. 각각의 서브 디렉토리 아래에는 다시 파이썬 모듈들이 들어있습니다. 만약 `padnas/core/series.py` 안에 들어있는 함수나 클래스에 접근하려면 어떻게 해야 할까요? 모듈에서 했던 것과 똑같이 점을 찍어서 하위 디렉토리로 내려가주면 됩니다. ###Code # 가상의 판다스 패키지 import pandas pandas.core.series.함수명() # pandas/core/series.py 안에 있는 함수 호출 pandas.core.series.클래스명() # pandas/core/series.py 안에 있는 클래스 호출 ###Output _____no_output_____ ###Markdown 여기에서 패키지의 계층적인 구조를 이해하는 것이 목표이며, 직접 패키지를 제작해보지는 않을 것입니다. 만약 직접 패키지를 만들어보고 싶다면 [점프 투 파이썬](https://wikidocs.net/1418) 교재를 참고하시기 바랍니다. 모듈과 패키지는 결국 이미 만들어진 파이썬 코드들의 모음이라고 했습니다. 우리는 데이터 분석에 필요한 코드들을 전부 직접 만들어서 사용하지는 않을 것이고, 다른 사람들이 만들어놓은 유용한 도구들을 찾아서 활용하게 될 것입니다. 물론 자신이 직접 유용한 패키지를 개발해서 배포한다면 파이썬 데이터 분석 생태계에 큰 도움이 되겠지만, 지금 당장은 시작하는 입장이므로 만들어진 툴을 잘 활용하는 것에 중점을 두도록 합시다! 3.3. 파이썬 패키지 관리자: pip & conda pip install`pip`는 파이썬의 패키지 관리 시스템입니다. `pip`를 통해서 다른 사람들이 개발한 패키지를 다운로드하거나, 이미 설치된 패키지를 업그레이드 혹은 삭제할 수도 있습니다. 다음은 `pip`의 기본적인 패키지 설치/삭제 명령어입니다. `pip` 명령어는 주피터 노트북 셀 혹은 기타 터미널에서 사용할 수 있습니다.- `pip install 패키지명`- `pip uninstall 패키지명`주피터 노트북이나 터미널 창에서 다음 명령어를 실행해보시기 바랍니다. `scikit-learn`은 파이썬의 대표적인 머신러닝 패키지이며, 딥러닝을 제외한 거의 모든 머신러닝에서 사실상의 표준입니다. 설치된 이후에는 import 문을 사용해서 사이킷 런의 선형회귀 클래스와 판다스, 넘파이를 주피터에 불러와보세요. ###Code pip install scikit-learn from sklearn.linear_model import LinearRegression # 사이킷런의 선형회귀 클래스 불러옴 import pandas as pd # pandas 패키지를 pd라는 별칭으로 불러옴 import numpy as np # numpy 패키지를 np라는 별칭으로 불러옴 ###Output _____no_output_____
ShapeFlow/ipynb/render_example.ipynb
###Markdown Unproject depth map to point cloud ###Code # take a sample point cloud from a shape m = trimesh.load("data/shapenet_watertight/val/03001627/bcc73b8ff332b4df3d25ee35360a1f4d/model_occnet.ply") eye_1 = [.8, .4, .5] eye_2 = [.3, .4, .9] center = [0, 0, 0] up = [0, 1, 0] img, depth, world2cam, cam2img = render_trimesh(m, eye_1, center, up, light_intensity=3) points_unproj = unproject_depth_img(depth, cam2img, world2cam) points_unproj_img_sameview, _, _, _ = render_trimesh(trimesh.PointCloud(points_unproj), eye_1, center, up, light_intensity=3) points_unproj_img_diffview, _, _, _ = render_trimesh(trimesh.PointCloud(points_unproj), eye_2, center, up, light_intensity=3) colors = np.zeros_like(points_unproj); colors[:, 1] = 1 points_unproj_img_overlay, _, _, _ = render_trimesh([trimesh.PointCloud(points_unproj, colors=colors), m], eye_2, center, up, light_intensity=3) fig, axes = plt.subplots(figsize=(25, 5), ncols=5) axes[0].imshow(img) axes[0].axis('off') axes[0].set_title("Rendered mesh (RGB)") d = depth.copy() d[depth==0] = np.nan axes[1].set_title("Rendered mesh (Depth)") c = axes[1].imshow(d) axes[1].axis('off') axes[2].imshow(points_unproj_img_sameview) axes[2].axis('off') axes[2].set_title("Unprojected points (same viewpoint)") axes[3].imshow(points_unproj_img_diffview) axes[3].axis('off') axes[3].set_title("Unprojected points (diff viewpoint)") axes[4].imshow(points_unproj_img_overlay) axes[4].axis('off') axes[4].set_title("Unprojected points (overlay)") # fig.colorbar(c, ax=axes[1]) plt.show() import pyrender from utils import render import glob import trimesh import numpy as np eye_1 = [.8, .4, .5] eye_2 = [.3, .4, .9] center = [0, 0, 0] up = [0, 1, 0] def line_meshes(verts, edges, colors=None, poses=None): """Create pyrender Mesh instance for lines. Args: verts: np.array floats of shape [#v, 3] edges: np.array ints of shape [#e, 3] colors: np.array floats of shape [#v, 3] poses: poses : (x,4,4) Array of 4x4 transformation matrices for instancing this object. """ prim = pyrender.primitive.Primitive( positions=verts, indices=edges, color_0=colors, mode=pyrender.constants.GLTF.LINES, poses=poses) return pyrender.mesh.Mesh(primitives=[prim], is_visible=True) # render lines verts = np.array([[-.5, 0, 0], [+.5, 0, 0]]) edges = np.array([0, 1]) line_mesh = line_meshes(verts, edges) img, _, _, _ = render.render_trimesh([line_mesh], eye_1, center, up, light_intensity=3) plt.figure(figsize=(8, 8)) plt.imshow(img) plt.show() ###Output _____no_output_____
notebooks/01_dynamics_experiments/vpython_visualization.ipynb
###Markdown Visualization with vpython ###Code import ipywidgets as widgets from IPython.core.display import display from ivisual import * def simulate(t): ball.pos = vector(t,0,0) def sim2(change): xmin = 10 xmax = 20 v = 0.5 x = xmin + 0.5*(xmax - xmin)/(slider.max - slider.min)*(slider.value - slider.min) simulate(t = x) scene2 = canvas() vscale = 5 varr = arrow(pos=vector(0,0,0), axis=vscale*vector(1,0,0), color=color.red) varr = arrow(pos=vector(0,0,0), axis=vscale*vector(0,1,0), color=color.green) varr = arrow(pos=vector(0,0,0), axis=vscale*vector(0,0,1), color=color.blue) ball = sphere(pos = vector(20,0,0),radius = 1) play = widgets.Play( interval=0.5, value=10, min=0, max=100, description="Press play", disabled=False ) slider = widgets.FloatSlider() widgets.jslink((play, 'value'), (slider, 'value')) play.observe(sim2, names='value') scene2.visible = True display(scene2) widgets.HBox([play, slider]) ###Output _____no_output_____
individual_code/michael/sumo_gym/.ipynb_checkpoints/PositiveSign_michael-checkpoint.ipynb
###Markdown Environment ###Code from __future__ import absolute_import from __future__ import print_function import os import sys import gym from gym import spaces, logger import numpy as np # we need to import python modules from the $SUMO_HOME/tools directory if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) else: sys.exit("please declare environment variable 'SUMO_HOME'") from sumolib import checkBinary import traci # HARDCODE controlled_lights = [{'name':'nodeX', 'curr_phase':0, 'num_phases': 2}] # uncontrolled_lights = [{'name':'nw', 'curr_phase':0, 'num_phases': 4}, {'name':'se', 'curr_phase':0, 'num_phases': 4}, {'name':'sw', 'curr_phase':0, 'num_phases': 4}] important_roads = ['edge1', 'edge2', 'edge3', 'edge4', 'edge5', 'edge6', 'edge7', 'edge8'] load_options = ["-c", "PositiveSign/PositiveSign.sumocfg", "--tripinfo-output", "tripinfo.xml", '--log', 'log.txt' , "-t"] # load_options = ["-c", "--tripinfo-output", "tripinfo.xml", '--log', 'log.txt' , "-t"] class SumoEnv(gym.Env): def __init__(self, steps_per_episode, render): super(SumoEnv, self).__init__() print('init') # self.scenario_name = scenario_name self.steps_per_episode = steps_per_episode self.is_done = False self.current_step = 0 self.reward_range = (-float('inf'), float('inf')) # HARDCODE self.action_space = spaces.Discrete(2) # HARDCODE self.observation_space = spaces.Box(low=0, high=np.inf, shape=np.array([16]), dtype=np.float32) # HARDCODE # Start connection with sumo self.noguiBinary = checkBinary('sumo') self.guiBinary = checkBinary('sumo-gui') # self.current_binary = self.noguiBinary self.current_binary = self.guiBinary if render else self.noguiBinary traci.start([self.current_binary] + load_options) def reset(self): print('reset') traci.load(load_options+["--start"]) self.current_step = 0 self.is_done = False return self._next_observation() def _next_observation(self): obs = [] wait_counts, road_counts = self._get_road_waiting_vehicle_count() # HARDCODE for lane in important_roads: obs.append(road_counts[lane]) obs.append(wait_counts[lane]) return np.array(obs) def step(self, action): self._take_action(action) traci.simulationStep() self.current_step += 1 obs = self._next_observation() reward = self._get_reward() if self.is_done: logger.warn("You are calling 'step()' even though this environment has already returned done = True. " "You should always call 'reset()' once you receive 'done = True' " "-- any further steps are undefined behavior.") reward = 0.0 if self.current_step + 1 == self.steps_per_episode: self.is_done = True return obs, reward, self.is_done, {} def _get_reward(self): road_waiting_vehicles_dict , _ = self._get_road_waiting_vehicle_count() reward = 0.0 for (road_id, num_vehicles) in road_waiting_vehicles_dict.items(): if road_id in important_roads: reward -= num_vehicles return reward def _take_action(self, action): if action != controlled_lights[0]['curr_phase']: controlled_lights[0]['curr_phase'] = action self._set_tl_phase(controlled_lights[0]['name'], action) def _get_road_waiting_vehicle_count(self): wait_counts = {'edge1':0, 'edge2':0, 'edge3':0, 'edge4':0, 'edge5':0, 'edge6':0, 'edge7':0, 'edge8':0} road_counts = {'edge1':0, 'edge2':0, 'edge3':0, 'edge4':0, 'edge5':0, 'edge6':0, 'edge7':0, 'edge8':0} vehicles = traci.vehicle.getIDList() for v in vehicles: road = traci.vehicle.getRoadID(v) if road in wait_counts.keys(): if traci.vehicle.getWaitingTime(v) > 0: wait_counts[road] += 1 road_counts[road] += 1 return wait_counts , road_counts def _on_training_end(self): super(self) traci.close() def _set_tl_phase(self, intersection_id, phase_id): traci.trafficlight.setPhase(intersection_id, phase_id) def render(self, mode='human', close=False): # self.save_replay = not self.save_replay self.current_binary = self.guiBinary def close(self): self._on_training_end() ###Output _____no_output_____ ###Markdown Test the environment with an agent ###Code # Remove TF warnings in Stable baselines (may not be safe) import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import tensorflow as tf tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) import traci import sys import gym from stable_baselines.common.policies import MlpPolicy from stable_baselines.common.vec_env import DummyVecEnv , SubprocVecEnv from stable_baselines import PPO2, DQN #from env.SumoEnv import SumoEnv #from env.SumoEnv_Parallel import SumoEnv_Parallel import time try: num_proc = 1 steps_per_episode = 1000 num_episodes = 100 if(num_proc == 1): env = DummyVecEnv([lambda: SumoEnv(steps_per_episode, True)]) else: env = SubprocVecEnv([lambda: SumoEnv_Parallel(steps_per_episode, False, i) for i in range(num_proc)], start_method='forkserver') model = DQN('MlpPolicy', env, verbose=1) start = time.time() model.learn(total_timesteps=steps_per_episode*num_episodes) print(f'LEARNING TIME: {time.time() - start}') model.save('dqn_positive2') print('done learning') traci.close() except: traci.close() traci.close() # Test the trained agent from stable_baselines.common.policies import MlpPolicy from stable_baselines.common.vec_env import DummyVecEnv , SubprocVecEnv from stable_baselines import PPO2, DQN try: steps_per_episode = 250 saved_model = "dqn_positive2" print('pre-env') env = DummyVecEnv([lambda: SumoEnv(steps_per_episode, True)]) print('post-env') # wrap it model = DQN.load(saved_model, env) print('pre-obs') obs = env.reset() print('post-obs') while True: action, _states = model.predict(obs,deterministic=True) obs, rewards, dones, info = env.step(action) env.render() except TraCIException: traci.close() traci.close() # Launch simulation server (SUMO-gui) current_binary = checkBinary('sumo-gui') load_options = ["-c", "PositiveSign/PositiveSign.sumocfg", "--tripinfo-output", "tripinfo.xml", '--log', 'log.txt' , "-t"] traci.start([current_binary] + load_options) # Perform this code while simulator server (SUMO) is open #Perform calculations here traci.simulationStep() # step simulation in time traci.close() # Close TraCI connection to prevent error def generate_routefile(N): with open("PositiveSign/PositiveSign.rou.xml", "w") as routes: print("""<routes> <vType id="default" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" guiShape="passenger"/> <route id="sw-ne" edges="edge1 edge4" /> <route id="ne-sw" edges="edge3 edge6" />""", file=routes) vehicle_id = 0 for i in range(N): if i % 8 == 0: print(f' <vehicle id="test_{vehicle_id}" type="default" route="sw-ne" depart="{i}" />', file=routes) vehicle_id += 1 print(f' <vehicle id="test_{vehicle_id}" type="default" route="ne-sw" depart="{i}" />', file=routes) vehicle_id += 1 print("</routes>", file=routes) generate_routefile(1000) def generate_routefile(route_list, vehicle_list): with open("PositiveSign/PositiveSign.rou.xml", "w") as routes: route_field = """<routes> <vType id="default" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" guiShape="passenger"/>""" for route in route_list: route_field += f"""<route id="{route['route_id']}" edges="{route['edge_list']}" />""" print(route_field, file=routes) for vehicle in vehicle_list: vehicle_id = 0 for i in range(vehicle['start'], vehicle['end']): if i % vehicle['interval'] == 0: vehicle_field = f"""<vehicle id="{vehicle['batch_name']+"_"+str(vehicle_id)}" type="default" route="{vehicle['route']}" depart="{i}" />""" print(vehicle_field, file=routes) vehicle_id += 1 print("</routes>", file=routes) route_list = [{'route_id':'A-C', 'edge_list': "edge1 edge6"}, {'route_id':'D-B', 'edge_list': "edge7 edge4"}] vehicle_list = [{'batch_name':'batch1', 'route':'A-C', 'start':0, 'end':10, 'interval':1}, {'batch_name':'batch2', 'route':'D-B', 'start':60, 'end':70, 'interval':1}, {'batch_name':'batch3', 'route':'A-C', 'start':120, 'end':130, 'interval':1}, {'batch_name':'batch4', 'route':'D-B', 'start':180, 'end':190, 'interval':1} ] generate_routefile(route_list, vehicle_list) generate_routefile(1000) routes = [{'route_id':'A-C', 'edge_list': "edge1 edge6"}, {'route_id':'D-B', 'edge_list': "edge7 edge4"}] vehicles = [{'batch_name':'batch1', 'route':'A-C', 'start':0, 'end':15, 'interval':1}, {'batch_name':'batch2', 'route':'D-B', 'start':30, 'end':45, 'interval':1}, {'batch_name':'batch3', 'route':'A-C', 'start':60, 'end':75, 'interval':1}, {'batch_name':'batch4', 'route':'D-B', 'start':90, 'end':105, 'interval':1}] for route in routes: print(f"""<route id="{route['route_id']}" edges="{route['edge_list']}" />""") for vehicle in vehicles: vehicle_id = 0 for i in range(vehicle['start'], vehicle['end']): if i % vehicle['interval'] == 0: print(f"""<vehicle id="{vehicle['batch_name']+"_"+str(vehicle_id)}" type="default" route="{vehicle['route']}" depart="{i}" />""") vehicle_id += 1 print("""<routes> <vType id="default" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" guiShape="passenger"/> <route id="sw-ne" edges="edge1 edge4" /> <route id="ne-sw" edges="edge3 edge6" />""") ###Output <routes> <vType id="default" accel="0.8" decel="4.5" sigma="0.5" length="5" minGap="2.5" maxSpeed="16.67" guiShape="passenger"/> <route id="sw-ne" edges="edge1 edge4" /> <route id="ne-sw" edges="edge3 edge6" />
notebooks/transfer_learning_pytorch_model.ipynb
###Markdown Transfer Learning: Feature Extraction"*In practice, very few people train an entire Convolutional Network from scratch (with random initialization), because it is relatively rare to have a dataset of sufficient size. Instead, it is common to pretrain a ConvNet on a very large dataset (e.g. ImageNet, which contains 1.2 million images with 1000 categories), and then use the ConvNet either as an initialization or a fixed feature extractor for the task of interest.*" From PyTorch.The goal here is to train a classifier from a pre-trained CNN on another data set. The original CNN classifier has 365 classes. The new data set has 132 class labels, so in feature extraction we freeze the convolutional base, and retrain the classifier portion of the CNN. Only this last fully connected layer is trained. ###Code import warnings warnings.filterwarnings("ignore") import os print(os.getcwd()) # C:\Users\chung\Documents\github_repos\nextpick\notebooks os.chdir('../NextPick-app/') print(os.getcwd()) # C:\Users\chung\Documents\github_repos\nextpick\ import time import copy from NextPick.NextPick.image_search import * from NextPick.NextPick.ImageDataset import ImageDataset import pickle import numpy as np import torch import torch.nn as nn from torch.autograd import Variable as V import torchvision import torchvision.models as models from torchvision import transforms as trn from torch.nn import functional as F import torch.optim as optim from torch.optim import lr_scheduler from PIL import Image from barbar import Bar ###Output C:\Users\chung\Documents\04-Insight\nextpick\notebooks C:\Users\chung\Documents\04-Insight\nextpick\NextPick-app ###Markdown `model` is the convolutional base of the pretrained CNN. Notice it's `fc` layer is empty. We are going to use this and add on a new layer to train our new classifier. \`model_full` is the original full pre-trained CNN. ###Code pkl_list = load_pkl_paths('data') input_dataset = ImageDataset('data') bs = 100 image_loader = torch.utils.data.DataLoader(input_dataset, batch_size=bs) model, model_full = load_pretrained_model() transform = trn.Compose([trn.Resize((256, 256)), trn.CenterCrop(224), trn.ToTensor(), trn.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) from torchvision.datasets import ImageFolder raw_dataset = ImageFolder(root='data', transform=transform) with open('NextPick/class_labels.pkl','rb') as f: class_labels = pickle.load(f) f.close() image, idx = raw_dataset[456] print(image.shape, class_labels[idx]) model model_full pd_files = input_dataset.get_file_df() with open('NextPick/pd_files.pkl','rb') as f: pd_files1 = pickle.load(f) f.close() pd_files.head(15) pd_files1.head(15) pd_files = pd_files.drop(columns=['path']) pd_files.equals(pd_files1) ###Output _____no_output_____ ###Markdown Now we freeze the convolutional base by setting `requires_grad == False`, and train the new classifier. ###Code for param in model.parameters(): param.requires_grad = False ###Output _____no_output_____ ###Markdown Construct new linear layer for new classifier. Note that we want the same input features, but just the number of class labels as the number of outputs. ###Code num_features = model_full.fc.in_features model.fc = nn.Linear(num_features, 132) ###Output _____no_output_____ ###Markdown Defining the device for training. ###Code device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = model.to(device) criterion = nn.CrossEntropyLoss() optimizer_conv = optim.Adam(model.fc.parameters(), lr=0.0001) exp_lr_scheduler = lr_scheduler.StepLR(optimizer_conv, step_size=7, gamma=0.1) ###Output _____no_output_____ ###Markdown We use the Torch imageFolder class and DataLoader ###Code trainloader = torch.utils.data.DataLoader(raw_dataset, batch_size=128, shuffle=True, num_workers=3) model.fc_backup = nn.Identity() ds_length = len(raw_dataset) ###Output _____no_output_____ ###Markdown Using the [Barbar](https://github.com/yusugomori/barbar) package for PyTorch deep learning training progress bar. Here we define the topk (top5) accuracy from this [discussion](https://discuss.pytorch.org/t/imagenet-example-accuracy-calculation/7840/3). ###Code since = time.time() num_epochs = 9 k = 5 model.train() for epoch in range(num_epochs): # loop over the dataset multiple times print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) running_loss = 0.0 running_corrects = 0 for inputs, labels in Bar(trainloader): inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer_conv.zero_grad() # forward. track history if only in train with torch.set_grad_enabled(True): outputs = model(inputs) _, preds = torch.topk(outputs, k, largest=True, sorted=True) # print() # print(preds.shape) preds = preds.t() # shape is now [topk, batch_size] loss = criterion(outputs, labels) # backward + optimize loss.backward() optimizer_conv.step() # statistics running_loss += loss.item() * inputs.size(0) correct = preds.eq(labels.view(1, -1).expand_as(preds)) # print(correct.shape) correct_k = correct.view(-1).float().sum(0, keepdim=True) # print(correct_k.shape) running_corrects += correct_k # print(running_corrects) # running_corrects += torch.sum(res == labels.data) exp_lr_scheduler.step() epoch_loss = running_loss / ds_length epoch_acc = running_corrects.double() / ds_length print('Loss: %.4f Acc: %.4f' %(epoch_loss, epoch_acc.numpy())) time_elapsed = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format( time_elapsed // 60, time_elapsed % 60)) print('Finished Training') ###Output Epoch 0/8 ---------- 12870/12870: [===============================>] - ETA 19.3sss Loss: 4.2810 Acc: 0.3998 Training complete in 25m 6s Epoch 1/8 ---------- 12870/12870: [===============================>] - ETA 17.6sss Loss: 4.0584 Acc: 0.4901 Training complete in 49m 51s Epoch 2/8 ---------- 12870/12870: [===============================>] - ETA 18.3sss Loss: 3.8630 Acc: 0.5420 Training complete in 74m 39s Epoch 3/8 ---------- 12870/12870: [===============================>] - ETA 17.3sss Loss: 3.6917 Acc: 0.5723 Training complete in 99m 29s Epoch 4/8 ---------- 12870/12870: [===============================>] - ETA 17.2sss Loss: 3.5386 Acc: 0.5939 Training complete in 124m 18s Epoch 5/8 ---------- 12870/12870: [===============================>] - ETA 17.0sss Loss: 3.4116 Acc: 0.6120 Training complete in 149m 0s Epoch 6/8 ---------- 12870/12870: [===============================>] - ETA 17.2sss Loss: 3.3359 Acc: 0.6235 Training complete in 173m 43s Epoch 7/8 ---------- 12870/12870: [===============================>] - ETA 17.3sss Loss: 3.3242 Acc: 0.6247 Training complete in 198m 30s Epoch 8/8 ---------- 12870/12870: [===============================>] - ETA 17.3sss Loss: 3.3122 Acc: 0.6267 Training complete in 223m 24s Finished Training ###Markdown Save the trained model ###Code torch.save(model.state_dict(), "transfer_model.pth") ###Output _____no_output_____ ###Markdown Load the model ###Code # Model class must be defined somewhere # model = torch.load(PATH) # model.eval() ###Output _____no_output_____
doc/source/examples/ale_regression_boston.ipynb
###Markdown Accumulated Local Effects for predicting house prices In this example we will explain the behaviour of regression models on the Boston housing dataset. We will show how to calculate accumulated local effects (ALE) for determining the feature effects on a model and how these vary on different kinds of models (linear and non-linear models). ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from alibi.explainers import ALE, plot_ale ###Output _____no_output_____ ###Markdown Load and prepare the dataset ###Code data = load_boston() feature_names = data.feature_names X = data.data y = data.target print(feature_names) ###Output ['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT'] ###Markdown Shuffle the data and define the train and test set: ###Code X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) ###Output _____no_output_____ ###Markdown Fit and evaluate models Fit and evaluate a linear regression model: ###Code lr = LinearRegression() lr.fit(X_train, y_train) mean_squared_error(y_test, lr.predict(X_test)) ###Output _____no_output_____ ###Markdown Fit and evaluate a random forest model: ###Code rf = RandomForestRegressor() rf.fit(X_train, y_train) mean_squared_error(y_test, rf.predict(X_test)) ###Output _____no_output_____ ###Markdown Feature Effects: Motivation Here we develop an intuition for calculating feature effects. We start by illustrating the calculation of feature effects for the linear regression model.For our regression model, the conditional mean or the prediction function $\mathbb{E}(y\vert x)=f(x)$ is linear:$$f(x) = w_0 + w_1x_1 + \dots + w_kx_k.$$Because the model is additive and doesn't include feature interactions, we can read off individual feature effects immediately: the effect of any feature $x_i$ is just $w_ix_i$, so the effect is a linear function of $x_i$ and the sign of the coefficient $w_i$ determines whether the effect is positive or negative as $x_i$ changes. Now suppose we don't know the true effect of the feature $x_i$ which is usually the case when using a more complex model. How might we approach the problem of estimating the effect? Let's focus on one feature - average number of rooms per dwelling (`RM`). The following is a scatterplot of model predictions versus the feature: ###Code FEATURE = 'RM' index = np.where(feature_names==FEATURE)[0][0] fig, ax = plt.subplots() ax.scatter(X_train[:, index], lr.predict(X_train)); ax.set_xlabel(FEATURE); ax.set_ylabel('Value in $1000\'s'); ###Output _____no_output_____ ###Markdown As we can see, there is a strong positive correlation as one might expect. However the feature effects for `RM` cannot be read off immediately because the prediction function includes the effects of all features not just `RM`. What we need is a procedure to block out the effects of all other features to uncover the true effect of `RM` only. This is exactly what the ALE approach does by averaging the differences of predictions across small intervals of the feature. Calculate Accumulated Local Effects Here we initialize the ALE object by passing it the predictor function which in this case is the `clf.predict` method for both models. We also pass in feature names and target name for easier interpretation of the resulting explanations. ###Code lr_ale = ALE(lr.predict, feature_names=feature_names, target_names=['Value in $1000\'s']) rf_ale = ALE(rf.predict, feature_names=feature_names, target_names=['Value in $1000\'s']) ###Output _____no_output_____ ###Markdown We now call the `explain` method on the explainer objects which will compute the ALE's and return an `Explanation` object which is ready for inspection and plotting. Since ALE is a global explanation method it takes in a batch of data for which the model feature effects are computed, in this case we pass in the training set. ###Code lr_exp = lr_ale.explain(X_train) rf_exp = rf_ale.explain(X_train) lr_exp.feature_names ###Output _____no_output_____ ###Markdown The resulting `Explanation` objects contain the ALE's for each feature under the `ale_values` attribute - this is a list of numpy arrays, one for each feature. The easiest way to interpret the ALE values is by plotting them against the feature values for which we provide a built-in function `plot_ale`. By calling the function without arguments, we will plot the effects of every feature, so in this case we will get 13 different subplots. To fit them all on the screen we pass in options for the figure size. ALE for the linear regression model The ALE plots show the main effects of each feature on the prediction function. ###Code plot_ale(lr_exp, fig_kw={'figwidth':10, 'figheight': 10}); ###Output _____no_output_____ ###Markdown The interpretation of the ALE plot is that given a feature value, the ALE value corresponding to that feature value is difference to the mean effect of that feature. Put differently, the ALE value is the relative feature effect on the prediction at that feature value. Effect of the average number of rooms Let's look at the ALE plot for the feature `RM` (average number of rooms per dwelling) in more detail: ###Code plot_ale(lr_exp, features=['RM']); ###Output _____no_output_____ ###Markdown The ALE on the y-axes of the plot above is in the units of the prediction variable which, in this case, is the value of the house in \$1000's. The ALE value for the point `RM=8` is ~7.5 which has the interpretation that for neighbourhoods for which the average number of rooms is ~8 the model predicts an up-lift of ~\$7500 **due to feature RM** with respect to the average prediction. On the other hand, for neighbourhoods with an average number of rooms lower than ~6.25, the feature effect on the prediction becomes negative, i.e. a smaller number of rooms brings the predicted value down with respect to the average prediction. Let's find the neighbourhoods for which the average number of rooms are close to 8: ###Code lower_index = np.where(lr_exp.feature_values[5] < 8)[0][-1] upper_index = np.where(lr_exp.feature_values[5] > 8)[0][0] subset = X_train[(X_train[:, 5] > lr_exp.feature_values[5][lower_index]) & (X_train[:, 5] < lr_exp.feature_values[5][upper_index])] print(subset.shape) ###Output (6, 13) ###Markdown The mean prediction on this subset is: ###Code subset_pred = lr.predict(subset).mean() subset_pred ###Output _____no_output_____ ###Markdown The zeroth order effects is the mean prediction averaged across the whole dataset: ###Code mean_pred = lr.predict(X_train).mean() mean_pred ###Output _____no_output_____ ###Markdown The difference between these two values is: ###Code subset_pred - mean_pred ###Output _____no_output_____ ###Markdown This is the total expected uplift in \$1000's for neigbourhoods with the average room number close to 8. The ALE value for `RM=8` tells us that this feature is responsible for roughly \$7.5K or almost half of the uplift while the combination of other features is responsible for the rest. Effect of the crime level An additional feature of the ALE plot is that it shows feature deciles on the x-axis. This helps understand in which regions there is no data so the ALE plot is interpolating. For example, for the `CRIM` feature (per capita crime rate by town), there is very little to no data in the feature interval ~30-85, so the ALE plot in that region is just linearly interpolating: ###Code plot_ale(lr_exp, features=['CRIM']); ###Output _____no_output_____ ###Markdown For linear models this is not an issue as we know the effect is linear across the whole range of the feature, however for non-linear models linear interpolation in feature areas with no data could be unreliable. This is why the use of deciles can help assess in which areas of the feature space the estimated feature effects are more reliable. Linearity of ALE It is no surprise that the ALE plots for the linear regression model are linear themselves—the feature effects are after all linear by definition. In fact, the slopes of the ALE lines are exactly the coefficients of the linear regression: ###Code lr.coef_ slopes = np.array([((v[-1]-v[0])/(f[-1]-f[0])).item() for v, f in zip(lr_exp.ale_values, lr_exp.feature_values)]) slopes ###Output _____no_output_____ ###Markdown Thus the slopes of the ALE plots for linear regression have exactly the same interpretation as the coefficients of the learnt model—global feature effects. In fact, we can calculate the ALE effect of linear regression analytically (with some assumptions on the conditional feature distributions) to show that the effect of feature $x_i$ is $\text{ALE}(x_i) = w_ix_i-w_i\mathbb{E}(x_i)$ which is the familiar effect $w_ix_i$ relative to the mean effect of the feature. ALE for the random forest model Now let's look at the ALE plots for the non-linear random forest model: ###Code axes = plot_ale(rf_exp, fig_kw={'figwidth':10, 'figheight': 10}); ###Output _____no_output_____ ###Markdown Because the model is no longer linear, the ALE plots are non-linear also and in some cases also non-monotonic. The interpretation of the plots is still the same—the ALE value at a point is the relative feature effect with respect to the mean feature effect, however the non-linear model used shows that the feature effects differ both in shape and magnitude when compared to the linear model. From these plots, it seems that the feature `RM` has the biggest impact on the prediction. Checking the feature importances of the random forest classifier confirms this: ###Code feature_names[rf.feature_importances_.argmax()] ###Output _____no_output_____ ###Markdown Let's explore the feature `DIS` (weighted distances to five Boston employment centres) and how its effects are different between the two models. To do this, we can pass in matplotlib `axes` objects for the `plot_ale` function to plot on: ###Code fig, ax = plt.subplots() plot_ale(lr_exp, features=['DIS'], ax=ax, line_kw={'label': 'Linear regression'}); plot_ale(rf_exp, features=['DIS'], ax=ax, line_kw={'label': 'Random forest'}); ###Output _____no_output_____ ###Markdown From this plot we can gather several interesting insights: - Linear regression puts a higher emphasis on the `DIS` feature, as evidenced by the relative magnitudes of the ALE scores across the feature range. - Whilst the linear regression feature effects of `DIS` are negatively correlated (the higher the distance to employment centres, the lower the predicted value), the random forest feature effects are not monotonic. - In particular, at the start of the range of `DIS` there seems to be switching between positive and negative effects. To compare multiple models and multiple features we can plot the ALE's on a common axis that is big enough to accommodate all features of interest: ###Code fig, ax = plt.subplots(5, 3, sharey='all'); plot_ale(lr_exp, ax=ax, fig_kw={'figwidth':10, 'figheight': 10}, line_kw={'label': 'Linear regression'}); plot_ale(rf_exp, ax=ax, line_kw={'label': 'Random forest'}); ###Output _____no_output_____ ###Markdown Accumulated Local Effects for predicting house prices In this example we will explain the behaviour of regression models on the Boston housing dataset. We will show how to calculate accumulated local effects (ALE) for determining the feature effects on a model and how these vary on different kinds of models (linear and non-linear models). ###Code %matplotlib inline import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from alibi.explainers import ALE, plot_ale ###Output _____no_output_____ ###Markdown Load and prepare the dataset ###Code data = load_boston() feature_names = data.feature_names X = data.data y = data.target print(feature_names) ###Output ['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT'] ###Markdown Shuffle the data and define the train and test set: ###Code X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) ###Output _____no_output_____ ###Markdown Fit and evaluate models Fit and evaluate a linear regression model: ###Code lr = LinearRegression() lr.fit(X_train, y_train) mean_squared_error(y_test, lr.predict(X_test)) ###Output _____no_output_____ ###Markdown Fit and evaluate a random forest model: ###Code rf = RandomForestRegressor() rf.fit(X_train, y_train) mean_squared_error(y_test, rf.predict(X_test)) ###Output _____no_output_____ ###Markdown Feature Effects: Motivation Here we develop an intuition for calculating feature effects. We start by illustrating the calculation of feature effects for the linear regression model.For our regression model, the conditional mean or the prediction function $\mathbb{E}(y\vert x)=f(x)$ is linear:$$f(x) = w_0 + w_1x_1 + \dots + w_kx_k.$$Because the model is additive and doesn't include feature interactions, we can read off individual feature effects immediately: the effect of any feature $x_i$ is just $w_ix_i$, so the effect is a linear function of $x_i$ and the sign of the coefficient $w_i$ determines whether the effect is positive or negative as $x_i$ changes. Now suppose we don't know the true effect of the feature $x_i$ which is usually the case when using a more complex model. How might we approach the problem of estimating the effect? Let's focus on one feature - average number of rooms per dwelling (`RM`). The following is a scatterplot of model predictions versus the feature: ###Code FEATURE = 'RM' index = np.where(feature_names==FEATURE)[0][0] fig, ax = plt.subplots() ax.scatter(X_train[:, index], lr.predict(X_train)); ax.set_xlabel(FEATURE); ax.set_ylabel('Value in $1000\'s'); ###Output _____no_output_____ ###Markdown As we can see, there is a strong positive correlation as one might expect. However the feature effects for `RM` cannot be read off immediately because the prediction function includes the effects of all features not just `RM`. What we need is a procedure to block out the effects of all other features to uncover the true effect of `RM` only. This is exactly what the ALE approach does by averaging the differences of predictions across small intervals of the feature. Calculate Accumulated Local Effects Here we initialize the ALE object by passing it the predictor function which in this case is the `clf.predict` method for both models. We also pass in feature names and target name for easier interpretation of the resulting explanations. ###Code lr_ale = ALE(lr.predict, feature_names=feature_names, target_names=['Value in $1000\'s']) rf_ale = ALE(rf.predict, feature_names=feature_names, target_names=['Value in $1000\'s']) ###Output _____no_output_____ ###Markdown We now call the `explain` method on the explainer objects which will compute the ALE's and return an `Explanation` object which is ready for inspection and plotting. Since ALE is a global explanation method it takes in a batch of data for which the model feature effects are computed, in this case we pass in the training set. ###Code lr_exp = lr_ale.explain(X_train) rf_exp = rf_ale.explain(X_train) lr_exp.feature_names ###Output _____no_output_____ ###Markdown The resulting `Explanation` objects contain the ALE's for each feature under the `ale_values` attribute - this is a list of numpy arrays, one for each feature. The easiest way to interpret the ALE values is by plotting them against the feature values for which we provide a built-in function `plot_ale`. By calling the function without arguments, we will plot the effects of every feature, so in this case we will get 13 different subplots. To fit them all on the screen we pass in options for the figure size. ALE for the linear regression model The ALE plots show the main effects of each feature on the prediction function. ###Code plot_ale(lr_exp, fig_kw={'figwidth':10, 'figheight': 10}); ###Output _____no_output_____ ###Markdown The interpretation of the ALE plot is that given a feature value, the ALE value corresponding to that feature value is difference to the mean effect of that feature. Put differently, the ALE value is the relative feature effect on the prediction at that feature value. Effect of the average number of rooms Let's look at the ALE plot for the feature `RM` (average number of rooms per dwelling) in more detail: ###Code plot_ale(lr_exp, features=['RM']); ###Output _____no_output_____ ###Markdown The ALE on the y-axes of the plot above is in the units of the prediction variable which, in this case, is the value of the house in \$1000's. The ALE value for the point `RM=8` is ~7.5 which has the interpretation that for neighbourhoods for which the average number of rooms is ~8 the model predicts an up-lift of ~\$7500 **due to feature RM** with respect to the average prediction. On the other hand, for neighbourhoods with an average number of rooms lower than ~6.25, the feature effect on the prediction becomes negative, i.e. a smaller number of rooms brings the predicted value down with respect to the average prediction. Let's find the neighbourhoods for which the average number of rooms are close to 8: ###Code lower_index = np.where(lr_exp.feature_values[5] < 8)[0][-1] upper_index = np.where(lr_exp.feature_values[5] > 8)[0][0] subset = X_train[(X_train[:, 5] > lr_exp.feature_values[5][lower_index]) & (X_train[:, 5] < lr_exp.feature_values[5][upper_index])] print(subset.shape) ###Output (6, 13) ###Markdown The mean prediction on this subset is: ###Code subset_pred = lr.predict(subset).mean() subset_pred ###Output _____no_output_____ ###Markdown The zeroth order effects is the mean prediction averaged across the whole dataset: ###Code mean_pred = lr.predict(X_train).mean() mean_pred ###Output _____no_output_____ ###Markdown The difference between these two values is: ###Code subset_pred - mean_pred ###Output _____no_output_____ ###Markdown This is the total expected uplift in \$1000's for neigbourhoods with the average room number close to 8. The ALE value for `RM=8` tells us that this feature is responsible for roughly \$7.5K or almost half of the uplift while the combination of other features is responsible for the rest. Effect of the crime level An additional feature of the ALE plot is that it shows feature deciles on the x-axis. This helps understand in which regions there is no data so the ALE plot is interpolating. For example, for the `CRIM` feature (per capita crime rate by town), there is very little to no data in the feature interval ~30-85, so the ALE plot in that region is just linearly interpolating: ###Code plot_ale(lr_exp, features=['CRIM']); ###Output _____no_output_____ ###Markdown For linear models this is not an issue as we know the effect is linear across the whole range of the feature, however for non-linear models linear interpolation in feature areas with no data could be unreliable. This is why the use of deciles can help assess in which areas of the feature space the estimated feature effects are more reliable. Linearity of ALE It is no surprise that the ALE plots for the linear regression model are linear themselves—the feature effects are after all linear by definition. In fact, the slopes of the ALE lines are exactly the coefficients of the linear regression: ###Code lr.coef_ slopes = np.array([((v[-1]-v[0])/(f[-1]-f[0])).item() for v, f in zip(lr_exp.ale_values, lr_exp.feature_values)]) slopes ###Output _____no_output_____ ###Markdown Thus the slopes of the ALE plots for linear regression have exactly the same interpretation as the coefficients of the learnt model—global feature effects. In fact, we can calculate the ALE effect of linear regression analytically (with some assumptions on the conditional feature distributions) to show that the effect of feature $x_i$ is $\text{ALE}(x_i) = w_ix_i-w_i\mathbb{E}(x_i)$ which is the familiar effect $w_ix_i$ relative to the mean effect of the feature. ALE for the random forest model Now let's look at the ALE plots for the non-linear random forest model: ###Code axes = plot_ale(rf_exp, fig_kw={'figwidth':10, 'figheight': 10}); ###Output _____no_output_____ ###Markdown Because the model is no longer linear, the ALE plots are non-linear also and in some cases also non-monotonic. The interpretation of the plots is still the same—the ALE value at a point is the relative feature effect with respect to the mean feature effect, however the non-linear model used shows that the feature effects differ both in shape and magnitude when compared to the linear model. From these plots, it seems that the feature `RM` has the biggest impact on the prediction. Checking the feature importances of the random forest classifier confirms this: ###Code feature_names[rf.feature_importances_.argmax()] ###Output _____no_output_____ ###Markdown Let's explore the feature `DIS` (weighted distances to five Boston employment centres) and how its effects are different between the two models. To do this, we can pass in matplotlib `axes` objects for the `plot_ale` function to plot on: ###Code fig, ax = plt.subplots() plot_ale(lr_exp, features=['DIS'], ax=ax, line_kw={'label': 'Linear regression'}); plot_ale(rf_exp, features=['DIS'], ax=ax, line_kw={'label': 'Random forest'}); ###Output _____no_output_____ ###Markdown From this plot we can gather several interesting insights: - Linear regression puts a higher emphasis on the `DIS` feature, as evidenced by the relative magnitudes of the ALE scores across the feature range. - Whilst the linear regression feature effects of `DIS` are negatively correlated (the higher the distance to employment centres, the lower the predicted value), the random forest feature effects are not monotonic. - In particular, at the start of the range of `DIS` there seems to be switching between positive and negative effects. To compare multiple models and multiple features we can plot the ALE's on a common axis that is big enough to accommodate all features of interest: ###Code fig, ax = plt.subplots(5, 3, sharey='all'); plot_ale(lr_exp, ax=ax, fig_kw={'figwidth':10, 'figheight': 10}, line_kw={'label': 'Linear regression'}); plot_ale(rf_exp, ax=ax, line_kw={'label': 'Random forest'}); ###Output _____no_output_____
header_footer/biosignalsnotebooks_environment/categories/Load/.ipynb_checkpoints/signal_loading_preparatory_steps-checkpoint.ipynb
###Markdown Signal Loading - Working with File Header Difficulty Level: Tags load&9729;metadata&9729;header Each one of the OpenSignals outputted file formats has some metadata linked to it.Acquisition parameters such as sampling rate, resolution, used channels... can be found in the file metadata. For the .txt file this info is stored in the header while in .h5 files is passed as attributes of the hierarchical objects.In the current Jupyter Notebook a detailed procedure for accessing file metadata (.txt and .h5) is explained, together with a simplified approach through the use of a biosignalsnotebooks specialized function. 0 - Importation of the needed packages ###Code # biosignalsnotebooks Python package with useful functions that support and complement the available Notebooks import biosignalsnotebooks as bsnb # Package dedicated to process Python abstract syntax grammar Abstract (Abstract Syntax Trees) from ast import literal_eval # Package used for accessing .h5 file contents from h5py import File ###Output _____no_output_____ ###Markdown 1A - Working with a .txt file (generate a dictionary that contains the header info) 1.1A - Open file (creation of a "file" object) ###Code # Specification of the file path (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/bvp_sample.txt" # Open file file_txt = open(relative_file_path, "r") # Embedding of .pdf file from IPython.display import IFrame IFrame(src="../../signal_samples/bvp_sample.txt", width="100%", height="350") ###Output _____no_output_____ ###Markdown As can be seen, in the previous IFrame and in the following figure, the metadata of our .txt file is placed in line 2. 1.2A - Read line 2 of the opened file through "readlines" method of "file_txt" object ###Code # The "readlines" method returns a list where each entry contains a line of the .txt file txt_data = file_txt.readlines() # We only need the content of line 2 (entry 1 of "txt_data" list) metadata = txt_data[1] # Close file file_txt.close() ###Output _____no_output_____ ###Markdown 1.3A - Conversion of line content into a dictionary 1.3.1A - Removal of "" symbol at the beginning of the string, the space between "" and "{" and the new line command "\n" at the end of the stringEssentially we want to exclude the first two entries of the string (0 and 1) and the last one (-1). ###Code metadata_aux = metadata[2:-1] print("\033[1mSplit String: \033[0m\n" + metadata_aux) ###Output Split String:  {"00:07:80:3B:46:61": {"sensor": ["BVP"], "device name": "00:07:80:3B:46:61", "column": ["nSeq", "DI", "CH1"], "sync interval": 2, "time": "9:33:55.606", "comments": "", "device connection": "BTH00:07:80:3B:46:61", "channels": [1], "date": "2017-1-17", "mode": 0, "digital IO": [0, 1], "firmware version": 772, "device": "biosignalsplux", "position": 0, "sampling rate": 1000, "label": ["CH1"], "resolution": [16], "special": [{}]}} ###Markdown 1.3.2A - Conversion of the remaining content of the original string to a dictionary format (using ast package) ###Code header_txt = literal_eval(metadata_aux) from sty import fg, rs print(str(header_txt).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'00:07:80:3B:46:61': {'sensor': ['BVP'], 'device name': '00:07:80:3B:46:61', 'column': ['nSeq', 'DI', 'CH1'], 'sync interval': 2, 'time': '9:33:55.606', 'comments': '', 'device connection': 'BTH00:07:80:3B:46:61', 'channels': [1], 'date': '2017-1-17', 'mode': 0, 'digital IO': [0, 1], 'firmware version': 772, 'device': 'biosignalsplux', 'position': 0, 'sampling rate': 1000, 'label': ['CH1'], 'resolution': [16], 'special': [{}]}} ###Markdown 1B - Working with a .h5 file (generate a dictionary that contains the header info) 1.1B - Load of .h5 file through the creation of a h5py object ###Code # Specification of the file path (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/ecg_20_sec_1000_Hz.h5" # Creation of h5py object file_h5 = File(relative_file_path) ###Output _____no_output_____ ###Markdown 1.2B - Determination of the list of available keys (one per device) ###Code available_keys = list(file_h5.keys()) print("Number of available devices: " + str(len(available_keys)) + "\nAvailable devices: " + str(available_keys)) ###Output Number of available devices: 1 Available devices: ['00:07:80:D8:A7:F9'] ###Markdown 1.3B - Since we are working only with one device, our mac address is stored in the first entry (index 0) of available_keys list ###Code mac = available_keys[0] ###Output _____no_output_____ ###Markdown 1.4B - Access to the first level of file hierarchy ###Code group_lv1 = file_h5.get(mac) print(group_lv1) ###Output <HDF5 group "/00:07:80:D8:A7:F9" (5 members)> ###Markdown 1.5B - Request of the metadata linked to the current hierarchy level ###Code attrs_lv1 = group_lv1.attrs.items() print(attrs_lv1) ###Output ItemsViewHDF5(<Attributes of HDF5 object at 495127792>) ###Markdown 1.6B - Final conversion into a dictionary ###Code header_h5 = dict(attrs_lv1) from sty import fg, rs print(str(header_h5).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'channels': array([1]), 'comments': '', 'date': b'2018-9-28', 'device': 'biosignalsplux', 'device connection': b'BTH00:07:80:D8:A7:F9', 'device name': b'00:07:80:D8:A7:F9', 'digital IO': array([0, 1]), 'duration': b'20s', 'firmware version': 773, 'keywords': b'', 'macaddress': b'00:07:80:D8:A7:F9', 'mode': 0, 'nsamples': 20400, 'resolution': array([16]), 'sampling rate': 1000, 'sync interval': 2, 'time': b'14:39:43.518'} ###Markdown By a simple "key" call it will be possible to access the values highlighted in blue, at topics 1.3.3A and 1.6B. ###Code sr_txt = header_txt["00:07:80:3B:46:61"]["sampling rate"] # Sampling rate of the acquisition contained inside .txt file sr_h5 = header_h5["sampling rate"] # Sampling rate of the acquisition contained inside .h5 file print("\033[1mSampling Rate (.txt):\033[0m " + str(sr_txt) + " Hz") print("\033[1mSampling Rate (.h5):\033[0m " + str(sr_h5) + " Hz") ###Output Sampling Rate (.txt): 1000 Hz Sampling Rate (.h5): 1000 Hz ###Markdown The previously described procedures, for accessing metadata from .txt and .h5 files, can be easily achieved while loading a file with bsnb.load function, by specifying the input argument called "get_header" as True ###Code # Specification of the file path (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/ecg_20_sec_1000_Hz.h5" data, header = bsnb.load(relative_file_path, get_header=True) from sty import fg, rs print(str(header).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'channels': array([1]), 'comments': '', 'date': b'2018-9-28', 'device': 'biosignalsplux', 'device connection': b'BTH00:07:80:D8:A7:F9', 'device name': b'00:07:80:D8:A7:F9', 'digital IO': array([0, 1]), 'firmware version': 773, 'resolution': array([16]), 'sampling rate': 1000, 'sync interval': 2, 'time': b'14:39:43.518', 'sensor': [b'ECG'], 'column labels': {1: 'channel_1'}} ###Markdown As can be understood, for a correct and efficient processing of OpenSignals files it is mandatory to access the information contained inside the header (.txt files) or stored as attributes (.h5 files), like the acquisition sampling rate or device mac-address.This info (metadata ) is always attached to the "real data" as an essential complement. We hope that you have enjoyed this guide. biosignalsnotebooks is an environment in continuous expansion, so don't stop your journey and learn more with the remaining Notebooks ! **Auxiliary Code Segment (should not be replicated by the user)** ###Code from biosignalsnotebooks.__notebook_support__ import css_style_apply css_style_apply() %%html <script> // AUTORUN ALL CELLS ON NOTEBOOK-LOAD! require( ['base/js/namespace', 'jquery'], function(jupyter, $) { $(jupyter.events).on("kernel_ready.Kernel", function () { console.log("Auto-running all cells-below..."); jupyter.actions.call('jupyter-notebook:run-all-cells-below'); jupyter.actions.call('jupyter-notebook:save-notebook'); }); } ); </script> ###Output _____no_output_____ ###Markdown Signal Loading - Working with File Header Difficulty Level: Tags load&9729;metadata&9729;header Each one of the OpenSignals outputted file formats has some metadata linked to it.Acquisition parameters such as sampling rate, resolution, used channels... can be found in the file metadata. For the .txt file this info is stored in the header while in .h5 files is passed as attributes of the hierarchical objects.In the current Jupyter Notebook a detailed procedure for accessing file metadata (.txt and .h5) is explained, together with a simplified approach through the use of a biosignalsnotebooks specialized function. 0 - Importation of the needed packages ###Code # biosignalsnotebooks Python package with useful functions that support and complement # the available Notebooks import biosignalsnotebooks as bsnb # Package dedicated to process Python abstract syntax grammar Abstract # (Abstract Syntax Trees) from ast import literal_eval # Package used for accessing .h5 file contents from h5py import File ###Output _____no_output_____ ###Markdown 1A - Working with a .txt file (generate a dictionary that contains the header info) 1.1A - Open file (creation of a "file" object) ###Code # Specification of the file path # (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/bvp_sample.txt" # Open file file_txt = open(relative_file_path, "r") # Embedding of .pdf file from IPython.display import IFrame IFrame(src="../../signal_samples/bvp_sample.txt", width="100%", height="350") ###Output _____no_output_____ ###Markdown As can be seen, in the previous IFrame and in the following figure, the metadata of our .txt file is placed in line 2. 1.2A - Read line 2 of the opened file through "readlines" method of "file_txt" object ###Code # The "readlines" method returns a list where each entry contains a line of the .txt file txt_data = file_txt.readlines() # We only need the content of line 2 (entry 1 of "txt_data" list) metadata = txt_data[1] # Close file file_txt.close() ###Output _____no_output_____ ###Markdown 1.3A - Conversion of line content into a dictionary 1.3.1A - Removal of "" symbol at the beginning of the string, the space between "" and "{" and the new line command "\n" at the end of the stringEssentially we want to exclude the first two entries of the string (0 and 1) and the last one (-1). ###Code metadata_aux = metadata[2:-1] print("\033[1mSplit String: \033[0m\n" + metadata_aux) ###Output Split String:  {"00:07:80:3B:46:61": {"sensor": ["BVP"], "device name": "00:07:80:3B:46:61", "column": ["nSeq", "DI", "CH1"], "sync interval": 2, "time": "9:33:55.606", "comments": "", "device connection": "BTH00:07:80:3B:46:61", "channels": [1], "date": "2017-1-17", "mode": 0, "digital IO": [0, 1], "firmware version": 772, "device": "biosignalsplux", "position": 0, "sampling rate": 1000, "label": ["CH1"], "resolution": [16], "special": [{}]}} ###Markdown 1.3.2A - Conversion of the remaining content of the original string to a dictionary format (using ast package) ###Code header_txt = literal_eval(metadata_aux) from sty import fg, rs print(str(header_txt).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'00:07:80:3B:46:61': {'sensor': ['BVP'], 'device name': '00:07:80:3B:46:61', 'column': ['nSeq', 'DI', 'CH1'], 'sync interval': 2, 'time': '9:33:55.606', 'comments': '', 'device connection': 'BTH00:07:80:3B:46:61', 'channels': [1], 'date': '2017-1-17', 'mode': 0, 'digital IO': [0, 1], 'firmware version': 772, 'device': 'biosignalsplux', 'position': 0, 'sampling rate': 1000, 'label': ['CH1'], 'resolution': [16], 'special': [{}]}} ###Markdown 1B - Working with a .h5 file (generate a dictionary that contains the header info) 1.1B - Load of .h5 file through the creation of a h5py object ###Code # Specification of the file path # (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/ecg_20_sec_1000_Hz.h5" # Creation of h5py object file_h5 = File(relative_file_path) ###Output _____no_output_____ ###Markdown 1.2B - Determination of the list of available keys (one per device) ###Code available_keys = list(file_h5.keys()) print("Number of available devices: " + str(len(available_keys)) + "\nAvailable devices: " + str(available_keys)) ###Output Number of available devices: 1 Available devices: ['00:07:80:D8:A7:F9'] ###Markdown 1.3B - Since we are working only with one device, our mac address is stored in the first entry (index 0) of available_keys list ###Code mac = available_keys[0] ###Output _____no_output_____ ###Markdown 1.4B - Access to the first level of file hierarchy ###Code group_lv1 = file_h5.get(mac) print(group_lv1) ###Output <HDF5 group "/00:07:80:D8:A7:F9" (5 members)> ###Markdown 1.5B - Request of the metadata linked to the current hierarchy level ###Code attrs_lv1 = group_lv1.attrs.items() print(attrs_lv1) ###Output ItemsViewHDF5(<Attributes of HDF5 object at 483553072>) ###Markdown 1.6B - Final conversion into a dictionary ###Code header_h5 = dict(attrs_lv1) from sty import fg, rs print(str(header_h5).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'channels': array([1]), 'comments': '', 'date': b'2018-9-28', 'device': 'biosignalsplux', 'device connection': b'BTH00:07:80:D8:A7:F9', 'device name': b'00:07:80:D8:A7:F9', 'digital IO': array([0, 1]), 'duration': b'20s', 'firmware version': 773, 'keywords': b'', 'macaddress': b'00:07:80:D8:A7:F9', 'mode': 0, 'nsamples': 20400, 'resolution': array([16]), 'sampling rate': 1000, 'sync interval': 2, 'time': b'14:39:43.518'} ###Markdown By a simple "key" call it will be possible to access the values highlighted in blue, at topics 1.3.3A and 1.6B. ###Code # Sampling rate of the acquisition contained inside .txt file sr_txt = header_txt["00:07:80:3B:46:61"]["sampling rate"] # Sampling rate of the acquisition contained inside .h5 file sr_h5 = header_h5["sampling rate"] print("\033[1mSampling Rate (.txt):\033[0m " + str(sr_txt) + " Hz") print("\033[1mSampling Rate (.h5):\033[0m " + str(sr_h5) + " Hz") ###Output Sampling Rate (.txt): 1000 Hz Sampling Rate (.h5): 1000 Hz ###Markdown The previously described procedures, for accessing metadata from .txt and .h5 files, can be easily achieved while loading a file with bsnb.load function, by specifying the input argument called "get_header" as True ###Code # Specification of the file path (in our case is a relative file path but an absolute one can be specified) relative_file_path = "../../signal_samples/ecg_20_sec_1000_Hz.h5" data, header = bsnb.load(relative_file_path, get_header=True) from sty import fg, rs print(str(header).replace("device name", fg(98,195,238) + "\033[1mdevice name\033[0m" + fg.rs).replace("sampling rate", fg(98,195,238) + "\033[1msampling rate\033[0m" + fg.rs).replace("resolution", fg(98,195,238) + "\033[1mresolution\033[0m" + fg.rs)) ###Output {'channels': array([1]), 'comments': '', 'date': b'2018-9-28', 'device': 'biosignalsplux', 'device connection': b'BTH00:07:80:D8:A7:F9', 'device name': b'00:07:80:D8:A7:F9', 'digital IO': array([0, 1]), 'firmware version': 773, 'resolution': array([16]), 'sampling rate': 1000, 'sync interval': 2, 'time': b'14:39:43.518', 'sensor': [b'ECG'], 'column labels': {1: 'channel_1'}} ###Markdown As can be understood, for a correct and efficient processing of OpenSignals files it is mandatory to access the information contained inside the header (.txt files) or stored as attributes (.h5 files), like the acquisition sampling rate or device mac-address.This info (metadata ) is always attached to the "real data" as an essential complement. We hope that you have enjoyed this guide. biosignalsnotebooks is an environment in continuous expansion, so don't stop your journey and learn more with the remaining Notebooks ! **Auxiliary Code Segment (should not be replicated by the user)** ###Code from biosignalsnotebooks.__notebook_support__ import css_style_apply css_style_apply() %%html <script> // AUTORUN ALL CELLS ON NOTEBOOK-LOAD! require( ['base/js/namespace', 'jquery'], function(jupyter, $) { $(jupyter.events).on("kernel_ready.Kernel", function () { console.log("Auto-running all cells-below..."); jupyter.actions.call('jupyter-notebook:run-all-cells-below'); jupyter.actions.call('jupyter-notebook:save-notebook'); }); } ); </script> ###Output _____no_output_____
tutorial/04-kg-enrichment-with-csv.ipynb
###Markdown Augment A Knowledge Graph Using CSV FilesA common knowledge graph augmentation use case is to integrate structured data present in databases, CSV and Excel files. KGTK provides an alternative to languages such as R2RML (https://www.w3.org/TR/r2rml/) and RML (https://rml.io/specs/rml/) or tools such as Karma (https://github.com/usc-isi-i2/Web-Karma) for integrating tabluar data. These languages and tools work by defining a mapping between a structured souce and an ontology. KGTK provides capabilities to transform the original structured data into the TSV format used in KGTK to store KGs. This tutorial illustrates the KGTK approach using a CSV file downloaded from Kaggle (https://www.kaggle.com/stefanoleone992/imdb-extensive-dataset) containing information about moves from IMDb (https://www.imdb.com/).This tutorial is divided into multiple sections:- Survey what is available in our KG and in the IMDb file- Prepare the IMDb file for ingestion in KGTK- Find overlap betwwen our KG and the IMDb KG- Integrate knowledge from the IMDb KG into our KG- Implement a better model for the data Step 0: Install KGTK Only run the following cell if KGTK is not installed. For example, if running in [Google Colab](https://colab.research.google.com/) ###Code !pip install kgtk ###Output _____no_output_____ ###Markdown Preamble: set up the environment and files used in the tutorial ###Code import io import os import subprocess import sys import csv import pandas as pd from kgtk.configure_kgtk_notebooks import ConfigureKGTK from kgtk.functions import kgtk, kypher # Parameters # Folder on local machine where to create the output and temporary folders input_path = None output_path = "/tmp/projects" project_name = "tutorial-augment" ###Output _____no_output_____ ###Markdown These are all the KG files that we use in this tutorial: ###Code files = [ "all", "label", "alias", "description", "external_id", "monolingualtext", "quantity", "string", "time", "item", "wikibase_property", "qualifiers", "datatypes", "p279", "p279star", "p31", "in_degree", "out_degree", "pagerank_directed", "pagerank_undirected" ] input_files_url = "https://github.com/usc-isi-i2/kgtk-tutorial-files/raw/main/datasets/arnold-profiled" ck = ConfigureKGTK(files, input_files_url=input_files_url) ck.configure_kgtk(input_graph_path=input_path, output_path=output_path, project_name=project_name) ck.print_env_variables() ###Output TEMP: /tmp/projects/tutorial-augment/temp.tutorial-augment STORE: /tmp/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db kypher: kgtk query --graph-cache /tmp/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db KGTK_GRAPH_CACHE: /tmp/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db USE_CASES_DIR: /Users/amandeep/Github/kgtk-notebooks/use-cases kgtk: kgtk EXAMPLES_DIR: /Users/amandeep/Github/kgtk-notebooks/examples KGTK_LABEL_FILE: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/labels.en.tsv.gz KGTK_OPTION_DEBUG: false GRAPH: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input OUT: /tmp/projects/tutorial-augment all: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/all.tsv.gz label: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/labels.en.tsv.gz alias: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/aliases.en.tsv.gz description: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/descriptions.en.tsv.gz external_id: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.external-id.tsv.gz monolingualtext: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.monolingualtext.tsv.gz quantity: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.quantity.tsv.gz string: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.string.tsv.gz time: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.time.tsv.gz item: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.wikibase-item.tsv.gz wikibase_property: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.wikibase-property.tsv.gz qualifiers: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/qualifiers.tsv.gz datatypes: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.property.datatypes.tsv.gz p279: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P279.tsv.gz p279star: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P279star.tsv.gz p31: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P31.tsv.gz in_degree: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.in_degree.tsv.gz out_degree: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.out_degree.tsv.gz pagerank_directed: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.pagerank.directed.tsv.gz pagerank_undirected: /Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.pagerank.undirected.tsv.gz ###Markdown Load all my files into the kypher cache so that all graph aliases are defined ###Code %%time ck.load_files_into_cache() ###Output kgtk query --graph-cache /tmp/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/all.tsv.gz" --as all -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/labels.en.tsv.gz" --as label -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/aliases.en.tsv.gz" --as alias -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/descriptions.en.tsv.gz" --as description -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.external-id.tsv.gz" --as external_id -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.monolingualtext.tsv.gz" --as monolingualtext -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.quantity.tsv.gz" --as quantity -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.string.tsv.gz" --as string -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.time.tsv.gz" --as time -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.wikibase-item.tsv.gz" --as item -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/claims.wikibase-property.tsv.gz" --as wikibase_property -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/qualifiers.tsv.gz" --as qualifiers -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.property.datatypes.tsv.gz" --as datatypes -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P279.tsv.gz" --as p279 -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P279star.tsv.gz" --as p279star -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/derived.P31.tsv.gz" --as p31 -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.in_degree.tsv.gz" --as in_degree -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.out_degree.tsv.gz" --as out_degree -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.pagerank.directed.tsv.gz" --as pagerank_directed -i "/Users/amandeep/isi-kgtk-tutorial/tutorial-augment_input/metadata.pagerank.undirected.tsv.gz" --as pagerank_undirected --limit 3 node1 label node2 id node2;wikidatatype P10 alias 'gif'@en P10-alias-en-282226-0 P10 alias 'animation'@en P10-alias-en-2f86d8-0 P10 alias 'media'@en P10-alias-en-c1427e-0 CPU times: user 3.69 ms, sys: 10.3 ms, total: 14 ms Wall time: 35.6 s ###Markdown Survey the data in the IMDb fileThe first step is to determine whether our KG has IMDb identifiers, as this will make it easy to integrate the IMDb data.The following query counts the number of items in our KG that have an `IMDb ID (P345)`.Fortunately, our KG has many entities with IMDb identifiers: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->(imdbid)' --return 'count(distinct movie) as `"movies with IMDb identifiers"`' """) ###Output _____no_output_____ ###Markdown As there are many items that have IMDb ids, we can augment our graph using data from IMDB. The following file comes from Kaggle: https://www.kaggle.com/stefanoleone992/imdb-extensive-datasetOur KG, a subset of Wikidata is missing many fields that are present in the IMDb file. For example, when we look at `film (Q11424)` in our browser http://ckg07.isi.edu:3008/browser/Q11424, we see that there is no information about ratings. ###Code url = "https://github.com/usc-isi-i2/kgtk-notebooks/raw/main/datasets/imdb" other_files = [ "IMDB.csv.gz", "imdb-kg-node.tsv", "imdb-kg.tsv" ] for file in other_files: cmd = f" wget {url}/{file} --directory-prefix={os.environ['GRAPH']}/imdb" print(subprocess.getoutput(cmd)) imdb = pd.read_csv(os.environ['GRAPH'] + "/imdb/IMDB.csv.gz") imdb.head() ###Output /var/folders/qv/cxzpwz3j29x7n79vwpw253v80000gn/T/ipykernel_81921/3614653023.py:1: DtypeWarning: Columns (3) have mixed types. Specify dtype option on import or set low_memory=False. imdb = pd.read_csv(os.environ['GRAPH'] + "/imdb/IMDB.csv.gz") ###Markdown Prepare the IMDb file for ingestion in KGTKThis step illustrates the power of the KGTK approach: you canb convert the CSV file into a KG by simply renaming the column in the file that contains the identifier for the records to have the column heading `id`. Once you do this, the file becomes a KGTK node file, where the `id` column identifies a node, and the other columns define properties about the node. The initial node file is only a first approaximation, as additional transformations will be needed to make the data compatible with the KG.In this step, you will use use Pandas to convert the IMDb file to a KG node file by renaming the `imdb_title_id` column to `id` as it is the identifier for a movie.We will also convert non-numeric values in the cells to strings to enable us later to use string transformations to clean the data. ###Code imdb_kg = imdb.rename(columns={'imdb_title_id':'id'}) imdb_kg.head() ###Output _____no_output_____ ###Markdown In KGTK, most commands rquire KGs to be in edge format (`node1/labal/node2`), so we use the `normalize-nodes` command to convert the IMDb nodes file to edge format.The IMDb file contains 85K rows and 22 columns, gemerating 1.8 million edges.The IMDb KG is completely isolated from our KG, but it is still a valid KG that we4 can manipulate in KGTK:> In KGTK, literals, such as the string identifiers of movies, can be used as the subjects (`node1`) of triples. After converting the original CSV file to a node file, you can use the `normmalize-nodes` command to convert the node file to and edge file usinf the `node1/label/node2` headings. The columns of the original file become the labels of the edges and appear in the second column. Having done this, the original IMDB file has become a KG that you can transform using other KGTK commands. ###Code %%time kgtk(imdb_kg, """ normalize-nodes """) ###Output CPU times: user 9.66 s, sys: 2.19 s, total: 11.8 s Wall time: 12.6 s ###Markdown Save the IMDb KG to a temorary file and give it the alias `imdbkg`: ###Code %%time kgtk(imdb_kg, """ normalize-nodes -o $TEMP/imdb-kg-edge.tsv """) kgtk("query -i $TEMP/imdb-kg-edge.tsv --as imdbkg --limit 10") ###Output CPU times: user 2.05 s, sys: 271 ms, total: 2.32 s Wall time: 15.1 s ###Markdown Find overlap between our KG and the IMDb KGThe IMDb KG uses IMDb identifiers as nodes, and our KG, extracted from Wikidata, defined property `IMDb ID (P345)` to record the IMDb identifiers of movies.We can use KGTK to query both graphs simultaneously to find the movies in our graph for which there are nodes in the IMDb KG.> We are only interested in the `node1` in the IMDb KG , so we don't have to list the other elements of the pattern, thee `label` and `node2`. ###Code kgtk(""" query -i imdbkg -i external_id --match ' imdb: (imdb_id), external_id: (movie)-[:P345]->(imdb_id) ' --return 'distinct movie as id, imdb_id as P345' """) ###Output _____no_output_____ ###Markdown Count the number of entities in our KG that have an `IMDb ID (P345)`: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->()' --return 'count(distinct movie) as count_movies' """) ###Output _____no_output_____ ###Markdown Find the number of `film (Q11424)` in our KG.> Our IMDb KG only has information for films. ###Code kgtk(""" query -i all --match '(film)-[:P31]->(class)-[:P279star]->(:Q11424)' --return 'count(distinct film) as count_film' """) ###Output _____no_output_____ ###Markdown So, over 6,000 entities in our KG have IMDb identifers, about half of these are films, and about half of those appear in our IMDb KG. Integrate knowledge from the IMDb KG into our KGThere are many fields in the IMDb KG that we could integrate into our KG. In this tutorial we will focus on three fields: the `reviews_from_users`, `reviews_from_critics` and `duration`.Approach:- Query both KGs, joining on the IMDb identifier, and extract the properties we want- ETL the data to conform to the Wikidata convetions used in our KG Let's start with `reviews_from_users`, `reviews_from_critics`, which are counts. If we search in the browser we see very specific properties named `number of ...`, but none referring to number of reviews, so we will create two new properties, and we will give them the identifiers `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews`> We follow the Wikidata convention where the identifiers for properties start with `P` and the identifiers for entities start with `Q`. KGTK does not require to use numbers following `P` or `Q`, and it does not require that we follow the `P/Q` convention.To integrate the data we will use two KGs:- The `imdbkg` with the data we pulled directly from the IMDb csv file- The `external_id` subset of our KG that contains all external identifiers for all items in our KG.The `match` clause does a join on the identifers, enabling us to pull from the `imdbkg` the items thatalso exist in our KG.The `opt` clause (optional) retrieves the `reviews_from_users` property from the `imdbkg` KGWe use the `opt` clause so that if the `imdbkg` has a null, we still output the result.The `return` clause builds a new node file: we use the `film` node from our KG as the `id` for our node file, and we translate the `reviews_from_users` data from the `imdbkg` as a `Pnumber_of_user_reviews`, a new property in our KG (below we extend this query to integrate all the data).> In KGTK, you can integrate data from external sources using queries to map from one schema (ontology) to another, and do ETL transformations in one place.Our KG is starting to take shape. For every film in the intersection of the two KGs, we now have a new property `Pnumber_of_user_reviews`: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown You can extend the query to integrate `reviews_from_critics` and `duration` by adding additional `opt` clauses.Wikidata has propery `duration (P2047`), so we reuse it: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, duration as P2047 ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown If we browse `Terminator 2: Judgment Day (Q170564)`, we see that we ought to define units of measure (`minute (Q7727)`).In KGTK, quantities such as duration are represented as structured literals that incorporate the quantity and the units in one symbol.For example "142 minutes" is represented as `142Q7727`.It is easy to incorporate the units into our query by using the `printf` statement to combine multiple variables into a formatted string:> The case of units of measure is a good example of the benefit to do schema mapping and ETL in the same query.> We illustrate the use the KGTK function `kgtk_quantity_number` in the `order-by` clause to extract the numeric value of a quantity structured literals (https://kgtk.readthedocs.io/en/latest/transform/query/functions-on-kgtk-numbers-and-quantities) ###Code %%time kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' --order-by 'kgtk_quantity_number(P2047) desc' """) ###Output CPU times: user 10.4 ms, sys: 20 ms, total: 30.4 ms Wall time: 1.59 s ###Markdown The query above extracts data from the simple `imdbkg` graph that uses the column headings as properties. The query maps the properties and data to new or existing Wikidata properties that we use in our KG, and performs simple data cleaning to conform to the Wikidata and KGTK format requirement. The resulting KG is in KGTK node format where the properties appear in the column headings; we save this graph in `$TEMP/imdb-import.node.tsv`:> It is possible to create the KGTK node file using Pandas as the node file has very simmilar structure to the original CSV file. One of the advantages of KGTK is that it empowers users to use tools that they are familiar with, e.g., Pandas, to transform KGTK graphs. Integration with KGTK is seamless. ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' -o $TEMP/imdb-import.node.tsv """) ###Output _____no_output_____ ###Markdown The last step is to convert the node file to a an edge file so that it is in the standard form used by all KGTK commands.Convert the node file to edges and add edge ids:> If you had used Pandas to create the graph in node format, this same command would transform it into and edge file, and make the4 graph ready for use with any other KGTL commands. ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata """) ###Output _____no_output_____ ###Markdown Store the IMDb data, now represented in the Wikidata ontology, into a KG file and give it alias `augment_imdb` so that we can use it in the next steps: ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata -o $TEMP/augment.imdb.tsv """) kgtk("query -i $TEMP/augment.imdb.tsv --as augment_imdb --limit 2") ###Output _____no_output_____ ###Markdown Deduplicate the durations (`duration (P2047)`)Wikidata defines durations for many films. If we want to integrate the IMDb data into our KG, we must be careful as there may be inconsitent durations.Approach:- Find the films where the durations in Wikidata and IMDB differ- In case of conflict, prefer the IMDb durations First, find films where the durations are different using a query that combines the orignal `all` graph and the `augment_imdb` graph.There are many differences, and we see cases where the data in Wikidata is suspect (the uncertainty is the same as the value): ###Code kgtk(""" query -i all -i augment_imdb --match 'all: (film)-[:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb)' --where 'duration_wd < duration_imdb' --return 'distinct film as film, duration_wd as duration_wd, duration_imdb as duration_imdb' --order-by 'film' / add-labels """) ###Output _____no_output_____ ###Markdown We decide to remove from our original graph the edges for durations that differ from the durations in IMDb. We enhance our query to return the ids of such edges: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' """) ###Output _____no_output_____ ###Markdown Store the ids of the discrepant duration edges in a file: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' -o $TEMP/id.discrepant_durations.tsv """) ###Output _____no_output_____ ###Markdown Compute the intersection and difference of the two files: the original `$quantity` file that contains all the quantity edges for our subset of Wikidata, and `$TEMP/id.discrepant_durations.tsv`, the file that contains the ids of duration edges in `$quantity` where the values in Wikidata and IMDb differ.Use the KGTK `ifexists` command (https://kgtk.readthedocs.io/en/latest/transform/ifexists/).Provide the two files, the names of the columns used as keys (`id`), and tell the command to output the `reject-file` containing edges in the input file that are not present in the filter file (this is the file we want): ###Code kgtk(""" ifexists -i $quantity --filter-on $TEMP/id.discrepant_durations.tsv --input-keys id --reject-file $OUT/quantity.minus_bad_durations.tsv """) ###Output _____no_output_____ ###Markdown Sanity check: subtract the number of edges in the original quantity file `$quantity` minus the number of edges in `$OUT/quantity.minus_bad_durations.tsv`: ###Code old = !zcat < $quantity | wc -l new = !cat $OUT/quantity.minus_bad_durations.tsv | wc -l int(old[0]) - int(new[0]) ###Output _____no_output_____ ###Markdown Implement a better model for the IMDb dataThe data model we just implemented is very simple. In this section, we will improve it to be more compatible with how Wikidata models data.We will:- Add a `point in time (P585)` qualifier to record the time when the reviews were counted. We will use 2020-01-01, the date reported in the Kaggle site- Combine `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` into a single `Pnumber_of_reviews` property, and use the `of (P642)` qualifier property to record whether the review counts are from a `customer (Q852835)` or a `critic (Q6430706)`The approach we will use is to tranform the `augment_imdb` data we created above to have the desired structure. > An alternative approach would be to generate the data in the desired structure in the first place. The following query transforms the `Pnumber_of_user_reviews` data into the desired structure. The work is done in the `return` statement: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' """) ###Output _____no_output_____ ###Markdown As always, we want an edge file with ids, so we need to add the requisite `add-id` and `normalize` commands:> When doing this for real, we would not define multiple cells to revise the query. We would edit the cell, refining the pipeline to produce the desired results: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True """) ###Output _____no_output_____ ###Markdown Do, the same transformation for the counts of critic reviews, and concatenate the result for user (customaer) and critic into on result file `$TEMP/reviews.tsv`: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.user.tsv """) kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_critic_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q6430706" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.critic.tsv """) kgtk(""" cat -i $TEMP/reviews.user.tsv -i $TEMP/reviews.critic.tsv -o $TEMP/reviews.tsv """) ###Output _____no_output_____ ###Markdown Now we need to remove the edges using the old `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` and put in the new ones. We will use the `filter` command to do "grep" on the old file, and return the lines that don't match `--invert True`. The `filter`command uses a simple pattern language of the form `node1 pattern ; lable pattern ; node2 pattern` (https://kgtk.readthedocs.io/en/latest/transform/filter/): ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True """) ###Output _____no_output_____ ###Markdown Here is the unix-like grep/cat pipeline that replaces the old statements with the new ones: ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True / cat -i - -i $TEMP/reviews.tsv -o $OUT/augment.imdb.tsv """) ###Output _____no_output_____ ###Markdown Let's double check the results. The data looks good.To add the new data to our KG, and view it in the browser, we have to define the new `Pnumber_of_reviews` property, give it a label, aliases and description, and most importantly, define its `datatype` as `quantity`> We will not do this step in this tutorial. See https://github.com/usc-isi-i2/kgtk/blob/dev/kgtk-properties/kgtk.properties.tsv for examples of how to define new properties. ###Code kgtk("cat -i $OUT/augment.imdb.tsv") ###Output _____no_output_____ ###Markdown Summary of this tutorial:In this tutorial we:- Extracted data from a CSV file to add to our KG- Converted a CSV file into a KGTK graph using Pandas to create a simple KG (this step is similar to doing a direct mapping using R2RML https://www.w3.org/TR/rdb-direct-mapping/)- Used KGTK to extract/transform/load (ETL) the data into a simple model consistent with the Wikidata ontology- Transformed the simple model into a better model- The output of this section is - `$OUT/augment.imdb.tsv`, containing the new edges we created from the IMDb file - `$OUT/quantity.minus_bad_durations.tsv`, a modification of the orignal `$quantity` file where we removed discrepant durations.> The original IMDb file contains many other interesting fields that would be fun to import. Many of them such as genre, director, actors require much more work as we must link the names to entities in Wikidata. Entity linking is outside the scope of KGTK; tools such as OpenRefine (https://openrefine.org/) or our own Table Linker (https://github.com/usc-isi-i2/table-linker) can be used to do entity linking. The KGTK `replace-nodes` command is helpful to process files containing probabilistic "same-as" statements to integrate the results of external entity linking tools. Deploy the results (Optional)Deploy the tutorial files after completing this notebook. ###Code files_to_deploy = [ "metadata.p31x.count.transitive.tsv", "derived.P31x.tsv", "derived.P1963computed.tsv", "derived.Pproperty_domain.tsv", "derived.Punits_used.tsv", "derived.Paward_count.tsv" ] # First copy all the files from the add-derived-graphs, we will overwrite the ones that change, e.g., all.tsv !cp -p {tutorial_deployment_path + "/arnold"}/*.tsv* {project_deployment_path} for file in files_to_deploy: path = "$OUT/" + file !cp -p {path} {project_deployment_path} all_file_path = project_deployment_path + "/all.tsv.gz" if os.path.exists(all_file_path): !rm {all_file_path} !kgtk cat -i {tutorial_deployment_path + "/arnold/all.tsv.gz"} -i {project_deployment_path}/*.tsv -o {all_file_path} ###Output _____no_output_____ ###Markdown Augment A Knowledge Graph Using CSV FilesA common knowledge graph augmentation use case is to integrate structured data present in databases, CSV and Excel files. KGTK provides an alternative to languages such as R2RML (https://www.w3.org/TR/r2rml/) and RML (https://rml.io/specs/rml/) or tools such as Karma (https://github.com/usc-isi-i2/Web-Karma) for integrating tabluar data. These languages and tools work by defining a mapping between a structured souce and an ontology. KGTK provides capabilities to transform the original structured data into the TSV format used in KGTK to store KGs. This tutorial illustrates the KGTK approach using a CSV file downloaded from Kaggle (https://www.kaggle.com/stefanoleone992/imdb-extensive-dataset) containing information about moves from IMDb (https://www.imdb.com/).This tutorial is divided into multiple sections:- Survey what is available in our KG and in the IMDb file- Prepare the IMDb file for ingestion in KGTK- Find overlap betwwen our KG and the IMDb KG- Integrate knowledge from the IMDb KG into our KG- Implement a better model for the data ###Code import io import os import subprocess import sys import numpy as np import pandas as pd from IPython.display import display, HTML import csv import papermill as pm from kgtk.configure_kgtk_notebooks import ConfigureKGTK from kgtk.functions import kgtk, kypher # Parameters kgtk_path = "/Users/pedroszekely/Documents/GitHub/kgtk" tutorial_deployment_path = "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets" project_deployment_path = tutorial_deployment_path + "/arnold-augmented" # Folder on local machine where to create the output and temporary folders # input_path = "/Volumes/saggu-ssd/kgtk-tutorial-files/datasets/arnold-profiled" input_path = "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled" output_path = "/Users/pedroszekely/Downloads/kypher/projects" project_name = "tutorial-augment" ###Output _____no_output_____ ###Markdown These are all the KG files that we use in this tutorial: ###Code files = [ "all", "label", "alias", "description", "external_id", "monolingualtext", "quantity", "string", "time", "item", "wikibase_property", "qualifiers", "datatypes", "p279", "p279star", "p31", "in_degree", "out_degree", "pagerank_directed", "pagerank_undirected" ] ck = ConfigureKGTK(files, kgtk_path=kgtk_path) ck.configure_kgtk(input_graph_path=input_path, output_path=output_path, project_name=project_name) ck.print_env_variables() ###Output kgtk: kgtk kypher: kgtk query --graph-cache /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db USE_CASES_DIR: /Users/pedroszekely/Documents/GitHub/kgtk/use-cases KGTK_GRAPH_CACHE: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db KGTK_LABEL_FILE: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz STORE: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db KGTK_OPTION_DEBUG: false OUT: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment EXAMPLES_DIR: /Users/pedroszekely/Documents/GitHub/kgtk/examples GRAPH: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled TEMP: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment all: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/all.tsv.gz label: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz alias: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/aliases.en.tsv.gz description: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/descriptions.en.tsv.gz external_id: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.external-id.tsv.gz monolingualtext: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.monolingualtext.tsv.gz quantity: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.quantity.tsv.gz string: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.string.tsv.gz time: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.time.tsv.gz item: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-item.tsv.gz wikibase_property: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-property.tsv.gz qualifiers: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/qualifiers.tsv.gz datatypes: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.property.datatypes.tsv.gz p279: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279.tsv.gz p279star: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279star.tsv.gz p31: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P31.tsv.gz in_degree: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.in_degree.tsv.gz out_degree: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.out_degree.tsv.gz pagerank_directed: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.directed.tsv.gz pagerank_undirected: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.undirected.tsv.gz ###Markdown Set up defaults KGTK ###Code os.environ['KGTK_GRAPH_CACHE'] = os.environ['STORE'] ###Output _____no_output_____ ###Markdown Load all my files into the kypher cache so that all graph aliases are defined ###Code %%time ck.load_files_into_cache() ###Output kgtk query --graph-cache /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/all.tsv.gz" --as all -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz" --as label -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/aliases.en.tsv.gz" --as alias -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/descriptions.en.tsv.gz" --as description -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.external-id.tsv.gz" --as external_id -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.monolingualtext.tsv.gz" --as monolingualtext -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.quantity.tsv.gz" --as quantity -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.string.tsv.gz" --as string -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.time.tsv.gz" --as time -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-item.tsv.gz" --as item -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-property.tsv.gz" --as wikibase_property -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/qualifiers.tsv.gz" --as qualifiers -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.property.datatypes.tsv.gz" --as datatypes -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279.tsv.gz" --as p279 -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279star.tsv.gz" --as p279star -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P31.tsv.gz" --as p31 -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.in_degree.tsv.gz" --as in_degree -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.out_degree.tsv.gz" --as out_degree -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.directed.tsv.gz" --as pagerank_directed -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.undirected.tsv.gz" --as pagerank_undirected --limit 3 node1 label node2 id node2;wikidatatype P10 alias 'gif'@en P10-alias-en-282226-0 P10 alias 'animation'@en P10-alias-en-2f86d8-0 P10 alias 'media'@en P10-alias-en-c1427e-0 CPU times: user 5.38 ms, sys: 9.3 ms, total: 14.7 ms Wall time: 704 ms ###Markdown Survey the data in the IMDb fileThe first step is to determine whether our KG has IMDb identifiers, as this will make it easy to integrate the IMDb data.The following query counts the number of items in our KG that have an `IMDb ID (P345)`.Fortunately, our KG has many entities with IMDb identifiers: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->(imdbid)' --return 'count(distinct movie) as `"movies with IMDb identifiers"`' """) ###Output _____no_output_____ ###Markdown As there are many items that have IMDb ids, we can augment our graph using data from IMDB. The following file comes from Kaggle: https://www.kaggle.com/stefanoleone992/imdb-extensive-datasetOur KG, a subset of Wikidata is missing many fields that are present in the IMDb file. For example, when we look at `film (Q11424)` in our browser http://ckg07.isi.edu:3008/browser/Q11424, we see that there is no information about ratings. ###Code imdb = pd.read_csv(input_path + "/../imdb/IMDB.csv.gz") imdb ###Output /Users/pedroszekely/opt/anaconda3/envs/kgtk/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3444: DtypeWarning: Columns (3) have mixed types.Specify dtype option on import or set low_memory=False. exec(code_obj, self.user_global_ns, self.user_ns) ###Markdown Prepare the IMDb file for ingestion in KGTKThis step illustrates the power of the KGTK approach: you canb convert the CSV file into a KG by simply renaming the column in the file that contains the identifier for the records to have the column heading `id`. Once you do this, the file becomes a KGTK node file, where the `id` column identifies a node, and the other columns define properties about the node. The initial node file is only a first approaximation, as additional transformations will be needed to make the data compatible with the KG.In this step, you will use use Pandas to convert the IMDb file to a KG node file by renaming the `imdb_title_id` column to `id` as it is the identifier for a movie.We will also convert non-numeric values in the cells to strings to enable us later to use string transformations to clean the data. ###Code imdb_kg = imdb.rename(columns={'imdb_title_id':'id'}) imdb_kg ###Output _____no_output_____ ###Markdown In KGTK, most commands rquire KGs to be in edge format (`node1/labal/node2`), so we use the `normalize-nodes` command to convert the IMDb nodes file to edge format.The IMDb file contains 85K rows and 22 columns, gemerating 1.8 million edges.The IMDb KG is completely isolated from our KG, but it is still a valid KG that we4 can manipulate in KGTK:> In KGTK, literals, such as the string identifiers of movies, can be used as the subjects (`node1`) of triples. After converting the original CSV file to a node file, you can use the `normmalize-nodes` command to convert the node file to and edge file usinf the `node1/label/node2` headings. The columns of the original file become the labels of the edges and appear in the second column. Having done this, the original IMDB file has become a KG that you can transform using other KGTK commands. ###Code %%time kgtk(imdb_kg, """ normalize-nodes """) ###Output CPU times: user 12.4 s, sys: 2.97 s, total: 15.3 s Wall time: 15.2 s ###Markdown Save the IMDb KG to a temorary file and give it the alias `imdbkg`: ###Code %%time kgtk(imdb_kg, """ normalize-nodes -o $TEMP/imdb-kg-edge.tsv """) kgtk("query -i $TEMP/imdb-kg-edge.tsv --as imdbkg --limit 3") ###Output CPU times: user 2.55 s, sys: 340 ms, total: 2.89 s Wall time: 19.5 s ###Markdown Find overlap betwwen our KG and the IMDb KGThe IMDb KG uses IMDb identifiers as nodes, and our KG, extracted from Wikidata, defined property `IMDb ID (P345)` to record the IMDb identifiers of movies.We can use KGTK to query both graphs simultaneously to find the movies in our graph for which there are nodes in the IMDb KG.> We are only interested in the `node1` in the IMDb KG , so we don't have to list the other elements of the pattern, thee `label` and `node2`. ###Code kgtk(""" query -i imdbkg -i external_id --match ' imdb: (imdb_id), external_id: (movie)-[:P345]->(imdb_id) ' --return 'distinct movie as id, imdb_id as P345' """) ###Output _____no_output_____ ###Markdown Count the number of entities in our KG that have an `IMDb ID (P345)`: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->()' --return 'count(distinct movie) as count_movies' """) ###Output _____no_output_____ ###Markdown Find the number of `film (Q11424)` in our KG.> Our IMDb KG only has information for films. ###Code kgtk(""" query -i all --match '(film)-[:P31]->(class)-[:P279star]->(:Q11424)' --return 'count(distinct film) as count_film' """) ###Output _____no_output_____ ###Markdown So, over 6,000 entities in our KG have IMDb identifers, about half of these are films, and about half of those appear in our IMDb KG. Integrate knowledge from the IMDb KG into our KGThere are many fields in the IMDb KG that we could integrate into our KG. In this tutorial we will focus on three fields: the `reviews_from_users`, `reviews_from_critics` and `duration`.Approach:- Query both KGs, joining on the IMDb identifier, and extract the properties we want- ETL the data to conform to the Wikidata convetions used in our KG Let's start with `reviews_from_users`, `reviews_from_critics`, which are counts. If we search in the browser we see very specific properties named `number of ...`, but none referring to number of reviews, so we will create two new properties, and we will give them the identifiers `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews`> We follow the Wikidata convention where the identifiers for properties start with `P` and the identifiers for entities start with `Q`. KGTK does not require to use numbers following `P` or `Q`, and it does not require that we follow the `P/Q` convention.To integrate the data we will use two KGs:- The `imdbkg` with the data we pulled directly from the IMDb csv file- The `external_id` subset of our KG that contains all external identifiers for all items in our KG.The `match` clause does a join on the identifers, enabling us to pull from the `imdbkg` the items thatalso exist in our KG.The `opt` clause (optional) retrieves the `reviews_from_users` property from the `imdbkg` KGWe use the `opt` clause so that if the `imdbkg` has a null, we still output the result.The `return` clause builds a new node file: we use the `film` node from our KG as the `id` for our node file, and we translate the `reviews_from_users` data from the `imdbkg` as a `Pnumber_of_user_reviews`, a new property in our KG (below we extend this query to integrate all the data).> In KGTK, you can integrate data from external sources using queries to map from one schema (ontology) to another, and do ETL transformations in one place.Our KG is starting to take shape. For every film in the intersection of the two KGs, we now have a new property `Pnumber_of_user_reviews`: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown You can extend the query to integrate `reviews_from_critics` and `duration` by adding additional `opt` clauses.Wikidata has propery `duration (P2047`), so we reuse it: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, duration as P2047 ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown If we browse `Terminator 2: Judgment Day (Q170564)`, we see that we ought to define units of measure (`minute (Q7727)`).In KGTK, quantities such as duration are represented as structured literals that incorporate the quantity and the units in one symbol.For example "142 minutes" is represented as `142Q7727`.It is easy to incorporate the units into our query by using the `printf` statement to combine multiple variables into a formatted string:> The case of units of measure is a good example of the benefit to do schema mapping and ETL in the same query.> We illustrate the use the KGTK function `kgtk_quantity_number` in the `order-by` clause to extract the numeric value of a quantity structured literals (https://kgtk.readthedocs.io/en/latest/transform/query/functions-on-kgtk-numbers-and-quantities) ###Code %%time kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' --order-by 'kgtk_quantity_number(P2047) desc' """) ###Output CPU times: user 11.6 ms, sys: 18.8 ms, total: 30.5 ms Wall time: 1.09 s ###Markdown The query above extracts data from the simple `imdbkg` graph that uses the column headings as properties. The query maps the properties and data to new or existing Wikidata properties that we use in our KG, and performs simple data cleaning to conform to the Wikidata and KGTK format requirement. The resulting KG is in KGTK node format where the properties appear in the column headings; we save this graph in `$TEMP/imdb-import.node.tsv`:> It is possible to create the KGTK node file using Pandas as the node file has very simmilar structure to the original CSV file. One of the advantages of KGTK is that it empowers users to use tools that they are familiar with, e.g., Pandas, to transform KGTK graphs. Integration with KGTK is seamless. ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' -o $TEMP/imdb-import.node.tsv """) ###Output _____no_output_____ ###Markdown The last step is to convert the node file to a an edge file so that it is in the standard form used by all KGTK commands.Convert the node file to edges and add edge ids:> If you had used Pandas to create the graph in node format, this same command would transform it into and edge file, and make the4 graph ready for use with any other KGTL commands. ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata """) ###Output _____no_output_____ ###Markdown Store the IMDb data, now represented in the Wikidata ontology, into a KG file and give it alias `augment_imdb` so that we can use it in the next steps: ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata -o $TEMP/augment.imdb.tsv """) kgtk("query -i $TEMP/augment.imdb.tsv --as augment_imdb --limit 2") ###Output _____no_output_____ ###Markdown Deduplicate the durations (`duration (P2047)`)Wikidata defines durations for many films. If we want to integrate the IMDb data into our KG, we must be careful as there may be inconsitent durations.Approach:- Find the films where the durations in Wikidata and IMDB differ- In case of conflict, prefer the IMDb durations First, find films where the durations are different using a query that combines the orignal `all` graph and the `augment_imdb` graph.There are many differences, and we see cases where the data in Wikidata is suspect (the uncertainty is the same as the value): ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct film as film, duration_wd as duration_wd, duration_imdb as duration_imdb' --order-by 'film' / add-labels """) ###Output _____no_output_____ ###Markdown We decide to remove from our original graph the edges for durations that differ from the durations in IMDb. We enhance our query to return the ids of such edges: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' """) ###Output _____no_output_____ ###Markdown Store the ids of the discrepant duration edges in a file: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' -o $TEMP/id.discrepant_durations.tsv """) ###Output _____no_output_____ ###Markdown Compute the intersection and difference of the two files: the original `$quantity` file that contains all the quantity edges for our subset of Wikidata, and `$TEMP/id.discrepant_durations.tsv`, the file that contains the ids of duration edges in `$quantity` where the values in Wikidata and IMDb differ.Use the KGTK `ifexists` command (https://kgtk.readthedocs.io/en/latest/transform/ifexists/).Provide the two files, the names of the columns used as keys (`id`), and tell the command to output the `reject-file` containing edges in the input file that are not present in the filter file (this is the file we want): ###Code kgtk(""" ifexists -i $quantity --filter-on $TEMP/id.discrepant_durations.tsv --input-keys id --reject-file $OUT/quantity.minus_bad_durations.tsv """) ###Output _____no_output_____ ###Markdown Sanity check: subtract the number of edges in the original quantity file `$quantity` minus the number of edges in `$OUT/quantity.minus_bad_durations.tsv`: ###Code old = !zcat < $quantity | wc -l new = !cat $OUT/quantity.minus_bad_durations.tsv | wc -l int(old[0]) - int(new[0]) ###Output _____no_output_____ ###Markdown Implement a better model for the IMDb dataThe data model we just implemented is very simple. In this section, we will improve it to be more compatible with how Wikidata models data.We will:- Add a `point in time (P585)` qualifier to record the time when the reviews were counted. We will use 2020-01-01, the date reported in the Kaggle site- Combine `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` into a single `Pnumber_of_reviews` property, and use the `of (P642)` qualifier property to record whether the review counts are from a `customer (Q852835)` or a `critic (Q6430706)`The approach we will use is to tranform the `augment_imdb` data we created above to have the desired structure. > An alternative approach would be to generate the data in the desired structure in the first place. The following query transforms the `Pnumber_of_user_reviews` data into the desired structure. The work is done in the `return` statement: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' """) ###Output _____no_output_____ ###Markdown As always, we want an edge file with ids, so we need to add the requisite `add-id` and `normalize` commands:> When doing this for real, we would not define multiple cells to revise the query. We would edit the cell, refining the pipeline to produce the desired results: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True """) ###Output _____no_output_____ ###Markdown Do, the same transformation for the counts of critic reviews, and concatenate the result for user (customaer) and critic into on result file `$TEMP/reviews.tsv`: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.user.tsv """) kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_critic_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q6430706" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.critic.tsv """) kgtk(""" cat -i $TEMP/reviews.user.tsv -i $TEMP/reviews.critic.tsv -o $TEMP/reviews.tsv """) ###Output _____no_output_____ ###Markdown Now we need to remove the edges using the old `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` and put in the new ones. We will use the `filter` command to do "grep" on the old file, and return the lines that don't match `--invert True`. The `filter`command uses a simple pattern language of the form `node1 pattern ; lable pattern ; node2 pattern` (https://kgtk.readthedocs.io/en/latest/transform/filter/): ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True """) ###Output _____no_output_____ ###Markdown Here is the unix-like grep/cat pipeline that replaces the old statements with the new ones: ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True / cat -i - -i $TEMP/reviews.tsv -o $OUT/augment.imdb.tsv """) ###Output _____no_output_____ ###Markdown Let's double check the results. The data looks good.To add the new data to our KG, and view it in the browser, we have to define the new `Pnumber_of_reviews` property, give it a label, aliases and description, and most importantly, define its `datatype` as `quantity`> We will not do this step in this tutorial. See https://github.com/usc-isi-i2/kgtk/blob/dev/kgtk-properties/kgtk.properties.tsv for examples of how to define new properties. ###Code kgtk("cat -i $OUT/augment.imdb.tsv") ###Output _____no_output_____ ###Markdown Summary of this tutorial:In this tutorial we:- Extracted data from a CSV file to add to our KG- Converted a CSV file into a KGTK graph using Pandas to create a simple KG (this step is similar to doing a direct mapping using R2RML https://www.w3.org/TR/rdb-direct-mapping/)- Used KGTK to extract/transform/load (ETL) the data into a simple model consistent with the Wikidata ontology- Transformed the simple model into a better model- The output of this section is - `$OUT/augment.imdb.tsv`, containing the new edges we created from the IMDb file - `$OUT/quantity.minus_bad_durations.tsv`, a modification of the orignal `$quantity` file where we removed discrepant durations.> The original IMDb file contains many other interesting fields that would be fun to import. Many of them such as genre, director, actors require much more work as we must link the names to entities in Wikidata. Entity linking is outside the scope of KGTK; tools such as OpenRefine (https://openrefine.org/) or our own Table Linker (https://github.com/usc-isi-i2/table-linker) can be used to do entity linking. The KGTK `replace-nodes` command is helpful to process files containing probabilistic "same-as" statements to integrate the results of external entity linking tools. Deploy the results (Optional)Deploy the tutorial files after completing this notebook. ###Code files_to_deploy = [ "metadata.p31x.count.transitive.tsv", "derived.P31x.tsv", "derived.P1963computed.tsv", "derived.Pproperty_domain.tsv", "derived.Punits_used.tsv", "derived.Paward_count.tsv" ] # First copy all the files from the add-derived-graphs, we will overwrite the ones that change, e.g., all.tsv !cp -p {tutorial_deployment_path + "/arnold"}/*.tsv* {project_deployment_path} for file in files_to_deploy: path = "$OUT/" + file !cp -p {path} {project_deployment_path} all_file_path = project_deployment_path + "/all.tsv.gz" if os.path.exists(all_file_path): !rm {all_file_path} !kgtk cat -i {tutorial_deployment_path + "/arnold/all.tsv.gz"} -i {project_deployment_path}/*.tsv -o {all_file_path} ###Output _____no_output_____ ###Markdown Augment A Knowledge Graph Using CSV FilesA common knowledge graph augmentation use case is to integrate structured data present in databases, CSV and Excel files. KGTK provides an alternative to languages such as R2RML (https://www.w3.org/TR/r2rml/) and RML (https://rml.io/specs/rml/) or tools such as Karma (https://github.com/usc-isi-i2/Web-Karma) for integrating tabluar data. These languages and tools work by defining a mapping between a structured souce and an ontology. KGTK provides capabilities to transform the original structured data into the TSV format used in KGTK to store KGs. This tutorial illustrates the KGTK approach using a CSV file downloaded from Kaggle (https://www.kaggle.com/stefanoleone992/imdb-extensive-dataset) containing information about moves from IMDb (https://www.imdb.com/).This tutorial is divided into multiple sections:- Survey what is available in our KG and in the IMDb file- Prepare the IMDb file for ingestion in KGTK- Find overlap betwwen our KG and the IMDb KG- Integrate knowledge from the IMDb KG into our KG- Implement a better model for the data ###Code import io import os import subprocess import sys import numpy as np import pandas as pd from IPython.display import display, HTML import csv import papermill as pm from kgtk.configure_kgtk_notebooks import ConfigureKGTK from kgtk.functions import kgtk, kypher # Parameters kgtk_path = "/Users/pedroszekely/Documents/GitHub/kgtk" tutorial_deployment_path = "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets" project_deployment_path = tutorial_deployment_path + "/arnold-augmented" # Folder on local machine where to create the output and temporary folders # input_path = "/Volumes/saggu-ssd/kgtk-tutorial-files/datasets/arnold-profiled" input_path = "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled" output_path = "/Users/pedroszekely/Downloads/kypher/projects" project_name = "tutorial-augment" ###Output _____no_output_____ ###Markdown These are all the KG files that we use in this tutorial: ###Code files = [ "all", "label", "alias", "description", "external_id", "monolingualtext", "quantity", "string", "time", "item", "wikibase_property", "qualifiers", "datatypes", "p279", "p279star", "p31", "in_degree", "out_degree", "pagerank_directed", "pagerank_undirected" ] ck = ConfigureKGTK(files, kgtk_path=kgtk_path) ck.configure_kgtk(input_graph_path=input_path, output_path=output_path, project_name=project_name) ck.print_env_variables() ###Output STORE: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db kgtk: kgtk USE_CASES_DIR: /Users/pedroszekely/Documents/GitHub/kgtk/use-cases OUT: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment kypher: kgtk query --graph-cache /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db EXAMPLES_DIR: /Users/pedroszekely/Documents/GitHub/kgtk/examples GRAPH: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled KGTK_OPTION_DEBUG: false TEMP: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment KGTK_GRAPH_CACHE: /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db KGTK_LABEL_FILE: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz all: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/all.tsv.gz label: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz alias: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/aliases.en.tsv.gz description: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/descriptions.en.tsv.gz external_id: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.external-id.tsv.gz monolingualtext: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.monolingualtext.tsv.gz quantity: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.quantity.tsv.gz string: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.string.tsv.gz time: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.time.tsv.gz item: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-item.tsv.gz wikibase_property: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-property.tsv.gz qualifiers: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/qualifiers.tsv.gz datatypes: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.property.datatypes.tsv.gz p279: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279.tsv.gz p279star: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279star.tsv.gz p31: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P31.tsv.gz in_degree: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.in_degree.tsv.gz out_degree: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.out_degree.tsv.gz pagerank_directed: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.directed.tsv.gz pagerank_undirected: /Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.undirected.tsv.gz ###Markdown Set up defaults KGTK ###Code os.environ['KGTK_GRAPH_CACHE'] = os.environ['STORE'] ###Output _____no_output_____ ###Markdown Load all my files into the kypher cache so that all graph aliases are defined ###Code %%time ck.load_files_into_cache() ###Output kgtk query --graph-cache /Users/pedroszekely/Downloads/kypher/projects/tutorial-augment/temp.tutorial-augment/wikidata.sqlite3.db -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/all.tsv.gz" --as all -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/labels.en.tsv.gz" --as label -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/aliases.en.tsv.gz" --as alias -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/descriptions.en.tsv.gz" --as description -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.external-id.tsv.gz" --as external_id -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.monolingualtext.tsv.gz" --as monolingualtext -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.quantity.tsv.gz" --as quantity -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.string.tsv.gz" --as string -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.time.tsv.gz" --as time -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-item.tsv.gz" --as item -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/claims.wikibase-property.tsv.gz" --as wikibase_property -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/qualifiers.tsv.gz" --as qualifiers -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.property.datatypes.tsv.gz" --as datatypes -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279.tsv.gz" --as p279 -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P279star.tsv.gz" --as p279star -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/derived.P31.tsv.gz" --as p31 -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.in_degree.tsv.gz" --as in_degree -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.out_degree.tsv.gz" --as out_degree -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.directed.tsv.gz" --as pagerank_directed -i "/Users/pedroszekely/Documents/GitHub/kgtk-tutorial-files/datasets/arnold-profiled/metadata.pagerank.undirected.tsv.gz" --as pagerank_undirected --limit 3 node1 label node2 id node2;wikidatatype P10 alias 'gif'@en P10-alias-en-282226-0 P10 alias 'animation'@en P10-alias-en-2f86d8-0 P10 alias 'media'@en P10-alias-en-c1427e-0 CPU times: user 7.07 ms, sys: 12 ms, total: 19.1 ms Wall time: 42.1 s ###Markdown Survey the data in the IMDb fileThe first step is to determine whether our KG has IMDb identifiers, as this will make it easy to integrate the IMDb data.The following query counts the number of items in our KG that have an `IMDb ID (P345)`.Fortunately, our KG has many entities with IMDb identifiers: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->(imdbid)' --return 'count(distinct movie) as `"movies with IMDb identifiers"`' """) ###Output _____no_output_____ ###Markdown As there are many items that have IMDb ids, we can augment our graph using data from IMDB. The following file comes from Kaggle: https://www.kaggle.com/stefanoleone992/imdb-extensive-datasetOur KG, a subset of Wikidata is missing many fields that are present in the IMDb file. For example, when we look at `film (Q11424)` in our browser http://ckg07.isi.edu:3008/browser/Q11424, we see that there is no information about ratings. ###Code imdb = pd.read_csv(input_path + "/../imdb/IMDB.csv.gz") imdb ###Output /Users/pedroszekely/opt/anaconda3/envs/kgtk/lib/python3.8/site-packages/IPython/core/interactiveshell.py:3444: DtypeWarning: Columns (3) have mixed types.Specify dtype option on import or set low_memory=False. exec(code_obj, self.user_global_ns, self.user_ns) ###Markdown Prepare the IMDb file for ingestion in KGTKThis step illustrates the power of the KGTK approach: you canb convert the CSV file into a KG by simply renaming the column in the file that contains the identifier for the records to have the column heading `id`. Once you do this, the file becomes a KGTK node file, where the `id` column identifies a node, and the other columns define properties about the node. The initial node file is only a first approaximation, as additional transformations will be needed to make the data compatible with the KG.In this step, you will use use Pandas to convert the IMDb file to a KG node file by renaming the `imdb_title_id` column to `id` as it is the identifier for a movie.We will also convert non-numeric values in the cells to strings to enable us later to use string transformations to clean the data. ###Code imdb_kg = imdb.rename(columns={'imdb_title_id':'id'}) imdb_kg ###Output _____no_output_____ ###Markdown In KGTK, most commands rquire KGs to be in edge format (`node1/labal/node2`), so we use the `normalize-nodes` command to convert the IMDb nodes file to edge format.The IMDb file contains 85K rows and 22 columns, gemerating 1.8 million edges.The IMDb KG is completely isolated from our KG, but it is still a valid KG that we4 can manipulate in KGTK:> In KGTK, literals, such as the string identifiers of movies, can be used as the subjects (`node1`) of triples. After converting the original CSV file to a node file, you can use the `normmalize-nodes` command to convert the node file to and edge file usinf the `node1/label/node2` headings. The columns of the original file become the labels of the edges and appear in the second column. Having done this, the original IMDB file has become a KG that you can transform using other KGTK commands. ###Code %%time kgtk(imdb_kg, """ normalize-nodes """) ###Output CPU times: user 9.59 s, sys: 1.89 s, total: 11.5 s Wall time: 12.2 s ###Markdown Save the IMDb KG to a temorary file and give it the alias `imdbkg`: ###Code %%time kgtk(imdb_kg, """ normalize-nodes -o $TEMP/imdb-kg-edge.tsv """) kgtk("query -i $TEMP/imdb-kg-edge.tsv --as imdbkg --limit 3") ###Output CPU times: user 13.1 ms, sys: 39.5 ms, total: 52.5 ms Wall time: 16.1 s ###Markdown Find overlap betwwen our KG and the IMDb KGThe IMDb KG uses IMDb identifiers as nodes, and our KG, extracted from Wikidata, defined property `IMDb ID (P345)` to record the IMDb identifiers of movies.We can use KGTK to query both graphs simultaneously to find the movies in our graph for which there are nodes in the IMDb KG.> We are only interested in the `node1` in the IMDb KG , so we don't have to list the other elements of the pattern, thee `label` and `node2`. ###Code kgtk(""" query -i imdbkg -i external_id --match ' imdb: (imdb_id), external_id: (movie)-[:P345]->(imdb_id) ' --return 'distinct movie as id, imdb_id as P345' """) ###Output _____no_output_____ ###Markdown Count the number of entities in our KG that have an `IMDb ID (P345)`: ###Code kgtk(""" query -i external_id --match '(movie)-[:P345]->()' --return 'count(distinct movie) as count_movies' """) ###Output _____no_output_____ ###Markdown Find the number of `film (Q11424)` in our KG.> Our IMDb KG only has information for films. ###Code kgtk(""" query -i all --match '(film)-[:P31]->(class)-[:P279star]->(:Q11424)' --return 'count(distinct film) as count_film' """) ###Output _____no_output_____ ###Markdown So, over 6,000 entities in our KG have IMDb identifers, about half of these are films, and about half of those appear in our IMDb KG. Integrate knowledge from the IMDb KG into our KGThere are many fields in the IMDb KG that we could integrate into our KG. In this tutorial we will focus on three fields: the `reviews_from_users`, `reviews_from_critics` and `duration`.Approach:- Query both KGs, joining on the IMDb identifier, and extract the properties we want- ETL the data to conform to the Wikidata convetions used in our KG Let's start with `reviews_from_users`, `reviews_from_critics`, which are counts. If we search in the browser we see very specific properties named `number of ...`, but none referring to number of reviews, so we will create two new properties, and we will give them the identifiers `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews`> We follow the Wikidata convention where the identifiers for properties start with `P` and the identifiers for entities start with `Q`. KGTK does not require to use numbers following `P` or `Q`, and it does not require that we follow the `P/Q` convention.To integrate the data we will use two KGs:- The `imdbkg` with the data we pulled directly from the IMDb csv file- The `external_id` subset of our KG that contains all external identifiers for all items in our KG.The `match` clause does a join on the identifers, enabling us to pull from the `imdbkg` the items thatalso exist in our KG.The `opt` clause (optional) retrieves the `reviews_from_users` property from the `imdbkg` KGWe use the `opt` clause so that if the `imdbkg` has a null, we still output the result.The `return` clause builds a new node file: we use the `film` node from our KG as the `id` for our node file, and we translate the `reviews_from_users` data from the `imdbkg` as a `Pnumber_of_user_reviews`, a new property in our KG (below we extend this query to integrate all the data).> In KGTK, you can integrate data from external sources using queries to map from one schema (ontology) to another, and do ETL transformations in one place.Our KG is starting to take shape. For every film in the intersection of the two KGs, we now have a new property `Pnumber_of_user_reviews`: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown You can extend the query to integrate `reviews_from_critics` and `duration` by adding additional `opt` clauses.Wikidata has propery `duration (P2047`), so we reuse it: ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, duration as P2047 ' --order-by 'cast(rfu, int) desc' """) ###Output _____no_output_____ ###Markdown If we browse `Terminator 2: Judgment Day (Q170564)`, we see that we ought to define units of measure (`minute (Q7727)`).In KGTK, quantities such as duration are represented as structured literals that incorporate the quantity and the units in one symbol.For example "142 minutes" is represented as `142Q7727`.It is easy to incorporate the units into our query by using the `printf` statement to combine multiple variables into a formatted string:> The case of units of measure is a good example of the benefit to do schema mapping and ETL in the same query.> We illustrate the use the KGTK function `kgtk_quantity_number` in the `order-by` clause to extract the numeric value of a quantity structured literals (https://kgtk.readthedocs.io/en/latest/transform/query/functions-on-kgtk-numbers-and-quantities) ###Code %%time kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' --order-by 'kgtk_quantity_number(P2047) desc' """) ###Output CPU times: user 10.5 ms, sys: 16.7 ms, total: 27.2 ms Wall time: 1.18 s ###Markdown The query above extracts data from the simple `imdbkg` graph that uses the column headings as properties. The query maps the properties and data to new or existing Wikidata properties that we use in our KG, and performs simple data cleaning to conform to the Wikidata and KGTK format requirement. The resulting KG is in KGTK node format where the properties appear in the column headings; we save this graph in `$TEMP/imdb-import.node.tsv`:> It is possible to create the KGTK node file using Pandas as the node file has very simmilar structure to the original CSV file. One of the advantages of KGTK is that it empowers users to use tools that they are familiar with, e.g., Pandas, to transform KGTK graphs. Integration with KGTK is seamless. ###Code kgtk(""" query -i imdbkg -i external_id --match ' external_id: (film)-[:P345]->(imdb_id), imdb: (imdb_id)' --opt ' imdb: (imdb_id)-[:reviews_from_users]->(rfu)' --opt ' imdb: (imdb_id)-[:reviews_from_critics]->(rfc)' --opt ' imdb: (imdb_id)-[:duration]->(duration)' --return 'distinct film as id, rfu as Pnumber_of_user_reviews, rfc as Pnumber_of_critic_reviews, printf("+%sQ7727", duration) as P2047 ' -o $TEMP/imdb-import.node.tsv """) ###Output _____no_output_____ ###Markdown The last step is to convert the node file to a an edge file so that it is in the standard form used by all KGTK commands.Convert the node file to edges and add edge ids:> If you had used Pandas to create the graph in node format, this same command would transform it into and edge file, and make the4 graph ready for use with any other KGTL commands. ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata """) ###Output _____no_output_____ ###Markdown Store the IMDb data, now represented in the Wikidata ontology, into a KG file and give it alias `augment_imdb` so that we can use it in the next steps: ###Code kgtk(""" normalize-nodes -i $TEMP/imdb-import.node.tsv / add-id --id-style wikidata -o $TEMP/augment.imdb.tsv """) kgtk("query -i $TEMP/augment.imdb.tsv --as augment_imdb --limit 2") ###Output _____no_output_____ ###Markdown Deduplicate the durations (`duration (P2047)`)Wikidata defines durations for many films. If we want to integrate the IMDb data into our KG, we must be careful as there may be inconsitent durations.Approach:- Find the films where the durations in Wikidata and IMDB differ- In case of conflict, prefer the IMDb durations First, find films where the durations are different using a query that combines the orignal `all` graph and the `augment_imdb` graph.There are many differences, and we see cases where the data in Wikidata is suspect (the uncertainty is the same as the value): ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct film as film, duration_wd as duration_wd, duration_imdb as duration_imdb' --order-by 'film' / add-labels """) ###Output _____no_output_____ ###Markdown We decide to remove from our original graph the edges for durations that differ from the durations in IMDb. We enhance our query to return the ids of such edges: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' """) ###Output _____no_output_____ ###Markdown Store the ids of the discrepant duration edges in a file: ###Code kgtk(""" query -i all -i augment_imdb --match ' all: (film)-[l:P2047]->(duration_wd), augment_imdb: (film)-[:P2047]->(duration_imdb) ' --where 'duration_wd < duration_imdb' --return 'distinct l as id' --order-by 'l' -o $TEMP/id.discrepant_durations.tsv """) ###Output _____no_output_____ ###Markdown Compute the intersection and difference of the two files: the original `$quantity` file that contains all the quantity edges for our subset of Wikidata, and `$TEMP/id.discrepant_durations.tsv`, the file that contains the ids of duration edges in `$quantity` where the values in Wikidata and IMDb differ.Use the KGTK `ifexists` command (https://kgtk.readthedocs.io/en/latest/transform/ifexists/).Provide the two files, the names of the columns used as keys (`id`), and tell the command to output the `reject-file` containing edges in the input file that are not present in the filter file (this is the file we want): ###Code kgtk(""" ifexists -i $quantity --filter-on $TEMP/id.discrepant_durations.tsv --input-keys id --reject-file $OUT/quantity.minus_bad_durations.tsv """) ###Output _____no_output_____ ###Markdown Sanity check: subtract the number of edges in the original quantity file `$quantity` minus the number of edges in `$OUT/quantity.minus_bad_durations.tsv`: ###Code old = !zcat < $quantity | wc -l new = !cat $OUT/quantity.minus_bad_durations.tsv | wc -l int(old[0]) - int(new[0]) ###Output _____no_output_____ ###Markdown Implement a better model for the IMDb dataThe data model we just implemented is very simple. In this section, we will improve it to be more compatible with how Wikidata models data.We will:- Add a `point in time (P585)` qualifier to record the time when the reviews were counted. We will use 2020-01-01, the date reported in the Kaggle site- Combine `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` into a single `Pnumber_of_reviews` property, and use the `of (P642)` qualifier property to record whether the review counts are from a `customer (Q852835)` or a `critic (Q6430706)`The approach we will use is to tranform the `augment_imdb` data we created above to have the desired structure. > An alternative approach would be to generate the data in the desired structure in the first place. The following query transforms the `Pnumber_of_user_reviews` data into the desired structure. The work is done in the `return` statement: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' """) ###Output _____no_output_____ ###Markdown As always, we want an edge file with ids, so we need to add the requisite `add-id` and `normalize` commands:> When doing this for real, we would not define multiple cells to revise the query. We would edit the cell, refining the pipeline to produce the desired results: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True """) ###Output _____no_output_____ ###Markdown Do, the same transformation for the counts of critic reviews, and concatenate the result for user (customaer) and critic into on result file `$TEMP/reviews.tsv`: ###Code kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_user_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q852835" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.user.tsv """) kgtk(""" query -i augment_imdb --match '(film)-[:Pnumber_of_critic_reviews]->(count)' --return ' film as node1, "Pnumber_of_reviews" as label, count as node2, "Q6430706" as P642, "^2020-01-01T00:00:00Z/11" as P585 ' / add-id --id-style wikidata / normalize --add-id True -o $TEMP/reviews.critic.tsv """) kgtk(""" cat -i $TEMP/reviews.user.tsv -i $TEMP/reviews.critic.tsv -o $TEMP/reviews.tsv """) ###Output _____no_output_____ ###Markdown Now we need to remove the edges using the old `Pnumber_of_user_reviews` and `Pnumber_of_critic_reviews` and put in the new ones. We will use the `filter` command to do "grep" on the old file, and return the lines that don't match `--invert True`. The `filter`command uses a simple pattern language of the form `node1 pattern ; lable pattern ; node2 pattern` (https://kgtk.readthedocs.io/en/latest/transform/filter/): ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True """) ###Output _____no_output_____ ###Markdown Here is the unix-like grep/cat pipeline that replaces the old statements with the new ones: ###Code kgtk(""" filter -i $TEMP/augment.imdb.tsv --pattern '; Pnumber_of_user_reviews, Pnumber_of_critic_reviews ;' --invert True / cat -i - -i $TEMP/reviews.tsv -o $OUT/augment.imdb.tsv """) ###Output _____no_output_____ ###Markdown Let's double check the results. The data looks good.To add the new data to our KG, and view it in the browser, we have to define the new `Pnumber_of_reviews` property, give it a label, aliases and description, and most importantly, define its `datatype` as `quantity`> We will not do this step in this tutorial. See https://github.com/usc-isi-i2/kgtk/blob/dev/kgtk-properties/kgtk.properties.tsv for examples of how to define new properties. ###Code kgtk("cat -i $OUT/augment.imdb.tsv") ###Output _____no_output_____ ###Markdown Summary of this tutorial:In this tutorial we:- Extracted data from a CSV file to add to our KG- Converted a CSV file into a KGTK graph using Pandas to create a simple KG (this step is similar to doing a direct mapping using R2RML https://www.w3.org/TR/rdb-direct-mapping/)- Used KGTK to extract/transform/load (ETL) the data into a simple model consistent with the Wikidata ontology- Transformed the simple model into a better model- The output of this section is - `$OUT/augment.imdb.tsv`, containing the new edges we created from the IMDb file - `$OUT/quantity.minus_bad_durations.tsv`, a modification of the orignal `$quantity` file where we removed discrepant durations.> The original IMDb file contains many other interesting fields that would be fun to import. Many of them such as genre, director, actors require much more work as we must link the names to entities in Wikidata. Entity linking is outside the scope of KGTK; tools such as OpenRefine (https://openrefine.org/) or our own Table Linker (https://github.com/usc-isi-i2/table-linker) can be used to do entity linking. The KGTK `replace-nodes` command is helpful to process files containing probabilistic "same-as" statements to integrate the results of external entity linking tools. Deploy the results (Optional)Deploy the tutorial files after completing this notebook. ###Code files_to_deploy = [ "metadata.p31x.count.transitive.tsv", "derived.P31x.tsv", "derived.P1963computed.tsv", "derived.Pproperty_domain.tsv", "derived.Punits_used.tsv", "derived.Paward_count.tsv" ] # First copy all the files from the add-derived-graphs, we will overwrite the ones that change, e.g., all.tsv !cp -p {tutorial_deployment_path + "/arnold"}/*.tsv* {project_deployment_path} for file in files_to_deploy: path = "$OUT/" + file !cp -p {path} {project_deployment_path} all_file_path = project_deployment_path + "/all.tsv.gz" if os.path.exists(all_file_path): !rm {all_file_path} !kgtk cat -i {tutorial_deployment_path + "/arnold/all.tsv.gz"} -i {project_deployment_path}/*.tsv -o {all_file_path} ###Output _____no_output_____ ###Markdown List all the files: ###Code !ls -l {project_deployment_path} ###Output _____no_output_____
pix2pix_inference.ipynb
###Markdown Load Pix2pix-mobilenet generator ###Code save_path = '/content/drive/MyDrive/B.Tech Project/saved_models/pix2pix3/mobilenetv2/bs1/' generator = tf.keras.models.load_model(save_path+'generator.h5') generator.summary() tf.keras.utils.plot_model(generator, show_shapes=True, dpi=64) ###Output Model: "model_1" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_3 (InputLayer) [(None, 256, 256, 1) 0 __________________________________________________________________________________________________ tf.concat (TFOpLambda) (None, 256, 256, 3) 0 input_3[0][0] input_3[0][0] input_3[0][0] __________________________________________________________________________________________________ model (Functional) [(None, 128, 128, 96 1841984 tf.concat[0][0] __________________________________________________________________________________________________ sequential_2 (Sequential) (None, 16, 16, 512) 2623488 model[0][4] __________________________________________________________________________________________________ concatenate (Concatenate) (None, 16, 16, 1088) 0 sequential_2[0][0] model[0][3] __________________________________________________________________________________________________ sequential_3 (Sequential) (None, 32, 32, 512) 8914944 concatenate[0][0] __________________________________________________________________________________________________ concatenate_1 (Concatenate) (None, 32, 32, 704) 0 sequential_3[0][0] model[0][2] __________________________________________________________________________________________________ sequential_4 (Sequential) (None, 64, 64, 256) 2884608 concatenate_1[0][0] __________________________________________________________________________________________________ concatenate_2 (Concatenate) (None, 64, 64, 400) 0 sequential_4[0][0] model[0][1] __________________________________________________________________________________________________ sequential_5 (Sequential) (None, 128, 128, 128 819712 concatenate_2[0][0] __________________________________________________________________________________________________ concatenate_3 (Concatenate) (None, 128, 128, 224 0 sequential_5[0][0] model[0][0] __________________________________________________________________________________________________ sequential_6 (Sequential) (None, 256, 256, 64) 229632 concatenate_3[0][0] __________________________________________________________________________________________________ conv2d_transpose_6 (Conv2DTrans (None, 256, 256, 3) 195 sequential_6[0][0] ================================================================================================== Total params: 17,314,563 Trainable params: 15,469,635 Non-trainable params: 1,844,928 __________________________________________________________________________________________________ ###Markdown Load Pix2pix-densenet generator ###Code save_path2 = '/content/drive/MyDrive/B.Tech Project/saved_models/pix2pix3/densenet121/bs1/' generator2 = tf.keras.models.load_model(save_path2+'generator.h5') generator2.summary() tf.keras.utils.plot_model(generator2, show_shapes=True, dpi=64) for inp, tar in test_dataset.take(50): generate_images(generator2, inp, tar) discriminator = Discriminator() discriminator.summary() ###Output Model: "model" __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_image (InputLayer) [(None, 256, 256, 1) 0 __________________________________________________________________________________________________ target_image (InputLayer) [(None, 256, 256, 2) 0 __________________________________________________________________________________________________ concatenate (Concatenate) (None, 256, 256, 3) 0 input_image[0][0] target_image[0][0] __________________________________________________________________________________________________ sequential (Sequential) (None, 128, 128, 64) 3072 concatenate[0][0] __________________________________________________________________________________________________ sequential_1 (Sequential) (None, 64, 64, 128) 131584 sequential[0][0] __________________________________________________________________________________________________ sequential_2 (Sequential) (None, 32, 32, 256) 525312 sequential_1[0][0] __________________________________________________________________________________________________ zero_padding2d (ZeroPadding2D) (None, 34, 34, 256) 0 sequential_2[0][0] __________________________________________________________________________________________________ conv2d_3 (Conv2D) (None, 31, 31, 512) 2097152 zero_padding2d[0][0] __________________________________________________________________________________________________ batch_normalization_2 (BatchNor (None, 31, 31, 512) 2048 conv2d_3[0][0] __________________________________________________________________________________________________ leaky_re_lu_3 (LeakyReLU) (None, 31, 31, 512) 0 batch_normalization_2[0][0] __________________________________________________________________________________________________ zero_padding2d_1 (ZeroPadding2D (None, 33, 33, 512) 0 leaky_re_lu_3[0][0] __________________________________________________________________________________________________ conv2d_4 (Conv2D) (None, 30, 30, 1) 8193 zero_padding2d_1[0][0] ================================================================================================== Total params: 2,767,361 Trainable params: 2,765,569 Non-trainable params: 1,792 __________________________________________________________________________________________________ ###Markdown Load CNN-based models ###Code model_cnn = tf.keras.models.load_model('/content/drive/MyDrive/B.Tech Project/saved_models/dataset_1/baseline_mse_finetune_50-0.010.h5') model_incep = tf.keras.models.load_model('/content/drive/MyDrive/B.Tech Project/saved_models/dataset_1/incep_mse_finetune_20-0.00.h5') from tensorflow.keras.applications.inception_resnet_v2 import preprocess_input #Load weights inception = tf.keras.applications.InceptionResNetV2(weights='imagenet', include_top=True) # inception.load_weights('/content/drive/MyDrive/Btech_project/saved_models/inception_resnet_v2_weights_tf_dim_ordering_tf_kernels.h5') #Create embedding def create_inception_embedding(grayscaled_rgb): grayscaled_rgb_resized = [] for i in grayscaled_rgb: i = transform.resize(i, (299, 299, 3), mode='constant') grayscaled_rgb_resized.append(i) grayscaled_rgb_resized = np.array(grayscaled_rgb_resized) grayscaled_rgb_resized = preprocess_input(grayscaled_rgb_resized) embed = inception.predict(grayscaled_rgb_resized) return embed ###Output _____no_output_____ ###Markdown Calculate MSE, PSNR, SSIM ###Code mse_list=[] psnr_list=[] ssim_list=[] inference_times = [] for i, (inp , tar) in enumerate(test_dataset): print(i+1) # print(inp.shape, tar.shape) # de-normalise input to 0-100 output_cnn = model_cnn.predict((inp+1)*50) start = time.time() # de-normalise input to 0-255 embed_inp = create_inception_embedding(np.expand_dims(gray2rgb(np.squeeze((inp+1)*127.5)), axis=0)) # de-normalise input to 0-100 output_incep = model_incep.predict([(inp+1)*50,embed_inp]) end = time.time() inference_times.append(end-start) # for Lab image inp_l = tf.squeeze(inp[0]) tar_rgb = to_rgb(inp[0],tar[0]) pred_rgb_1 = to_rgb(inp[0],output_cnn[0]) pred_rgb_2 = to_rgb(inp[0],output_incep[0]) display_list = [inp_l, tar_rgb, pred_rgb_1, pred_rgb_2] metric_mse = tf.reduce_mean(tf.square(tar - output_incep)).numpy() metric_psnr = tf.image.psnr(tar, output_incep,max_val=2.0)[0].numpy() metric_ssim = tf.image.ssim(tar, output_incep, max_val=2.0)[0].numpy() mse_list.append(metric_mse) psnr_list.append(metric_psnr) ssim_list.append(metric_ssim) print('MSE:',metric_mse, 'PSNR:', metric_psnr, 'SSIM:', metric_ssim) # plt.figure(figsize=(15,15)) # title = ['Input Image', 'Ground Truth', 'CNN', 'Inception-resnetv2'] # for i in range(4): # plt.subplot(1, 4, i+1) # plt.title(title[i]) # # getting the pixel values between [0, 1] to plot it. # plt.imshow(display_list[i] * 0.5 + 0.5,cmap='gray') # plt.axis('off') # plt.show() avg_mse = np.mean(mse_list) avg_psnr = np.mean(psnr_list) avg_ssim = np.mean(ssim_list) print('Average values:') print('MSE:',avg_mse, 'PSNR:', avg_psnr, 'SSIM:', avg_ssim) print('Average inference time:',np.mean(inference_times)) mse_list=[] psnr_list=[] # ssim_list=[] inference_times = [] for i, (inp , tar) in enumerate(test_dataset): # print(i+1) # print(inp.shape, tar.shape) start = time.time() pred = generator2(inp, training=True) end = time.time() inference_times.append(end-start) # for Lab image inp_l = tf.squeeze(inp[0]) tar_rgb = tar[0] #to_rgb(inp[0],tar[0]) pred_rgb = pred[0] #to_rgb(inp[0],pred[0]) display_list = [inp_l, tar_rgb, pred_rgb] metric_mse = tf.reduce_mean(tf.square(tar - pred)).numpy() metric_psnr = tf.image.psnr(tar, pred,max_val=2.0)[0].numpy() metric_ssim = tf.image.ssim(tar, pred, max_val=2.0)[0].numpy() mse_list.append(metric_mse) psnr_list.append(metric_psnr) # ssim_list.append(metric_ssim) # print('MSE:',metric_mse, 'PSNR:', metric_psnr, 'SSIM:', metric_ssim) # plt.figure(figsize=(20,15)) # title = ['Input Image', 'Ground Truth', 'Predicted Image'] # for i in range(3): # plt.subplot(1, 3, i+1) # plt.title(title[i]) # # getting the pixel values between [0, 1] to plot it. # plt.imshow(display_list[i] * 0.5 + 0.5,cmap='gray') # plt.axis('off') # plt.show() avg_mse = np.mean(mse_list) avg_psnr = np.mean(psnr_list) # avg_ssim = np.mean(ssim_list) print('Average values:') print('MSE:',avg_mse, 'PSNR:', avg_psnr) print('Average inference time:',np.mean(inference_times)) ###Output _____no_output_____ ###Markdown sem7_testFor RGB images:(with spot) Densenet121 mse error: 0.0234 Average values: MSE: 0.0237 PSNR: 23.725 Average inference time: 0.103 MobilenetV2 mse error: 0.0291 Average values: MSE: 0.0289 PSNR: 22.59 Average inference time: 0.053For Lab images:- Average values: baseline CNN MSE: 0.012060764 PSNR: 26.443317 Average inference time: 0.056530563047809894- Average values: Inception-resnetv2 MSE: 0.012103569 PSNR: 26.630455 Average inference time: 0.15866528243372907- Average values: Mobilenetv2 MSE: 0.010663359 PSNR: 26.870356 Average inference time: 0.06132557899894768- Average values: Densenet121 MSE: 0.010835831 PSNR: 26.872643 Average inference time: 0.11661153956091791 ###Code 8fig = plt.figure(figsize=(15,30)) grid = ImageGrid(fig, 111, nrows_ncols=(8, 6), axes_pad=0.0, ) for i, (inp , tar) in enumerate(test_dataset.shuffle(500).take(48)): if(i%8==0 and i!=0): plt.show() fig = plt.figure(figsize=(15,30)) grid = ImageGrid(fig, 111, nrows_ncols=(8, 6), axes_pad=0.0, ) # mobilenet output pred_mob = generator(inp, training=False) # densenet output pred_dense = generator2(inp, training=False) # baseline CNN output, de-normalise input to 0-100 pred_cnn = model_cnn.predict((inp+1)*50) # de-normalise input to 0-255 embed_inp = create_inception_embedding(np.expand_dims(gray2rgb(np.squeeze((inp+1)*127.5)), axis=0)) # Inception-resnetv2 based CNN, de-normalise input to 0-100 pred_incep = model_incep.predict([(inp+1)*50,embed_inp]) # for Lab image inp_l = tf.squeeze(inp[0]) tar_rgb = to_rgb(inp[0],tar[0]) pred_mob = to_rgb(inp[0],pred_mob[0]) pred_dense = to_rgb(inp[0],pred_dense[0]) pred_cnn = to_rgb(inp[0],pred_cnn[0]) pred_incep = to_rgb(inp[0],pred_incep[0]) # Input image, Baseline CNN, Inception-resnetv2 based CNN, Pix2pix with mobilenetv2 encoder, Pix2pix with densenet121 encoder, Target image display_list = [inp_l, pred_cnn, pred_incep, pred_mob, pred_dense, tar_rgb] for j in range(6): grid[(i%8)*6 + j].imshow(display_list[j] * 0.5 + 0.5,cmap='gray') grid[(i%8)*6 + j].axis('off') ###Output _____no_output_____
example/glow.ipynb
###Markdown Glow ###Code # Import required packages import torch import torchvision as tv import numpy as np import normflow as nf from matplotlib import pyplot as plt from tqdm import tqdm # Set up model # Define flows L = 3 K = 16 torch.manual_seed(0) input_shape = (3, 32, 32) channels = 3 hidden_channels = 256 split_mode = 'channel' scale = True num_classes = 10 # Set up flows, distributions and merge operations q0 = [] merges = [] flows = [] for i in range(L): flows_ = [] for j in range(K): flows_ += [nf.flows.GlowBlock(channels * 2 ** (L + 1 - i), hidden_channels, split_mode=split_mode, scale=scale)] flows_ += [nf.flows.Squeeze()] flows += [flows_] latent_shape = (input_shape[0] * 2 ** (L - i), input_shape[1] // 2 ** (L - i), input_shape[2] // 2 ** (L - i)) if i > 0: merges += [nf.flows.Merge()] latent_shape = (input_shape[0] * 2 ** (L - i), input_shape[1] // 2 ** (L - i), input_shape[2] // 2 ** (L - i)) else: latent_shape = (input_shape[0] * 2 ** (L + 1), input_shape[1] // 2 ** L, input_shape[2] // 2 ** L) q0 += [nf.distributions.ClassCondDiagGaussian(latent_shape, num_classes)] # Construct flow model model = nf.MultiscaleFlow(q0, flows, merges) # Move model on GPU if available enable_cuda = True device = torch.device('cuda' if torch.cuda.is_available() and enable_cuda else 'cpu') model = model.to(device) model = model.double() # Prepare training data batch_size = 128 logit = nf.utils.Logit(alpha=0.05) transform = tv.transforms.Compose([tv.transforms.ToTensor(), nf.utils.Jitter(), logit, nf.utils.ToDevice(device)]) train_data = tv.datasets.CIFAR10('/scratch2/vs488/flow/lars/datasets/', train=True, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, drop_last=True) test_data = tv.datasets.CIFAR10('/scratch2/vs488/flow/lars/datasets/', train=False, download=True, transform=transform) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size) train_iter = iter(train_loader) # Train model max_iter = 2000 loss_hist = np.array([]) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5) for i in tqdm(range(max_iter)): try: x, y = next(train_iter) except StopIteration: train_iter = iter(train_loader) x, y = next(train_iter) optimizer.zero_grad() loss = model.forward_kld(x, y.to(device)) if ~(torch.isnan(loss) | torch.isinf(loss)): loss.backward() optimizer.step() loss_hist = np.append(loss_hist, loss.detach().to('cpu').numpy()) del(x, y, loss) plt.figure(figsize=(10, 10)) plt.plot(loss_hist, label='loss') plt.legend() plt.show() # Model samples num_sample = 10 with torch.no_grad(): y = torch.arange(num_classes).repeat(num_sample).to(device) x, _ = model.sample(y=y) x_ = torch.clamp(logit.inverse(x).detach().cpu(), 0, 1) plt.figure(figsize=(10, 10)) plt.imshow(np.transpose(tv.utils.make_grid(x_, nrow=num_classes).numpy(), (1, 2, 0))) plt.show() del(x, y, x_) torch.cuda.empty_cache() nf.utils.bitsPerDimDataset(model, test_loader) ###Output _____no_output_____ ###Markdown Glow ###Code # Import required packages import torch import torchvision as tv import numpy as np import normflow as nf from matplotlib import pyplot as plt from tqdm import tqdm # Set up model # Define flows L = 3 K = 16 torch.manual_seed(0) input_shape = (3, 32, 32) n_dims = np.prod(input_shape) channels = 3 hidden_channels = 256 split_mode = 'channel' scale = True num_classes = 10 # Set up flows, distributions and merge operations q0 = [] merges = [] flows = [] for i in range(L): flows_ = [] for j in range(K): flows_ += [nf.flows.GlowBlock(channels * 2 ** (L + 1 - i), hidden_channels, split_mode=split_mode, scale=scale)] flows_ += [nf.flows.Squeeze()] flows += [flows_] latent_shape = (input_shape[0] * 2 ** (L - i), input_shape[1] // 2 ** (L - i), input_shape[2] // 2 ** (L - i)) if i > 0: merges += [nf.flows.Merge()] latent_shape = (input_shape[0] * 2 ** (L - i), input_shape[1] // 2 ** (L - i), input_shape[2] // 2 ** (L - i)) else: latent_shape = (input_shape[0] * 2 ** (L + 1), input_shape[1] // 2 ** L, input_shape[2] // 2 ** L) q0 += [nf.distributions.ClassCondDiagGaussian(latent_shape, num_classes)] # Construct flow model model = nf.MultiscaleFlow(q0, flows, merges) # Move model on GPU if available enable_cuda = True device = torch.device('cuda' if torch.cuda.is_available() and enable_cuda else 'cpu') model = model.to(device) # Prepare training data batch_size = 128 transform = tv.transforms.Compose([tv.transforms.ToTensor(), nf.utils.Scale(255. / 256.), nf.utils.Jitter(1 / 256.)]) train_data = tv.datasets.CIFAR10('datasets/', train=True, download=True, transform=transform) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, drop_last=True) test_data = tv.datasets.CIFAR10('datasets/', train=False, download=True, transform=transform) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size) train_iter = iter(train_loader) # Train model max_iter = 2000 loss_hist = np.array([]) optimizer = torch.optim.Adamax(model.parameters(), lr=1e-3, weight_decay=1e-5) for i in tqdm(range(max_iter)): try: x, y = next(train_iter) except StopIteration: train_iter = iter(train_loader) x, y = next(train_iter) optimizer.zero_grad() loss = model.forward_kld(x.to(device), y.to(device)) if ~(torch.isnan(loss) | torch.isinf(loss)): loss.backward() optimizer.step() loss_hist = np.append(loss_hist, loss.detach().to('cpu').numpy()) del(x, y, loss) plt.figure(figsize=(10, 10)) plt.plot(loss_hist, label='loss') plt.legend() plt.show() # Model samples num_sample = 10 with torch.no_grad(): y = torch.arange(num_classes).repeat(num_sample).to(device) x, _ = model.sample(y=y) x_ = torch.clamp(x, 0, 1) plt.figure(figsize=(10, 10)) plt.imshow(np.transpose(tv.utils.make_grid(x_, nrow=num_classes).cpu().numpy(), (1, 2, 0))) plt.show() del(x, y, x_) # Get bits per dim n = 0 bpd_cum = 0 with torch.no_grad(): for x, y in iter(test_loader): nll = model(x.to(device), y.to(device)) nll_np = nll.cpu().numpy() bpd_cum += np.nansum(nll_np / np.log(2) / n_dims + 8) n += len(x) - np.sum(np.isnan(nll_np)) print('Bits per dim: ', bpd_cum / n) ###Output _____no_output_____
03_finite_differences.ipynb
###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code %matplotlib inline from __future__ import print_function import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite DifferencesFinite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne way to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$Derive the approximation centered at $x_0$ from this polynomial. Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1})$ and $(x_{n-1}, u(x_{n-1})$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} f'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common derivatives $u^{(k)}(x_n)$ together we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 1 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 \end{aligned}$$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 20 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) for i in range(N - 1): f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation # f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$\begin{aligned} u''(x_n) + R(x_n) &= \quad A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) \\ &\quad+ B u(x_n) \\ &\quad+ C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )\end{aligned}$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 0 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1\end{aligned}$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$\begin{aligned} u''(x_n) + R(x_n) &= \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} \\&\quad+ \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)\end{aligned}$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if} \quad i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0]))) print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])) * 12) ###Output _____no_output_____ ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$\begin{aligned} P_N'(x) &= [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)]+ \cdots \\ &\quad + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]\end{aligned}$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____ ###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code from __future__ import print_function %matplotlib inline import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite DifferencesFinite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne way to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$Derive the approximation centered at $x_0$ from this polynomial. Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1}))$ and $(x_{n-1}, u(x_{n-1}))$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common derivatives $u^{(k)}(x_n)$ together we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 1 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 \end{aligned}$$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 20 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] print("%s = %s" % (delta_x, (x_hat[-1] - x_hat[0]) / (N - 1))) # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) for i in range(N - 1): f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation # f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) axes.set_xlabel("x") axes.set_ylabel(r"$f'(x)$") plt.show() ###Output _____no_output_____ ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$\begin{aligned} u''(x_n) + R(x_n) &= \quad A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) \\ &\quad+ B u(x_n) \\ &\quad+ C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )\end{aligned}$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 0 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1\end{aligned}$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$\begin{aligned} u''(x_n) + R(x_n) &= \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} \\&\quad+ \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)\end{aligned}$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if} \quad i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0]))) print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])) * 12) ###Output _____no_output_____ ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$\begin{aligned} P_N'(x) &= [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)]+ \cdots \\ &\quad + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]\end{aligned}$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____ ###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code %matplotlib inline import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite Differences Finite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne was to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$ Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1})$ and $(x_{n-1}, u(x_{n-1})$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} f'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common $\Delta x^n$ we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\Delta x^0: ~~~~ A + B + C = 0$$$$\Delta x^1: ~~~~ A \Delta x - C \Delta x = 1 $$$$\Delta x^2: ~~~~ A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 $$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 20 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) for i in xrange(N - 1): f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation # f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$u''(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\Delta x^0: ~~~~ A + B + C = 0$$$$\Delta x^1: ~~~~ A \Delta x - C \Delta x = 0$$$$\Delta x^2: ~~~~ A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$u''(x_n) + R(x_n) = \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} + \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if}~i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0])) print finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0])) print finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0])) ###Output _____no_output_____ ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$P_N'(x) = [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)] + \cdots + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + 0.5 * delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____ ###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code from __future__ import print_function %matplotlib inline import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite DifferencesFinite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne way to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$Derive the approximation centered at $x_0$ from this polynomial. Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1}))$ and $(x_{n-1}, u(x_{n-1}))$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} f'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common derivatives $u^{(k)}(x_n)$ together we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 1 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 \end{aligned}$$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] print("%s = %s" % (delta_x, (x_hat[-1] - x_hat[0]) / (N - 1))) # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) # for i in range(N - 1): # f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x # f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) axes.set_xlabel("x") axes.set_ylabel(r"$f'(x)$") plt.show() ###Output 1.3962634015954638 = 1.3962634015954636 ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$\begin{aligned} u''(x_n) + R(x_n) &= \quad A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) \\ &\quad+ B u(x_n) \\ &\quad+ C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )\end{aligned}$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 0 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1\end{aligned}$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$\begin{aligned} u''(x_n) + R(x_n) &= \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} \\&\quad+ \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)\end{aligned}$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 100 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if} \quad i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0]))) print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])) * 12) ###Output [ 1. -2. 1.] [-0.5 0. 0.5] [-2.08333333 4. -3. 1.33333333 -0.25 ] [ 10. -15. -4. 14. -6. 1.] ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$\begin{aligned} P_N'(x) &= [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)]+ \cdots \\ &\quad + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]\end{aligned}$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____ ###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code %matplotlib inline import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite Differences Finite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne was to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$ Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1})$ and $(x_{n-1}, u(x_{n-1})$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} f'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common $\Delta x^n$ we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\Delta x^0: ~~~~ A + B + C = 0$$$$\Delta x^1: ~~~~ A \Delta x - C \Delta x = 1 $$$$\Delta x^2: ~~~~ A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 $$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 20 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) for i in xrange(N - 1): f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation # f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$u''(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\Delta x^0: ~~~~ A + B + C = 0$$$$\Delta x^1: ~~~~ A \Delta x - C \Delta x = 0$$$$\Delta x^2: ~~~~ A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$u''(x_n) + R(x_n) = \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} + \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if}~i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0])) print finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0])) print finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0])) ###Output _____no_output_____ ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$P_N'(x) = [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)] + \cdots + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in xrange(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____ ###Markdown Text provided under a Creative Commons Attribution license, CC-BY. All code is made available under the FSF-approved MIT license. (c) Kyle T. Mandli ###Code from __future__ import print_function %matplotlib inline import numpy import matplotlib.pyplot as plt ###Output _____no_output_____ ###Markdown Review: Finite DifferencesFinite differences are expressions that approximate derivatives of a function evaluated at a set of points, often called a *stencil*. These expressions can come in many different flavors including types of stencils, order of accuracy, and order of derivatives. In this lecture we will review the process of derivation, error analysis and application of finite differences. Derivation of Finite DifferencesThe general approach to deriving finite differences should be familiar for at least the first order differences. Consider three different ways to define a derivative at a point $x_i$$$ u'(x_i) = \lim_{\Delta x \rightarrow 0} \left \{ \begin{aligned} &\frac{u(x_i + \Delta x) - u(x_i)}{\Delta x} & \equiv D_+ u(x_i)\\ &\frac{u(x_i + \Delta x) - u(x_i - \Delta_x)}{2 \Delta x} & \equiv D_0 u(x_i)\\ &\frac{u(x_i) - u(x_i - \Delta_x)}{\Delta x} & \equiv D_- u(x_i). \end{aligned} \right .$$![Approximations to $u'(x)$](./images/fd_basic.png) If instead of allowing $\Delta x \rightarrow 0$ we come up with an approximation to the slope $u'(x_i)$ and hence our definitions of derivatives can directly be seen as approximations to derivatives when $\Delta x$ is perhaps small but non-zero.For the rest of the review we will delve into a more systematic way to derive these approximations as well as find higher order accurate approximations, higher order derivative approximations, and understand the error associated with the approximations. Interpolating PolynomialsOne way to derive finite difference approximations is by finding an interpolating polynomial through the given stencil and differentiating that directly. Given $N+1$ points $(x_0,u(x_0)), (x_1,u(x_1)), \ldots, (x_{N},u(x_{N}))$ assuming the $x_i$ are all unique, the interpolating polynomial $P_N(x)$ can be written as$$ P_N(x) = \sum^{N}_{i=0} u(x_i) \ell_i(x)$$where $$ \ell_i(x) = \prod^{N}_{j=0, j \neq i} \frac{x - x_j}{x_i - x_j} = \frac{x - x_0}{x_i - x_0} \frac{x - x_1}{x_i - x_1} \cdots \frac{x - x_{i-1}}{x_i - x_{i-1}}\frac{x - x_{i+1}}{x_i - x_{i+1}} \cdots \frac{x - x_{N}}{x_i - x_{N}}$$ Note that $\ell_i(x_i) = 1$ and $\forall j\neq i, ~~ \ell_i(x_j) = 0$. Since we know how to differentiate a polynomial we should be able to then compute the given finite difference approximation given these data points. Example: 2-Point StencilSay we have two points to form the approximation to the derivative with. The interpolating polynomial through two points is a linear function with the form$$ P_1(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} + u(x_1) \frac{x - x_0}{x_1 - x_0}.$$Derive the approximation centered at $x_0$ from this polynomial. Differentiating $P_1(x)$ leads to$$ P'_1(x) = u(x_0) \frac{1}{x_0 - x_1} + u(x_1) \frac{1}{x_1 - x_0}.$$ If we allow the spacing between $x_0$ and $x_1$ to be $\Delta x = x_1 - x_0$ we can then write this as$$ P'_1(x) = \frac{u(x_1) - u(x_0)}{\Delta x}$$which is the general form of $D_-u(x)$ and $D_+u(x)$ above. If we extend this to have three points we have the interpolating polynomial$$ P_2(x) = u(x_0) \frac{x - x_1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + u(x_1) \frac{x - x_0}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + u(x_2) \frac{x - x_0}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1}.$$ Differentiating this leads to$$\begin{aligned} P'_2(x) &= u(x_0) \left( \frac{1}{x_0 - x_1} \frac{x - x_2}{x_0 - x_2} + \frac{x - x_1}{x_0 - x_1} \frac{1}{x_0 - x_2}\right )+ u(x_1) \left ( \frac{1}{x_1 - x_0} \frac{x - x_2}{x_1 - x_2} + \frac{x - x_0}{x_1 - x_0} \frac{1}{x_1 - x_2} \right )+ u(x_2)\left ( \frac{1}{x_2 - x_0} \frac{x - x_1}{x_2 - x_1} + \frac{x - x_0}{x_2 - x_0} \frac{1}{x_2 - x_1} \right ) \\ &= u(x_0) \left(\frac{x - x_2}{2 \Delta x^2} + \frac{x - x_1}{2 \Delta x^2} \right )+ u(x_1) \left ( \frac{x - x_2}{-\Delta x^2} + \frac{x - x_0}{-\Delta x^2} \right )+ u(x_2)\left ( \frac{x - x_1}{2\Delta x^2} + \frac{x - x_0}{2 \Delta x^2} \right ) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0) \\ &=\frac{u(x_0)}{2\Delta x^2} (2x - x_2 - x_1)+ \frac{u(x_1)}{-\Delta x^2} ( 2x - x_2 - x_0)+ \frac{u(x_2)}{2\Delta x^2}( 2x - x_1 - x_0).\end{aligned}$$ If we now evaluate the derivative at $x_1$, assuming this is the central point, we have$$\begin{aligned} P'_2(x_1) &= \frac{u(x_0)}{2\Delta x^2} (x_1 - x_2)+ \frac{u(x_1)}{-\Delta x^2} ( x_1 - x_2 + x_1 - x_0)+ \frac{u(x_2)}{\Delta x^2}( x_1 - x_0) \\ &= \frac{u(x_0)}{2\Delta x^2} (-\Delta x)+ \frac{u(x_1)}{-\Delta x^2} ( -\Delta x + \Delta x)+ \frac{u(x_2)}{\Delta x^2}( 2\Delta x) \\ &= \frac{u(x_2) - u(x_0)}{2 \Delta x}\end{aligned}$$giving us the third approximation from above. Taylor-Series MethodsAnother way to derive finite difference approximations can be computed by using the Taylor series and the method of undetermined coefficients.$$u(x) = u(x_n) + (x - x_n) u'(x_n) + \frac{(x - x_n)^2}{2!} u''(x_n) + \frac{(x - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x - x_n)^4)$$ Say we want to derive the second order accurate, first derivative approximation that just did, this requires the values $(x_{n+1}, u(x_{n+1}))$ and $(x_{n-1}, u(x_{n-1}))$. We can express these values via our Taylor series approximation above as$$\begin{aligned} u(x_{n+1}) &= u(x_n) + (x_{n+1} - x_n) u'(x_n) + \frac{(x_{n+1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n+1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n+1} - x_n)^4) \\ &= u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ and $$\begin{aligned} u(x_{n-1}) &= u(x_n) + (x_{n-1} - x_n) u'(x_n) + \frac{(x_{n-1} - x_n)^2}{2!} u''(x_n) + \frac{(x_{n-1} - x_n)^3}{3!} u'''(x_n) + \mathcal{O}((x_{n-1} - x_n)^4) \\&= u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} f'''(x_n) + \mathcal{O}(\Delta x^4) \end{aligned}$$ Now to find out how to combine these into an expression for the derivative we assume our approximation looks like$$u'(x_n) + R(x_n) = A u(x_{n+1}) + B u(x_n) + C u(x_{n-1})$$where $R(x_n)$ is our error. Plugging in the Taylor series approximations we find$$u'(x_n) + R(x_n) = A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4)\right ) + B u(x_n) + C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) \right )$$ Since we want $R(x_n) = \mathcal{O}(\Delta x^2)$ we want all terms lower than this to disappear except for those multiplying $u'(x_n)$ as those should sum to 1 to give us our approximation. Collecting the terms with common derivatives $u^{(k)}(x_n)$ together we get a series of expressions for the coefficients $A$, $B$, and $C$ based on the fact we want an approximation to $u'(x_n)$. The $n=0$ terms collected are $A + B + C$ and are set to 0 as we want the $u(x_n)$ term to disappear$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 1 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 0 \end{aligned}$$ This last equation $\Rightarrow A = -C$, using this in the second equation gives $A = \frac{1}{2 \Delta x}$ and $C = -\frac{1}{2 \Delta x}$. The first equation then leads to $B = 0$. Putting this altogether then gives us our previous expression including an estimate for the error:$$u'(x_n) + R(x_n) = \frac{u(x_{n+1}) - u(x_{n-1})}{2 \Delta x} + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) + \frac{1}{2 \Delta x} \frac{\Delta x^3}{3!} u'''(x_n) + \mathcal{O}(\Delta x^4) $$$$R(x_n) = \frac{\Delta x^2}{3!} u'''(x_n) + \mathcal{O}(\Delta x^3) = \mathcal{O}(\Delta x^2)$$ Example: First Order Derivatives ###Code f = lambda x: numpy.sin(x) f_prime = lambda x: numpy.cos(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 20 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] print("%s = %s" % (delta_x, (x_hat[-1] - x_hat[0]) / (N - 1))) # Compute forward difference using a loop f_prime_hat = numpy.empty(x_hat.shape) for i in range(N - 1): f_prime_hat[i] = (f(x_hat[i+1]) - f(x_hat[i])) / delta_x f_prime_hat[-1] = (f(x_hat[i]) - f(x_hat[i-1])) / delta_x # Vector based calculation # f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x # Backward Difference at x_N fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_prime(x), 'k') axes.plot(x_hat + 0.5 * delta_x, f_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) axes.set_xlabel("x") axes.set_ylabel(r"$f'(x)$") plt.show() ###Output _____no_output_____ ###Markdown Example: Second Order DerivativeUsing our Taylor series approach lets derive the second order accurate second derivative formula. Again we will use the same points and the Taylor series centered at $x = x_n$ so we end up with the same expression as before:$$\begin{aligned} u''(x_n) + R(x_n) &= \quad A \left ( u(x_n) + \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) + \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5)\right ) \\ &\quad+ B u(x_n) \\ &\quad+ C \left ( u(x_n) - \Delta x u'(x_n) + \frac{\Delta x^2}{2!} u''(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) + \mathcal{O}(\Delta x^5) \right )\end{aligned}$$except this time we want to leave $u''(x_n)$ on the right hand side. Doing the same trick as before we have the following expressions:$$\begin{aligned} u(x_n): & \quad A + B + C = 0 \\ u'(x_n): & \quad A \Delta x - C \Delta x = 0 \\ u''(x_n): & \quad A \frac{\Delta x^2}{2} + C \frac{\Delta x^2}{2} = 1\end{aligned}$$ The second equation implies $A = C$ which combined with the third implies$$A = C = \frac{1}{\Delta x^2}$$Finally the first equation gives$$B = -\frac{2}{\Delta x^2}$$leading to the final expression$$\begin{aligned} u''(x_n) + R(x_n) &= \frac{u(x_{n+1}) - 2 u(x_n) + u(x_{n-1})}{\Delta x^2} \\&\quad+ \frac{1}{\Delta x^2} \left(\frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) - \frac{\Delta x^3}{3!} u'''(x_n) + \frac{\Delta x^4}{4!} u^{(4)}(x_n) \right) + \mathcal{O}(\Delta x^5)\end{aligned}$$with$$R(x_n) = \frac{\Delta x^2}{12} u^{(4)}(x_n) + \mathcal{O}(\Delta x^3)$$ ###Code f = lambda x: numpy.sin(x) f_dubl_prime = lambda x: -numpy.sin(x) # Use uniform discretization x = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, 1000) N = 10 x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x = x_hat[1] - x_hat[0] # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x**2) # Use first-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x**2 fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.plot(x, f_dubl_prime(x), 'k') axes.plot(x_hat, f_dubl_prime_hat, 'ro') axes.set_xlim((x[0], x[-1])) axes.set_ylim((-1.1, 1.1)) plt.show() ###Output _____no_output_____ ###Markdown General DerivationFor a general finite difference approximation located at $\bar{x}$ to the $k$th derivative with the arbitrary stencil $N \geq k + 1$ points $x_1, \ldots, x_N$ we can use some generalizations of the above method. Note that although it is common that $\bar{x}$ is one of the stencil points this is not necessary. We also assume that $u(x)$ is sufficiently smooth so that our Taylor series are valid. At each stencil point we have the approximation$$ u(x_i) = u(\bar{x}) + (x_i - \bar{x})u'(\bar{x}) + \cdots + \frac{1}{k!}(x_i - \bar{x})^k u^{(k)}(\bar{x}) + \cdots.$$ Following our methodology above we want to find the linear combination of these Taylor series expansions such that$$ u^{(k)}(\bar{x}) + \mathcal{O}(\Delta x^p) = a_1 u(x_1) + a_2 u(x_2) + a_3 u(x_3) + \cdots + a_n u(x_n).$$Note that $\Delta x$ can vary in general and the asymptotic behavior of the method will be characterized by some sort of average distance or sometimes the maximum distance between the stencil points. Generalizing the approach above with the method of undetermined coefficients we want to eliminate the pieces of the above approximation that are in front of the derivatives less than order $k$. The condition for this is$$ \frac{1}{(i - 1)!} \sum^N_{j=1} a_j (x_j - \bar{x})^{(i-1)} = \left \{ \begin{aligned} 1 & & \text{if} \quad i - 1 = k, \\ 0 & & \text{otherwise} \end{aligned} \right .$$for $i=1, \ldots, N$. Assuming the $x_j$ are distinct we can write the system of equations in a Vandermonde system which will have a unique solution. ###Code import scipy.special def finite_difference(k, x_bar, x): """Compute the finite difference stencil for the kth derivative""" N = x.shape[0] A = numpy.ones((N, N)) x_row = x - x_bar for i in range(1, N): A[i, :] = x_row ** i / scipy.special.factorial(i) b = numpy.zeros(N) b[k] = 1.0 c = numpy.linalg.solve(A, b) return c print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, 0.0, numpy.asarray([-1.0, 0.0, 1.0]))) print(finite_difference(1, -2.0, numpy.asarray([-2.0, -1.0, 0.0, 1.0, 2.0]))) print(finite_difference(2, 0.0, numpy.asarray([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0])) * 12) ###Output _____no_output_____ ###Markdown Error Analysis Polynomial ViewGiven $N + 1$ points we can form an interpolant $P_N(x)$ of degree $N$ where$$u(x) = P_N(x) + R_N(x)$$ We know from Lagrange's Theorem that the remainder term looks like$$R_N(x) = (x - x_0)(x - x_1)\cdots (x - x_{N})(x - x_{N+1}) \frac{u^{(N+1)}(c)}{(N+1)!}$$noting that we need to require that $u(x) \in C^{N+1}$ on the interval of interest. Taking the derivative of the interpolant $P_N(x)$ (in terms of Newton polynomials) then leads to $$\begin{aligned} P_N'(x) &= [u(x_0), u(x_1)] + ((x - x_1) + (x - x_0)) [u(x_0), u(x_1), u(x_2)]+ \cdots \\ &\quad + \left(\sum^{N-1}_{i=0}\left( \prod^{N-1}_{j=0,~j\neq i} (x - x_j) \right )\right ) [u(x_0), u(x_1), \ldots, u(x_N)]\end{aligned}$$ Similarly we can find the derivative of the remainder term $R_N(x)$ as$$R_N'(x) = \left(\sum^{N}_{i=0} \left( \prod^{N}_{j=0,~j\neq i} (x - x_j) \right )\right ) \frac{u^{(N+1)}(c)}{(N+1)!}$$ Now if we consider the approximation of the derivative evaluated at one of our data points $(x_k, y_k)$ these expressions simplify such that$$u'(x_k) = P_N'(x_k) + R_N'(x_k)$$ If we let $\Delta x = \max_i |x_k - x_i|$ we then know that the remainder term will be $\mathcal{O}(\Delta x^N)$ as $\Delta x \rightarrow 0$ thus showing that this approach converges and we can find arbitrarily high order approximations. Truncation ErrorIf we are using a Taylor series approach we can also look at the dominate term left over from in the Taylor series to find the *truncation error*.As an example lets again consider the first derivative approximations above, we need the Taylor expansions$$ u(\bar{x} + \Delta x) = u(\bar{x}) + \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)$$and$$ u(\bar{x} - \Delta x) = u(\bar{x}) - \Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) - \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Plugging these into our expressions we have$$\begin{aligned} D_+ u(\bar{x}) &= \frac{u(\bar{x} + \Delta x) - u(\bar{x})}{\Delta x} \\ &= \frac{\Delta x u'(\bar{x}) + \frac{1}{2} \Delta x^2 u''(\bar{x}) + \frac{1}{3!} \Delta x^3 u'''(\bar{x}) + \mathcal{O}(\Delta x^4)}{\Delta x} \\ &= u'(\bar{x}) + \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3).\end{aligned}$$ If we now difference $D_+ u(\bar{x}) - u'(\bar{x})$ we get the truncation error$$ \frac{1}{2} \Delta x u''(\bar{x}) + \frac{1}{3!} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^3)$$so the error for $D_+$ goes as $\mathcal{O}(\Delta x)$ and is controlled by $u''(\bar{x})$. Note that this approximation is dependent on $\Delta x$ as the derivatives evaluated at $\bar{x}$ are constants. Similarly for the centered approximation we have$$ D_0 u(\bar{x}) - u'(\bar{x}) = \frac{1}{6} \Delta x^2 u'''(\bar{x}) + \mathcal{O}(\Delta x^4).$$ Computing Order of Accuracy GraphicallyModel the error as$$\begin{aligned} e(\Delta x) &= C \Delta x^n \\ \log e(\Delta x) &= \log C + n \log \Delta x\end{aligned}$$Slope of line is $n$ when computing this! We can also match the first point by solving for $C$:$$C = e^{\log e(\Delta x) - n \log \Delta x}$$ ###Code f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute forward difference f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[:-1] = (f(x_hat[1:]) - f(x_hat[:-1])) / (delta_x[-1]) # Use first-order differences for points at edge of domain f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Backward Difference at x_N error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat + delta_x[-1]) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, 'ko', label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'r--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'b--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 1st Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_prime = lambda x: numpy.cos(x) + 2.0 * x + 9.0 * x**2 # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N + 1) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_prime_hat = numpy.empty(x_hat.shape) f_prime_hat[1:-1] = (f(x_hat[2:]) - f(x_hat[:-2])) / (2 * delta_x[-1]) # Use first-order differences for points at edge of domain # f_prime_hat[0] = (f(x_hat[1]) - f(x_hat[0])) / delta_x[-1] # f_prime_hat[-1] = (f(x_hat[-1]) - f(x_hat[-2])) / delta_x[-1] # Use second-order differences for points at edge of domain f_prime_hat[0] = (-3.0 * f(x_hat[0]) + 4.0 * f(x_hat[1]) + - f(x_hat[2])) / (2.0 * delta_x[-1]) f_prime_hat[-1] = ( 3.0 * f(x_hat[-1]) + -4.0 * f(x_hat[-2]) + f(x_hat[-3])) / (2.0 * delta_x[-1]) error.append(numpy.linalg.norm(numpy.abs(f_prime(x_hat) - f_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) axes.loglog(delta_x, error, "ro", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[0], error[0], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[0], error[0], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) axes.set_title("Convergence of 2nd Order Differences") axes.set_xlabel("$\Delta x$") axes.set_ylabel("$|f'(x) - \hat{f}'(x)|$") plt.show() f = lambda x: numpy.sin(x) + x**2 + 3.0 * x**3 f_dubl_prime = lambda x: -numpy.sin(x) + 2.0 + 18.0 * x # Compute the error as a function of delta_x delta_x = [] error = [] # for N in xrange(2, 101): for N in range(50, 1000, 50): x_hat = numpy.linspace(-2 * numpy.pi, 2 * numpy.pi, N) delta_x.append(x_hat[1] - x_hat[0]) # Compute derivative f_dubl_prime_hat = numpy.empty(x_hat.shape) f_dubl_prime_hat[1:-1] = (f(x_hat[2:]) -2.0 * f(x_hat[1:-1]) + f(x_hat[:-2])) / (delta_x[-1]**2) # Use second-order differences for points at edge of domain f_dubl_prime_hat[0] = (2.0 * f(x_hat[0]) - 5.0 * f(x_hat[1]) + 4.0 * f(x_hat[2]) - f(x_hat[3])) / delta_x[-1]**2 f_dubl_prime_hat[-1] = (2.0 * f(x_hat[-1]) - 5.0 * f(x_hat[-2]) + 4.0 * f(x_hat[-3]) - f(x_hat[-4])) / delta_x[-1]**2 error.append(numpy.linalg.norm(numpy.abs(f_dubl_prime(x_hat) - f_dubl_prime_hat), ord=numpy.infty)) error = numpy.array(error) delta_x = numpy.array(delta_x) fig = plt.figure() axes = fig.add_subplot(1, 1, 1) # axes.plot(delta_x, error) axes.loglog(delta_x, error, "ko", label="Approx. Derivative") order_C = lambda delta_x, error, order: numpy.exp(numpy.log(error) - order * numpy.log(delta_x)) axes.loglog(delta_x, order_C(delta_x[2], error[2], 1.0) * delta_x**1.0, 'b--', label="1st Order") axes.loglog(delta_x, order_C(delta_x[2], error[2], 2.0) * delta_x**2.0, 'r--', label="2nd Order") axes.legend(loc=4) plt.show() ###Output _____no_output_____
week4_EDA_np_pd_json_apis_regex/day5_matplotlib_I_api/theory/apis/api_no_token.ipynb
###Markdown _El maravilloso mundo de las_ **APIs** o EL RETORNO DE JSON API: Interfaz de Programación de AplicacionesConjunto de definiciones y protocolos que se utiliza para desarrollar e integrar el software de las aplicaciones, permitiendo la comunicación entre dos aplicaciones de software a través de un conjunto de reglas. Listado de **APIs** for free: https://github.com/public-apis/public-apis ###Code import json import requests import pandas as pd from pandas.io.json import json_normalize #para jsns en pandas url_s = "https://favqs.com/" #accedemos a una api (citas de gente famosa) endpoint = "api/qotd" url_w = url_s + endpoint requests.get(url_w) #justo hoy no funciona la pagina qotd = requests.get(url_w).json() qotd qotd["quote"] cita = qotd["quote"] fecha = qotd["qotd_date"][:10] autor = cita["author"] cita_texto = cita["body"] print("La frase del día", fecha, "es de", autor, "y es la siguiente:\n\n" + cita_texto) json_normalize(qotd) ###Output _____no_output_____ ###Markdown API sin token **¿Qué es importante cuando tratamos con APIs?**Leer la documentación porque, si no lo hacemos, no sabemos cómo usarla. https://pokeapi.cohttps://pokeapi.co/docs/v2 ------------------ Objetivo: Tener todos los nombres de s junto con su url----------------- ###Code #para acceder a algunas apis tienes que tener un cliente y un usuario. client y api_key # No todas las APIs devuelven todos los posibles valores debido a limitación de recursos url = "https://pokeapi.co/api/v2/" #si pones esto con el api te trae informacion de x ->https://pokeapi.co/api/v2/?offset=20&limit=20 <- nos estan trayendo los 20 primeros ->next': 'https://pokeapi.co/api/v2/?offset=20&limit=20' next es la clave y dice para poder acceder los siguiente 20 en esta url. podemos cambiar el limite si no ponemos nada son 20 si ponemos 1000 pues mil. offset es desde donde queremos empezar a obtener los datos #el get es para obtener la informacion 'previous poke_json = requests.get(url).json() poke_json json_normalize(poke_json) #nos ha transformado lapeticion en un data frame poke_json["next"] #accedo al valor de la clave next en este caso empezamos desde el 20 20 -> la ? indica desde dond emepiezan los metadatos (parametros) #'https://pokeapi.co/api/v2/?offset=20&limit=20' esta url es la siguiente answer = requests.get(poke_json["next"]).json() answer #esto nos esta enseñando los siguiente 20 # Cogemos 77 s new_url='https://pokeapi.co/api/v2/?offset=0&limit=77' answer = requests.get(new_url).json() answer #si quiero traer todos los s, puedo poner un limite muy alto para traer todo 'next': 'https://pokeapi.co/api/v2/?offset=77&limit=77', te tendria que salir el next como none todos_url='https://pokeapi.co/api/v2/?offset=0&limit=99999' answer=requests.get(todos_url).json() answer df_s = pd.DataFrame(answer) df_s #hay un diccionario dentro del dataframe df2 = pd.DataFrame(answer["results"]) #accedemos a la columna results y ponlo en dataframe df2 #asi accedemos a ese diccionario dentro de un diccionario l1 = [2, 4] l2 = ["a", "b"] l1.extend(l2) #extendemos una lista con otra lista l1 poke_json #es la url que teniamos caudno haciamos la primera llamada a la api = [] # para contener todos los resultados de la api c poke_dict = {"name":"url"} #queremos poner las url de cada con su nombre clave nombre con su nombre y otra clave "url" con la direccion .extend(poke_json["results"]) #extend ampliar resultados de la lista %%time #mide el timepo que tarda en ejecutarse esta celda _api_url = "https://pokeapi.co/api/v2/" #trae de 20 en 20 poke_json = requests.get(_api_url).json()#hacemos la peticion de obtener la info = [] #creamos un diccionario varcio # Almacenamos 40 s realizando peticiones hasta que la lista de s tenga 40 o más s while len() < 40: #while len() < 1118: .extend(poke_json["results"]) #extendemos los resultados en la lista next_url = poke_json["next"]#usando la url de next que hemos visto antes poke_json = requests.get(next_url).json() #volver a llamar pero con next_url a los siguientes 20 print(len()) #como vemos es una lista del diccionario de los nombres y url %%time #viendo el tiempo, es mucho mejor trayendo todo de golpe en vez de realizar muchas llamadas a la api _api_url = "https://pokeapi.co/api/v2/" poke_json = requests.get(_api_url).json() = [] import time while poke_json["next"] != None: #mientras esa nueva petiicon que le estoy haceindo no sea none, mientras haya alguna nueva url, mientras la url de next no sea none -> como hemos visto antes. (esto es de la api de , otras paginas tienen otras claves) hace llamadas infinitas de 20 en 20 .extend(poke_json["results"]) next_url = poke_json["next"] poke_json = requests.get(next_url).json() #print(poke_json["next"]) #time.sleep(1) .extend(poke_json["results"]) print(len()) diccionario_s_url = {} #con api puedo transformar todo como yo necesite for i, e in enumerate(): nombre_ = [i]["name"] url_ = [i]["url"] diccionario_s_url[nombre_] = url_# que recorra (creada anteriormente) y que el nombre de los sean las claves y la url sea el valor diccionario_s_url df = pd.DataFrame(diccionario_s_url, index=["url"]) #transformarlo en dataframe df = df.T # hay que transponerlo -> si no se hace asi, si no le hacemos asi, va a poner a cada columna de cada su url asi que hay que transponerlo df # Para acceder al índice de cualquier DataFrame print(type(df.T.index.values)) df.index for nombre_, url in diccionario_s_url.items(): # que muestre las claves y las url peticion_api_url = requests.get(url).json() # traemos en un nuevo json toda la informacion relevante de cada pokemn print(nombre_) print(url) break peticion_api_url #es la informacion que representa el 1 pd.DataFrame(peticion_api_url["abilities"]) for nombre_, url in diccionario_s_url.items(): #clave y valor items peticion_api_url = requests.get(url).json() print(nombre_) print(url) break # solo el primero peticion_api_url["types"] #accedo a su tipo bulvasor es hierba y veneno pd.DataFrame(peticion_api_url["types"]) #dataframe con las habilidades de cada pokemin pd.DataFrame(peticion_api_url["types"]).type.values[0] #tendria que acceder a la shabilidades de cada accedo a cada columna asi paso esa columnas a coleccion de elementos y accedo al primero type_poke = pd.DataFrame(peticion_api_url["types"]).type.values[0]["url"] #url el prime rtipo del primer type_poke peticion_api_url = requests.get(type_poke).json() #llamo a la api del tipo 1 de lprimer peticion_api_url ###Output _____no_output_____ ###Markdown _El maravilloso mundo de las_ **APIs** o EL RETORNO DE JSON API: Interfaz de Programación de AplicacionesConjunto de definiciones y protocolos que se utiliza para desarrollar e integrar el software de las aplicaciones, permitiendo la comunicación entre dos aplicaciones de software a través de un conjunto de reglas. Listado de **APIs** for free: https://github.com/public-apis/public-apis ###Code import json import requests import pandas as pd from pandas.io.json import json_normalize import requests import json file_endpt = 'https://api.gdc.cancer.gov/data/' file_uuid = 'd853e541-f16a-4345-9f00-88e03c2dc0bc' response = requests.get(file_endpt + file_uuid) # OUTPUT METHOD 1: Write to a file. file = open("sample_request.json", "w") file.write(response.text) file.close() https://api.gdc.cancer.gov/data url_s = "https://api.gdc.cancer.gov/data" endpoint = "api/qotd" url_w = url_s + endpoint requests.get(url_w) qotd = requests.get(url_w).json() qotd qotd["quote"] cita = qotd["quote"] fecha = qotd["qotd_date"][:10] autor = cita["author"] cita_texto = cita["body"] print("La frase del día", fecha, "es de", autor, "y es la siguiente:\n\n" + cita_texto) json_normalize(qotd) ###Output _____no_output_____ ###Markdown API sin token **¿Qué es importante cuando tratamos con APIs?**Leer la documentación porque, si no lo hacemos, no sabemos cómo usarla. https://pokeapi.cohttps://pokeapi.co/docs/v2pokemon ------------------ Objetivo: Tener todos los nombres de pokemons junto con su url----------------- ###Code # No todas las APIs devuelven todos los posibles valores debido a limitación de recursos url = "https://pokeapi.co/api/v2/pokemon" poke_json = requests.get(url).json() poke_json json_normalize(poke_json) poke_json["next"] url_new = 'https://pokeapi.co/api/v2/pokemon?offset=0&limit=65' answer = requests.get(url_new).json() answer answer = requests.get(poke_json["next"]).json() answer # Cogemos todos los pokemons answer = requests.get("https://pokeapi.co/api/v2/pokemon?offset=0&limit=999999").json() answer df_pokemons = pd.DataFrame(answer) df_pokemons df2 = pd.DataFrame(answer["results"]) df2 l1 = [2, 4] l2 = ["a", "b"] l1.extend(l2) l1 poke_json pokemon = [] # para contener todos los resultados de la api poke_dict = {"name":"url"} pokemon.extend(poke_json["results"]) pokemon %%time pokemon_api_url = "https://pokeapi.co/api/v2/pokemon" poke_json = requests.get(pokemon_api_url).json() pokemon = [] # Almacenamos 40 pokemons realizando peticiones hasta que la lista de pokemons tenga 40 o más pokemons while len(pokemon) < 40: pokemon.extend(poke_json["results"]) next_url = poke_json["next"] poke_json = requests.get(next_url).json() print(len(pokemon)) pokemon poke_json %%time pokemon_api_url = "https://pokeapi.co/api/v2/pokemon" poke_json = requests.get(pokemon_api_url).json() pokemon = [] print(poke_json["next"]) import time while poke_json["next"] != None: pokemon.extend(poke_json["results"]) next_url = poke_json["next"] poke_json = requests.get(next_url).json() print(poke_json["next"]) #time.sleep(1) # Se pare un segundo pokemon.extend(poke_json["results"]) print(len(pokemon)) pokemon diccionario_pokemons_url = {} for i, e in enumerate(pokemon): nombre_pokemon = pokemon[i]["name"] url_pokemon = pokemon[i]["url"] diccionario_pokemons_url[nombre_pokemon] = url_pokemon diccionario_pokemons_url df = pd.DataFrame(diccionario_pokemons_url, index=["url"]) df = df.T df # Para acceder al índice de cualquier DataFrame print(type(df.T.index.values)) df.index diccionario_pokemons_url for nombre_pokemon, url in diccionario_pokemons_url.items(): peticion_api_url = requests.get(url).json() print(nombre_pokemon) print(url) break peticion_api_url pd.DataFrame(peticion_api_url["abilities"]) for nombre_pokemon, url in diccionario_pokemons_url.items(): peticion_api_url = requests.get(url).json() print(nombre_pokemon) print(url) break peticion_api_url["types"] pd.DataFrame(peticion_api_url["types"]) pd.DataFrame(peticion_api_url["types"]).type.values[0] type_poke = pd.DataFrame(peticion_api_url["types"]).type.values[0]["url"] type_poke peticion_api_url = requests.get(type_poke).json() peticion_api_url ###Output _____no_output_____
Homework-05.ipynb
###Markdown Cultural Analytics: Homework 5Due 11:59PM 11/10/2019--- ###Code # import required libraries from glob import glob import numpy as np from sklearn.feature_extraction.text import CountVectorizer from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics from sklearn.feature_extraction import stop_words # for visualization import seaborn as sn %matplotlib inline ###Output _____no_output_____ ###Markdown Make sure to edit the following cell before continuing ###Code # Edit the remaining 'label' entries in this cell with either 'British' or 'American' # You should be able to find all these authors easily with a Google search # Make sure to complete *ALL* these entries novel_data = [['data/Novel450/EN_1813_Austen,Jane_PrideandPrejudice_Novel.txt', 'British'], ['data/Novel450/EN_1817_Scott,Walter_RobRoy_Novel.txt', 'British'], ["data/Novel450/EN_1862_Braddon,Mary_LadyAudley'sSecret_Novel.txt", 'British'], ['data/Novel450/EN_1917_Webb,Mary_GonetoEart_Novel.txt', 'British'], ['data/Novel450/EN_1917_Cahan,Abraham_TheRiseofDavidLevinsky_Novel.txt', 'American'], ['data/Novel450/EN_1850_Hawthorne,Nathaniel_TheScarletLetter_Novel.txt', 'American'], ['data/Novel450/EN_1820_Scott,Walter_Ivanhoe_Novel.txt', 'British'], ['data/Novel450/EN_1818_Shelley,Mary_Frankenstein_Novel.txt', 'British'], ["data/Novel450/EN_1912_Cather,Willa_Alexander'sBridge_Novel.txt", 'American'], ['data/Novel450/EN_1847_Aguilar,Grace_HomeInfluence_Novel.txt', 'British'], ['data/Novel450/EN_1805_Lewis,Matthew_TheBravoofVenice_Novel.txt', 'British'], ["data/Novel450/EN_1853_Stowe,HarrietBeecher_UncleTom'sCabin_Novel.txt", 'American'], ['data/Novel450/EN_1853_Yonge,Charlotte_TheHeirofRedcliffe_Novel.txt', 'British'], ['data/Novel450/EN_1876_Trollope,FrancesEleanor_ACharmingFellow_Novel.txt', 'British'], ['data/Novel450/EN_1893_Gissing,George_TheOddWomen_Novel.txt', 'British'], ['data/Novel450/EN_1906_Sinclair,Upton_TheJungle_Novel.txt', 'American'], ['data/Novel450/EN_1843_Borrow,George_TheBibleinSpain_Novel.txt', 'label'], ['data/Novel450/EN_1899_Conrad,Joseph_HeartofDarkness_Novel.txt', 'label'], ['data/Novel450/EN_1884_Lyall,Edna_WeTwo_Novel.txt', 'label'], ['data/Novel450/EN_1894_Freeman,MaryWilkins_Pembroke_Novel.txt', 'label'], ['data/Novel450/EN_1804_Opie,Amelia_AdelineMowbray_Novel.txt', 'label'], ['data/Novel450/EN_1860_Collins,Wilkie_TheWomaninWhite_Novel.txt', 'label'], ['data/Novel450/EN_1794_Radcliffe,Ann_TheMysteriesofUdolpho_Novel.txt', 'label'], ['data/Novel450/EN_1869_Alcott,Louisa_LittleWomen_Novel.txt', 'label'], ['data/Novel450/EN_1850_Aguilar,Grace_ValeofCedars_Novel.txt', 'label'], ['data/Novel450/EN_1821_Galt,John_AnnalsoftheParish_Novel.txt', 'label'], ['data/Novel450/EN_1925_Woolf,Virginia_Mrs.Dalloway_Novel.txt', 'label'], ['data/Novel450/EN_1838_Poe,EdgarAllen_TheNarrativeofArthurGordonPym_Novel.txt', 'label'], ['data/Novel450/EN_1901_Norris,Frank_TheOctopus_Novel.txt', 'label'], ['data/Novel450/EN_1930_Mansfield,Katherine_TheAloe_Novel.txt', 'label'], ['data/Novel450/EN_1913_Lawrence,D.H._SonsandLovers_Novel.txt', 'label'], ['data/Novel450/EN_1908_Forster,E.M._ARoomWithaView_Novel.txt', 'label'], ['data/Novel450/EN_1905_Orczy,Emma_TheScarletPimpernel_Novel.txt', 'label'], ['data/Novel450/EN_1874_Hardy,Thomas_FarFromtheMaddingCrowd_Novel.txt', 'label'], ['data/Novel450/EN_1890_Chopin,Kate_AtFault_Novel.txt', 'label'], ['data/Novel450/EN_1856_Craik,Dinah_JohnHalifax_Novel.txt', 'label'], ['data/Novel450/EN_1815_Peacock,ThomasLove_HeadlongHall_Novel.txt', 'label'], ['data/Novel450/EN_1864_Braddon,Mary_HenryDunbar_Novel.txt', 'label'], ['data/Novel450/EN_1893_Harraden,Beatrice_ShipsThatPassintheNight_Novel.txt', 'label'], ['data/Novel450/EN_1838_Martineau,Harriet_Deerbrook_Novel.txt', 'label'], ["data/Novel450/EN_1885_Barr,Amelia_JanVeeder'sWife_Novel.txt", 'label'], ['data/Novel450/EN_1886_Stevenson,RobertLouis_JekyllandHyde_Novel.txt', 'label']] # we can leave this section as is for later testing... unlabled_testing_data = [ ['data/Novel450/EN_1894_Hope,Anthony_ThePrisonerofZenda_Novel.txt', 'label'], ['data/Novel450/EN_1922_Joyce,James_Ulysses_Novel.txt', 'label'], ['data/Novel450/EN_1786_Beckford,William_Vathek_Novel.txt', 'label'], ['data/Novel450/EN_1887_Bellamy,Edward_LookingBackward_Novel.txt', 'label'], ["data/Novel450/EN_1891_Hardy,Thomas_TessoftheD'Urbervilles_Novel.txt", 'label'], ['data/Novel450/EN_1847_Thackeray,William_VanityFair_Novel.txt', 'label'], ['data/Novel450/EN_1889_Doyle,ArthurConan_TheMysteryoftheCloomber_Novel.txt', 'label'], ['data/Novel450/EN_1906_Stein,Gertrude_ThreeLives_Novel.txt', 'label'], ['data/Novel450/EN_1871_Carroll,Lewis_ThroughtheLookingGlass.txt', 'label'], ['data/Novel450/EN_1916_Joyce,James_APortraitoftheArtistasaYoungMan_Novel.txt', 'label'], ['data/Novel450/EN_1888_Trollope,FrancesEleanor_ThatUnfortunateMarriage_Novel.txt', 'label'], ['data/Novel450/EN_1799_Brown,CharlesBrockden_ArthurMervyn_Novel.txt', 'label'], ['data/Novel450/EN_1911_Wharton,Edith_EthanFrome_Novel.txt', 'label'], ['data/Novel450/EN_1806_Edgeworth,Maria_Leonora_Novel.txt', 'label'], ['data/Novel450/EN_1798_Wollstonecraft,Mary_Maria_Novel.txt', 'label'], ['data/Novel450/EN_1809_More,Hannah_CoelebsinSearchofaWife_Novel.txt', 'label'], ['data/Novel450/EN_1862_Eliot,George_Romola_Novel.txt', 'label'], ['data/Novel450/EN_1917_Lewis,Sinclair_TheInnocents_Novel.txt', 'label'], ['data/Novel450/EN_1882_Stevenson,RobertLouis_TreasureIsland_Novel.txt', 'label'], ['data/Novel450/EN_1837_Trollope,FrancesMilton_TheVicarofWrexham_Novel.txt', 'label'], ['data/Novel450/EN_1848_Gaskell,Elizabeth_MaryBarton_Novel.txt', 'label'], ['data/Novel450/EN_1890_Wilde,Oscar_ThePictureofDorianGray_Novel.txt', 'label'], ['data/Novel450/EN_1853_Kingsley,Charles_Hypatia_Novel.txt', 'label'], ['data/Novel450/EN_1899_Chopin,Kate_TheAwakening_Novel.txt', 'label'], ['data/Novel450/EN_1910_Forster,E.M._HowardsEnd_Novel.txt', 'label'], ['data/Novel450/EN_1906_London,Jack_WhiteFang_Novel.txt', 'label'], ['data/Novel450/EN_1823_Cooper,JamesFenimore_ThePioneers_Novel.txt', 'label'], ['data/Novel450/EN_1852_Collins,Wilkie_Basil_Novel.txt', 'label'], ['data/Novel450/EN_1788_Wollstonecraft,Mary_Mary_Novel.txt', 'label'], ['data/Novel450/EN_1859_Dickens,Charles_ATaleofTwoCities_Novel.txt', 'label'], ['data/Novel450/EN_1891_Gissing,George_NewGrubStreet_Novel.txt', 'label'], ['data/Novel450/EN_1920_DosPassos,John_ThreeSoldiers_Novel.txt', 'label'], ['data/Novel450/EN_1895_Wells,H.G._TheTimeMachine_Novel.txt', 'label'], ['data/Novel450/EN_1903_James,Henry_TheAmbassadors_Novel.txt', 'label'], ['data/Novel450/EN_1795_Lewis,Matthew_TheMonk_Novel.txt', 'label'], ['data/Novel450/EN_1782_Burney,Fanny_Cecilia_Novel.txt', 'label'], ['data/Novel450/EN_1884_Twain,Mark_TheAdventuresofHuckleberryFinn_Novel.txt', 'label'], ['data/Novel450/EN_1883_Braddon,Mary_TheGoldenCalf_Novel.txt', 'label'], ['data/Novel450/EN_1811_Austen,Jane_SenseandSensibility_Novel.txt', 'label'], ['data/Novel450/EN_1900_Kipling,Rudyard_Kim_Novel.txt', 'label'], ['data/Novel450/EN_1922_Fitzgerald,FScott_TheBeautifulandtheDamned_Novel.txt', 'label'], ['data/Novel450/EN_1819_Shelley,Mary_Mathilda_Novel.txt', 'label'], ["data/Novel450/EN_1853_Craik,Dinah_Agatha'sHusband_Novel.txt", 'label'], ['data/Novel450/EN_1881_James,Henry_PortraitofaLady_Novel.txt', 'label'], ['data/Novel450/EN_1869_Trollope,Anthony_PhineasFinn_Novel.txt', 'label'], ['data/Novel450/EN_1860_Eliot,George_TheMillontheFloss_Novel.txt', 'label'], ['data/Novel450/EN_1794_Godwin,William_CalebWilliams_Novel.txt', 'label'], ['data/Novel450/EN_1900_Dreiser,Theodore_SisterCarrie_Novel.txt', 'label'], ['data/Novel450/EN_1900_Barr,Amelia_TheMaidofMaidenLane_Novel.txt', 'label'], ['data/Novel450/EN_1826_Disraeli,Benjamin_VivianGrey_Novel.txt', 'label'], ['data/Novel450/EN_1822_Hogg,James_ThreePerilsofMan_Novel.txt', 'label'], ['data/Novel450/EN_1814_Austen,Jane_MansfieldPark_Novel.txt', 'label'], ['data/Novel450/EN_1836_Child,Lydia_Philothea_Novel.txt', 'label'], ['data/Novel450/EN_1905_Wharton,Edith_TheHouseofMirth_Novel.txt', 'label'], ['data/Novel450/EN_1849_Kingsley,Charles_AltonLocke_Novel.txt', 'label'], ['data/Novel450/EN_1927_Woolf,Virginia_TotheLighthouse_Novel.txt', 'label'], ['data/Novel450/EN_1869_Blackmore,R.D._LornaDoone_Novel.txt', 'label'], ['data/Novel450/EN_1904_Murfree,MaryNoailles_TheFrontiersman_Novel.txt', 'label'], ['data/Novel450/EN_1851_Hawthorne,Nathaniel_TheHouseoftheSevenGables_Novel.txt', 'label'], ['data/Novel450/EN_1818_Peacock,ThomasLove_NightmareAbbey_Novel.txt', 'label'], ['data/Novel450/EN_1912_Dreiser,Theodore_TheFinancier_Novel.txt', 'label'], ['data/Novel450/EN_1796_Hays,Mary_EmmaCourtney_Novel.txt', 'label'], ['data/Novel450/EN_1903_Norris,Frank_ThePit_Novel.txt', 'label'], ['data/Novel450/EN_1861_Dickens,Charles_GreatExpectations_Novel.txt', 'label'], ['data/Novel450/EN_1920_Wharton,Edith_TheAgeofInnocence_Novel.txt', 'label'], ['data/Novel450/EN_1847_Bronte,Emily_WutheringHeights_Novel.txt', 'label'], ['data/Novel450/EN_1894_Kipling,Rudyard_TheJungleBook_Novel.txt', 'label'], ["data/Novel450/EN_1850_Yonge,Charlotte_Henrietta'sWish_Novel.txt", 'label'], ['data/Novel450/EN_1797_Foster,HannahWebster_TheCoquette_Novel.txt', 'label'], ['data/Novel450/EN_1891_Doyle,ArthurConan_TheDoingsofRafflesHaw_Novel.txt', 'label'], ['data/Novel450/EN_1800_Edgeworth,Maria_CastleRackrent_Novel.txt', 'label'], ['data/Novel450/EN_1771_Smollett,Tobias_TheExpedictionofHenryClinker_Novel.txt', 'label'], ['data/Novel450/EN_1876_Twain,Mark_TheAdventuresofTomSawyer_Novel.txt', 'label'], ['data/Novel450/EN_1796_Bonhote,Elizabeth_BungayCastle_Novel.txt', 'label'], ['data/Novel450/EN_1847_Bronte,Charlotte_JaneEyre_Novel.txt', 'label'], ['data/Novel450/EN_1771_Mackenzie,Henry_TheManofFeeling_Novel.txt', 'label'], ['data/Novel450/EN_1920_Fitzgerald,FScott_ThisSideofParadise_Novel.txt', 'label'], ['data/Novel450/EN_1854_Gaskell,Elizabeth_NorthandSouth_Novel.txt', 'label'], ['data/Novel450/EN_1895_Crane,Stephen_TheRedBadgeofCourage_Novel.txt', 'label'], ['data/Novel450/EN_1778_Burney,Fanny_Evelina_Novel.txt', 'label'], ['data/Novel450/EN_1911_Barrie,J.M._PeterPan_Novel.txt', 'label'], ['data/Novel450/EN_1851_Melville,Hermann_MobyDick_Novel.txt', 'label'], ['data/Novel450/EN_1898_Crockett,SR_TheRedAxe_Novel.txt', 'label'], ['data/Novel450/EN_1790_Radcliffe,Ann_ASicilianRomance_Novel.txt', 'label'], ['data/Novel450/EN_1844_Yonge,Charlotte_Abbeychurch_Novel.txt', 'label'], ['data/Novel450/EN_1915_Ford,FordMadox_TheGoodSoldier_Novel.txt', 'label'], ['data/Novel450/EN_1821_Peacock,ThomasLove_MaidMarian_Novel.txt', 'label'], ['data/Novel450/EN_1855_Trollope,FrancesMilton_TheWidowBarnaby_Novel.txt', 'label'], ['data/Novel450/EN_1897_Stoker,Bram_Dracula_Novel.txt', 'label'], ['data/Novel450/EN_1826_Cooper,JameFenimore_TheLastoftheMohicans_Novel.txt', 'label'], ['data/Novel450/EN_1902_Bennett,Arnold_GrandBabylonHotel_Novel.txt', 'label'], ['data/Novel450/EN_1801_Edgeworth,Maria_Belinda_Novel.txt', 'label'], ["data/Novel450/EN_1865_Carroll,Lewis_Alice'sAdventureinWonderland_Novel.txt", 'label'], ['data/Novel450/EN_1918_Lewis,Sinclai_TheJob_Nove.txt', 'label'], ['data/Novel450/EN_1857_Trollope,Anthony_BarchesterTowers_Novel.txt', 'label'], ['data/Novel450/EN_1888_Ward,Mrs.Humphry_RobertElsmere_Novel.txt', 'label'], ['data/Novel450/EN_1890_Broughton,Rhoda_Alas!_Novel.txt', 'label'], ['data/Novel450/EN_1903_London,Jack_TheCalloftheWild_Novel.txt', 'label'], ['data/Novel450/EN_1893_Grand,Sarah_TheHeavenlyTwins_Novel.txt', 'label'], ['data/Novel450/EN_1796_Burney,Fanny_Camilla_Novel.txt', 'label'], ['data/Novel450/EN_1798_Brown,CharlesBrockden_Wieland_Novel.txt', 'label'], ['data/Novel450/EN_1848_Bronte,Ann_TheTenantofWildfellHall_Novel.txt', 'label'], ['data/Novel450/EN_1794_Rowson,Susanna_CharlotteTemple_Novel.txt', 'label'], ['data/Novel450/EN_1928_Woolf,Virginia_Orlando_Novel.txt', 'label'], ['data/Novel450/EN_1814_Scott,Walter_Waverley_Novel.txt', 'label'], ['data/Novel450/EN_1902_Bellamy,Edward_Eleonora_Novel.txt', 'label'], ['data/Novel450/EN_1877_Sewell,Anna_BlackBeauty_Novel.txt', 'label'], ['data/Novel450/EN_1837_Disraeli,Benjamin_Venetia_Novel.txt', 'label']] # what did we find? print("found {0} labeled texts".format(len(novel_data))) print("found {0} unlabeled texts".format(len(unlabled_testing_data))) # split into test and training data train_files = [x[0] for x in novel_data[:30]] train_labels = [x[1] for x in novel_data[:30]] test_files = [x[0] for x in novel_data[31:]] test_labels = [x[1] for x in novel_data[31:]] # count our test and training datasets print("{0} training texts".format(len(train_files))) print("{0} testing texts".format(len(test_files))) # initialize the vectorizer # after running through, you might want to make some changes here to see if these # alter your results vectorizer = CountVectorizer(input='filename', lowercase=True, strip_accents='unicode') # fit training data train_data = vectorizer.fit_transform(train_files) # fit testing data test_data = vectorizer.transform(test_files) # get vocabulary for later vocabulary = vectorizer.get_feature_names() # Return total number of documents and the number of items in the vocabulary dc, vc = train_data.shape print("document count:",dc,"vocabulary count:",vc) # run kNN and fit training data knn = KNeighborsClassifier(n_neighbors=4) knn.fit(train_data,train_labels) # Predict results from the test data and check accuracy pred = knn.predict(test_data) score = metrics.accuracy_score(test_labels, pred) print("model accuracy: %0.3f" % score) print(metrics.classification_report(test_labels, pred)) print("confusion matrix:") print(metrics.confusion_matrix(test_labels, pred)) # Produce visualization of confusion matrix # # Learn more about the meaning of this matrix here: # https://en.wikipedia.org/wiki/Confusion_matrix sn.heatmap(metrics.confusion_matrix(test_labels, pred),annot=True,cmap='Blues',fmt='g') ###Output _____no_output_____ ###Markdown Question 1: How accurate was this model? What did you learn about training and testing data? Did you try to change the CountVectorizer options? How did that alter the accuracy of your classifier? RESPONSE GOES HEREQuestion 2: Try other labels instead of 'American' and 'British' (you can have many different labels or classes as long as you have enough samples of both testing and training data) for the novel_data cell. After editing, save and rerun the entire notebook (Kernel -> 'Restart and Run All') Does this work better for certain labels? What have you learned about machine learning?RESPONSE GOES HERE ###Code # If you've completed the above, you can now try to classify the remainder of the texts # by running this cell. It will use whatever labels you have assigned. # fit testing data utd = vectorizer.transform([x[0] for x in unlabled_testing_data]) # predict pred_others = knn.predict(utd) for i, text in enumerate(pred_others): print(text,unlabled_testing_data[i][0]) ###Output _____no_output_____
Week2-Python-Fundamentals-3&4/Python_Bootcamp_Week_2.ipynb
###Markdown Python Bootcamp Week2Python fundamentals 4: testing, type annotation, Python best practices 1. Testing Why do you need to test your code? Well, you have to make sure your code does what it is supposed to do.- The test is used to validate the output against a known response- You have to make sure your function/test return the same result each time no matter how many times it runsWhen do you need to test your code:- You should **always** test your code.- When you write any code, you should first manually check if its working, and then write a test to test its working - Note that there is also an opposite process which is to write your test first and then write your code, this process is called *Test Driven Development (TDD)* - TDD can be very effective, since by writing your tests first, you should think about the edge cases first and your code will produce less bugs- You should test any edge cases that you can think of. Missing handle of the edge cases are mostly the cause of the bugs. Automated vs. Manual Testing- Manual Testing: - To have a complete set of manual tests, all you need to do is make a list of all the features your application has, the different types of input it can accept, and the expected results. - However, every time you make a change to your code, you need to go through every single item on that list and check it.- Automated Testing: use script to execute your test plan. - How do we do automated testing? We use the `assert` keyword ###Code assert 1 + 2 + 3 == 6, "Should be 6" assert 1 == 6, "Should be 6" def test_sum(a_list, target): assert sum(a_list) == target, f"Should be {target}" test_sum([1,2,3], 6) test_sum([1,2], 6) ###Output _____no_output_____ ###Markdown Unit Tests vs. Integration Tests- Unit test and integration test are two very important terminology in the world of testing- Unit test: test a single component/function- Integration test: test multiple components- For example: Suppose we have a calculator that does simple `+-*/` calculation - We have the following unit test: - Turn on the calculator, display works - Punch in numbers, display shows correct numbers - Simple calculation works, such as `1+1=2`, `1-1=0`, `1*1=1`, `1/1=1` - We have the following integration test: - Complex calculation works, such as `5*(20+3) - 8 = 107` Test framework- Although we can write test code from scratch, there are two famous test frameworks in Python: - Unittest (built into Python standard library since Python 2.1) - Pytest - nose/nose2 (not so popular nowadays, you may see it in some leacy code) Unittest frameworkHow to use unittest:1. `import unittest`2. Created a test class to inherit from `TestCase`3. You can use `self.assert_` to assert different cases, such as *equal*, *in*, etcFor example:```pythonimport unittestclass TestSum(unittest.TestCase): def test_sum(self): self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") def test_sum_tuple(self): self.assertEqual(sum([1, 2, 2]), 6, "Should be 6")if __name__ == '__main__': This means that if you execute the script alone by running python test.py at the command line, it will call unittest.main() unittest.main()```- When you would like to do something prior to the tests (such as setup some data or functions), you can use `setUp` method.- When you would like to clean up after the tests are done (such as delete some content, reset some configurations, etc), you can use the `tearDown` method.- A good example of the test class looks like:```python class TestXxx(unittest.TestCase): def setUp(self): """ setup for test cases """ pass def tearDown(self): """ CLeanup for test cases """ pass def test_yyy_description1(self): """ test description 1 """ pass def test_yyy_description2(self): """ test description 2 """ pass``` - Unittest has many builtin methods for quick testing, such as test equals, element inside list, a detailed list can be seen in the Reference lists- You can also test if there is an error in the code (i.e. test expected failures happens) using `self.assertRaises````python def test_bad_type(self): data = "banana" with self.assertRaises(TypeError): result = sum(data)``` Pytest frameworkPytest is built upon unittest, so ALL your unittest code can work seemlessly with pytest.Benefits of Pytest over unittest:1. pytest test cases are a series of functions in a Python file starting with the name `test_`, so its function based rather than class based.2. Support for the built-in `assert` statement instead of using special `self.assert*()` methods3. Support for filtering for test cases4. Ability to rerun from the last failing test5. Better debug information6. An ecosystem of hundreds of plugins to extend the functionalityHow to use Pytest:```pythondef test_sum(a_list, target): assert sum(a_list) == target, f"Should be {target}"```Similarly, pytest can also assert exception as follows:```pythondef test_zero_division(): with pytest.raises(ZeroDivisionError): 1 / 0``` Test file structureThere are basically two ways you can structure your files for your project:First one is to have your test files in a test folder outside of the applicaiton code (**Preferred**):```project/│├── my_sum/│ └── __init__.py|└── tests/ └── test_my_sum.py```The second one is to have your test files in your application code folder:```project/│└── my_sum/ ├── __init__.py | └── tests/ └── test_my_sum.py ``` Test executionThe Python application that executes your test code, checks the assertions, and gives you test results in your console is called the **test runner**.How do you run the test in command line:- To run the test: `python -m unittest test` (suppose your test file is named as `test.py`) - Note that you can also run specific test function with `python -m unittest test.TestClass.test_method`- Add `-v` flag for print more info into the consol: `python -m unittest -v test` - Note you can also add multiple `v` flags for more detailed info- Use auto-discovery for patterns rather than file name: `python -m unittest discover` - It will detect and run all the files named `test*.py` in the current directory (i.e. `test_sum.py` etc) Read test outputSuppose you have the following output:```$ python -m unittest testF.======================================================================FAIL: test_list_fraction (test.TestSum)----------------------------------------------------------------------Traceback (most recent call last): File "test.py", line 21, in test_list_fraction self.assertEqual(result, 1)AssertionError: Fraction(9, 10) != 1----------------------------------------------------------------------Ran 2 tests in 0.001sFAILED (failures=1)```What does it mean?- `F` means the test failed, `.` means the test passed- The `Traceback` shows you where the error happened, and line number indicates which line the error happened- The `AssertionError` shows what error happened: expected result *(1)* and the actual result *(Fraction(9, 10))***NOTE** you can configure your IDE to run tests too, details in the Reference links Fixtures- The data that you create as an input is known as a **fixture**. It’s common practice to create fixtures and reuse them.- You can write your own function from scratch to create fixtures, or you can use thrid party packages- pytest framework has builtin functions to mark your functions as fixtures- `Factory Boy` is a famous package for creating fixtures with ORMs (to initiate some data in database) Mocks- Mocks are another important part of unit testing. - As of Python 3.3 and later, mock became a standard library in python, you can import it in `unittest.mock`- Since unit testing is to test a specific function, sometimes we don't care about the other parts of the functions and that's why we mock them.- We also use mocks to control your code's behavior during testing. In another word, your tests execute predictably only so far as the environments are behaving as you expected.For exmaple: ###Code from datetime import datetime from unittest.mock import Mock # Save a couple of test days tuesday = datetime(year=2019, month=1, day=1) saturday = datetime(year=2019, month=1, day=5) # Mock datetime to control today's date datetime = Mock() def is_weekday(): today = datetime.today() # Python's datetime library treats Monday as 0 and Sunday as 6 return (0 <= today.weekday() < 5) # Mock .today() to return Tuesday datetime.today.return_value = tuesday # Test Tuesday is a weekday assert is_weekday() # Mock .today() to return Saturday datetime.today.return_value = saturday # Test Saturday is not a weekday assert not is_weekday() ###Output _____no_output_____ ###Markdown References- [Getting Started With Testing in Python](https://realpython.com/python-testing/)- [python Unittest](https://docs.python.org/3/library/unittest.html)- [Unittest Cheatsheet](https://gist.github.com/mogproject/fc7c4e94ba505e95fa03)- [pytest Cheatsheet](https://www.valentinog.com/blog/pytest/)- [Test directory structure](https://docs.pytest.org/en/reorganize-docs/new-docs/user/directory_structure.html)- [How to run test in Pycharm](https://www.jetbrains.com/help/pycharm/performing-tests.html)- [Python testing in VScode](https://code.visualstudio.com/docs/python/testing)- [Testing in django](https://docs.djangoproject.com/en/dev/topics/testing/overview/)- [Understanding the Python Mock Object Library](https://realpython.com/python-mock-library/) 2. Type annotation As we all know python types are really flexible (weakly typed), but this could create some confusions in the code.Python 3.6 introduced type annotation. [**PEP 526**](https://www.python.org/dev/peps/pep-0526/) describes it in full details. ###Code age: int = 1 # In Python 3.5 and earlier you can use a type comment instead # (equivalent to the previous definition) age = 1 # type: int # You don't need to initialize a variable to annotate it a: int # Ok (no value at runtime until assigned) # The latter is useful in conditional branches child: bool if age < 18: child = True else: child = False ###Output _____no_output_____ ###Markdown You can anotate variables, functions, classes, pretty much anything ###Code # this function has an input type str and return type str def greeting(name: str) -> str: return 'Hello ' + name ###Output _____no_output_____ ###Markdown There are many builtin types you can use: ###Code from typing import List, Set, Dict, Tuple # For simple built-in types, just use the name of the type x: int = 1 x: float = 1.0 x: bool = True x: str = "test" x: bytes = b"test" # For collections, the name of the type is capitalized, and the # name of the type inside the collection is in brackets x: List[int] = [1] x: Set[int] = {6, 7} # Same as above, but with type comment syntax x = [1] # type: List[int] # For mappings, we need the types of both keys and values x: Dict[str, float] = {'field': 2.0} # For tuples of fixed size, we specify the types of all the elements x: Tuple[int, str, float] = (3, "yes", 7.5) # For tuples of variable size, we use one type and ellipsis x: Tuple[int, ...] = (1, 2, 3) ###Output _____no_output_____ ###Markdown You can also create custom types for you code ###Code from typing import NewType UserId = NewType('UserId', int) some_id = UserId(524313) ###Output _____no_output_____ ###Markdown Combine them together, you can annotate your function easily: ###Code from typing import Callable, Iterator, Union, Optional, List def send_email( address: Union[str, List[str]], sender: str, cc: Optional[List[str]], bcc: Optional[List[str]], subject='', body: Optional[List[str]] = None ) -> bool: pass ###Output _____no_output_____ ###Markdown Reference- [Type hints cheat sheet (Python 3)](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html)- [Python Type Checking (Guide)](https://realpython.com/python-type-checking/) 3. Python Best practicesI've seen so much code with bad practice (leetcode, kaggle, open source projects, etc), that's why I would like to show you what are the Python best practices.**DISCLAIMER**: This presentation is entirely subjective, and is based on author’s experience, and what’s widely accepted by Python devsAll python code is guided by Python Enhancement Proposals (***PEP***s) Virtual EnvironmentSince Python has many different versions, and there are many packages with different versions, its always best to use virtual enviornments to make sure the verions are properly isolated.There are mainly three virtual environments:- Virtualenv- Anaconda- Pipenv Virtualenv- Most widely used- The package `virtualenvwrapper` makes everything much eaiser - `makevirtualenv` - `workon` and `deactivate` - `setvirtualenvproject` Anaconda- Most widely used in the AI areas (ML, DS, etc)- Integration of many packages- Commands slightly different or Win and Mac- Some commands - `conda create –n ` - `conda install ` - `source activate` & `source deactivate` Pipenv- New standard of python packages- Combination of pip and virtualenv- Dependency version lock- Some Commands: - `pipenv shell` - `pipenv install ` - `pipenv install --dev` Code Structure ```project/│├── src/│ ├── __init__.py│ └── main_func.py|├── tests/│ └── test_my_func.py|├── README.md|├── License|├── requirements.txt|├── Documentations/│ └── my_doc.md|└─ setup.py if this is a package``` Formatting, linting, and typing**Format** is how you write your code**Linting** is a way to check your code's format**Types** are the annotations talked aboveThese two things you ***MUST*** remember:- ***PEP8***: Official style guide for Python code - https://www.python.org/dev/peps/pep-0008/- ***Black***: the Uncompromising Code Formatter - More readability, great formatting - One of the official supported formatter for VSCode - Django has accepted using black as formatting as of May 10, 2019***Code is executed by machines, but is read by human***For example: Badly formated code Good foramted code autoencoder = create_autoencoder(dae_train.shape[1]) autoencoder.fit(noised_train, dae_train, epochs=500, batch_size=128, callbacks=[ ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience = 3, verbose=1, min_delta=1e-4, mode='min') , ModelCheckpoint(f'dae.hdf5', monitor = 'val_loss', verbose = 0, save_best_only = True, save_weights_only = True, mode = 'min') , EarlyStopping(monitor = 'val_loss', min_delta = 1e-4, patience = 8, mode = 'min', baseline = None, restore_best_weights = True)], shuffle=True, validation_split=0.2) autoencoder = create_autoencoder(dae_train.shape[1]) autoencoder.fit( noised_train, dae_train, epochs=500, batch_size=128, callbacks=[ ReduceLROnPlateau( monitor='val_loss', factor=0.1, patience=3, verbose=1, min_delta=1e-4, mode='min', ), ModelCheckpoint( f'dae.hdf5', monitor='val_loss', verbose=0, save_best_only=True, save_weights_only=True, mode='min', ), EarlyStopping( monitor='val_loss', min_delta=1e-4, patience=8, mode='min', baseline=None, restore_best_weights=True, ), ], shuffle=True, validation_split=0.2, ) ###Code a_dict = dict( name="Carson", title="developer", name1="Carson", title2="developer", name3="Carson", title4="developer", ) print(a_dict) from pprint import pprint pprint(a_dict) import datetime def get_week(): pass ###Output _____no_output_____ ###Markdown Indentation- Python recognizes both space and tab for indentation level- PEP8 suggests using space- **4 spaces** per indentation level- must **NEVER MIX** spaces and tabs Strings- People use to use single quote (**‘** **’**) coz its easier to type- Double quote (**“** **”**) is used by English language- **Black suggests to use double quotes to reduce confusion** - For example: - `print(f"You've never seen this {animal} before")` - `print(f'You\'ve never seen this {animal} before')`- You can use `--skip-string-normalization` to stop black formatting your quotations Line length- PEP8 suggests all lines limit to 79 characters, and 72 characters for comments- Many companies use line length from 100 to 120 characters- **Black suggests using 88 characters per line** Line break- PEP8 suggests line break after binary operators for readability ```python Correct: easy to match operators with operands income = (gross_wages + taxable_interest + (dividends - qualified_dividends) - ira_deduction - student_loan_interest) ```- Surround top-level function and class definitions with *two blank lines*- Method definitions inside a class are surrounded by a single blank line Imports- Be explicit ```python Correct: from subprocess import Popen, PIPE ```- Imports should be on separate lines ```python Correct: import os import sys ``` ```python Wrong: import sys, os ```- Imports order: 1. Standard lib 2. Related 3rd party 3. Local lib- What if there are too many classes need to be imported from 1 package? ```python from sklearn.model_selection import ( TimeSeriesSplit, KFold, ShuffleSplit, StratifiedKFold, GroupShuffleSplit, GroupKFold, StratifiedShuffleSplit, train_test_split, ) ``` Call ChainsSome popular APIs, like ORMs, use call chaining.Here is how black formats it:```pythondef example(session): result = ( session.query(models.Customer.id) .filter( models.Customer.account_id == account_id, models.Customer.email == email_address, ) .order_by(models.Customer.id.asc()) .all() )``` Long String- When you have a super long string, you can break it up to a few lines- Use triple quotation- Use plus sign, but it creates more strings- Or do multiple lines ###Code # Break into a few lines message1 = ( "some really long message" "and some really really long message" ) print(f"1. Break into a few lines: {message1}") # Use triple quotation message2 = """ some really long message and some really really long message """ print(f"2. Use triple quotation: {message2}") # Break into a few lines message3 = ( "some really long message" + "and some really really long message" ) print(f"3. Use plus sign: {message3}") ###Output 1. Break into a few lines: some really long messageand some really really long message 2. Use triple quotation: some really long message and some really really long message 3. Use plus sign: some really long messageand some really really long message
notebooks/collision_avoidance/train_model_resnet18.ipynb
###Markdown Collision Avoidance - Train Model (ResNet18)Welcome to this host side Jupyter Notebook! This should look familiar if you ran through the notebooks that run on the robot. In this notebook we'll train our image classifier to detect two classes``free`` and ``blocked``, which we'll use for avoiding collisions. For this, we'll use a popular deep learning library *PyTorch* ###Code import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms ###Output _____no_output_____ ###Markdown Upload and extract datasetBefore you start, you should upload the ``dataset.zip`` file that you created in the ``data_collection.ipynb`` notebook on the robot.You should then extract this dataset by calling the command below ###Code !unzip -q dataset.zip ###Output _____no_output_____ ###Markdown You should see a folder named ``dataset`` appear in the file browser. Create dataset instance Now we use the ``ImageFolder`` dataset class available with the ``torchvision.datasets`` package. We attach transforms from the ``torchvision.transforms`` package to prepare the data for training. ###Code dataset = datasets.ImageFolder( 'dataset', transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) ) ###Output _____no_output_____ ###Markdown Split dataset into train and test sets Next, we split the dataset into *training* and *test* sets. The test set will be used to verify the accuracy of the model we train. ###Code train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - 50, 50]) ###Output _____no_output_____ ###Markdown Create data loaders to load data in batches We'll create two ``DataLoader`` instances, which provide utilities for shuffling data, producing *batches* of images, and loading the samples in parallel with multiple workers. ###Code train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=16, shuffle=True, num_workers=4 ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=16, shuffle=True, num_workers=4 ) ###Output _____no_output_____ ###Markdown Define the neural networkNow, we define the neural network we'll be training. The *torchvision* package provides a collection of pre-trained models that we can use.In a process called *transfer learning*, we can repurpose a pre-trained model (trained on millions of images) for a new task that has possibly much less data available.Important features that were learned in the original training of the pre-trained model are re-usable for the new task. We'll use the ``resnet18`` model. ###Code model = models.resnet18(pretrained=True) ###Output _____no_output_____ ###Markdown The ``resnet18`` model was originally trained for a dataset that had 1000 class labels, but our dataset only has two class labels! We'll replacethe final layer with a new, untrained layer that has only two outputs. ###Code model.fc = torch.nn.Linear(512, 2) ###Output _____no_output_____ ###Markdown Finally, we transfer our model for execution on the GPU ###Code device = torch.device('cuda') model = model.to(device) ###Output _____no_output_____ ###Markdown Train the neural networkUsing the code below we will train the neural network for 30 epochs, saving the best performing model after each epoch.> An epoch is a full run through our data. ###Code NUM_EPOCHS = 30 BEST_MODEL_PATH = 'best_model_resnet18.pth' best_accuracy = 0.0 optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(NUM_EPOCHS): for images, labels in iter(train_loader): images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() test_error_count = 0.0 for images, labels in iter(test_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) print('%d: %f' % (epoch, test_accuracy)) if test_accuracy > best_accuracy: torch.save(model.state_dict(), BEST_MODEL_PATH) best_accuracy = test_accuracy ###Output _____no_output_____ ###Markdown Collision Avoidance - Train Model (ResNet18)Welcome to this host side Jupyter Notebook! This should look familiar if you ran through the notebooks that run on the robot. In this notebook we'll train our image classifier to detect two classes``free`` and ``blocked``, which we'll use for avoiding collisions. For this, we'll use a popular deep learning library *PyTorch* ###Code import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms ###Output _____no_output_____ ###Markdown Upload and extract datasetBefore you start, you should upload the ``dataset.zip`` file that you created in the ``data_collection.ipynb`` notebook on the robot.You should then extract this dataset by calling the command below ###Code !unzip -q dataset.zip ###Output _____no_output_____ ###Markdown You should see a folder named ``dataset`` appear in the file browser. Create dataset instance Now we use the ``ImageFolder`` dataset class available with the ``torchvision.datasets`` package. We attach transforms from the ``torchvision.transforms`` package to prepare the data for training. ###Code dataset = datasets.ImageFolder( 'dataset', transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) ) ###Output _____no_output_____ ###Markdown Split dataset into train and test sets Next, we split the dataset into *training* and *test* sets. The test set will be used to verify the accuracy of the model we train. ###Code train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - 50, 50]) ###Output _____no_output_____ ###Markdown Create data loaders to load data in batches We'll create two ``DataLoader`` instances, which provide utilities for shuffling data, producing *batches* of images, and loading the samples in parallel with multiple workers. ###Code train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=8, shuffle=True, num_workers=0, ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=8, shuffle=True, num_workers=0, ) ###Output _____no_output_____ ###Markdown Define the neural networkNow, we define the neural network we'll be training. The *torchvision* package provides a collection of pre-trained models that we can use.In a process called *transfer learning*, we can repurpose a pre-trained model (trained on millions of images) for a new task that has possibly much less data available.Important features that were learned in the original training of the pre-trained model are re-usable for the new task. We'll use the ``resnet18`` model. ###Code model = models.resnet18(pretrained=True) ###Output _____no_output_____ ###Markdown The ``resnet18`` model was originally trained for a dataset that had 1000 class labels, but our dataset only has two class labels! We'll replacethe final layer with a new, untrained layer that has only two outputs. ###Code model.fc = torch.nn.Linear(512, 2) ###Output _____no_output_____ ###Markdown Finally, we transfer our model for execution on the GPU ###Code device = torch.device('cuda') model = model.to(device) ###Output _____no_output_____ ###Markdown Train the neural networkUsing the code below we will train the neural network for 30 epochs, saving the best performing model after each epoch.> An epoch is a full run through our data. ###Code NUM_EPOCHS = 30 BEST_MODEL_PATH = 'best_model_resnet18.pth' best_accuracy = 0.0 optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(NUM_EPOCHS): for images, labels in iter(train_loader): images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() test_error_count = 0.0 for images, labels in iter(test_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) print('%d: %f' % (epoch, test_accuracy)) if test_accuracy > best_accuracy: torch.save(model.state_dict(), BEST_MODEL_PATH) best_accuracy = test_accuracy ###Output _____no_output_____ ###Markdown Collision Avoidance - Train Model (ResNet18)Welcome to this host side Jupyter Notebook! This should look familiar if you ran through the notebooks that run on the robot. In this notebook we'll train our image classifier to detect two classes``free`` and ``blocked``, which we'll use for avoiding collisions. For this, we'll use a popular deep learning library *PyTorch* ###Code import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms ###Output _____no_output_____ ###Markdown Upload and extract datasetBefore you start, you should upload the ``dataset.zip`` file that you created in the ``data_collection.ipynb`` notebook on the robot.You should then extract this dataset by calling the command below ###Code !unzip -q dataset.zip ###Output _____no_output_____ ###Markdown You should see a folder named ``dataset`` appear in the file browser. Create dataset instance Now we use the ``ImageFolder`` dataset class available with the ``torchvision.datasets`` package. We attach transforms from the ``torchvision.transforms`` package to prepare the data for training. ###Code dataset = datasets.ImageFolder( 'dataset', transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) ) ###Output _____no_output_____ ###Markdown Split dataset into train and test sets Next, we split the dataset into *training* and *test* sets. The test set will be used to verify the accuracy of the model we train. ###Code train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - 50, 50]) ###Output _____no_output_____ ###Markdown Create data loaders to load data in batches We'll create two ``DataLoader`` instances, which provide utilities for shuffling data, producing *batches* of images, and loading the samples in parallel with multiple workers. ###Code train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=8, shuffle=True, num_workers=0, ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=8, shuffle=True, num_workers=0, ) ###Output _____no_output_____ ###Markdown Define the neural networkNow, we define the neural network we'll be training. The *torchvision* package provides a collection of pre-trained models that we can use.In a process called *transfer learning*, we can repurpose a pre-trained model (trained on millions of images) for a new task that has possibly much less data available.Important features that were learned in the original training of the pre-trained model are re-usable for the new task. We'll use the ``resnet18`` model. ###Code model = models.resnet18(pretrained=True) ###Output _____no_output_____ ###Markdown The ``resnet18`` model was originally trained for a dataset that had 1000 class labels, but our dataset only has two class labels! We'll replacethe final layer with a new, untrained layer that has only two outputs. ###Code model.fc = torch.nn.Linear(512, 2) ###Output _____no_output_____ ###Markdown Finally, we transfer our model for execution on the GPU ###Code device = torch.device('cuda') model = model.to(device) ###Output _____no_output_____ ###Markdown Train the neural networkUsing the code below we will train the neural network for 30 epochs, saving the best performing model after each epoch.> An epoch is a full run through our data. ###Code NUM_EPOCHS = 30 BEST_MODEL_PATH = 'best_model_resnet18.pth' best_accuracy = 0.0 optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(NUM_EPOCHS): for images, labels in iter(train_loader): images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() test_error_count = 0.0 for images, labels in iter(test_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) print('%d: %f' % (epoch, test_accuracy)) if test_accuracy > best_accuracy: torch.save(model.state_dict(), BEST_MODEL_PATH) best_accuracy = test_accuracy ###Output 0: 0.980000 1: 1.000000 2: 1.000000 4: 1.000000 5: 1.000000 6: 1.000000 7: 1.000000 8: 1.000000 9: 1.000000 10: 1.000000 11: 1.000000 12: 1.000000 13: 0.980000 14: 1.000000 15: 1.000000 16: 1.000000 17: 1.000000 18: 1.000000 19: 1.000000 20: 1.000000 21: 1.000000 22: 1.000000 23: 1.000000 24: 1.000000 25: 1.000000 26: 1.000000 27: 1.000000 28: 1.000000 29: 1.000000 ###Markdown Collision Avoidance - Train Model (ResNet18)Welcome to this host side Jupyter Notebook! This should look familiar if you ran through the notebooks that run on the robot. In this notebook we'll train our image classifier to detect two classes``free`` and ``blocked``, which we'll use for avoiding collisions. For this, we'll use a popular deep learning library *PyTorch* ###Code import torch import torch.optim as optim import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.models as models import torchvision.transforms as transforms ###Output _____no_output_____ ###Markdown Upload and extract datasetBefore you start, you should upload the ``dataset.zip`` file that you created in the ``data_collection.ipynb`` notebook on the robot.You should then extract this dataset by calling the command below ###Code !unzip -q dataset.zip ###Output _____no_output_____ ###Markdown You should see a folder named ``dataset`` appear in the file browser. Create dataset instance Now we use the ``ImageFolder`` dataset class available with the ``torchvision.datasets`` package. We attach transforms from the ``torchvision.transforms`` package to prepare the data for training. ###Code dataset = datasets.ImageFolder( 'dataset', transforms.Compose([ transforms.ColorJitter(0.1, 0.1, 0.1, 0.1), transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) ) ###Output _____no_output_____ ###Markdown Split dataset into train and test sets Next, we split the dataset into *training* and *test* sets. The test set will be used to verify the accuracy of the model we train. ###Code train_dataset, test_dataset = torch.utils.data.random_split(dataset, [len(dataset) - 50, 50]) ###Output _____no_output_____ ###Markdown Create data loaders to load data in batches We'll create two ``DataLoader`` instances, which provide utilities for shuffling data, producing *batches* of images, and loading the samples in parallel with multiple workers. ###Code train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=8, shuffle=True, num_workers=0, ) test_loader = torch.utils.data.DataLoader( test_dataset, batch_size=8, shuffle=True, num_workers=0, ) ###Output _____no_output_____ ###Markdown Define the neural networkNow, we define the neural network we'll be training. The *torchvision* package provides a collection of pre-trained models that we can use.In a process called *transfer learning*, we can repurpose a pre-trained model (trained on millions of images) for a new task that has possibly much less data available.Important features that were learned in the original training of the pre-trained model are re-usable for the new task. We'll use the ``resnet18`` model. ###Code model = models.resnet18(pretrained=True) ###Output _____no_output_____ ###Markdown The ``resnet18`` model was originally trained for a dataset that had 1000 class labels, but our dataset only has two class labels! We'll replacethe final layer with a new, untrained layer that has only two outputs. ###Code model.fc = torch.nn.Linear(512, 2) ###Output _____no_output_____ ###Markdown Finally, we transfer our model for execution on the GPU ###Code device = torch.device('cuda') model = model.to(device) ###Output _____no_output_____ ###Markdown Train the neural networkUsing the code below we will train the neural network for 30 epochs, saving the best performing model after each epoch.> An epoch is a full run through our data. ###Code NUM_EPOCHS = 30 BEST_MODEL_PATH = 'best_model_resnet18.pth' best_accuracy = 0.0 optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(NUM_EPOCHS): for images, labels in iter(train_loader): images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = F.cross_entropy(outputs, labels) loss.backward() optimizer.step() test_error_count = 0.0 for images, labels in iter(test_loader): images = images.to(device) labels = labels.to(device) outputs = model(images) test_error_count += float(torch.sum(torch.abs(labels - outputs.argmax(1)))) test_accuracy = 1.0 - float(test_error_count) / float(len(test_dataset)) print('%d: %f' % (epoch, test_accuracy)) if test_accuracy > best_accuracy: torch.save(model.state_dict(), BEST_MODEL_PATH) best_accuracy = test_accuracy ###Output _____no_output_____
13.10 Bar Plots with Dataframes.ipynb
###Markdown ![title](img/cover4.png) Copyright! This material is protected, please do not copy or distribute. by:Taher Assaf ***Udemy course : Python Bootcamp for Data Science 2021 Numpy Pandas & Seaborn *** 13.10 Bar Plots with Dataframes First we import pandas library: ###Code import pandas as pd ###Output _____no_output_____ ###Markdown Now we create a series using the fucntion **pd.Series()**: ###Code data = pd.Series([34,76,12,89,45], index= list('ABCDE')) data ###Output _____no_output_____ ###Markdown We can create a **bar plot** for this series usignt the function **plot.bar()**: ###Code data.plot.bar() ###Output _____no_output_____ ###Markdown We can **rotate** the labels of the x-axis using the argument **rot**We can change the **color** of the bars using the argument **color**We can aslo change the **transperancy** of the bars using the argument **alpha**: ###Code data.plot.bar(rot = 0, color = 'r', alpha = 0.7 ) ###Output _____no_output_____ ###Markdown To create a horizontal bar plot, we use the function **plot.barh()**: ###Code data.plot.barh(color = 'g', alpha = 0.7 ) ###Output _____no_output_____ ###Markdown For dataframes, lets first read this dataframe from a csv file using the function **pd.read_csv()**: ###Code frame1 = pd.read_csv('data/ex6.csv', index_col = 'branch number') frame1 ###Output _____no_output_____ ###Markdown To create a bar plot for the dataframe we use the same function which is **plot.bar()** ###Code frame1.plot.bar(rot = 0) ###Output _____no_output_____ ###Markdown To create a horizontal bar plot we use the function **plot.barh()**: ###Code frame1.plot.barh() ###Output _____no_output_____ ###Markdown To create stacked bar plot, we add the argument **stacked = True**: ###Code frame1.plot.bar(stacked = True, rot =0) ###Output _____no_output_____ ###Markdown We can also create a horizontal stacked bar plot, like this: ###Code frame1.plot.barh(stacked = True) ###Output _____no_output_____ ###Markdown Another option to create a bar plot is to use the **plot()** function and the argument **kind = 'bar'**: ###Code frame1.plot(kind = 'bar', rot =0) ###Output _____no_output_____
_downloads/ed53a4de288ff13451ef7f7685f5ef28/plot_gromov.ipynb
###Markdown Gromov-Wasserstein exampleThis example is designed to show how to use the Gromov-Wassertsein distancecomputation in POT. ###Code # Author: Erwan Vautier <[email protected]> # Nicolas Courty <[email protected]> # # License: MIT License import scipy as sp import numpy as np import matplotlib.pylab as pl from mpl_toolkits.mplot3d import Axes3D # noqa import ot ###Output _____no_output_____ ###Markdown Sample two Gaussian distributions (2D and 3D)---------------------------------------------The Gromov-Wasserstein distance allows to compute distances with samples thatdo not belong to the same metric space. For demonstration purpose, we sampletwo Gaussian distributions in 2- and 3-dimensional spaces. ###Code n_samples = 30 # nb samples mu_s = np.array([0, 0]) cov_s = np.array([[1, 0], [0, 1]]) mu_t = np.array([4, 4, 4]) cov_t = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) xs = ot.datasets.make_2D_samples_gauss(n_samples, mu_s, cov_s) P = sp.linalg.sqrtm(cov_t) xt = np.random.randn(n_samples, 3).dot(P) + mu_t ###Output _____no_output_____ ###Markdown Plotting the distributions-------------------------- ###Code fig = pl.figure() ax1 = fig.add_subplot(121) ax1.plot(xs[:, 0], xs[:, 1], '+b', label='Source samples') ax2 = fig.add_subplot(122, projection='3d') ax2.scatter(xt[:, 0], xt[:, 1], xt[:, 2], color='r') pl.show() ###Output _____no_output_____ ###Markdown Compute distance kernels, normalize them and then display--------------------------------------------------------- ###Code C1 = sp.spatial.distance.cdist(xs, xs) C2 = sp.spatial.distance.cdist(xt, xt) C1 /= C1.max() C2 /= C2.max() pl.figure() pl.subplot(121) pl.imshow(C1) pl.subplot(122) pl.imshow(C2) pl.show() ###Output _____no_output_____ ###Markdown Compute Gromov-Wasserstein plans and distance--------------------------------------------- ###Code p = ot.unif(n_samples) q = ot.unif(n_samples) gw0, log0 = ot.gromov.gromov_wasserstein( C1, C2, p, q, 'square_loss', verbose=True, log=True) gw, log = ot.gromov.entropic_gromov_wasserstein( C1, C2, p, q, 'square_loss', epsilon=5e-4, log=True, verbose=True) print('Gromov-Wasserstein distances: ' + str(log0['gw_dist'])) print('Entropic Gromov-Wasserstein distances: ' + str(log['gw_dist'])) pl.figure(1, (10, 5)) pl.subplot(1, 2, 1) pl.imshow(gw0, cmap='jet') pl.title('Gromov Wasserstein') pl.subplot(1, 2, 2) pl.imshow(gw, cmap='jet') pl.title('Entropic Gromov Wasserstein') pl.show() ###Output _____no_output_____
docs/level1/sdsdot.ipynb
###Markdown `sdsdot(N, SB, SX, INCX, SY, INCY)`Computes the dot product of a vector $\mathbf{x}$ and a vector $\mathbf{y}$ plus a constant $\beta$.Operates on single-precision real valued arrays.Input scalar $\beta$ is given by the double precision value `SA`.Input vector $\mathbf{x}$ is represented as a [strided array](../strided_arrays.ipynb) `SX`, spaced by `INCX`.Input vector $\mathbf{y}$ is represented as a [strided array](../strided_arrays.ipynb) `SY`, spaced by `INCY`.Both $\mathbf{x}$ and $\mathbf{y}$ are of size `N`. Example usage ###Code import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(''), "..", ".."))) import numpy as np from pyblas.level1 import sdsdot x = np.array([1, 2, 3], dtype=np.single) y = np.array([6, 7, 8], dtype=np.single) N = len(x) incx = 1 incy = 1 beta = 5 sdsdot(N, beta, x, incx, y, incy) ###Output _____no_output_____ ###Markdown Docstring ###Code help(sdsdot) ###Output Help on function sdsdot in module pyblas.level1.sdsdot: sdsdot(N, SB, SX, INCX, SY, INCY) Computes the dot-product of a vector x and a vector y plus a constant beta. Parameters ---------- N : int Number of elements in input vectors SB : numpy.single Specifies the scalar beta SX : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCX`)) INCX : int Storage spacing between elements of `SX` SY : numpy.ndarray A single precision real array, dimension (1 + (`N` - 1)*abs(`INCY`)) INCY : int Storage spacing between elements of `SY` Returns ------- numpy.single See Also -------- sdot : Single-precision real dot product dsdot : Single-precision real dot product (computed in double precision, returned as double precision) ddot : Double-precision real dot product cdotu : Single-precision complex dot product cdotc : Single-precision complex conjugate dot product zdotu : Double-precision complex dot product zdotc : Double-precision complex conjugate dot product Notes ----- Online PyBLAS documentation: https://nbviewer.jupyter.org/github/timleslie/pyblas/blob/main/docs/sdsdot.ipynb Reference BLAS documentation: https://github.com/Reference-LAPACK/lapack/blob/v3.9.0/BLAS/SRC/sdsdot.f Examples -------- >>> beta = 5 >>> x = np.array([1, 2, 3], dtype=np.single) >>> y = np.array([6, 7, 8], dtype=np.single) >>> N = len(x) >>> incx = 1 >>> incy = 1 >>> sdot(N, beta, x, incx, y, incy) 49.0 ###Markdown Source code ###Code sdsdot?? ###Output _____no_output_____
state_analysis.ipynb
###Markdown This notebook is intended to give visual representationa and analysis of COVID19 situtaion in India.We are analysing statewise cases in this notebook. We will first see the ongoing scenario in current week and then we will compare the overall performance of current week with the avg of total. This will give us an idea about whether we are proceesing in right direction or not. ###Code import json import requests from matplotlib import pyplot import datetime import numpy ###Output _____no_output_____ ###Markdown Gathering all the required data from apiFirst we will gather required data from api and then we will format that data in such way that we can easily play with it. ###Code # Getting json data from the api stateData = requests.get("https://api.covid19india.org/v4/timeseries.json").content with open('state.json', 'wb') as fw: fw.write(stateData) print(f"Data available for following states:\n {tuple(json.loads(stateData).keys())}") ###Output Data available for following states: ('AN', 'AP', 'AR', 'AS', 'BR', 'CH', 'CT', 'DL', 'DN', 'GA', 'GJ', 'HP', 'HR', 'JH', 'JK', 'KA', 'KL', 'LA', 'MH', 'ML', 'MN', 'MP', 'MZ', 'NL', 'OR', 'PB', 'PY', 'RJ', 'SK', 'TG', 'TN', 'TR', 'TT', 'UN', 'UP', 'UT', 'WB') ###Markdown Filter the data statewise and then store them in different variables. We will use these variables in representaion section. Available fields in retrieved data are : for last date - "confirmed", "deceased", "recovered", "tested" for total - "confirmed", "deceased", "migrated", "recovered", "tested" *But fields are only there when they correspond to some data* ###Code # Filtering data for a state bihar_data = json.loads(stateData)['BR'] dates = tuple(bihar_data['dates'].keys()) last_date = dates[-1] # if todays data are not updated then use last available data if 'delta' not in bihar_data['dates'][last_date].keys(): last_date = dates[-2] last_update = bihar_data['dates'][last_date]['delta'] total_summary = bihar_data['dates'][dates[-1]]['total'] # labels and colors to be used on plots labels = ('tested', 'confirmed', 'deceased', 'recovered') colors = ('blue', 'orange', 'red', 'green') # Getting data of last one week: last_week = dates[-7] if last_week[-1] != last_date: last_week = dates[-8:-1] last_week_data = tuple(bihar_data['dates'][x]['delta'] for x in last_week) # day wise last_week_update = {label: list(map(lambda x: x[label] , last_week_data))for label in labels} # lable wise # or we can use # last_week_update = {label :[x[label] for x in last_week_data] for label in labels } last_week_mmdd = tuple(x[-5:] for x in last_week) # dates in mm-dd format # Variable data which will be ploted variables = tuple(x for x in last_week_update.values()) ###Output _____no_output_____ ###Markdown Now its time to plot the data for visual analysisFirst we will plot data for last week. We are plotting here on linear plot and bar chart to analyse No. of tests, confirmed cases, deceased and recovered. ###Code fig, axs = pyplot.subplots(4, sharex = True) fig.suptitle('COVID19 past week stats') for i in range(len(labels)): axs[i].plot(last_week_mmdd, variables[i], label=labels[i], color=colors[i]) axs[i].legend(loc='best') pyplot.show() # All data on a single plot fig, ax = pyplot.subplots() for i in range(len(labels)): ax.plot(last_week_mmdd, variables[i], label=labels[i], color=colors[i]) ax.legend(loc='best') ax.set_xlabel("Dates") ax.set_ylabel("Cases") ax.set_yscale('log') # log scaling for better analysis on single plot ax.set_title("COVID19 past week stats") pyplot.show() # Bar chart pyplot.figure(figsize=(10,20)) fig, axs = pyplot.subplots(2,2, sharex=True) for (i,j), _ in numpy.ndenumerate(axs): bar = axs[i][j].bar(last_week_mmdd, variables[i*2+j], color=colors[i*2+j]) axs[i][j].set_title(labels[i*2+j]) axs[i][j].tick_params(axis='x', which='major', labelsize=7) pyplot.show() ###Output _____no_output_____ ###Markdown comparision between last week data and total till nowNow we will compare the performance of this week with total cases till now. ###Code total_lw = tuple(sum(label) for label in variables) total_now = tuple(total_summary[label] for label in labels) total_lw, total_now # set width of bar barWidth = 0.25 # Set position of bar on X axis ind1 = numpy.arange(len(bars1)) ind2 = [x + barWidth for x in r1] # Make the plot pyplot.figure(figsize=(10,15)) fig, ax = pyplot.subplots() ax.bar(r1, total_lw, color='red', width=barWidth, edgecolor='white', label='this week') ax.bar(r2, total_now, color='black', width=barWidth, edgecolor='white', label='total') # Add xticks on the middle of the group bars ax.set_xlabel('group', fontweight='bold') pyplot.xticks(ind1 + barWidth / 2, labels) # Create legend & Show graphic ax.legend(loc='best') pyplot.show() # Pie chart # Set which pie to pop out and how much explode = (0, 0, 0.5, 0) fig, axs = pyplot.subplots(1,2) axs[0].pie(total_lw, explode=explode, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, pctdistance=0.8, labeldistance=1.1) axs[0].axis('equal') axs[0].set_title("Last week cases") axs[1].pie(total_now, explode=explode, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, pctdistance=0.8, labeldistance=1.1) axs[1].axis('equal') axs[1].set_title("Total cases now") pyplot.tight_layout() pyplot.legend(labels=labels, loc='best') pyplot.show() # Scatter plot fig, ax = pyplot.subplots() ax.scatter(labels, total_lw, alpha=0.5, color='red') ax.scatter(labels, total_now, alpha=0.5, color='black') ax.set_yscale('log') ax.set_xlabel(r'Groups', fontsize=25) ax.set_ylabel(r'Cases', fontsize=15) fig.suptitle('COVID case comparision') pyplot.show() ###Output _____no_output_____
API workshop #1 - Basics.ipynb
###Markdown PDBe API Training=========This interactive Python notebook will guide you through various ways of programmatically accessing Protein Data Bank in Europe (PDBe) data using REST APIThe REST API is a programmatic way to obtain information from the PDB and EMDB. You can access details about:* sample* experiment* models* compounds* cross-references* publications * quality * assemblies * and more...For more information, visit http://www.ebi.ac.uk/pdbe/pdbe-rest-api Notebook 1This notebook is the first in the training material series. It aims to lay down the foundation for understanding how users can interact with the PDBe REST API using Python3. 1) Making imports and setting variablesFirst, we import some packages that we will use, and set some variables.Note: Full list of valid URLs is available from http://www.ebi.ac.uk/pdbe/api/doc/ ###Code import re import requests base_url = "https://www.ebi.ac.uk/pdbe/" api_base = base_url + "api/" summary_url = api_base + 'pdb/entry/summary/' ###Output _____no_output_____ ###Markdown 2) Basic examplesWe will start with some very basic examples and operations. 2.1) Iterating through lists ###Code # This is a simple list with 2 PDB entry IDs basic_pdb_list = ["1cbs", "3bow"] # Iterating through this list (or any other lists) # can be done with a simple function, such as: def iterate_list(my_list): """ This function will iterate through a list, and print each item :param my_list: List :return: None """ for item in my_list: print(item) # Calling the function: print("Iterating through PDB id list") print() iterate_list(basic_pdb_list) ###Output Iterating through PDB id list 1cbs 3bow ###Markdown 2.2) Getting a specific item from a listGetting a specific element of a list can be done using a function such as this below.Please note that indices start from 0 in Python, so the first element of a list has an index of 0 ###Code def get_item(index, my_list): """ This function will get an item from a list using the index of the item :param index: Integer :param my_list: List :return: String """ return my_list[index] # Calling the function for the first element first = get_item(0, basic_pdb_list) print("First PDB id: %s" % first) # Calling the function for the second element second = get_item(1, basic_pdb_list) print("Second PDB id: %s" % second) ###Output First PDB id: 1cbs Second PDB id: 3bow ###Markdown 2.3) Getting a value for a key from a dictionaryDictionaries are data structures with unique keys and corresponding values.PDBe API calls generally return data in the form of dictionaries, i.e. collections of key and value pairsGetting values from a dictionary can be done either by directly accessing the value using the key, or by using a simple function, such as below. ###Code simple_dictionary = {"key": "value"} # Getting value directly from a dictionary using its key simple_dictionary["key"] # Basic example of a dictionary with two keys and two # corresponding values basic_pdb_dictionary = { "pdb_id": "1cbs", "experimental_method": "X-ray diffraction", } # Getting value directly using key print("Getting value directly: %s" % basic_pdb_dictionary["pdb_id"]) # Getting value using simple function def get_value(key, my_dictionary): """ Gets the value that corresponds to a key in a dictionary :param key: String, :param my_dictionary: Dict :return: String """ return(my_dictionary[key]) print("Getting value using function: %s" % get_value("pdb_id", basic_pdb_dictionary)) ###Output Getting value directly: 1cbs Getting value using function: 1cbs ###Markdown 3) Creating a mock PDBe entryThe dictionary below will serve as an offline example of what an actual API call would return for the entry "1CBS" when querying for the entry summaryYou can try to make this call from your browser by copy/pasting the URL below:https://www.ebi.ac.uk/pdbe/api/pdb/entry/summary/1cbs ###Code mock_entry_summary = { "1cbs": [ { "related_structures": [ ], "split_entry": [ ], "title": "CRYSTAL STRUCTURE OF CELLULAR RETINOIC-ACID-BINDING PROTEINS I AND II IN COMPLEX WITH ALL-TRANS-RETINOIC ACID AND A SYNTHETIC RETINOID", "release_date": "19950126", "experimental_method": [ "X-ray diffraction" ], "experimental_method_class": [ "x-ray" ], "revision_date": "20110713", "entry_authors": [ "Kleywegt, G.J.", "Bergfors, T.", "Jones, T.A." ], "deposition_site": "null", "number_of_entities": { "polypeptide": 1, "dna": 0, "ligand": 1, "dna/rna": 0, "rna": 0, "sugar": 0, "water": 1, "other": 0 }, "processing_site": "null", "deposition_date": "19940928", "assemblies": [ { "assembly_id": "1", "form": "homo", "preferred": "true", "name": "monomer" } ] } ] } ###Output _____no_output_____ ###Markdown As you can see, the data is structured as a JSON dictionary, with key and value pairs, for example: "revision_data": "20110713"We will use this mock data for our first few operations. 4) Getting entry from the mock PDB dataNow let's try to get entries using a simple function!We will first use the mock PDB data to perform our GET function (and call our get_value function) ###Code def get_entry(pdb_id): """ This function tries to get the data that corresponds to a PDB id If the entry id is not found, it print an error message and returns None :param pdb_id: String :return: Dict or None """ try: # This next line will use our previously written # get_value() function return {pdb_id: get_value(pdb_id, mock_entry_summary)} except KeyError as error: print("Key error: %s" % error) return None # Try to get PDB entry "3bow" print("Trying with PDB id which is not in the dictionary:") print(get_entry("3bow")) print() # Try to get PDB entry "1cbs" print("Trying with PDB id which is in the dictionary:") print(get_entry("1cbs")) ###Output Trying with PDB id which is not in the dictionary: Key error: '3bow' None Trying with PDB id which is in the dictionary: {'1cbs': [{'related_structures': [], 'split_entry': [], 'title': 'CRYSTAL STRUCTURE OF CELLULAR RETINOIC-ACID-BINDING PROTEINS I AND II IN COMPLEX WITH ALL-TRANS-RETINOIC ACID AND A SYNTHETIC RETINOID', 'release_date': '19950126', 'experimental_method': ['X-ray diffraction'], 'experimental_method_class': ['x-ray'], 'revision_date': '20110713', 'entry_authors': ['Kleywegt, G.J.', 'Bergfors, T.', 'Jones, T.A.'], 'deposition_site': 'null', 'number_of_entities': {'polypeptide': 1, 'dna': 0, 'ligand': 1, 'dna/rna': 0, 'rna': 0, 'sugar': 0, 'water': 1, 'other': 0}, 'processing_site': 'null', 'deposition_date': '19940928', 'assemblies': [{'assembly_id': '1', 'form': 'homo', 'preferred': 'true', 'name': 'monomer'}]}]} ###Markdown 5) Getting summary information for an entry (still using mock data)Let's write a function that can be used to write a brief summary of a PDB entryPlease note, that certain calls could return multiple PDB entries (i.e. POST calls), but the GET summary call we use in this exercise will always return only one PDB entry ###Code def make_summary(data): """ This function creates a summary for a PDB entry by getting data for an entry, and extracting pieces of information :param data: Dict :return: String """ pdb_id = "" # Certain calls could return multiple PDB entries, # but the GET summary call we use in this exercise # will always return only one PDB entry for key in data.keys(): pdb_id = key # The data is a list of dictionaries, and for the summary information, # it is always the first element of the list entry = get_item(0, data[pdb_id]) # Getting the title of the entry title = get_value("title", entry) # Getting the release date of the entry release_date = get_value("release_date", entry) # Formatting the entry to make it more user-friendly formatted_release_date = "%s/%s/%s" % ( release_date[:4], release_date[4:6], release_date[6:]) # Getting the experimental methods # Note that there can be multiple methods, so this is a list that # needs to be iterated experimental_methods = "" for experimental_method in get_value("experimental_method", entry): if experimental_methods: experimental_methods += " and " experimental_methods += experimental_method # Creating the summary text using all the extracted # information summary = "Entry is titled \"%s\" and was released on %s." % ( title, formatted_release_date) summary += " This entry was determined using %s." % experimental_methods return summary print(make_summary(get_entry("1cbs"))) ###Output Entry is titled "CRYSTAL STRUCTURE OF CELLULAR RETINOIC-ACID-BINDING PROTEINS I AND II IN COMPLEX WITH ALL-TRANS-RETINOIC ACID AND A SYNTHETIC RETINOID" and was released on 1995/01/26. This entry was determined using X-ray diffraction. ###Markdown 6) Switching to real API dataFinally, we will start using the PDBe API to make real calls to get data for any PDB entry of interestFirst, we need a function to communicate with the APIMaking calls over the network is more expensive than getting data from a mock dictionary, so we will include an additional check before making the call: we will check if the PDB id in the pdb_id argument is a valid id that matches the PDB id pattern ###Code def get_entry_from_api(pdb_id, api_url): """ This function will make a call to the PDBe API using the PDB id and API url provided as arguments :param pdb_id: String, :param api_url: String :return: Dict or None """ if not re.match("[0-9][A-Za-z][A-Za-z0-9]{2}", pdb_id): print("Invalid PDB id") return None # Make a GET call to the API URL get_request = requests.get(url=api_url+pdb_id) if get_request.status_code == 200: # If there is data returned (with HTML status code 200) # then return the data in JSON format return get_request.json() else: # If there is no data, print status code and response print(get_request.status_code, get_request.text) return None # Try our GET function with an invalid PDB id print("Trying to GET data with invalid PDB id:") print(get_entry_from_api("whatever", summary_url)) print() print("Trying to GET data with valid PDB id:") print(get_entry_from_api("1cbs", summary_url)) # As you can hopefully see, the data displayed is very similar to # what we had in the mock data in previous sections - however, # this is actual data coming from the PDBe API ###Output Trying to GET data with invalid PDB id: Invalid PDB id None Trying to GET data with valid PDB id: {'1cbs': [{'related_structures': [], 'split_entry': [], 'title': 'CRYSTAL STRUCTURE OF CELLULAR RETINOIC-ACID-BINDING PROTEINS I AND II IN COMPLEX WITH ALL-TRANS-RETINOIC ACID AND A SYNTHETIC RETINOID', 'release_date': '19950126', 'experimental_method': ['X-ray diffraction'], 'experimental_method_class': ['x-ray'], 'revision_date': '20110713', 'entry_authors': ['Kleywegt, G.J.', 'Bergfors, T.', 'Jones, T.A.'], 'deposition_site': None, 'number_of_entities': {'polypeptide': 1, 'dna': 0, 'ligand': 1, 'dna/rna': 0, 'rna': 0, 'sugar': 0, 'water': 1, 'other': 0}, 'processing_site': None, 'deposition_date': '19940928', 'assemblies': [{'assembly_id': '1', 'form': 'homo', 'preferred': True, 'name': 'monomer'}]}]} ###Markdown As you can hopefully see, the data displayed is very similar to what we had in the mock data in previous sections - however, this is actual data coming from the PDBe API 7) Trying the make_summary() function with real API dataTo wrap up this first interactive notebook, we will try to use our make_summary() function on real API data - All we need to do is to change the argument (data) we are passing into it ###Code print("Example #1") print(make_summary(get_entry_from_api("3bow", summary_url))) print() print("Example #2") print(make_summary(get_entry_from_api("2klm", summary_url))) ###Output Example #1 Entry is titled "Structure of M-calpain in complex with Calpastatin" and was released on 2008/11/25. This entry was determined using X-ray diffraction. Example #2 Entry is titled "Solution Structure of L11 with SAXS and RDC" and was released on 2009/10/06. This entry was determined using Solution NMR and X-ray solution scattering.
example/stt-ctc-model/load-stt-ctc-model.ipynb
###Markdown Speech-to-Text CTC Encoder model + CTC loss This tutorial is available as an IPython notebook at [malaya-speech/example/stt-ctc-model](https://github.com/huseinzol05/malaya-speech/tree/master/example/stt-ctc-model). This module is not language independent, so it not save to use on different languages. Pretrained models trained on hyperlocal languages. This is an application of malaya-speech Pipeline, read more about malaya-speech Pipeline at [malaya-speech/example/pipeline](https://github.com/huseinzol05/malaya-speech/tree/master/example/pipeline). ###Code import malaya_speech import numpy as np from malaya_speech import Pipeline ###Output _____no_output_____ ###Markdown List available CTC model ###Code malaya_speech.stt.available_ctc() ###Output _____no_output_____ ###Markdown Google Speech-to-Text accuracyWe tested on the same malay dataset to compare malaya-speech models and Google Speech-to-Text, check the notebook at [benchmark-google-speech-malay-dataset.ipynb](https://github.com/huseinzol05/malaya-speech/blob/master/pretrained-model/prepare-stt/benchmark-google-speech-malay-dataset.ipynb). ###Code malaya_speech.stt.google_accuracy ###Output _____no_output_____ ###Markdown **Again, even some models beat google speech-to-text accuracy for CER, we really need to be skeptical with the score, the test set and postprocessing might favoured for malaya-speech**. Load CTC model```pythondef deep_ctc( model: str = 'wav2vec2-conformer', quantized: bool = False, **kwargs): """ Load Encoder-Transducer ASR model. Parameters ---------- model : str, optional (default='conformer') Model architecture supported. Allowed values: * ``'wav2vec2-conformer'`` - Finetuned Wav2Vec2 Conformer. * ``'wav2vec2-conformer-large'`` - Finetuned Wav2Vec2 Conformer LARGE. quantized : bool, optional (default=False) if True, will load 8-bit quantized model. Quantized model not necessary faster, totally depends on the machine. Returns ------- result : malaya_speech.model.tf.CTC class """``` ###Code model = malaya_speech.stt.deep_ctc(model = 'wav2vec2-conformer-large') subwords_model = malaya_speech.stt.deep_ctc(model = 'hubert-conformer-subword') ###Output _____no_output_____ ###Markdown Load Quantized deep modelTo load 8-bit quantized model, simply pass `quantized = True`, default is `False`.We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. ###Code quantized_model = malaya_speech.stt.deep_ctc(model = 'wav2vec2-conformer-large', quantized = True) ###Output WARNING:root:Load quantized model will cause accuracy drop. ###Markdown Load sample ###Code ceramah, sr = malaya_speech.load('speech/khutbah/wadi-annuar.wav') record1, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-36-06_294832.wav') record2, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-40-56_929661.wav') import IPython.display as ipd ipd.Audio(ceramah, rate = sr) ###Output _____no_output_____ ###Markdown As we can hear, the speaker speaks in kedahan dialects plus some arabic words, let see how good our model is. ###Code ipd.Audio(record1, rate = sr) ipd.Audio(record2, rate = sr) ###Output _____no_output_____ ###Markdown Predict using default CTCdefault CTC decoder is from Tensorflow. We can choose,1. `greedy` decoder, automatically `beam_size` will become 1.2. `beam` decoder, by default `beam_size` is 100, feel free to edit it.```pythondef predict( self, inputs, decoder: str = 'beam', beam_size: int = 100, **kwargs): """ Transcribe inputs, will return list of strings. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. decoder: str, optional (default='beam') decoder mode, allowed values: * ``'greedy'`` - greedy decoder. * ``'beam'`` - beam decoder. beam_size: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` ###Code model.predict([ceramah, record1, record2]) quantized_model.predict([ceramah, record1, record2]) subwords_model.predict([ceramah, record1, record2]) ###Output _____no_output_____ ###Markdown Predict using LM CTC```pythondef predict_lm(self, inputs, lm, beam_size: int = 100, **kwargs): """ Transcribe inputs using Beam Search + LM, will return list of strings. This method will not able to utilise batch decoding, instead will do loop to decode for each elements. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. lm: ctc_decoders.Scorer Returned from `malaya_speech.stt.language_model()`. beam_size: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` List available Language ModelWe provided language model for our ASR CTC models, ###Code malaya_speech.stt.available_language_model() ###Output _____no_output_____ ###Markdown Feel free to use your own language model, generated from `kenlm` library, steps to reproduce can check at https://malaya-speech.readthedocs.io/en/latest/ctc-language-model.htmlBuild-custom-Language-Model Load Language Model```pythondef language_model( model: str = 'bahasa', alpha: float = 0.5, beta: float = 1.0, **kwargs): """ Load KenLM language model. Parameters ---------- model : str, optional (default='bahasa') Model architecture supported. Allowed values: * ``'bahasa'`` - Gathered from malaya-speech ASR bahasa transcript. * ``'bahasa-news'`` - Gathered from malaya-speech ASR bahasa transcript + Bahasa News (Random sample 300k sentences). * ``'bahasa-combined'`` - Gathered from malaya-speech ASR bahasa transcript + Bahasa News (Random sample 300k sentences) + Bahasa Wikipedia (Random sample 150k sentences). * ``'redape-community'`` - Mirror for https://github.com/redapesolutions/suara-kami-community alpha: float, optional (default=0.5) score = alpha * np.log(lm) + beta * np.log(word_cnt), increase will put more bias on lm score computed by kenlm. beta: float, optional (beta=1.0) score = alpha * np.log(lm) + beta * np.log(word_cnt), increase will put more bias on word count. Returns ------- result : ctc_decoders.Scorer """```**Subwords based models not able to use Language Model decoder**. ###Code lm = malaya_speech.stt.language_model(model = 'redape-community') model.predict_lm([ceramah, record1, record2], lm) quantized_model.predict_lm([ceramah, record1, record2], lm) ###Output _____no_output_____ ###Markdown Speech-to-Text CTC Encoder model + CTC loss This tutorial is available as an IPython notebook at [malaya-speech/example/stt-ctc-model](https://github.com/huseinzol05/malaya-speech/tree/master/example/stt-ctc-model). This module is not language independent, so it not save to use on different languages. Pretrained models trained on hyperlocal languages. This is an application of malaya-speech Pipeline, read more about malaya-speech Pipeline at [malaya-speech/example/pipeline](https://github.com/huseinzol05/malaya-speech/tree/master/example/pipeline). ###Code import malaya_speech import numpy as np from malaya_speech import Pipeline ###Output _____no_output_____ ###Markdown List available CTC model ###Code malaya_speech.stt.available_ctc() ###Output _____no_output_____ ###Markdown Google Speech-to-Text accuracyWe tested on the same malay dataset to compare malaya-speech models and Google Speech-to-Text, check the notebook at [benchmark-google-speech-malay-dataset.ipynb](https://github.com/huseinzol05/malaya-speech/blob/master/pretrained-model/prepare-stt/benchmark-google-speech-malay-dataset.ipynb). ###Code malaya_speech.stt.google_accuracy ###Output _____no_output_____ ###Markdown **Again, even some models beat google speech-to-text accuracy for CER, we really need to be skeptical with the score, the test set and postprocessing might favoured for malaya-speech**. Load CTC model```pythondef deep_ctc( model: str = 'hubert-conformer', quantized: bool = False, **kwargs): """ Load Encoder-Transducer ASR model. Parameters ---------- model : str, optional (default='hubert-conformer') Model architecture supported. Allowed values: * ``'hubert-conformer-tiny'`` - Finetuned HuBERT Conformer TINY. * ``'hubert-conformer'`` - Finetuned HuBERT Conformer. * ``'hubert-conformer-large'`` - Finetuned HuBERT Conformer LARGE. * ``'hubert-conformer-large-3mixed'`` - Finetuned HuBERT Conformer LARGE for (Malay + Singlish + Mandarin) languages. quantized : bool, optional (default=False) if True, will load 8-bit quantized model. Quantized model not necessary faster, totally depends on the machine. Returns ------- result : malaya_speech.model.tf.Wav2Vec2_CTC class """``` ###Code model = malaya_speech.stt.deep_ctc(model = 'hubert-conformer-large') ###Output _____no_output_____ ###Markdown Load Quantized deep modelTo load 8-bit quantized model, simply pass `quantized = True`, default is `False`.We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. ###Code quantized_model = malaya_speech.stt.deep_ctc(model = 'hubert-conformer-large', quantized = True) ###Output WARNING:root:Load quantized model will cause accuracy drop. ###Markdown Load sample ###Code ceramah, sr = malaya_speech.load('speech/khutbah/wadi-annuar.wav') record1, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-36-06_294832.wav') record2, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-40-56_929661.wav') import IPython.display as ipd ipd.Audio(ceramah, rate = sr) ###Output _____no_output_____ ###Markdown As we can hear, the speaker speaks in kedahan dialects plus some arabic words, let see how good our model is. ###Code ipd.Audio(record1, rate = sr) ipd.Audio(record2, rate = sr) ###Output _____no_output_____ ###Markdown Predict using greedy decoder```pythondef greedy_decoder(self, inputs): """ Transcribe inputs using greedy decoder. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. Returns ------- result: List[str] """``` ###Code %%time model.greedy_decoder([ceramah, record1, record2]) %%time quantized_model.greedy_decoder([ceramah, record1, record2]) ###Output CPU times: user 16.7 s, sys: 5.5 s, total: 22.2 s Wall time: 4.15 s ###Markdown Predict using beam decoder```pythondef beam_decoder(self, inputs, beam_width: int = 100): """ Transcribe inputs using beam decoder. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. beam_width: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` ###Code %%time model.beam_decoder([ceramah, record1, record2]) %%time quantized_model.beam_decoder([ceramah, record1, record2]) ###Output CPU times: user 26.5 s, sys: 11 s, total: 37.5 s Wall time: 19.3 s ###Markdown Predict logits```pythondef predict_logits(self, inputs): """ Predict logits from inputs. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. Returns ------- result: List[np.array] """``` ###Code %%time logits = model.predict_logits([ceramah, record1, record2]) logits, logits[0].shape, logits[1].shape ###Output _____no_output_____ ###Markdown Speech-to-Text CTC Encoder model + CTC loss This tutorial is available as an IPython notebook at [malaya-speech/example/stt-ctc-model](https://github.com/huseinzol05/malaya-speech/tree/master/example/stt-ctc-model). This module is not language independent, so it not save to use on different languages. Pretrained models trained on hyperlocal languages. This is an application of malaya-speech Pipeline, read more about malaya-speech Pipeline at [malaya-speech/example/pipeline](https://github.com/huseinzol05/malaya-speech/tree/master/example/pipeline). ###Code import malaya_speech import numpy as np from malaya_speech import Pipeline ###Output _____no_output_____ ###Markdown List available CTC model ###Code malaya_speech.stt.available_ctc() ###Output _____no_output_____ ###Markdown Google Speech-to-Text accuracyWe tested on the same malay dataset to compare malaya-speech models and Google Speech-to-Text, check the notebook at [benchmark-google-speech-malay-dataset.ipynb](https://github.com/huseinzol05/malaya-speech/blob/master/pretrained-model/prepare-stt/benchmark-google-speech-malay-dataset.ipynb). ###Code malaya_speech.stt.google_accuracy ###Output _____no_output_____ ###Markdown **Again, even some models beat google speech-to-text accuracy for CER, we really need to be skeptical with the score, the test set and postprocessing might favoured for malaya-speech**. Load CTC model```pythondef deep_ctc( model: str = 'hubert-conformer', quantized: bool = False, **kwargs): """ Load Encoder-CTC ASR model. Parameters ---------- model : str, optional (default='hubert-conformer') Model architecture supported. Allowed values: * ``'hubert-conformer-tiny'`` - Finetuned HuBERT Conformer TINY. * ``'hubert-conformer'`` - Finetuned HuBERT Conformer. * ``'hubert-conformer-large'`` - Finetuned HuBERT Conformer LARGE. * ``'hubert-conformer-large-3mixed'`` - Finetuned HuBERT Conformer LARGE for (Malay + Singlish + Mandarin) languages. * ``'best-rq-conformer-tiny'`` - Finetuned BEST-RQ Conformer TINY. * ``'best-rq-conformer'`` - Finetuned BEST-RQ Conformer. * ``'best-rq-conformer-large'`` - Finetuned BEST-RQ Conformer LARGE. quantized : bool, optional (default=False) if True, will load 8-bit quantized model. Quantized model not necessary faster, totally depends on the machine. Returns ------- result : malaya_speech.model.tf.Wav2Vec2_CTC class """``` ###Code model = malaya_speech.stt.deep_ctc(model = 'hubert-conformer-large') ###Output _____no_output_____ ###Markdown Load Quantized deep modelTo load 8-bit quantized model, simply pass `quantized = True`, default is `False`.We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. ###Code quantized_model = malaya_speech.stt.deep_ctc(model = 'hubert-conformer-large', quantized = True) ###Output WARNING:root:Load quantized model will cause accuracy drop. ###Markdown Load sample ###Code ceramah, sr = malaya_speech.load('speech/khutbah/wadi-annuar.wav') record1, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-36-06_294832.wav') record2, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-40-56_929661.wav') import IPython.display as ipd ipd.Audio(ceramah, rate = sr) ###Output _____no_output_____ ###Markdown As we can hear, the speaker speaks in kedahan dialects plus some arabic words, let see how good our model is. ###Code ipd.Audio(record1, rate = sr) ipd.Audio(record2, rate = sr) ###Output _____no_output_____ ###Markdown Predict using greedy decoder```pythondef greedy_decoder(self, inputs): """ Transcribe inputs using greedy decoder. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. Returns ------- result: List[str] """``` ###Code %%time model.greedy_decoder([ceramah, record1, record2]) %%time quantized_model.greedy_decoder([ceramah, record1, record2]) ###Output CPU times: user 16.7 s, sys: 5.5 s, total: 22.2 s Wall time: 4.15 s ###Markdown Predict using beam decoder```pythondef beam_decoder(self, inputs, beam_width: int = 100): """ Transcribe inputs using beam decoder. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. beam_width: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` ###Code %%time model.beam_decoder([ceramah, record1, record2]) %%time quantized_model.beam_decoder([ceramah, record1, record2]) ###Output CPU times: user 26.5 s, sys: 11 s, total: 37.5 s Wall time: 19.3 s ###Markdown Predict logits```pythondef predict_logits(self, inputs): """ Predict logits from inputs. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.Frame]. Returns ------- result: List[np.array] """``` ###Code %%time logits = model.predict_logits([ceramah, record1, record2]) logits, logits[0].shape, logits[1].shape ###Output _____no_output_____ ###Markdown Speech-to-Text CTC Encoder model + CTC loss This tutorial is available as an IPython notebook at [malaya-speech/example/stt-ctc-model](https://github.com/huseinzol05/malaya-speech/tree/master/example/stt-ctc-model). This module is not language independent, so it not save to use on different languages. Pretrained models trained on hyperlocal languages. This is an application of malaya-speech Pipeline, read more about malaya-speech Pipeline at [malaya-speech/example/pipeline](https://github.com/huseinzol05/malaya-speech/tree/master/example/pipeline). ###Code import malaya_speech import numpy as np from malaya_speech import Pipeline ###Output _____no_output_____ ###Markdown List available CTC model ###Code malaya_speech.stt.available_ctc() ###Output _____no_output_____ ###Markdown Load CTC model```pythondef deep_ctc(model: str = 'jasper', quantized: bool = False, **kwargs): """ Load Encoder-CTC ASR model. Parameters ---------- model : str, optional (default='jasper') Model architecture supported. Allowed values: * ``'mini-jasper'`` - Small-factor NVIDIA Jasper, https://arxiv.org/pdf/1904.03288.pdf * ``'medium-jasper'`` - Medium-factor NVIDIA Jasper, https://arxiv.org/pdf/1904.03288.pdf * ``'jasper'`` - NVIDIA Jasper, https://arxiv.org/pdf/1904.03288.pdf quantized : bool, optional (default=False) if True, will load 8-bit quantized model. Quantized model not necessary faster, totally depends on the machine. Returns ------- result : malaya_speech.supervised.stt.ctc_load function """``` ###Code model = malaya_speech.stt.deep_ctc(model = 'mini-jasper') ###Output WARNING:tensorflow:From /Users/huseinzolkepli/Documents/malaya-speech/malaya_speech/utils/__init__.py:66: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead. WARNING:tensorflow:From /Users/huseinzolkepli/Documents/malaya-speech/malaya_speech/utils/__init__.py:68: The name tf.GraphDef is deprecated. Please use tf.compat.v1.GraphDef instead. WARNING:tensorflow:From /Users/huseinzolkepli/Documents/malaya-speech/malaya_speech/utils/__init__.py:61: The name tf.InteractiveSession is deprecated. Please use tf.compat.v1.InteractiveSession instead. ###Markdown Load Quantized deep modelTo load 8-bit quantized model, simply pass `quantized = True`, default is `False`.We can expect slightly accuracy drop from quantized model, and not necessary faster than normal 32-bit float model, totally depends on machine. ###Code quantized_model = malaya_speech.stt.deep_ctc(model = 'mini-jasper', quantized = True) ###Output WARNING:root:Load quantized model will cause accuracy drop. /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s). warnings.warn('An interactive session is already active. This can ' ###Markdown Load sample ###Code ceramah, sr = malaya_speech.load('speech/khutbah/wadi-annuar.wav') record1, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-36-06_294832.wav') record2, sr = malaya_speech.load('speech/record/savewav_2020-11-26_22-40-56_929661.wav') import IPython.display as ipd ipd.Audio(ceramah, rate = sr) ###Output _____no_output_____ ###Markdown As we can hear, the speaker speaks in kedahan dialects plus some arabic words, let see how good our model is. ###Code ipd.Audio(record1, rate = sr) ipd.Audio(record2, rate = sr) ###Output _____no_output_____ ###Markdown Predict using default CTCdefault CTC decoder is from Tensorflow. We can choose,1. `greedy` decoder, automatically `beam_size` will become 1.2. `beam` decoder, by default `beam_size` is 100, feel free to edit it.```pythondef predict( self, inputs, decoder: str = 'beam', beam_size: int = 100, **kwargs): """ Transcribe inputs, will return list of strings. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.FRAME]. decoder: str, optional (default='beam') decoder mode, allowed values: * ``'greedy'`` - greedy decoder. * ``'beam'`` - beam decoder. beam_size: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` ###Code model.predict([ceramah, record1, record2]) quantized_model.predict([ceramah, record1, record2]) ###Output _____no_output_____ ###Markdown Predict using LM CTC```pythondef predict_lm(self, inputs, lm, beam_size: int = 100, **kwargs): """ Transcribe inputs using Beam Search + LM, will return list of strings. This method will not able to utilise batch decoding, instead will do loop to decode for each elements. Parameters ---------- input: List[np.array] List[np.array] or List[malaya_speech.model.frame.FRAME]. lm: ctc_decoders.Scorer Returned from `malaya_speech.stt.language_model()`. beam_size: int, optional (default=100) beam size for beam decoder. Returns ------- result: List[str] """``` List available Language ModelWe provided language model for our ASR CTC models, ###Code malaya_speech.stt.available_language_model() ###Output _____no_output_____ ###Markdown Feel free to use your own language model, generated from `kenlm` library, steps to reproduce can check at https://malaya-speech.readthedocs.io/en/latest/ctc-language-model.htmlBuild-custom-Language-Model Load Language Model```pythondef language_model( model: str = 'malaya-speech', alpha: float = 2.5, beta: float = 0.3, **kwargs): """ Load KenLM language model. Parameters ---------- model : str, optional (default='malaya-speech') Model architecture supported. Allowed values: * ``'malaya-speech'`` - Gathered from malaya-speech ASR transcript. * ``'malaya-speech-wikipedia'`` - Gathered from malaya-speech ASR transcript + Wikipedia (Random sample 300k sentences). * ``'local'`` - Gathered from IIUM Confession. * ``'wikipedia'`` - Gathered from malay Wikipedia. alpha: float, optional (default=2.5) score = alpha * np.log(lm) + beta * np.log(word_cnt), increase will put more bias on lm score computed by kenlm. beta: float, optional (beta=0.3) score = alpha * np.log(lm) + beta * np.log(word_cnt), increase will put more bias on word count. Returns ------- result : Tuple[ctc_decoders.Scorer, List[str]] Tuple of ctc_decoders.Scorer and vocab. """``` ###Code lm = malaya_speech.stt.language_model(model = 'malaya-speech-wikipedia') model.predict_lm([ceramah, record1, record2], lm) quantized_model.predict_lm([ceramah, record1, record2], lm) ###Output _____no_output_____