text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# LinearSVR with MinMaxScaler & Power Transformer This Code template is for the Classification task using Support Vector Regressor (SVR) based on the Support Vector Machine algorithm with Power Transformer as Feature Transformation Technique and MinMaxScaler for Feature Scaling in a pipeline. ### Required Packages ``` import warnings import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as se from sklearn.preprocessing import PowerTransformer, MinMaxScaler from sklearn.pipeline import make_pipeline from sklearn.model_selection import train_test_split from imblearn.over_sampling import RandomOverSampler from sklearn.svm import LinearSVR from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error warnings.filterwarnings('ignore') ``` ### Initialization Filepath of CSV file ``` #filepath file_path="" ``` List of features which are required for model training . ``` #x_values features=[] ``` Target feature for prediction. ``` #y_values target='' ``` ### Data fetching Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. ``` df=pd.read_csv(file_path) df.head() ``` ### Feature Selections It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model. We will assign all the required input features to X and target/outcome to Y. ``` X=df[features] Y=df[target] ``` ### Data preprocessing Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. ``` def NullClearner(df): if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])): df.fillna(df.mean(),inplace=True) return df elif(isinstance(df, pd.Series)): df.fillna(df.mode()[0],inplace=True) return df else:return df def EncodeX(df): return pd.get_dummies(df) ``` Calling preprocessing functions on the feature and target set. ``` x=X.columns.to_list() for i in x: X[i]=NullClearner(X[i]) X=EncodeX(X) Y=NullClearner(Y) X.head() ``` #### Correlation Map In order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. ``` f,ax = plt.subplots(figsize=(18, 18)) matrix = np.triu(X.corr()) se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix) plt.show() ``` ### Data Splitting The train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data. ``` x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123)#performing datasplitting ``` ### Model Support vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection. A Support Vector Machine is a discriminative classifier formally defined by a separating hyperplane. In other terms, for a given known/labelled data points, the SVM outputs an appropriate hyperplane that classifies the inputted new cases based on the hyperplane. In 2-Dimensional space, this hyperplane is a line separating a plane into two segments where each class or group occupied on either side. LinearSVR is similar to SVR with kernel=’linear’. It has more flexibility in the choice of tuning parameters and is suited for large samples. #### Feature Transformation PowerTransformer applies a power transform featurewise to make data more Gaussian-like. Power transforms are a family of parametric, monotonic transformations that are applied to make data more Gaussian-like. This is useful for modeling issues related to heteroscedasticity (non-constant variance), or other situations where normality is desired. For more information... [click here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PowerTransformer.html) #### Model Tuning Parameters 1. epsilon : float, default=0.0 > Epsilon parameter in the epsilon-insensitive loss function. 2. loss : {‘epsilon_insensitive’, ‘squared_epsilon_insensitive’}, default=’epsilon_insensitive’ > Specifies the loss function. ‘hinge’ is the standard SVM loss (used e.g. by the SVC class) while ‘squared_hinge’ is the square of the hinge loss. The combination of penalty='l1' and loss='hinge' is not supported. 3. C : float, default=1.0 > Regularization parameter. The strength of the regularization is inversely proportional to C. Must be strictly positive. 4. tol : float, default=1e-4 > Tolerance for stopping criteria. 5. dual : bool, default=True > Select the algorithm to either solve the dual or primal optimization problem. Prefer dual=False when n_samples > n_features. ### Feature Scaling #### MinMaxScalar: Transform features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, e.g. between zero and one. ``` model=make_pipeline(MinMaxScaler(),PowerTransformer(),LinearSVR()) model.fit(x_train, y_train) ``` #### Model Accuracy We will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model. > **score**: The **score** function returns the coefficient of determination <code>R<sup>2</sup></code> of the prediction. ``` print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) ``` > **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our model. > **mse**: The **mean squared error** function squares the error(penalizes the model for large errors) by our model. ``` y_pred=model.predict(x_test) print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100)) print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred))) print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) ``` #### Prediction Plot First, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis. For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. ``` plt.figure(figsize=(14,10)) plt.plot(range(20),y_test[0:20], color = "green") plt.plot(range(20),model.predict(x_test[0:20]), color = "red") plt.legend(["Actual","prediction"]) plt.title("Predicted vs True Value") plt.xlabel("Record number") plt.ylabel(target) plt.show() ``` #### Creator:Shreepad Nade , Github: [Profile](https://github.com/shreepad-nade)
github_jupyter
<img src="../images/26-weeks-of-data-science-banner.jpg"/> # Getting Started with Python ## About Python <img src="../images/python-logo.png" alt="Python" style="width: 500px;"/> Python is a - general purpose programming language - interpreted, not compiled - both **dynamically typed** _and_ **strongly typed** - supports multiple programming paradigms: object oriented, functional - comes in 2 main versions in use today: 2.7 and 3.x ## Why Python for Data Science? *** Python is great for data science because: - general purpose programming language (as opposed to R) - faster idea to execution to deployment - battle-tested - mature ML libraries <div class="alert alert-block alert-success">And it is easy to learn !</div> <img src="../images/icon/Concept-Alert.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Python's Interactive Console : The Interpreter *** - The Python interpreter is a console that allows interactive development - We are currently using the Jupyter notebook, which uses an advanced Python interpreter called IPython - This gives us much more power and flexibility **Let's try it out !** ``` print("Hello World!") #As usual with any language we start with with the print function ``` # What are we going to learn today? *** - CHAPTER 1 - **Python Basics** - **Strings** - Creating a String, variable assignments - String Indexing & Slicing - String Concatenation & Repetition - Basic Built-in String Methods - **Numbers** - Types of Numbers - Basic Arithmetic - CHAPTER 2 - **Data Types & Data Structures** - Lists - Dictionaries - Sets & Booleans - CHAPTER 3 - **Python Programming Constructs** - Loops & Iterative Statements - if,elif,else statements - for loops, while loops - Comprehensions - Exception Handling - Modules, Packages, - File I/O operations # CHAPTER - 1 : Python Basics *** Let's understand - Basic data types - Variables and Scoping - Modules, Packages and the **`import`** statement - Operators <img src="../images/icon/Technical-Stuff.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Strings *** Strings are used in Python to record text information, such as name. Strings in Python are actually a *sequence*, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string "hello' to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter). This idea of a sequence is an important one in Python and we will touch upon it later on in the future. In this lecture we'll learn about the following: 1.) Creating Strings 2.) Printing Strings 3.) String Indexing and Slicing 4.) String Properties 5.) String Methods 6.) Print Formatting <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Creating a String *** To create a string in Python you need to use either single quotes or double quotes. For example: ``` # Single word print('hello World!') print() # Used to have a line space between two sentences. Try deleting this line & seeing the difference. # Entire phrase print('This is also a string') ``` <img src="../images/icon/Technical-Stuff.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Variables : Store your Value in me! *** In the code below we begin to explore how we can use a variable to which a string can be assigned. This can be extremely useful in many cases, where you can call the variable instead of typing the string everytime. This not only makes our code clean but it also makes it less redundant. Example syntax to assign a value or expression to a variable, variable_name = value or expression Now let's get coding!!. With the below block of code showing how to assign a string to variable. ``` s = 'New York' print(s) print(type(s)) print(len(s)) # what's the string length ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ### String Indexing *** We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let's learn how this works. In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let's create a new object called s and the walk through a few examples of indexing. ``` # Assign s as a string s = 'Hello World' # Print the object print(s) print() # Show first element (in this case a letter) print(s[0]) print() # Show the second element (also a letter) print(s[1]) #Show from first element to 5th element print(s[0:4]) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## String Concatenation and Repetition *** **String Concatenation** is a process to combine two strings. It is done using the '+' operator. **String Repetition** is a process of repeating a same string multiple times The examples of the above concepts is as follows. ``` # concatenation (addition) s1 = 'Hello' s2 = "World" print(s1 + " " + s2) # repetition (multiplication) print("Hello_" * 3) print("-" * 10) print("=" * 10) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## String Slicing & Indexing *** **String Indexing** is used to to select the letter at a particular index/position. **String Slicing** is a process to select a subset of an entire string The examples of the above stated are as follows ``` s = "Namaste World" # print sub strings print(s[1]) #This is indexing. print(s[6:11]) #This is known as slicing. print(s[-5:-1]) # test substring membership print("Wor" in s) ``` Note the above slicing. Here we're telling Python to grab everything from 6 up to 10 and from fifth last to second last. You'll notice this a lot in Python, where statements and are usually in the context of "up to, but not including". <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Basic Built-in String methods *** Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself. We call methods with a period and then the method name. Methods are in the form: object.method(parameters) Where parameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. Later on we will be creating our own objects and functions! Here are some examples of built-in methods in strings: ``` s = "Hello World" print(s.upper()) ## Convert all the element of the string to Upper case..!! print(s.lower()) ## Convert all the element of the string to Lower case..!! ``` ## Print Formatting We can use the .format() method to add formatted objects to printed string statements. The easiest way to show this is through an example: ``` name = "Bibek" age = 22 married = False print("My name is %s, my age is %s, and it is %s that I am married" % (name, age, married)) print("My name is {}, my age is {}, and it is {} that I am married".format(name, age, married)) ``` <img src="../images/icon/Concept-Alert.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Numbers *** Having worked with string we will turn our attention to numbers We'll learn about the following topics: 1.) Types of Numbers in Python 2.) Basic Arithmetic 3.) Object Assignment in Python <img src="../images/icon/Concept-Alert.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Types of numbers *** Python has various "types" of numbers (numeric literals). We'll mainly focus on integers and floating point numbers. Integers are just whole numbers, positive or negative. For example: 2 and -2 are examples of integers. Floating point numbers in Python are notable because they have a decimal point in them, or use an exponential (e) to define the number. For example 2.0 and -2.1 are examples of floating point numbers. 4E2 (4 times 10 to the power of 2) is also an example of a floating point number in Python. Throughout this course we will be mainly working with integers or simple float number types. Here is a table of the two main types we will spend most of our time working with some examples: <table> <tr> <th>Examples</th> <th>Number "Type"</th> </tr> <tr> <td>1,2,-5,1000</td> <td>Integers</td> </tr> <tr> <td>1.2,-0.5,2e2,3E2</td> <td>Floating-point numbers</td> </tr> </table> Now let's start with some basic arithmetic. ## Basic Arithmetic ``` # Addition print(2+1) # Subtraction print(2-1) # Multiplication print(2*2) # Division print(3/2) ``` ## Arithmetic continued ``` # Powers 2 ** 3 3 **2 # Order of Operations followed in Python 2 + 10 * 10 + 3 # Can use parenthesis to specify orders (2+10) * (10+3) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Variable Assignments *** Now that we've seen how to use numbers in Python as a calculator let's see how we can assign names and create variables. We use a single equals sign to assign labels to variables. Let's see a few examples of how we can do this. ``` # Let's create an object called "a" and assign it the number 5 a = 5 ``` Now if I call *a* in my Python script, Python will treat it as the number 5. ``` # Adding the objects a+a ``` What happens on reassignment? Will Python let us write it over? ``` # Reassignment a = 10 # Check a ``` <img src="../images/icon/ppt-icons.png" alt="ppt-icons" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Mini Challenge - 1 *** Its your turn now!! store the word `hello` in my_string. print the my_string + name. ``` my_string = 'Hello ' name = 'Bibek' print(my_string + name) ``` <img src="../images/icon/ppt-icons.png" alt="ppt-icons" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Mini Challenge - 2 *** **Its your turn now!!!** given the numbers stored in variables `a` and `b`. Can you write a simple code to compute the mean of these two numbers and assign it to a variable `mean`. ``` a = 8 b = 6 mean = (a+b)/2 print(mean) ``` <img src="../images/icon/Pratical-Tip.png" alt="Pratical-Tip" style="width: 100px;float:left; margin-right:15px"/> <br /> The names you use when creating these labels need to follow a few rules: 1. Names can not start with a number. 2. There can be no spaces in the name, use _ instead. 3. Can't use any of these symbols :'",<>/?|\()!@#$%^&*~-+ Using variable names can be a very useful way to keep track of different variables in Python. For example: ``` a$ = 9 ``` ## From Sales to Data Science *** Discover the story of Sagar Dawda who made a successful transition from Sales to Data Science. Making a successful switch to Data Science is a game of Decision and Determenination. But it's a long road from Decision to Determination. To read more, click <a href="https://greyatom.com/blog/2018/03/career-transition-decision-to-determination/">here</a> # CHAPTER - 2 : Data Types & Data Structures *** - Everything in Python is an "object", including integers/floats - Most common and important types (classes) - "Single value": None, int, float, bool, str, complex - "Multiple values": list, tuple, set, dict - Single/Multiple isn't a real distinction, this is for explanation - There are many others, but these are most frequently used ### Identifying Data Types ``` a = 42 b = 32.30 print(type(a))#gets type of a print(type(b))#gets type of b ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Single Value Types *** - int: Integers - float: Floating point numbers - bool: Boolean values (True, False) - complex: Complex numbers - str: String <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Lists *** Lists can be thought of the most general version of a *sequence* in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed! In this section we will learn about: 1.) Creating lists 2.) Indexing and Slicing Lists 3.) Basic List Methods 4.) Nesting Lists 5.) Introduction to List Comprehensions Lists are constructed with brackets [] and commas separating every element in the list. Let's go ahead and see how we can construct lists! ``` # Assign a list to an variable named my_list my_list = [1,2,3] ``` We just created a list of integers, but lists can actually hold different object types. For example: ``` my_list = ['A string',23,100.232,'o'] ``` Just like strings, the len() function will tell you how many items are in the sequence of the list. ``` len(my_list) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Adding New Elements to a list *** We use two special commands to add new elements to a list. Let's make a new list to remind ourselves of how this works: ``` my_list = ['one','two','three',4,5] # append a value to the end of the list l = [1, 2.3, ['a', 'b'], 'New York'] l.append(3.1) print(l) # extend a list with another list. l = [1, 2, 3] l.extend([4, 5, 6]) print(l) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Slicing *** Slicing is used to access individual elements or a rage of elements in a list. Python supports "slicing" indexable sequences. The syntax for slicing lists is: - `list_object[start:end:step]` or - `list_object[start:end]` start and end are indices (start inclusive, end exclusive). All slicing values are optional. ``` lst = list(range(10)) # create a list containing 10 numbers starting from 0 print(lst) print("elements from index 4 to 7:", lst[4:7]) print("alternate elements, starting at index 0:", lst[0::2]) # prints elements from index 0 till last index with a step of 2 print("every third element, starting at index 1:", lst[1::3]) # prints elements from index 1 till last index with a step of 3 ``` <div class="alert alert-block alert-success">**Other `list` operations**</div> *** - **`.append`**: add element to end of list - **`.insert`**: insert element at given index - **`.extend`**: extend one list with another list # Did you know? **Did you know that Japanese Anime Naruto is related to Data Science. Find out how** <img src="https://greyatom.com/blog/wp-content/uploads/2017/06/naruto-1-701x321.png"> Find out here https://medium.com/greyatom/naruto-and-data-science-how-data-science-is-an-art-and-data-scientist-an-artist-c5f16a68d670 <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> # Dictionaries *** Now we're going to switch gears and learn about *mappings* called *dictionaries* in Python. If you're familiar with other languages you can think of these Dictionaries as hash tables. This section will serve as a brief introduction to dictionaries and consist of: 1.) Constructing a Dictionary 2.) Accessing objects from a dictionary 3.) Nesting Dictionaries 4.) Basic Dictionary Methods A Python dictionary consists of a key and then an associated value. That value can be almost any Python object. ## Constructing a Dictionary *** Let's see how we can construct dictionaries to get a better understanding of how they work! ``` # Make a dictionary with {} and : to signify a key and a value my_dict = {'key1':'value1','key2':'value2'} # Call values by their key my_dict['key2'] ``` We can effect the values of a key as well. For instance: ``` my_dict['key1']=123 my_dict # Subtract 123 from the value my_dict['key1'] = my_dict['key1'] - 123 #Check my_dict['key1'] ``` A quick note, Python has a built-in method of doing a self subtraction or addition (or multiplication or division). We could have also used += or -= for the above statement. For example: ``` # Set the object equal to itself minus 123 my_dict['key1'] -= 123 my_dict['key1'] ``` Now its your turn to get hands-on with Dictionary, create a empty dicts. Create a new key calle animal and assign a value 'Dog' to it.. ``` # Create a new dictionary d = {} # Create a new key through assignment d['animal'] = 'Dog' ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> # Set and Booleans *** There are two other object types in Python that we should quickly cover. Sets and Booleans. ## Sets Sets are an unordered collection of *unique* elements. We can construct them by using the set() function. Let's go ahead and make a set to see how it works #### Set Theory <img src="../images/sets2.png" width="60%"/> ``` x = set() # We add to sets with the add() method x.add(1) #Show x ``` Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as a set being a dictionary with only keys. We know that a set has only unique entries. So what happens when we try to add something that is already in a set? ``` # Add a different element x.add(2) #Show x # Try to add the same element x.add(1) #Show x ``` Notice how it won't place another 1 there. That's because a set is only concerned with unique elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For example: ``` # Create a list with repeats l = [1,1,2,2,3,4,5,6,1,1] # Cast as set to get unique values set(l) ``` <img src="../images/icon/ppt-icons.png" alt="ppt-icons" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Mini Challenge - 3 *** Can you access the last element of a l which is a list and find the last element of that list. ``` l = [10,20,30,40,50] l[-1] ``` # CHAPTER - 3 : Python Programming Constructs *** We'll be talking about - Looping - Conditional Statements - Comprehensions <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Loops and Iterative Statements ## If,elif,else Statements *** if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results. Verbally, we can imagine we are telling the computer: "Hey if this case happens, perform some action" We can then expand the idea further with elif and else statements, which allow us to tell the computer: "Hey if this case happens, perform some action. Else if another case happens, perform some other action. Else-- none of the above cases happened, perform this action" Let's go ahead and look at the syntax format for if statements to get a better idea of this: if case1: perform action1 elif case2: perform action2 else: perform action 3 ``` a = 5 b = 4 if a > b: # we are inside the if block print("a is greater than b") elif b > a: # we are inside the elif block print("b is greater than a") else: # we are inside the else block print("a and b are equal") # Note: Python doesn't have a switch statement ``` <img src="../images/icon/Warning.png" alt="Warning" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Indentation *** It is important to keep a good understanding of how indentation works in Python to maintain the structure and order of your code. We will touch on this topic again when we start building out functions! <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> # For Loops *** A **for** loop acts as an iterator in Python, it goes through items that are in a *sequence* or any other iterable item. Objects that we've learned about that we can iterate over include strings,lists,tuples, and even built in iterables for dictionaries, such as the keys or values. We've already seen the **for** statement a little bit in past lectures but now lets formalize our understanding. Here's the general format for a **for** loop in Python: for item in object: statements to do stuff The variable name used for the item is completely up to the coder, so use your best judgment for choosing a name that makes sense and you will be able to understand when revisiting your code. This item name can then be referenced inside you loop, for example if you wanted to use if statements to perform checks. Let's go ahead and work through several example of **for** loops using a variety of data object types. ``` #Simple program to find the even numbers in a list list_1 = [2,4,5,6,8,7,9,10] # Initialised the list for number in list_1: # Selects one element in list_1 if number % 2 == 0: # Checks if it is even. IF even, only then, goes to next step else performs above step and continues iteration print(number,end=' ') # prints no if even. end=' ' prints the nos on the same line with a space in between. Try deleting this command & seeing the difference. lst1 = [4, 7, 13, 11, 3, 11, 15] lst2 = [] for index, e in enumerate(lst1): if e == 10: break if e < 10: continue lst2.append((index, e*e)) else: print("out of loop without using break statement") lst2 ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> # While loops *** The **while** statement in Python is one of most general ways to perform iteration. A **while** statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met. The general format of a while loop is: while test: code statement else: final code statements Let’s look at a few simple while loops in action. ``` x = 0 while x < 10: print ('x is currently: ',x,end=' ') #end=' ' to put print below statement on the same line after thsi statement print (' x is still less than 10, adding 1 to x') x+=1 ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Comprehensions *** - Python provides syntactic sugar to write small loops to generate lists/sets/tuples/dicts in one line - These are called comprehensions, and can greatly increase development speed and readability Syntax: ``` sequence = [expression(element) for element in iterable if condition] ``` The brackets used for creating the comprehension define what type of object is created. Use **[ ]** for lists, **()** for _generators_, **{}** for sets and dicts ### `list` Comprehension ``` names = ["Ravi", "Pooja", "Vijay", "Kiran"] hello = ["Hello " + name for name in names] print(hello) numbers = [55, 32, 87, 99, 10, 54, 32] even = [num for num in numbers if num % 2 == 0] print(even) odd_squares = [(num, num * num) for num in numbers if num % 2 == 1] print(odd_squares) ``` <img src="../images/icon/Technical-Stuff.png" alt="Technical-Stuff" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Exception Handling *** #### try and except The basic terminology and syntax used to handle errors in Python is the **try** and **except** statements. The code which can cause an exception to occue is put in the *try* block and the handling of the exception is the implemented in the *except* block of code. The syntax form is: try: You do your operations here... ... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block. ... else: If there is no exception then execute this block. We can also just check for any exception with just using except: To get a better understanding of all this lets check out an example: We will look at some code that opens and writes a file: ``` try: x = 1 / 0 except ZeroDivisionError: print('divided by zero') print('executed when exception occurs') else: print('executed only when exception does not occur') finally: print('finally block, always executed') ``` <img src="../images/icon/Concept-Alert.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## Modules, Packages, and `import` *** A module is a collection of functions and variables that have been bundled together in a single file. Module helps us: - Used for code organization, packaging and reusability - Module: A Python file - Package: A folder with an ``__init__.py`` file - Namespace is based on file's directory path Module's are usually organised around a theme. Let's see how to use a module. To access our module we will import it using python's import statement. Math module provides access to the mathematical functions. ``` # import the math module import math # use the log10 function in the math module math.log10(123) ``` <img src="../images/icon/Technical-Stuff.png" alt="Concept-Alert" style="width: 100px;float:left; margin-right:15px"/> <br /> ## File I/O : Helps you read your files *** - Python provides a `file` object to read text/binary files. - This is similar to the `FileStream` object in other languages. - Since a `file` is a resource, it must be closed after use. This can be done manually, or using a context manager (**`with`** statement) <div class="alert alert-block alert-info">Create a file in the current directory</div> ``` with open('myfile.txt', 'w') as f: f.write("This is my first file!\n") f.write("Second line!\n") f.write("Last line!\n") # let's verify if it was really created. # For that, let's find out which directory we're working from import os print(os.path.abspath(os.curdir)) ``` <div class="alert alert-block alert-info">Read the newly created file</div> ``` # read the file we just created with open('myfile.txt', 'r') as f: for line in f: print(line) ``` <img src="../images/icon/ppt-icons.png" alt="ppt-icons" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Mini Challenge - 4 *** Can you compute the square of a number assigned to a variable a using the math module? ``` import math number = 9 square_of_number = math.pow(number,2) # pow(power) function in math module takes number and power as arguments. print(square_of_number) ``` <img src="../images/icon/ppt-icons.png" alt="ppt-icons" style="width: 100px;float:left; margin-right:15px"/> <br /> ### Mini Challenge - 5 *** Can you create a list of 10 numbers iterate through the list and print the square of each number ? ``` l = [i for i in range(1,11)] for i in l: print(i*i,end=' ') ``` # Further Reading - Official Python Documentation: https://docs.python.org/ <img src="../images/icon/Recap.png" alt="Recap" style="width: 100px;float:left; margin-right:15px"/> <br /> # In-session Recap Time *** * Python Basics * Variables and Scoping * Modules, Packages and Imports * Data Types & Data Structures * Python Programming Constructs * Data Types & Data Structures * Lists * Dictionaries * Sets & Booleans * Python Prograamming constructs * Loops and Conditional Statements * Exception Handling * File I/O # Thank You *** ### Coming up next... - **Python Functions**: How to write modular functions to enable code reuse - **NumPy**: Learn the basis of most numeric computation in Python
github_jupyter
#Instalamos pytorch ``` #pip install torch===1.6.0 torchvision===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html ``` #Clonamos el repositorio para obtener el dataset ``` !git clone https://github.com/joanby/deeplearning-az.git from google.colab import drive drive.mount('/content/drive') ``` # Importar las librerías ``` import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data from torch.autograd import Variable ``` # Importar el dataset ``` movies = pd.read_csv("/content/deeplearning-az/datasets/Part 6 - AutoEncoders (AE)/ml-1m/movies.dat", sep = '::', header = None, engine = 'python', encoding = 'latin-1') users = pd.read_csv("/content/deeplearning-az/datasets/Part 6 - AutoEncoders (AE)/ml-1m/users.dat", sep = '::', header = None, engine = 'python', encoding = 'latin-1') ratings = pd.read_csv("/content/deeplearning-az/datasets/Part 6 - AutoEncoders (AE)/ml-1m/ratings.dat", sep = '::', header = None, engine = 'python', encoding = 'latin-1') ``` # Preparar el conjunto de entrenamiento y elconjunto de testing ``` training_set = pd.read_csv("/content/deeplearning-az/datasets/Part 6 - AutoEncoders (AE)/ml-100k/u1.base", sep = "\t", header = None) training_set = np.array(training_set, dtype = "int") test_set = pd.read_csv("/content/deeplearning-az/datasets/Part 6 - AutoEncoders (AE)/ml-100k/u1.test", sep = "\t", header = None) test_set = np.array(test_set, dtype = "int") ``` # Obtener el número de usuarios y de películas ``` nb_users = int(max(max(training_set[:, 0]), max(test_set[:,0]))) nb_movies = int(max(max(training_set[:, 1]), max(test_set[:, 1]))) ``` # Convertir los datos en un array X[u,i] con usuarios u en fila y películas i en columna ``` def convert(data): new_data = [] for id_user in range(1, nb_users+1): id_movies = data[:, 1][data[:, 0] == id_user] id_ratings = data[:, 2][data[:, 0] == id_user] ratings = np.zeros(nb_movies) ratings[id_movies-1] = id_ratings new_data.append(list(ratings)) return new_data training_set = convert(training_set) test_set = convert(test_set) ``` # Convertir los datos a tensores de Torch ``` training_set = torch.FloatTensor(training_set) test_set = torch.FloatTensor(test_set) ``` # Crear la arquitectura de la Red Neuronal ``` class SAE(nn.Module): def __init__(self, ): super(SAE, self).__init__() self.fc1 = nn.Linear(nb_movies, 20) self.fc2 = nn.Linear(20, 10) self.fc3 = nn.Linear(10, 20) self.fc4 = nn.Linear(20, nb_movies) self.activation = nn.Sigmoid() def forward(self, x): x = self.activation(self.fc1(x)) x = self.activation(self.fc2(x)) x = self.activation(self.fc3(x)) x = self.fc4(x) return x sae = SAE() criterion = nn.MSELoss() optimizer = optim.RMSprop(sae.parameters(), lr = 0.01, weight_decay = 0.5) ``` # Entrenar el SAE ``` nb_epoch = 200 for epoch in range(1, nb_epoch+1): train_loss = 0 s = 0. for id_user in range(nb_users): input = Variable(training_set[id_user]).unsqueeze(0) target = input.clone() if torch.sum(target.data > 0) > 0: output = sae.forward(input) target.require_grad = False output[target == 0] = 0 loss = criterion(output, target) # la media no es sobre todas las películas, sino sobre las que realmente ha valorado mean_corrector = nb_movies/float(torch.sum(target.data > 0)+1e-10) loss.backward() train_loss += np.sqrt(loss.data*mean_corrector) ## sum(errors) / n_pelis_valoradas s += 1. optimizer.step() print("Epoch: "+str(epoch)+", Loss: "+str(train_loss/s)) ``` # Evaluar el conjunto de test en nuestro SAE ``` test_loss = 0 s = 0. for id_user in range(nb_users): input = Variable(training_set[id_user]).unsqueeze(0) target = Variable(test_set[id_user]).unsqueeze(0) if torch.sum(target.data > 0) > 0: output = sae.forward(input) target.require_grad = False output[target == 0] = 0 loss = criterion(output, target) # la media no es sobre todas las películas, sino sobre las que realmente ha valorado mean_corrector = nb_movies/float(torch.sum(target.data > 0)+1e-10) test_loss += np.sqrt(loss.data*mean_corrector) ## sum(errors) / n_pelis_valoradas s += 1. print("Test Loss: "+str(test_loss/s)) ```
github_jupyter
# NLP Intent Recognition Hallo und herzlich willkommen zum codecentric.AI bootcamp! Heute wollen wir uns mit einem fortgeschrittenen Thema aus dem Bereich _natural language processing_, kurz _NLP_, genannt, beschäftigen: > Wie bringt man Sprachassistenten, Chatbots und ähnlichen Systemen bei, die Absicht eines Nutzers aus seinen Äußerungen zu erkennen? Dieses Problem wird im Englischen allgemein als _intent recognition_ bezeichnet und gehört zu dem ambitionierten Gebiet des _natural language understanding_, kurz _NLU_ genannt. Einen Einstieg in dieses Thema bietet das folgende [Youtube-Video](https://www.youtube.com/watch?v=H_3R8inCOvM): ``` # lade Video from IPython.display import IFrame IFrame('https://www.youtube.com/embed/H_3R8inCOvM', width=850, height=650) ``` Zusammen werden wir in diesem Tutorial mit Hilfe der NLU-Bibliothek [Rasa-NLU](https://rasa.com/docs/nlu/) einem WetterBot beibringen, einfache Fragemuster zum Wetter zu verstehen und zu beantworten. Zum Beispiel wird er auf die Fragen > `"Wie warm war es 1989?"` mit <img src="img/answer-1.svg" width="85%" align="middle"> und auf > `"Welche Temperatur hatten wir in Schleswig-Holstein und in Baden-Württemberg?"` mit <img src="img/answer-2.svg" width="85%" align="middle"> antworten. Der folgende Screencast gibt einen Überblick über das Notebook: ``` # lade Video from IPython.display import IFrame IFrame('https://www.youtube.com/embed/pVwO4Brs4kY', width=850, height=650) ``` Damit es gleich richtig losgehen kann, importieren wir noch zwei Standardbibliotheken und vereinbaren das Datenverzeichnis: ``` import os import numpy as np DATA_DIR = 'data' ``` ## Unser Ausgangspunkt Allgemein ist die Aufgabe, aus einer Sprachäußerung die zugrunde liegende Absicht zu erkennen, selbst für Menschen manchmal nicht einfach. Soll ein Computer diese schwierige Aufgabe lösen, so muss man sich überlegen, was man zu einem gegebenen Input &mdash; also einer (unstrukturierten) Sprachäußerung &mdash; für einen Output erwarten, wie man also Absichten modelliert und strukturiert. Weit verbreitet ist folgender Ansatz für Intent Recognition: - jede Äußerung wird einer _Domain_, also einem Gebiet, zugeordnet, - für jede _Domain_ gibt es einen festen Satz von _Intents_, also eine Reihe von Absichten, - jede Absicht kann durch _Parameter_ konkretisiert werden und hat dafür eine Reihe von _Slots_, die wie Parameter einer Funktion oder Felder eines Formulares mit gewissen Werten gefüllt werden können. Für die Äußerungen > - `"Wie warm war es 1990 in Berlin?"` > - `"Welche Temperatur hatten wir in Hessen im Jahr 2018?"` > - `"Wie komme ich zum Hauptbahnhof?"` könnte _Intent Recognition_ also zum Beispiel jeweils folgende Ergebnisse liefern: > - `{'intent': 'Frag_Temperatur', 'slots': {'Ort': 'Berlin', 'Jahr': '1990'}}` > - `{'intent': 'Frag_Temperatur', 'slots': {'Ort': 'Hessen', 'Jahr': '2018'}}` > - `{'intent': 'Frag_Weg', 'slots': {'Start': None, 'Ziel': 'Hauptbahnhof'}}` Für Python steht eine ganze von NLP-Bibliotheken zur Verfügung, die Intent Recognition in der einen oder anderen Form ermöglichen, zum Beispiel - [Rasa NLU](https://rasa.com/docs/nlu/) (&bdquo;Language Understanding for chatbots and AI assistants&ldquo;), - [snips](https://snips-nlu.readthedocs.io/en/latest/) (&bdquo;Using Voice to Make Technology Disappear&ldquo;), - [DeepPavlov](http://deeppavlov.ai) (&bdquo;an open-source conversational AI library&ldquo;), - [NLP Architect](http://nlp_architect.nervanasys.com/index.html) von Intel (&bdquo;for exploring state-of-the-art deep learning topologies and techniques for natural language processing and natural language unterstanding&ldquo;), - [pytext](https://pytext-pytext.readthedocs-hosted.com/en/latest/index.html) von Facebook (&bdquo;a deep-learning based NLP modeling framework built on PyTorch&ldquo;). Wir entscheiden uns im Folgenden für die Bibliothek Rasa NLU, weil wir dafür bequem mit einem Open-Source-Tool (chatette) umfangreiche Trainingsdaten generieren können. Rasa NLU wiederum benutzt die NLP-Bibliothek [spaCy](https://spacy.io), die Machine-Learning-Bibliothek [scikit-learn](https://scikit-learn.org/stable/) und die Deep-Learning-Bibliothek [TensorFlow](https://www.tensorflow.org/). ## Intent Recognition von Anfang bis Ende mit Rasa NLU Schauen wir uns an, wie man eine Sprach-Engine für Intent Recognition trainieren kann! Dafür beschränken wir uns zunächst auf wenige Intents und Trainingsdaten und gehen die benötigten Schritte von Anfang bis Ende durch. ### Schritt 1: Intents durch Trainingsdaten beschreiben Als Erstes müssen wir die Intents mit Hilfe von Trainingsdaten beschreiben. _Rasa NLU_ erwartet beides zusammen in einer Datei im menschenfreundlichen [Markdown-Format](http://markdown.de/) oder im computerfreundlichen [JSON-Format](https://de.wikipedia.org/wiki/JavaScript_Object_Notation). Ein Beispiel für solche Trainingsdaten im Markdown-Format ist der folgende Python-String, den wir in die Datei `intents.md` speichern: ``` TRAIN_INTENTS = """ ## intent: Frag_Temperatur - Wie [warm](Eigenschaft) war es [1900](Zeit) in [Brandenburg](Ort) - Wie [kalt](Eigenschaft) war es in [Hessen](Ort) [1900](Zeit) - Was war die Temperatur [1977](Zeit) in [Sachsen](Ort) ## intent: Frag_Ort - Wo war es [1998](Zeit) am [kältesten](Superlativ:kalt) - Finde das [kältesten](Superlativ:kalt) Bundesland im Jahr [2004](Zeit) - Wo war es [2010](Zeit) [kälter](Komparativ:kalt) als [1994](Zeit) in [Rheinland-Pfalz](Ort) ## intent: Frag_Zeit - Wann war es in [Bayern](Ort) am [kühlsten](Superlativ:kalt) - Finde das [kälteste](Superlativ:kalt) Jahr im [Saarland](Ort) - Wann war es in [Schleswig-Holstein](Ort) [wärmer](Komparativ:warm) als in [Baden-Württemberg](Ort) ## intent: Ende - Ende - Auf Wiedersehen - Tschuess """ INTENTS_PATH = os.path.join(DATA_DIR, 'intents.md') def write_file(filename, text): with open(filename, 'w', encoding='utf-8') as file: file.write(text) write_file(INTENTS_PATH, TRAIN_INTENTS) ``` Hier wird jeder Intent erst in der Form > `## intent: NAME` deklariert, wobei `NAME` durch die Bezeichnung des Intents zu ersetzen ist. Anschließend wird der Intent durch eine Liste von Beispiel-Äußerungen beschrieben. Die Parameter beziehungsweise Slots werden in den Beispieläußerungen in der Form > `[WERT](SLOT)` markiert, wobei `SLOT` die Bezeichnung des Slots und `Wert` der entsprechende Teil der Äußerung ist. ### Schritt 2: Sprach-Engine konfigurieren... Die Sprach-Engine von _Rasa NLU_ ist als Pipeline gestaltet und [sehr flexibel konfigurierbar](https://rasa.com/docs/nlu/components/#section-pipeline). Zwei [Beispiel-Konfigurationen](https://rasa.com/docs/nlu/choosing_pipeline/) sind in Rasa bereits enthalten: - `spacy_sklearn` verwendet vortrainierte Wortvektoren, eine [scikit-learn-Implementierung](https://scikit-learn.org/stable/modules/svm.html) einer linearen [Support-vector Machine]( https://en.wikipedia.org/wiki/Support-vector_machine) für die Klassifikation und wird für kleine Trainingsmengen (<1000) empfohlen. Da diese Pipeline vortrainierte Wortvektoren und spaCy benötigt, kann sie nur für [die meisten westeuropäische Sprachen](https://rasa.com/docs/nlu/languages/#section-languages) verwendet werden. Allerdings sind die Version 0.20.1 von scikit-learn und 0.13.8 von Rasa-NLU nicht kompatibel - `tensorflow_embedding` trainiert für die Klassifikation Einbettungen von Äußerungen und von Intents in denselben Vektorraum und wird für größere Trainingsmengen (>1000) empfohlen. Die zu Grunde liegende Idee stammt aus dem Artikel [StarSpace: Embed All The Things!](https://arxiv.org/abs/1709.03856). Sie ist sehr vielseitig anwendbar und beispielsweise auch für [Question Answering](https://en.wikipedia.org/wiki/Question_answering) geeignet. Diese Pipeline benötigt kein Vorwissen über die verwendete Sprache, ist also universell einsetzbar, und kann auch auf das Erkennen mehrerer Intents in einer Äußerung trainiert werden. Zum Füllen der Slots verwenden beide Pipelines eine [Python-Implementierung](http://www.chokkan.org/software/crfsuite/) von [Conditional Random Fields](https://en.wikipedia.org/wiki/Conditional_random_field). Die Konfiguration der Pipeline wird durch eine YAML-Datei beschrieben. Der folgende Python-String entspricht der Konfiguration `tensorflow_embedding`: ``` CONFIG_TF = """ pipeline: - name: "tokenizer_whitespace" - name: "ner_crf" - name: "ner_synonyms" - name: "intent_featurizer_count_vectors" - name: "intent_classifier_tensorflow_embedding" """ ``` ### Schritt 3: ...trainieren... Sind die Trainingsdaten und die Konfiguration der Pipeline beisammen, so kann die Sprach-Engine trainiert werden. In der Regel erfolgt dies bei Rasa mit Hilfe eines Kommandozeilen-Interface oder direkt [in Python](https://rasa.com/docs/nlu/python/). Die folgende Funktion `train` erwartet die Konfiguration als Python-String und den Namen der Datei mit den Trainingsdaten und gibt die trainierte Sprach-Engine als Instanz einer `Interpreter`-Klasse zurück: ``` import rasa_nlu.training_data import rasa_nlu.config from rasa_nlu.model import Trainer, Interpreter MODEL_DIR = 'models' def train(config=CONFIG_TF, intents_path=INTENTS_PATH): config_path = os.path.join(DATA_DIR, 'rasa_config.yml') write_file(config_path, config) trainer = Trainer(rasa_nlu.config.load(config_path)) trainer.train(rasa_nlu.training_data.load_data(intents_path)) return Interpreter.load(trainer.persist(MODEL_DIR)) interpreter = train() ``` ### Schritt 4: ...und testen! Wir testen nun, ob die Sprach-Engine `interpreter` folgende Test-Äußerungen richtig versteht: ``` TEST_UTTERANCES = [ 'Was war die durchschnittliche Temperatur 2004 in Mecklenburg-Vorpommern', 'Nenn mir das wärmste Bundesland 2018', 'In welchem Jahr war es in Nordrhein-Westfalen heißer als 1990', 'Wo war es 2000 am kältesten', 'Bis bald', ] ``` Die Methode `parse` von `interpreter` erwartet eine Äußerung als Python-String, wendet Intent Recognition an und liefert eine sehr detaillierte Rückgabe: ``` interpreter.parse(TEST_UTTERANCES[0]) ``` Die Rückgabe umfasst im Wesentlichen - den Namen des ermittelten Intent sowie eine Sicherheit beziehungsweise Konfidenz zwischen 0 und 1, - für jeden ermittelten Parameter die Start- und Endposition in der Äußerung, den Wert und wieder eine Konfidenz, - ein Ranking der möglichen Intents nach der Sicherheit/Konfidenz, mit der sie in dieser Äußerung vermutet wurden. Für eine übersichtlichere Darstellung und leichte Weiterverarbeitung bereiten wir die Rückgabe mit Hilfe der Funktionen `extract_intent` und `extract_confidences` ein wenig auf. Anschließend gehen wir unsere Test-Äußerungen durch: ``` def extract_intent(intent): return (intent['intent']['name'] if intent['intent'] else None, [(ent['entity'], ent['value']) for ent in intent['entities']]) def extract_confidences(intent): return (intent['intent']['confidence'] if intent['intent'] else None, [ent['confidence'] for ent in intent['entities']]) def test(interpreter, utterances=TEST_UTTERANCES): for utterance in utterances: intent = interpreter.parse(utterance) print('<', utterance) print('>', extract_intent(intent)) print(' ', extract_confidences(intent)) print() test(interpreter) ``` Das Ergebnis ist noch nicht ganz überzeugend &mdash; wir haben aber auch nur ganz wenig Trainingsdaten vorgegeben! ## Trainingsdaten generieren mit Chatette Für ein erfolgreiches Training brauchen wir also viel mehr Trainingsdaten. Doch fängt man an, weitere Beispiele aufzuschreiben, so fallen einem schnell viele kleine Variationsmöglichkeiten ein, die sich recht frei kombinieren lassen. Zum Beispiel können wir für eine Frage nach der Temperatur in Berlin im Jahr 1990 mit jeder der Phrasen > - "Wie warm war es..." > - "Wie kalt war es..." > - "Welche Temperatur hatten wir..." beginnen und dann mit > - "...in Berlin 1990" > - "...1990 in Berlin" abschließen, vor "1990" noch "im Jahr" einfügen und so weiter. Statt alle denkbaren Kombinationen aufzuschreiben, ist es sinnvoller, die Möglichkeiten mit Hilfe von Regeln zu beschreiben und daraus Trainingsdaten generieren zu lassen. Genau das ermöglicht das Python-Tool [chatette](https://github.com/SimGus/Chatette), das wir im Folgenden verwenden. Dieses Tool liest Regeln, die einer speziellen Syntax folgen müssen, aus einer Datei aus und erzeugt dann daraus Trainingsdaten für Rasa NLU im JSON-Format. ### Regeln zur Erzeugung von Trainingsdaten Wir legen im Folgenden erst einen Grundvorrat an Regeln für die Intents `Frag_Temperatur`, `Frag_Ort`, `Frag_Zeit` und `Ende` in einem Python-Dictionary an und erläutern danach genauer, wie die Regeln aufgebaut sind: ``` RULES = { '@[Ort]': ( 'Brandenburg', 'Baden-Wuerttemberg', 'Bayern', 'Hessen', 'Rheinland-Pfalz', 'Schleswig-Holstein', 'Saarland', 'Sachsen', ), '@[Zeit]': set(map(str, np.random.randint(1891, 2018, size=5))), '@[Komparativ]': ('wärmer', 'kälter',), '@[Superlativ]': ('wärmsten', 'kältesten',), '%[Frag_Temperatur]': ('Wie {warm/kalt} war es ~[zeit_ort]', 'Welche Temperatur hatten wir ~[zeit_ort]', 'Wie war die Temperatur ~[zeit_ort]', ), '%[Frag_Ort]': ( '~[wo_war] es @[Zeit] @[Komparativ] als {@[Zeit]/in @[Ort]}', '~[wo_war] es @[Zeit] am @[Superlativ]', ), '%[Frag_Jahr]': ( '~[wann_war] es in @[Ort] @[Komparativ] als {@[Zeit]/in @[Ort]}', '~[wann_war] es in @[Ort] am @[Superlativ]', ), '%[Ende]': ('Ende', 'Auf Wiedersehen', 'Tschuess',), '~[finde]': ('Sag mir', 'Finde'), '~[wie_war]': ('Wie war', '~[finde]',), '~[was_war]': ('Was war', '~[finde]',), '~[wo_war]': ('Wo war', 'In welchem {Bundesland|Land} war',), '~[wann_war]': ('Wann war', 'In welchem Jahr war',), '~[zeit_ort]': ('@[Zeit] in @[Ort]', '@[Ort] in @[Zeit]',), '~[Bundesland]': ('Land', 'Bundesland',), } ``` Jede Regel besteht aus einem Namen beziehungsweise Platzhalter und einer Menge von Phrasen. Je nachdem, ob der Name die Form > `%[NAME]`, `@[NAME]` oder `~[NAME]` hat, beschreibt die Regel einen > _Intent_, _Slot_ oder eine _Alternative_ mit der Bezeichnung `NAME`. Jede Phrase kann ihrerseits Platzhalter für Slots und Alternativen erhalten. Diese Platzhalter werden bei der Erzeugung von Trainingsdaten von chatette jeweils durch eine der Phrasen ersetzt, die in der Regel für den jeweiligen Slot beziehungsweise die Alternativen aufgelistet sind. Außerdem können Phrasen - Alternativen der Form `{_|_|_}`, - optionale Teile in der Form `[_?]` und einige weitere spezielle Konstrukte enthalten. Mehr Details finden sich in der [Syntax-Beschreibung](https://github.com/SimGus/Chatette/wiki/Syntax-specifications) von chatette. ### Erzeugung der Trainingsdaten Die in dem Python-Dictionary kompakt abgelegten Regeln müssen nun für chatette so formatiert werden, dass bei jeder Regel der Name einen neuen Absatz einleitet und anschließend die möglichen Phrasen schön eingerückt Zeile für Zeile aufgelistet werden. Dies leistet die folgende Funktion `format_rules`. Zusätzlich fügt sie eine Vorgabe ein, wieviel Trainingsbeispiele pro Intent erzeugt werden sollen: ``` def format_rules(rules, train_samples): train_str = "('training':'{}')".format(train_samples) llines = [[name if (name[0] != '%') else name + train_str] + [' ' + val for val in rules[name]] + [''] for name in rules] return '\n'.join((l for lines in llines for l in lines)) ``` Nun wenden wir chatette an, um die Trainingsdaten zu generieren. Dafür bietet chatette ein bequemes [Kommandozeilen-Interface](https://github.com/SimGus/Chatette/wiki/Command-line-interface), aber wir verwenden direkt die zu Grunde liegenden Python-Module. Die folgende Funktion `chatette` erwartet wie `format_rules` ein Python-Dictionary mit Regeln, schreibt diese passend formatiert in eine Datei, löscht etwaige zuvor generierte Trainingsdateien und erzeugt dann den Regeln entsprechend neue Trainingsdaten. ``` from chatette.adapters import RasaAdapter from chatette.parsing import Parser from chatette.generator import Generator import glob TRAIN_SAMPLES = 400 CHATETTE_DIR = os.path.join(DATA_DIR, 'chatette') def chatette(rules=RULES, train_samples=TRAIN_SAMPLES): rules_path = os.path.join(DATA_DIR, 'intents.chatette') write_file(rules_path, format_rules(rules, train_samples)) with open(rules_path, 'r') as rule_file: parser = Parser(rule_file) parser.parse() generator = Generator(parser) for f in glob.glob(os.path.join(CHATETTE_DIR, '*')): os.remove(f) RasaAdapter().write(CHATETTE_DIR, list(generator.generate_train()), generator.get_entities_synonyms()) chatette(train_samples=400) ``` ### Und nun: neuer Test! Bringen die umfangreicheren Trainingsdaten wirklich eine Verbesserung? Schauen wir's uns an! Um verschiedene Sprach-Engines zu vergleichen, nutzen wir die folgende Funktion: ``` def train_and_test(config=CONFIG_TF, utterances=TEST_UTTERANCES): interpreter = train(config, CHATETTE_DIR) test(interpreter, utterances) return interpreter interpreter = train_and_test() ``` Hier wurde nur die letzte Äußerung nicht verstanden, aber das ist auch nicht weiter verwunderlich. ## Unser kleiner WetterBot Experimentieren macht mehr Spaß, wenn es auch mal zischt und knallt. Oder zumindest irgendeine andere Reaktion erfolgt. Und deswegen bauen wir uns einen kleinen WetterBot, der auf die erkannten Intents reagieren kann. Zuerst schreiben wir dafür eine Eingabe-Verarbeitungs-Ausgabe-Schleife. Diese erwartet als Parameter erstens die Sprach-Engine `interpreter` und zweitens ein Python-Dictionary `handlers`, welches jeder Intent-Bezeichnung einen Handler zuordnet. Der Handler wird dann mit dem erkannten Intent aufgerufen und sollte zurückgeben, ob die Schleife fortgeführt werden soll oder nicht: ``` def dialog(interpreter, handlers): quit = False while not quit: intent = extract_intent(interpreter.parse(input('>'))) print('<', intent) intent_name = intent[0] if intent_name in handlers: quit = handlers[intent_name](intent) ``` Wir implementieren gleich beispielhaft einen Handler für den Intent `Frag_Temperatur`und reagieren auf alle anderen Intents mit einer Standard-Antwort: ``` def message(msg, quit=False): print(msg) return quit HANDLERS = { 'Ende': lambda intent: message('=> Oh, wie schade. Bis bald!', True), 'Frag_Zeit': lambda intent: message('=> Das ist eine gute Frage.'), 'Frag_Ort': lambda intent: message('=> Dafür wurde ich nicht programmiert.'), 'Frag_Temperatur': lambda intent: message('=> Das weiss ich nicht.') } ``` Um die Fragen nach den Temperaturen zu beantworten, nutzen wir [Archiv-Daten](ftp://ftp-cdc.dwd.de/pub/CDC/regional_averages_DE/annual/air_temperature_mean/regional_averages_tm_year.txt) des [Deutschen Wetterdienstes](https://www.dwd.de), die wir schon etwas aufbereitet haben. Die Routine `show` gibt die nachgefragten Temperaturdaten je nach Anzahl der angegebenen Jahre und Bundesländer als Liniendiagramm, Balkendiagramm oder in Textform an. Der eigentliche Hander `frag_wert` prüft, ob die angegebenen Jahre und Orte auch zulässig sind und setzt, falls eine der beiden Angaben fehlt, einfach alle Jahre beziehungsweise Bundesländer ein: ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from IPython.display import set_matplotlib_formats %matplotlib inline set_matplotlib_formats('svg') sns.set() DATA_PATH = os.path.join(DATA_DIR, 'temperaturen.txt') temperature = pd.read_csv(DATA_PATH, index_col=0, sep=';') def show(times, places): if (len(places) == 0) and (len(times) == 0): print('Keine zulässigen Orte oder Zeiten') elif (len(places) == 1) and (len(times) == 1): print(temperature.loc[times, places]) else: if (len(places) > 1) and (len(times) == 1): temperature.loc[times[0], places].plot.barh() if (len(places) == 1) and (len(times) > 1): temperature.loc[times, places[0]].plot.line() if (len(places) > 1) and (len(times) > 1): temperature.loc[times, places].plot.line() plt.legend(bbox_to_anchor=(1.05,1), loc=2, borderaxespad=0.) plt.show() def frag_temperatur(intent): def validate(options, ent_name, fn): chosen = [fn(value) for (name, value) in intent[1] if name == ent_name] return list(set(options) & set(chosen)) if chosen else options places = validate(list(temperature.columns), 'Ort', lambda x:x) times = validate(list(temperature.index), 'Zeit', int) show(times, places) return False HANDLERS['Frag_Temperatur'] = frag_temperatur ``` Nun kann der WetterBot getestet werden! Zum Beispiel mit > "Wie warm war es in Baden-Württemberg und Sachsen?" ``` dialog(interpreter, HANDLERS) ``` ## Intent Recognition selbst gemacht &mdash; ein Bi-LSTM-Netzwerk mit Keras Im Prinzip haben wir nun gesehen, wie sich Intent Recognition mit Hilfe von Rasa NLU recht einfach anwenden lässt. Aber wie funktioniert das ganz genau? In diesem zweiten Teil des Notebooks werden wir - ein bidirektionales rekurrentes Netz, wie es im Video vorgestellt wurde, implementieren, - die mit chatette erstellten Trainingsdaten so aufbereiten, dass wir damit das Netz trainieren können, und sehen, dass das ganz gut klappt und gar nicht so schwer ist! ### Intents einlesen und aufbereiten Zuerst lesen wir die Trainings-Daten, die von chatette im JSON-Format ausgegeben in die Date `RASA_INTENTS` geschrieben wurden, aus, und schauen uns das Format der Einträge an: ``` import json CHATETTE_DIR = os.path.join(DATA_DIR, 'chatette') RASA_INTENTS = os.path.join(CHATETTE_DIR, 'output.json') def load_intents(): with open(RASA_INTENTS) as intents_file: intents = json.load(intents_file) return intents['rasa_nlu_data']['common_examples'] sample_intent = load_intents()[0] ``` Wie bereits im [Video](https://www.youtube.com/watch?v=H_3R8inCOvM) erklärt, sind für Intent Recognition zwei Aufgaben zu lösen: - die _Klassifikation_ des Intent anhand der gegebenen Äußerung und - das Füllen der Slots. Die zweite Aufgabe kann man als _Sequence Tagging_ auffassen &mdash; für jedes Token der Äußerung ist zu bestimmen, ob es den Parameter für einen Slot darstellt oder nicht. Für den Beispiel-Intent > `{'entities': [{'end': 20, 'entity': 'Zeit', 'start': 16, 'value': '1993'}, > {'end': 35, 'entity': 'Ort', 'start': 24, 'value': 'Brandenburg'}], > 'intent': 'Frag_Temperatur', > 'text': 'Wie warm war es 1993 in Brandenburg'}` wäre die Eingabe für diese beiden Aufgaben also die Token-Folge > `['Wie', 'warm', 'war', 'es', '1993', 'in', 'Brandenburg']` und die gewünschte Ausgabe jeweils > `'Frag_Temperatur'` beziehungsweise die Tag-Folge > `['-', '-', '-', '-', 'Zeit', '-', 'Ort']` Die folgende Funktion extrahiert aus den geladenen Beispiel-Intents die gewünschte Eingabe und die Ausgaben für diese beiden Aufgaben: ``` import spacy from itertools import accumulate nlp = spacy.load('de_core_news_sm') def tokenize(text): return [word for word in nlp(text)] NO_ENTITY = '-' def intent_and_sequences(intent): def get_tag(offset): """Returns the tag (+slot name) for token starting at `offset`""" ents = [ent['entity'] for ent in intent['entities'] if ent['start'] == offset] return ents[0] if ents else NO_ENTITY token = tokenize(intent['text']) # `offsets` is the list of starting positions of the token offsets = list(accumulate([0,] + [len(t.text_with_ws) for t in token])) return (intent['intent'], token, list(map(get_tag, offsets[:-1]))) intent_and_sequences(sample_intent) ``` ### Symbolische Daten in numerische Daten umwandeln Die aufbereiteten Intents enthalten nun jeweils 1. die Folge der Token als "Eingabe" 2. den Namen des Intent als Ergebnis der Klassifikation und 3. die Folge der Slot-Namen als Ergebnis des Sequence Tagging. Diese kategoriellen Daten müssen wir für die Weiterverarbeitung in numerische Daten umwandeln. Dafür bieten sich - für 1. Wortvektoren und - für 2. und 3. die One-hot-Kodierung an. Außerdem müssen wir die Eingabe-Folge und Tag-Folge auf eine feste Länge bringen. Beginnen wir mit der One-hot-Kodierung. Die folgende Funktion erzeug zu einer gegebenen Menge von Objekten ein Paar von Python-Dictionaries, welche jedem Objekt einen One-hot-Code und umgekehrt jedem Index das entsprechende Objekt zuordnet. ``` def ohe(s): codes = np.eye(len(s)) numerated = list(enumerate(s)) return ({value: codes[idx] for (idx, value) in numerated}, {idx: value for (idx, value) in numerated}) ``` Die nächste Hilfsfunktion erwartet eine Liste von Elementen und schneidet diese auf eine vorgegebene Länge beziehungsweise füllt sie mit einem vorgegebenen Element auf diese Länge auf. ``` def fill(items, max_len, filler): if len(items) < max_len: return items + [filler] * (max_len - len(items)) else: return items[0:max_len] ``` Die Umwandlung der aufbereiteten Intent-Tripel in numerische Daten verpacken wir in einen [scikit-learn-Transformer](https://scikit-learn.org/stable/data_transforms.html), weil während der Umwandlung die One-Hot-Kodierung der Intent-Namen und Slot-Namen gelernt und eventuell später für neue Testdaten wieder gebraucht wird. ``` from sklearn.base import BaseEstimator, TransformerMixin MAX_LEN = 20 VEC_DIM = len(list(nlp(' '))[0].vector) class IntentNumerizer(BaseEstimator, TransformerMixin): def __init__(self): pass def fit(self, X, y=None): intent_names = set((x[0] for x in X)) self.intents_ohe, self.idx_intents = ohe(intent_names) self.nr_intents = len(intent_names) tag_lists = list(map(lambda x: set(x[2]), X)) + [[NO_ENTITY]] tag_names = frozenset().union(*tag_lists) # tag_names = set(()) self.tags_ohe, self.idx_tags = ohe(tag_names) self.nr_tags = len(tag_names) return self def transform_utterance(self, token): return np.stack(fill([tok.vector for tok in token], MAX_LEN, np.zeros((VEC_DIM)))) def transform_tags(self, tags): return np.stack([self.tags_ohe[t] for t in fill(tags, MAX_LEN, NO_ENTITY)]) def transform(self, X): return (np.stack([self.transform_utterance(x[1]) for x in X]), np.stack([self.intents_ohe[x[0]] for x in X]), np.stack([self.transform_tags(x[2]) for x in X])) def revert(self, intent_idx, tag_idxs): return (self.idx_intents[intent_idx], [self.idx_tags[t] for t in tag_idxs]) ``` ### Keras-Implementierung eines Bi-LSTM-Netzes für Intent Recognition Wir implementieren nun mit Keras eine Netz-Architektur, die in [diesem Artikel]() vorgeschlagen wurde und schematisch in folgendem Diagramm dargestellt ist: <img src="img/birnn.svg" style="background:white" width="80%" align="middle"> Hierbei wird 1. die Eingabe, wie bereits erklärt, als Folge von Wortvektoren dargestellt, 2. diese Eingabe erst durch eine rekurrente Schicht forwärts abgearbeitet, 3. der Endzustand dieser Schicht als Initialisierung einer sich anschließenden rekurrenten Schicht verwendet, welche die Eingabefolge rückwärts abarbeitet, 4. der Endzustand dieser Schicht an eine Schicht mit genau so vielen Neuronen, wie es Intent-Klassen gibt, zur Klassifikation des Intent weitergleitet, 5. die Ausgabe der beiden rekurrenten Schichten für jeden Schritt zusammengefügt und 6. die zusammengefügte Ausgabe jeweils an ein Bündel von so vielen Neuronen, wie es Slot-Arten gibt, zur Klassifikation des Tags des jeweiligen Wortes weitergeleitet. Genau diesen Aufbau bilden wir nun mit Keras ab, wobei wir die [funktionale API]() benutzen. Als Loss-Funktion verwenden wir jeweils [kategorielle Kreuzentropie](). Für die rekurrenten Schichten verwenden wir [LSTM-Zellen](), auf die wir gleich noch eingehen. ``` from keras.models import Model from keras.layers import Input, LSTM, Concatenate, TimeDistributed, Dense UNITS = 256 def build_bilstm(input_dim, nr_intents, nr_tags, units=UNITS): inputs = Input(shape=(MAX_LEN, input_dim)) lstm_params = {'units': units, 'return_sequences': True, 'return_state': True} fwd = LSTM(**lstm_params)(inputs) bwd = LSTM(**lstm_params)(inputs, initial_state=fwd[1:]) merged = Concatenate()([fwd[0], bwd[0]]) tags = TimeDistributed(Dense(nr_tags, activation='softmax'))(merged) intent = Dense(nr_intents, activation='softmax')(bwd[2]) model = Model(inputs=inputs, outputs=[intent, tags]) model.compile(optimizer='Adam' ,loss='categorical_crossentropy') return model ``` Schauen wir uns einmal genauer an, wie so eine LSTM-Zelle aufgebaut ist: <img src="img/lstm.svg" style="background:white" width="70%" align="middle"> Die Bezeichnung 'LSTM' steht für _long short-term memory_ und rührt daher, dass solch eine Zelle neben der Eingabe des aktuellen Schrittes nicht nur die Ausgabe des vorherigen Schrittes, sondern zusätzlich auch einen Speicherwert des vorherigen Schrittes erhält. Nacheinander wird in der LSTM-Zelle dann jeweils anhand der aktuellen Eingabe und der vorherigen Ausgabe 1. in einem _forget gate_ entschieden, wieviel vom alten Speicherwert vergessen werden soll, 2. in einem _input gate_ entschieden, wieviel von der neuen Eingabe in den neuen Speicherwert aufgenommen werden soll, 3. in einem _output gate_ aus dem aktuellen Speicher die aktuelle Ausgabe gebildet. ### Training und Test des Bi-LSTM-Netzes Schauen wir uns nun an, wie gut das funktioniert! Dazu müssen wir nun alles zusammenfügen und tun das in zwei Schritten. Die Funktion `train_test_data` erwartet als Eingabe Regeln, wie wir sie für chatette in einem Python-Dictionary gespeichert hatten, und liefert die entsprechend erzeugten Intents in numerisch aufbereiter Form, aufgeteilt in Trainings- und Validierungsdaten, einschließlich des angepassten `IntentNumerizer`zurück. ``` TRAIN_RATIO = 0.7 def train_test_data(rules=RULES, train_ratio=TRAIN_RATIO): structured_intents = list(map(intent_and_sequences, load_intents())) intent_numerizer = IntentNumerizer() X, y, Y = intent_numerizer.fit_transform(structured_intents) nr_samples = len(y) shuffled_indices = np.random.permutation(nr_samples) split = int(nr_samples * train_ratio) train_indices, test_indices = (shuffled_indices[0:split], shuffled_indices[split:]) y_train, X_train, Y_train = y[train_indices], X[train_indices], Y[train_indices] y_test, X_test, Y_test = y[test_indices], X[test_indices], Y[test_indices] return intent_numerizer, X_train, y_train, Y_train, X_test, y_test, Y_test ``` Mit diesen Trainings- und Testdaten trainiert beziehungsweise validiert die folgende Funktion `build_interpreter` nun das von `build_lstm` gebaute neuronale Netz und liefert einen Interpreter-Funktion zurück. Diese erwartet als Eingabe eine Äußerung, transformiert diese anschließend mit dem angepassten `IntentNumerizer` und führt mit dem zuvor trainierten Netz die Intent Recognition durch. ``` BATCH_SIZE = 128 EPOCHS = 10 def build_interpreter(rules=RULES, units=UNITS, batch_size=128, epochs=EPOCHS): def interpreter(utterance): x = intent_numerizer.transform_utterance(tokenize(utterance)) y, Y = model.predict(np.stack([x])) tag_idxs = np.argmax(Y[0], axis=1) intent_idx = np.argmax(y[0]) return intent_numerizer.revert(intent_idx, tag_idxs) intent_numerizer, X_train, y_train, Y_train, X_test, y_test, Y_test = train_test_data(rules) model = build_bilstm(X_train.shape[2], y_train.shape[1], Y_train.shape[2], units) model.fit(x=X_train, y=[y_train, Y_train], validation_data=(X_test,[y_test, Y_test]), batch_size=batch_size, epochs=epochs) return interpreter ``` Und nun sind wir bereit zum Testen! ``` interpreter = build_interpreter() interpreter('Welche ungefähre Temperatur war 1992 und 2018 in Sachsen') ``` Und jetzt kannt Du loslegen &mdash; der WetterBot kann noch nicht viel, ist aber nun recht einfach zu trainieren! Und mit der selbstgebauten Intent Recognition wird er bestimmt noch besser! Ein paar Ideen dazu gibt Dir das Notebook mit Aufgaben zu Intent Recognition. _Viel Spaß und bis bald zu einer neuen Lektion vom codecentric.AI bootcamp!_
github_jupyter
Copyright 2018 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **This tutorial is for educational purposes purposes only and is not intended for use in clinical diagnosis or clinical decision-making or for any other clinical use.** # Training/Inference on Breast Density Classification Model on AutoML Vision The goal of this tutorial is to train, deploy and run inference on a breast density classification model. Breast density is thought to be a factor for an increase in the risk for breast cancer. This will emphasize using the [Cloud Healthcare API](https://cloud.google.com/healthcare/) in order to store, retreive and transcode medical images (in DICOM format) in a managed and scalable way. This tutorial will focus on using [Cloud AutoML Vision](https://cloud.google.com/vision/automl/docs/beginners-guide) to scalably train and serve the model. **Note: This is the AutoML version of the Cloud ML Engine Codelab found [here](./breast_density_cloud_ml.ipynb).** ## Requirements - A Google Cloud project. - Project has [Cloud Healthcare API](https://cloud.google.com/healthcare/docs/quickstart) enabled. - Project has [Cloud AutoML API ](https://cloud.google.com/vision/automl/docs/quickstart) enabled. - Project has [Cloud Build API](https://cloud.google.com/cloud-build/docs/quickstart-docker) enabled. - Project has [Kubernetes engine API](https://console.developers.google.com/apis/api/container.googleapis.com/overview?project=) enabled. - Project has [Cloud Resource Manager API](https://console.cloud.google.com/cloud-resource-manager) enabled. ## Notebook dependencies We will need to install the hcls_imaging_ml_toolkit package found [here](./toolkit). This toolkit helps make working with DICOM objects and the Cloud Healthcare API easier. In addition, we will install [dicomweb-client](https://dicomweb-client.readthedocs.io/en/latest/) to help us interact with the DIOCOMWeb API and [pydicom](https://pydicom.github.io/pydicom/dev/index.html) which is used to help up construct DICOM objects. ``` %%bash pip3 install git+https://github.com/GoogleCloudPlatform/healthcare.git#subdirectory=imaging/ml/toolkit pip3 install dicomweb-client pip3 install pydicom ``` ## Input Dataset The dataset that will be used for training is the [TCIA CBIS-DDSM](https://wiki.cancerimagingarchive.net/display/Public/CBIS-DDSM) dataset. This dataset contains ~2500 mammography images in DICOM format. Each image is given a [BI-RADS breast density ](https://breast-cancer.ca/densitbi-rads/) score from 1 to 4. In this tutorial, we will build a binary classifier that distinguishes between breast density "2" (*scattered density*) and "3" (*heterogeneously dense*). These are the two most common and variably assigned scores. In the literature, this is said to be [particularly difficult for radiologists to consistently distinguish](https://aapm.onlinelibrary.wiley.com/doi/pdf/10.1002/mp.12683). ``` project_id = "MY_PROJECT" # @param location = "us-central1" dataset_id = "MY_DATASET" # @param dicom_store_id = "MY_DICOM_STORE" # @param # Input data used by AutoML must be in a bucket with the following format. automl_bucket_name = "gs://" + project_id + "-vcm" %%bash -s {project_id} {location} {automl_bucket_name} # Create bucket. gsutil -q mb -c regional -l $2 $3 # Allow Cloud Healthcare API to write to bucket. PROJECT_NUMBER=`gcloud projects describe $1 | grep projectNumber | sed 's/[^0-9]//g'` SERVICE_ACCOUNT="service-${PROJECT_NUMBER}@gcp-sa-healthcare.iam.gserviceaccount.com" COMPUTE_ENGINE_SERVICE_ACCOUNT="${PROJECT_NUMBER}-compute@developer.gserviceaccount.com" gsutil -q iam ch serviceAccount:${SERVICE_ACCOUNT}:objectAdmin $3 gsutil -q iam ch serviceAccount:${COMPUTE_ENGINE_SERVICE_ACCOUNT}:objectAdmin $3 gcloud projects add-iam-policy-binding $1 --member=serviceAccount:${SERVICE_ACCOUNT} --role=roles/pubsub.publisher gcloud projects add-iam-policy-binding $1 --member=serviceAccount:${COMPUTE_ENGINE_SERVICE_ACCOUNT} --role roles/pubsub.admin # Allow compute service account to create datasets and dicomStores. gcloud projects add-iam-policy-binding $1 --member=serviceAccount:${COMPUTE_ENGINE_SERVICE_ACCOUNT} --role roles/healthcare.dicomStoreAdmin gcloud projects add-iam-policy-binding $1 --member=serviceAccount:${COMPUTE_ENGINE_SERVICE_ACCOUNT} --role roles/healthcare.datasetAdmin import json import os import google.auth from google.auth.transport.requests import AuthorizedSession from hcls_imaging_ml_toolkit import dicom_path credentials, project = google.auth.default() authed_session = AuthorizedSession(credentials) # Path to Cloud Healthcare API. HEALTHCARE_API_URL = 'https://healthcare.googleapis.com/v1' # Create Cloud Healthcare API dataset. path = os.path.join(HEALTHCARE_API_URL, 'projects', project_id, 'locations', location, 'datasets?dataset_id=' + dataset_id) headers = {'Content-Type': 'application/json'} resp = authed_session.post(path, headers=headers) assert resp.status_code == 200, 'error creating Dataset, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) # Create Cloud Healthcare API DICOM store. path = os.path.join(HEALTHCARE_API_URL, 'projects', project_id, 'locations', location, 'datasets', dataset_id, 'dicomStores?dicom_store_id=' + dicom_store_id) resp = authed_session.post(path, headers=headers) assert resp.status_code == 200, 'error creating DICOM store, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) dicom_store_path = dicom_path.Path(project_id, location, dataset_id, dicom_store_id) ``` Next, we are going to transfer the DICOM instances to the Cloud Healthcare API. Note: We are transfering >100GB of data so this will take some time to complete ``` # Store DICOM instances in Cloud Healthcare API. path = 'https://healthcare.googleapis.com/v1/{}:import'.format(dicom_store_path) headers = {'Content-Type': 'application/json'} body = { 'gcsSource': { 'uri': 'gs://gcs-public-data--healthcare-tcia-cbis-ddsm/dicom/**' } } resp = authed_session.post(path, headers=headers, json=body) assert resp.status_code == 200, 'error creating Dataset, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) response = json.loads(resp.text) operation_name = response['name'] import time def wait_for_operation_completion(path, timeout, sleep_time=30): success = False while time.time() < timeout: print('Waiting for operation completion...') resp = authed_session.get(path) assert resp.status_code == 200, 'error polling for Operation results, code: {0}, response: {1}'.format(resp.status_code, resp.text) response = json.loads(resp.text) if 'done' in response: if response['done'] == True and 'error' not in response: success = True; break time.sleep(sleep_time) print('Full response:\n{0}'.format(resp.text)) assert success, "operation did not complete successfully in time limit" print('Success!') return response path = os.path.join(HEALTHCARE_API_URL, operation_name) timeout = time.time() + 40*60 # Wait up to 40 minutes. _ = wait_for_operation_completion(path, timeout) ``` ### Explore the Cloud Healthcare DICOM dataset (optional) This is an optional section to explore the Cloud Healthcare DICOM dataset. In the following code, we simply just list the studies that we have loaded into the Cloud Healthcare API. You can modify the *num_of_studies_to_print* parameter to print as many studies as desired. ``` num_of_studies_to_print = 2 # @param path = os.path.join(HEALTHCARE_API_URL, dicom_store_path.dicomweb_path_str, 'studies') resp = authed_session.get(path) assert resp.status_code == 200, 'error querying Dataset, code: {0}, response: {1}'.format(resp.status_code, resp.text) response = json.loads(resp.text) print(json.dumps(response[:num_of_studies_to_print], indent=2)) ``` ## Convert DICOM to JPEG The ML model that we will build requires that the dataset be in JPEG. We will leverage the Cloud Healthcare API to transcode DICOM to JPEG. First we will create a [Google Cloud Storage](https://cloud.google.com/storage/) bucket to hold the output JPEG files. Next, we will use the ExportDicomData API to transform the DICOMs to JPEGs. ``` # Folder to store input images for AutoML Vision. jpeg_folder = automl_bucket_name + "/images/" ``` Next we will convert the DICOMs to JPEGs using the [ExportDicomData](https://cloud.google.com/sdk/gcloud/reference/beta/healthcare/dicom-stores/export/gcs). ``` %%bash -s {jpeg_folder} {project_id} {location} {dataset_id} {dicom_store_id} gcloud beta healthcare --project $2 dicom-stores export gcs $5 --location=$3 --dataset=$4 --mime-type="image/jpeg; transfer-syntax=1.2.840.10008.1.2.4.50" --gcs-uri-prefix=$1 ``` Meanwhile, you should be able to observe the JPEG images being added to your Google Cloud Storage bucket. Next, we will join the training data stored in Google Cloud Storage with the labels in the TCIA website. The output of this step is a [CSV file that is input to AutoML](https://cloud.google.com/vision/automl/docs/prepare). This CSV contains a list of pairs of (IMAGE_PATH, LABEL). ``` # tensorflow==1.15.0 to have same versions in all environments - dataflow, automl, ai-platform !pip install tensorflow==1.15.0 --ignore-installed # CSV to hold (IMAGE_PATH, LABEL) list. input_data_csv = automl_bucket_name + "/input.csv" import csv import os import re from tensorflow.python.lib.io import file_io import scripts.tcia_utils as tcia_utils # Get map of study_uid -> file paths. path_list = file_io.get_matching_files(os.path.join(jpeg_folder, '*/*/*')) study_uid_to_file_paths = {} pattern = r'^{0}(?P<study_uid>[^/]+)/(?P<series_uid>[^/]+)/(?P<instance_uid>.*)'.format(jpeg_folder) for path in path_list: match = re.search(pattern, path) study_uid_to_file_paths[match.group('study_uid')] = path # Get map of study_uid -> labels. study_uid_to_labels = tcia_utils.GetStudyUIDToLabelMap() # Join the two maps, output results to CSV in Google Cloud Storage. with file_io.FileIO(input_data_csv, 'w') as f: writer = csv.writer(f, delimiter=',') for study_uid, label in study_uid_to_labels.items(): if study_uid in study_uid_to_file_paths: writer.writerow([study_uid_to_file_paths[study_uid], label]) ``` ## Training ***This section will focus on using AutoML through its API. AutoML can also be used through the user interface found [here](https://console.cloud.google.com/vision/). The below steps in this section can all be done through the web UI .*** We will use [AutoML Vision ](https://cloud.google.com/automl/) to train the classification model. AutoML provides a fully managed solution for training the model. All we will do is input the list of input images and labels. The trained model in AutoML will be able to classify the mammography images as either "2" (scattered density) or "3" (heterogeneously dense). As a first step, we will create a AutoML dataset. ``` automl_dataset_display_name = "MY_AUTOML_DATASET" # @param import json import os # Path to AutoML API. AUTOML_API_URL = 'https://automl.googleapis.com/v1beta1' # Path to request creation of AutoML dataset. path = os.path.join(AUTOML_API_URL, 'projects', project_id, 'locations', location, 'datasets') # Headers (request in JSON format). headers = {'Content-Type': 'application/json'} # Body (encoded in JSON format). config = {'display_name': automl_dataset_display_name, 'image_classification_dataset_metadata': {'classification_type': 'MULTICLASS'}} resp = authed_session.post(path, headers=headers, json=config) assert resp.status_code == 200, 'creating AutoML dataset, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) # Record the AutoML dataset name. response = json.loads(resp.text) automl_dataset_name = response['name'] ``` Next, we will import the CSV that contains the list of (IMAGE_PATH, LABEL) list into AutoML. **Please ignore errors regarding an existing ground truth.** ``` # Path to request import into AutoML dataset. path = os.path.join(AUTOML_API_URL, automl_dataset_name + ':importData') # Body (encoded in JSON format). config = {'input_config': {'gcs_source': {'input_uris': [input_data_csv]}}} resp = authed_session.post(path, headers=headers, json=config) assert resp.status_code == 200, 'error importing AutoML dataset, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) # Record operation_name so we can poll for it later. response = json.loads(resp.text) operation_name = response['name'] ``` The output of the previous step is an [operation](https://cloud.google.com/vision/automl/docs/models#get-operation) that will need to poll the status for. We will poll until the operation's "done" field is set to true. This will take a few minutes to complete so we will wait until completion. ``` path = os.path.join(AUTOML_API_URL, operation_name) timeout = time.time() + 40*60 # Wait up to 40 minutes. _ = wait_for_operation_completion(path, timeout) ``` Next, we will train the model to perform classification. We will set the training budget to be a maximum of 1hr (but this can be modified below). The cost of using AutoML can be found [here](https://cloud.google.com/vision/automl/pricing). Typically, the longer the model is trained for, the more accurate it will be. ``` # Name of the model. model_display_name = "MY_MODEL_NAME" # @param # Training budget (1 hr). training_budget = 1 # @param # Path to request import into AutoML dataset. path = os.path.join(AUTOML_API_URL, 'projects', project_id, 'locations', location, 'models') # Headers (request in JSON format). headers = {'Content-Type': 'application/json'} # Body (encoded in JSON format). automl_dataset_id = automl_dataset_name.split('/')[-1] config = {'display_name': model_display_name, 'dataset_id': automl_dataset_id, 'image_classification_model_metadata': {'train_budget': training_budget}} resp = authed_session.post(path, headers=headers, json=config) assert resp.status_code == 200, 'error creating AutoML model, code: {0}, response: {1}'.format(resp.status_code, contenresp.text) print('Full response:\n{0}'.format(resp.text)) # Record operation_name so we can poll for it later. response = json.loads(resp.text) operation_name = response['name'] ``` The output of the previous step is also an [operation](https://cloud.google.com/vision/automl/docs/models#get-operation) that will need to poll the status of. We will poll until the operation's "done" field is set to true. This will take a few minutes to complete. ``` path = os.path.join(AUTOML_API_URL, operation_name) timeout = time.time() + 40*60 # Wait up to 40 minutes. sleep_time = 5*60 # Update each 5 minutes. response = wait_for_operation_completion(path, timeout, sleep_time) full_model_name = response['response']['name'] # google.cloud.automl to make api calls to Cloud AutoML !pip install google-cloud-automl from google.cloud import automl_v1 client = automl_v1.AutoMlClient() response = client.deploy_model(full_model_name) print(u'Model deployment finished. {}'.format(response.result())) ``` Next, we will check out the accuracy metrics for the trained model. The following command will return the [AUC (ROC)](https://developers.google.com/machine-learning/crash-course/classification/roc-and-auc), [precision](https://developers.google.com/machine-learning/crash-course/classification/precision-and-recall) and [recall](https://developers.google.com/machine-learning/crash-course/classification/precision-and-recall) for the model, for various ML classification thresholds. ``` # Path to request to get model accuracy metrics. path = os.path.join(AUTOML_API_URL, full_model_name, 'modelEvaluations') resp = authed_session.get(path) assert resp.status_code == 200, 'error getting AutoML model evaluations, code: {0}, response: {1}'.format(resp.status_code, resp.text) print('Full response:\n{0}'.format(resp.text)) ``` ## Inference To allow medical imaging ML models to be easily integrated into clinical workflows, an *inference module* can be used. A standalone modality, a PACS system or a DICOM router can push DICOM instances into Cloud Healthcare [DICOM stores](https://cloud.google.com/healthcare/docs/introduction), allowing ML models to be triggered for inference. This inference results can then be structured into various DICOM formats (e.g. DICOM [structured reports](http://dicom.nema.org/MEDICAL/Dicom/2014b/output/chtml/part20/sect_A.3.html)) and stored in the Cloud Healthcare API, which can then be retrieved by the customer. The inference module is built as a [Docker](https://www.docker.com/) container and deployed using [Kubernetes](https://kubernetes.io/), allowing you to easily scale your deployment. The dataflow for inference can look as follows (see corresponding diagram below): 1. Client application uses [STOW-RS](ftp://dicom.nema.org/medical/Dicom/2013/output/chtml/part18/sect_6.6.html) to push a new DICOM instance to the Cloud Healthcare DICOMWeb API. 2. The insertion of the DICOM instance triggers a [Cloud Pubsub](https://cloud.google.com/pubsub/) message to be published. The *inference module* will pull incoming Pubsub messages and will recieve a message for the previously inserted DICOM instance. 3. The *inference module* will retrieve the instance in JPEG format from the Cloud Healthcare API using [WADO-RS](ftp://dicom.nema.org/medical/Dicom/2013/output/chtml/part18/sect_6.5.html). 4. The *inference module* will send the JPEG bytes to the model hosted on AutoML. 5. AutoML will return the prediction back to the *inference module*. 6. The *inference module* will package the prediction into a DICOM instance. This can potentially be a DICOM structured report, [presentation state](ftp://dicom.nema.org/MEDICAL/dicom/2014b/output/chtml/part03/sect_A.33.html), or even burnt text on the image. In this codelab, we will focus on just DICOM structured reports, specifically [Comprehensive Structured Reports](http://dicom.nema.org/dicom/2013/output/chtml/part20/sect_A.3.html). The structured report is then stored back in the Cloud Healthcare API using STOW-RS. 7. The client application can query for (or retrieve) the structured report by using [QIDO-RS](http://dicom.nema.org/dicom/2013/output/chtml/part18/sect_6.7.html) or WADO-RS. Pubsub can also be used by the client application to poll for the newly created DICOM structured report instance. ![Inference data flow](images/automl_inference_pipeline.png) To begin, we will create a new DICOM store that will store our inference source (DICOM mammography instance) and results (DICOM structured report). In order to enable Pubsub notifications to be triggered on inserted instances, we will give the DICOM store a Pubsub channel to publish on. ``` # Pubsub config. pubsub_topic_id = "MY_PUBSUB_TOPIC_ID" # @param pubsub_subscription_id = "MY_PUBSUB_SUBSRIPTION_ID" # @param # DICOM Store for store DICOM used for inference. inference_dicom_store_id = "MY_INFERENCE_DICOM_STORE" # @param pubsub_subscription_name = "projects/" + project_id + "/subscriptions/" + pubsub_subscription_id inference_dicom_store_path = dicom_path.FromPath(dicom_store_path, store_id=inference_dicom_store_id) %%bash -s {pubsub_topic_id} {pubsub_subscription_id} {project_id} {location} {dataset_id} {inference_dicom_store_id} # Create Pubsub channel. gcloud beta pubsub topics create $1 gcloud beta pubsub subscriptions create $2 --topic $1 # Create a Cloud Healthcare DICOM store that published on given Pubsub topic. TOKEN=`gcloud beta auth application-default print-access-token` NOTIFICATION_CONFIG="{notification_config: {pubsub_topic: \"projects/$3/topics/$1\"}}" curl -s -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ${TOKEN}" -d "${NOTIFICATION_CONFIG}" https://healthcare.googleapis.com/v1/projects/$3/locations/$4/datasets/$5/dicomStores?dicom_store_id=$6 # Enable Cloud Healthcare API to publish on given Pubsub topic. PROJECT_NUMBER=`gcloud projects describe $3 | grep projectNumber | sed 's/[^0-9]//g'` SERVICE_ACCOUNT="service-${PROJECT_NUMBER}@gcp-sa-healthcare.iam.gserviceaccount.com" gcloud beta pubsub topics add-iam-policy-binding $1 --member="serviceAccount:${SERVICE_ACCOUNT}" --role="roles/pubsub.publisher" ``` Next, we will building the *inference module* using [Cloud Build API](https://cloud.google.com/cloud-build/docs/api/reference/rest/). This will create a Docker container that will be stored in [Google Container Registry](https://cloud.google.com/container-registry/). The inference module code is found in *[inference.py](./scripts/inference/inference.py)*. The build script used to build the Docker container for this module is *[cloudbuild.yaml](./scripts/inference/cloudbuild.yaml)*. Progress of build may be found on [cloud build dashboard](https://console.cloud.google.com/cloud-build/builds?project=). ``` %%bash -s {project_id} PROJECT_ID=$1 gcloud builds submit --config scripts/inference/cloudbuild.yaml --timeout 1h scripts/inference ``` Next, we will deploy the *inference module* to Kubernetes. Then we create a Kubernetes Cluster and a Deployment for the *inference module*. ``` %%bash -s {project_id} {location} {pubsub_subscription_name} {full_model_name} {inference_dicom_store_path} gcloud container clusters create inference-module --region=$2 --scopes https://www.googleapis.com/auth/cloud-platform --num-nodes=1 PROJECT_ID=$1 SUBSCRIPTION_PATH=$3 MODEL_PATH=$4 INFERENCE_DICOM_STORE_PATH=$5 cat <<EOF | kubectl create -f - apiVersion: extensions/v1beta1 kind: Deployment metadata: name: inference-module namespace: default spec: replicas: 1 template: metadata: labels: app: inference-module spec: containers: - name: inference-module image: gcr.io/${PROJECT_ID}/inference-module:latest command: - "/opt/inference_module/bin/inference_module" - "--subscription_path=${SUBSCRIPTION_PATH}" - "--model_path=${MODEL_PATH}" - "--dicom_store_path=${INFERENCE_DICOM_STORE_PATH}" - "--prediction_service=AutoML" EOF ``` Next, we will store a mammography DICOM instance from the TCIA dataset to the DICOM store. This is the image that we will request inference for. Pushing this instance to the DICOM store will result in a Pubsub message, which will trigger the *inference module*. ``` # DICOM Study/Series UID of input mammography image that we'll push for inference. input_mammo_study_uid = "1.3.6.1.4.1.9590.100.1.2.85935434310203356712688695661986996009" input_mammo_series_uid = "1.3.6.1.4.1.9590.100.1.2.374115997511889073021386151921807063992" input_mammo_instance_uid = "1.3.6.1.4.1.9590.100.1.2.289923739312470966435676008311959891294" from google.cloud import storage from dicomweb_client.api import DICOMwebClient from dicomweb_client import session_utils from pydicom storage_client = storage.Client() bucket = storage_client.bucket('gcs-public-data--healthcare-tcia-cbis-ddsm', user_project=project_id) blob = bucket.blob("dicom/{}/{}/{}.dcm".format(input_mammo_study_uid,input_mammo_series_uid,input_mammo_instance_uid)) blob.download_to_filename('example.dcm') dataset = pydicom.dcmread('example.dcm') session = session_utils.create_session_from_gcp_credentials() study_path = dicom_path.FromPath(inference_dicom_store_path, study_uid=input_mammo_study_uid) dicomweb_url = os.path.join(HEALTHCARE_API_URL, study_path.dicomweb_path_str) dcm_client = DICOMwebClient(dicomweb_url, session) dcm_client.store_instances(datasets=[dataset]) ``` You should be able to observe the *inference module*'s logs by running the following command. In the logs, you should observe that the inference module successfully recieved the the Pubsub message and ran inference on the DICOM instance. The logs should also include the inference results. It can take a few minutes for the Kubernetes deployment to start up, so you many need to run this a few times. The logs should also include the inference results. It can take a few minutes for the Kubernetes deployment to start up, so you many need to run this a few times. ``` !kubectl logs -l app=inference-module ``` You can also query the Cloud Healthcare DICOMWeb API (using QIDO-RS) to see that the DICOM structured report has been inserted for the study. The structured report contents can be found under tag **"0040A730"**. You can optionally also use WADO-RS to recieve the instance (e.g. for viewing). ``` dcm_client.search_for_instances(study_path.study_uid, fields=['all']) ```
github_jupyter
# Lab 2: networkX Drawing and Network Properties ``` import matplotlib.pyplot as plt import pandas as pd from networkx import nx ``` ## TOC 1. [Q1](#Q1) 2. [Q2](#Q2) 3. [Q3](#Q3) 4. [Q4](#Q4) ``` fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(11, 8)) ax = axes.flatten() path = nx.path_graph(5) nx.draw_networkx(path, with_labels=True, ax=ax[0]) ax[0].set_title('Path') cycle = nx.cycle_graph(5) nx.draw_networkx(cycle, node_color='green', with_labels=True, ax=ax[1]) ax[1].set_title('Cycle') complete = nx.complete_graph(5) nx.draw_networkx(complete, node_color='#A0CBE2', edge_color='red', width=2, with_labels=False, ax=ax[2]) ax[2].set_title('Complete') star = nx.star_graph(5) pos=nx.spring_layout(star) nx.draw_networkx(star, pos, with_labels=True, ax=ax[3]) ax[3].set_title('Star') for i in range(4): ax[i].set_axis_off() plt.show() ``` ### Q1: *Use one sentence each to briefly describe the characteristics of each graph type (its shape, edges, etc..)* $V$ = a set of vertices, where $V \ni \{v_1, v_2, ... , v_n\}$ $E$ = a set of edges, where $E \subseteq \{\{v_x,v_y\}\mid v_x,v_y\in V\}$ Let $G$ = ($V$, $E$) be an undirected graph - **Path Graph** := Suppose there are n vertices ($v_0, v_1, ... , v_n$) in $G$, such that $\forall e_{(v_x,v_y)} \in E $ | $0 \leq x \leq n-1$; $y = x + 1$ - **Cycle Graph** := Suppose there are n vertices ($v_0, v_1, ... , v_n$) in $G$, such that $\forall e_{(v_x,v_y)} \in E $ | $0 \leq x \leq n; \{(0 \leq x \leq n-1) \Rightarrow (y = x + 1)\} \land \{(x = n) \Rightarrow (y = 0)\}$ - **Complete Graph**:= Suppose there are n vertices ($v_0, v_1, ... , v_n$) in $G$, such that $\forall e_{(v_x,v_y)} \in E $ | $x \neq y; 0 \leq x,y \leq n$ - **Star Graph** := Suppose there are n vertices ($v_0, v_1, ... , v_n$) in $G$, such that $\forall e_{(v_x,v_y)} \in E $ | $x = 0; 1 \leq y \leq n$ ``` G = nx.lollipop_graph(3,2) nx.draw(G, with_labels=True) plt.show() list(nx.connected_components(G)) nx.clustering(G) ``` ### Q2: *How many connected components are there in the graph? What are they?* There is only one connected component in the graph, it's all 5 vertices of the graph ### Q3: *Which nodes have the highest local clustering coefficient? Explain (from the definition) why they have high clustering coefficient.* Node 0 and 1 have the highest local clustering coefficient of 1, because the neighbor of these two nodes are each other and node 2, $(2*1\text{ between neighbor link})\div(2\text{ degrees}*(2-1)) = 1$ ``` def netMeta(net): meta = {} meta["radius"]= nx.radius(net) meta["diameter"]= nx.diameter(net) meta["eccentricity"]= nx.eccentricity(net) meta["center"]= nx.center(net) meta["periphery"]= nx.periphery(net) meta["density"]= nx.density(net) return meta netMeta(G) def netAna(net): cols = ['Node name', "Betweenness centrality", "Degree centrality", "Closeness centrality", "Eigenvector centrality"] rows =[] print() a = nx.betweenness_centrality(net) b = nx.degree_centrality(net) c = nx.closeness_centrality(net) d = nx.eigenvector_centrality(net) for v in net.nodes(): temp = [] temp.append(v) temp.append(a[v]) temp.append(b[v]) temp.append(c[v]) temp.append(d[v]) rows.append(temp) df = pd.DataFrame(rows,columns=cols) df.set_index('Node name', inplace = True) return df G_stat = netAna(G) G_stat G_stat.sort_values(by=['Eigenvector centrality']) ``` ### Q4: *Which node(s) has the highest betweenness, degree, closeness, eigenvector centrality? Explain using the definitions and graph structures.* Node 2 has the highest betweenness, degree, closeness, and eigenvector centrality Because node 2 has the most geodesics passing through, it has the highest degree of 3, it has the shortest average path length, and it has the most refferences by its neighbors ``` pathlengths = [] print("source vertex {target:length, }") for v in G.nodes(): spl = dict(nx.single_source_shortest_path_length(G, v)) print('{} {} '.format(v, spl)) for p in spl: pathlengths.append(spl[p]) print('') print("average shortest path length %s" % (sum(pathlengths) / len(pathlengths))) dist = {} for p in pathlengths: if p in dist: dist[p] += 1 else: dist[p] = 1 print('') print("length #paths") verts = dist.keys() for d in sorted(verts): print('%s %d' % (d, dist[d])) mapping = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'} H = nx.relabel_nodes(G, mapping) nx.draw(H, with_labels=True) plt.show() ```
github_jupyter
# Lesson 1 Experiments This section just reproduces lesson 1 logic using my own code and with 30 tennis and 30 basketball player images. I chose all male players for simplicity. ``` # Put these at the top of every notebook, to get automatic reloading and inline plotting %reload_ext autoreload %autoreload 2 %matplotlib inline # This file contains all the main external libs we'll use from fastai.imports import * from fastai.transforms import * from fastai.conv_learner import * from fastai.model import * from fastai.dataset import * from fastai.sgdr import * from fastai.plots import * from typing import List, Union from pathlib import Path ``` ## Download the Sample Data Only execute the cell below once! If the commands below don't work, try the direct link [here](https://1drv.ms/u/s!AkhwiUY5vHPCs03Q26908HIwKFkG). ``` !wget 'https://onedrive.live.com/download?cid=C273BC3946897048&resid=C273BC3946897048%216605&authkey=AIVFQLj7IoJYiz4' -O foo.zip !unzip -d data foo.zip !rm foo.zip ``` ## Load the Sample Data ``` sz=224 path = Path('data/tennisbball') path.absolute(), list(path.glob('*')) sample = plt.imread(next(iter((path / 'valid' / 'tennis').iterdir()))) plt.imshow(sample) plt.figure() sample = plt.imread(next(iter((path / 'valid' / 'bball').iterdir()))) plt.imshow(sample) sample.shape, sample[:4,:4] torch.cuda.is_available(),torch.backends.cudnn.enabled ``` ## Construct the Model Define the model architecture ``` #tfms_from_model -- model based image transforms (preprocessing stats) arch=resnet50 data = ImageClassifierData.from_paths(path, test_name='test', test_with_labels=True, tfms=tfms_from_model(arch, sz)) #precompute=True to save conv layer activations! pass False if you want to run the data viz below learner = ConvLearner.pretrained(f=arch, data=data, precompute=False) ``` ## Train a Model This section trains a model using transfer learning. ``` learner.fit(0.01, 15) #uncomment line below to save the model #learner.save('tennis_v_bball.lrnr') ``` ## Load/Visualize an Existing Model Or if you've already trained a model, skip the above section and start from here. ``` learner.load('tennis_v_bball.lrnr') probs = np.exp(learner.predict()) probs #TODO: improve def display_images(images:List[Union[Path, np.ndarray]], columns:int, titles:List[str]=None, figsize=None) -> None: if not titles: titles = [f'Image {i+1}' for i in range(len(images))] rows = len(images) // columns + int(len(images) % columns > 0) if figsize is None: figsize = (60,60) plt.figure(figsize=figsize) for i, (image, title) in enumerate(zip(images, titles)): if isinstance(image, Path): image = np.array(PIL.Image.open(image)) plt.subplot(rows, columns, i+1) plt.imshow(image) plt.title(title, fontsize=10*columns) plt.axis('off') #val images predictions = probs.argmax(axis=1) images, titles = [], [] for prob, pclass, fname in zip(probs, predictions, data.val_ds.fnames): images.append(path / fname) titles.append(f'{fname} -- {prob[pclass]:.{3}f} ({data.classes[pclass]})') display_images(images, 4, titles) test_probs = np.exp(learner.predict(is_test=True)) test_predictions = test_probs.argmax(axis=1) #test images images, titles = [],[] for prob, pclass, fname in zip(test_probs, test_predictions, data.test_ds.fnames): images.append(path / fname) titles.append(f'{fname} -- {prob[pclass]:.{3}f} ({data.classes[pclass]})') display_images(images, 4, titles) ``` ## Dataviz -- Activations ``` #check out the model structure model = learner.model model # # utilize torch hooks to capture the activations for any conv layer. for simplicity we use a # batch size of 1. # class ActivationHook: def __init__(self): self.output = [] def __call__(self, module, input, output): self.output = output.data def find_layers(module, ltype): rv = [] if isinstance(module, ltype): rv.append(module) else: for c in module.children(): rv.extend(find_layers(c, ltype)) return rv def capture_activations(model, x): layers = find_layers(model, nn.Conv2d) hooks = [ActivationHook() for _ in layers] handles = [conv.register_forward_hook(hook) for conv, hook in zip(layers, hooks)] model(x) for h in handles: h.remove() return [h.output for h in hooks] bs = data.bs data.bs = 1 dl = data.get_dl(data.test_ds, False) i = iter(dl) ball_x = next(i)[0] noball_x = next(i)[0] data.bs = bs ball_activations = capture_activations(model, Variable(ball_x)) noball_activations = capture_activations(model, Variable(noball_x)) for i, layer_output in enumerate(ball_activations): print(f'Layer {i}: {layer_output.squeeze().shape}') #layer 5, filter 18, 36 seems to like circular type things layer_idx = 0 images = [] titles = [] num_filters = ball_activations[layer_idx].shape[1] asize = ball_activations[layer_idx].shape[2] def filter_activations_to_image(activations, lidx, fidx): a = activations[lidx].squeeze() #choose conv layer & discard batch dimension a = a[fidx] #choose conv filter a = (a - a.mean())/(3*a.std()) + 0.5 #center and scale down a = a.clamp(0, 1).numpy() # and finally clamp return a buff_size = 10 for filter_idx in range(num_filters): a0 = filter_activations_to_image(ball_activations, layer_idx, filter_idx) a1 = filter_activations_to_image(noball_activations, layer_idx, filter_idx) z = np.hstack([a0, np.ones((asize, 10)), a1]) plt.imshow(z, cmap='gray') plt.axis('off') plt.title(f'Filter {filter_idx}') plt.show() ``` ## DataViz -- Filters We can also look at filters. This is easiest at the first layer where each filter is 3 dimensional. ``` import matplotlib.colors as mc import math conv = find_layers(learner.model, nn.Conv2d)[0] weight = conv.weight.data.numpy() num_filters, depth, w, h = weight.shape rows = int(num_filters**0.5) cols = int(math.ceil(num_filters/rows)) border = 1 img = np.zeros((depth, rows*h + (1+rows)*border, cols*w + (1+cols)*border)) for f in range(num_filters): r = f // rows c = f % cols x = border + r * (w+border) y = border + c * (w+border) norm = mc.Normalize() img[:, x:x+w, y:y+h] = norm(weight[f, :, :, :]) plt.figure(figsize=(12,12)) plt.imshow(img.transpose(1,2,0)) _ = plt.axis('off') ``` We can also visualize subsequent layers, though it's not so pretty. We can map each dimension of each filter back into grayscale. ``` # for i, conv in enumerate(find_layers(learner.model, nn.Conv2d)): # print(conv, conv.weight.shape) weight = find_layers(learner.model, nn.Conv2d)[2].weight.data.numpy() num_filters, depth, w, h = weight.shape rows = num_filters cols = depth border = 1 img = np.zeros((rows*h + (1+rows)*border, cols*w + (1+cols)*border)) for f in range(num_filters): norm = mc.Normalize() normed = norm(weight[f, :, :, :]) #normalize over all the weights in a filter for d in range(depth): r = f c = d x = border + r * (w+border) y = border + c * (w+border) img[x:x+w, y:y+h] = normed[d] plt.figure(figsize=(18,18)) plt.imshow(img, cmap='gray') _ = plt.axis('off') ``` ## Occlusion We can also mask out portions of the image by sliding a gray block over the image repeatedly and record how the predictions change. ``` block_size = 50 image_path = path / data.test_ds.fnames[0] image = open_image(image_path) image[50:250, 50:250] = np.full((200,200,3), 0.75) scaled_image = Scale(sz=224).do_transform(orig_image, False) # image[0:block_size, 0:block_size] = np.full((block_size,block_size,3), 0.75) plt.imshow(image) _ = plt.axis('off') block_size = 50 image_path = path / data.test_ds.fnames[0] orig_image = open_image(image_path) # image[0:200, 0:200] = np.full((200,200,3), 0.75) scaled_image = Scale(sz=224).do_transform(orig_image, False) # image[0:block_size, 0:block_size] = np.full((block_size,block_size,3), 0.75) # plt.imshow(image) plt.axis('off') #the prediction for the smaller image should be essentially unchanged print(learner.model(VV(tfms_from_model(arch, sz)[1](scaled_image)).unsqueeze(0)).exp()) w,h,_ = scaled_image.shape learner.model.eval() t0 = time.time() prob_map = np.zeros((2, w, h)) z = 0 #TODO: add stride for efficiency. for x in tqdm(range(1 - block_size, w)): for y in range(1 - block_size, h): image = np.array(scaled_image) x0, x1 = max(0, x), min(w, x + block_size) y0, y1 = max(0, y), min(h, y + block_size) image[x0:x1,y0:y1] = np.full((x1-x0, y1-y0, 3), 0.75) image = tfms_from_model(arch, sz)[1](image) predictions = learner.model(VV(image).unsqueeze(0)) prob_map[0,x0:x1,y0:y1] += predictions.exp().data[0][0] prob_map[1,x0:x1,y0:y1] += 1 np.save('probs-heatmap.npy', prob_map) heatmap = prob_map[0]/prob_map[1] plt.subplot(1,2,1) plt.imshow(1 - heatmap, cmap='jet') plt.axis('off') plt.subplot(1,2,2) plt.imshow(orig_image) _ = plt.axis('off') block_size = 50 image_path = path / 'valid/bball/29.jpg' orig_image = open_image(image_path) # image[0:200, 0:200] = np.full((200,200,3), 0.75) scaled_image = Scale(sz=224).do_transform(orig_image, False) # orig_image[0:block_size, 0:block_size] = np.full((block_size,block_size,3), 0.75) # plt.imshow(orig_image) # plt.axis('off') #the prediction for the smaller image should be essentially unchanged print(learner.model(VV(tfms_from_model(arch, sz)[1](scaled_image)).unsqueeze(0)).exp()) w,h,_ = scaled_image.shape learner.model.eval() t0 = time.time() prob_map = np.zeros((2, w, h)) z = 0 #TODO: add stride for efficiency. for x in tqdm(range(1 - block_size, w)): for y in range(1 - block_size, h):b image = np.array(scaled_image) x0, x1 = max(0, x), min(w, x + block_size) y0, y1 = max(0, y), min(h, y + block_size) image[x0:x1,y0:y1] = np.full((x1-x0, y1-y0, 3), 0.75) image = tfms_from_model(arch, sz)[1](image) predictions = learner.model(VV(image).unsqueeze(0)) prob_map[0,x0:x1,y0:y1] += predictions.exp().data[0][0] prob_map[1,x0:x1,y0:y1] += 1 np.save('probs-giannis-heatmap.npy', prob_map) heatmap = prob_map[0]/prob_map[1] plt.subplot(1,2,1) plt.imshow(1 - heatmap, cmap='jet') plt.axis('off') plt.subplot(1,2,2) plt.imshow(orig_image) _ = plt.axis('off') block_size = 50 image_path = path / 'valid/tennis/23.jpg' orig_image = open_image(image_path) # image[0:200, 0:200] = np.full((200,200,3), 0.75) scaled_image = Scale(sz=224).do_transform(orig_image, False) # orig_image[0:block_size, 0:block_size] = np.full((block_size,block_size,3), 0.75) plt.imshow(scaled_image) # plt.axis('off') #the prediction for the smaller image should be essentially unchanged print(learner.model(VV(tfms_from_model(arch, sz)[1](scaled_image)).unsqueeze(0)).exp()) w,h,_ = scaled_image.shape learner.model.eval() t0 = time.time() prob_map = np.zeros((2, w, h)) z = 0 #TODO: add stride for efficiency. for x in tqdm(range(1 - block_size, w)): for y in range(1 - block_size, h): image = np.array(scaled_image) x0, x1 = max(0, x), min(w, x + block_size) y0, y1 = max(0, y), min(h, y + block_size) image[x0:x1,y0:y1] = np.full((x1-x0, y1-y0, 3), 0.75) image = tfms_from_model(arch, sz)[1](image) predictions = learner.model(VV(image).unsqueeze(0)) prob_map[0,x0:x1,y0:y1] += predictions.exp().data[0][0] prob_map[1,x0:x1,y0:y1] += 1 np.save('probs-tennis-heatmap.npy', prob_map) heatmap = prob_map[0]/prob_map[1] plt.subplot(1,2,1) plt.imshow(heatmap, cmap='jet') plt.axis('off') plt.subplot(1,2,2) plt.imshow(orig_image) _ = plt.axis('off') ```
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Recurrent Neural Networks (RNN) with Keras <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/guide/keras/rnn"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/keras/rnn.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/keras/rnn.ipynb"> <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a> </td> <td> <a target="_blank" href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/keras/rnn.ipynb"> <img src="https://www.tensorflow.org/images/download_logo_32px.png" /> Download notebook</a> </td> </table> Recurrent neural networks (RNN) are a class of neural networks that is powerful for modeling sequence data such as time series or natural language. Schematically, a RNN layer uses a `for` loop to iterate over the timesteps of a sequence, while maintaining an internal state that encodes information about the timesteps it has seen so far. The Keras RNN API is designed with a focus on: - **Ease of use**: the built-in `tf.keras.layers.RNN`, `tf.keras.layers.LSTM`, `tf.keras.layers.GRU` layers enable you to quickly build recurrent models without having to make difficult configuration choices. - **Ease of customization**: You can also define your own RNN cell layer (the inner part of the `for` loop) with custom behavior, and use it with the generic `tf.keras.layers.RNN` layer (the `for` loop itself). This allows you to quickly prototype different research ideas in a flexible way with minimal code. ## Setup ``` import collections import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow.keras import layers ``` ## Build a simple model There are three built-in RNN layers in Keras: 1. `tf.keras.layers.SimpleRNN`, a fully-connected RNN where the output from previous timestep is to be fed to next timestep. 2. `tf.keras.layers.GRU`, first proposed in [Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation](https://arxiv.org/abs/1406.1078). 3. `tf.keras.layers.LSTM`, first proposed in [Long Short-Term Memory](https://www.bioinf.jku.at/publications/older/2604.pdf). In early 2015, Keras had the first reusable open-source Python implementations of LSTM and GRU. Here is a simple example of a `Sequential` model that processes sequences of integers, embeds each integer into a 64-dimensional vector, then processes the sequence of vectors using a `LSTM` layer. ``` model = tf.keras.Sequential() # Add an Embedding layer expecting input vocab of size 1000, and # output embedding dimension of size 64. model.add(layers.Embedding(input_dim=1000, output_dim=64)) # Add a LSTM layer with 128 internal units. model.add(layers.LSTM(128)) # Add a Dense layer with 10 units. model.add(layers.Dense(10)) model.summary() ``` ## Outputs and states By default, the output of a RNN layer contain a single vector per sample. This vector is the RNN cell output corresponding to the last timestep, containing information about the entire input sequence. The shape of this output is `(batch_size, units)` where `units` corresponds to the `units` argument passed to the layer's constructor. A RNN layer can also return the entire sequence of outputs for each sample (one vector per timestep per sample), if you set `return_sequences=True`. The shape of this output is `(batch_size, timesteps, units)`. ``` model = tf.keras.Sequential() model.add(layers.Embedding(input_dim=1000, output_dim=64)) # The output of GRU will be a 3D tensor of shape (batch_size, timesteps, 256) model.add(layers.GRU(256, return_sequences=True)) # The output of SimpleRNN will be a 2D tensor of shape (batch_size, 128) model.add(layers.SimpleRNN(128)) model.add(layers.Dense(10)) model.summary() ``` In addition, a RNN layer can return its final internal state(s). The returned states can be used to resume the RNN execution later, or [to initialize another RNN](https://arxiv.org/abs/1409.3215). This setting is commonly used in the encoder-decoder sequence-to-sequence model, where the encoder final state is used as the initial state of the decoder. To configure a RNN layer to return its internal state, set the `return_state` parameter to `True` when creating the layer. Note that `LSTM` has 2 state tensors, but `GRU` only has one. To configure the initial state of the layer, just call the layer with additional keyword argument `initial_state`. Note that the shape of the state needs to match the unit size of the layer, like in the example below. ``` encoder_vocab = 1000 decoder_vocab = 2000 encoder_input = layers.Input(shape=(None, )) encoder_embedded = layers.Embedding(input_dim=encoder_vocab, output_dim=64)(encoder_input) # Return states in addition to output output, state_h, state_c = layers.LSTM( 64, return_state=True, name='encoder')(encoder_embedded) encoder_state = [state_h, state_c] decoder_input = layers.Input(shape=(None, )) decoder_embedded = layers.Embedding(input_dim=decoder_vocab, output_dim=64)(decoder_input) # Pass the 2 states to a new LSTM layer, as initial state decoder_output = layers.LSTM( 64, name='decoder')(decoder_embedded, initial_state=encoder_state) output = layers.Dense(10)(decoder_output) model = tf.keras.Model([encoder_input, decoder_input], output) model.summary() ``` ## RNN layers and RNN cells In addition to the built-in RNN layers, the RNN API also provides cell-level APIs. Unlike RNN layers, which processes whole batches of input sequences, the RNN cell only processes a single timestep. The cell is the inside of the `for` loop of a RNN layer. Wrapping a cell inside a `tf.keras.layers.RNN` layer gives you a layer capable of processing batches of sequences, e.g. `RNN(LSTMCell(10))`. Mathematically, `RNN(LSTMCell(10))` produces the same result as `LSTM(10)`. In fact, the implementation of this layer in TF v1.x was just creating the corresponding RNN cell and wrapping it in a RNN layer. However using the built-in `GRU` and `LSTM` layers enables the use of CuDNN and you may see better performance. There are three built-in RNN cells, each of them corresponding to the matching RNN layer. - `tf.keras.layers.SimpleRNNCell` corresponds to the `SimpleRNN` layer. - `tf.keras.layers.GRUCell` corresponds to the `GRU` layer. - `tf.keras.layers.LSTMCell` corresponds to the `LSTM` layer. The cell abstraction, together with the generic `tf.keras.layers.RNN` class, make it very easy to implement custom RNN architectures for your research. ## Cross-batch statefulness When processing very long sequences (possibly infinite), you may want to use the pattern of **cross-batch statefulness**. Normally, the internal state of a RNN layer is reset every time it sees a new batch (i.e. every sample seen by the layer is assume to be independent from the past). The layer will only maintain a state while processing a given sample. If you have very long sequences though, it is useful to break them into shorter sequences, and to feed these shorter sequences sequentially into a RNN layer without resetting the layer's state. That way, the layer can retain information about the entirety of the sequence, even though it's only seeing one sub-sequence at a time. You can do this by setting `stateful=True` in the constructor. If you have a sequence `s = [t0, t1, ... t1546, t1547]`, you would split it into e.g. ``` s1 = [t0, t1, ... t100] s2 = [t101, ... t201] ... s16 = [t1501, ... t1547] ``` Then you would process it via: ```python lstm_layer = layers.LSTM(64, stateful=True) for s in sub_sequences: output = lstm_layer(s) ``` When you want to clear the state, you can use `layer.reset_states()`. > Note: In this setup, sample `i` in a given batch is assumed to be the continuation of sample `i` in the previous batch. This means that all batches should contain the same number of samples (batch size). E.g. if a batch contains `[sequence_A_from_t0_to_t100, sequence_B_from_t0_to_t100]`, the next batch should contain `[sequence_A_from_t101_to_t200, sequence_B_from_t101_to_t200]`. Here is a complete example: ``` paragraph1 = np.random.random((20, 10, 50)).astype(np.float32) paragraph2 = np.random.random((20, 10, 50)).astype(np.float32) paragraph3 = np.random.random((20, 10, 50)).astype(np.float32) lstm_layer = layers.LSTM(64, stateful=True) output = lstm_layer(paragraph1) output = lstm_layer(paragraph2) output = lstm_layer(paragraph3) # reset_states() will reset the cached state to the original initial_state. # If no initial_state was provided, zero-states will be used by default. lstm_layer.reset_states() ``` ### RNN State Reuse <a id="rnn_state_reuse"></a> The recorded states of the RNN layer are not included in the `layer.weights()`. If you would like to reuse the state from a RNN layer, you can retrieve the states value by `layer.states` and use it as the initial state for a new layer via the Keras functional API like `new_layer(inputs, initial_state=layer.states)`, or model subclassing. Please also note that sequential model might not be used in this case since it only supports layers with single input and output, the extra input of initial state makes it impossible to use here. ``` paragraph1 = np.random.random((20, 10, 50)).astype(np.float32) paragraph2 = np.random.random((20, 10, 50)).astype(np.float32) paragraph3 = np.random.random((20, 10, 50)).astype(np.float32) lstm_layer = layers.LSTM(64, stateful=True) output = lstm_layer(paragraph1) output = lstm_layer(paragraph2) existing_state = lstm_layer.states new_lstm_layer = layers.LSTM(64) new_output = new_lstm_layer(paragraph3, initial_state=existing_state) ``` ##Bidirectional RNNs For sequences other than time series (e.g. text), it is often the case that a RNN model can perform better if it not only processes sequence from start to end, but also backwards. For example, to predict the next word in a sentence, it is often useful to have the context around the word, not only just the words that come before it. Keras provides an easy API for you to build such bidirectional RNNs: the `tf.keras.layers.Bidirectional` wrapper. ``` model = tf.keras.Sequential() model.add(layers.Bidirectional(layers.LSTM(64, return_sequences=True), input_shape=(5, 10))) model.add(layers.Bidirectional(layers.LSTM(32))) model.add(layers.Dense(10)) model.summary() ``` Under the hood, `Bidirectional` will copy the RNN layer passed in, and flip the `go_backwards` field of the newly copied layer, so that it will process the inputs in reverse order. The output of the `Bidirectional` RNN will be, by default, the concatenation of the forward layer output and the backward layer output. If you need a different merging behavior, e.g. sum, change the `merge_mode` parameter in the `Bidirectional` wrapper constructor. For more details about `Bidirectional`, please check [the API docs](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/Bidirectional). ## Performance optimization and CuDNN kernels in TensorFlow 2.0 In TensorFlow 2.0, the built-in LSTM and GRU layers have been updated to leverage CuDNN kernels by default when a GPU is available. With this change, the prior `keras.layers.CuDNNLSTM/CuDNNGRU` layers have been deprecated, and you can build your model without worrying about the hardware it will run on. Since the CuDNN kernel is built with certain assumptions, this means the layer **will not be able to use the CuDNN kernel if you change the defaults of the built-in LSTM or GRU layers**. E.g.: - Changing the `activation` function from `tanh` to something else. - Changing the `recurrent_activation` function from `sigmoid` to something else. - Using `recurrent_dropout` > 0. - Setting `unroll` to True, which forces LSTM/GRU to decompose the inner `tf.while_loop` into an unrolled `for` loop. - Setting `use_bias` to False. - Using masking when the input data is not strictly right padded (if the mask corresponds to strictly right padded data, CuDNN can still be used. This is the most common case). For the detailed list of constraints, please see the documentation for the [LSTM](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/LSTM) and [GRU](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/GRU) layers. ### Using CuDNN kernels when available Let's build a simple LSTM model to demonstrate the performance difference. We'll use as input sequences the sequence of rows of MNIST digits (treating each row of pixels as a timestep), and we'll predict the digit's label. ``` batch_size = 64 # Each MNIST image batch is a tensor of shape (batch_size, 28, 28). # Each input sequence will be of size (28, 28) (height is treated like time). input_dim = 28 units = 64 output_size = 10 # labels are from 0 to 9 # Build the RNN model def build_model(allow_cudnn_kernel=True): # CuDNN is only available at the layer level, and not at the cell level. # This means `LSTM(units)` will use the CuDNN kernel, # while RNN(LSTMCell(units)) will run on non-CuDNN kernel. if allow_cudnn_kernel: # The LSTM layer with default options uses CuDNN. lstm_layer = tf.keras.layers.LSTM(units, input_shape=(None, input_dim)) else: # Wrapping a LSTMCell in a RNN layer will not use CuDNN. lstm_layer = tf.keras.layers.RNN( tf.keras.layers.LSTMCell(units), input_shape=(None, input_dim)) model = tf.keras.models.Sequential([ lstm_layer, tf.keras.layers.BatchNormalization(), tf.keras.layers.Dense(output_size)] ) return model ``` ### Load MNIST dataset ``` mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 sample, sample_label = x_train[0], y_train[0] ``` ### Create a model instance and compile it We choose `sparse_categorical_crossentropy` as the loss function for the model. The output of the model has shape of `[batch_size, 10]`. The target for the model is a integer vector, each of the integer is in the range of 0 to 9. ``` model = build_model(allow_cudnn_kernel=True) model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer='sgd', metrics=['accuracy']) model.fit(x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=5) ``` ### Build a new model without CuDNN kernel ``` slow_model = build_model(allow_cudnn_kernel=False) slow_model.set_weights(model.get_weights()) slow_model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer='sgd', metrics=['accuracy']) slow_model.fit(x_train, y_train, validation_data=(x_test, y_test), batch_size=batch_size, epochs=1) # We only train for one epoch because it's slower. ``` As you can see, the model built with CuDNN is much faster to train compared to the model that use the regular TensorFlow kernel. The same CuDNN-enabled model can also be use to run inference in a CPU-only environment. The `tf.device` annotation below is just forcing the device placement. The model will run on CPU by default if no GPU is available. You simply don't have to worry about the hardware you're running on anymore. Isn't that pretty cool? ``` with tf.device('CPU:0'): cpu_model = build_model(allow_cudnn_kernel=True) cpu_model.set_weights(model.get_weights()) result = tf.argmax(cpu_model.predict_on_batch(tf.expand_dims(sample, 0)), axis=1) print('Predicted result is: %s, target result is: %s' % (result.numpy(), sample_label)) plt.imshow(sample, cmap=plt.get_cmap('gray')) ``` ## RNNs with list/dict inputs, or nested inputs Nested structures allow implementers to include more information within a single timestep. For example, a video frame could have audio and video input at the same time. The data shape in this case could be: `[batch, timestep, {"video": [height, width, channel], "audio": [frequency]}]` In another example, handwriting data could have both coordinates x and y for the current position of the pen, as well as pressure information. So the data representation could be: `[batch, timestep, {"location": [x, y], "pressure": [force]}]` The following code provides an example of how to build a custom RNN cell that accepts such structured inputs. ### Define a custom cell that support nested input/output See [Custom Layers and Models](custom_layers_and_models.ipynb) for details on writing your own layers. ``` class NestedCell(tf.keras.layers.Layer): def __init__(self, unit_1, unit_2, unit_3, **kwargs): self.unit_1 = unit_1 self.unit_2 = unit_2 self.unit_3 = unit_3 self.state_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])] self.output_size = [tf.TensorShape([unit_1]), tf.TensorShape([unit_2, unit_3])] super(NestedCell, self).__init__(**kwargs) def build(self, input_shapes): # expect input_shape to contain 2 items, [(batch, i1), (batch, i2, i3)] i1 = input_shapes[0][1] i2 = input_shapes[1][1] i3 = input_shapes[1][2] self.kernel_1 = self.add_weight( shape=(i1, self.unit_1), initializer='uniform', name='kernel_1') self.kernel_2_3 = self.add_weight( shape=(i2, i3, self.unit_2, self.unit_3), initializer='uniform', name='kernel_2_3') def call(self, inputs, states): # inputs should be in [(batch, input_1), (batch, input_2, input_3)] # state should be in shape [(batch, unit_1), (batch, unit_2, unit_3)] input_1, input_2 = tf.nest.flatten(inputs) s1, s2 = states output_1 = tf.matmul(input_1, self.kernel_1) output_2_3 = tf.einsum('bij,ijkl->bkl', input_2, self.kernel_2_3) state_1 = s1 + output_1 state_2_3 = s2 + output_2_3 output = (output_1, output_2_3) new_states = (state_1, state_2_3) return output, new_states def get_config(self): return {'unit_1':self.unit_1, 'unit_2':unit_2, 'unit_3':self.unit_3} ``` ### Build a RNN model with nested input/output Let's build a Keras model that uses a `tf.keras.layers.RNN` layer and the custom cell we just defined. ``` unit_1 = 10 unit_2 = 20 unit_3 = 30 i1 = 32 i2 = 64 i3 = 32 batch_size = 64 num_batches = 100 timestep = 50 cell = NestedCell(unit_1, unit_2, unit_3) rnn = tf.keras.layers.RNN(cell) input_1 = tf.keras.Input((None, i1)) input_2 = tf.keras.Input((None, i2, i3)) outputs = rnn((input_1, input_2)) model = tf.keras.models.Model([input_1, input_2], outputs) model.compile(optimizer='adam', loss='mse', metrics=['accuracy']) ``` ### Train the model with randomly generated data Since there isn't a good candidate dataset for this model, we use random Numpy data for demonstration. ``` input_1_data = np.random.random((batch_size * num_batches, timestep, i1)) input_2_data = np.random.random((batch_size * num_batches, timestep, i2, i3)) target_1_data = np.random.random((batch_size * num_batches, unit_1)) target_2_data = np.random.random((batch_size * num_batches, unit_2, unit_3)) input_data = [input_1_data, input_2_data] target_data = [target_1_data, target_2_data] model.fit(input_data, target_data, batch_size=batch_size) ``` With the Keras `tf.keras.layers.RNN` layer, You are only expected to define the math logic for individual step within the sequence, and the `tf.keras.layers.RNN` layer will handle the sequence iteration for you. It's an incredibly powerful way to quickly prototype new kinds of RNNs (e.g. a LSTM variant). For more details, please visit the [API docs](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/keras/layers/RNN).
github_jupyter
# Tutorial In this notebook, we will see how to pass your own encoder and decoder's architectures to your VAE model using pythae! ``` # If you run on colab uncomment the following line #!pip install git+https://github.com/clementchadebec/benchmark_VAE.git import torch import torchvision.datasets as datasets import matplotlib.pyplot as plt import numpy as np import os %matplotlib inline %load_ext autoreload %autoreload 2 ``` ### Get the data ``` mnist_trainset = datasets.MNIST(root='../data', train=True, download=True, transform=None) n_samples = 200 dataset = mnist_trainset.data[np.array(mnist_trainset.targets)==2][:n_samples].reshape(-1, 1, 28, 28) / 255. fig, axes = plt.subplots(2, 10, figsize=(10, 2)) for i in range(2): for j in range(10): axes[i][j].matshow(dataset[i*10 +j].reshape(28, 28), cmap='gray') axes[i][j].axis('off') plt.tight_layout(pad=0.8) ``` ## Let's build a custom auto-encoding architecture! ### First thing, you need to import the ``BaseEncoder`` and ``BaseDecoder`` as well as ``ModelOutput`` classes from pythae by running ``` from pythae.models.nn import BaseEncoder, BaseDecoder from pythae.models.base.base_utils import ModelOutput ``` ### Then build your own architectures ``` import torch.nn as nn class Encoder_VAE_MNIST(BaseEncoder): def __init__(self, args): BaseEncoder.__init__(self) self.input_dim = (1, 28, 28) self.latent_dim = args.latent_dim self.n_channels = 1 self.conv_layers = nn.Sequential( nn.Conv2d(self.n_channels, 128, 4, 2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(128, 256, 4, 2, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.Conv2d(256, 512, 4, 2, padding=1), nn.BatchNorm2d(512), nn.ReLU(), nn.Conv2d(512, 1024, 4, 2, padding=1), nn.BatchNorm2d(1024), nn.ReLU(), ) self.embedding = nn.Linear(1024, args.latent_dim) self.log_var = nn.Linear(1024, args.latent_dim) def forward(self, x: torch.Tensor): h1 = self.conv_layers(x).reshape(x.shape[0], -1) output = ModelOutput( embedding=self.embedding(h1), log_covariance=self.log_var(h1) ) return output class Decoder_AE_MNIST(BaseDecoder): def __init__(self, args): BaseDecoder.__init__(self) self.input_dim = (1, 28, 28) self.latent_dim = args.latent_dim self.n_channels = 1 self.fc = nn.Linear(args.latent_dim, 1024 * 4 * 4) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(1024, 512, 3, 2, padding=1), nn.BatchNorm2d(512), nn.ReLU(), nn.ConvTranspose2d(512, 256, 3, 2, padding=1, output_padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.ConvTranspose2d(256, self.n_channels, 3, 2, padding=1, output_padding=1), nn.Sigmoid(), ) def forward(self, z: torch.Tensor): h1 = self.fc(z).reshape(z.shape[0], 1024, 4, 4) output = ModelOutput(reconstruction=self.deconv_layers(h1)) return output ``` ### Define a model configuration (in which the latent will be stated). Here, we use the RHVAE model. ``` from pythae.models import VAEConfig model_config = VAEConfig( input_dim=(1, 28, 28), latent_dim=10 ) ``` ### Build your encoder and decoder ``` encoder = Encoder_VAE_MNIST(model_config) decoder= Decoder_AE_MNIST(model_config) ``` ### Last but not least. Build you RHVAE model by passing the ``encoder`` and ``decoder`` arguments ``` from pythae.models import VAE model = VAE( model_config=model_config, encoder=encoder, decoder=decoder ) ``` ### Now you can see the model that you've just built contains the custom autoencoder and decoder ``` model ``` ### *note*: If you want to launch a training of such a model, try to ensure that the provided architectures are suited for the data. pythae performs a model sanity check before launching training and raises an error if the model cannot encode and decode an input data point ## Train the model ! ``` from pythae.trainers import BaseTrainerConfig from pythae.pipelines import TrainingPipeline ``` ### Build the training pipeline with your ``TrainingConfig`` instance ``` training_config = BaseTrainerConfig( output_dir='my_model_with_custom_archi', learning_rate=1e-3, batch_size=200, steps_saving=None, num_epochs=200) pipeline = TrainingPipeline( model=model, training_config=training_config) ``` ### Launch the ``Pipeline`` ``` torch.manual_seed(8) torch.cuda.manual_seed(8) pipeline( train_data=dataset ) ``` ### *note 1*: You will see now that a ``encoder.pkl`` and ``decoder.pkl`` appear in the folder ``my_model_with_custom_archi/training_YYYY_MM_DD_hh_mm_ss/final_model`` to allow model rebuilding with your own architecture ``Encoder_VAE_MNIST`` and ``Decoder_AE_MNIST``. ### *note 2*: Model rebuilding is based on the [dill](https://pypi.org/project/dill/) librairy allowing to reload the class whithout importing them. Hence, you should still be able to reload the model even if the classes ``Encoder_VAE_MNIST`` or ``Decoder_AE_MNIST`` were not imported. ``` last_training = sorted(os.listdir('my_model_with_custom_archi'))[-1] print(last_training) ``` ### You can now reload the model easily using the classmethod ``VAE.load_from_folder`` ``` model_rec = VAE.load_from_folder(os.path.join('my_model_with_custom_archi', last_training, 'final_model')) model_rec ``` ## The model can now be used to generate new samples ! ``` from pythae.samplers import NormalSampler sampler = NormalSampler( model=model_rec ) gen_data = sampler.sample( num_samples=25 ) import matplotlib.pyplot as plt fig, axes = plt.subplots(nrows=5, ncols=5, figsize=(10, 10)) for i in range(5): for j in range(5): axes[i][j].imshow(gen_data[i*5 +j].cpu().reshape(28, 28), cmap='gray') axes[i][j].axis('off') plt.tight_layout(pad=0.) ```
github_jupyter
# Chapter 3 : pandas ``` #load watermark %load_ext watermark %watermark -a 'Gopala KR' -u -d -v -p watermark,numpy,pandas,matplotlib,nltk,sklearn,tensorflow,theano,mxnet,chainer,seaborn,keras,tflearn,bokeh,gensim ``` # pandas DataFrames ``` import numpy as np import scipy as sp import pandas as pd ``` ## Load the data file into data frame ``` from pandas.io.parsers import read_csv df = read_csv("WHO_first9cols.csv") print("Dataframe Top 5 rows:\n", df.head()) print("Shape:\n", df.shape) print("\n") print("Length:\n", len(df)) print("\n") print("Column Headers:\n", df.columns) print("\n") print("Data types:\n", df.dtypes) print("\n") print("Index:\n", df.index) print("\n") print("Values:\n", df.values) ``` # pandas Series ``` country_col = df["Country"] print("Type df:\n", type(df), "\n") print("Type country col:\n", type(country_col), "\n") print("Series shape:\n", country_col.shape, "\n") print("Series index:\n", country_col.index, "\n") print("Series values:\n", country_col.values, "\n") print("Series name:\n", country_col.name, "\n") print("Last 2 countries:\n", country_col[-2:], "\n") print("Last 2 countries type:\n", type(country_col[-2:]), "\n") last_col = df.columns[-1] print("Last df column signs:\n", last_col, np.sign(df[last_col]), "\n") np.sum([0, np.nan]) df.dtypes print(np.sum(df[last_col] - df[last_col].values)) ``` # Querying Data in pandas ``` !pip install quandl import quandl sunspots = quandl.get("SIDC/SUNSPOTS_A") print("Head 2:\n", sunspots.head(2) ) print("Tail 2:\n", sunspots.tail(2)) last_date = sunspots.index[-1] print("Last value:\n",sunspots.loc[last_date]) print("Values slice by date:\n", sunspots["20020101": "20131231"]) print("Slice from a list of indices:\n", sunspots.iloc[[2, 4, -4, -2]]) print("Scalar with Iloc:", sunspots.iloc[0, 0]) print("Scalar with iat", sunspots.iat[1, 0]) print("Boolean selection:\n", sunspots[sunspots > sunspots.mean()]) print("Boolean selection with column label:\n", sunspots[sunspots['Number of Observations'] > sunspots['Number of Observations'].mean()]) ``` # Statistics with pandas DataFrame ``` import quandl # Data from http://www.quandl.com/SIDC/SUNSPOTS_A-Sunspot-Numbers-Annual # PyPi url https://pypi.python.org/pypi/Quandl sunspots = quandl.get("SIDC/SUNSPOTS_A") print("Describe", sunspots.describe(),"\n") print("Non NaN observations", sunspots.count(),"\n") print("MAD", sunspots.mad(),"\n") print("Median", sunspots.median(),"\n") print("Min", sunspots.min(),"\n") print("Max", sunspots.max(),"\n") print("Mode", sunspots.mode(),"\n") print("Standard Deviation", sunspots.std(),"\n") print("Variance", sunspots.var(),"\n") print("Skewness", sunspots.skew(),"\n") print("Kurtosis", sunspots.kurt(),"\n") ``` # Data Aggregation ``` import pandas as pd from numpy.random import seed from numpy.random import rand from numpy.random import randint import numpy as np seed(42) df = pd.DataFrame({'Weather' : ['cold', 'hot', 'cold', 'hot', 'cold', 'hot', 'cold'], 'Food' : ['soup', 'soup', 'icecream', 'chocolate', 'icecream', 'icecream', 'soup'], 'Price' : 10 * rand(7), 'Number' : randint(1, 9)}) print(df) weather_group = df.groupby('Weather') i = 0 for name, group in weather_group: i = i + 1 print("Group", i, name) print(group) print("Weather group first\n", weather_group.first()) print("Weather group last\n", weather_group.last()) print("Weather group mean\n", weather_group.mean()) wf_group = df.groupby(['Weather', 'Food']) print("WF Groups", wf_group.groups) print("WF Aggregated\n", wf_group.agg([np.mean, np.median])) ``` # Concatenating and appending DataFrames ``` print("df :3\n", df[:3]) print("Concat Back together\n", pd.concat([df[:3], df[3:]])) print("Appending rows\n", df[:3].append(df[5:])) ``` # joining DataFrames ``` dests = pd.read_csv('dest.csv') print("Dests\n", dests) tips = pd.read_csv('tips.csv') print("Tips\n", tips) print("Merge() on key\n", pd.merge(dests, tips, on='EmpNr')) print("Dests join() tips\n", dests.join(tips, lsuffix='Dest', rsuffix='Tips')) print("Inner join with merge()\n", pd.merge(dests, tips, how='inner')) print("Outer join\n", pd.merge(dests, tips, how='outer')) ``` # Handlng missing Values ``` df = pd.read_csv('WHO_first9cols.csv') # Select first 3 rows of country and Net primary school enrolment ratio male (%) df = df[['Country', df.columns[-2]]][:2] print("New df\n", df) print("Null Values\n", pd.isnull(df)) print("Total Null Values\n", pd.isnull(df).sum()) print("Not Null Values\n", df.notnull()) print("Last Column Doubled\n", 2 * df[df.columns[-1]]) print("Last Column plus NaN\n", df[df.columns[-1]] + np.nan) print("Zero filled\n", df.fillna(0)) ``` # dealing with dates ``` print("Date range", pd.date_range('1/1/1900', periods=42, freq='D')) import sys try: print("Date range", pd.date_range('1/1/1677', periods=4, freq='D')) except: etype, value, _ = sys.exc_info() print("Error encountered", etype, value) offset = pd.DateOffset(seconds=2 ** 33/10 ** 9) mid = pd.to_datetime('1/1/1970') print("Start valid range", mid - offset) print("End valid range", mid + offset) print("With format", pd.to_datetime(['19021112', '19031230'], format='%Y%m%d')) print("Illegal date coerced", pd.to_datetime(['1902-11-12', 'not a date'], errors='coerce')) ``` # Pivot Tables ``` seed(42) N = 7 df = pd.DataFrame({ 'Weather' : ['cold', 'hot', 'cold', 'hot', 'cold', 'hot', 'cold'], 'Food' : ['soup', 'soup', 'icecream', 'chocolate', 'icecream', 'icecream', 'soup'], 'Price' : 10 * rand(N), 'Number' : randint(1, 9)}) print("DataFrame\n", df) print(pd.pivot_table(df, columns=['Food'], aggfunc=np.sum)) ```
github_jupyter
``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt from ttim import * ``` ### Theis ``` from scipy.special import exp1 def theis(r, t, T, S, Q): u = r ** 2 * S / (4 * T * t) h = -Q / (4 * np.pi * T) * exp1(u) return h def theisQr(r, t, T, S, Q): u = r ** 2 * S / (4 * T * t) return -Q / (2 * np.pi) * np.exp(-u) / r T = 500 S = 1e-4 t = np.logspace(-5, 0, 100) r = 30 Q = 788 htheis = theis(r, t, T, S, Q) Qrtheis = theisQr(r, t, T, S, Q) ml = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=1) w = Well(ml, tsandQ=[(0, Q)], rw=1e-5) ml.solve() h = ml.head(r, 0, t) Qx, Qy = ml.disvec(r, 0, t) plt.figure(figsize=(12, 4)) plt.subplot(121) plt.semilogx(t, htheis, 'b', label='theis') plt.semilogx(t, h[0], 'r--', label='ttim') plt.xlabel('time (day)') plt.ylabel('head (m)') plt.legend(); plt.subplot(122) plt.semilogx(t, Qrtheis, 'b', label='theis') plt.semilogx(t, Qx[0], 'r--', label='ttim') plt.xlabel('time (day)') plt.ylabel('head (m)') plt.legend(loc='best'); def test(M=10): ml = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=1, M=M) w = Well(ml, tsandQ=[(0, Q)], rw=1e-5) ml.solve(silent=True) h = ml.head(r, 0, t) return htheis - h[0] enumba = test(M=10) plt.plot(t, enumba, 'C1') plt.xlabel('time (d)') plt.ylabel('head difference Thies - Ttim'); plt.plot(t, Qrtheis - Qx[0]) plt.xlabel('time (d)') plt.ylabel('Qx difference Thies - Ttim'); def compare(M=10): ml = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=1, M=M) w = Well(ml, tsandQ=[(0, Q)], rw=1e-5) ml.solve(silent=True) h = ml.head(r, 0, t) rmse = np.sqrt(np.mean((h[0] - htheis)**2)) return rmse Mlist = np.arange(1, 21) rmse = np.zeros(len(Mlist)) for i, M in enumerate(Mlist): rmse[i] = compare(M) plt.semilogy(Mlist, rmse) plt.xlabel('Number of terms M') plt.xticks(np.arange(1, 21)) plt.ylabel('relative error') plt.title('comparison between TTim solution and Theis \n solution using numba and M terms') plt.grid() def volume(r, t=1): return -2 * np.pi * r * ml.head(r, 0, t) * ml.aq.Scoefaq[0] from scipy.integrate import quad quad(volume, 1e-5, np.inf) from scipy.special import exp1 def theis2(r, t, T, S, Q, tend): u1 = r ** 2 * S / (4 * T * t) u2 = r ** 2 * S / (4 * T * (t[t > tend] - tend)) h = -Q / (4 * np.pi * T) * exp1(u1) h[t > tend] -= -Q / (4 * np.pi * T) * exp1(u2) return h ml2 = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=10) w2 = Well(ml2, tsandQ=[(0, Q), (1, 0)]) ml2.solve() t2 = np.linspace(0.01, 2, 100) htheis2 = theis2(r, t2, T, S, Q, tend=1) h2 = ml2.head(r, 0, t2) plt.plot(t2, htheis2, 'b', label='theis') plt.plot(t2, h2[0], 'r--', label='ttim') plt.legend(loc='best'); ``` ### Hantush ``` T = 500 S = 1e-4 c = 1000 t = np.logspace(-5, 0, 100) r = 30 Q = 788 from scipy.integrate import quad def integrand_hantush(y, r, lab): return np.exp(-y - r ** 2 / (4 * lab ** 2 * y)) / y def hantush(r, t, T, S, c, Q, tstart=0): lab = np.sqrt(T * c) u = r ** 2 * S / (4 * T * (t - tstart)) F = quad(integrand_hantush, u, np.inf, args=(r, lab))[0] return -Q / (4 * np.pi * T) * F hantushvec = np.vectorize(hantush) ml = ModelMaq(kaq=25, z=[21, 20, 0], c=[1000], Saq=S/20, topboundary='semi', tmin=1e-5, tmax=1) w = Well(ml, tsandQ=[(0, Q)]) ml.solve() hhantush = hantushvec(30, t, T, S, c, Q) h = ml.head(r, 0, t) plt.semilogx(t, hhantush, 'b', label='hantush') plt.semilogx(t, h[0], 'r--', label='ttim') plt.legend(loc='best'); ``` ### Well with welbore storage ``` T = 500 S = 1e-4 t = np.logspace(-5, 0, 100) rw = 0.3 Q = 788 ml = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=1) w = Well(ml, rw=rw, tsandQ=[(0, Q)]) ml.solve() hnostorage = ml.head(rw, 0, t) ml = ModelMaq(kaq=25, z=[20, 0], Saq=S/20, tmin=1e-5, tmax=1) w = Well(ml, rw=rw, tsandQ=[(0, Q)], rc=rw) ml.solve() hstorage = ml.head(rw, 0, t) plt.semilogx(t, hnostorage[0], label='no storage') plt.semilogx(t, hstorage[0], label='with storage') plt.legend(loc='best') plt.xticks([1/(24*60*60), 1/(24 * 60), 1/24, 1], ['1 sec', '1 min', '1 hr', '1 d']); ``` ### Slug test ``` k = 25 H = 20 S = 1e-4 / H t = np.logspace(-7, -1, 100) rw = 0.2 rc = 0.2 delh = 1 ml = ModelMaq(kaq=k, z=[H, 0], Saq=S, tmin=1e-7, tmax=1) Qslug = np.pi * rc ** 2 * delh w = Well(ml, tsandQ=[(0, -Qslug)], rw=rw, rc=rc, wbstype='slug') ml.solve() h = w.headinside(t) plt.semilogx(t, h[0]) plt.xticks([1 / (24 * 60 * 60) / 10, 1 / (24 * 60 * 60), 1 / (24 * 60), 1 / 24], ['0.1 sec', '1 sec', '1 min', '1 hr']); ``` ### Slug test in 5-layer aquifer Well in top 2 layers ``` k = 25 H = 20 Ss = 1e-4 / H t = np.logspace(-7, -1, 100) rw = 0.2 rc = 0.2 delh = 1 ml = Model3D(kaq=k, z=np.linspace(H, 0, 6), Saq=Ss, tmin=1e-7, tmax=1) Qslug = np.pi * rc**2 * delh w = Well(ml, tsandQ=[(0, -Qslug)], rw=rw, rc=rc, layers=[0, 1], wbstype='slug') ml.solve() hw = w.headinside(t) plt.semilogx(t, hw[0], label='inside well') h = ml.head(0.2 + 1e-8, 0, t) for i in range(2, 5): plt.semilogx(t, h[i], label='layer' + str(i)) plt.legend() plt.xticks([1/(24*60*60)/10, 1/(24*60*60), 1/(24 * 60), 1/24], ['0.1 sec', '1 sec', '1 min', '1 hr']); ``` 20 layers ``` k = 25 H = 20 S = 1e-4 / H t = np.logspace(-7, -1, 100) rw = 0.2 rc = 0.2 delh = 1 ml = Model3D(kaq=k, z=np.linspace(H, 0, 21), Saq=S, tmin=1e-7, tmax=1) Qslug = np.pi * rc**2 * delh w = Well(ml, tsandQ=[(0, -Qslug)], rw=rw, rc=rc, layers=np.arange(8), wbstype='slug') ml.solve() hw = w.headinside(t) plt.semilogx(t, hw[0], label='inside well') h = ml.head(0.2 + 1e-8, 0, t) for i in range(8, 20): plt.semilogx(t, h[i], label='layer' + str(i)) plt.legend() plt.xticks([1/(24*60*60)/10, 1/(24*60*60), 1/(24 * 60), 1/24], ['0.1 sec', '1 sec', '1 min', '1 hr']); ``` ### Head Well ``` ml = ModelMaq(kaq=25, z=[20, 0], Saq=1e-5, tmin=1e-3, tmax=1000) w = HeadWell(ml, tsandh=[(0, -1)], rw=0.2) ml.solve() plt.figure(figsize=(12,5)) plt.subplot(1,2,1) ml.xsection(0.2, 100, 0, 0, 100, t=[0.1, 1, 10], sstart=0.2, newfig=False) t = np.logspace(-3, 3, 100) dis = w.discharge(t) plt.subplot(1,2,2) plt.semilogx(t, dis[0], label='rw=0.2') ml = ModelMaq(kaq=25, z=[20, 0], Saq=1e-5, tmin=1e-3, tmax=1000) w = HeadWell(ml, tsandh=[(0, -1)], rw=0.3) ml.solve() dis = w.discharge(t) plt.semilogx(t, dis[0], label='rw=0.3') plt.xlabel('time (d)') plt.ylabel('discharge (m3/d)') plt.legend(); ```
github_jupyter
``` %load_ext autoreload %autoreload 2 import argparse import sys from time import sleep import numpy as np from rdkit import Chem, DataStructs from rdkit.Chem import AllChem from rdkit.Chem.Crippen import MolLogP from sklearn.metrics import accuracy_score, mean_squared_error import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import Dataset, DataLoader #from utils import read_ZINC_smiles, smiles_to_onehot, partition, OneHotLogPDataSet from tqdm import tnrange, tqdm_notebook import pandas as pd import seaborn as sns paser = argparse.ArgumentParser() args = paser.parse_args("") args.seed = 123 args.val_size = 0.15 args.test_size = 0.15 args.shuffle = True np.random.seed(args.seed) torch.manual_seed(args.seed) ``` ## 1. Pre-Processing ``` def read_ZINC_smiles(file_name, num_mol): f = open(file_name, 'r') contents = f.readlines() smi_list = [] logP_list = [] for i in tqdm_notebook(range(num_mol), desc='Reading Data'): smi = contents[i].strip() m = Chem.MolFromSmiles(smi) smi_list.append(smi) logP_list.append(MolLogP(m)) logP_list = np.asarray(logP_list).astype(float) return smi_list, logP_list def smiles_to_onehot(smi_list): def smiles_to_vector(smiles, vocab, max_length): while len(smiles) < max_length: smiles += " " vector = [vocab.index(str(x)) for x in smiles] one_hot = np.zeros((len(vocab), max_length), dtype=int) for i, elm in enumerate(vector): one_hot[elm][i] = 1 return one_hot vocab = np.load('./vocab.npy') smi_total = [] for i, smi in tqdm_notebook(enumerate(smi_list), desc='Converting to One Hot'): smi_onehot = smiles_to_vector(smi, list(vocab), 120) smi_total.append(smi_onehot) return np.asarray(smi_total) def convert_to_graph(smiles_list): adj = [] adj_norm = [] features = [] maxNumAtoms = 50 for i in tqdm_notebook(smiles_list, desc='Converting to Graph'): # Mol iMol = Chem.MolFromSmiles(i.strip()) #Adj iAdjTmp = Chem.rdmolops.GetAdjacencyMatrix(iMol) # Feature if( iAdjTmp.shape[0] <= maxNumAtoms): # Feature-preprocessing iFeature = np.zeros((maxNumAtoms, 58)) iFeatureTmp = [] for atom in iMol.GetAtoms(): iFeatureTmp.append( atom_feature(atom) ) ### atom features only iFeature[0:len(iFeatureTmp), 0:58] = iFeatureTmp ### 0 padding for feature-set features.append(iFeature) # Adj-preprocessing iAdj = np.zeros((maxNumAtoms, maxNumAtoms)) iAdj[0:len(iFeatureTmp), 0:len(iFeatureTmp)] = iAdjTmp + np.eye(len(iFeatureTmp)) adj.append(np.asarray(iAdj)) features = np.asarray(features) return features, adj def atom_feature(atom): return np.array(one_of_k_encoding_unk(atom.GetSymbol(), ['C', 'N', 'O', 'S', 'F', 'H', 'Si', 'P', 'Cl', 'Br', 'Li', 'Na', 'K', 'Mg', 'Ca', 'Fe', 'As', 'Al', 'I', 'B', 'V', 'Tl', 'Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se', 'Ti', 'Zn', 'Ge', 'Cu', 'Au', 'Ni', 'Cd', 'Mn', 'Cr', 'Pt', 'Hg', 'Pb']) + one_of_k_encoding(atom.GetDegree(), [0, 1, 2, 3, 4, 5]) + one_of_k_encoding_unk(atom.GetTotalNumHs(), [0, 1, 2, 3, 4]) + one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1, 2, 3, 4, 5]) + [atom.GetIsAromatic()]) # (40, 6, 5, 6, 1) def one_of_k_encoding(x, allowable_set): if x not in allowable_set: raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set)) #print list((map(lambda s: x == s, allowable_set))) return list(map(lambda s: x == s, allowable_set)) def one_of_k_encoding_unk(x, allowable_set): """Maps inputs not in the allowable set to the last element.""" if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set)) class GCNDataset(Dataset): def __init__(self, list_feature, list_adj, list_logP): self.list_feature = list_feature self.list_adj = list_adj self.list_logP = list_logP def __len__(self): return len(self.list_feature) def __getitem__(self, index): return self.list_feature[index], self.list_adj[index], self.list_logP[index] def partition(list_feature, list_adj, list_logP, args): num_total = list_feature.shape[0] num_train = int(num_total * (1 - args.test_size - args.val_size)) num_val = int(num_total * args.val_size) num_test = int(num_total * args.test_size) feature_train = list_feature[:num_train] adj_train = list_adj[:num_train] logP_train = list_logP[:num_train] feature_val = list_feature[num_train:num_train + num_val] adj_val = list_adj[num_train:num_train + num_val] logP_val = list_logP[num_train:num_train + num_val] feature_test = list_feature[num_total - num_test:] adj_test = list_adj[num_train:num_train + num_val] logP_test = list_logP[num_total - num_test:] train_set = GCNDataset(feature_train, adj_train, logP_train) val_set = GCNDataset(feature_val, adj_val, logP_val) test_set = GCNDataset(feature_test, adj_test, logP_test) partition = { 'train': train_set, 'val': val_set, 'test': test_set } return partition list_smi, list_logP = read_ZINC_smiles('ZINC.smiles', 2000) list_feature, list_adj = convert_to_graph(list_smi) args.dict_partition = partition(list_feature, list_adj, list_logP, args) ``` ## 2. Model Construction ``` class GatedSkipConnection(nn.Module): def __init__(self, in_dim, new_dim, out_dim, activation): super(GatedSkipConnection, self).__init__() self.in_dim = in_dim self.new_dim = new_dim self.out_dim = out_dim self.activation = activation self.linear_in = nn.Linear(in_dim, out_dim) self.linear_new = nn.Linear(new_dim, out_dim) self.sigmoid = nn.Sigmoid() def forward(self, input_x, new_x): z = self.gate_coefficient(input_x, new_x) if (self.in_dim != self.out_dim): input_x = self.linear_in(input_x) if (self.new_dim != self.out_dim): new_x = self.linear_new(new_x) out = torch.mul(new_x, z) + torch.mul(input_x, 1.0-z) return out def gate_coefficient(self, input_x, new_x): X1 = self.linear_in(input_x) X2 = self.linear_new(new_x) gate_coefficient = self.sigmoid(X1 + X2) return gate_coefficient class GraphConvolution(nn.Module): def __init__(self, in_dim, hidden_dim, activation, sc='no'): super(GraphConvolution, self).__init__() self.in_dim = in_dim self.hidden_dim = hidden_dim self.activation = activation self.sc = sc self.linear = nn.Linear(self.in_dim, self.hidden_dim) nn.init.xavier_uniform_(self.linear.weight) self.gated_skip_connection = GatedSkipConnection(self.in_dim, self.hidden_dim, self.hidden_dim, self.activation) def forward(self, x, adj): out = self.linear(x) out = torch.matmul(adj, out) if (self.sc == 'gsc'): out = self.gated_skip_connection(x, out) elif (self.sc == 'no'): out = self.activation(out) else: out = self.activation(out) return out class ReadOut(nn.Module): def __init__(self, in_dim, out_dim, activation): super(ReadOut, self).__init__() self.in_dim = in_dim self.out_dim= out_dim self.linear = nn.Linear(self.in_dim, self.out_dim) nn.init.xavier_uniform_(self.linear.weight) self.activation = activation def forward(self, x): out = self.linear(x) out = torch.sum(out, dim=1) out = self.activation(out) return out class Predictor(nn.Module): def __init__(self, in_dim, out_dim, activation=None): super(Predictor, self).__init__() self.in_dim = in_dim self.out_dim = out_dim self.linear = nn.Linear(self.in_dim, self.out_dim) nn.init.xavier_uniform_(self.linear.weight) self.activation = activation def forward(self, x): out = self.linear(x) if self.activation != None: out = self.activation(out) return out class LogPPredictor(nn.Module): def __init__(self, n_layer, in_dim, hidden_dim_1, hidden_dim_2, out_dim, sc='no'): super(LogPPredictor, self).__init__() self.n_layer = n_layer self.graph_convolution_1 = GraphConvolution(in_dim, hidden_dim_1, nn.ReLU(), sc) self.graph_convolution_2 = GraphConvolution(hidden_dim_1, hidden_dim_1, nn.ReLU(), sc) self.readout = ReadOut(hidden_dim_1, hidden_dim_2, nn.Sigmoid()) self.predictor_1 = Predictor(hidden_dim_2, hidden_dim_2, nn.ReLU()) self.predictor_2 = Predictor(hidden_dim_2, hidden_dim_2, nn.Tanh()) self.predictor_3 = Predictor(hidden_dim_2, out_dim) def forward(self, x, adj): out = self.graph_convolution_1(x, adj) for i in range(self.n_layer-1): out = self.graph_convolution_2(out, adj) out = self.readout(out) out = self.predictor_1(out) out = self.predictor_2(out) out = self.predictor_3(out) return out args.batch_size = 10 args.lr = 0.001 args.l2_coef = 0.001 args.optim = optim.Adam args.criterion = nn.MSELoss() args.epoch = 10 args.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') use_gpu = lambda x=True: torch.set_default_tensor_type(torch.cuda.DoubleTensor if torch.cuda.is_available() and x else torch.FloatTensor) use_gpu() print(args.device) model = LogPPredictor(1, 58, 64, 128, 1, 'gsc') model.to(args.device) model.cuda() list_train_loss = list() list_val_loss = list() acc = 0 mse = 0 optimizer = args.optim(model.parameters(), lr=args.lr, weight_decay=args.l2_coef) data_train = DataLoader(args.dict_partition['train'], batch_size=args.batch_size, shuffle=args.shuffle) data_val = DataLoader(args.dict_partition['val'], batch_size=args.batch_size, shuffle=args.shuffle) for epoch in tqdm_notebook(range(args.epoch), desc='Epoch'): model.train() epoch_train_loss = 0 for i, batch in enumerate(data_train): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) optimizer.zero_grad() list_pred_logP = model(list_feature, list_adj) list_pred_logP.require_grad = False train_loss = args.criterion(list_pred_logP, list_logP) epoch_train_loss += train_loss.item() train_loss.backward() optimizer.step() list_train_loss.append(epoch_train_loss/len(data_train)) model.eval() epoch_val_loss = 0 with torch.no_grad(): for i, batch in enumerate(data_val): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) list_pred_logP = model(list_feature, list_adj) val_loss = args.criterion(list_pred_logP, list_logP) epoch_val_loss += val_loss.item() list_val_loss.append(epoch_val_loss/len(data_val)) data_test = DataLoader(args.dict_partition['test'], batch_size=args.batch_size, shuffle=args.shuffle) model.eval() with torch.no_grad(): logP_total = list() pred_logP_total = list() for i, batch in enumerate(data_val): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) logP_total += list_logP.tolist() list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) list_pred_logP = model(list_feature, list_adj) pred_logP_total += list_pred_logP.tolist() mse = mean_squared_error(logP_total, pred_logP_total) data = np.vstack((list_train_loss, list_val_loss)) data = np.transpose(data) epochs = np.arange(args.epoch) df_loss = pd.DataFrame(data, epochs, ["Train Loss", "Validation Loss"]) sns.set_style("darkgrid", {"axes.facecolor": ".9"}) grid = sns.lineplot(data=df_loss) grid.set_title("Loss vs Epoch (tox=nr-ahr)") grid.set_ylabel("Loss") grid.set_xlabel("Epoch") model = LogPPredictor(1, 58, 64, 128, 1, 'gsc') model.to(args.device) list_train_loss = list() list_val_loss = list() acc = 0 mse = 0 optimizer = args.optim(model.parameters(), lr=args.lr, weight_decay=args.l2_coef) data_train = DataLoader(args.dict_partition['train'], batch_size=args.batch_size, shuffle=args.shuffle) data_val = DataLoader(args.dict_partition['val'], batch_size=args.batch_size, shuffle=args.shuffle) for epoch in tqdm_notebook(range(args.epoch), desc='Epoch'): model.train() epoch_train_loss = 0 for i, batch in enumerate(data_train): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) optimizer.zero_grad() list_pred_logP = model(list_feature, list_adj) list_pred_logP.require_grad = False train_loss = args.criterion(list_pred_logP, list_logP) epoch_train_loss += train_loss.item() train_loss.backward() optimizer.step() list_train_loss.append(epoch_train_loss/len(data_train)) model.eval() epoch_val_loss = 0 with torch.no_grad(): for i, batch in enumerate(data_val): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) list_pred_logP = model(list_feature, list_adj) val_loss = args.criterion(list_pred_logP, list_logP) epoch_val_loss += val_loss.item() list_val_loss.append(epoch_val_loss/len(data_val)) data_test = DataLoader(args.dict_partition['test'], batch_size=args.batch_size, shuffle=args.shuffle) model.eval() with torch.no_grad(): logP_total = list() pred_logP_total = list() for i, batch in enumerate(data_val): list_feature = torch.tensor(batch[0]) list_adj = torch.tensor(batch[1]) list_logP = torch.tensor(batch[2]) logP_total += list_logP.tolist() list_logP = list_logP.view(-1,1) list_feature, list_adj, list_logP = list_feature.to(args.device), list_adj.to(args.device), list_logP.to(args.device) list_pred_logP = model(list_feature, list_adj) pred_logP_total += list_pred_logP.tolist() mse = mean_squared_error(logP_total, pred_logP_total) data = np.vstack((list_train_loss, list_val_loss)) data = np.transpose(data) epochs = np.arange(args.epoch) df_loss = pd.DataFrame(data, epochs, ["Train Loss", "Validation Loss"]) sns.set_style("darkgrid", {"axes.facecolor": ".9"}) grid = sns.lineplot(data=df_loss) grid.set_title("Loss vs Epoch (tox=nr-ahr)") grid.set_ylabel("Loss") grid.set_xlabel("Epoch") for i in tqdm_notebook(range(10), desc='1', leave=True, position=1): for j in tqdm_notebook(range(100), desc='2', leave=False, position=2): sleep(0.01) ```
github_jupyter
# Control In this notebook we want to control the chaos in the Henon map. The Henon map is defined by $$ \begin{align} x_{n+1}&=1-ax_n^2+y_n\\ y_{n+1}&=bx_n \end{align}. $$ ``` from plotly import offline as py from plotly import graph_objs as go py.init_notebook_mode(connected=True) ``` ### Fixed points First we need to find the fixed points of the Henon map. From $y_n=y_{n+1}=bx_n$ we can elliminate $y_n$ in the first equation. The quadratic equation obtained after ellimination with $x_n=x_{n+1}$ yields, $$ \begin{align} x^*=\frac{b-1\pm\sqrt{4a+(b-1)^2}}{2a}, && y^*=bx^*, \end{align} $$ as the fixed points of the Henon map. ``` def henon_map(x0, y0, a, b, N): x = [x0] y = [y0] for i in range(N): xn = x[-1] yn = y[-1] x.append(1 - a * xn**2 + yn) y.append(b * xn) return x, y def fixed_points(a, b): u = (b - 1) / (2 * a) v = np.sqrt(4 * a + (b - 1)**2) / (2 * a) x1 = u - v x2 = u + v y1 = b * x1 y2 = b * x2 return [(x1, y1), (x2, y2)] ((xf1, yf1), (xf2, yf2)) = fixed_points(a=1.4, b=0.3) radius = 0.1 layout = go.Layout( title='Henon Attractor', xaxis=dict(title='x'), yaxis=dict(title='y', scaleanchor='x'), showlegend=False, shapes=[ { 'type': 'circle', 'xref': 'x', 'yref': 'y', 'x0': xf1 + radius, 'y0': yf1 + radius, 'x1': xf1 - radius, 'y1': yf1 - radius, 'line': { 'color': 'gray' }, }, { 'type': 'circle', 'xref': 'x', 'yref': 'y', 'x0': xf2 + radius, 'y0': yf2 + radius, 'x1': xf2 - radius, 'y1': yf2 - radius, }, ] ) x = [] y = [] for i in range(50): x0, y0 = np.random.uniform(0.2, 0.8, 2) xx, yy = henon_map(x0, y0, a=1.4, b=0.3, N=100) if np.abs(xx[-1]) < 10 and np.abs(yy[-1]) < 10: x += xx y += yy figure = go.Figure([ go.Scatter(x=x, y=y, mode='markers', marker=dict(size=3)) ], layout) py.iplot(figure) ``` So the second fixed point (positive sign) sits on the attractor. ``` def fixed_point(a, b): return fixed_points(a, b)[1] fixed_point(a=1.4, b=0.3) ``` We assume that coordinates and parameters are sufficiently close such that the following Taylor expansion is valid,$$ \boldsymbol{x}_{n+1} = \boldsymbol{F}\left(\boldsymbol{x}^*,\boldsymbol{r}_0\right) + \frac{d\boldsymbol{F}}{d\boldsymbol{x}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0}\left(\boldsymbol{x}_n-\boldsymbol{x}^*\right) + \frac{d\boldsymbol{F}}{d\boldsymbol{r}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0}\left(\boldsymbol{r}_n-\boldsymbol{r}_0\right).$$ In the regime where these linear approximations are valid we can use, $$ \Delta\boldsymbol{r}_n = \gamma\left(\boldsymbol{x}_n-\boldsymbol{x}^*\right). $$ Further introducing $\Delta\boldsymbol{x}_n=\boldsymbol{x}_n-\boldsymbol{x}^*$ we can rewrite the map as, $$ \Delta\boldsymbol{x}_{n+1} = \underbrace{\left( \frac{d\boldsymbol{F}}{d\boldsymbol{x}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0} + \frac{d\boldsymbol{F}}{d\boldsymbol{r}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0} \right)}_{A} \Delta\boldsymbol{x}_n.$$ The Jacobians are $$ \begin{align} \frac{d\boldsymbol{F}}{d\boldsymbol{x}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0} = \begin{pmatrix} -2 a_0 x^* & 1 \\ b_0 & 0 \end{pmatrix}, && \frac{d\boldsymbol{F}}{d\boldsymbol{r}_n}\Bigr|_{\boldsymbol{x}^*,\boldsymbol{r}_0} = \begin{pmatrix} -{x^*}^2 & 0 \\ 0 & x^* \end{pmatrix} \end{align}. $$ Thus the matrix $A$ reads, $$ A = \begin{pmatrix} -2a_0x^*-\gamma{x^*}^2 & 1 \\ b_0 & \gamma x^* \end{pmatrix}. $$ The optimal value for $\gamma$ can be found for $0=A\Delta\boldsymbol{x}_n$. ``` def eigenvector(a, b): xf, yf = fixed_point(a, b) A = np.array([ [-2 * a * xf - xf**2, 1], [b, xf] ]) return u-v, u+v eigenvalues(a=1.4, b=0.3) ``` The Jacobian of the Henon map close to $(x^*,a_0,b_0)$ is given through, $$ \begin{pmatrix} -2 a_0 x^* & 1 \\ b_0 & 0 \end{pmatrix},$$ and has eigenvalues $$\lambda=-a_0\left[x^*\pm\sqrt{{x^*}^2+b_0/a_0^2}\right]$$ ``` fixed_point(a=1.4, b=0.3) ```
github_jupyter
# Single model ``` from consav import runtools runtools.write_numba_config(disable=0,threads=4) %matplotlib inline %load_ext autoreload %autoreload 2 # Local modules from Model import RetirementClass import SimulatedMinimumDistance as SMD import figs import funs # Global modules import numpy as np import matplotlib.pyplot as plt import seaborn as sns import time ``` ### Solve and simulate model ``` tic1 = time.time() Single = RetirementClass() tic2 = time.time() Single.recompute() tic3 = time.time() Single.solve() tic4 = time.time() Single.simulate(accuracy=True,tax=True) tic5 = time.time() print('Class :', round(tic2-tic1,2)) print('Precompute:', round(tic3-tic2,2)) print('Solve :', round(tic4-tic3,2)) print('Simulate :', round(tic5-tic4,2)) tic1 = time.time() Single.solve() tic2 = time.time() Single.simulate(accuracy=True,tax=True) tic3 = time.time() print('Solve :', round(tic2-tic1,2)) print('Simulate :', round(tic3-tic2,2)) ``` ### Retirement probabilities from solution Women ``` G = figs.choice_probs(Single,ma=0) G['legendsize'] = 12 G['marker'] = 'o' figs.MyPlot(G,linewidth=3).savefig('figs/Model/Single_ChoiceProb_Women.png') ``` Men ``` G = figs.choice_probs(Single,ma=1) G['legendsize'] = 12 G['marker'] = 'o' figs.MyPlot(G,linewidth=3).savefig('figs/Model/Single_ChoiceProb_Men.png') ``` ### Simulation ``` def rename_gender(G_lst): G_lst[0]['label'] = ['Women'] G_lst[1]['label'] = ['Men'] 936092.2561647706 - np.nansum(Single.sol.c) 37833823.081779644 - np.nansum(Single.sol.v) print(np.nansum(Single.par.labor)) print(np.nansum(Single.par.erp)) print(np.nansum(Single.par.oap)) Single.par.T_erp 68.51622393567519 - np.nansum(Single.par.erp) Single.par.pension_male = np.array([10.8277686, 18.94859504]) Single.par.pension_female = np.array([ 6.6438835, 11.62679612]) transitions.precompute_inc_single(Single.par) Single.solve() Single.simulate() Single.par.start_T = 53 Single.par.simT = Single.par.end_T - Single.par.start_T + 1 Single.par.var = np.array([0.202, 0.161]) Single.par.reg_labor_male = np.array((1.166, 0.360, 0.432, -0.406)) Single.par.reg_labor_female = np.array((4.261, 0.326, 0.303, -0.289)) Single.par.priv_pension_female = 728*1000/Single.par.denom Single.par.priv_pension_male = 1236*1000/Single.par.denom Single.solve(recompute=True) Single.simulate() np.nanmean(Single.sim.m[:,0]) Single.sim.m[:,0] = 20 Single.simulate() Gw = figs.retirement_probs(Single,MA=[0]) Gm = figs.retirement_probs(Single,MA=[1]) rename_gender([Gw,Gm]) figs.MyPlot([Gw,Gm],linewidth=3).savefig('figs/Model/SimSingleProbs') Gw = figs.retirement_probs(Single,MA=[0]) Gm = figs.retirement_probs(Single,MA=[1]) rename_gender([Gw,Gm]) figs.MyPlot([Gw,Gm],linewidth=3).savefig('figs/Model/SimSingleProbs') Gw = figs.retirement_probs(Single,MA=[0]) Gm = figs.retirement_probs(Single,MA=[1]) rename_gender([Gw,Gm]) figs.MyPlot([Gw,Gm],linewidth=3).savefig('figs/Model/SimSingleProbs') Gw = figs.lifecycle(Single,var='m',MA=[0],ages=[57,80]) Gm = figs.lifecycle(Single,var='m',MA=[1],ages=[57,80]) rename_gender([Gw,Gm]) figs.MyPlot([Gw,Gm],linewidth=3,save=False) Gw = figs.lifecycle(Single,var='c',MA=[0],ages=[57,80]) Gm = figs.lifecycle(Single,var='c',MA=[1],ages=[57,80]) rename_gender([Gw,Gm]) figs.MyPlot([Gw,Gm],linewidth=3,save=False) ``` ### Consumption functions Retired ``` G = figs.policy(Single,var='c',T=list(range(77,87))[::2],MA=[0],ST=[3],RA=[0],D=[0],label=['t']) G['legendsize'] = 12 figs.MyPlot(G,ylim=[0,12],save=False) G = figs.policy(Single,var='c',T=list(range(97,111))[::2],MA=[0],ST=[3],RA=[0],D=[0],label=['t']) G['legendsize'] = 12 figs.MyPlot(G,ylim=[0,16],save=False) ``` Working ``` G = figs.policy(Single,var='c',T=list(range(57,67))[::2],MA=[0],ST=[3],RA=[0],D=[1],label=['t']) G['legendsize'] = 12 figs.MyPlot(G,ylim=[0,8],save=False) G = figs.policy(Single,var='c',T=list(range(67,75))[::2],MA=[0],ST=[3],RA=[0],D=[1],label=['t']) G['legendsize'] = 12 figs.MyPlot(G,ylim=[0,10],save=False) ``` ### Simulation - Retirement ``` def rename(G_lst): G_lst[0]['label'] = ['High skilled'] G_lst[1]['label'] = ['Base'] G_lst[2]['label'] = ['Low skilled'] ``` Women ``` G_hs = figs.retirement_probs(Single,MA=[0],ST=[1,3]) G_base = figs.retirement_probs(Single,MA=[0]) G_ls = figs.retirement_probs(Single,MA=[0],ST=[0,2]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` Men ``` G_hs = figs.retirement_probs(Single,MA=[1],ST=[1,3]) G_base = figs.retirement_probs(Single,MA=[1]) G_ls = figs.retirement_probs(Single,MA=[1],ST=[0,2]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` ### Simulation - Consumption Women ``` G_hs = figs.lifecycle(Single,var='c',MA=[0],ST=[1,3],ages=[57,80]) G_base = figs.lifecycle(Single,var='c',MA=[0],ages=[57,80]) G_ls = figs.lifecycle(Single,var='c',MA=[0],ST=[0,2],ages=[57,80]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` Men ``` G_hs = figs.lifecycle(Single,var='c',MA=[1],ST=[1,3],ages=[57,80]) G_base = figs.lifecycle(Single,var='c',MA=[1],ages=[57,80]) G_ls = figs.lifecycle(Single,var='c',MA=[1],ST=[0,2],ages=[57,80]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` ### Simulation - Wealth Women ``` G_hs = figs.lifecycle(Single,var='m',MA=[0],ST=[1,3],ages=[57,68]) G_base = figs.lifecycle(Single,var='m',MA=[0],ages=[57,68]) G_ls = figs.lifecycle(Single,var='m',MA=[0],ST=[0,2],ages=[57,68]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` Men ``` G_hs = figs.lifecycle(Single,var='m',MA=[1],ST=[1,3],ages=[57,68]) G_base = figs.lifecycle(Single,var='m',MA=[1],ages=[57,68]) G_ls = figs.lifecycle(Single,var='m',MA=[1],ST=[0,2],ages=[57,68]) rename([G_hs,G_base,G_ls]) figs.MyPlot([G_hs,G_base,G_ls],linewidth=3,save=False) ``` ### Euler errors ``` MA = [0,1] ST = [0,1,2,3] ages = [Single.par.start_T,Single.par.end_T-1] for ma in MA: for st in ST: funs.log_euler(Single,MA=[ma],ST=[st],ages=ages,plot=True) print('Total:',funs.log_euler(Single,ages=ages)[0]) MA = [0,1] ST = [0,1,2,3] ages = [Single.par.start_T,Single.par.end_T-1] for ma in MA: for st in ST: funs.log_euler(Single,MA=[ma],ST=[st],ages=ages,plot=True) print('Total:',funs.log_euler(Single,ages=ages)[0]) Na = Single.par.Na funs.resolve(Single,Na=np.linspace(50,1000)) Single.par.Na = Na Single.recompute() # reset a_phi = test.par.a_phi funs.resolve(test,a_phi = np.linspace(1.0,2.0,num=10)) test.par.a_phi = a_phi test.solve(recompute=True) # reset ```
github_jupyter
# CNTK 201A Part A: CIFAR-10 Data Loader This tutorial will show how to prepare image data sets for use with deep learning algorithms in CNTK. The CIFAR-10 dataset (http://www.cs.toronto.edu/~kriz/cifar.html) is a popular dataset for image classification, collected by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. It is a labeled subset of the [80 million tiny images](http://people.csail.mit.edu/torralba/tinyimages/) dataset. The CIFAR-10 dataset is not included in the CNTK distribution but can be easily downloaded and converted to CNTK-supported format CNTK 201A tutorial is divided into two parts: - Part A: Familiarizes you with the CIFAR-10 data and converts them into CNTK supported format. This data will be used later in the tutorial for image classification tasks. - Part B: We will introduce image understanding tutorials. If you are curious about how well computers can perform on CIFAR-10 today, Rodrigo Benenson maintains a [blog](http://rodrigob.github.io/are_we_there_yet/build/classification_datasets_results.html#43494641522d3130) on the state-of-the-art performance of various algorithms. ``` from __future__ import print_function from PIL import Image import getopt import numpy as np import pickle as cp import os import shutil import struct import sys import tarfile import xml.etree.cElementTree as et import xml.dom.minidom try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve # Config matplotlib for inline plotting %matplotlib inline ``` ## Data download The CIFAR-10 dataset consists of 60,000 32x32 color images in 10 classes, with 6,000 images per class. There are 50,000 training images and 10,000 test images. The 10 classes are: airplane, automobile, bird, cat, deer, dog, frog, horse, ship, and truck. ``` # CIFAR Image data imgSize = 32 numFeature = imgSize * imgSize * 3 ``` We first setup a few helper functions to download the CIFAR data. The archive contains the files data_batch_1, data_batch_2, ..., data_batch_5, as well as test_batch. Each of these files is a Python "pickled" object produced with cPickle. To prepare the input data for use in CNTK we use three oprations: > `readBatch`: Unpack the pickle files > `loadData`: Compose the data into single train and test objects > `saveTxt`: As the name suggests, saves the label and the features into text files for both training and testing. ``` def readBatch(src): with open(src, 'rb') as f: if sys.version_info[0] < 3: d = cp.load(f) else: d = cp.load(f, encoding='latin1') data = d['data'] feat = data res = np.hstack((feat, np.reshape(d['labels'], (len(d['labels']), 1)))) return res.astype(np.int) def loadData(src): print ('Downloading ' + src) fname, h = urlretrieve(src, './delete.me') print ('Done.') try: print ('Extracting files...') with tarfile.open(fname) as tar: tar.extractall() print ('Done.') print ('Preparing train set...') trn = np.empty((0, numFeature + 1), dtype=np.int) for i in range(5): batchName = './cifar-10-batches-py/data_batch_{0}'.format(i + 1) trn = np.vstack((trn, readBatch(batchName))) print ('Done.') print ('Preparing test set...') tst = readBatch('./cifar-10-batches-py/test_batch') print ('Done.') finally: os.remove(fname) return (trn, tst) def saveTxt(filename, ndarray): with open(filename, 'w') as f: labels = list(map(' '.join, np.eye(10, dtype=np.uint).astype(str))) for row in ndarray: row_str = row.astype(str) label_str = labels[row[-1]] feature_str = ' '.join(row_str[:-1]) f.write('|labels {} |features {}\n'.format(label_str, feature_str)) ``` In addition to saving the images in the text format, we would save the images in PNG format. In addition we also compute the mean of the image. `saveImage` and `saveMean` are two functions used for this purpose. ``` def saveImage(fname, data, label, mapFile, regrFile, pad, **key_parms): # data in CIFAR-10 dataset is in CHW format. pixData = data.reshape((3, imgSize, imgSize)) if ('mean' in key_parms): key_parms['mean'] += pixData if pad > 0: pixData = np.pad(pixData, ((0, 0), (pad, pad), (pad, pad)), mode='constant', constant_values=128) img = Image.new('RGB', (imgSize + 2 * pad, imgSize + 2 * pad)) pixels = img.load() for x in range(img.size[0]): for y in range(img.size[1]): pixels[x, y] = (pixData[0][y][x], pixData[1][y][x], pixData[2][y][x]) img.save(fname) mapFile.write("%s\t%d\n" % (fname, label)) # compute per channel mean and store for regression example channelMean = np.mean(pixData, axis=(1,2)) regrFile.write("|regrLabels\t%f\t%f\t%f\n" % (channelMean[0]/255.0, channelMean[1]/255.0, channelMean[2]/255.0)) def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(imgSize) et.SubElement(root, 'Col').text = str(imgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' ')) ``` `saveTrainImages` and `saveTestImages` are simple wrapper functions to iterate through the data set. ``` def saveTrainImages(filename, foldername): if not os.path.exists(foldername): os.makedirs(foldername) data = {} dataMean = np.zeros((3, imgSize, imgSize)) # mean is in CHW format. with open('train_map.txt', 'w') as mapFile: with open('train_regrLabels.txt', 'w') as regrFile: for ifile in range(1, 6): with open(os.path.join('./cifar-10-batches-py', 'data_batch_' + str(ifile)), 'rb') as f: if sys.version_info[0] < 3: data = cp.load(f) else: data = cp.load(f, encoding='latin1') for i in range(10000): fname = os.path.join(os.path.abspath(foldername), ('%05d.png' % (i + (ifile - 1) * 10000))) saveImage(fname, data['data'][i, :], data['labels'][i], mapFile, regrFile, 4, mean=dataMean) dataMean = dataMean / (50 * 1000) saveMean('CIFAR-10_mean.xml', dataMean) def saveTestImages(filename, foldername): if not os.path.exists(foldername): os.makedirs(foldername) with open('test_map.txt', 'w') as mapFile: with open('test_regrLabels.txt', 'w') as regrFile: with open(os.path.join('./cifar-10-batches-py', 'test_batch'), 'rb') as f: if sys.version_info[0] < 3: data = cp.load(f) else: data = cp.load(f, encoding='latin1') for i in range(10000): fname = os.path.join(os.path.abspath(foldername), ('%05d.png' % i)) saveImage(fname, data['data'][i, :], data['labels'][i], mapFile, regrFile, 0) # URLs for the train image and labels data url_cifar_data = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' # Paths for saving the text files data_dir = './data/CIFAR-10/' train_filename = data_dir + '/Train_cntk_text.txt' test_filename = data_dir + '/Test_cntk_text.txt' train_img_directory = data_dir + '/Train' test_img_directory = data_dir + '/Test' root_dir = os.getcwd() if not os.path.exists(data_dir): os.makedirs(data_dir) try: os.chdir(data_dir) trn, tst= loadData('http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz') print ('Writing train text file...') saveTxt(r'./Train_cntk_text.txt', trn) print ('Done.') print ('Writing test text file...') saveTxt(r'./Test_cntk_text.txt', tst) print ('Done.') print ('Converting train data to png images...') saveTrainImages(r'./Train_cntk_text.txt', 'train') print ('Done.') print ('Converting test data to png images...') saveTestImages(r'./Test_cntk_text.txt', 'test') print ('Done.') finally: os.chdir("../..") ```
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Eager execution <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/guide/eager"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/guide/eager.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/guide/eager.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/eager.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> TensorFlow's eager execution is an imperative programming environment that evaluates operations immediately, without building graphs: operations return concrete values instead of constructing a computational graph to run later. This makes it easy to get started with TensorFlow and debug models, and it reduces boilerplate as well. To follow along with this guide, run the code samples below in an interactive `python` interpreter. Eager execution is a flexible machine learning platform for research and experimentation, providing: * *An intuitive interface*—Structure your code naturally and use Python data structures. Quickly iterate on small models and small data. * *Easier debugging*—Call ops directly to inspect running models and test changes. Use standard Python debugging tools for immediate error reporting. * *Natural control flow*—Use Python control flow instead of graph control flow, simplifying the specification of dynamic models. Eager execution supports most TensorFlow operations and GPU acceleration. Note: Some models may experience increased overhead with eager execution enabled. Performance improvements are ongoing, but please [file a bug](https://github.com/tensorflow/tensorflow/issues) if you find a problem and share your benchmarks. ## Setup and basic usage ``` from __future__ import absolute_import, division, print_function, unicode_literals import os try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x #gpu except Exception: pass import tensorflow as tf import cProfile ``` In Tensorflow 2.0, eager execution is enabled by default. ``` tf.executing_eagerly() ``` Now you can run TensorFlow operations and the results will return immediately: ``` x = [[2.]] m = tf.matmul(x, x) print("hello, {}".format(m)) ``` Enabling eager execution changes how TensorFlow operations behave—now they immediately evaluate and return their values to Python. `tf.Tensor` objects reference concrete values instead of symbolic handles to nodes in a computational graph. Since there isn't a computational graph to build and run later in a session, it's easy to inspect results using `print()` or a debugger. Evaluating, printing, and checking tensor values does not break the flow for computing gradients. Eager execution works nicely with [NumPy](http://www.numpy.org/). NumPy operations accept `tf.Tensor` arguments. TensorFlow [math operations](https://www.tensorflow.org/api_guides/python/math_ops) convert Python objects and NumPy arrays to `tf.Tensor` objects. The `tf.Tensor.numpy` method returns the object's value as a NumPy `ndarray`. ``` a = tf.constant([[1, 2], [3, 4]]) print(a) # Broadcasting support b = tf.add(a, 1) print(b) # Operator overloading is supported print(a * b) # Use NumPy values import numpy as np c = np.multiply(a, b) print(c) # Obtain numpy value from a tensor: print(a.numpy()) # => [[1 2] # [3 4]] ``` ## Dynamic control flow A major benefit of eager execution is that all the functionality of the host language is available while your model is executing. So, for example, it is easy to write [fizzbuzz](https://en.wikipedia.org/wiki/Fizz_buzz): ``` def fizzbuzz(max_num): counter = tf.constant(0) max_num = tf.convert_to_tensor(max_num) for num in range(1, max_num.numpy()+1): num = tf.constant(num) if int(num % 3) == 0 and int(num % 5) == 0: print('FizzBuzz') elif int(num % 3) == 0: print('Fizz') elif int(num % 5) == 0: print('Buzz') else: print(num.numpy()) counter += 1 fizzbuzz(15) ``` This has conditionals that depend on tensor values and it prints these values at runtime. ## Eager training ### Computing gradients [Automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) is useful for implementing machine learning algorithms such as [backpropagation](https://en.wikipedia.org/wiki/Backpropagation) for training neural networks. During eager execution, use `tf.GradientTape` to trace operations for computing gradients later. You can use `tf.GradientTape` to train and/or compute gradients in eager. It is especially useful for complicated training loops. Since different operations can occur during each call, all forward-pass operations get recorded to a "tape". To compute the gradient, play the tape backwards and then discard. A particular `tf.GradientTape` can only compute one gradient; subsequent calls throw a runtime error. ``` w = tf.Variable([[1.0]]) with tf.GradientTape() as tape: loss = w * w grad = tape.gradient(loss, w) print(grad) # => tf.Tensor([[ 2.]], shape=(1, 1), dtype=float32) ``` ### Train a model The following example creates a multi-layer model that classifies the standard MNIST handwritten digits. It demonstrates the optimizer and layer APIs to build trainable graphs in an eager execution environment. ``` # Fetch and format the mnist data (mnist_images, mnist_labels), _ = tf.keras.datasets.mnist.load_data() dataset = tf.data.Dataset.from_tensor_slices( (tf.cast(mnist_images[...,tf.newaxis]/255, tf.float32), tf.cast(mnist_labels,tf.int64))) dataset = dataset.shuffle(1000).batch(32) # Build the model mnist_model = tf.keras.Sequential([ tf.keras.layers.Conv2D(16,[3,3], activation='relu', input_shape=(None, None, 1)), tf.keras.layers.Conv2D(16,[3,3], activation='relu'), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(10) ]) ``` Even without training, call the model and inspect the output in eager execution: ``` for images,labels in dataset.take(1): print("Logits: ", mnist_model(images[0:1]).numpy()) ``` While keras models have a builtin training loop (using the `fit` method), sometimes you need more customization. Here's an example, of a training loop implemented with eager: ``` optimizer = tf.keras.optimizers.Adam() loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) loss_history = [] ``` Note: Use the assert functions in `tf.debugging` to check if a condition holds up. This works in eager and graph execution. ``` def train_step(images, labels): with tf.GradientTape() as tape: logits = mnist_model(images, training=True) # Add asserts to check the shape of the output. tf.debugging.assert_equal(logits.shape, (32, 10)) loss_value = loss_object(labels, logits) loss_history.append(loss_value.numpy().mean()) grads = tape.gradient(loss_value, mnist_model.trainable_variables) optimizer.apply_gradients(zip(grads, mnist_model.trainable_variables)) def train(epochs): for epoch in range(epochs): for (batch, (images, labels)) in enumerate(dataset): train_step(images, labels) print ('Epoch {} finished'.format(epoch)) train(epochs = 3) import matplotlib.pyplot as plt plt.plot(loss_history) plt.xlabel('Batch #') plt.ylabel('Loss [entropy]') ``` ### Variables and optimizers `tf.Variable` objects store mutable `tf.Tensor`-like values accessed during training to make automatic differentiation easier. The collections of variables can be encapsulated into layers or models, along with methods that operate on them. See [Custom Keras layers and models](./keras/custom_layers_and_models.ipynb) for details. The main difference between layers and models is that models add methods like `Model.fit`, `Model.evaluate`, and `Model.save`. For example, the automatic differentiation example above can be rewritten: ``` class Linear(tf.keras.Model): def __init__(self): super(Linear, self).__init__() self.W = tf.Variable(5., name='weight') self.B = tf.Variable(10., name='bias') def call(self, inputs): return inputs * self.W + self.B # A toy dataset of points around 3 * x + 2 NUM_EXAMPLES = 2000 training_inputs = tf.random.normal([NUM_EXAMPLES]) noise = tf.random.normal([NUM_EXAMPLES]) training_outputs = training_inputs * 3 + 2 + noise # The loss function to be optimized def loss(model, inputs, targets): error = model(inputs) - targets return tf.reduce_mean(tf.square(error)) def grad(model, inputs, targets): with tf.GradientTape() as tape: loss_value = loss(model, inputs, targets) return tape.gradient(loss_value, [model.W, model.B]) ``` Next: 1. Create the model. 2. The Derivatives of a loss function with respect to model parameters. 3. A strategy for updating the variables based on the derivatives. ``` model = Linear() optimizer = tf.keras.optimizers.SGD(learning_rate=0.01) print("Initial loss: {:.3f}".format(loss(model, training_inputs, training_outputs))) steps = 300 for i in range(steps): grads = grad(model, training_inputs, training_outputs) optimizer.apply_gradients(zip(grads, [model.W, model.B])) if i % 20 == 0: print("Loss at step {:03d}: {:.3f}".format(i, loss(model, training_inputs, training_outputs))) print("Final loss: {:.3f}".format(loss(model, training_inputs, training_outputs))) print("W = {}, B = {}".format(model.W.numpy(), model.B.numpy())) ``` Note: Variables persist until the last reference to the python object is removed, and is the variable is deleted. ### Object-based saving A `tf.keras.Model` includes a covienient `save_weights` method allowing you to easily create a checkpoint: ``` model.save_weights('weights') status = model.load_weights('weights') ``` Using `tf.train.Checkpoint` you can take full control over this process. This section is an abbreviated version of the [guide to training checkpoints](./checkpoint.ipynb). ``` x = tf.Variable(10.) checkpoint = tf.train.Checkpoint(x=x) x.assign(2.) # Assign a new value to the variables and save. checkpoint_path = './ckpt/' checkpoint.save('./ckpt/') x.assign(11.) # Change the variable after saving. # Restore values from the checkpoint checkpoint.restore(tf.train.latest_checkpoint(checkpoint_path)) print(x) # => 2.0 ``` To save and load models, `tf.train.Checkpoint` stores the internal state of objects, without requiring hidden variables. To record the state of a `model`, an `optimizer`, and a global step, pass them to a `tf.train.Checkpoint`: ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(16,[3,3], activation='relu'), tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(10) ]) optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) checkpoint_dir = 'path/to/model_dir' if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") root = tf.train.Checkpoint(optimizer=optimizer, model=model) root.save(checkpoint_prefix) root.restore(tf.train.latest_checkpoint(checkpoint_dir)) ``` Note: In many training loops, variables are created after `tf.train.Checkpoint.restore` is called. These variables will be restored as soon as they are created, and assertions are available to ensure that a checkpoint has been fully loaded. See the [guide to training checkpoints](./checkpoint.ipynb) for details. ### Object-oriented metrics `tf.keras.metrics` are stored as objects. Update a metric by passing the new data to the callable, and retrieve the result using the `tf.keras.metrics.result` method, for example: ``` m = tf.keras.metrics.Mean("loss") m(0) m(5) m.result() # => 2.5 m([8, 9]) m.result() # => 5.5 ``` ### Summaries and TensorBoard [TensorBoard](https://tensorflow.org/tensorboard) is a visualization tool for understanding, debugging and optimizing the model training process. It uses summary events that are written while executing the program. You can use `tf.summary` to record summaries of variable in eager execution. For example, to record summaries of `loss` once every 100 training steps: ``` logdir = "./tb/" writer = tf.summary.create_file_writer(logdir) steps = 1000 with writer.as_default(): # or call writer.set_as_default() before the loop. for i in range(steps): step = i + 1 # Calculate loss with your real train function. loss = 1 - 0.001 * step if step % 100 == 0: tf.summary.scalar('loss', loss, step=step) !ls tb/ ``` ## Advanced automatic differentiation topics ### Dynamic models `tf.GradientTape` can also be used in dynamic models. This example for a [backtracking line search](https://wikipedia.org/wiki/Backtracking_line_search) algorithm looks like normal NumPy code, except there are gradients and is differentiable, despite the complex control flow: ``` def line_search_step(fn, init_x, rate=1.0): with tf.GradientTape() as tape: # Variables are automatically tracked. # But to calculate a gradient from a tensor, you must `watch` it. tape.watch(init_x) value = fn(init_x) grad = tape.gradient(value, init_x) grad_norm = tf.reduce_sum(grad * grad) init_value = value while value > init_value - rate * grad_norm: x = init_x - rate * grad value = fn(x) rate /= 2.0 return x, value ``` ### Custom gradients Custom gradients are an easy way to override gradients. Within the forward function, define the gradient with respect to the inputs, outputs, or intermediate results. For example, here's an easy way to clip the norm of the gradients in the backward pass: ``` @tf.custom_gradient def clip_gradient_by_norm(x, norm): y = tf.identity(x) def grad_fn(dresult): return [tf.clip_by_norm(dresult, norm), None] return y, grad_fn ``` Custom gradients are commonly used to provide a numerically stable gradient for a sequence of operations: ``` def log1pexp(x): return tf.math.log(1 + tf.exp(x)) def grad_log1pexp(x): with tf.GradientTape() as tape: tape.watch(x) value = log1pexp(x) return tape.gradient(value, x) # The gradient computation works fine at x = 0. grad_log1pexp(tf.constant(0.)).numpy() # However, x = 100 fails because of numerical instability. grad_log1pexp(tf.constant(100.)).numpy() ``` Here, the `log1pexp` function can be analytically simplified with a custom gradient. The implementation below reuses the value for `tf.exp(x)` that is computed during the forward pass—making it more efficient by eliminating redundant calculations: ``` @tf.custom_gradient def log1pexp(x): e = tf.exp(x) def grad(dy): return dy * (1 - 1 / (1 + e)) return tf.math.log(1 + e), grad def grad_log1pexp(x): with tf.GradientTape() as tape: tape.watch(x) value = log1pexp(x) return tape.gradient(value, x) # As before, the gradient computation works fine at x = 0. grad_log1pexp(tf.constant(0.)).numpy() # And the gradient computation also works at x = 100. grad_log1pexp(tf.constant(100.)).numpy() ``` ## Performance Computation is automatically offloaded to GPUs during eager execution. If you want control over where a computation runs you can enclose it in a `tf.device('/gpu:0')` block (or the CPU equivalent): ``` import time def measure(x, steps): # TensorFlow initializes a GPU the first time it's used, exclude from timing. tf.matmul(x, x) start = time.time() for i in range(steps): x = tf.matmul(x, x) # tf.matmul can return before completing the matrix multiplication # (e.g., can return after enqueing the operation on a CUDA stream). # The x.numpy() call below will ensure that all enqueued operations # have completed (and will also copy the result to host memory, # so we're including a little more than just the matmul operation # time). _ = x.numpy() end = time.time() return end - start shape = (1000, 1000) steps = 200 print("Time to multiply a {} matrix by itself {} times:".format(shape, steps)) # Run on CPU: with tf.device("/cpu:0"): print("CPU: {} secs".format(measure(tf.random.normal(shape), steps))) # Run on GPU, if available: if tf.config.experimental.list_physical_devices("GPU"): with tf.device("/gpu:0"): print("GPU: {} secs".format(measure(tf.random.normal(shape), steps))) else: print("GPU: not found") ``` A `tf.Tensor` object can be copied to a different device to execute its operations: ``` if tf.config.experimental.list_physical_devices("GPU"): x = tf.random.normal([10, 10]) x_gpu0 = x.gpu() x_cpu = x.cpu() _ = tf.matmul(x_cpu, x_cpu) # Runs on CPU _ = tf.matmul(x_gpu0, x_gpu0) # Runs on GPU:0 ``` ### Benchmarks For compute-heavy models, such as [ResNet50](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/eager/python/examples/resnet50) training on a GPU, eager execution performance is comparable to `tf.function` execution. But this gap grows larger for models with less computation and there is work to be done for optimizing hot code paths for models with lots of small operations. ## Work with functions While eager execution makes development and debugging more interactive, TensorFlow 1.x style graph execution has advantages for distributed training, performance optimizations, and production deployment. To bridge this gap, TensorFlow 2.0 introduces `function`s via the `tf.function` API. For more information, see the [tf.function](./function.ipynb) guide.
github_jupyter
``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Train Your Own Model and Serve It With TensorFlow Serving In this notebook, you will train a neural network to classify images of handwritten digits from the [MNIST](http://yann.lecun.com/exdb/mnist/) dataset. You will then save the trained model, and serve it using [TensorFlow Serving](https://www.tensorflow.org/tfx/guide/serving). **Warning: This notebook is designed to be run in a Google Colab only**. It installs packages on the system and requires root access. If you want to run it in a local Jupyter notebook, please proceed with caution. <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/lmoroney/dlaicourse/blob/master/TensorFlow%20Deployment/Course%204%20-%20TensorFlow%20Serving/Week%201/Exercises/TFServing_Week1_Exercise_Answer.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/lmoroney/dlaicourse/blob/master/TensorFlow%20Deployment/Course%204%20-%20TensorFlow%20Serving/Week%201/Exercises/TFServing_Week1_Exercise_Answer.ipynb"> <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a> </td> </table> ## Setup ``` try: %tensorflow_version 2.x except: pass import os import json import tempfile import requests import numpy as np import matplotlib.pyplot as plt import tensorflow as tf print("\u2022 Using TensorFlow Version:", tf.__version__) ``` ## Import the MNIST Dataset The [MNIST](http://yann.lecun.com/exdb/mnist/) dataset contains 70,000 grayscale images of the digits 0 through 9. The images show individual digits at a low resolution (28 by 28 pixels). Even though these are really images, we will load them as NumPy arrays and not as binary image objects. ``` mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # EXERCISE: Scale the values of the arrays below to be between 0.0 and 1.0. train_images = train_images / 255.0 test_images = test_images / 255.0 ``` In the cell below use the `.reshape` method to resize the arrays to the following sizes: ```python train_images.shape: (60000, 28, 28, 1) test_images.shape: (10000, 28, 28, 1) ``` ``` # EXERCISE: Reshape the arrays below. train_images = train_images.reshape(train_images.shape[0], 28, 28, 1) test_images = test_images.reshape(test_images.shape[0], 28, 28, 1) print('\ntrain_images.shape: {}, of {}'.format(train_images.shape, train_images.dtype)) print('test_images.shape: {}, of {}'.format(test_images.shape, test_images.dtype)) ``` ## Look at a Sample Image ``` idx = 42 plt.imshow(test_images[idx].reshape(28,28), cmap=plt.cm.binary) plt.title('True Label: {}'.format(test_labels[idx]), fontdict={'size': 16}) plt.show() ``` ## Build a Model In the cell below build a `tf.keras.Sequential` model that can be used to classify the images of the MNIST dataset. Feel free to use the simplest possible CNN. Make sure your model has the correct `input_shape` and the correct number of output units. ``` # EXERCISE: Create a model. model = tf.keras.Sequential([ tf.keras.layers.Conv2D(input_shape=(28,28,1), filters=8, kernel_size=3, strides=2, activation='relu', name='Conv1'), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10, activation=tf.nn.softmax, name='Softmax') ]) model.summary() ``` ## Train the Model In the cell below configure your model for training using the `adam` optimizer, `sparse_categorical_crossentropy` as the loss, and `accuracy` for your metrics. Then train the model for the given number of epochs, using the `train_images` array. ``` # EXERCISE: Configure the model for training. model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) epochs = 5 # EXERCISE: Train the model. history = model.fit(train_images, train_labels, epochs=epochs) ``` ## Evaluate the Model ``` # EXERCISE: Evaluate the model on the test images. results_eval = model.evaluate(test_images, test_labels, verbose=0) for metric, value in zip(model.metrics_names, results_eval): print(metric + ': {:.3}'.format(value)) ``` ## Save the Model ``` MODEL_DIR = tempfile.gettempdir() version = 1 export_path = os.path.join(MODEL_DIR, str(version)) if os.path.isdir(export_path): print('\nAlready saved a model, cleaning up\n') !rm -r {export_path} model.save(export_path, save_format="tf") print('\nexport_path = {}'.format(export_path)) !ls -l {export_path} ``` ## Examine Your Saved Model ``` !saved_model_cli show --dir {export_path} --all ``` ## Add TensorFlow Serving Distribution URI as a Package Source ``` # This is the same as you would do from your command line, but without the [arch=amd64], and no sudo # You would instead do: # echo "deb [arch=amd64] http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list && \ # curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | sudo apt-key add - !echo "deb http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal" | tee /etc/apt/sources.list.d/tensorflow-serving.list && \ curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add - !apt update ``` ## Install TensorFlow Serving ``` !apt-get install tensorflow-model-server ``` ## Run the TensorFlow Model Server You will now launch the TensorFlow model server with a bash script. In the cell below use the following parameters when running the TensorFlow model server: * `rest_api_port`: Use port `8501` for your requests. * `model_name`: Use `digits_model` as your model name. * `model_base_path`: Use the environment variable `MODEL_DIR` defined below as the base path to the saved model. ``` os.environ["MODEL_DIR"] = MODEL_DIR # EXERCISE: Fill in the missing code below. %%bash --bg nohup tensorflow_model_server \ --rest_api_port=8501 \ --model_name=digits_model \ --model_base_path="${MODEL_DIR}" >server.log 2>&1 !tail server.log ``` ## Create JSON Object with Test Images In the cell below construct a JSON object and use the first three images of the testing set (`test_images`) as your data. ``` # EXERCISE: Create JSON Object data = json.dumps({"signature_name": "serving_default", "instances": test_images[0:3].tolist()}) ``` ## Make Inference Request In the cell below, send a predict request as a POST to the server's REST endpoint, and pass it your test data. You should ask the server to give you the latest version of your model. ``` # EXERCISE: Fill in the code below headers = {"content-type": "application/json"} json_response = requests.post('http://localhost:8501/v1/models/digits_model:predict', data=data, headers=headers) predictions = json.loads(json_response.text)['predictions'] ``` ## Plot Predictions ``` plt.figure(figsize=(10,15)) for i in range(3): plt.subplot(1,3,i+1) plt.imshow(test_images[i].reshape(28,28), cmap = plt.cm.binary) plt.axis('off') color = 'green' if np.argmax(predictions[i]) == test_labels[i] else 'red' plt.title('Prediction: {}\nTrue Label: {}'.format(np.argmax(predictions[i]), test_labels[i]), color=color) plt.show() ```
github_jupyter
# MARATONA BEHIND THE CODE 2020 ## DESAFIO 2: PARTE 1 ### Introdução Em projetos de ciência de dados visando a construção de modelos de *machine learning*, ou aprendizado estatístico, é muito incomum que os dados iniciais estejam já no formato ideal para a construção de modelos. São necessários vários passos intermediários de pré-processamento de dados, como por exemplo a codificação de variáveis categóricas, normalização de variáveis numéricas, tratamento de dados faltantes, etc. A biblioteca **scikit-learn** -- uma das mais populares bibliotecas de código-aberto para *machine learning* no mundo -- possui diversas funções já integradas para a realização das transformações de dados mais utilizadas. Entretanto, em um fluxo comum de um modelo de aprendizado de máquina, é necessária a aplicação dessas transformações pelo menos duas vezes: a primeira vez para "treinar" o modelo, e depois novamente quando novos dados forem enviados como entrada para serem classificados por este modelo. Para facilitar o trabalho com esse tipo de fluxo, o scikit-learn possui também uma ferramenta chamada **Pipeline**, que nada mais é do que uma lista ordenada de transformações que devem ser aplicadas nos dados. Para auxiliar no desenvolvimento e no gerenciamento de todo o ciclo-de-vida dessas aplicações, alem do uso de Pipelines, as equipes de cientistas de dados podem utilizar em conjunto o **Watson Machine Learning**, que possui dezenas de ferramentas para treinar, gerenciar, hospedar e avaliar modelos baseados em aprendizado de máquina. Além disso, o Watson Machine Learning é capaz de encapsular pipelines e modelos em uma API pronta para uso e integração com outras aplicações. Durante o desafio 2, você participante irá aprender a construir uma **Pipeline** para um modelo de classificação e hospedá-lo como uma API com o auxílio do Watson Machine Learning. Uma vez hospedado, você poderá integrar o modelo criado com outras aplicações, como assistentes virtuais e muito mais. Neste notebook, será apresentado um exemplo funcional de criação de um modelo e de uma pipeline no scikit-learn (que você poderá utilizar como template para a sua solução!). ## ** ATENÇÃO ** Este notebook serve apenas um propósito educativo, você pode alterar o código como quiser e nada aqui será avaliado/pontuado. A recomendação é que você experimente e teste diferentes algoritmos aqui antes de passar para a *parte-2*, onde será realizado o deploy do seu modelo no **Watson Machine Learning** :) ### Trabalhando com Pipelines do scikit-learn ``` # Primeiro, realizamos a instalação do scikit-learn versão 0.20.3 e do xgboost versão 0.71 no Kernel deste notebook # ** CUIDADO AO TROCAR A VERSÃO DAS BIBLIOTECAS -- VERSÕES DIFERENTES PODEM SER INCOMPATÍVEIS COM O WATSON STUDIO ** # OBS: A instalação do xgboost leva um tempo considerável !pip install scikit-learn==0.20.3 --upgrade !pip install xgboost==0.71 --upgrade # Em seguida iremos importar diversas bibliotecas que serão utilizadas: # Pacote para trabalhar com JSON import json # Pacote para realizar requisições HTTP import requests # Pacote para exploração e análise de dados import pandas as pd # Pacote com métodos numéricos e representações matriciais import numpy as np # Pacote para construção de modelo baseado na técnica Gradient Boosting import xgboost as xgb # Pacotes do scikit-learn para pré-processamento de dados # "SimpleImputer" é uma transformação para preencher valores faltantes em conjuntos de dados from sklearn.impute import SimpleImputer # Pacotes do scikit-learn para treinamento de modelos e construção de pipelines # Método para separação de conjunto de dados em amostras de treino e teste from sklearn.model_selection import train_test_split # Método para criação de modelos baseados em árvores de decisão from sklearn.tree import DecisionTreeClassifier # Classe para a criação de uma pipeline de machine-learning from sklearn.pipeline import Pipeline # Pacotes do scikit-learn para avaliação de modelos # Métodos para validação cruzada do modelo criado from sklearn.model_selection import KFold, cross_validate ``` ### Importando um .csv de seu projeto no IBM Cloud Pak for Data para o Kernel deste notebook Primeiro iremos importar o dataset fornecido para o desafio, que já está incluso neste projeto! Você pode realizar a importação dos dados de um arquivo .csv diretamente para o Kernel do notebook como um DataFrame da biblioteca Pandas, muito utilizada para a manipulação de dados em Python. Para realizar a importação, basta selecionar a próxima célula e seguir as instruções na imagem abaixo: ![alt text](https://i.imgur.com/K1DwL9I.png "importing-csv-as-df") Após a seleção da opção **"Insert to code"**, a célula abaixo será preenchida com o código necessário para importação e leitura dos dados no arquivo .csv como um DataFrame Pandas. ``` << INSIRA O DATASET COMO UM PANDAS DATAFRAME NESTA CÉLULA! >>> ``` Temos 15 colunas presentes no dataset fornecido, sendo dezessete delas variáveis características (dados de entrada) e um delas uma variável-alvo (que queremos que o nosso modelo seja capaz de prever). As variáveis características são: MATRICULA - número de matrícula do estudante NOME - nome completo do estudante REPROVACOES_DE - número de reprovações na disciplina de ``Direito Empresarial`` REPROVACOES_EM - número de reprovações na disciplina de ``Empreendedorismo`` REPROVACOES_MF - número de reprovações na disciplina de ``Matemática Financeira`` REPROVACOES_GO - número de reprovações na disciplina de ``Gestão Operacional`` NOTA_DE - média simples das notas do aluno na disciplina de ``Direito Empresarial`` (0-10) NOTA_EM - média simples das notas do aluno na disciplina de ``Empreendedorismo`` (0-10) NOTA_MF - média simples das notas do aluno na disciplina de ``Matemática Financeira`` (0-10) NOTA_GO - média simples das notas do aluno na disciplina de ``Gestão Operacional`` (0-10) INGLES - variável binária que indica se o estudante tem conhecimento em língua inglesa (0 -> sim ou 1 -> não). H_AULA_PRES - horas de estudo presencial realizadas pelo estudante TAREFAS_ONLINE - número de tarefas online entregues pelo estudante FALTAS - número de faltas acumuladas do estudante (todas disciplinas) A variável-alvo é: PERFIL - uma *string* que indica uma de cinco possibilidades: "EXCELENTE" - Estudante não necessita de mentoria "MUITO BOM" - Estudante não necessita de mentoria "HUMANAS" - Estudante necessita de mentoria exclusivamente em matérias com conteúdo de ciências humanas "EXATAS" - Estudante necessita de mentoria apenas em disciplinas com conteúdo de ciências exatas "DIFICULDADE" - Estudante necessita de mentoria em duas ou mais disciplinas Com um modelo capaz de classificar um estudante em uma dessas categorias, podemos automatizar parte da mentoria estudantil através de assistentes virtuais, que serão capazes de recomendar práticas de estudo e conteúdo personalizado com base nas necessidades de cada aluno. ### Explorando os dados fornecidos Podemos continuar a exploração dos dados fornecidos com a função ``info()``: ``` df_data_1.info() ``` É notado que existem variáveis do tipo ``float64`` (números "decimais"), variáveis do tipo ``int64`` (números inteiros) e do tipo ``object`` (nesse caso são *strings*, ou texto). Como a maioria dos algoritmos de aprendizado estatístico supervisionado só aceita valores numéricos como entrada, é necessário então o pré-processamento das variáveis do tipo "object" antes de usar esse dataset como entrada para o treinamento de um modelo. Também é notado que existem valores faltantes em várias colunas. Esses valores faltantes também devem ser tratados antes de serem construídos modelos com esse conjunto de dados base. A função ``describe()`` gera várias informações sobre as variáveis numéricas que também podem ser úteis: ``` df_data_1.describe() ``` ### Visualizações Para visualizar o dataset fornecido, podemos utilizar as bibliotecas ``matplotlib`` e ``seaborn``: ``` import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(28, 4)) sns.countplot(ax=axes[0], x='REPROVACOES_DE', data=df_data_1) sns.countplot(ax=axes[1], x='REPROVACOES_EM', data=df_data_1) sns.countplot(ax=axes[2], x='REPROVACOES_MF', data=df_data_1) sns.countplot(ax=axes[3], x='REPROVACOES_GO', data=df_data_1) fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(28, 4)) sns.distplot(df_data_1['NOTA_DE'], ax=axes[0]) sns.distplot(df_data_1['NOTA_EM'], ax=axes[1]) sns.distplot(df_data_1['NOTA_MF'], ax=axes[2]) sns.distplot(df_data_1['NOTA_GO'].dropna(), ax=axes[3]) fig, axes = plt.subplots(nrows=1, ncols=4, figsize=(28, 4)) sns.countplot(ax=axes[0], x='INGLES', data=df_data_1) sns.countplot(ax=axes[1], x='FALTAS', data=df_data_1) sns.countplot(ax=axes[2], x='H_AULA_PRES', data=df_data_1) sns.countplot(ax=axes[3], x='TAREFAS_ONLINE', data=df_data_1) fig = plt.plot() sns.countplot(x='PERFIL', data=df_data_1) ``` ## ** ATENÇÃO ** Você pode notar pela figura acima que este dataset é desbalanceado, isto é, a quantidade de amostras para cada classe que desejamos classificar é bem discrepante. O participante é livre para adicionar ou remover **LINHAS** no dataset fornecido, inclusive utilizar bibliotecas para balanceamento com ``imblearn``. Entretanto tome **muito cuidado**!!! Você não pode alterar os tipos dos dados e nem remover ou desordenar o dataset fornecido. Todas as operações desse tipo deverão ser feitas por meio de Transforms do scikit-learn :) <hr> ### Realizando o pré-processamento dos dados Para o pré-processamento dos dados serão apresentadas duas transformações básicas neste notebook, demonstrando a construção de uma Pipeline com um modelo funcional. Esta Pipeline funcional fornecida deverá ser melhorada pelo participante para que o modelo final alcance a maior acurácia possível, garantindo uma pontuação maior no desafio. Essa melhoria pode ser feita apenas no pré-processamento dos dados, na escolha de um algoritmo para treinamento de modelo diferente, ou até mesmo na alteração do *framework* usado (entretanto só será fornecido um exemplo pronto de integração do Watson Machine Learning com o *scikit-learn*). A primeira transformação (passo na nossa Pipeline) será a exclusão da coluna "NOME" do nosso dataset, que além de não ser uma variável numérica, também não é uma variável relacionada ao desempenho dos estudantes nas disciplinas. Existem funções prontas no scikit-learn para a realização dessa transformação, entretanto nosso exemplo irá demonstrar como criar uma transformação personalizada do zero no scikit-learn. Se desejado, o participante poderá utilizar esse exemplo para criar outras transformações e adicioná-las à Pipeline final :) #### Transformação 1: excluindo colunas do dataset Para a criação de uma transformação de dados personalizada no scikit-learn, é necessária basicamente a criação de uma classe com os métodos ``transform`` e ``fit``. No método transform será executada a lógica da nossa transformação. Na próxima célula é apresentado o código completo de uma transformação ``DropColumns`` para a remoção de colunas de um DataFrame pandas. ``` from sklearn.base import BaseEstimator, TransformerMixin # All sklearn Transforms must have the `transform` and `fit` methods class DropColumns(BaseEstimator, TransformerMixin): def __init__(self, columns): self.columns = columns def fit(self, X, y=None): return self def transform(self, X): # Primeiro realizamos a cópia do dataframe 'X' de entrada data = X.copy() # Retornamos um novo dataframe sem as colunas indesejadas return data.drop(labels=self.columns, axis='columns') ``` Para aplicar essa transformação em um DataFrame pandas, basta instanciar um objeto *DropColumns* e chamar o método transform(). ``` # Instanciando uma transformação DropColumns rm_columns = DropColumns( columns=["NOME"] # Essa transformação recebe como parâmetro uma lista com os nomes das colunas indesejadas ) print(rm_columns) # Visualizando as colunas do dataset original print("Colunas do dataset original: \n") print(df_data_1.columns) # Aplicando a transformação ``DropColumns`` ao conjunto de dados base rm_columns.fit(X=df_data_1) # Reconstruindo um DataFrame Pandas com o resultado da transformação df_data_2 = pd.DataFrame.from_records( data=rm_columns.transform( X=df_data_1 ), ) # Visualizando as colunas do dataset transformado print("Colunas do dataset após a transformação ``DropColumns``: \n") print(df_data_2.columns) ``` Nota-se que a coluna "NOME" foi removida e nosso dataset agora poossui apenas 17 colunas. #### Transformação 2: tratando dados faltantes Para tratar os dados faltantes em nosso conjunto de dados, iremos agora utilizar uma transformação pronta da biblioteca scikit-learn, chamada **SimpleImputer**. Essa transformação permite diversas estratégias para o tratamento de dados faltantes. A documentação oficial pode ser encontrada em: https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html Neste exemplo iremos simplesmente transformar todos os valores faltantes em zero. ``` # Criação de um objeto ``SimpleImputer`` si = SimpleImputer( missing_values=np.nan, # os valores faltantes são do tipo ``np.nan`` (padrão Pandas) strategy='constant', # a estratégia escolhida é a alteração do valor faltante por uma constante fill_value=0, # a constante que será usada para preenchimento dos valores faltantes é um int64=0. verbose=0, copy=True ) # Visualizando os dados faltantes do dataset após a primeira transformação (df_data_2) print("Valores nulos antes da transformação SimpleImputer: \n\n{}\n".format(df_data_2.isnull().sum(axis = 0))) # Aplicamos o SimpleImputer ``si`` ao conjunto de dados df_data_2 (resultado da primeira transformação) si.fit(X=df_data_2) # Reconstrução de um novo DataFrame Pandas com o conjunto imputado (df_data_3) df_data_3 = pd.DataFrame.from_records( data=si.transform( X=df_data_2 ), # o resultado SimpleImputer.transform(<<pandas dataframe>>) é lista de listas columns=df_data_2.columns # as colunas originais devem ser conservadas nessa transformação ) # Visualizando os dados faltantes do dataset após a segunda transformação (SimpleImputer) (df_data_3) print("Valores nulos no dataset após a transformação SimpleImputer: \n\n{}\n".format(df_data_3.isnull().sum(axis = 0))) ``` Nota-se que não temos mais nenhum valor faltante no nosso conjunto de dados :) Vale salientar que nem sempre a alteração dos valores faltantes por 0 é a melhor estratégia. O participante é incentivado a estudar e implementar estratégias diferentes de tratamento dos valores faltantes para aprimorar seu modelo e melhorar sua pontuação final. ### Treinando um modelo de classificação Finalizado o pré-processamento, já temos o conjunto de dados no formato necessário para o treinamento do nosso modelo: ``` df_data_3.head() ``` No exemplo fornecido, iremos utilizar todas as colunas, exceto a coluna **LABELS** como *features* (variáveis de entrada). A variável **LABELS** será a variável-alvo do modelo, conforme descrito no enunciado do desafio. #### Definindo as features do modelo ``` # Definição das colunas que serão features (nota-se que a coluna NOME não está presente) features = [ "MATRICULA", 'REPROVACOES_DE', 'REPROVACOES_EM', "REPROVACOES_MF", "REPROVACOES_GO", "NOTA_DE", "NOTA_EM", "NOTA_MF", "NOTA_GO", "INGLES", "H_AULA_PRES", "TAREFAS_ONLINE", "FALTAS", ] # Definição da variável-alvo target = ["PERFIL"] # Preparação dos argumentos para os métodos da biblioteca ``scikit-learn`` X = df_data_3[features] y = df_data_3[target] ``` O conjunto de entrada (X): ``` X.head() ``` As variáveis-alvo correspondentes (y): ``` y.head() ``` #### Separando o dataset em um conjunto de treino e um conjunto de teste Iremos separar o dataset fornecido em dois grupos: um para treinar nosso modelo, e outro para testarmos o resultado através de um teste cego. A separação do dataset pode ser feita facilmente com o método *train_test_split()* do scikit-learn: ``` # Separação dos dados em um conjunto de treino e um conjunto de teste X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=337) ``` <hr> #### Criando um modelo baseado em árvores de decisão No exemplo fornecido iremos criar um classificador baseado em **árvores de decisão**. Material teórico sobre árvores de decisão na documentação oficial do scikit-learn: https://scikit-learn.org/stable/modules/tree.html O primeiro passo é basicamente instanciar um objeto *DecisionTreeClassifier()* da biblioteca scikit-learn. ``` # Criação de uma árvore de decisão com a biblioteca ``scikit-learn``: decision_tree = DecisionTreeClassifier() ``` #### Testando o classificador baseado em árvore de decisão ``` # Treino do modelo (é chamado o método *fit()* com os conjuntos de treino) decision_tree.fit( X_train, y_train ) ``` #### Execução de predições e avaliação da árvore de decisão ``` # Realização de teste cego no modelo criado y_pred = decision_tree.predict(X_test) X_test.head() print(y_pred) from sklearn.metrics import accuracy_score # Acurácia alcançada pela árvore de decisão print("Acurácia: {}%".format(100*round(accuracy_score(y_test, y_pred), 2))) ``` <hr> Neste notebook foi demonstrado como trabalhar com transformações e modelos com a biblioteca scikit-learn. É recomendado que o participante realize seus experimentos editando o código fornecido aqui até que um modelo com acurácia elevada seja alcançado. Quando você estiver satisfeito com seu modelo, pode passar para a segunda etapa do desafio -- encapsular seu modelo como uma API REST pronta para uso com o Watson Machine Learning! O notebook para a segunda etapa já se encontra neste projeto, basta acessar a aba **ASSETS** e inicializá-lo! Não se esqueca de antes desligar o Kernel deste notebook para reduzir o consumo de sua camada grátis do IBM Cloud Pak for Data.
github_jupyter
``` import os import time import random import pandas as pd import numpy as np import gc import re import torch from torchtext import data import spacy from tqdm import tqdm_notebook, tnrange from tqdm.auto import tqdm from unidecode import unidecode import random tqdm.pandas(desc='Progress') from collections import Counter from textblob import TextBlob from nltk import word_tokenize import torch as t import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch.autograd import Variable from torchtext.data import Example from torch.optim.optimizer import Optimizer import torchtext from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.preprocessing import StandardScaler from sklearn.model_selection import StratifiedKFold from sklearn.metrics import f1_score ``` ### Basic Parameters ``` embed_size = 300 # how big is each word vector max_features = 120000 # how many unique words to use (i.e num rows in embedding vector) maxlen = 70 # max number of words in a question to use batch_size = 512 # how many samples to process at once n_epochs = 5 # how many times to iterate over all samples n_splits = 5 # Number of K-fold Splits SEED = 1029 # seed_everything def seed_everything(seed=1029): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True seed_everything() ## FUNCTIONS TAKEN FROM https://www.kaggle.com/gmhost/gru-capsule def load_glove(word_index): EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')[:300] embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.005838499,0.48782197 embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_fasttext(word_index): EMBEDDING_FILE = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE) if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = all_embs.mean(), all_embs.std() embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix def load_para(word_index): EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt' def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32') embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore') if len(o)>100) all_embs = np.stack(embeddings_index.values()) emb_mean,emb_std = -0.0053247833,0.49346462 embed_size = all_embs.shape[1] # word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size)) for word, i in word_index.items(): if i >= max_features: continue embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector return embedding_matrix df_train = pd.read_csv("../input/train.csv") df_test = pd.read_csv("../input/test.csv") df = pd.concat([df_train ,df_test],sort=True) def build_vocab(texts): sentences = texts.apply(lambda x: x.split()).values vocab = {} for sentence in sentences: for word in sentence: try: vocab[word] += 1 except KeyError: vocab[word] = 1 return vocab vocab = build_vocab(df['question_text']) sin = len(df_train[df_train["target"]==0]) insin = len(df_train[df_train["target"]==1]) persin = (sin/(sin+insin))*100 perinsin = (insin/(sin+insin))*100 print("# Sincere questions: {:,}({:.2f}%) and # Insincere questions: {:,}({:.2f}%)".format(sin,persin,insin,perinsin)) print("# Test samples: {:,}({:.3f}% of train samples)".format(len(df_test),len(df_test)/len(df_train))) def build_vocab(texts): sentences = texts.apply(lambda x: x.split()).values vocab = {} for sentence in sentences: for word in sentence: try: vocab[word] += 1 except KeyError: vocab[word] = 1 return vocab def known_contractions(embed): known = [] for contract in contraction_mapping: if contract in embed: known.append(contract) return known def clean_contractions(text, mapping): specials = ["’", "‘", "´", "`"] for s in specials: text = text.replace(s, "'") text = ' '.join([mapping[t] if t in mapping else t for t in text.split(" ")]) return text def correct_spelling(x, dic): for word in dic.keys(): x = x.replace(word, dic[word]) return x def unknown_punct(embed, punct): unknown = '' for p in punct: if p not in embed: unknown += p unknown += ' ' return unknown def clean_numbers(x): x = re.sub('[0-9]{5,}', '00000', x) x = re.sub('[0-9]{4}', '0000', x) x = re.sub('[0-9]{3}', '000', x) x = re.sub('[0-9]{2}', '00', x) return x def clean_special_chars(text, punct, mapping): for p in mapping: text = text.replace(p, mapping[p]) for p in punct: text = text.replace(p, f' {p} ') specials = {'\u200b': ' ', '…': ' ... ', '\ufeff': '', 'करना': '', 'है': ''} # Other special characters that I have to deal with in last for s in specials: text = text.replace(s, specials[s]) return text def add_lower(embedding, vocab): count = 0 for word in vocab: if word in embedding and word.lower() not in embedding: embedding[word.lower()] = embedding[word] count += 1 print(f"Added {count} words to embedding") puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', '+', '\\', '•', '~', '@', '£', '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…', '“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', ':', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞', '∙', ')', '↓', '、', '│', '(', '»', ',', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ] mispell_dict = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'} def clean_text(x): x = str(x) for punct in puncts: x = x.replace(punct, f' {punct} ') return x def _get_mispell(mispell_dict): mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys())) return mispell_dict, mispell_re mispellings, mispellings_re = _get_mispell(mispell_dict) def replace_typical_misspell(text): def replace(match): return mispellings[match.group(0)] return mispellings_re.sub(replace, text) ``` Extra feature part taken from https://github.com/wongchunghang/toxic-comment-challenge-lstm/blob/master/toxic_comment_9872_model.ipynb ``` from sklearn.preprocessing import StandardScaler def add_features(df): df['question_text'] = df['question_text'].progress_apply(lambda x:str(x)) df['total_length'] = df['question_text'].progress_apply(len) df['capitals'] = df['question_text'].progress_apply(lambda comment: sum(1 for c in comment if c.isupper())) df['caps_vs_length'] = df.progress_apply(lambda row: float(row['capitals'])/float(row['total_length']), axis=1) df['num_words'] = df.question_text.str.count('\S+') df['num_unique_words'] = df['question_text'].progress_apply(lambda comment: len(set(w for w in comment.split()))) df['words_vs_unique'] = df['num_unique_words'] / df['num_words'] return df def load_and_prec(): train_df = pd.read_csv("../input/train.csv") test_df = pd.read_csv("../input/test.csv") print("Train shape : ",train_df.shape) print("Test shape : ",test_df.shape) # lower train_df["question_text"] = train_df["question_text"].apply(lambda x: x.lower()) test_df["question_text"] = test_df["question_text"].apply(lambda x: x.lower()) # Clean the text train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_text(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_text(x)) # Clean numbers train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: clean_numbers(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_numbers(x)) # Clean speelings train_df["question_text"] = train_df["question_text"].progress_apply(lambda x: replace_typical_misspell(x)) test_df["question_text"] = test_df["question_text"].apply(lambda x: replace_typical_misspell(x)) ## fill up the missing values train_X = train_df["question_text"].fillna("_##_").values test_X = test_df["question_text"].fillna("_##_").values ###################### Add Features ############################### # https://github.com/wongchunghang/toxic-comment-challenge-lstm/blob/master/toxic_comment_9872_model.ipynb train = add_features(train_df) test = add_features(test_df) features = train[['caps_vs_length', 'words_vs_unique']].fillna(0) test_features = test[['caps_vs_length', 'words_vs_unique']].fillna(0) ss = StandardScaler() ss.fit(np.vstack((features, test_features))) features = ss.transform(features) test_features = ss.transform(test_features) ########################################################################### ## Tokenize the sentences tokenizer = Tokenizer(num_words=max_features) tokenizer.fit_on_texts(list(train_X)) train_X = tokenizer.texts_to_sequences(train_X) test_X = tokenizer.texts_to_sequences(test_X) ## Pad the sentences train_X = pad_sequences(train_X, maxlen=maxlen) test_X = pad_sequences(test_X, maxlen=maxlen) ## Get the target values train_y = train_df['target'].values # # Splitting to training and a final test set # train_X, x_test_f, train_y, y_test_f = train_test_split(list(zip(train_X,features)), train_y, test_size=0.2, random_state=SEED) # train_X, features = zip(*train_X) # x_test_f, features_t = zip(*x_test_f) #shuffling the data np.random.seed(SEED) trn_idx = np.random.permutation(len(train_X)) train_X = train_X[trn_idx] train_y = train_y[trn_idx] features = features[trn_idx] return train_X, test_X, train_y, features, test_features, tokenizer.word_index # return train_X, test_X, train_y, x_test_f,y_test_f,features, test_features, features_t, tokenizer.word_index # return train_X, test_X, train_y, tokenizer.word_index # fill up the missing values # x_train, x_test, y_train, word_index = load_and_prec() x_train, x_test, y_train, features, test_features, word_index = load_and_prec() # x_train, x_test, y_train, x_test_f,y_test_f,features, test_features,features_t, word_index = load_and_prec() np.save("x_train",x_train) np.save("x_test",x_test) np.save("y_train",y_train) np.save("features",features) np.save("test_features",test_features) np.save("word_index.npy",word_index) x_train = np.load("x_train.npy") x_test = np.load("x_test.npy") y_train = np.load("y_train.npy") features = np.load("features.npy") test_features = np.load("test_features.npy") word_index = np.load("word_index.npy").item() features.shape # missing entries in the embedding are set using np.random.normal so we have to seed here too seed_everything() glove_embeddings = load_glove(word_index) paragram_embeddings = load_para(word_index) embedding_matrix = np.mean([glove_embeddings, paragram_embeddings], axis=0) # vocab = build_vocab(df['question_text']) # add_lower(embedding_matrix, vocab) del glove_embeddings, paragram_embeddings gc.collect() np.shape(embedding_matrix) splits = list(StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED).split(x_train, y_train)) splits[:3] ``` ### Cyclic CLR Code taken from https://www.kaggle.com/dannykliu/lstm-with-attention-clr-in-pytorch ``` # code inspired from: https://github.com/anandsaha/pytorch.cyclic.learning.rate/blob/master/cls.py class CyclicLR(object): def __init__(self, optimizer, base_lr=1e-3, max_lr=6e-3, step_size=2000, mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle', last_batch_iteration=-1): if not isinstance(optimizer, Optimizer): raise TypeError('{} is not an Optimizer'.format( type(optimizer).__name__)) self.optimizer = optimizer if isinstance(base_lr, list) or isinstance(base_lr, tuple): if len(base_lr) != len(optimizer.param_groups): raise ValueError("expected {} base_lr, got {}".format( len(optimizer.param_groups), len(base_lr))) self.base_lrs = list(base_lr) else: self.base_lrs = [base_lr] * len(optimizer.param_groups) if isinstance(max_lr, list) or isinstance(max_lr, tuple): if len(max_lr) != len(optimizer.param_groups): raise ValueError("expected {} max_lr, got {}".format( len(optimizer.param_groups), len(max_lr))) self.max_lrs = list(max_lr) else: self.max_lrs = [max_lr] * len(optimizer.param_groups) self.step_size = step_size if mode not in ['triangular', 'triangular2', 'exp_range'] \ and scale_fn is None: raise ValueError('mode is invalid and scale_fn is None') self.mode = mode self.gamma = gamma if scale_fn is None: if self.mode == 'triangular': self.scale_fn = self._triangular_scale_fn self.scale_mode = 'cycle' elif self.mode == 'triangular2': self.scale_fn = self._triangular2_scale_fn self.scale_mode = 'cycle' elif self.mode == 'exp_range': self.scale_fn = self._exp_range_scale_fn self.scale_mode = 'iterations' else: self.scale_fn = scale_fn self.scale_mode = scale_mode self.batch_step(last_batch_iteration + 1) self.last_batch_iteration = last_batch_iteration def batch_step(self, batch_iteration=None): if batch_iteration is None: batch_iteration = self.last_batch_iteration + 1 self.last_batch_iteration = batch_iteration for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()): param_group['lr'] = lr def _triangular_scale_fn(self, x): return 1. def _triangular2_scale_fn(self, x): return 1 / (2. ** (x - 1)) def _exp_range_scale_fn(self, x): return self.gamma**(x) def get_lr(self): step_size = float(self.step_size) cycle = np.floor(1 + self.last_batch_iteration / (2 * step_size)) x = np.abs(self.last_batch_iteration / step_size - 2 * cycle + 1) lrs = [] param_lrs = zip(self.optimizer.param_groups, self.base_lrs, self.max_lrs) for param_group, base_lr, max_lr in param_lrs: base_height = (max_lr - base_lr) * np.maximum(0, (1 - x)) if self.scale_mode == 'cycle': lr = base_lr + base_height * self.scale_fn(cycle) else: lr = base_lr + base_height * self.scale_fn(self.last_batch_iteration) lrs.append(lr) return lrs import torch as t import torch.nn as nn import torch.nn.functional as F embedding_dim = 300 embedding_path = '../save/embedding_matrix.npy' # or False, not use pre-trained-matrix use_pretrained_embedding = True hidden_size = 60 gru_len = hidden_size Routings = 4 #5 Num_capsule = 5 Dim_capsule = 5#16 dropout_p = 0.25 rate_drop_dense = 0.28 LR = 0.001 T_epsilon = 1e-7 num_classes = 30 class Embed_Layer(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None, embedding_dim=300): super(Embed_Layer, self).__init__() self.encoder = nn.Embedding(vocab_size + 1, embedding_dim) if use_pretrained_embedding: # self.encoder.weight.data.copy_(t.from_numpy(np.load(embedding_path))) # 方法一,加载np.save的npy文件 self.encoder.weight.data.copy_(t.from_numpy(embedding_matrix)) # 方法二 def forward(self, x, dropout_p=0.25): return nn.Dropout(p=dropout_p)(self.encoder(x)) class GRU_Layer(nn.Module): def __init__(self): super(GRU_Layer, self).__init__() self.gru = nn.GRU(input_size=300, hidden_size=gru_len, bidirectional=True) def init_weights(self): ih = (param.data for name, param in self.named_parameters() if 'weight_ih' in name) hh = (param.data for name, param in self.named_parameters() if 'weight_hh' in name) b = (param.data for name, param in self.named_parameters() if 'bias' in name) for k in ih: nn.init.xavier_uniform_(k) for k in hh: nn.init.orthogonal_(k) for k in b: nn.init.constant_(k, 0) def forward(self, x): return self.gru(x) # core caps_layer with squash func class Caps_Layer(nn.Module): def __init__(self, input_dim_capsule=gru_len * 2, num_capsule=Num_capsule, dim_capsule=Dim_capsule, \ routings=Routings, kernel_size=(9, 1), share_weights=True, activation='default', **kwargs): super(Caps_Layer, self).__init__(**kwargs) self.num_capsule = num_capsule self.dim_capsule = dim_capsule self.routings = routings self.kernel_size = kernel_size self.share_weights = share_weights if activation == 'default': self.activation = self.squash else: self.activation = nn.ReLU(inplace=True) if self.share_weights: self.W = nn.Parameter( nn.init.xavier_normal_(t.empty(1, input_dim_capsule, self.num_capsule * self.dim_capsule))) else: self.W = nn.Parameter( t.randn(BATCH_SIZE, input_dim_capsule, self.num_capsule * self.dim_capsule)) # 64即batch_size def forward(self, x): if self.share_weights: u_hat_vecs = t.matmul(x, self.W) else: print('add later') batch_size = x.size(0) input_num_capsule = x.size(1) u_hat_vecs = u_hat_vecs.view((batch_size, input_num_capsule, self.num_capsule, self.dim_capsule)) u_hat_vecs = u_hat_vecs.permute(0, 2, 1, 3) # 转成(batch_size,num_capsule,input_num_capsule,dim_capsule) b = t.zeros_like(u_hat_vecs[:, :, :, 0]) # (batch_size,num_capsule,input_num_capsule) for i in range(self.routings): b = b.permute(0, 2, 1) c = F.softmax(b, dim=2) c = c.permute(0, 2, 1) b = b.permute(0, 2, 1) outputs = self.activation(t.einsum('bij,bijk->bik', (c, u_hat_vecs))) # batch matrix multiplication # outputs shape (batch_size, num_capsule, dim_capsule) if i < self.routings - 1: b = t.einsum('bik,bijk->bij', (outputs, u_hat_vecs)) # batch matrix multiplication return outputs # (batch_size, num_capsule, dim_capsule) # text version of squash, slight different from original one def squash(self, x, axis=-1): s_squared_norm = (x ** 2).sum(axis, keepdim=True) scale = t.sqrt(s_squared_norm + T_epsilon) return x / scale class Capsule_Main(nn.Module): def __init__(self, embedding_matrix=None, vocab_size=None): super(Capsule_Main, self).__init__() self.embed_layer = Embed_Layer(embedding_matrix, vocab_size) self.gru_layer = GRU_Layer() self.gru_layer.init_weights() self.caps_layer = Caps_Layer() self.dense_layer = Dense_Layer() def forward(self, content): content1 = self.embed_layer(content) content2, _ = self.gru_layer( content1) content3 = self.caps_layer(content2) output = self.dense_layer(content3) return output class Attention(nn.Module): def __init__(self, feature_dim, step_dim, bias=True, **kwargs): super(Attention, self).__init__(**kwargs) self.supports_masking = True self.bias = bias self.feature_dim = feature_dim self.step_dim = step_dim self.features_dim = 0 weight = torch.zeros(feature_dim, 1) nn.init.xavier_uniform_(weight) self.weight = nn.Parameter(weight) if bias: self.b = nn.Parameter(torch.zeros(step_dim)) def forward(self, x, mask=None): feature_dim = self.feature_dim step_dim = self.step_dim eij = torch.mm( x.contiguous().view(-1, feature_dim), self.weight ).view(-1, step_dim) if self.bias: eij = eij + self.b eij = torch.tanh(eij) a = torch.exp(eij) if mask is not None: a = a * mask a = a / torch.sum(a, 1, keepdim=True) + 1e-10 weighted_input = x * torch.unsqueeze(a, -1) return torch.sum(weighted_input, 1) class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self).__init__() fc_layer = 16 fc_layer1 = 16 self.embedding = nn.Embedding(max_features, embed_size) self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32)) self.embedding.weight.requires_grad = False self.embedding_dropout = nn.Dropout2d(0.1) self.lstm = nn.LSTM(embed_size, hidden_size, bidirectional=True, batch_first=True) self.gru = nn.GRU(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm2 = nn.LSTM(hidden_size * 2, hidden_size, bidirectional=True, batch_first=True) self.lstm_attention = Attention(hidden_size * 2, maxlen) self.gru_attention = Attention(hidden_size * 2, maxlen) self.bn = nn.BatchNorm1d(16, momentum=0.5) self.linear = nn.Linear(hidden_size*8+3, fc_layer1) #643:80 - 483:60 - 323:40 self.relu = nn.ReLU() self.dropout = nn.Dropout(0.1) self.fc = nn.Linear(fc_layer**2,fc_layer) self.out = nn.Linear(fc_layer, 1) self.lincaps = nn.Linear(Num_capsule * Dim_capsule, 1) self.caps_layer = Caps_Layer() def forward(self, x): # Capsule(num_capsule=10, dim_capsule=10, routings=4, share_weights=True)(x) h_embedding = self.embedding(x[0]) h_embedding = torch.squeeze( self.embedding_dropout(torch.unsqueeze(h_embedding, 0))) h_lstm, _ = self.lstm(h_embedding) h_gru, _ = self.gru(h_lstm) ##Capsule Layer content3 = self.caps_layer(h_gru) content3 = self.dropout(content3) batch_size = content3.size(0) content3 = content3.view(batch_size, -1) content3 = self.relu(self.lincaps(content3)) ##Attention Layer h_lstm_atten = self.lstm_attention(h_lstm) h_gru_atten = self.gru_attention(h_gru) # global average pooling avg_pool = torch.mean(h_gru, 1) # global max pooling max_pool, _ = torch.max(h_gru, 1) f = torch.tensor(x[1], dtype=torch.float).cuda() #[512,160] conc = torch.cat((h_lstm_atten, h_gru_atten,content3, avg_pool, max_pool,f), 1) conc = self.relu(self.linear(conc)) conc = self.bn(conc) conc = self.dropout(conc) out = self.out(conc) return out ``` ### Training The method for training is borrowed from https://www.kaggle.com/hengzheng/pytorch-starter ``` class MyDataset(Dataset): def __init__(self,dataset): self.dataset = dataset def __getitem__(self, index): data, target = self.dataset[index] return data, target, index def __len__(self): return len(self.dataset) def sigmoid(x): return 1 / (1 + np.exp(-x)) # matrix for the out-of-fold predictions train_preds = np.zeros((len(x_train))) # matrix for the predictions on the test set test_preds = np.zeros((len(df_test))) # always call this before training for deterministic results seed_everything() # x_test_cuda_f = torch.tensor(x_test_f, dtype=torch.long).cuda() # test_f = torch.utils.data.TensorDataset(x_test_cuda_f) # test_loader_f = torch.utils.data.DataLoader(test_f, batch_size=batch_size, shuffle=False) x_test_cuda = torch.tensor(x_test, dtype=torch.long).cuda() test = torch.utils.data.TensorDataset(x_test_cuda) test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) avg_losses_f = [] avg_val_losses_f = [] global_test_saver = [] for split_idx, (train_idx, valid_idx) in enumerate(splits): # split data in train / validation according to the KFold indeces # also, convert them to a torch tensor and store them on the GPU (done with .cuda()) x_train = np.array(x_train) y_train = np.array(y_train) features = np.array(features) x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long).cuda() y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32).cuda() kfold_X_features = features[train_idx.astype(int)] kfold_X_valid_features = features[valid_idx.astype(int)] x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long).cuda() y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32).cuda() # model = BiLSTM(lstm_layer=2,hidden_dim=40,dropout=DROPOUT).cuda() model = NeuralNet() # make sure everything in the model is running on the GPU model.cuda() # define binary cross entropy loss # note that the model returns logit to take advantage of the log-sum-exp trick # for numerical stability in the loss loss_fn = torch.nn.BCEWithLogitsLoss(reduction='sum') step_size = 300 base_lr, max_lr = 0.001, 0.003 optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=max_lr) ################################################################################################ scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr, step_size=step_size, mode='exp_range', gamma=0.99994) ############################################################################################### train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold) valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold) train = MyDataset(train) valid = MyDataset(valid) ##No need to shuffle the data again here. Shuffling happens when splitting for kfolds. train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True) valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False) print('Fold ',str(split_idx+1)) for epoch in range(n_epochs): # set train mode of the model. This enables operations which are only applied during training like dropout start_time = time.time() model.train() avg_loss = 0. for i, (x_batch, y_batch, index) in enumerate(train_loader): # Forward pass: compute predicted y by passing x to the model. ################################################################################################ f = kfold_X_features[index] y_pred = model([x_batch,f]) ################################################################################################ ################################################################################################ if scheduler: scheduler.batch_step() ################################################################################################ # Compute and print loss. loss = loss_fn(y_pred, y_batch) # Before the backward pass, use the optimizer object to zero all of the # gradients for the Tensors it will update (which are the learnable weights # of the model) optimizer.zero_grad() # Backward pass: compute gradient of the loss with respect to model parameters loss.backward() # Calling the step function on an Optimizer makes an update to its parameters optimizer.step() avg_loss += loss.item() / len(train_loader) # set evaluation mode of the model. This disabled operations which are only applied during training like dropout model.eval() # predict all the samples in y_val_fold batch per batch valid_preds_fold = np.zeros((x_val_fold.size(0))) test_preds_fold = np.zeros((len(df_test))) avg_val_loss = 0. for i, (x_batch, y_batch, index) in enumerate(valid_loader): f = kfold_X_valid_features[index] y_pred = model([x_batch,f]).detach() avg_val_loss += loss_fn(y_pred, y_batch).item() / len(valid_loader) valid_preds_fold[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] elapsed_time = time.time() - start_time print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format( epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time)) avg_losses_f.append(avg_loss) avg_val_losses_f.append(avg_val_loss) # predict all samples in the test set batch per batch for i, (x_batch,) in enumerate(test_loader): f = test_features[i * batch_size:(i+1) * batch_size] y_pred = model([x_batch,f]).detach() test_preds_fold[i * batch_size:(i+1) * batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0] train_preds[valid_idx] = valid_preds_fold test_preds += test_preds_fold / len(splits) global_test_saver.append(test_preds_fold) print('All \t loss={:.4f} \t val_loss={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f))) diff = np.zeros([n_splits,n_splits]) for ii in range(n_splits): for jj in range(ii,n_splits): diff[ii,jj] = int(np.sum(np.abs(global_test_saver[ii] - global_test_saver[jj]))) diff_sum = np.sum(diff) print(diff) print(diff_sum / (n_splits)/(n_splits - 1) * 2 /len(global_test_saver[0])) for ii in range(n_splits): for jj in range(ii,n_splits): diff[ii,jj] = int(np.sum(np.power(global_test_saver[ii] - global_test_saver[jj],2))) diff_sum = np.sum(diff) print(diff) print(diff_sum / (n_splits)/(n_splits - 1) * 2 /len(global_test_saver[0])) # x_train, x_test_f, y_train, y_test_f ``` ### Find final Thresshold Borrowed from: https://www.kaggle.com/ziliwang/baseline-pytorch-bilstm ``` def bestThresshold(y_train,train_preds): tmp = [0,0,0] # idx, cur, max delta = 0 for tmp[0] in tqdm(np.arange(0.1, 0.501, 0.01)): tmp[1] = f1_score(y_train, np.array(train_preds)>tmp[0]) if tmp[1] > tmp[2]: delta = tmp[0] tmp[2] = tmp[1] print('best threshold is {:.4f} with F1 score: {:.4f}'.format(delta, tmp[2])) return delta delta = bestThresshold(y_train,train_preds) submission = df_test[['qid']].copy() submission['prediction'] = (test_preds > delta).astype(int) submission.to_csv('submission.csv', index=False) ```
github_jupyter
# Discrete stochastic Erlang SEIR model Author: Lam Ha @lamhm Date: 2018-10-03 ## Calculate Discrete Erlang Probabilities The following function is to calculate the discrete truncated Erlang probability, given $k$ and $\gamma$: \begin{equation*} p_i = \frac{1}{C(n^{E})} \Bigl(\sum_{j=0}^{k-1} \frac{e^{-(i-1)\gamma} \times ((i-1)\gamma)^{j}} {j!} -\sum_{j=0}^{k-1} \frac{e^{-i\gamma} \times (i\gamma)^{j}} {j!}\Bigr),\quad\text{for $i=1,...,n^{E}$}. \end{equation*} where \begin{equation*} n^{E} = argmin_n\Bigl(C(n) = 1 - \sum_{j=0}^{k-1} \frac{e^{-n\gamma} \times (n\gamma)^{j}} {j!} > 0.99 \Bigr) \end{equation*} **N.B. The formula of $p_i$ here is slightly different from what is shown in the original paper because the latter (which is likely to be wrong) would lead to negative probabilities.** ``` #' @param k The shape parameter of the Erlang distribution. #' @param gamma The rate parameter of the Erlang distribution. #' @return A vector containing all p_i values, for i = 1 : n. compute_erlang_discrete_prob <- function(k, gamma) { n_bin <- 0 factorials <- 1 ## 0! = 1 for (i in 1 : k) { factorials[i + 1] <- factorials[i] * i ## factorial[i + 1] = i! } one_sub_cummulative_probs <- NULL cummulative_prob <- 0 while (cummulative_prob <= 0.99) { n_bin <- n_bin + 1 one_sub_cummulative_probs[n_bin] <- 0 for ( j in 0 : (k - 1) ) { one_sub_cummulative_probs[n_bin] <- one_sub_cummulative_probs[n_bin] + ( exp( -n_bin * gamma ) * ( (n_bin * gamma) ^ j ) / factorials[j + 1] ## factorials[j + 1] = j! ) } cummulative_prob <- 1 - one_sub_cummulative_probs[n_bin] } one_sub_cummulative_probs <- c(1, one_sub_cummulative_probs) density_prob <- head(one_sub_cummulative_probs, -1) - tail(one_sub_cummulative_probs, -1) density_prob <- density_prob / cummulative_prob return(density_prob) } ``` The implementation above calculates discrete probabilities $p_i$'s base on the cummulative density function of the Erlang distribution: \begin{equation*} p_i = CDF_{Erlang}(x = i) - CDF_{Erlang}(x = i-1) \end{equation*} Meanwhile, the estimates of $p_i$'s in the original paper seems to be based on the probability density function: \begin{equation*} p_i = PDF_{Erlang}(x = i) \end{equation*} While the two methods give slightly different estimates, they do not lead to any visible differences in the results of the subsequent simulations. This implementation uses the CDF function since it leads to faster runs. ## Simulate the SEIR Dynamics The next function is to simulate the SEIR (susceptible, exposed, infectious, recovered) dynamics of an epidemic, assuming that transmission is frequency-dependent, i.e. \begin{equation*} \beta = \beta_0 \frac{I(t)}{N} \end{equation*} where $N$ is the population size, $I(t)$ is the number of infectious people at time $t$, and $\beta_0$ is the base transmission rate. This model does not consider births and deads (i.e. $N$ is constant). The rates at which individuals move through the E and the I classes are assumed to follow Erlang distributions of given shapes ($k^E$, $k^I$) and rates ($\gamma^E$, $\gamma^I$). ``` #' @param initial_state A vector that contains 4 numbers corresponding to the #' initial values of the 4 classes: S, E, I, and R. #' @param parameters A vector that contains 5 numbers corresponding to the #' following parameters: the shape and the rate parameters #' of the Erlang distribution that will be used to #' calculate the transition rates between the E components #' (i.e. k[E] and gamma[E]), the shape and the rate parameters #' of the Erlang distribution that will be used to #' calculate the transition rates between the I components #' (i.e. k[I] and gamma[I]), and the base transmission rate #' (i.e. beta). #' @param max_time The length of the simulation. #' @return A data frame containing the values of S, E, I, and R over time #' (from 1 to max_time). seir_simulation <- function(initial_state, parameters, max_time) { names(initial_state) <- c("S", "E", "I", "R") names(parameters) <- c( "erlang_shape_for_E", "erlang_rate_for_E", "erlang_shape_for_I", "erlang_rate_for_I", "base_transmission_rate" ) population_size <- sum(initial_state) sim_data <- data.frame( time = c(1 : max_time), S = NA, E = NA, I = NA, R = NA ) sim_data[1, 2:5] <- initial_state ## Initialise a matrix to store the states of the exposed sub-blocks over time. exposed_block_adm_rates <- compute_erlang_discrete_prob( k = parameters["erlang_shape_for_E"], gamma = parameters["erlang_rate_for_E"] ) n_exposed_blocks <- length(exposed_block_adm_rates) exposed_blocks <- matrix( data = 0, nrow = max_time, ncol = n_exposed_blocks ) exposed_blocks[1, n_exposed_blocks] <- sim_data$E[1] ## Initialise a matrix to store the states of the infectious sub-blocks over time. infectious_block_adm_rates <- compute_erlang_discrete_prob( k = parameters["erlang_shape_for_I"], gamma = parameters["erlang_rate_for_I"] ) n_infectious_blocks <- length(infectious_block_adm_rates) infectious_blocks <- matrix( data = 0, nrow = max_time, ncol = n_infectious_blocks ) infectious_blocks[1, n_infectious_blocks] <- sim_data$I[1] ## Run the simulation from time t = 2 to t = max_time for (time in 2 : max_time) { transmission_rate <- parameters["base_transmission_rate"] * sim_data$I[time - 1] / population_size exposure_prob <- 1 - exp(-transmission_rate) new_exposed <- rbinom(1, sim_data$S[time - 1], exposure_prob) new_infectious <- exposed_blocks[time - 1, 1] new_recovered <- infectious_blocks[time - 1, 1] if (new_exposed > 0) { exposed_blocks[time, ] <- t( rmultinom(1, size = new_exposed, prob = exposed_block_adm_rates) ) } exposed_blocks[time, ] <- exposed_blocks[time, ] + c( exposed_blocks[time - 1, 2 : n_exposed_blocks], 0 ) if (new_infectious > 0) { infectious_blocks[time, ] <- t( rmultinom(1, size = new_infectious, prob = infectious_block_adm_rates) ) } infectious_blocks[time, ] <- infectious_blocks[time, ] + c( infectious_blocks[time - 1, 2 : n_infectious_blocks], 0 ) sim_data$S[time] <- sim_data$S[time - 1] - new_exposed sim_data$E[time] <- sum(exposed_blocks[time, ]) sim_data$I[time] <- sum(infectious_blocks[time, ]) sim_data$R[time] <- sim_data$R[time - 1] + new_recovered } return(sim_data) } ``` To run a simulation, simply call the $seir\_simulation(\dots)$ method above. Below is an example simulation where $k^E = 5$, $\gamma^E = 1$, $k^I = 10$, $\gamma^I = 1$, and $\beta_0 = 0.25$ ($R_0 = \beta_0\frac{k^I}{\gamma^I} = 2.5$). The population size is $N = 10,000$. The simmulation starts with 1 exposed case and everyone else belongs to the susceptible class. These settings are the same the the simulation 11 of the original paper. **N.B. Since this is a stochastic model, there is chance for the outbreak not to occur even with a high $R_0$.** ``` sim <- seir_simulation( initial_state = c(S = 9999, E = 1, I = 0, R = 0), parameters = c(5, 1, 10, 1, 0.25), max_time = 300 ) ``` ## Visualisation ``` library(ggplot2) ggplot(sim, aes(time)) + geom_line(aes(y = S, colour = "Susceptible"), lwd = 1) + geom_line(aes(y = E, colour = "Exposed"), lwd = 1) + geom_line(aes(y = I, colour = "Infectious"), lwd = 1) + geom_line(aes(y = R, colour = "Recovered"), lwd = 1) + xlab("Time") + ylab("Number of Individuals") ``` ## Test Case ``` set.seed(12345) test_sim <- seir_simulation( initial_state = c(S = 9999, E = 1, I = 0, R = 0), parameters = c(5, 1, 10, 1, 0.25), max_time = 100 ) test_result <- as.matrix( tail(test_sim, 3) ) correct_result <- matrix( c( 98, 7384, 794, 1015, 807, 99, 7184, 864, 1068, 884, 100, 6986, 920, 1144, 950), nrow = 3, byrow = T ) n_correct_cells <- sum(correct_result == test_result) cat("\n--------------------\n") if (n_correct_cells == 15) { cat(" Test PASSED\n") } else { cat(" Test FAILED\n") } cat("--------------------\n\n") ```
github_jupyter
# <div align="center">Random Forest Classification in Python</div> --------------------------------------------------------------------- you can Find me on Github: > ###### [ GitHub](https://github.com/lev1khachatryan) <img src="asset/main.png" /> <a id="top"></a> <br> ## Notebook Content 1. [The random forests algorithm](#1) 2. [How does the algorithm work?](#2) 3. [Its advantages and disadvantages](#3) 4. [Finding important features](#4) 5. [Comparision between random forests and decision trees](#5) 6. [Building a classifier with scikit-learn](#6) 7. [Finding important features with scikit-learn](#7) <a id="1"></a> <br> # <div align="center">1. The Random Forests Algorithm</div> --------------------------------------------------------------------- [go to top](#top) Random forests is a supervised learning algorithm. It can be used both for classification and regression. It is also the most flexible and easy to use algorithm. A forest is comprised of trees. It is said that the more trees it has, the more robust a forest is. Random forests creates decision trees on randomly selected data samples, gets prediction from each tree and selects the best solution by means of voting. It also provides a pretty good indicator of the feature importance. Random forests has a variety of applications, such as recommendation engines, image classification and feature selection. It can be used to classify loyal loan applicants, identify fraudulent activity and predict diseases. It lies at the base of the Boruta algorithm, which selects important features in a dataset. Let’s understand the algorithm in layman’s terms. Suppose you want to go on a trip and you would like to travel to a place which you will enjoy. So what do you do to find a place that you will like? You can search online, read reviews on travel blogs and portals, or you can also ask your friends. Let’s suppose you have decided to ask your friends, and talked with them about their past travel experience to various places. You will get some recommendations from every friend. Now you have to make a list of those recommended places. Then, you ask them to vote (or select one best place for the trip) from the list of recommended places you made. The place with the highest number of votes will be your final choice for the trip. In the above decision process, there are two parts. First, asking your friends about their individual travel experience and getting one recommendation out of multiple places they have visited. This part is like using the decision tree algorithm. Here, each friend makes a selection of the places he or she has visited so far. The second part, after collecting all the recommendations, is the voting procedure for selecting the best place in the list of recommendations. This whole process of getting recommendations from friends and voting on them to find the best place is known as the random forests algorithm. It technically is an ensemble method (based on the divide-and-conquer approach) of decision trees generated on a randomly split dataset. This collection of decision tree classifiers is also known as the forest. The individual decision trees are generated using an attribute selection indicator such as information gain, gain ratio, and Gini index for each attribute. Each tree depends on an independent random sample. In a classification problem, each tree votes and the most popular class is chosen as the final result. In the case of regression, the average of all the tree outputs is considered as the final result. It is simpler and more powerful compared to the other non-linear classification algorithms. <a id="2"></a> <br> # <div align="center">2. How does the algorithm work?</div> --------------------------------------------------------------------- [go to top](#top) It works in four steps: 1) Select random samples from a given dataset. 2) Construct a decision tree for each sample and get a prediction result from each decision tree. 3) Perform a vote for each predicted result. 4) Select the prediction result with the most votes as the final prediction. <img src="asset/1.png" /> <a id="3"></a> <br> # <div align="center">3. Its advantages and disadvantages</div> --------------------------------------------------------------------- [go to top](#top) ### Advantages: * Random forests is considered as a highly accurate and robust method because of the number of decision trees participating in the process. * It does not suffer from the overfitting problem. The main reason is that it takes the average of all the predictions, which cancels out the biases. * The algorithm can be used in both classification and regression problems. * Random forests can also handle missing values. There are two ways to handle these: using median values to replace continuous variables, and computing the proximity-weighted average of missing values. * You can get the relative feature importance, which helps in selecting the most contributing features for the classifier. ### Disadvantages: * Random forests is slow in generating predictions because it has multiple decision trees. Whenever it makes a prediction, all the trees in the forest have to make a prediction for the same given input and then perform voting on it. This whole process is time-consuming. * The model is difficult to interpret compared to a decision tree, where you can easily make a decision by following the path in the tree. <a id="4"></a> <br> # <div align="center">4. Finding important features</div> --------------------------------------------------------------------- [go to top](#top) Random forests also offers a good feature selection indicator. Scikit-learn provides an extra variable with the model, which shows the relative importance or contribution of each feature in the prediction. It automatically computes the relevance score of each feature in the training phase. Then it scales the relevance down so that the sum of all scores is 1. This score will help you choose the most important features and drop the least important ones for model building. Random forest uses ***gini importance*** or mean decrease in impurity (***MDI***) to calculate the importance of each feature. Gini importance is also known as the total decrease in node impurity. This is how much the model fit or accuracy decreases when you drop a variable. The larger the decrease, the more significant the variable is. Here, the mean decrease is a significant parameter for variable selection. The Gini index can describe the overall explanatory power of the variables. <a id="5"></a> <br> # <div align="center">5. Random Forests vs Decision Trees</div> --------------------------------------------------------------------- [go to top](#top) * Random forests is a set of multiple decision trees. * Deep decision trees may suffer from overfitting, but random forests prevents overfitting by creating trees on random subsets. * Decision trees are computationally faster. * Random forests is difficult to interpret, while a decision tree is easily interpretable and can be converted to rules. <a id="6"></a> <br> # <div align="center">6. Building a Classifier using Scikit-learn</div> --------------------------------------------------------------------- [go to top](#top) ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.ensemble import RandomForestClassifier # Import Random Forest Classifier from sklearn.model_selection import train_test_split # Import train_test_split function from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation from sklearn.metrics import auc, \ confusion_matrix, \ classification_report, \ roc_curve, \ roc_auc_score, \ precision_recall_curve, \ average_precision_score, \ accuracy_score, \ balanced_accuracy_score, \ precision_score, \ recall_score def roc_curve_plot(fpr, tpr): ''' Plot ROC rurve Parameters: fpr: float tpr: float Returns: plot: ROC curve graph ''' x = np.linspace(0,1,100) plt.figure(figsize = (10,6)) plt.plot(fpr, tpr) plt.plot(x,x,".", markersize = 1.6) plt.title("ROC Curve") plt.xlabel("FPR") plt.ylabel("TPR") plt.show() users = pd.read_csv('input/All_Users.csv') KPIs = pd.read_csv('input/KPIs_2&3.csv') Activities = pd.merge(users, KPIs) Activities.fillna(0, inplace =True) Activities['Learn'] = Activities.L + Activities.UL Activities['Social_1'] = Activities.UC + Activities.UP + Activities.DP Activities['Social_2'] = Activities.CP + Activities.P + Activities.OP Checkins = pd.read_csv('input/Checkins_4,5&6.csv') retained_activities = pd.read_csv('input/KPIs_4,5&6.csv') Retention = pd.merge(pd.merge(users, Checkins, how = 'left'), retained_activities) Retention.fillna(0, inplace =True) Retention['Learn'] = Retention.L + Retention.UL Retention['Social_1'] = Retention.UC + Retention.UP + Retention.DP Retention['Social_2'] = Retention.CP + Retention.P + Retention.OP Retention['Total'] = Retention.Learn + Retention.Social_1 + Retention.Social_2 Retention['y'] = np.where((Retention.NofCheckins > 0) & (Retention.Total >= 3) & (Retention.Learn >= 0) & (Retention.Social_1 >= 0), 1 , 0) # columns to use X_col = ['UC', 'UP', 'DP', 'CP', 'L', 'UL', 'P', 'OP', 'F'] # X_col = ['Learn', 'Social_1', 'Social_2'] y_col = 'y' X = Activities[X_col] y = Retention[y_col] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test from sklearn.model_selection import GridSearchCV rfc = RandomForestClassifier(random_state=42) param_grid = { 'n_estimators': [3, 4, 5, 200, 500], 'max_features': ['auto', 'sqrt', 'log2'], 'max_depth' : [4,5,6,7,8], 'criterion' :['gini', 'entropy'] } CV_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv= 5) CV_rfc.fit(X_train, y_train) CV_rfc.best_params_ clf = RandomForestClassifier(random_state=42, max_features='auto', n_estimators= 500, max_depth=8, criterion='entropy') clf.fit(X_train,y_train) y_pred=clf.predict(X_test) pred = clf.predict(X_test) pred_prob = clf.predict_proba(X_test) ''' Obtain confusion_matrix ''' tn, fp, fn, tp = confusion_matrix(y_true = y_test, y_pred = pred, labels = np.array([0,1])).ravel() print(tn, fp, fn, tp) ''' Calculate auc(Area Under the Curve) for positive class ''' fpr, tpr, thresholds = roc_curve(y_true = y_test, y_score = pred_prob[:,1], pos_label = 1) auc_random_forest = auc(fpr,tpr) print(auc_random_forest) roc_curve_plot(fpr=fpr, tpr=tpr) ''' Calculation of metrics using standard functions ''' print('Accuracy: {}'.format(accuracy_score(y_test,pred))) print('Balanced accuracy: {}'.format(balanced_accuracy_score(y_test, pred))) print('Precision: {}'.format(precision_score(y_test, pred))) print('Recall: {}'.format(recall_score(y_test, pred))) ``` <a id="7"></a> <br> # <div align="center">7. Finding Important Features in Scikit-learn</div> --------------------------------------------------------------------- [go to top](#top) Here, you are finding important features or selecting features in the dataset. In scikit-learn, you can perform this task in the following steps: 1) First, you need to create a random forests model. 2) Second, use the feature importance variable to see feature importance scores. 3) Third, visualize these scores using the seaborn library. ``` feature_imp = pd.Series(clf.feature_importances_, index=X_train.columns.values).sort_values(ascending=False) feature_imp ``` You can also visualize the feature importance. Visualizations are easy to understand and interpretable. For visualization, you can use a combination of matplotlib and seaborn. Because seaborn is built on top of matplotlib, it offers a number of customized themes and provides additional plot types. Matplotlib is a superset of seaborn and both are equally important for good visualizations. ``` import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline # Creating a bar plot sns.barplot(x=feature_imp, y=feature_imp.index) # Add labels to your graph plt.xlabel('Feature Importance Score') plt.ylabel('Features') plt.title("Visualizing Important Features") plt.show(); ```
github_jupyter
<a href="https://colab.research.google.com/github/zjzsu2000/CMPE297_AdvanceDL_Project/blob/main/Data_Preprocessing/Final_result.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd import numpy as np from google.colab import drive from keras.models import Sequential, Model, load_model from keras.layers import Dense, Activation, LeakyReLU, BatchNormalization, LSTM, Bidirectional, Input, Concatenate from keras import backend as K from keras.callbacks import TensorBoard from keras.optimizers import Adam from keras.utils import plot_model from sklearn.model_selection import train_test_split drive.mount('/gdrive') option = pd.read_csv('/gdrive/My Drive/Data set/Option/WIX_call-options-black-scholes.csv') lstm_option = pd.read_csv('/gdrive/My Drive/Data set/Option/underlying/call/WIX_underlying_call.csv') model_lstm = load_model('/gdrive/Shareddrives/CMPE297_49_project/models/model1_lstm_call_1.h5') model2 = load_model('/gdrive/Shareddrives/CMPE297_49_project/models/model2_call21_all_4000.h5') model3= load_model('/gdrive/Shareddrives/CMPE297_49_project/models/model3_call_sigma5_all_1024_4000.h5') lstm_option.tail() model_lstm.summary() lstm_test = lstm_option[lstm_option['OptionSymbol']=='WIX200117C00060000'] lstm_test lstm_test = lstm_test[['UnderlyingPrice','Strike','Bid','Ask','sigma_21','date_diff','treasury_rate','1','2','3','4','5','6','7','8','9','10' ,'11','12','13','14','15','16','17','18','19','20','21']] lstm_test = lstm_test.dropna() lstm_test #test_lstm_f = lstm_test[['UnderlyingPrice','Strike','sigma_21','date_diff','treasury_rate']] test_lstm_x = lstm_test.drop(['Bid','sigma_21','Ask'], axis=1).values #[['1','2','3','4','5','6','7','8','9','10' # ,'11','12','13','14','15','16','17','18','19','20','21']] test_lstm_y = (lstm_test.Bid + lstm_test.Ask) /2 N_TIMESTEPS = 21 test_lstm_x = [test_lstm_x[:, -N_TIMESTEPS:].reshape(test_lstm_x.shape[0], N_TIMESTEPS, 1), test_lstm_x[:, :4]] test_lstm_x[1] model_lstm.evaluate([test_lstm_x,test_lstm_f],test_lstm_y,batch_size=1024) lstmpre = model_lstm.predict(test_lstm_x) test_lstm_y lstmpre from matplotlib import pyplot as plt4 plt4.figure(figsize=(20, 10)) plt4.ylabel('price') plt4.xlabel('day') plt4.title('LSTM compare') plt4.plot(lstmpre,label = 'LSTM') plt4.plot(test_lstm_y.values, label = 'real') plt4.legend() model2.summary() option.head() option.OptionSymbol.value_counts() test = option[option['OptionSymbol']=='WIX200117C00060000'] test = test[['UnderlyingPrice','Strike','Bid','Ask','sigma_21','date_diff','treasury_rate']] test=test.dropna() test test_x = test[['UnderlyingPrice','Strike','sigma_21','date_diff','treasury_rate']] test_y = (test.Bid + test.Ask) /2 model2.evaluate(test_x,test_y,batch_size=1024) pred= model2.predict(test_x) len(pred) len(test_y) test_y from matplotlib import pyplot as plt plt.figure(figsize=(20, 10)) plt.ylabel('price') plt.xlabel('day') plt.title('model2 compare') plt.plot(pred,label = 'model2') plt.plot(test_y.values, label = 'real') plt.legend() model3.summary() pre3=model3.predict(test_x) len(pre3[:,0]) test_y3 = test[['Bid','Ask']] test_yb = test_y3.Bid.values test_ya = test_y3.Ask.values from matplotlib import pyplot as plt2 plt2.figure(figsize=(20, 10)) plt2.ylabel('price') plt2.xlabel('day') plt2.title('model3 Bid') plt2.plot(pre3[:,0],label = 'model3') plt2.plot(test_yb, label = 'Bid') plt2.legend() from matplotlib import pyplot as plt3 plt3.figure(figsize=(20, 10)) plt3.ylabel('price') plt3.xlabel('day') plt3.title('model3 Ask') plt3.plot(pre3[:,1],label = 'model3') plt3.plot(test_ya, label = 'Ask') plt3.legend() ```
github_jupyter
``` # hide # all_tutorial ! [ -e /content ] && pip install -Uqq mrl-pypi # upgrade mrl on colab ``` # Tutorial - Conditional LSTM Language Models >Training and using conditional LSTM language models ## LSTM Language Models LSTM language models are a type of autoregressive generative model. This particular type of model is a good fit for RL-based optimization as they are light, robust and easy to optimize. These models make use of the [LSTM](https://arxiv.org/abs/1402.1128) architecture design. Language models are trained in a self-supervised fashion by next token prediction. Given a series of tokens, the model predicts a probability distribution over he next token. Self supervised training is very fast and doesn't require any data labels. Each text string in the dataset labels itself. During generation, we sample from the model in an autoregression fashion. Given an input token, the model predicts aa distribution of tokens over the next token. We then sample from that distributiona and feed the selected token back into the model. We repeat this process until either an end of sentence (EOS) token is predicted, or the generated sequence reaches a maximum allowed length. During sampling, we save the log probability of each token predicted. This gives us a probability value for the model's estimated likelihood of the generated compound. We can also backprop through this value. ### Conditional Language Models Conditional language models condition the generated sequences on some latent vector. Conditioning can be implemented in two ways: - hidden conditioning: use the latent vector to initialize the hidden state of the model - output conditioning: concatenate the latent vector to the model activations right before the LSTM layers The latent vector itself is generated by some encoder ``` import sys sys.path.append('..') from mrl.imports import * from mrl.core import * from mrl.chem import * from mrl.torch_imports import * from mrl.torch_core import * from mrl.layers import * from mrl.dataloaders import * from mrl.g_models.all import * from mrl.train.agent import * from mrl.vocab import * ``` ## Setup Before creating a model, we need to set up our data. Our raw data is in the form of SMILES strings. We need to convert these to tensors. First we need a `Vocab` to handle converting strings to tokens and mapping those tokens to integers. We will use the `CharacterVocab` class with the `SMILES_CHAR_VOCAB` vocabulary. This will tokenize SMILES on a character basis. More sophisticated tokenization schemes exist, but character tokenization is nice for the simplicity. Character tokenization has a small, compact vocabulary. Other tokenization strategies can tokenize by more meaningful subwords, but these strategies create a long tail of low frequency tokens and lots of `unk` characters. ``` # if in the repo df = pd.read_csv('../files/smiles.csv') # if in Collab: # download_files() # df = pd.read_csv('files/smiles.csv') df.head() vocab = CharacterVocab(SMILES_CHAR_VOCAB) ``` `vocab` first tokenizes smiles into characters, then numericalizes the tokens into integer keys ``` ' '.join(vocab.tokenize(df.smiles.values[0])) ' '.join([str(i) for i in vocab.numericalize(vocab.tokenize(df.smiles.values[0]))]) ``` ## Dataset Now we need a dataset. For a conditional language model, we have to decide what data we want to send to the encoder to generate a latent vector. For this tutorial, we are going to use molecular fingerprints to generate the latent vector. The model will use the encoder to map the input fingerprint to a latent vector. Then the latent vector will be used to condition the hidden state of the decoder, which will reconstruct the SMILES string corresponding to the fingerprint. To do this, we will use the `Vec_To_Text_Dataset` dataset with `ECFP6` as our fingerprint function ``` dataset = Vec_To_Text_Dataset(df.smiles.values, vocab, ECFP6) dataloader = dataset.dataloader(32) ``` Now we can look at the actual data ``` x,y = next(iter(dataloader)) x y ``` The `x` tensor is a tuple containing `(fingerprint, smiles_ints)`. The fingerprint (`x[1]`) will be used to generate the latent vector, while the integer-coded SMILES string (`x[0]`) will be sent to the decoder along with the latent vector. You will notice the `y` tensor is the same as the `x[0]` tensor with the values shifted by one. This is because the goal of autoregressive language modeling is to predict the next character given the previous series of characters. ## Model Creation We can create a model through the `Conditional_LSTM_LM` class. First we need an encoder. Since our encoder data is a fingerprint, we will use a MLP-type encoder and set our latent vector to have a dimension of `512` ``` enc_drops = [0.1, 0.1] d_latent = 512 encoder = MLP_Encoder(2048, [1024, 512], d_latent, enc_drops) ``` Now we create the model ``` d_vocab = len(vocab.itos) bos_idx = vocab.stoi['bos'] d_embedding = 256 d_hidden = 1024 n_layers = 3 tie_weights = True input_dropout = 0.3 lstm_dropout = 0.3 model = Conditional_LSTM_LM( encoder, d_vocab, d_embedding, d_hidden, d_latent, n_layers, input_dropout=input_dropout, lstm_dropout=lstm_dropout, norm_latent=True, condition_hidden=True, condition_output=False, bos_idx=bos_idx, ) ``` We can examine the encoder-decoder structure of the model. We have a `MLP_Encoder` section which contains three MP layers. then we have a `decoder` section that consists of an embedding, three LSTM layers and an output layer ``` model ``` Now we'll put the model into a `GenerativeAgent` to manage supervised training. We need to specify a loss function - we will use standard cross entropy ``` loss_function = CrossEntropy() agent = GenerativeAgent(model, vocab, loss_function, dataset, base_model=False) ``` Now we can train in a supervised fashion on next token prediction ``` agent.train_supervised(32, 1, 1e-3) ``` This was just a quick example to show the training API. We're not going to do a whole training process here. To train custom models, repeat this code with your own set of SMILES. ## Pre-trained Models The MRL model zoo offers a number of pre-trained models. We'll load one of these to continue. We'll use the `LSTM_LM_Small_Chembl` model. This model was trained first on a chunk of the ZINC database ``` del model del agent gc.collect() torch.cuda.empty_cache() from mrl.model_zoo import FP_Cond_LSTM_LM_Small_ZINC agent = FP_Cond_LSTM_LM_Small_ZINC(drop_scale=0.5, base_model=False) ``` Now with a fully pre-trained model, we can look at drawing samples ``` preds, lps = agent.model.sample_no_grad(256, 100, temperature=1.) preds lps.shape ``` The `sample_no_grad` function gives is two outputs - `preds` and `lps`. `preds` is a long tensor of size `(bs, sl)` containing the integer tokens of the samples. `lps` is a float tensor of size `(bs, sl)` containing the log probabilities of each value in `preds` We can now reconstruct the predictions back into SMILES strings ``` smiles = agent.reconstruct(preds) smiles[:10] mols = to_mols(smiles) ``` Now lets look at some key generation statistics. - diversity - the percentage of unique samples - valid - the number of chemically valid samples ``` div = len(set(smiles))/len(smiles) val = len([i for i in mols if i is not None])/len(mols) print(f'Diversity:\t{div:.3f}\nValid:\t\t{val:.3f}') valid_mols = [i for i in mols if i is not None] draw_mols(valid_mols[:16], mols_per_row=4) ``` ## Conditional Generation Lets look further at how conditional generation works. One important aspect of conditioning on a latent space is the ability to sample from it. This poses an interesting challenge for a conditional language model, because unlike models like `VAE`, there is no set prior distribution. The `Conditional_LSTM_LM` class handles this with the `norm_latent` argument. If `norm_latent=true` (as above), the latent vectors are all normalized to a magnitude of 1 before being sent to the decoder. This is similar to what is done in StyleGan-type models. By setting the norm constraint, we can sample valid latent vectors by sampling from a normal distribution and normalizing the resulting vectors. ``` latents = to_device(torch.randn((64, agent.model.encoder.d_latent))) preds, lps = agent.model.sample_no_grad(latents.shape[0], 100, z=latents, temperature=1.) smiles = agent.reconstruct(preds) mols = to_mols(smiles) mols = [i for i in mols if i is not None] draw_mols(mols[:16], mols_per_row=4) ``` ## Conditional Samples on a Single Input One advantage of using a conditional generation is the ability to sample multiple compounds from a specific input. Here we get a latent vector from a specific molecule in the datase ``` smile = df.smiles.values[0] to_mol(smile) smile_ds = dataset.new([smile]) batch = to_device(smile_ds.collate_function([smile_ds[0]])) x,y = batch agent.model.eval(); latents = agent.model.x_to_latent(x) latents.shape ``` Now we sample 64 molecules from the same latent vector. The diversity of the outputs will depend on the sampling temperature used and the degree of dropout (if enabled) ``` agent.model.train(); preds, lps = agent.model.sample_no_grad(64, 100, z=latents.repeat(64,1), temperature=1.) smiles = agent.reconstruct(preds) print(len(set(smiles)), len(set(smiles))/len(smiles)) smiles = list(set(smiles)) mols = to_mols(smiles) mols = [i for i in mols if i is not None] len(mols) draw_mols(mols[:16], mols_per_row=4) ``` In the above section, we generated 64 compounds and ended up with 10 unique SMILES strings. If we want more diversity, we can sample with a higher temperature. You'll see we get 40 unique SMILES. However, only 36 of them are valid SMILES strings. This is the tradeoff of using higher sampling temperatures ``` preds, lps = agent.model.sample_no_grad(64, 100, z=latents.repeat(64,1), temperature=2.) smiles = agent.reconstruct(preds) print(len(set(smiles)), len(set(smiles))/len(smiles)) smiles = list(set(smiles)) mols = to_mols(smiles) mols = [i for i in mols if i is not None] len(mols) draw_mols(mols[:16], mols_per_row=4) ``` ## Prior The `Conditional_LSTM_LM` supports a defined prior distrribution for sampling. By default, this prior is not enabled. We can set the prior using the latent vector we generated earlier to focus the model's prior distribution on that area of the latent space. To create this distribution, we first need to define the log-variance of the latent space. We will set the log variance to `-5` to set aa tight distribution around the latent vector. ``` logvar = to_device(torch.zeros(latents.shape)-5) agent.model.set_prior_from_latent(latents.squeeze(0), logvar.squeeze(0), trainable=False) preds, lps = agent.model.sample_no_grad(128, 100, temperature=1.) smiles = agent.reconstruct(preds) print(len(set(smiles)), len(set(smiles))/len(smiles)) smiles = list(set(smiles)) mols = to_mols(smiles) mols = [i for i in mols if i is not None] len(mols) draw_mols(mols[:16], mols_per_row=4) ``` With the small but nonzero variance around the latent vector, we get compounds that are different but share many of the features of the original molecule
github_jupyter
# Decisiton Tree interpretability notebook ``` import os import matplotlib.pyplot as plt import pandas as pd from sklearn.tree import plot_tree from dtreeviz.trees import * from pycaret import classification ``` ### Exploratory data analysis Import to specify correctly the data path. Initally we can make an easy exploration. ``` data_folder_path = os.path.join('..', 'data') data_file = 'ds.csv' df = pd.read_csv(os.path.join(data_folder_path, data_file)) df.describe() df.gender.value_counts() playerTypes = pd.get_dummies(df['PlayerType']) df = pd.concat([df.drop("PlayerType", axis=1), playerTypes], axis=1) df.head() ``` ### Classification Set-up Definition of main model hyperparameters. Numeric features and target with full description available. ``` classification_setup = classification.setup( data=df, target='gender', numeric_features=[c for c in df.columns if c not in ['gender', 'matchPeriod', 'PlayerType']] ) ``` Initial exploration to understand general performance metrics for different classification algorithms (Focus at Accuracy and AUC) ``` classification.compare_models() ``` Decision tree implementation, prunning of the tree at 40 samples per leaf and looking at the Entropy gain of each split. Model evaluated with a 10-fold cross validation. ``` classification.set_config('seed', 7940) dt_model = classification.create_model('dt', min_samples_leaf=40, criterion='entropy') dt_model tuned_dt_model = classification.tune_model(dt_model) dt_model = classification.load_model('./static_models/dt_6_10') dt_model ``` ### Decision Tree implementation - Feature importance as an aggregated from each split. - Full Tree visualization. ``` classification_setup[0].columns plot_options = ["auc","threshold","pr","confusion_matrix","error","class_report","boundary","rfe","learning","manifold","calibration","vc","dimension","feature","parameter"] classification.plot_model(dt_model, plot='feature', save=True) #Importance of the features measured by how much the nod purity is imporved on average. interpretation_options = ['summary', 'correlation', 'reason'] classification.interpret_model(dt_model, interpretation_options[0]) classification.interpret_model(dt_model, interpretation_options[1], feature='Clearances') viz = dtreeviz(dt_model, classification_setup[0], df.gender, target_name='gender', feature_names=classification_setup[0].columns, class_names=['Female', 'Male'], orientation='TD', fontname='serif') viz.view() classification.plot_model(dt_model, plot='boundary') plot_tree(dt_model, filled=True) ``` ### Scientific Reporting ``` coef_df = pd.DataFrame({'Feature': classification_setup[0].columns, 'Coefficients': dt_model.feature_importances_}) coef_df.sort_values(by=['Coefficients'], ascending=False).head(10).to_latex(index=False) ```
github_jupyter
# OpenCV example. Show webcam image and detect face. It uses Lena's face and add random noise to it if the video capture doesn't work for some reason. https://gist.github.com/astanin/3097851 <table > <tr> <th>![Lena's picture + random noise](./images/Screenshot_2017-06-15_12-47-50.png)</th> <th>![Patrick's face captured without noise](./images/Screenshot_2017-06-15_12-50-42.png)</th> </tr> </table> ## OpenCV Haar Cascade classifer http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html https://github.com/opencv/opencv/tree/master/data/haarcascades Exit by pressing `ESC` ``` from __future__ import print_function import numpy as np import cv2 # local modules from video import create_capture from common import clock, draw_str def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects def draw_rects(img, rects, color): for x1, y1, x2, y2 in rects: cv2.rectangle(img, (x1, y1), (x2, y2), color, 2) import sys, getopt print(__doc__) args, video_src = getopt.getopt(sys.argv[2:], '', ['cascade=', 'nested-cascade=']) try: video_src = video_src[0] except: video_src = 0 args = dict(args) fullpath_openCV = '/home/patechoc/anaconda2/share/OpenCV/haarcascades/' cascade_fn = args.get('--cascade', fullpath_openCV + "haarcascade_frontalface_alt.xml") nested_fn = args.get('--nested-cascade', fullpath_openCV + "haarcascade_eye.xml") cascade = cv2.CascadeClassifier(cascade_fn) nested = cv2.CascadeClassifier(nested_fn) # cam = create_capture(video_src, fallback='synth:bg=./data/lena.jpg:noise=0.05') cam = create_capture(video_src, fallback='synth:bg=./data/lena.jpg:noise=0.05') while True: ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) t = clock() rects = detect(gray, cascade) vis = img.copy() draw_rects(vis, rects, (0, 255, 0)) if not nested.empty(): for x1, y1, x2, y2 in rects: roi = gray[y1:y2, x1:x2] vis_roi = vis[y1:y2, x1:x2] subrects = detect(roi.copy(), nested) draw_rects(vis_roi, subrects, (255, 0, 0)) dt = clock() - t draw_str(vis, (20, 20), 'time: %.1f ms' % (dt*1000)) cv2.imshow('facedetect', vis) if cv2.waitKey(5) == 27: break cv2.destroyAllWindows() ```
github_jupyter
# Neural Nets with Keras In this notebook you will learn how to implement neural networks using the Keras API. We will use TensorFlow's own implementation, *tf.keras*, which comes bundled with TensorFlow. Don't hesitate to look at the documentation at [keras.io](https://keras.io/). All the code examples should work fine with tf.keras, the only difference is how to import Keras: ```python # keras.io code: from keras.layers import Dense output_layer = Dense(10) # corresponding tf.keras code: from tensorflow.keras.layers import Dense output_layer = Dense(10) # or: from tensorflow import keras output_layer = keras.layers.Dense(10) ``` In this notebook, we will not use any TensorFlow-specific code, so everything you see would run just the same way on [keras-team](https://github.com/keras-team/keras) or any other Python implementation of the Keras API (except for the imports). ## Imports ``` %matplotlib inline %load_ext tensorboard.notebook import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import sklearn import sys import tensorflow as tf from tensorflow import keras # tf.keras import time print("python", sys.version) for module in mpl, np, pd, sklearn, tf, keras: print(module.__name__, module.__version__) assert sys.version_info >= (3, 5) # Python ≥3.5 required assert tf.__version__ >= "2.0" # TensorFlow ≥2.0 required ``` **Note**: The preview version of TensorFlow 2.0 shows up as version 1.13. That's okay. To test that this behaves like TF 2.0, we verify that `tf.function()` is present. ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 1 – TensorFlow Playground Visit the [TensorFlow Playground](http://playground.tensorflow.org). * **Layers and patterns**: try training the default neural network by clicking the "Run" button (top left). Notice how it quickly finds a good solution for the classification task. Notice that the neurons in the first hidden layer have learned simple patterns, while the neurons in the second hidden layer have learned to combine the simple patterns of the first hidden layer into more complex patterns). In general, the more layers, the more complex the patterns can be. * **Activation function**: try replacing the Tanh activation function with the ReLU activation function, and train the network again. Notice that it finds a solution even faster, but this time the boundaries are linear. This is due to the shape of the ReLU function. * **Local minima**: modify the network architecture to have just one hidden layer with three neurons. Train it multiple times (to reset the network weights, just add and remove a neuron). Notice that the training time varies a lot, and sometimes it even gets stuck in a local minimum. * **Too small**: now remove one neuron to keep just 2. Notice that the neural network is now incapable of finding a good solution, even if you try multiple times. The model has too few parameters and it systematically underfits the training set. * **Large enough**: next, set the number of neurons to 8 and train the network several times. Notice that it is now consistently fast and never gets stuck. This highlights an important finding in neural network theory: large neural networks almost never get stuck in local minima, and even when they do these local optima are almost as good as the global optimum. However, they can still get stuck on long plateaus for a long time. * **Deep net and vanishing gradients**: now change the dataset to be the spiral (bottom right dataset under "DATA"). Change the network architecture to have 4 hidden layers with 8 neurons each. Notice that training takes much longer, and often gets stuck on plateaus for long periods of time. Also notice that the neurons in the highest layers (i.e. on the right) tend to evolve faster than the neurons in the lowest layers (i.e. on the left). This problem, called the "vanishing gradients" problem, can be alleviated using better weight initialization and other techniques, better optimizers (such as AdaGrad or Adam), or using Batch Normalization. * **More**: go ahead and play with the other parameters to get a feel of what they do. In fact, after this course you should definitely play with this UI for at least one hour, it will grow your intuitions about neural networks significantly. ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 2 – Image classification with tf.keras ### Load the Fashion MNIST dataset Let's start by loading the fashion MNIST dataset. Keras has a number of functions to load popular datasets in `keras.datasets`. The dataset is already split for you between a training set and a test set, but it can be useful to split the training set further to have a validation set: ``` fashion_mnist = keras.datasets.fashion_mnist (X_train_full, y_train_full), (X_test, y_test) = ( fashion_mnist.load_data()) X_valid, X_train = X_train_full[:5000], X_train_full[5000:] y_valid, y_train = y_train_full[:5000], y_train_full[5000:] ``` The training set contains 55,000 grayscale images, each 28x28 pixels: ``` X_train.shape ``` Each pixel intensity is represented by a uint8 (byte) from 0 to 255: ``` X_train[0] ``` You can plot an image using Matplotlib's `imshow()` function, with a `'binary'` color map: ``` plt.imshow(X_train[0], cmap="binary") plt.show() ``` The labels are the class IDs (represented as uint8), from 0 to 9: ``` y_train ``` Here are the corresponding class names: ``` class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] ``` So the first image in the training set is a coat: ``` class_names[y_train[0]] ``` The validation set contains 5,000 images, and the test set contains 10,000 images: ``` X_valid.shape X_test.shape ``` Let's take a look at a sample of the images in the dataset: ``` n_rows = 5 n_cols = 10 plt.figure(figsize=(n_cols*1.4, n_rows * 1.6)) for row in range(n_rows): for col in range(n_cols): index = n_cols * row + col plt.subplot(n_rows, n_cols, index + 1) plt.imshow(X_train[index], cmap="binary", interpolation="nearest") plt.axis('off') plt.title(class_names[y_train[index]]) plt.show() ``` This dataset has the same structure as the famous MNIST dataset (which you can load using `keras.datasets.mnist.load_data()`), except the images represent fashion items rather than handwritten digits, and it is much more challenging. A simple linear model can reach 92% accuracy on MNIST, but only 83% on fashion MNIST. ### Build a classification neural network with Keras ### 2.1) Build a `Sequential` model (`keras.models.Sequential`), without any argument, then and add four layers to it by calling its `add()` method: * a `Flatten` layer (`keras.layers.Flatten`) to convert each 28x28 image to a single row of 784 pixel values. Since it is the first layer in your model, you should specify the `input_shape` argument, leaving out the batch size: `[28, 28]`. * a `Dense` layer (`keras.layers.Dense`) with 300 neurons (aka units), and the `"relu"` activation function. * Another `Dense` layer with 100 neurons, also with the `"relu"` activation function. * A final `Dense` layer with 10 neurons (one per class), and with the `"softmax"` activation function to ensure that the sum of all the estimated class probabilities for each image is equal to 1. ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28,28])) model.add(keras.layers.Dense(300, activation="relu")) ``` ### 2.2) Alternatively, you can pass a list containing the 4 layers to the constructor of the `Sequential` model. The model's `layers` attribute holds the list of layers. ### 2.3) Call the model's `summary()` method and examine the output. Also, try using `keras.utils.plot_model()` to save an image of your model's architecture. Alternatively, you can uncomment the following code to display the image within Jupyter. **Warning**: you will need `pydot` and `graphviz` to use `plot_model()`. ### 2.4) After a model is created, you must call its `compile()` method to specify the `loss` function and the `optimizer` to use. In this case, you want to use the `"sparse_categorical_crossentropy"` loss, and the `"sgd"` optimizer (stochastic gradient descent). Moreover, you can optionally specify a list of additional metrics that should be measured during training. In this case you should specify `metrics=["accuracy"]`. **Note**: you can find more loss functions in `keras.losses`, more metrics in `keras.metrics` and more optimizers in `keras.optimizers`. ### 2.5) Now your model is ready to be trained. Call its `fit()` method, passing it the input features (`X_train`) and the target classes (`y_train`). Set `epochs=10` (or else it will just run for a single epoch). You can also (optionally) pass the validation data by setting `validation_data=(X_valid, y_valid)`. If you do, Keras will compute the loss and the additional metrics (the accuracy in this case) on the validation set at the end of each epoch. If the performance on the training set is much better than on the validation set, your model is probably overfitting the training set (or there is a bug, such as a mismatch between the training set and the validation set). **Note**: the `fit()` method will return a `History` object containing training stats. Make sure to preserve it (`history = model.fit(...)`). ### 2.6) Try running `pd.DataFrame(history.history).plot()` to plot the learning curves. To make the graph more readable, you can also set `figsize=(8, 5)`, call `plt.grid(True)` and `plt.gca().set_ylim(0, 1)`. ### 2.7) Try running `model.fit()` again, and notice that training continues where it left off. ### 2.8) call the model's `evaluate()` method, passing it the test set (`X_test` and `y_test`). This will compute the loss (cross-entropy) on the test set, as well as all the additional metrics (in this case, the accuracy). Your model should achieve over 80% accuracy on the test set. ### 2.9) Define `X_new` as the first 10 instances of the test set. Call the model's `predict()` method to estimate the probability of each class for each instance (for better readability, you may use the output array's `round()` method): ### 2.10) Often, you may only be interested in the most likely class. Use `np.argmax()` to get the class ID of the most likely class for each instance. **Tip**: you want to set `axis=1`. ### 2.11) Call the model's `predict_classes()` method for `X_new`. You should get the same result as above. ### 2.12) (Optional) It is often useful to know how confident the model is for each prediction. Try finding the estimated probability for each predicted class using `np.max()`. ### 2.13) (Optional) It is frequent to want the top k classes and their estimated probabilities rather just the most likely class. You can use `np.argsort()` for this. ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 2 - Solution ### 2.1) Build a `Sequential` model (`keras.models.Sequential`), without any argument, then and add four layers to it by calling its `add()` method: * a `Flatten` layer (`keras.layers.Flatten`) to convert each 28x28 image to a single row of 784 pixel values. Since it is the first layer in your model, you should specify the `input_shape` argument, leaving out the batch size: `[28, 28]`. * a `Dense` layer (`keras.layers.Dense`) with 300 neurons (aka units), and the `"relu"` activation function. * Another `Dense` layer with 100 neurons, also with the `"relu"` activation function. * A final `Dense` layer with 10 neurons (one per class), and with the `"softmax"` activation function to ensure that the sum of all the estimated class probabilities for each image is equal to 1. ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) model.add(keras.layers.Dense(300, activation="relu")) model.add(keras.layers.Dense(100, activation="relu")) model.add(keras.layers.Dense(10, activation="softmax")) ``` ### 2.2) Alternatively, you can pass a list containing the 4 layers to the constructor of the `Sequential` model. The model's `layers` attribute holds the list of layers. ``` model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.Dense(300, activation="relu"), keras.layers.Dense(100, activation="relu"), keras.layers.Dense(10, activation="softmax") ]) model.layers ``` ### 2.3) Call the model's `summary()` method and examine the output. Also, try using `keras.utils.plot_model()` to save an image of your model's architecture. Alternatively, you can uncomment the following code to display the image within Jupyter. ``` model.summary() keras.utils.plot_model(model, "my_mnist_model.png", show_shapes=True) %%html <img src="my_mnist_model.png" /> ``` **Warning**: at the present, you need `from tensorflow.python.keras.utils.vis_utils import model_to_dot`, instead of simply `keras.utils.model_to_dot`. See [TensorFlow issue 24639](https://github.com/tensorflow/tensorflow/issues/24639). ``` from IPython.display import SVG from tensorflow.python.keras.utils.vis_utils import model_to_dot SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg')) ``` ### 2.4) After a model is created, you must call its `compile()` method to specify the `loss` function and the `optimizer` to use. In this case, you want to use the `"sparse_categorical_crossentropy"` loss, and the `"sgd"` optimizer (stochastic gradient descent). Moreover, you can optionally specify a list of additional metrics that should be measured during training. In this case you should specify `metrics=["accuracy"]`. **Note**: you can find more loss functions in `keras.losses`, more metrics in `keras.metrics` and more optimizers in `keras.optimizers`. ``` model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) ``` ### 2.5) Now your model is ready to be trained. Call its `fit()` method, passing it the input features (`X_train`) and the target classes (`y_train`). Set `epochs=10` (or else it will just run for a single epoch). You can also (optionally) pass the validation data by setting `validation_data=(X_valid, y_valid)`. If you do, Keras will compute the loss and the additional metrics (the accuracy in this case) on the validation set at the end of each epoch. If the performance on the training set is much better than on the validation set, your model is probably overfitting the training set (or there is a bug, such as a mismatch between the training set and the validation set). **Note**: the `fit()` method will return a `History` object containing training stats. Make sure to preserve it (`history = model.fit(...)`). ``` history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid)) ``` ### 2.6) Try running `pd.DataFrame(history.history).plot()` to plot the learning curves. To make the graph more readable, you can also set `figsize=(8, 5)`, call `plt.grid(True)` and `plt.gca().set_ylim(0, 1)`. ``` def plot_learning_curves(history): pd.DataFrame(history.history).plot(figsize=(8, 5)) plt.grid(True) plt.gca().set_ylim(0, 1) plt.show() plot_learning_curves(history) ``` ### 2.7) Try running `model.fit()` again, and notice that training continues where it left off. ``` history = model.fit(X_train, y_train, epochs=10, validation_data=(X_valid, y_valid)) ``` ### 2.8) Call the model's `evaluate()` method, passing it the test set (`X_test` and `y_test`). This will compute the loss (cross-entropy) on the test set, as well as all the additional metrics (in this case, the accuracy). Your model should achieve over 80% accuracy on the test set. ``` model.evaluate(X_test, y_test) ``` ### 2.9) Define `X_new` as the first 10 instances of the test set. Call the model's `predict()` method to estimate the probability of each class for each instance (for better readability, you may use the output array's `round()` method): ``` n_new = 10 X_new = X_test[:n_new] y_proba = model.predict(X_new) y_proba.round(2) ``` ### 2.10) Often, you may only be interested in the most likely class. Use `np.argmax()` to get the class ID of the most likely class for each instance. **Tip**: you want to set `axis=1`. ``` y_pred = y_proba.argmax(axis=1) y_pred ``` ### 2.11) Call the model's `predict_classes()` method for `X_new`. You should get the same result as above. ``` y_pred = model.predict_classes(X_new) y_pred ``` ### 2.12) (Optional) It is often useful to know how confident the model is for each prediction. Try finding the estimated probability for each predicted class using `np.max()`. ``` y_proba.max(axis=1).round(2) ``` ### 2.13) (Optional) It is frequent to want the top k classes and their estimated probabilities rather just the most likely class. You can use `np.argsort()` for this. ``` k = 3 top_k = np.argsort(-y_proba, axis=1)[:, :k] top_k row_indices = np.tile(np.arange(len(top_k)), [k, 1]).T y_proba[row_indices, top_k].round(2) ``` ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 3 – Scale the features ### 3.1) When using Gradient Descent, it is usually best to ensure that the features all have a similar scale, preferably with a Normal distribution. Try to standardize the pixel values and see if this improves the performance of your neural network. **Tips**: * For each feature (pixel intensity), you must subtract the `mean()` of that feature (across all instances, so use `axis=0`) and divide by its standard deviation (`std()`, again `axis=0`). Alternatively, you can use Scikit-Learn's `StandardScaler`. * Make sure you compute the means and standard deviations on the training set, and use these statistics to scale the training set, the validation set and the test set (you should not fit the validation set or the test set, and computing the means and standard deviations counts as "fitting"). ### 3.2) Plot the learning curves. Do they look better than earlier? ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 3 – Solution ### 3.1) When using Gradient Descent, it is usually best to ensure that the features all have a similar scale, preferably with a Normal distribution. Try to standardize the pixel values and see if this improves the performance of your neural network. ``` pixel_means = X_train.mean(axis = 0) pixel_stds = X_train.std(axis = 0) X_train_scaled = (X_train - pixel_means) / pixel_stds X_valid_scaled = (X_valid - pixel_means) / pixel_stds X_test_scaled = (X_test - pixel_means) / pixel_stds from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) X_valid_scaled = scaler.transform(X_valid.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) X_test_scaled = scaler.transform(X_test.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.Dense(300, activation="relu"), keras.layers.Dense(100, activation="relu"), keras.layers.Dense(10, activation="softmax") ]) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=20, validation_data=(X_valid_scaled, y_valid)) model.evaluate(X_test_scaled, y_test) ``` ### 3.2) Plot the learning curves. Do they look better than earlier? ``` plot_learning_curves(history) ``` ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 4 – Use Callbacks ### 4.1) The `fit()` method accepts a `callbacks` argument. Try training your model with a large number of epochs, a validation set, and with a few callbacks from `keras.callbacks`: * `TensorBoard`: specify a log directory. It should be a subdirectory of a root logdir, such as `./my_logs/run_1`, and it should be different every time you train your model. You can use a timestamp in the subdirectory's path to ensure that it changes at every run. * `EarlyStopping`: specify `patience=5` * `ModelCheckpoint`: specify the path of the checkpoint file to save (e.g., `"my_mnist_model.h5"`) and set `save_best_only=True` Notice that the `EarlyStopping` callback will interrupt training before it reaches the requested number of epochs. This reduces the risk of overfitting. ``` root_logdir = os.path.join(os.curdir, "my_logs") ``` ### 4.2) The Jupyter plugin for tensorboard was loaded at the beginning of this notebook (`%load_ext tensorboard.notebook`), so you can now simply start it by using the `%tensorboard` magic command. Explore the various tabs available, in particular the SCALARS tab to view learning curves, the GRAPHS tab to view the computation graph, and the PROFILE tab which is very useful to identify bottlenecks if you run into performance issues. ``` %tensorboard --logdir=./my_logs ``` ### 4.3) The early stopping callback only stopped training after 10 epochs without progress, so your model may already have started to overfit the training set. Fortunately, since the `ModelCheckpoint` callback only saved the best models (on the validation set), the last saved model is the best on the validation set, so try loading it using `keras.models.load_model()`. Finally evaluate it on the test set. ### 4.4) Look at the list of available callbacks at https://keras.io/callbacks/ ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 4 – Solution ### 4.1) The `fit()` method accepts a `callbacks` argument. Try training your model with a large number of epochs, a validation set, and with a few callbacks from `keras.callbacks`: * `TensorBoard`: specify a log directory. It should be a subdirectory of a root logdir, such as `./my_logs/run_1`, and it should be different every time you train your model. You can use a timestamp in the subdirectory's path to ensure that it changes at every run. * `EarlyStopping`: specify `patience=5` * `ModelCheckpoint`: specify the path of the checkpoint file to save (e.g., `"my_mnist_model.h5"`) and set `save_best_only=True` Notice that the `EarlyStopping` callback will interrupt training before it reaches the requested number of epochs. This reduces the risk of overfitting. ``` model = keras.models.Sequential([ keras.layers.Flatten(input_shape=[28, 28]), keras.layers.Dense(300, activation="relu"), keras.layers.Dense(100, activation="relu"), keras.layers.Dense(10, activation="softmax") ]) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) logdir = os.path.join(root_logdir, "run_{}".format(time.time())) callbacks = [ keras.callbacks.TensorBoard(logdir), keras.callbacks.EarlyStopping(patience=5), keras.callbacks.ModelCheckpoint("my_mnist_model.h5", save_best_only=True), ] history = model.fit(X_train_scaled, y_train, epochs=50, validation_data=(X_valid_scaled, y_valid), callbacks=callbacks) ``` ### 4.2) Done ### 4.3) The early stopping callback only stopped training after 10 epochs without progress, so your model may already have started to overfit the training set. Fortunately, since the `ModelCheckpoint` callback only saved the best models (on the validation set), the last saved model is the best on the validation set, so try loading it using `keras.models.load_model()`. Finally evaluate it on the test set. ``` model = keras.models.load_model("my_mnist_model.h5") model.evaluate(X_valid_scaled, y_valid) ``` ### 4.4) Look at the list of available callbacks at https://keras.io/callbacks/ ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 5 – A neural net for regression ### 5.1) Load the California housing dataset using `sklearn.datasets.fetch_california_housing`. This returns an object with a `DESCR` attribute describing the dataset, a `data` attribute with the input features, and a `target` attribute with the labels. The goal is to predict the price of houses in a district (a census block) given some stats about that district. This is a regression task (predicting values). ### 5.2) Split the dataset into a training set, a validation set and a test set using Scikit-Learn's `sklearn.model_selection.train_test_split()` function. ### 5.3) Scale the input features (e.g., using a `sklearn.preprocessing.StandardScaler`). Once again, don't forget that you should not fit the validation set or the test set, only the training set. ### 5.4) Now build, train and evaluate a neural network to tackle this problem. Then use it to make predictions on the test set. **Tips**: * Since you are predicting a single value per district (the median house price), there should only be one neuron in the output layer. * Usually for regression tasks you don't want to use any activation function in the output layer (in some cases you may want to use `"relu"` or `"softplus"` if you want to constrain the predicted values to be positive, or `"sigmoid"` or `"tanh"` if you want to constrain the predicted values to 0-1 or -1-1). * A good loss function for regression is generally the `"mean_squared_error"` (aka `"mse"`). When there are many outliers in your dataset, you may prefer to use the `"mean_absolute_error"` (aka `"mae"`), which is a bit less precise but less sensitive to outliers. ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 5 – Solution ### 5.1) Load the California housing dataset using `sklearn.datasets.fetch_california_housing`. This returns an object with a `DESCR` attribute describing the dataset, a `data` attribute with the input features, and a `target` attribute with the labels. The goal is to predict the price of houses in a district (a census block) given some stats about that district. This is a regression task (predicting values). ``` from sklearn.datasets import fetch_california_housing housing = fetch_california_housing() print(housing.DESCR) housing.data.shape housing.target.shape ``` ### 5.2) Split the dataset into a training set, a validation set and a test set using Scikit-Learn's `sklearn.model_selection.train_test_split()` function. ``` from sklearn.model_selection import train_test_split X_train_full, X_test, y_train_full, y_test = train_test_split(housing.data, housing.target, random_state=42) X_train, X_valid, y_train, y_valid = train_test_split(X_train_full, y_train_full, random_state=42) len(X_train), len(X_valid), len(X_test) ``` ### 5.3) Scale the input features (e.g., using a `sklearn.preprocessing.StandardScaler`). Once again, don't forget that you should not fit the validation set or the test set, only the training set. ``` from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_valid_scaled = scaler.transform(X_valid) X_test_scaled = scaler.transform(X_test) ``` ### 5.4) Now build, train and evaluate a neural network to tackle this problem. Then use it to make predictions on the test set. ``` model = keras.models.Sequential([ keras.layers.Dense(30, activation="relu", input_shape=X_train.shape[1:]), keras.layers.Dense(1) ]) model.compile(loss="mean_squared_error", optimizer="sgd") callbacks = [keras.callbacks.EarlyStopping(patience=10)] history = model.fit(X_train_scaled, y_train, validation_data=(X_valid_scaled, y_valid), epochs=100, callbacks=callbacks) model.evaluate(X_test_scaled, y_test) model.predict(X_test_scaled) plot_learning_curves(history) ``` ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 6 – Hyperparameter search ### 6.1) Try training your model multiple times, with different a learning rate each time (e.g., 1e-4, 3e-4, 1e-3, 3e-3, 3e-2), and compare the learning curves. For this, you need to create a `keras.optimizers.SGD` optimizer and specify the `learning_rate` in its constructor, then pass this `SGD` instance to the `compile()` method using the `optimizer` argument. ### 6.2) Let's look at a more sophisticated way to tune hyperparameters. Create a `build_model()` function that takes three arguments, `n_hidden`, `n_neurons`, `learning_rate`, and builds, compiles and returns a model with the given number of hidden layers, the given number of neurons and the given learning rate. It is good practice to give a reasonable default value to each argument. ### 6.3) Create a `keras.wrappers.scikit_learn.KerasRegressor` and pass the `build_model` function to the constructor. This gives you a Scikit-Learn compatible predictor. Try training it and using it to make predictions. Note that you can pass the `n_epochs`, `callbacks` and `validation_data` to the `fit()` method. ### 6.4) Use a `sklearn.model_selection.RandomizedSearchCV` to search the hyperparameter space of your `KerasRegressor`. **Tips**: * create a `param_distribs` dictionary where each key is the name of a hyperparameter you want to fine-tune (e.g., `"n_hidden"`), and each value is the list of values you want to explore (e.g., `[0, 1, 2, 3]`), or a Scipy distribution from `scipy.stats`. * You can use the reciprocal distribution for the learning rate (e.g, `reciprocal(3e-3, 3e-2)`). * Create a `RandomizedSearchCV`, passing the `KerasRegressor` and the `param_distribs` to its constructor, as well as the number of iterations (`n_iter`), and the number of cross-validation folds (`cv`). If you are short on time, you can set `n_iter=10` and `cv=3`. You may also want to set `verbose=2`. * Finally, call the `RandomizedSearchCV`'s `fit()` method on the training set. Once again you can pass it `n_epochs`, `validation_data` and `callbacks` if you want to. * The best parameters found will be available in the `best_params_` attribute, the best score will be in `best_score_`, and the best model will be in `best_estimator_`. ### 6.5) Evaluate the best model found on the test set. You can either use the best estimator's `score()` method, or get its underlying Keras model *via* its `model` attribute, and call this model's `evaluate()` method. Note that the estimator returns the negative mean square error (it's a score, not a loss, so higher is better). ### 6.6) Finally, save the best Keras model found. **Tip**: it is available via the best estimator's `model` attribute, and just need to call its `save()` method. **Tip**: while a randomized search is nice and simple, there are more powerful (but complex) options available out there for hyperparameter search, for example: * [Hyperopt](https://github.com/hyperopt/hyperopt) * [Hyperas](https://github.com/maxpumperla/hyperas) * [Sklearn-Deap](https://github.com/rsteca/sklearn-deap) * [Scikit-Optimize](https://scikit-optimize.github.io/) * [Spearmint](https://github.com/JasperSnoek/spearmint) * [PyMC3](https://docs.pymc.io/) * [GPFlow](https://gpflow.readthedocs.io/) * [Yelp/MOE](https://github.com/Yelp/MOE) * Commercial services such as: [Google Cloud ML Engine](https://cloud.google.com/ml-engine/docs/tensorflow/using-hyperparameter-tuning), [Arimo](https://arimo.com/) or [Oscar](http://oscar.calldesk.ai/) ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 6 – Solution ### 6.1) Try training your model multiple times, with different a learning rate each time (e.g., 1e-4, 3e-4, 1e-3, 3e-3, 3e-2), and compare the learning curves. For this, you need to create a `keras.optimizers.SGD` optimizer and specify the `learning_rate` in its constructor, then pass this `SGD` instance to the `compile()` method using the `optimizer` argument. ``` learning_rates = [1e-4, 3e-4, 1e-3, 3e-3, 1e-2, 3e-2] histories = [] for learning_rate in learning_rates: model = keras.models.Sequential([ keras.layers.Dense(30, activation="relu", input_shape=X_train.shape[1:]), keras.layers.Dense(1) ]) optimizer = keras.optimizers.SGD(learning_rate) model.compile(loss="mean_squared_error", optimizer=optimizer) callbacks = [keras.callbacks.EarlyStopping(patience=10)] history = model.fit(X_train_scaled, y_train, validation_data=(X_valid_scaled, y_valid), epochs=100, callbacks=callbacks) histories.append(history) for learning_rate, history in zip(learning_rates, histories): print("Learning rate:", learning_rate) plot_learning_curves(history) ``` ### 6.2) Let's look at a more sophisticated way to tune hyperparameters. Create a `build_model()` function that takes three arguments, `n_hidden`, `n_neurons`, `learning_rate`, and builds, compiles and returns a model with the given number of hidden layers, the given number of neurons and the given learning rate. It is good practice to give a reasonable default value to each argument. ``` def build_model(n_hidden=1, n_neurons=30, learning_rate=3e-3): model = keras.models.Sequential() options = {"input_shape": X_train.shape[1:]} for layer in range(n_hidden + 1): model.add(keras.layers.Dense(n_neurons, activation="relu", **options)) options = {} model.add(keras.layers.Dense(1, **options)) optimizer = keras.optimizers.SGD(learning_rate) model.compile(loss="mse", optimizer=optimizer) return model ``` ### 6.3) Create a `keras.wrappers.scikit_learn.KerasRegressor` and pass the `build_model` function to the constructor. This gives you a Scikit-Learn compatible predictor. Try training it and using it to make predictions. Note that you can pass the `n_epochs`, `callbacks` and `validation_data` to the `fit()` method. ``` keras_reg = keras.wrappers.scikit_learn.KerasRegressor(build_model) keras_reg.fit(X_train_scaled, y_train, epochs=100, validation_data=(X_valid_scaled, y_valid), callbacks=[keras.callbacks.EarlyStopping(patience=10)]) keras_reg.predict(X_test_scaled) ``` ### 6.4) Use a `sklearn.model_selection.RandomizedSearchCV` to search the hyperparameter space of your `KerasRegressor`. ``` from scipy.stats import reciprocal param_distribs = { "n_hidden": [0, 1, 2, 3], "n_neurons": np.arange(1, 100), "learning_rate": reciprocal(3e-4, 3e-2), } from sklearn.model_selection import RandomizedSearchCV rnd_search_cv = RandomizedSearchCV(keras_reg, param_distribs, n_iter=10, cv=3, verbose=2) rnd_search_cv.fit(X_train_scaled, y_train, epochs=100, validation_data=(X_valid_scaled, y_valid), callbacks=[keras.callbacks.EarlyStopping(patience=10)]) rnd_search_cv.best_params_ rnd_search_cv.best_score_ rnd_search_cv.best_estimator_ ``` ### 6.5) Evaluate the best model found on the test set. You can either use the best estimator's `score()` method, or get its underlying Keras model *via* its `model` attribute, and call this model's `evaluate()` method. Note that the estimator returns the negative mean square error (it's a score, not a loss, so higher is better). ``` rnd_search_cv.score(X_test_scaled, y_test) model = rnd_search_cv.best_estimator_.model model.evaluate(X_test_scaled, y_test) ``` ### 6.6) Finally, save the best Keras model found. **Tip**: it is available via the best estimator's `model` attribute, and just need to call its `save()` method. ``` model.save("my_fine_tuned_housing_model.h5") ``` ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 7 – The functional API Not all neural network models are simply sequential. Some may have complex topologies. Some may have multiple inputs and/or multiple outputs. For example, a Wide & Deep neural network (see [paper](https://ai.google/research/pubs/pub45413)) connects all or part of the inputs directly to the output layer, as shown on the following diagram: <img src="images/wide_and_deep_net.png" title="Wide and deep net" width=300 /> ### 7.1) Use Keras' functional API to implement a Wide & Deep network to tackle the California housing problem. **Tips**: * You need to create a `keras.layers.Input` layer to represent the inputs. Don't forget to specify the input `shape`. * Create the `Dense` layers, and connect them by using them like functions. For example, `hidden1 = keras.layers.Dense(30, activation="relu")(input)` and `hidden2 = keras.layers.Dense(30, activation="relu")(hidden1)` * Use the `keras.layers.concatenate()` function to concatenate the input layer and the second hidden layer's output. * Create a `keras.models.Model` and specify its `inputs` and `outputs` (e.g., `inputs=[input]`). * Then use this model just like a `Sequential` model: you need to compile it, display its summary, train it, evaluate it and use it to make predictions. ### 7.2) After the Sequential API and the Functional API, let's try the Subclassing API: * Create a subclass of the `keras.models.Model` class. * Create all the layers you need in the constructor (e.g., `self.hidden1 = keras.layers.Dense(...)`). * Use the layers to process the `input` in the `call()` method, and return the output. * Note that you do not need to create a `keras.layers.Input` in this case. * Also note that `self.output` is used by Keras, so you should use another name for the output layer (e.g., `self.output_layer`). **When should you use the Subclassing API?** * Both the Sequential API and the Functional API are declarative: you first declare the list of layers you need and how they are connected, and only then can you feed your model with actual data. The models that these APIs build are just static graphs of layers. This has many advantages (easy inspection, debugging, saving, loading, sharing, etc.), and they cover the vast majority of use cases, but if you need to build a very dynamic model (e.g., with loops or conditional branching), or if you want to experiment with new ideas using an imperative programming style, then the Subclassing API is for you. You can pretty much do any computation you want in the `call()` method, possibly with loops and conditions, using Keras layers of even low-level TensorFlow operations. * However, this extra flexibility comes at the cost of less transparency. Since the model is defined within the `call()` method, Keras cannot fully inspect it. All it sees is the list of model attributes (which include the layers you define in the constructor), so when you display the model summary you just see a list of unconnected layers. Consequently, you cannot save or load the model without writing extra code. So this API is best used only when you really need the extra flexibility. ``` class MyModel(keras.models.Model): def __init__(self): super(MyModel, self).__init__() # create layers here def call(self, input): # write any code here, using layers or even low-level TF code return output model = MyModel() ``` ### 7.3) Now suppose you want to send only features 0 to 4 directly to the output, and only features 2 to 7 through the hidden layers, as shown on the following diagram. Use the functional API to build, train and evaluate this model. **Tips**: * You need to create two `keras.layers.Input` (`input_A` and `input_B`) * Build the model using the functional API, as above, but when you build the `keras.models.Model`, remember to set `inputs=[input_A, input_B]` * When calling `fit()`, `evaluate()` and `predict()`, instead of passing `X_train_scaled`, pass `(X_train_scaled_A, X_train_scaled_B)` (two NumPy arrays containing only the appropriate features copied from `X_train_scaled`). <img src="images/multiple_inputs.png" title="Multiple inputs" width=300 /> ### 7.4) Build the multi-input and multi-output neural net represented in the following diagram. <img src="images/multiple_inputs_and_outputs.png" title="Multiple inputs and outputs" width=400 /> **Why?** There are many use cases in which having multiple outputs can be useful: * Your task may require multiple outputs, for example, you may want to locate and classify the main object in a picture. This is both a regression task (finding the coordinates of the object's center, as well as its width and height) and a classification task. * Similarly, you may have multiple independent tasks to perform based on the same data. Sure, you could train one neural network per task, but in many cases you will get better results on all tasks by training a single neural network with one output per task. This is because the neural network can learn features in the data that are useful across tasks. * Another use case is as a regularization technique (i.e., a training constraint whose objective is to reduce overfitting and thus improve the model's ability to generalize). For example, you may want to add some auxiliary outputs in a neural network architecture (as shown in the diagram) to ensure that that the underlying part of the network learns something useful on its own, without relying on the rest of the network. **Tips**: * Building the model is pretty straightforward using the functional API. Just make sure you specify both outputs when creating the `keras.models.Model`, for example `outputs=[output, aux_output]`. * Each output has its own loss function. In this scenario, they will be identical, so you can either specify `loss="mse"` (this loss will apply to both outputs) or `loss=["mse", "mse"]`, which does the same thing. * The final loss used to train the whole network is just a weighted sum of all loss functions. In this scenario, you want most to give a much smaller weight to the auxiliary output, so when compiling the model, you must specify `loss_weights=[0.9, 0.1]`. * When calling `fit()` or `evaluate()`, you need to pass the labels for all outputs. In this scenario the labels will be the same for the main output and for the auxiliary output, so make sure to pass `(y_train, y_train)` instead of `y_train`. * The `predict()` method will return both the main output and the auxiliary output. ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 7 – Solution ### 7.1) Use Keras' functional API to implement a Wide & Deep network to tackle the California housing problem. ``` input = keras.layers.Input(shape=X_train.shape[1:]) hidden1 = keras.layers.Dense(30, activation="relu")(input) hidden2 = keras.layers.Dense(30, activation="relu")(hidden1) concat = keras.layers.concatenate([input, hidden2]) output = keras.layers.Dense(1)(concat) model = keras.models.Model(inputs=[input], outputs=[output]) model.compile(loss="mean_squared_error", optimizer="sgd") model.summary() history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) model.evaluate(X_test_scaled, y_test) model.predict(X_test_scaled) ``` ### 7.2) After the Sequential API and the Functional API, let's try the Subclassing API: * Create a subclass of the `keras.models.Model` class. * Create all the layers you need in the constructor (e.g., `self.hidden1 = keras.layers.Dense(...)`). * Use the layers to process the `input` in the `call()` method, and return the output. * Note that you do not need to create a `keras.layers.Input` in this case. * Also note that `self.output` is used by Keras, so you should use another name for the output layer (e.g., `self.output_layer`). ``` class MyModel(keras.models.Model): def __init__(self): super(MyModel, self).__init__() self.hidden1 = keras.layers.Dense(30, activation="relu") self.hidden2 = keras.layers.Dense(30, activation="relu") self.output_ = keras.layers.Dense(1) def call(self, input): hidden1 = self.hidden1(input) hidden2 = self.hidden2(hidden1) concat = keras.layers.concatenate([input, hidden2]) output = self.output_(concat) return output model = MyModel() model.compile(loss="mse", optimizer="sgd") history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) model.summary() model.evaluate(X_test_scaled, y_test) model.predict(X_test_scaled) ``` ### 7.3) Now suppose you want to send only features 0 to 4 directly to the output, and only features 2 to 7 through the hidden layers, as shown on the diagram. Use the functional API to build, train and evaluate this model. ``` input_A = keras.layers.Input(shape=[5]) input_B = keras.layers.Input(shape=[6]) hidden1 = keras.layers.Dense(30, activation="relu")(input_B) hidden2 = keras.layers.Dense(30, activation="relu")(hidden1) concat = keras.layers.concatenate([input_A, hidden2]) output = keras.layers.Dense(1)(concat) model = keras.models.Model(inputs=[input_A, input_B], outputs=[output]) model.compile(loss="mean_squared_error", optimizer="sgd") model.summary() X_train_scaled_A = X_train_scaled[:, :5] X_train_scaled_B = X_train_scaled[:, 2:] X_valid_scaled_A = X_valid_scaled[:, :5] X_valid_scaled_B = X_valid_scaled[:, 2:] X_test_scaled_A = X_test_scaled[:, :5] X_test_scaled_B = X_test_scaled[:, 2:] history = model.fit([X_train_scaled_A, X_train_scaled_B], y_train, epochs=10, validation_data=([X_valid_scaled_A, X_valid_scaled_B], y_valid)) model.evaluate([X_test_scaled_A, X_test_scaled_B], y_test) model.predict([X_test_scaled_A, X_test_scaled_B]) ``` ### 7.4) Build the multi-input and multi-output neural net represented in the diagram. ``` input_A = keras.layers.Input(shape=X_train_scaled_A.shape[1:]) input_B = keras.layers.Input(shape=X_train_scaled_B.shape[1:]) hidden1 = keras.layers.Dense(30, activation="relu")(input_B) hidden2 = keras.layers.Dense(30, activation="relu")(hidden1) concat = keras.layers.concatenate([input_A, hidden2]) output = keras.layers.Dense(1)(concat) aux_output = keras.layers.Dense(1)(hidden2) model = keras.models.Model(inputs=[input_A, input_B], outputs=[output, aux_output]) model.compile(loss="mean_squared_error", loss_weights=[0.9, 0.1], optimizer="sgd") model.summary() history = model.fit([X_train_scaled_A, X_train_scaled_B], [y_train, y_train], epochs=10, validation_data=([X_valid_scaled_A, X_valid_scaled_B], [y_valid, y_valid])) model.evaluate([X_test_scaled_A, X_test_scaled_B], [y_test, y_test]) y_pred, y_pred_aux = model.predict([X_test_scaled_A, X_test_scaled_B]) y_pred y_pred_aux ``` ![Exercise](https://c1.staticflickr.com/9/8101/8553474140_c50cf08708_b.jpg) ## Exercise 8 – Deep Nets Let's go back to Fashion MNIST and build deep nets to tackle it. We need to load it, split it and scale it. ``` fashion_mnist = keras.datasets.fashion_mnist (X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data() X_valid, X_train = X_train_full[:5000], X_train_full[5000:] y_valid, y_train = y_train_full[:5000], y_train_full[5000:] from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) X_valid_scaled = scaler.transform(X_valid.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) X_test_scaled = scaler.transform(X_test.astype(np.float32).reshape(-1, 28 * 28)).reshape(-1, 28, 28) ``` ### 8.1) Build a sequential model with 20 hidden dense layers, with 100 neurons each, using the ReLU activation function, plus the output layer (10 neurons, softmax activation function). Try to train it for 10 epochs on Fashion MNIST and plot the learning curves. Notice that progress is very slow. ### 8.2) Update the model to add a `BatchNormalization` layer after every hidden layer. Notice that performance progresses much faster per epoch, although computations are much more intensive. Display the model summary and notice all the non-trainable parameters (the scale $\gamma$ and offset $\beta$ parameters). ### 8.3) Try moving the BN layers before the hidden layers' activation functions. Does this affect the model's performance? ### 8.4) Remove all the BN layers, and just use the SELU activation function instead (always use SELU with LeCun Normal weight initialization). Notice that you get better performance than with BN but training is much faster. Isn't it marvelous? :-) ### 8.5) Try training for 10 additional epochs, and notice that the model starts overfitting. Try adding a Dropout layer (with a 50% dropout rate) just before the output layer. Does it reduce overfitting? What about the final validation accuracy? **Warning**: you should not use regular Dropout, as it breaks the self-normalizing property of the SELU activation function. Instead, use AlphaDropout, which is designed to work with SELU. ![Exercise solution](https://camo.githubusercontent.com/250388fde3fac9135ead9471733ee28e049f7a37/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f302f30362f46696c6f735f736567756e646f5f6c6f676f5f253238666c69707065642532392e6a7067) ## Exercise 8 – Solution ### 8.1) Build a sequential model with 20 hidden dense layers, with 100 neurons each, using the ReLU activation function, plus the output layer (10 neurons, softmax activation function). Try to train it for 10 epochs on Fashion MNIST and plot the learning curves. Notice that progress is very slow. ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) for _ in range(20): model.add(keras.layers.Dense(100, activation="relu")) model.add(keras.layers.Dense(10, activation="softmax")) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) ``` ### 8.2) Update the model to add a `BatchNormalization` layer after every hidden layer. Notice that performance progresses much faster per epoch, although computations are much more intensive. Display the model summary and notice all the non-trainable parameters (the scale $\gamma$ and offset $\beta$ parameters). ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) for _ in range(20): model.add(keras.layers.Dense(100, activation="relu")) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dense(10, activation="softmax")) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) model.summary() ``` ### 8.3) Try moving the BN layers before the hidden layers' activation functions. Does this affect the model's performance? ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) for _ in range(20): model.add(keras.layers.Dense(100)) model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Activation("relu")) model.add(keras.layers.Dense(10, activation="softmax")) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) ``` ### 8.4) Remove all the BN layers, and just use the SELU activation function instead (always use SELU with LeCun Normal weight initialization). Notice that you get better performance than with BN but training is much faster. Isn't it marvelous? :-) ``` model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) for _ in range(20): model.add(keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal")) model.add(keras.layers.Dense(10, activation="softmax")) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) ``` ### 8.5) Try training for 10 additional epochs, and notice that the model starts overfitting. Try adding a Dropout layer (with a 50% dropout rate) just before the output layer. Does it reduce overfitting? What about the final validation accuracy? ``` history = model.fit(X_train_scaled, y_train, epochs=10, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) model = keras.models.Sequential() model.add(keras.layers.Flatten(input_shape=[28, 28])) for _ in range(20): model.add(keras.layers.Dense(100, activation="selu", kernel_initializer="lecun_normal")) model.add(keras.layers.AlphaDropout(rate=0.5)) model.add(keras.layers.Dense(10, activation="softmax")) model.compile(loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"]) history = model.fit(X_train_scaled, y_train, epochs=20, validation_data=(X_valid_scaled, y_valid)) plot_learning_curves(history) ```
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` # Numerical Integration The definite integral $\int_a^b f(x) dx$ can be computed exactly if the primitive $F$ of $f$ is known, e.g. ``` f = lambda x: np.divide(np.dot(x,np.exp(x)),np.power(x+1,2)) F = lambda x: np.divide(np.exp(x),(x+1)) a = 0; b = 1; I_ex = F(b) - F(a) I_ex ``` In many cases the primitive is unknown though and one has to resort to numerical integration. The idea is to approximate the integrand by a function whose integral is known, e.g. piecewise linear interpolation. - [Riemans Rule](https://www.math.ubc.ca/~pwalls/math-python/integration/riemann-sums/): sum of rectangles - [Trapezoid Rule](https://www.math.ubc.ca/~pwalls/math-python/integration/trapezoid-rule/): sum of trapezoids or piecewise quadratic interpolation - [Simpson Rule](https://www.math.ubc.ca/~pwalls/math-python/integration/simpsons-rule/): quadratic polynomial on each subinterval Trapezoids: The definite integral of $f(x)$ is equal to the (net) area under the curve $y=f(x)$ over the interval $[a,b]$. Riemann sums approximate definite integrals by using sums of rectangles to approximate the area. The trapezoid rule gives a better approximation of a definite integral by summing the areas of the trapezoids connecting the points $$(x_{i-1},0),(x_i,0),(x_{i-1},f(x_{i-1})),(x_i,f(x_1))$$ for each subinterval $[x_{i-1},x_i]$ of a partition. Note that the area of each trapezoid is the sum of a rectangle and a triangle $$(x_i-x_{i-1})f(x_{i-1}+\frac{1}{2}(x_i-x_{i-1})(f(x_i)-f(x_{i-1}))=\frac{1}{2}(f(x_i)+f(x_{i-1}))(x_i-x_{i-1})$$ For example, we can use a single trapezoid to approximate: $$\int_0^1=e^{-x^2}dx$$ First, let's plot the curve $y=e^{-x^2}$ and the trapezoid on the interval $[0,1]$: ``` x = np.linspace(-0.5,1.5,100) y = np.exp(-x**2) plt.plot(x,y) x0 = 0; x1 = 1; y0 = np.exp(-x0**2); y1 = np.exp(-x1**2); plt.fill_between([x0,x1],[y0,y1]) plt.xlim([-0.5,1.5]); plt.ylim([0,1.5]); plt.show() ``` Approximate the integral by the area of the trapezoid: ``` A = 0.5*(y1 + y0)*(x1 - x0) print("Trapezoid area:", A) ``` ## Trapezoid Rule This choice leads to the trapezoidal rule. If the interval $[a,b]$ is divided into subintervals $[x_k, x_{k+1}]$ of the same length $h = (b-a)/n$, with $x_0 := a$ and $x_n := b$, the summed version reads $$\int_a^b f(x) dx \approx \frac{h}{2}(f(a) + f(b)) + h \sum_{k=1}^{n-1} f(x_k) =: T(h). $$ This is implemented in `trapez`. The error of the numerical integral is $$\left| T(h) - \int_a^b f(x) dx \right| = \frac{(b-a)h^2}{12} |f''(\xi)|, \quad \xi\in[a,b]$$ so if the number of intervals is doubled (and hence is halved) then the error is expected to decrease by a factor of 4. Let's check: Let's write a function called trapz which takes input parameters $f,a,b$ and $N$ and returns the approximation $T_N(f)$. Furthermore, let's assign default value $N=50$. ([source](https://www.math.ubc.ca/~pwalls/math-python/integration/trapezoid-rule/)) ``` def trapz(f,a,b,N=50): '''Approximate the integral of f(x) from a to b by the trapezoid rule. The trapezoid rule approximates the integral \int_a^b f(x) dx by the sum: (dx/2) \sum_{k=1}^N (f(x_k) + f(x_{k-1})) where x_k = a + k*dx and dx = (b - a)/N. Parameters ---------- f : function Vectorized function of a single variable a , b : numbers Interval of integration [a,b] N : integer Number of subintervals of [a,b] Returns ------- float Approximation of the integral of f(x) from a to b using the trapezoid rule with N subintervals of equal length. Examples -------- >>> trapz(np.sin,0,np.pi/2,1000) 0.9999997943832332 ''' x = np.linspace(a,b,N+1) # N+1 points make N subintervals y = f(x) y_right = y[1:] # right endpoints y_left = y[:-1] # left endpoints dx = (b - a)/N T = (dx/2) * np.sum(y_right + y_left) return T ``` Let's test our function on an integral where we know the answer $$\int_0^1 3x^2 dx=1$$ ``` trapz(lambda x : 3*x**2,0,1,10000) ``` The SciPy subpackage `scipy.integrate` contains several functions for approximating definite integrals and numerically solving differential equations. Let's import the subpackage under the name `spi`. ``` import scipy.integrate as spi ``` The function scipy.integrate.trapz computes the approximation of a definite by the trapezoid rule. Consulting the documentation, we see that all we need to do it supply arrays of $x$ and $y$ values for the integrand and `scipy.integrate.trapz` returns the approximation of the integral using the trapezoid rule. The number of points we give to `scipy.integrate.trapz` is up to us but we have to remember that more points gives a better approximation but it takes more time to compute! ``` N = 10000; a = 0; b = 1; x = np.linspace(a,b,N+1) y = 3*x**2 approximation = spi.trapz(y,x) print(approximation) ``` ## Simpson Rule Simpson's rule uses a quadratic polynomial on each subinterval of a partition to approximate the function $f(x)$ and to compute the definite integral. This is an improvement over the trapezoid rule which approximates $f(x)$ by a straight line on each subinterval of a partition. Here $[a,b]$ is divided into an even number $2n$ of intervals, so $h=(b-a)/(2n)$. The formula for Simpson's rule is $$\int_a^b f(x) dx \approx \frac{h}{3} \left( f(a) + f(b) + 4 \sum_{k=1}^{n} f(x_{2k-1}) + 2 \sum_{k=1}^{n-1} f(x_{2k}) \right) =: S(h). $$ The error goes like $h^4$ (instead of $h^2$ for the trapezoidal rule): $$\left| S(h) - \int_a^b f(x) dx \right| = \frac{(b-a)h^4}{180} |f^{(4)}(\xi)|, \quad \xi\in[a,b].$$ So when the number of intervals is doubled, the error should decrease by a factor of 16: Let's write a function called simps which takes input parameters $f,a,b$ and $N$ and returns the approximation $S_N(f)$. Furthermore, let's assign a default value $N=50$. ``` def simps(f,a,b,N=50): '''Approximate the integral of f(x) from a to b by Simpson's rule. Simpson's rule approximates the integral \int_a^b f(x) dx by the sum: (dx/3) \sum_{k=1}^{N/2} (f(x_{2i-2} + 4f(x_{2i-1}) + f(x_{2i})) where x_i = a + i*dx and dx = (b - a)/N. Parameters ---------- f : function Vectorized function of a single variable a , b : numbers Interval of integration [a,b] N : (even) integer Number of subintervals of [a,b] Returns ------- float Approximation of the integral of f(x) from a to b using Simpson's rule with N subintervals of equal length. Examples -------- >>> simps(lambda x : 3*x**2,0,1,10) 1.0 ''' if N % 2 == 1: raise ValueError("N must be an even integer.") dx = (b-a)/N x = np.linspace(a,b,N+1) y = f(x) S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2]) return S ``` Let's test our function on an integral where we know the answer $$\int_0^1 3x^2 dx=1$$ ``` simps(lambda x : 3*x**2,0,1,10) ``` The SciPy subpackage `scipy.integrate` contains several functions for approximating definite integrals and numerically solving differential equations. Let's import the subpackage under the name spi. ``` import scipy.integrate as spi ``` The function `scipy.integrate.simps` computes the approximation of a definite integral by Simpson's rule. Consulting the documentation, we see that all we need to do it supply arrays of $x$ and $y$ values for the integrand and `scipy.integrate.simps` returns the approximation of the integral using Simpson's rule. ``` N = 10; a = 0; b = 1; x = np.linspace(a,b,N+1) y = 3*x**2 approximation = spi.simps(y,x) print(approximation) ```
github_jupyter
# 012_importing_datasets [Source](https://github.com/iArunava/Python-TheNoTheoryGuide/) ``` # Required Imports import pandas as pd import sklearn as sk import sqlite3 from pandas.io import sql # Importing CSV files from local directory # NOTE: Make sure the Path you use contains the dataset named 'whereisthatdataset.csv' df1 = pd.read_csv ('./assets/whereisthatdataset.csv') # Using relative path df2 = pd.read_csv ('/home/arunava/Datasets/whereisthatdataset.csv') # Using absolute path df1.head(3) # If a dataset comes without headers then you need to pass `headers=None` # Note: This Dataset comes with headers, # specifying `headers=None` leads python to treat the first row as part of the dataset df1 = pd.read_csv ('./assets/whereisthatdataset.csv', header=None) df1.head(3) # Specify header names while importing datasets with (or without) headers df1 = pd.read_csv ('./assets/whereisthatdataset.csv', header=None, names=['Where', 'on', 'earth', 'did', 'you', 'got', 'this', 'dataset', 'of', 'Pigeons', 'racing']) df1.head(3) # Importing file from URL df1 = pd.read_csv('https://raw.githubusercontent.com/iArunava/Python-TheNoTheoryGuide/master/assets/whereisthatdataset.csv') df1.head(3) # Reading Data from text file # NOTE: Use `sep` to specify how your data is seperated df1 = pd.read_table ('./assets/whereisthatdataset.txt', sep=',') df2 = pd.read_csv ('./assets/whereisthatdataset.txt', sep=',') df1.head(3) # Read excel file # NOTE: you need 'xlrd' module to read .xls files df1 = pd.read_excel ('./assets/whereisthatdataset.xls', sheetname='whereisthatdataset', skiprows=1) df1.head(3) # Read SAS file df1 = pd.read_sas ('./assets/whereisthatdataset.sas7bdat') df1.head(3) # Read SQL Table conn = sqlite3.connect ('./assets/whereisthatdataset.db') query = 'SELECT * FROM whereisthattable;' df1 = pd.read_sql(query, con=conn) df1.head(3) # Read sample rows and columns # nrows: Number of rows to select # usecols: list of cols to use (either all string or unicode) sdf1 = pd.read_csv ('./assets/whereisthatdataset.csv', nrows=4, usecols=[1, 5, 7]) sdf2 = pd.read_csv ('./assets/whereisthatdataset.csv', nrows=4, usecols=['Breeder', 'Sex', 'Arrival']) sdf1 # Skip rows while importing # NOTE: If you don't set header=None, pandas will treat the first row of all the rows to be considered as the header row df1 = pd.read_csv ('./assets/whereisthatdataset.csv', header=None, skiprows=5) df1.head(3) # Specify Missing Values # na_values: pass a list, which if present in the dataset will be considered as missing values df1 = pd.read_csv ('./assets/whereisthatdataset.csv', na_values=['NaN']) df1.head(3) ```
github_jupyter
``` # install composer, hiding output to keep the notebook clean ! pip install mosaicml > /dev/null 2>&1 ``` # Using the Functional API In this tutorial, we'll see an example of using Composer's algorithms in a standalone fashion with no changes to the surrounding code and no requirement to use the Composer trainer. We'll be training a simple model on CIFAR-10, similar to the [PyTorch classifier tutorial](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html). Because we'll be using a toy model trained for only a few epochs, we won't get the same speed or accuracy gains we might expect from a more realistic problem. However, this notebook should still serve as a useful illustration of how to use various algorithms. For examples of more realistic results, see the MosaicML [Explorer](https://app.mosaicml.com/explorer/imagenet). First, we need to define our original model, dataloader, and training loop. Let's start with the dataloader: ``` import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as transforms datadir = './data' batch_size = 1024 transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ] ) trainset = torchvision.datasets.CIFAR10(root=datadir, train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=datadir, train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2) ``` As you can see, we compose two transforms, one which transforms the images to tensors and another that normalizes them. We apply these transformations to both the train and test sets. Now, let's define our model. We're going to use a toy convolutional neural network so that the training epochs finish quickly. ``` class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 16, kernel_size=(3, 3), stride=2) self.conv2 = nn.Conv2d(16, 32, kernel_size=(3, 3)) self.norm = nn.BatchNorm2d(32) self.pool = nn.AdaptiveAvgPool2d(1) self.fc1 = nn.Linear(32, 128) self.fc2 = nn.Linear(128, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = self.conv2(x) x = F.relu(self.norm(x)) x = torch.flatten(self.pool(x), 1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x ``` Finally, let's write a simple training loop that prints the accuracy on the test set at the end of each epoch. We'll just run a few epochs for brevity. ``` from tqdm.notebook import tqdm import composer.functional as cf num_epochs = 5 def train_and_eval(model, train_loader, test_loader): torch.manual_seed(42) device = 'cuda' if torch.cuda.is_available() else 'cpu' model = model.to(device) opt = torch.optim.Adam(model.parameters()) for epoch in range(num_epochs): print(f"---- Beginning epoch {epoch} ----") model.train() progress_bar = tqdm(train_loader) for X, y in progress_bar: X = X.to(device) y_hat = model(X).to(device) loss = F.cross_entropy(y_hat, y) progress_bar.set_postfix_str(f"train loss: {loss.detach().numpy():.4f}") loss.backward() opt.step() opt.zero_grad() model.eval() num_right = 0 eval_size = 0 for X, y in test_loader: y_hat = model(X.to(device)).to(device) num_right += (y_hat.argmax(dim=1) == y).sum().numpy() eval_size += len(y) acc_percent = 100 * num_right / eval_size print(f"Epoch {epoch} validation accuracy: {acc_percent:.2f}%") ``` Great. Now, let's instantiate this baseline model and see how it fares on our dataset. ``` model = Net() train_and_eval(model, trainloader, testloader) ``` Now that we have this baseline, let's add algorithms to improve our data pipeline and model. We'll start by adding some data augmentation, accessed via `cf.colout_batch`. ``` # create dataloaders for the train and test sets shared_transforms = [ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ] train_transforms = shared_transforms[:] + [cf.colout_batch] test_transform = transforms.Compose(shared_transforms) train_transform = transforms.Compose(train_transforms) trainset = torchvision.datasets.CIFAR10(root=datadir, train=True, download=True, transform=train_transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root=datadir, train=False, download=True, transform=test_transform) testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size, shuffle=False, num_workers=2) ``` Let's see how our model does with just these changes. ``` model = Net() # only use one data augmentation since our small model runs quickly # and allows the dataloader little time to do anything fancy train_and_eval(model, trainloader, testloader) ``` As we might expect, adding data augmentation doesn't help us when we aren't training long enough to start overfitting. Let's try using some algorithms that modify the model. We're going to keep things simple and just add a [Squeeze-and-Excitation](https://docs.mosaicml.com/en/latest/method_cards/squeeze_excite.html) module after the larger of the two conv2d operations in our model. ``` # squeeze-excite can add a lot of overhead for small # conv2d operations, so only add it after convs with a # minimum number of channels cf.apply_squeeze_excite(model, latent_channels=64, min_channels=16) ``` Now let's see how our model does with the above algorithm applied. ``` train_and_eval(model, trainloader, testloader) ``` Adding squeeze-excite gives us another few percentage points of accuracy and does so with little decrease in the number of iterations per second. Great! Of course, this is a toy model and dataset, but it serves to illustrate how to use Composer's algorithms inside your own training loops, with minimal changes to your code. If you hit any problems or have questions, feel free to [open an issue](https://github.com/mosaicml/composer/issues/new/) or reach out to us [on Slack](https://join.slack.com/t/mosaicml-community/shared_invite/zt-w0tiddn9-WGTlRpfjcO9J5jyrMub1dg).
github_jupyter
``` # default_exp distributed #export from fastai.basics import * from fastai.callback.progress import ProgressCallback from torch.nn.parallel import DistributedDataParallel, DataParallel from fastai.data.load import _FakeLoader ``` # Distributed and parallel training > Callbacks and helper functions to train in parallel or use distributed training ## Parallel Patch the parallel models so they work with RNNs ``` #export @patch def reset(self: DataParallel): if hasattr(self.module, 'reset'): self.module.reset() #export @log_args class ParallelTrainer(Callback): run_after,run_before = TrainEvalCallback,Recorder def __init__(self, device_ids): self.device_ids = device_ids def before_fit(self): self.learn.model = DataParallel(self.learn.model, device_ids=self.device_ids) def after_fit(self): self.learn.model = self.learn.model.module #export @patch def to_parallel(self: Learner, device_ids=None): self.add_cb(ParallelTrainer(device_ids)) return self #export @patch def detach_parallel(self: Learner): "Remove ParallelTrainer callback from Learner." self.remove_cb(ParallelTrainer) return self #export @patch @contextmanager def parallel_ctx(self: Learner, device_ids=None): "A context manager to adapt a learner to train in data parallel mode." try: self.to_parallel(device_ids) yield self finally: self.detach_parallel() ``` ## Distributed Patch the parallel models so they work with RNNs ``` #export @patch def reset(self: DistributedDataParallel): if hasattr(self.module, 'reset'): self.module.reset() ``` Convenience functions to set up/tear down torch distributed data parallel mode. ``` #export def setup_distrib(gpu=None): if gpu is None: return gpu gpu = int(gpu) torch.cuda.set_device(int(gpu)) if num_distrib() > 1: torch.distributed.init_process_group(backend='nccl', init_method='env://') return gpu #export def teardown_distrib(): if torch.distributed.is_initialized(): torch.distributed.destroy_process_group() ``` ### DataLoader We need to change the dataloaders so that they only get one part of the batch each (otherwise there is no point in using distributed training). ``` #export @log_args(but_as=TfmdDL.__init__) class DistributedDL(TfmdDL): _round_to_multiple=lambda number,multiple:int(math.ceil(number/multiple)*multiple) def _broadcast(self,t,rank): "Broadcasts t from rank `rank` to all other ranks. Returns t so t is same for all ranks after call." t = LongTensor(t).cuda() # nccl only works with cuda tensors torch.distributed.broadcast(t,rank) return t.cpu().tolist() def __len__(self): return DistributedDL._round_to_multiple(len(self.dl),self.world_size)//self.world_size def get_idxs(self): idxs = self.dl.get_idxs() # compute get_idxs in all ranks (we'll only use rank 0 but size must be consistent) idxs = self._broadcast(idxs,0) # broadcast and receive it from rank 0 to all n_idxs = len(idxs) # add extra samples to make it evenly divisible idxs += idxs[:(DistributedDL._round_to_multiple(n_idxs,self.world_size)-n_idxs)] # subsample return idxs[self.rank::self.world_size] def sample(self): # this gets executed in fake_l context (e.g. subprocesses) so we cannot call self.get_idxs() here return (b for i,b in enumerate(self._idxs) if i//(self.bs or 1)%self.nw==self.offs) def before_iter(self): self.dl.before_iter() self._idxs = self.get_idxs() def randomize(self): self.dl.randomize() def after_batch(self,b): return self.dl.after_batch(b) def after_iter(self): self.dl.after_iter() def create_batches(self,samps): return self.dl.create_batches(samps) def __init__(self,dl,rank,world_size): store_attr('dl,rank,world_size') self.bs,self.device,self.drop_last,self.dataset = dl.bs,dl.device,dl.drop_last,dl.dataset self.fake_l = _FakeLoader(self, dl.fake_l.pin_memory, dl.fake_l.num_workers, dl.fake_l.timeout) _tmp_file = tempfile.NamedTemporaryFile().name # i tried putting this inside self / _broadcast to no avail # patch _broadcast with a mocked version so we can test DistributedDL w/o a proper DDP setup @patch def _broadcast(self:DistributedDL,t,rank): t = LongTensor(t) if rank == self.rank: torch.save(t,_tmp_file) else: t.data = torch.load(_tmp_file) return t.tolist() dl = TfmdDL(list(range(50)), bs=16, num_workers=2) for i in range(4): dl1 = DistributedDL(dl, i, 4) test_eq(list(dl1)[0], torch.arange(i, 52, 4)%50) dl = TfmdDL(list(range(50)), bs=16, num_workers=2, shuffle=True) res = [] for i in range(4): dl1 = DistributedDL(dl, i, 4) res += list(dl1)[0].tolist() #All items should be sampled (we cannot test order b/c shuffle=True) test_eq(np.unique(res), np.arange(50)) from fastai.callback.data import WeightedDL dl = WeightedDL(list(range(50)), bs=16, num_workers=2, shuffle=True,wgts=list(np.arange(50)>=25)) res = [] for i in range(4): dl1 = DistributedDL(dl, i, 4) res += list(dl1)[0].tolist() test(res,[25]*len(res),operator.ge) # all res >=25 test(res,[25]*len(res),lambda a,b: ~(a<b)) # all res NOT < 25 #export @log_args class DistributedTrainer(Callback): run_after,run_before = TrainEvalCallback,Recorder fup = None # for `find_unused_parameters` in DistributedDataParallel() def __init__(self, cuda_id=0,sync_bn=True): store_attr('cuda_id,sync_bn') def before_fit(self): opt_kwargs = { 'find_unused_parameters' : DistributedTrainer.fup } if DistributedTrainer.fup is not None else {} self.learn.model = DistributedDataParallel( nn.SyncBatchNorm.convert_sync_batchnorm(self.model) if self.sync_bn else self.model, device_ids=[self.cuda_id], output_device=self.cuda_id, **opt_kwargs) self.old_dls = list(self.dls) self.learn.dls.loaders = [self._wrap_dl(dl) for dl in self.dls] if rank_distrib() > 0: self.learn.logger=noop def _wrap_dl(self, dl): return dl if isinstance(dl, DistributedDL) else DistributedDL(dl, rank_distrib(), num_distrib()) def before_train(self): self.learn.dl = self._wrap_dl(self.learn.dl) def before_validate(self): self.learn.dl = self._wrap_dl(self.learn.dl) def after_fit(self): self.learn.model = self.learn.model.module self.learn.dls.loaders = self.old_dls ``` Attach, remove a callback which adapts the model to use DistributedDL to train in distributed data parallel mode. ``` #export @patch def to_distributed(self: Learner, cuda_id,sync_bn=True): self.add_cb(DistributedTrainer(cuda_id,sync_bn)) if rank_distrib() > 0: self.remove_cb(ProgressCallback) return self #export @patch def detach_distributed(self: Learner): if num_distrib() <=1: return self self.remove_cb(DistributedTrainer) if rank_distrib() > 0 and not hasattr(self, 'progress'): self.add_cb(ProgressCallback()) return self #export @patch @contextmanager def distrib_ctx(self: Learner, cuda_id=None,sync_bn=True): "A context manager to adapt a learner to train in distributed data parallel mode." # Figure out the GPU to use from rank. Create a dpg if none exists yet. if cuda_id is None: cuda_id = rank_distrib() if not torch.distributed.is_initialized(): setup_distrib(cuda_id) cleanup_dpg = torch.distributed.is_initialized() else: cleanup_dpg = False # Adapt self to DistributedDataParallel, yield, and cleanup afterwards. try: if num_distrib() > 1: self.to_distributed(cuda_id,sync_bn) yield self finally: self.detach_distributed() if cleanup_dpg: teardown_distrib() ``` ### `distrib_ctx` context manager **`distrib_ctx(cuda_id)`** prepares a learner to train in distributed data parallel mode. It assumes these [environment variables](https://pytorch.org/tutorials/intermediate/dist_tuto.html#initialization-methods) have all been setup properly, such as those launched by [`python -m fastai.launch`](https://github.com/fastai/fastai/blob/master/fastai/launch.py). #### Typical usage: ``` with learn.distrib_ctx(): learn.fit(.....) ``` It attaches a `DistributedTrainer` callback and `DistributedDL` data loader to the learner, then executes `learn.fit(.....)`. Upon exiting the context, it removes the `DistributedTrainer` and `DistributedDL`, and destroys any locally created distributed process group. The process is still attached to the GPU though. ``` #export def rank0_first(func): "Execute `func` in the Rank-0 process first, then in other ranks in parallel." dummy_l = Learner(DataLoaders(device='cpu'), nn.Linear(1,1), loss_func=lambda: 0) with dummy_l.distrib_ctx(): if rank_distrib() == 0: res = func() distrib_barrier() if rank_distrib() != 0: res = func() return res ``` **`rank0_first(f)`** calls `f()` in rank-0 process first, then in parallel on the rest, in distributed training mode. In single process, non-distributed training mode, `f()` is called only once as expected. One application of `rank0_first()` is to make fresh downloads via `untar_data()` safe in distributed training scripts launched by `python -m fastai.launch <script>`: > <code>path = untar_data(URLs.IMDB)</code> becomes: > <code>path = <b>rank0_first(lambda:</b> untar_data(URLs.IMDB))</code> Some learner factory methods may use `untar_data()` to **download pretrained models** by default: > <code>learn = text_classifier_learner(dls, AWD_LSTM, drop_mult=0.5, metrics=accuracy)</code> becomes: > <code>learn = <b>rank0_first(lambda:</b> text_classifier_learner(dls, AWD_LSTM, drop_mult=0.5, metrics=accuracy))</code> Otherwise, multiple processes will download at the same time and corrupt the data. ``` #hide from nbdev.export import notebook2script notebook2script() ```
github_jupyter
# Description for Modules pandas-> read our csv files numpy-> convert the data to suitable form to feed into the classification data seaborn and matplotlib-> For visualizations sklearn-> To use logistic regression ``` import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt % matplotlib inline from google.colab import files uploaded = files.upload() from sklearn.linear_model import LogisticRegression ``` # Reading the "diabetes.csv" # The following features have been provided to help us predict whether a person is diabetic or not: * **Pregnancies**: Number of times pregnant * **Glucose**: Plasma glucose concentration over 2 hours in an oral glucose tolerance test * **BloodPressure**: Diastolic blood pressure (mm Hg) * **SkinThickness**: Triceps skin fold thickness (mm) * **Insulin**: 2-Hour serum insulin (mu U/ml) * **BMI**: Body mass index (weight in kg/(height in m)2) * **DiabetesPedigreeFunction**: Diabetes pedigree function (a function which scores likelihood of diabetes based on family history) * **Age**: Age (years) * **Outcome**: Class variable (0 if non-diabetic, 1 if diabetic) ``` diabetes_df = pd.read_csv("diabetes.csv") diabetes_df.head(15) diabetes_df.info() ``` In the above data, you can see that there are many missing values in * **Insulin** * **skin thickness** * **blood pressure** We could replace the missing values with the mean of the respective features ``` corr = diabetes_df.corr() print(corr) sns.heatmap(corr, xticklabels = corr.columns, yticklabels = corr.columns, vmin = 0, vmax = 0.5) ``` In the above heatmap, brighter colours indicate more correlation. > **Glucose**, **# of pregnancies**, **BMI** and **age** have significant correlation with **outcome** variable. > Other correlation like **age**->**pregnancies**, **BMI**-> **skin thickness**, **Insulin**-> **skin thickness** ``` outcome = diabetes_df["Outcome"] outcome.head() sns.set_theme(style = "darkgrid", palette = "deep") sns.countplot(x = 'Outcome', data = diabetes_df) ``` ``` sns.set_theme(style = "darkgrid", palette = "deep") sns.barplot(x = 'Outcome', y = "Age", data = diabetes_df, saturation = 1.6) ``` # Data Preparation splitting the data into: * **Training Data** * **Test Data** * **Check Data** ``` dfTrain = diabetes_df[:650] dfTest = diabetes_df[650:750] dfcheck = diabetes_df[750:] ``` **Separating label and features for both training and testing** ``` trainLabel = np.asarray(dfTrain['Outcome']) trainData = np.asarray(dfTrain.drop("Outcome", 1)) testLabel = np.asarray(dfTest['Outcome']) testData = np.asarray(dfTest.drop("Outcome", 1)) means = np.mean(trainData, axis = 0) stds = np.std(trainData, axis = 0) trainData = (trainData - means) / stds testData = (testData - means) / stds diabetesCheck = LogisticRegression() diabetesCheck.fit(trainData, trainLabel) accuracy = diabetesCheck.score(testData, testLabel) print("accuracy = ", accuracy * 100, "%") ```
github_jupyter
# sports-book-manager ## Example 1: ### Using the BookScraper class Importing the scraper class and setting the domain and directory paths. ``` import sports_book_manager.book_scrape_class as bs PointsBet = bs.BookScraper(domain=r'https://nj.pointsbet.com/sports', directories={'NHL':r'/ice-hockey/NHL', 'NBA':r'/basketball/NBA' } ) ``` Setting the element values for the scraper. Lines and Odds data are contained in a class that other data is stored in as well, so parent values need to be set for them. driver_path is needed only if Selenium cannot find the chromedriver using webdriver.Chrome(). ``` PointsBet.update_html_elements(driver_path=..., ancestor_container='.facf5sk', event_row=".f1oyvxkl", team_class='.fji5frh.fr8jv7a.f1wtz5iq', line_class='.fsu5r7i', line_parent_tag='button', line_parent_attr='data-test', line_parent_val='Market0OddsButton', odds_class='.fheif50', odds_parent_tag='button', odds_parent_attr='data-test', odds_parent_val='Market0OddsButton') ``` Retrieving the PointsBet odds in a pandas dataframe. ``` data = PointsBet.retrieve_sports_book('NBA') data ``` ## Example 2: ### Using sports-book-manager functions to compare sports book wagers to model outputs First we will pull an example of hockey wagers from the data folder in the sports-book-wager package. ``` from os import path import sports_book_manager import pandas as pd data_path = path.join(path.abspath(sports_book_manager.__file__), '..', 'data') df = pd.read_csv(f'{data_path}\\hockey_odds.csv') df ``` For implied_probability_calculator and model_probability to work the values must be numeric. This is a good practice to follow as we don't what data type the scraper will set the data to. ``` df['Odds'] = pd.to_numeric(df['Odds']) df['Lines'] = pd.to_numeric(df['Lines']) ``` Using pandas lambda function we can perform the implied_probability_calculator function to every row to create a new column. ``` import sports_book_manager.implied_probability_calculator as ipc df['implied_probability'] = df.apply(lambda x: ipc.implied_probability_calculator(x['Odds']), axis = 1) df ``` Getting an example of model outputs from the data folder in the sports-book-wager package and merging the two dataframes together. ``` model = pd.read_csv(f'{data_path}\\model_output_example.csv') df_join = df.join(model, lsuffix='Teams', rsuffix='team') df_join = df_join.drop(columns=['team']) ``` We use the lambda function again to perform the model_probability calculations which evaluate the model's expected probability of a team winning at the margin set with the market line. ``` import sports_book_manager.model_probability as mp df_join['model_probability'] = df_join.apply(lambda x: mp.model_probability(x['mean_win_margin'], x['sd'], x['Lines']), axis = 1) df_join ``` We can then format our pandas dataframe to compare the market's expected probability to the model's and find the bets the model feels best about. ``` df_join['difference'] = df_join.apply(lambda x: (x['model_probability']) - x['implied_probability'], axis=1) df_join = df_join.sort_values(by=['difference'], ascending=False) df_join ```
github_jupyter
&emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&ensp; [Home Page](../../START_HERE.ipynb) [Previous Notebook](Challenge.ipynb) &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; [1](Challenge.ipynb) [2] # Challenge - Gene Expression Classification - Workbook ### Introduction This notebook walks through an end-to-end GPU machine learning workflow where cuDF is used for processing the data and cuML is used to train machine learning models on it. After completing this excercise, you will be able to use cuDF to load data from disk, combine tables, scale features, use one-hote encoding and even write your own GPU kernels to efficiently transform feature columns. Additionaly you will learn how to pass this data to cuML, and how to train ML models on it. The trained model is saved and it will be used for prediction. It is not required that the user is familiar with cuDF or cuML. Since our aim is to go from ETL to ML training, a detailed introduction is out of scope for this notebook. We recommend [Introduction to cuDF](../../CuDF/01-Intro_to_cuDF.ipynb) for additional information. ### Problem Statement: We are trying to classify patients with acute myeloid leukemia (AML) and acute lymphoblastic leukemia (ALL) using machine learning (classification) algorithms. This dataset comes from a proof-of-concept study published in 1999 by Golub et al. It showed how new cases of cancer could be classified by gene expression monitoring (via DNA microarray) and thereby provided a general approach for identifying new cancer classes and assigning tumors to known classes. Here is the dataset link: https://www.kaggle.com/crawford/gene-expression. ## Here is the list of exercises and modules to work on in the lab: - Convert the serial Pandas computations to CuDF operations. - Utilize CuML to accelerate the machine learning models. - Experiment with Dask to create a cluster and distribute the data and scale the operations. You will start writing code from <a href='#dask1'>here</a>, but make sure you execute the data processing blocks to understand the dataset. ### 1. Data Processing The first step is downloading the dataset and putting it in the data directory, for using in this tutorial. Download the dataset here, and place it in (host/data) folder. Now we will import the necessary libraries. ``` import numpy as np; print('NumPy Version:', np.__version__) import pandas as pd import sys import sklearn; print('Scikit-Learn Version:', sklearn.__version__) from sklearn import preprocessing from sklearn.utils import resample from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectFromModel from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_curve, auc from sklearn.preprocessing import OrdinalEncoder, StandardScaler import cudf import cupy # import for model building from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import mean_squared_error from cuml.metrics.regression import r2_score from sklearn.preprocessing import StandardScaler from sklearn.pipeline import make_pipeline from sklearn import linear_model from sklearn.metrics import accuracy_score from sklearn import model_selection, datasets from cuml.dask.common import utils as dask_utils from dask.distributed import Client, wait from dask_cuda import LocalCUDACluster import dask_cudf from cuml.dask.ensemble import RandomForestClassifier as cumlDaskRF from sklearn.ensemble import RandomForestClassifier as sklRF ``` We'll read the dataframe into y from the csv file, view its dimensions and observe the first 5 rows of the dataframe. ``` %%time y = pd.read_csv('../../../data/actual.csv') print(y.shape) y.head() ``` Let's convert our target variable categories to numbers. ``` y['cancer'].value_counts() # Recode label to numeric y = y.replace({'ALL':0,'AML':1}) labels = ['ALL', 'AML'] # for plotting convenience later on ``` Read the training and test data provided in the challenge from the data folder. View their dimensions. ``` # Import training data df_train = pd.read_csv('../../../data/data_set_ALL_AML_train.csv') print(df_train.shape) # Import testing data df_test = pd.read_csv('../../../data/data_set_ALL_AML_independent.csv') print(df_test.shape) ``` Observe the first few rows of the train dataframe and the data format. ``` df_train.head() ``` Observe the first few rows of the test dataframe and the data format. ``` df_test.head() ``` As we can see, the data set has categorical values but only for the columns starting with "call". We won't use the columns having categorical values, but remove them. ``` # Remove "call" columns from training and testing data train_to_keep = [col for col in df_train.columns if "call" not in col] test_to_keep = [col for col in df_test.columns if "call" not in col] X_train_tr = df_train[train_to_keep] X_test_tr = df_test[test_to_keep] ``` Rename the columns and reindex for formatting purposes and ease in reading the data. ``` train_columns_titles = ['Gene Description', 'Gene Accession Number', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38'] X_train_tr = X_train_tr.reindex(columns=train_columns_titles) test_columns_titles = ['Gene Description', 'Gene Accession Number','39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72'] X_test_tr = X_test_tr.reindex(columns=test_columns_titles) ``` We will take the transpose of the dataframe so that each row is a patient and each column is a gene. ``` X_train = X_train_tr.T X_test = X_test_tr.T print(X_train.shape) X_train.head() ``` Just clearning the data, removing extra columns and converting to numerical values. ``` # Clean up the column names for training and testing data X_train.columns = X_train.iloc[1] X_train = X_train.drop(["Gene Description", "Gene Accession Number"]).apply(pd.to_numeric) # Clean up the column names for Testing data X_test.columns = X_test.iloc[1] X_test = X_test.drop(["Gene Description", "Gene Accession Number"]).apply(pd.to_numeric) print(X_train.shape) print(X_test.shape) X_train.head() ``` We have the 38 patients as rows in the training set, and the other 34 as rows in the testing set. Each of those datasets has 7129 gene expression features. But we haven't yet associated the target labels with the right patients. You will recall that all the labels are all stored in a single dataframe. Let's split the data so that the patients and labels match up across the training and testing dataframes.We are now splitting the data into train and test sets. We will subset the first 38 patient's cancer types. ``` X_train = X_train.reset_index(drop=True) y_train = y[y.patient <= 38].reset_index(drop=True) # Subset the rest for testing X_test = X_test.reset_index(drop=True) y_test = y[y.patient > 38].reset_index(drop=True) ``` Generate descriptive statistics to analyse the data further. ``` X_train.describe() ``` Clearly there is some variation in the scales across the different features. Many machine learning models work much better with data that's on the same scale, so let's create a scaled version of the dataset. ``` X_train_fl = X_train.astype(float, 64) X_test_fl = X_test.astype(float, 64) # Apply the same scaling to both datasets scaler = StandardScaler() X_train = scaler.fit_transform(X_train_fl) X_test = scaler.transform(X_test_fl) # note that we transform rather than fit_transform ``` <a id='dask1'></a> ### 2. Conversion to CuDF Dataframe Convert the pandas dataframes to CuDF dataframes to carry out the further CuML tasks. ``` #Modify the code in this cell %%time X_cudf_train = cudf.DataFrame() #Pass X train dataframe here X_cudf_test = cudf.DataFrame() #Pass X test dataframe here y_cudf_train = cudf.DataFrame() #Pass y train dataframe here #y_cudf_test = cudf.Series(y_test.values) #Pass y test dataframe here ``` ### 3. Model Building #### Dask Integration We will try using the Random Forests Classifier and implement using CuML and Dask. #### Start Dask cluster ``` #Modify the code in this cell # This will use all GPUs on the local host by default cluster = LocalCUDACluster() #Set 1 thread per worker using arguments to cluster c = Client() #Pass the cluster as an argument to Client # Query the client for all connected workers workers = c.has_what().keys() n_workers = len(workers) n_streams = 8 # Performance optimization ``` #### Define Parameters In addition to the number of examples, random forest fitting performance depends heavily on the number of columns in a dataset and (especially) on the maximum depth to which trees are allowed to grow. Lower `max_depth` values can greatly speed up fitting, though going too low may reduce accuracy. ``` # Random Forest building parameters max_depth = 12 n_bins = 16 n_trees = 1000 ``` #### Distribute data to worker GPUs ``` X_train = X_train.astype(np.float32) X_test = X_test.astype(np.float32) y_train = y_train.astype(np.int32) y_test = y_test.astype(np.int32) n_partitions = n_workers def distribute(X, y): # First convert to cudf (with real data, you would likely load in cuDF format to start) X_cudf = cudf.DataFrame.from_pandas(pd.DataFrame(X)) y_cudf = cudf.Series(y) # Partition with Dask # In this case, each worker will train on 1/n_partitions fraction of the data X_dask = dask_cudf.from_cudf(X_cudf, npartitions=n_partitions) y_dask = dask_cudf.from_cudf(y_cudf, npartitions=n_partitions) # Persist to cache the data in active memory X_dask, y_dask = \ dask_utils.persist_across_workers(c, [X_dask, y_dask], workers=workers) return X_dask, y_dask #Modify the code in this cell X_train_dask, y_train_dask = distribute() #Pass train data as arguments here X_test_dask, y_test_dask = distribute() #Pass test data as arguments here ``` #### Create the Scikit-learn model Since a scikit-learn equivalent to the multi-node multi-GPU K-means in cuML doesn't exist, we will use Dask-ML's implementation for comparison. ``` %%time # Use all avilable CPU cores skl_model = sklRF(max_depth=max_depth, n_estimators=n_trees, n_jobs=-1) skl_model.fit(X_train, y_train.iloc[:,1]) ``` #### Train the distributed cuML model ``` #Modify the code in this cell %%time cuml_model = cumlDaskRF(max_depth=max_depth, n_estimators=n_trees, n_bins=n_bins, n_streams=n_streams) cuml_model.fit() # Pass X and y train dask data here wait(cuml_model.rfs) # Allow asynchronous training tasks to finish ``` #### Predict and check accuracy ``` #Modify the code in this cell skl_y_pred = skl_model.predict(X_test) cuml_y_pred = cuml_model.predict().compute().to_array() #Pass the X test dask data as argument here # Due to randomness in the algorithm, you may see slight variation in accuracies print("SKLearn accuracy: ", accuracy_score(y_test.iloc[:,1], skl_y_pred)) print("CuML accuracy: ", accuracy_score()) #Pass the y test dask data and predicted values from CuML model as argument here ``` <a id='ex4'></a><br> ### 4. CONCLUSION Let's compare the performance of our solution! | Algorithm | Implementation | Accuracy | Time | Algorithm | Implementation | Accuracy | Time | | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | ----------- | Write down your observations and compare the CuML and Scikit learn scores. They should be approximately equal. We hope that you found this exercise exciting and beneficial in understanding RAPIDS better. Share your highest accuracy and try to use the unique features of RAPIDS for accelerating your data science pipelines. Don't restrict yourself to the previously explained concepts, but use the documentation to apply more models and functions and achieve the best results. ### 5. References <p xmlns:dct="http://purl.org/dc/terms/"> <a rel="license" href="http://creativecommons.org/publicdomain/zero/1.0/"> <center><img src="http://i.creativecommons.org/p/zero/1.0/88x31.png" style="border-style: none;" alt="CC0" /></center> </a> </p> - The dataset is licensed under a CC0: Public Domain license. - Molecular Classification of Cancer: Class Discovery and Class Prediction by Gene Expression. Science 286:531-537. (1999). Published: 1999.10.14. T.R. Golub, D.K. Slonim, P. Tamayo, C. Huard, M. Gaasenbeek, J.P. Mesirov, H. Coller, M. Loh, J.R. Downing, M.A. Caligiuri, C.D. Bloomfield, and E.S. Lander ## Licensing This material is released by OpenACC-Standard.org, in collaboration with NVIDIA Corporation, under the Creative Commons Attribution 4.0 International (CC BY 4.0). [Previous Notebook](Challenge.ipynb) &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; [1](Challenge.ipynb) [2] &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&emsp;&emsp;&emsp; &emsp;&emsp;&ensp; [Home Page](../../START_HERE.ipynb)
github_jupyter
# UMAP on the PBMC dataset of Zheng ``` %load_ext autoreload %autoreload 2 %env CUDA_VISIBLE_DEVICES=2 import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import umap from firelight.visualizers.colorization import get_distinct_colors from matplotlib.colors import ListedColormap import pickle import matplotlib.lines as mlines import matplotlib from umap.my_plot import plot_all_losses, hists_from_graph_embd from umap.my_utils import filter_graph dir_path = "../data/zheng_pbmc" fig_path = "../figures" seed = 0 # load the data pca50 = pd.read_csv(os.path.join(dir_path, "pbmc_qc_final.txt"), sep='\t', header=None) pca50.shape cell_types = pd.read_csv(os.path.join(dir_path, "pbmc_qc_final_labels.txt"), sep=',', header=None).to_numpy().flatten() np.unique(cell_types) # rename cell types by stripping "CD..." prefixes if possible for i in range(len(cell_types)): words = cell_types[i].split(" ") if words[0].startswith("CD") and not len(words) == 1: words = words[1:] cell_types[i] = " ".join(words) labels = np.zeros(len(cell_types)).astype(int) name_to_label = {} for i, phase in enumerate(np.unique(cell_types)): name_to_label[phase] = i labels[cell_types==phase] = i np.random.seed(seed) colors = get_distinct_colors(len(name_to_label)) cmap = ListedColormap(colors) np.random.shuffle(colors) try: with open(os.path.join(dir_path, f"umapperns_after_seed_{seed}.pkl"), "rb") as file: umapperns_after = pickle.load(file) embd_after = umapperns_after.embedding_ except FileNotFoundError: umapperns_after = umap.UMAP(metric="cosine", n_neighbors=30, n_epochs=750, log_losses="after", random_state=seed, verbose=True) embd_after = umapperns_after.fit_transform(pca50) with open(os.path.join(dir_path, f"umapperns_after_seed_{seed}.pkl"), "wb") as file: pickle.dump(umapperns_after, file, pickle.HIGHEST_PROTOCOL) plt.figure(figsize=(8,8)) scatter = plt.scatter(-embd_after[:,1], -embd_after[:,0], c=labels, s=0.1, alpha=1.0, cmap=cmap) plt.axis("off") plt.gca().set_aspect("equal") # dummy dots for legend dots = [] for i in range(len(np.unique(cell_types))): dot = mlines.Line2D([], [], color=colors[i], marker='.', linestyle="none", markersize=15, label=np.unique(cell_types)[i]) dots.append(dot) plt.legend(handles=dots, prop={'size': 20}, loc=(1,0)) plt.savefig(os.path.join(fig_path, f"pbmc_after_seed_{seed}.png"), bbox_inches = 'tight', pad_inches = 0, dpi=300) start=10 # omit early epochs where UMAP's sampling approximation is poor matplotlib.rcParams.update({'font.size': 15}) fig_losses_after = plot_all_losses(umapperns_after.aux_data,start=start) fig_losses_after.savefig(os.path.join(fig_path, f"pbmc_after_losses_{start}_seed_{seed}.png"), bbox_inches = 'tight', pad_inches = 0, dpi=300) alpha=0.5 min_dist = 0.1 spread = 1.0 a, b= umap.umap_.find_ab_params(spread=spread, min_dist=min_dist) fil_graph = filter_graph(umapperns_after.graph_, umapperns_after.n_epochs).tocoo() hist_high_pbmc, \ hist_high_pos_pbmc, \ hist_target_pbmc, \ hist_target_pos_pbmc, \ hist_low_pbmc, \ hist_low_pos_pbmc, \ bins_pbmc = hists_from_graph_embd(graph=fil_graph, embedding=embd_after, a=a, b=b) # plot histogram of positive high-dimensional edges plt.rcParams.update({'font.size': 22}) plt.figure(figsize=(8, 5)) plt.hist(bins_pbmc[:-1], bins_pbmc, weights=hist_high_pos_pbmc, alpha=alpha, label=r"$\mu_{ij}$") plt.hist(bins_pbmc[:-1], bins_pbmc, weights=hist_target_pos_pbmc, alpha=alpha, label=r"$\nu_{ij}^*$") plt.hist(bins_pbmc[:-1], bins_pbmc, weights=hist_low_pos_pbmc, alpha=alpha, label=r"$\nu_{ij}$") plt.legend(loc="upper center", ncol=3) #plt.yscale("symlog", linthresh=1) plt.gca().spines['left'].set_position("zero") plt.gca().spines['bottom'].set_position("zero") #plt.savefig(os.path.join(fig_path, f"pbmc_hist_sims_pos_seed_{seed}.png"), # bbox_inches = 'tight', # pad_inches = 0,dpi=300) ```
github_jupyter
# Ray Crash Course - Actors © 2019-2021, Anyscale. All Rights Reserved ![Anyscale Academy](../images/AnyscaleAcademyLogo.png) Using Ray _tasks_ is great for distributing work around a cluster, but we've said nothing so far about managing distributed _state_, one of the big challenges in distributed computing. Ray tasks are great for _stateless_ computation, but we need something for _stateful_ computation. Python classes are a familiar mechanism for encapsulating state. Just as Ray tasks extend the familiar concept of Python _functions_, Ray addresses stateful computation by extending _classes_ to become Ray _actors_. > **Tip:** For more about Ray, see [ray.io](https://ray.io) or the [Ray documentation](https://docs.ray.io/en/latest/). ## What We Mean by Distributed State If you've worked with data processing libraries like [Pandas](https://pandas.pydata.org/) or big data tools like [Apache Spark](https://spark.apache.org), you know that they provide rich features for manipulating large, structured _data sets_, i.e., the analogs of tables in a database. Some tools even support partitioning of these data sets over clusters for scalability. This isn't the kind of distributed "state" Ray addresses. Instead, it's the more open-ended _graph of objects_ found in more general-purpose applications. For example, it could be the state of a game engine used in a reinforcement learning (RL) application or the total set of parameters in a giant neural network, some of which now have hundreds of millions of parameters. ## Conway's Game of Life Let's explore Ray's actor model using [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway's_Game_of_Life), a famous _cellular automaton_. Here is an example of a notable pattern of game evolution, _Gospers glider gun_: ![Example Gospers glider gun](../images/Gospers_glider_gun.gif) (credit: Lucas Vieira - Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=101736) We'll use an implementation of Conway's Game of Life as a nontrivial example of maintaining state, the current grid of living and dead cells. We'll see how to leverage Ray to scale it. > **Note:** Sadly, [John Horton Conway](https://en.wikipedia.org/wiki/John_Horton_Conway), the inventor of this automaton, passed away from COVID-19 on April 11, 2020. This lesson is dedicated to Professor Conway. Let's start with some imports ``` import ray, time, statistics, sys, os import numpy as np import os sys.path.append("..") # For library helper functions ``` I've never seen this done anywhere else, but our implementation of Game of Life doesn't just use `1` for living cells, it uses the number of iterations they've been alive, so `1-N`. I'll exploit this when we graph the game. ``` from game_of_life import Game, State, ConwaysRules ``` Utility functions for plotting using Holoviews and Bokeh, as well as running and timing games. ``` from actor_lesson_util import new_game_of_life_graph, new_game_of_life_grid, run_games, run_ray_games, show_cmap ``` The implementation is a bit long, so all the code is contained in [`game_of_life.py`](game_of_life.py). (You can also run that file as a standalone script from the command line, try `python game_of_life.py --help`. On MacOS and Linux machines, the script is executable, so you can omit the `python`). The first class is the `State`, which encapsulates the board state as an `N x N` grid of _cells_, where `N` is specified by the user. (For simplicity, we just use square grids.) There are two ways to initialize the game, specifying a starting grid or a size, in which case the cells are set randomly. The sample below just shows the size option. `State` instances are _immutable_, because the `Game` (discussed below) keeps a sequence of them, representing the lifetime states of the game. For smaller grids, it's often possible that the game reaches a terminal state where it stops evolving. Larger grids are more likely to exhibit different cyclic patterns that would evolve forever, thereby making those runs appear to be _immortal_, except they eventually get disrupted by evolving neighbors. ```python class State: def __init__(self, size = 10): # The version in the file also lets you pass in a grid of initial cells. self.size = size self.grid = np.random.randint(2, size = size*size).reshape((size, size)) def living_cells(self): cells = [(i,j) for i in range(self.size) for j in range(self.size) if self.grid[i][j] != 0] return zip(*cells) ``` Next, `ConwaysRules` encapsulates the logic of computing the new state of a game from the current state, using the update rules defined as follows: * Any live cell with fewer than two live neighbours dies, as if by underpopulation. * Any live cell with two or three live neighbours lives on to the next generation. * Any live cell with more than three live neighbours dies, as if by overpopulation. * Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. This class is stateless; `step()` is passed a `State` instance and it returns a new instance for the udpated state. ```python class ConwaysRules: def step(self, state): """ Determine the next values for all the cells, based on the current state. Creates a new State with the changes. """ new_grid = state.grid.copy() for i in range(state.size): for j in range(state.size): new_grid[i][j] = self.apply_rules(i, j, state) new_state = State(grid = new_grid) return new_state def apply_rules(self, i, j, state): # Compute and return the next state for grid[i][j] return ... ``` Finally, the game holds a sequence of states and the rules "engine". ```python class Game: def __init__(self, initial_state, rules): self.states = [initial_state] self.rules = rules def step(self, num_steps = 1): """Take 1 or more steps, returning a list of new states.""" new_states = [self.rules.step(self.states[-1]) for _ in range(num_steps)] self.states.extend(new_states) return new_states ``` Okay, let's try it out!! ``` steps = 100 # Use a larger number for a long-running game. game_size = 100 plot_size = 800 max_cell_age = 10 # clip the age of cells for graphing. use_fixed_cell_sizes = True # Keep the points the same size. Try False, too! ``` For the graphs, we'll use a "greenish" background that looks good with `RdYlBu` color map. However, if you have red-green color blindness, change the `bgcolor` string to `white`! Or, try the second combination with a custom color map `cmap` and background color `white` or `darkgrey`. ``` # Color maps from Bokeh: cmap = 'RdYlBu' # others: 'Turbo' 'YlOrBr' bgcolor = '#C0CfC8' # a greenish color, but not great for forms of red-green color blindness, where 'white' is better. # A custom color map created at https://projects.susielu.com/viz-palette. Works best with white or dark grey background #cmap=['#ffd700', '#ffb14e', '#fa8775', '#ea5f94', '#cd34b5', '#9d02d7', '#0000ff'] #bgcolor = 'darkgrey' # 'white' def new_game(game_size): initial_state = State(size = game_size) rules = ConwaysRules() game = Game(initial_state=initial_state, rules=rules) return game game = new_game(10) print(game.states[0]) ``` Now let's create a graph for a game of life using the imported utility function, `new_game_of_life_grid` (with only one graph in the "grid" for now). **Note:** It will be empty for now. ``` _, graphs = new_game_of_life_grid(game_size, plot_size, x_grid=1, y_grid=1, shrink_factor=1.0, bgcolor=bgcolor, cmap=cmap, use_fixed_cell_sizes=use_fixed_cell_sizes, max_cell_age=max_cell_age) graphs[0] ``` To make sure we don't consume too much driver memory, since games can grow large, let's write a function, `do_trial`, to run the experiment, then when it returns, the games will go out of scope and their memory will be reclaimed. It will use a library function we imported, `run_games` and the `new_game` function above to do most of the work. (You might wonder why we don't create the `graphs` inside the function. It's essentially impossible to show the grid **before** the games run **and** to do the update visualization after it's shown inside one function inside a notebook cell. We have to build the grid, render it separately, then call `do_trial`.) ``` def do_trial(graphs, num_games=1, steps=steps, batch_size=1, game_size_for_each=game_size, pause_between_batches=0.0): games = [new_game(game_size_for_each) for _ in range(num_games)] return run_games(games, graphs, steps, batch_size, pause_between_batches) %time num_games, steps, batch_size, duration = do_trial(graphs, steps=steps, pause_between_batches=0.1) num_games, steps, batch_size, duration ``` If you can't see the plot or see it update, click here for a screen shot: * [colored background](../images/ConwaysGameOfLife-Snapshot.png) * [white background](../images/ConwaysGameOfLife-Snapshot-White-Background.png) (Want to run longer? Pass a larger value for `steps` in the previous cell. 1000 takes several minutes, but you'll see interesting patterns develop.) The first line of output is written by `run_games`, which is called by `do_trial`. The next two lines are output from the `%time` "magic". The fourth line shows the values returned by `run_games` through `do_trial`, which we'll use more fully in the exercise below. How much time did it take? Note that there were `steps*0.1` seconds of sleep time between steps, so the rest is compute time. Does that account for the difference between the _user_ time and the _wall_ time? ``` steps*0.1 ``` Yes, this covers most of the extra wall time. A point's color changed as it lived longer. Here is the _color map_ used, where the top color corresponds to the longest-lived cells. ``` show_cmap(cmap=cmap, max_index=max_cell_age) ``` If you can't see the color map in the previous cell output, click [here](../images/ConwaysGameOfLife-ColorMap-RdYlBu.png) for the color map `RdYlBu`. You could experiment with different values for `max_cell_age`. > **Mini Exercise:** Change the value passed for `use_fixed_cell_sizes` to be `False` (in the cell that calls `new_game_of_life_grid`). Then rerun the `%time do_trial()` cell. What happens to the graph? ### Running Lots of Games Suppose we wanted to run many of these games at the same time. For example, we might use reinforcement learning to find the initial state that maximizes some _reward_, like the most live cells after `N` steps or for immortal games. You could try writing a loop that starts `M` games and run the previous step loop interleaving games. Let's try that, with smaller grids. ``` x_grid = 5 y_grid = 3 shrink_factor = y_grid # Instead of 1 N-size game, build N/shrinkfactor size games small_game_size = round(game_size/shrink_factor) ``` First build a grid of graphs, like before: ``` gridspace, all_graphs = new_game_of_life_grid(small_game_size, plot_size, x_grid, y_grid, shrink_factor, bgcolor=bgcolor, cmap=cmap, use_fixed_cell_sizes=use_fixed_cell_sizes, max_cell_age=max_cell_age) gridspace %time num_games, steps, batch_size, duration = do_trial(all_graphs, num_games=x_grid*y_grid, steps=steps, batch_size=1, game_size_for_each=small_game_size, pause_between_batches=0.1) num_games, steps, batch_size, duration ``` If you can't see the plot or see it update, click here for a screen shot: * [colored background](../images/ConwaysGameOfLife-Grid-Snapshot.png) * [white background](../images/ConwaysGameOfLife-Grid-Snapshot-White-Background.png) (captured earlier in the run) How much time did it take? You can perceive a "wave" across the graphs at each time step, because the games aren't running concurrently. Sometimes, a "spurt" of updates will happen, etc. Not ideal... There were the same `steps*0.1` seconds of sleep time between steps, not dependent on the number of games, so the rest is compute time. ## Improving Performance with Ray. Let's start Ray as before in the [first lesson](01-Ray-Tasks.ipynb). ``` ray.init(ignore_reinit_error=True) ``` Running on your laptop? Click the output of the next cell to open the Ray Dashboard. If you are running on the Anyscale platform, use the dashboard URL provided to you. ``` print(f'New port? http://{ray.get_dashboard_url()}') ``` ## Actors - Ray's Tool for Distributed State Python is an object-oriented language. We often encapsulate bits of state in classes, like we did for `State` above. Ray leverages this familiar mechanism to manage distributed state. Recall that adding the `@ray.remote` annotation to a _function_ turned it into a _task_. If we use the same annotation on a Python _class_, we get an _actor_. ### Why "Actor" The [Actor Model of Concurrency](https://en.wikipedia.org/wiki/Actor_model) is almost 50 years old! It's a _message-passing_ model, where autonomous blocks of code, the actors, receive messages from other actors asking them to perform work or return some results. Implementations provide thread safety while the messages are processed, one at a time. This means the user of an actor model implementation doesn't have to worry about writing thread-safe code. Because many messages might arrive while one is being processed, they are stored in a queue and processed one at a time, the order of arrival. There are many other implementations of the actor model, including [Erlang](https://www.erlang.org/), the first system to create a production-grade implementation, initially used for telecom switches, and [Akka](https://akka.io), a JVM implementation inspired by Erlang. > **Tip:** The [Ray Package Reference](https://ray.readthedocs.io/en/latest/package-ref.html) in the [Ray Docs](https://ray.readthedocs.io/en/latest/) is useful for exploring the API features we'll learn. Let's start by simply making `Game` an actor. We'll just subclass it and add `@ray.remote` to the subclass. There's one other change we have to make; if we want to access the `state` and `rules` instances in an Actor, we can't just use `mygame.state`, for example, as you would normally do for Python instances. Instead, we have to add "getter" methods for them. Here's our Game actor definition. ``` @ray.remote class RayGame(Game): def __init__(self, initial_state, rules): super().__init__(initial_state, rules) def get_states(self): return self.states def get_rules(self): return self.rules ``` To construct an instance and call methods, you use `.remote` as for tasks: ``` def new_ray_game(game_size): initial_state = State(size = game_size) rules = ConwaysRules() ray_game_actor = RayGame.remote(initial_state, rules) # Note that .remote(...) is used to construct the instance. return ray_game_actor ``` We'll use the following function to try out the implementation, but then take the Ray actor out of scope when we're done. This is because actors remain pinned to a worker as long as the driver (this notebook) has a reference to them. We don't want that wasted space... ``` def try_ray_game_actor(): ray_game_actor = new_ray_game(small_game_size) print(f'Actor for game: {ray_game_actor}') init_states = ray.get(ray_game_actor.step.remote()) print(f'\nInitial state:\n{init_states[0]}') new_states = ray.get(ray_game_actor.step.remote()) print(f'\nState after step #1:\n{new_states[0]}') try_ray_game_actor() ``` > **Key Points:** To summarize: > > 1. Declare an _actor_ by annotating a class with `@ray.remote`, just like declaring a _task_ from a function. > 2. Add _accessor_ methods for any data members that you need to read or write, because using direct access, such as `my_game.state`, doesn't work for actors. > 3. Construct actor instances with `my_instance = MyClass.remote(...)`. > 4. Call methods with `my_instance.some_method.remote(...)`. > 5. Use `ray.get()` and `ray.wait()` to retrieve results, just like you do for task results. > **Tip:** If you start getting warnings about lots of Python processes running or you have too many actors scheduled, you can safely ignore these messages for now, but the performance measurements below won't be as accurate. Okay, now let's repeat our grid experiment with a Ray-enabled Game of Life. Let's define a helper function, `do_ray_trail`, which is analogous to `do_trial` above. It encapsulates some of the steps, for the same reasons mentioned above; so that our actors go out of scope and the worker slots are reclaimed when the function call returns. We call a library function `run_ray_games` to run these games. It's somewhat complicated, because it uses `ray.wait()` to process updates as soon as they are available, and also has hooks for batch processing and running without graphing (see below). We'll create the graphs separately and pass them into `do_ray_trial`. ``` def do_ray_trial(graphs, num_games=1, steps=steps, batch_size=1, game_size_for_each=game_size, pause_between_batches=0.0): game_actors = [new_ray_game(game_size_for_each) for _ in range(num_games)] return run_ray_games(game_actors, graphs, steps, batch_size, pause_between_batches) ray_gridspace, ray_graphs = new_game_of_life_grid(small_game_size, plot_size, x_grid, y_grid, shrink_factor, bgcolor=bgcolor, cmap=cmap, use_fixed_cell_sizes=use_fixed_cell_sizes, max_cell_age=max_cell_age) ray_gridspace %time do_ray_trial(ray_graphs, num_games=x_grid*y_grid, steps=steps, batch_size=1, game_size_for_each=small_game_size, pause_between_batches=0.1) ``` (Can't see the image? It's basically the same as the previous grid example.) How did your times compare? For example, using a recent model MacBook Pro laptop, this run took roughly 19 seconds vs. 21 seconds for the previous run without Ray. That's not much of an improvement. Why? In fact, updating the graphs causes enough overhead to remove most of the speed advantage of using Ray. We also sleep briefly between generations for nicer output. However, using Ray does produce smoother graph updates. So, if we want to study more performance optimizations, we should remove the graphing overhead, which we'll do for the rest of this lesson. Let's run the two trials without graphs and compare the performance. We'll use no pauses between "batches" and run the same number of games as the number of CPU (cores) Ray says we have. This is actually the number of workers Ray started for us and 2x the number of actual cores: ``` num_cpus_float = ray.cluster_resources()['CPU'] num_cpus_float ``` As soon as you start the next two cell, switch to the Ray Dashboard and watch the CPU utilization. You'll see the Ray workers are idle, because we aren't using them right now, but the total CPU utilization will be about well under 100%. For example, on a four-core laptop, the total CPU utilization will be 20-25% or roughly 1/4th capacity. Why? We're running the whole computation in the Python process for this notebook, which only utilizes one core. ``` %time do_trial(None, num_games=round(num_cpus_float), steps=steps, batch_size=1, game_size_for_each=game_size, pause_between_batches=0.0) ``` Now use Ray. Again, as soon as you start the next cell, switch to the Ray Dashboard and watch the CPU utilization. Now, the Ray workers will be utilized (but not 100%) and the total CPU utilization will be higher. You'll probably see 70-80% utilization. Hence, now we're running on all cores. ``` %time do_ray_trial(None, num_games=round(num_cpus_float), steps=steps, batch_size=1, game_size_for_each=game_size, pause_between_batches=0.0) ``` So, using Ray does help when running parallel games. On a typical laptop, the performance boost is about 2-3 times better. It's not 15 times better (the number of concurrent games), because the computation is CPU intensive for each game with frequent memory access, so all the available cores are fully utilized. We would see much more impressive improvements on a cluster with a lot of CPU cores when running a massive number of games. Notice the times for `user` and `total` times reported for the non-Ray and Ray runs (which are printed by the `%time` "magic"). They are only measuring the time for the notebook Python process, i.e., our "driver" program, not the whole application. Without Ray, all the work is done in this process, as we said previously, so the `user` and `total` times roughly equal the wall clock time. However, for Ray, these times are very low; the notebook is mostly idle, while the work is done in the separate Ray worker processes. ## More about Actors Let's finish with a discussion of additional important information about actors, including recapping some points mentioned above. ### Actor Scheduling and Lifetimes For the most part, when Ray runs actor code, it uses the same _task_ mechanisms we discussed in the [Ray Tasks](01-Ray-Tasks.ipynb) lesson. Actor constructor and method invocations work just like task invocations. However, there are a few notable differences: * Once a _task_ finishes, it is removed from the worker that executed it, while an actor is _pinned_ to the worker until all Python references to it in the driver program are out of scope. That is, the usual garbage collection mechanism in Python determines when an actor is no longer needed and is removed from a worker. The reason the actor must remain in memory is because it holds state that might be needed, whereas tasks are stateless. * Currently, each actor instance uses tens of MB of memory overhead. Hence, just as you should avoid having too many fine-grained tasks, you should avoid too many actor instances. (Reducing the overhead per actor is an ongoing improvement project.) We explore actor scheduling and lifecycles in much greater depth in lesson [03: Ray Internals](03-Ray-Internals.ipynb) in the [Advanced Ray](../advanced-ray/00-Advanced-Ray-Overview.ipynb) tutorial. ### Durability of Actor State At this time, Ray provides no built-in mechanism for _persisting_ actor state, i.e., writing to disk or a database in case of process failure. Hence, if a worker or whole server goes down with actor instances, their state is lost. This is an area where Ray will evolve and improve in the future. For now, an important design consideration is to decide when you need to _checkpoint_ state and to use an appropriate mechanism for this purpose. Some of the Ray APIs explored in other tutorials have built-in checkpoint features, such as for saving snapshots of trained models to a file system. ## Extra - Does It Help to Run with Larger Batch Sizes? You can read this section but choose to skip running the code for time's sake. The outcomes are discussed at the end. You'll notice that we defined `run_games` and `do_trial`, as well as `run_ray_games` and `do_ray_trial` to take an optional `batch_size` that defaults to `1`. The idea is that maybe running game steps in batches, rather than one step at a time, will improve performance (but look less pleasing in the graphs). This concept works in some contexts, such as minimizing the number of messages sent in networks (that is, fewer, but larger payloads), but it actually doesn't help a lot here, because each game is played in a single process, whether using Ray or not (at least as currently implemented...). Batching reduces the number of method invocations, but it's not an important amount of overhead in our case. Let's confirm our suspicion about batching, that it doesn't help a lot. Let's time several batch sizes without and with Ray. We'll run several times with each batch size to get an informal sense of the variation possible. Once again, watch the Ray Dashboard while the next two code cells run. ``` for batch in [1, 10, 25, 50]: for run in [0, 1]: do_trial(graphs = None, num_games=1, steps=steps, batch_size=batch, game_size_for_each=game_size, pause_between_batches=0.0) ``` There isn't a significant difference based on batch size. What about Ray? If we're running just one game, the results should be about the same. ``` for batch in [1, 10, 25, 50]: for run in [0, 1]: do_ray_trial(graphs = None, num_games=1, steps=steps, batch_size=batch, game_size_for_each=game_size, pause_between_batches=0.0) ``` With Ray's background activity, there is likely to be a little more variation in the numbers, but the conclusion is the same; the batch size doesn't matter because no additional exploitation of asynchronous computing is used. # Exercises When we needed to run multiple games concurrently as fast as possible, Ray was an easy win. If we graphed them while running, the wall-clock time is about the same, due to the graphics overhead, but the graphs updated more smoothly and each one looked independent. Just as for Ray tasks, actors add some overhead, so there will be a crossing point for small problems where the concurrency provided by Ray won't be as beneficial. This exercise uses a simple actor example to explore this tradeoff. See the [solutions notebook](solutions/Ray-Crash-Course-Solutions.ipynb) for a discussion of questions posed in this exercise. ## Exercise 1 Let's investigat Ray Actor performance. Answers to the questions posed here are in the [solutions](solutions/Ray-Crash-Course-Solutions.ipynb) notebook. Consider the following class and actor, which simulate a busy process using `time.sleep()`: ``` class Counter: """Remember how many times ``next()`` has been called.""" def __init__(self, pause): self.count = 0 self.pause = pause def next(self): time.sleep(self.pause) self.count += 1 return self.count @ray.remote class RayCounter(Counter): """Remember how many times ``next()`` has been called.""" def __init__(self, pause): super().__init__(pause) def get_count(self): return self.count ``` Recall that for an actor we need an accessor method to get the current count. Here are methods to time them. ``` def counter_trial(count_to, num_counters = 1, pause = 0.01): print('not ray: count_to = {:5d}, num counters = {:4d}, pause = {:5.3f}: '.format(count_to, num_counters, pause), end='') start = time.time() counters = [Counter(pause) for _ in range(num_counters)] for i in range(num_counters): for n in range(count_to): counters[i].next() duration = time.time() - start print('time = {:9.5f} seconds'.format(duration)) return count_to, num_counters, pause, duration def ray_counter_trial(count_to, num_counters = 1, pause = 0.01): print('ray: count_to = {:5d}, num counters = {:4d}, pause = {:5.3f}: '.format(count_to, num_counters, pause), end='') start = time.time() final_count_futures = [] counters = [RayCounter.remote(pause) for _ in range(num_counters)] for i in range(num_counters): for n in range(count_to): counters[i].next.remote() final_count_futures.append(counters[i].get_count.remote()) ray.get(final_count_futures) # Discard result, but wait until finished! duration = time.time() - start print('time = {:9.5f} seconds'.format(duration)) return count_to, num_counters, pause, duration ``` Let's get a sense of what the performance looks like: ``` count_to = 10 for num_counters in [1, 2, 3, 4]: counter_trial(count_to, num_counters, 0.0) for num_counters in [1, 2, 3, 4]: counter_trial(count_to, num_counters, 0.1) for num_counters in [1, 2, 3, 4]: counter_trial(count_to, num_counters, 0.2) ``` When there is no sleep pause, the results are almost instaneous. For nonzero pauses, the times scale linearly in the pause size and the number of `Counter` instances. This is expected, since `Counter` and `counter_trail` are completely synchronous. What about for Ray? ``` count_to = 10 for num_counters in [1, 2, 3, 4]: ray_counter_trial(count_to, num_counters, 0.0) for num_counters in [1, 2, 3, 4]: ray_counter_trial(count_to, num_counters, 0.1) for num_counters in [1, 2, 3, 4]: ray_counter_trial(count_to, num_counters, 0.2) ``` Ray has higher overhead, so the zero-pause times for `RayCounter` are much longer than for `Counter`, but the times are roughly independent of the number of counters, because the instances are now running in parallel unlike before. However, the times _per counter_ still grow linearly in the pause time and they are very close to the the times per counter for `Counter` instances. Here's a repeat run to show what we mean: ``` count_to=10 num_counters = 1 for pause in range(0,6): counter_trial(count_to, num_counters, pause*0.1) ray_counter_trial(count_to, num_counters, pause*0.1) ``` Ignoring pause = 0, can you explain why the Ray times are almost, but slightly larger than the non-ray times consistently? Study the implementations for `ray_counter_trial` and `RayCounter`. What code is synchronous and blocking vs. concurrent? In fact, is there _any_ code that is actually concurrent when you have just one instance of `Counter` or `RayCounter`? To finish, let's look at the behavior for smaller pause steps, 0.0 to 0.1, and plot the times. ``` count_to=10 num_counters = 1 pauses=[] durations=[] ray_durations=[] for pause in range(0,11): pauses.append(pause*0.01) _, _, _, duration = counter_trial(count_to, num_counters, pause*0.01) durations.append(duration) _, _, _, duration = ray_counter_trial(count_to, num_counters, pause*0.01) ray_durations.append(duration) from bokeh_util import two_lines_plot # utility we used in the previous lesson from bokeh.plotting import show, figure from bokeh.layouts import gridplot two_lines = two_lines_plot( "Pause vs. Execution Times (Smaller Is Better)", 'Pause', 'Time', 'No Ray', 'Ray', pauses, durations, pauses, ray_durations, x_axis_type='linear', y_axis_type='linear') show(two_lines, plot_width=800, plot_height=400) ``` (Can't see the plot? Click [here](../images/actor-trials.png) for a screen shot.) Once past zero pauses, the Ray overhead is constant. It doesn't grow with the pause time. Can you explain why it doesn't grow? Run the next cell when you are finished with this notebook: ``` ray.shutdown() # "Undo ray.init()". Terminate all the processes started in this notebook. ``` The next lesson, [Why Ray?](03-Why-Ray.ipynb), takes a step back and explores the origin and motivations for Ray, and Ray's growing ecosystem of libraries and tools.
github_jupyter
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All). Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as well as your name and collaborators below: ``` NAME = "" COLLABORATORS = "" ``` --- <!--NOTEBOOK_HEADER--> *This notebook contains material from [PyRosetta](https://RosettaCommons.github.io/PyRosetta.notebooks); content is available [on Github](https://github.com/RosettaCommons/PyRosetta.notebooks.git).* <!--NAVIGATION--> < [Visualization with the `PyMOLMover`](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.06-Visualization-and-PyMOL-Mover.ipynb) | [Contents](toc.ipynb) | [Index](index.ipynb) | [Visualization and `pyrosetta.distributed.viewer`](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.08-Visualization-and-pyrosetta.distributed.viewer.ipynb) ><p><a href="https://colab.research.google.com/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.07-RosettaScripts-in-PyRosetta.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open in Google Colaboratory"></a> # RosettaScripts in PyRosetta Keywords: RosettaScripts, script, xml, XMLObjects ## Overview RosettaScripts in another way to script custom modules in PyRosetta. It is much simpler than PyRosetta, but can be extremely powerful, and with great documentation. There are also many publications that give `RosettaScript` examples, or whole protocols as a `RosettaScript` instead of a mover or application. In addition, some early Rosetta code was written with `RosettaScripts` in mind, and still may only be fully accessible via `RosettaScripts` in order to change important variables. Recent versions of Rosetta have enabled full RosettaScript protocols to be run in PyRosetta. A new class called `XMLObjects`, has also enabled the setup of specific rosetta class types in PyRosetta instead of constructing them from code. This tutorial will introduce how to use this integration to get the most out of Rosetta. Note that some tutorials use RosettaScripts almost exclusively, such as the parametric protein design notebook, as it is simpler to use RS than setting up everything manually in code. ## RosettaScripts A RosettaScript is made up of different sections where different types of Rosetta classes are constructed. You will see many of these types throughout the notebooks to come. Briefly: `ScoreFunctions`: A scorefunction evaluates the energy of a pose through physical and statistal energy terms `ResidueSelectors`: These select a list of residues in a pose according to some criteria `Movers`: These do things to a pose. They all have an `apply()` method that you will see shortly. `TaskOperations`: These control side-chain packing and design `SimpleMetrics`: The return some metric value of a pose. This value can be a real number, string, or a composite of values. ### Skeleton RosettaScript Format ```xml <ROSETTASCRIPTS> <SCOREFXNS> </SCOREFXNS> <RESIDUE_SELECTORS> </RESIDUE_SELECTORS> <TASKOPERATIONS> </TASKOPERATIONS> <SIMPLE_METRICS> </SIMPLE_METRICS> <FILTERS> </FILTERS> <MOVERS> </MOVERS> <PROTOCOLS> </PROTOCOLS> <OUTPUT /> </ROSETTASCRIPTS> ``` Anything outside of the \< \> notation is ignored and can be used to comment the xml file ### RosettaScript Example ```xml <ROSETTASCRIPTS> <SCOREFXNS> </SCOREFXNS> <RESIDUE_SELECTORS> <CDR name="L1" cdrs="L1"/> </RESIDUE_SELECTORS> <MOVE_MAP_FACTORIES> <MoveMapFactory name="movemap_L1" bb="0" chi="0"> <Backbone residue_selector="L1" /> <Chi residue_selector="L1" /> </MoveMapFactory> </MOVE_MAP_FACTORIES> <SIMPLE_METRICS> <TimingProfileMetric name="timing" /> <SelectedResiduesMetric name="rosetta_sele" residue_selector="L1" rosetta_numbering="1"/> <SelectedResiduesPyMOLMetric name="pymol_selection" residue_selector="L1" /> <SequenceMetric name="sequence" residue_selector="L1" /> <SecondaryStructureMetric name="ss" residue_selector="L1" /> </SIMPLE_METRICS> <MOVERS> <MinMover name="min_mover" movemap_factory="movemap_L1" tolerance=".1" /> <RunSimpleMetrics name="run_metrics1" metrics="pymol_selection,sequence,ss,rosetta_sele" prefix="m1_" /> <RunSimpleMetrics name="run_metrics2" metrics="timing,ss" prefix="m2_" /> </MOVERS> <PROTOCOLS> <Add mover_name="run_metrics1"/> <Add mover_name="min_mover" /> <Add mover_name="run_metrics2" /> </PROTOCOLS> </ROSETTASCRIPTS> ``` Rosetta will carry out the order of operations specified in PROTOCOLS. An important point is that SimpleMetrics and Filters never change the sequence or conformation of the structure. The movers do change the pose, and the output file will be the result of sequentially applying the movers in the protocols section. The standard scores of the output will be carried over from any protocol doing scoring, unless the OUTPUT tag is specified, in which case the corresponding score function from the SCOREFXNS block will be used. ## RosettaScripts Documentation It is recommended to read up on RosettaScripts here. Note that each type of Rosetta class has a list and documentation of ALL accessible components. This is extremely useful to get an idea of what Rosetta can do and how to use it in PyRosetta. https://www.rosettacommons.org/docs/latest/scripting_documentation/RosettaScripts/RosettaScripts ``` # Notebook setup import sys if 'google.colab' in sys.modules: !pip install pyrosettacolabsetup import pyrosettacolabsetup pyrosettacolabsetup.setup() print ("Notebook is set for PyRosetta use in Colab. Have fun!") ``` ## Running Whole Protocols via RosettaScriptsParser Here we will use a whole the parser to generate a ParsedProtocol (mover). This mover can then be run with the apply method on a pose of interest. Lets run the protocol above. We will be running this on the file itself. ``` from pyrosetta import * from rosetta.protocols.rosetta_scripts import * init('-no_fconfig @inputs/rabd/common') pose = pose_from_pdb("inputs/rabd/my_ab.pdb") original_pose = pose.clone() if not os.getenv("DEBUG"): parser = RosettaScriptsParser() protocol = parser.generate_mover_and_apply_to_pose(pose, "inputs/min_L1.xml") protocol.apply(pose) ``` ## Running via XMLObjects and strings Next, we will use XMLObjects to create a protocol from a string. Note that in-code, XMLOjbects uses special functionality of the `RosettaScriptsParser`. Also note that the `XMLObjects` also has a `create_from_file` method that will take a path to an XML file. ``` pose = original_pose.clone() min_L1 = """ <ROSETTASCRIPTS> <SCOREFXNS> </SCOREFXNS> <RESIDUE_SELECTORS> <CDR name="L1" cdrs="L1"/> </RESIDUE_SELECTORS> <MOVE_MAP_FACTORIES> <MoveMapFactory name="movemap_L1" bb="0" chi="0"> <Backbone residue_selector="L1" /> <Chi residue_selector="L1" /> </MoveMapFactory> </MOVE_MAP_FACTORIES> <SIMPLE_METRICS> <TimingProfileMetric name="timing" /> <SelectedResiduesMetric name="rosetta_sele" residue_selector="L1" rosetta_numbering="1"/> <SelectedResiduesPyMOLMetric name="pymol_selection" residue_selector="L1" /> <SequenceMetric name="sequence" residue_selector="L1" /> <SecondaryStructureMetric name="ss" residue_selector="L1" /> </SIMPLE_METRICS> <MOVERS> <MinMover name="min_mover" movemap_factory="movemap_L1" tolerance=".1" /> <RunSimpleMetrics name="run_metrics1" metrics="pymol_selection,sequence,ss,rosetta_sele" prefix="m1_" /> <RunSimpleMetrics name="run_metrics2" metrics="timing,ss" prefix="m2_" /> </MOVERS> <PROTOCOLS> <Add mover_name="run_metrics1"/> <Add mover_name="min_mover" /> <Add mover_name="run_metrics2" /> </PROTOCOLS> </ROSETTASCRIPTS> """ if not os.getenv("DEBUG"): xml = XmlObjects.create_from_string(min_L1) protocol = xml.get_mover("ParsedProtocol") protocol.apply(pose) ``` ## Constructing Rosetta objects using XMLObjects ### Pulling from whole script Here we will use our previous XMLObject that we setup using our script to pull a specific component from it. Note that while this is very useful for running pre-defined Rosetta objects, we will not have any tab completion for it as it will be a generic type - which means we will be unable to further modify it. Lets grab the residue selector and then see which residues are L1. ``` if not os.getenv("DEBUG"): L1_sele = xml.get_residue_selector("L1") L1_res = L1_sele.apply(pose) for i in range(1, len(L1_res)+1): if L1_res[i]: print("L1 Residue: ", pose.pdb_info().pose2pdb(i), ":", i ) ``` ### Constructing from single section Here, we instead of parsing a whole script, we'll simply create the same L1 selector from the string itself. This can be used for nearly every Rosetta class type in the script. The 'static' part in the name means that we do not have to construct the XMLObject first, we can simply call its function. ``` if not os.getenv("DEBUG"): L1_sele = XmlObjects.static_get_residue_selector('<CDR name="L1" cdrs="L1"/>') L1_res = L1_sele.apply(pose) for i in range(1, len(L1_res)+1): if L1_res[i]: print("L1 Residue: ", pose.pdb_info().pose2pdb(i), ":", i ) ``` Do these residues match what we had before? Why do both of these seem a bit slower? The actual residue selection is extremely quick, but validating the XML against a schema (which checks to make sure the string that you passed is valid and works) takes time. And that's it! That should be everything you need to know about RosettaScripts in PyRosetta. Enjoy! For XMLObjects, each type has a corresponding function (with and without static), these are listed below, but tab completion will help you here. As you have seen above, the static functions are called on the class type, `XmlObjects`, while the non-static objects are called on an instance of the class after parsing a script, in our example, it was called `xml`. ``` .get_score_function / .static_get_score_function .get_residue_selector / .static_get_residue_selector .get_simple_metric / .static_get_simple_metric .get_filter / .static_get_filter .get_mover / .static_get_mover .get_task_operation / .static_get_task_operation ``` <!--NAVIGATION--> < [Visualization with the `PyMOLMover`](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.06-Visualization-and-PyMOL-Mover.ipynb) | [Contents](toc.ipynb) | [Index](index.ipynb) | [Visualization and `pyrosetta.distributed.viewer`](http://nbviewer.jupyter.org/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.08-Visualization-and-pyrosetta.distributed.viewer.ipynb) ><p><a href="https://colab.research.google.com/github/RosettaCommons/PyRosetta.notebooks/blob/master/notebooks/02.07-RosettaScripts-in-PyRosetta.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open in Google Colaboratory"></a>
github_jupyter
<a href="https://githubtocolab.com/giswqs/geemap/blob/master/examples/notebooks/57_cartoee_blend.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a> Uncomment the following line to install [geemap](https://geemap.org) and [cartopy](https://scitools.org.uk/cartopy/docs/latest/installing.html#installing) if needed. Keep in mind that cartopy can be challenging to install. If you are unable to install cartopy on your computer, you can try Google Colab with this the [notebook example](https://colab.research.google.com/github/giswqs/geemap/blob/master/examples/notebooks/cartoee_colab.ipynb). See below the commands to install cartopy and geemap using conda/mamba: ``` conda create -n carto python=3.8 conda activate carto conda install mamba -c conda-forge mamba install cartopy scipy -c conda-forge mamba install geemap -c conda-forge jupyter notebook ``` ``` # !pip install cartopy scipy # !pip install geemap ``` # Creating publication-quality maps with multiple Earth Engine layers ``` import ee import geemap from geemap import cartoee import cartopy.crs as ccrs %pylab inline ``` ## Create an interactive map ``` Map = geemap.Map() image = ( ee.ImageCollection('MODIS/MCD43A4_006_NDVI') .filter(ee.Filter.date('2018-04-01', '2018-05-01')) .select("NDVI") .first() ) vis_params = { 'min': 0.0, 'max': 1.0, 'palette': [ 'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901', '66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01', '012E01', '011D01', '011301', ], } Map.setCenter(-7.03125, 31.0529339857, 2) Map.addLayer(image, vis_params, 'MODIS NDVI') countries = ee.FeatureCollection('users/giswqs/public/countries') style = {"color": "00000088", "width": 1, "fillColor": "00000000"} Map.addLayer(countries.style(**style), {}, "Countries") ndvi = image.visualize(**vis_params) blend = ndvi.blend(countries.style(**style)) Map.addLayer(blend, {}, "Blend") Map ``` ## Plot an image with the default projection ``` # specify region to focus on bbox = [180, -88, -180, 88] fig = plt.figure(figsize=(15, 10)) # plot the result with cartoee using a PlateCarre projection (default) ax = cartoee.get_map(blend, region=bbox) cb = cartoee.add_colorbar(ax, vis_params=vis_params, loc='right') ax.set_title(label='MODIS NDVI', fontsize=15) # ax.coastlines() plt.show() ``` ## Plot an image with a different projection ``` fig = plt.figure(figsize=(15, 10)) projection = ccrs.EqualEarth(central_longitude=-180) # plot the result with cartoee using a PlateCarre projection (default) ax = cartoee.get_map(blend, region=bbox, proj=projection) cb = cartoee.add_colorbar(ax, vis_params=vis_params, loc='right') ax.set_title(label='MODIS NDVI', fontsize=15) # ax.coastlines() plt.show() ```
github_jupyter
# Using the MANN Package to convert and prune an existing TensorFlow model In this notebook, we utilize the MANN package on an existing TensorFlow model to convert existing layers to MANN layers and then prune the model. ``` # Load the MANN package and TensorFlow import tensorflow as tf import mann # Load the data (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar10.load_data() x_train = x_train/255 x_test = x_test/255 # Load the model to be used vgg16 = tf.keras.applications.VGG16( include_top = False, # Don't include the top layers weights = 'imagenet', # Load the imagenet weights input_shape = x_train.shape[1:] # Input shape is the shape of the images ) ``` ## Create the model to be trained In the following cell, we create the model using the existing VGG model fed into fully-connected layers. ``` # Build the model using VGG16 and a few layers on top of it model = tf.keras.models.Sequential() model.add(vgg16) model.add(tf.keras.layers.Flatten()) model.add(tf.keras.layers.Dense(512, activation = 'relu')) model.add(tf.keras.layers.Dense(512, activation = 'relu')) model.add(tf.keras.layers.Dense(512, activation = 'relu')) model.add(tf.keras.layers.Dense(10, activation = 'softmax')) # Compile the model model.compile( loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'], optimizer = 'adam' ) # Present model summary model.summary() ``` ## Convert the model and perform initial pruning In the following cell, we convert the model and perform initial pruning of the model to 40%. ``` # Use the add_layer_masks function to add masking layers to the model converted_model = mann.utils.add_layer_masks(model) # Compile the model converted_model.compile( loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'], optimizer = 'adam' ) # Mask the model using magnitude as the metric converted_model = mann.utils.mask_model( converted_model, 40, method = 'magnitude' ) # Recompile the model for the weights to take effect converted_model.compile( loss = 'sparse_categorical_crossentropy', metrics = ['accuracy'], optimizer = 'adam' ) # Present the model summary converted_model.summary() ``` ## Train and further prune the model In this cell, we create the ActiveSparsification callback and train the model using that callback to prune the model as the model improves in performance. ``` # Create the sparsification callback object callback = mann.utils.ActiveSparsification( performance_cutoff = 0.75, # The accuracy score the model needs to achieve starting_sparsification = 40, # Starting sparsification sparsification_rate = 5 # Sparsification increase every time the model achieves performance cutoff ) # Fit the model model.fit( x_train, y_train, epochs = 1000, callbacks = [callback], validation_split = 0.2, batch_size = 256 ) ``` ## Convert the model back to remove masking layers In the following cell, we remove the layer masks created for training, while completely preserving performance. ``` # Convert the model back model = mann.utils.remove_layer_masks(model) # Present the model model.summary() ``` ## Report accuracy and save model ``` # Get the predictions on test data preds = model.predict(x_test).argmax(axis = 1) # Print the accuracy print(f'Model Accuracy: {(preds.flatten() == y_test.flatten()).sum().astype(int)/y_test.flatten().shape[0]}') # Save the model model.save('cifar_vgg16.h5') ```
github_jupyter
# Demistifying GANs in TensorFlow 2.0 ``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow import keras print(tf.__version__) ``` ## Global Parameters ``` BATCH_SIZE = 256 BUFFER_SIZE = 60000 EPOCHES = 300 OUTPUT_DIR = "img" # The output directory where the images of the generator a stored during training ``` ## Loading the MNIST dataset ``` mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() #train_images[0] (train_images[0].shape) train_images.shape plt.imshow(train_images[1], cmap = "gray") ``` ### Adding the Data to tf.Dataset ``` train_images = train_images.astype("float32") train_images = (train_images - 127.5) / 127.5 train_dataset = tf.data.Dataset.from_tensor_slices(train_images.reshape(train_images.shape[0],784)).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) train_dataset ``` ## Generator Network ``` class Generator(keras.Model): def __init__(self, random_noise_size = 100): super().__init__(name='generator') #layers self.input_layer = keras.layers.Dense(units = random_noise_size) self.dense_1 = keras.layers.Dense(units = 128) self.leaky_1 = keras.layers.LeakyReLU(alpha = 0.01) self.dense_2 = keras.layers.Dense(units = 128) self.leaky_2 = keras.layers.LeakyReLU(alpha = 0.01) self.dense_3 = keras.layers.Dense(units = 256) self.leaky_3 = keras.layers.LeakyReLU(alpha = 0.01) self.output_layer = keras.layers.Dense(units=784, activation = "tanh") def call(self, input_tensor): ## Definition of Forward Pass x = self.input_layer(input_tensor) x = self.dense_1(x) x = self.leaky_1(x) x = self.dense_2(x) x = self.leaky_2(x) x = self.dense_3(x) x = self.leaky_3(x) return self.output_layer(x) def generate_noise(self,batch_size, random_noise_size): return np.random.uniform(-1,1, size = (batch_size, random_noise_size)) ``` ### Objective Function ``` cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits = True) def generator_objective(dx_of_gx): # Labels are true here because generator thinks he produces real images. return cross_entropy(tf.ones_like(dx_of_gx), dx_of_gx) ``` ### Plotting The Noise (Fake Image) ``` generator = Generator() fake_image = generator(np.random.uniform(-1,1, size =(1,100))) fake_image = tf.reshape(fake_image, shape = (28,28)) plt.imshow(fake_image, cmap = "gray") ``` ## Discriminator Network ``` class Discriminator(keras.Model): def __init__(self): super().__init__(name = "discriminator") #Layers self.input_layer = keras.layers.Dense(units = 784) self.dense_1 = keras.layers.Dense(units = 128) self.leaky_1 = keras.layers.LeakyReLU(alpha = 0.01) self.dense_2 = keras.layers.Dense(units = 128) self.leaky_2 = keras.layers.LeakyReLU(alpha = 0.01) self.dense_3 = keras.layers.Dense(units = 128) self.leaky_3 = keras.layers.LeakyReLU(alpha = 0.01) self.logits = keras.layers.Dense(units = 1) # This neuron tells us if the input is fake or real def call(self, input_tensor): ## Definition of Forward Pass x = self.input_layer(input_tensor) x = self.dense_1(x) x = self.leaky_1(x) x = self.leaky_2(x) x = self.leaky_3(x) x = self.leaky_3(x) x = self.logits(x) return x discriminator = Discriminator() ``` ### Objective Function ``` def discriminator_objective(d_x, g_z, smoothing_factor = 0.9): """ d_x = real output g_z = fake output """ real_loss = cross_entropy(tf.ones_like(d_x) * smoothing_factor, d_x) # If we feed the discriminator with real images, we assume they all are the right pictures --> Because of that label == 1 fake_loss = cross_entropy(tf.zeros_like(g_z), g_z) # Each noise we feed in are fakes image --> Because of that labels are 0 total_loss = real_loss + fake_loss return total_loss ``` ## Optimizer ``` generator_optimizer = keras.optimizers.RMSprop() discriminator_optimizer = keras.optimizers.RMSprop() ``` ## Training Functions ``` @tf.function() def training_step(generator: Discriminator, discriminator: Discriminator, images:np.ndarray , k:int =1, batch_size = 32): for _ in range(k): with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: noise = generator.generate_noise(batch_size, 100) g_z = generator(noise) d_x_true = discriminator(images) # Trainable? d_x_fake = discriminator(g_z) # dx_of_gx discriminator_loss = discriminator_objective(d_x_true, d_x_fake) # Adjusting Gradient of Discriminator gradients_of_discriminator = disc_tape.gradient(discriminator_loss, discriminator.trainable_variables) discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables)) # Takes a list of gradient and variables pairs generator_loss = generator_objective(d_x_fake) # Adjusting Gradient of Generator gradients_of_generator = gen_tape.gradient(generator_loss, generator.trainable_variables) generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables)) seed = np.random.uniform(-1,1, size = (1, 100)) # generating some noise for the training # Just to make sure the output directory exists.. import os directory=OUTPUT_DIR if not os.path.exists(directory): os.makedirs(directory) def training(dataset, epoches): for epoch in range(epoches): for batch in dataset: training_step(generator, discriminator, batch ,batch_size = BATCH_SIZE, k = 1) ## After ith epoch plot image if (epoch % 50) == 0: fake_image = tf.reshape(generator(seed), shape = (28,28)) print("{}/{} epoches".format(epoch, epoches)) #plt.imshow(fake_image, cmap = "gray") plt.imsave("{}/{}.png".format(OUTPUT_DIR,epoch),fake_image, cmap = "gray") %%time training(train_dataset, EPOCHES) ``` ## Testing the Generator ``` fake_image = generator(np.random.uniform(-1,1, size = (1, 100))) plt.imshow(tf.reshape(fake_image, shape = (28,28)), cmap="gray") ``` ## Obsolete Training Function I tried to implement the training step with the k factor as described in the original paper. I achieved much worse results as with the function above. Maybe i did something wrong?! @tf.function() def training_step(generator: Discriminator, discriminator: Discriminator, images:np.ndarray , k:int =1, batch_size = 256): for _ in range(k): with tf.GradientTape() as disc_tape: noise = generator.generate_noise(batch_size, 100) g_z = generator(noise) d_x_true = discriminator(images) # Trainable? d_x_fake = discriminator(g_z) # dx_of_gx discriminator_loss = discriminator_objective(d_x_true, d_x_fake, smoothing_factor=0.9) # Adjusting Gradient of Discriminator gradients_of_discriminator = disc_tape.gradient(discriminator_loss, discriminator.trainable_variables) discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables)) # Takes a list of gradient and variables pairs with tf.GradientTape() as gen_tape: noise = generator.generate_noise(batch_size, 100) d_x_fake = discriminator(generator(noise)) generator_loss = generator_objective(d_x_fake) # Adjusting Gradient of Generator gradients_of_generator = gen_tape.gradient(generator_loss, generator.trainable_variables) generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables)) ``` ```
github_jupyter
<a href="https://colab.research.google.com/github/christianhidber/easyagents/blob/master/jupyter_notebooks/intro_cartpole.ipynb" target="_parent"> <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/> </a> # CartPole Gym environment with TfAgents ## Install packages (gym, tfagents, tensorflow,....) #### suppress package warnings, prepare matplotlib, if in colab: load additional packages for rendering ``` %matplotlib inline import matplotlib.pyplot as plt import sys import warnings warnings.filterwarnings('ignore') if 'google.colab' in sys.modules: !apt-get update >/dev/null !apt-get install xvfb >/dev/null !pip install pyvirtualdisplay >/dev/null from pyvirtualdisplay import Display Display(visible=0, size=(960, 720)).start() else: # for local installation sys.path.append('..') ``` #### install easyagents ``` import sys if 'google.colab' in sys.modules: !pip install easyagents >/dev/null ``` The fc_layers argument defines the policy's neural network architecture. Here we use 3 fully connected layers with 100 neurons in the first, 50 in the second and 25 in the final layer. By default fc_layers=(75,75) is used. The first argument of the train method is a list of callbacks. Through callbacks we define the plots generated during training, the logging behaviour or control training duration. By passing [plot.State(), plot.Loss(), plot.Actions(), plot.Rewards()] we add in particular the State() plot, depicting the last observation state of the last evaluation episode. plot.Actions() displays a histogram of the actions taken for each episode played during the last evaluation period. Besides num_iterations there are quite a few parameters to specify the exact training duration (e.g. num_episodes_per_iteration, num_epochs_per_iteration, max_steps_per_episode,...). ## Switching the algorithm Switching from Ppo to Dqn is easy, essentially just replace PpoAgent with DqnAgent (the evaluation may take a few minuites): ``` from easyagents.agents import DqnAgent from easyagents.callbacks import plot %%time dqnAgent = DqnAgent('CartPole-v0', fc_layers=(100, )) dqnAgent.train([plot.State(), plot.Loss(), plot.Actions(), plot.Rewards()], num_iterations=20000, num_iterations_between_eval=1000) ``` Since Dqn by default only takes 1 step per iteration (and thus an episode spans over several iterations) we increased the num_iterations parameter. ## Next: custom training, creating a movie & switching backends. * see [Orso on colab](https://colab.research.google.com/github/christianhidber/easyagents/blob/master/jupyter_notebooks/intro_orso.ipynb) (an example of a gym environment implementation based on a routing problem)
github_jupyter
Tutorials table of content: - [Tutorial 1: Run a first scenario](./Tutorial-1_Run_your_first_scenario.ipynb) - [Tutorial 2: Add contributivity measurements methods](./Tutorial-2_Add_contributivity_measurement.ipynb) - Tutorial 3: Use a custom dataset # Tutorial 3 : Use homemade dataset With this example, we dive deeper into the potential of the library, and run a scenario on a new dataset, that we will implement ## 1 - Prerequisites In order to run this example, you'll need to: * use python 3.7 + * install this package https://pypi.org/project/mplc/ If you did not follow our firsts tutorials, it is highly recommended to [take a look at it !](https://github.com/SubstraFoundation/distributed-learning-contributivity/tree/master/notebooks/examples/) ``` !pip install mplc ``` ## 2 - Context In collaborative data science projects partners sometimes need to train a model on multiple datasets, contributed by different data providing partners. In such cases the partners might have to measure how much each dataset involved contributed to the performance of the model. This is useful for example as a basis to agree on how to share the reward of the ML challenge or the future revenues derived from the predictive model, or to detect possible corrupted datasets or partners not playing by the rules. The library explores this question and the opportunity to implement some mechanisms helping partners in such scenarios to measure each dataset's *contributivity* (as *contribution to the performance of the model*). In the [first tutorial](./Tutorial-1_Run_your_first_scenario.ipynb), you learned how to parametrize and run a scenario. In the [second tutorial](./Tutorial-2_Add_contributivity_measurement.ipynb), you discovered how to add to your scenario run one of the contributivity measurement methods available. In this third tutorial, we are going to use a custom dataset. ### The dataset : Sentiment140 We are going to use a subset of the [sentiment140](http://help.sentiment140.com/for-students) dataset and try to classified short film review, between positive sentiments and negative sentiments for movies. *The whole machine learning process is inspired from this [article](https://medium.com/@alyafey22/sentiment-classification-from-keras-to-the-browser-7eda0d87cdc6)* Please note that the library provided a really easy way to adapt a single partner, common machine learning use case with tensorflow, to a multipartner case, with contributivity measurement. ``` # imports import seaborn as sns import pandas as pd import numpy as np from sklearn.model_selection import train_test_split import re from keras.models import Sequential from keras.layers import Dense, GRU, Embedding from mplc.dataset import Dataset from mplc.scenario import Scenario sns.set() ``` ## 3 - Generation, and preparation of the dataset The scenario object needs a dataset object to run. In the previous tutorials, we indicate which one to generate automatically by passing a name of a pre-implemented dataset to the scenario constructor. Here, we will create this dataset object and pass it to the scenario constructor. To do so, we are going to create a new class, which inherit from the mplc.Dataset abstract class. A sub-class of Dataset needs few attribute and method. First, the constructor of the Dataset object needs few arguments. ### Dataset generator : The structure of the dataset generator is represented below: ```python dataset = Dataset( "name", x_train, x_test, y_train, y_test, input_shape, num_classes, ) ``` #### Data labels The data labels can take whatever shape you need, with only one condition. The labels need to be convertible into string format, and with respect to the condition that if label1 is equal to label2 ( reciprocally different from), therefore str(label1) must be equal to str(label2) (reciprocally different from) #### Model generator This method needs to be implemented, and provides the model use, which will be trained by the `Scenario` object. Note: It is mandatory to have loss and accuracy as metrics for your model. #### Train/validation/test splits The `Dataset` constructor (called via `super()`) must be provided some separated train and test sets (referred to as global train set and global test set). The global train set is then further split into a global train set and a global validation set, by the function `train_val_split_global`. Please denote that if this function is not overwritten, the sklearn's `train_test_split` function will be called by default, and 10% of the training set will be use as validation set. In the multi-partner learning computations, the global validation set is used for early stopping and the global test set is used for performance evaluation. The global train set is then split amongst partners (according to the scenario configuration) to populate the partner's local datasets. For each partner, the local dataset will be split into separated train, validation and test sets, using the `train_test_split_local` and `train_val_split_local` methods. These are not mandatory, by default the local dataset will not be split. Denote that currently, the local validation and test set are not used, but they are available for further developments of multi-partner learning and contributivity measurement approaches. ### Dataset construction Now that we know all of that, we can create our dataset class. #### Download and unzip data if needed ``` !curl https://cs.stanford.edu/people/alecmgo/trainingandtestdata.zip --output trainingandtestdata.zip !unzip trainingandtestdata.zip ``` #### Define our Dataset class ``` class Sentiment140(Dataset): def __init__(self): x, y = self.load_data() self.max_tokens = self.getMax(x) self.num_words = None self.word_index = self.tokenize() self.num_words = len(self.word_index) x = self.create_sequences(x) y = self.preprocess_dataset_labels(y) self.input_shape = self.max_tokens self.num_classes = len(np.unique(y)) print('length of the dictionary ',len(self.word_index)) print('max token ', self.max_tokens) print('num classes', self.num_classes) (x_train, x_test) = train_test_split(x, shuffle = False) (y_train, y_test) = train_test_split(y, shuffle = False) super(Sentiment140, self).__init__(dataset_name='sentiment140', num_classes=self.num_classes, input_shape=self.input_shape, x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test) @staticmethod def load_data(): # load the data, transform the .csv into usable dataframe df_train = pd.read_csv("training.1600000.processed.noemoticon.csv", encoding = "raw_unicode_escape", header=None) df_test = pd.read_csv("testdata.manual.2009.06.14.csv", encoding = "raw_unicode_escape", header=None) df_train.columns = ["polarity", "id", "date", "query", "user", "text"] df_test.columns = ["polarity", "id", "date", "query", "user", "text"] # We keep only a fraction of the whole dataset df_train = df_train.sample(frac = 0.1) x = df_train["text"] y = df_train["polarity"] return x, y # Preprocessing methods @staticmethod def process( txt): out = re.sub(r'[^a-zA-Z0-9\s]', '', txt) out = out.split() out = [word.lower() for word in out] return out @staticmethod def getMax( data): max_tokens = 0 for txt in data: if max_tokens < len(txt.split()): max_tokens = len(txt.split()) return max_tokens def tokenize(self, thresh = 5): count = dict() idx = 1 word_index = dict() for txt in x: words = self.process(txt) for word in words: if word in count.keys(): count[word] += 1 else: count[word] = 1 most_counts = [word for word in count.keys() if count[word]>=thresh] for word in most_counts: word_index[word] = idx idx+=1 return word_index def create_sequences(self,data): tokens = [] for txt in data: words = self.process(txt) seq = [0] * self.max_tokens i = 0 for word in words: start = self.max_tokens-len(words) if word.lower() in self.word_index.keys(): seq[i+start] = self.word_index[word] i+=1 tokens.append(seq) return np.array(tokens) @staticmethod def preprocess_dataset_labels( label): label = np.array([e/4 for e in label]) return label def generate_new_model(self): # Define the model generator model = Sequential() embedding_size = 8 model.add(Embedding(input_dim=self.num_words, output_dim=embedding_size, input_length=self.max_tokens, name='layer_embedding')) model.add(GRU(units=16, name = "gru_1",return_sequences=True)) model.add(GRU(units=8, name = "gru_2" ,return_sequences=True)) model.add(GRU(units=4, name= "gru_3")) model.add(Dense(1, activation='sigmoid',name="dense_1")) model.compile(loss='binary_crossentropy', optimizer="Adam", metrics=['accuracy']) return model ``` #### Create dataset And we can eventually generate our object! ``` my_dataset = Sentiment140() ## 4 - Create the custom scenario The dataset can be passed to the scenario, through the `dataset` argument. ``` # That's it! Now you can explore our other tutorials for a better overview of what can be done with `mplc`! This work is collaborative, enthusiasts are welcome to comment open issues and PRs or open new ones. Should you be interested in this open effort and would like to share any question, suggestion or input, you can use the following channels: - This Github repository (issues or PRs) - Substra Foundation's [Slack workspace](https://substra-workspace.slack.com/join/shared_invite/zt-cpyedcab-FHYgpy08efKJ2FCadE2yCA), channel `#workgroup-mpl-contributivity` - Email: hello@substra.org ![logo Substra Foundation](../../img/substra_logo_couleur_rvb_w150px.png)
github_jupyter
# Programming and Database Fundamentals for Data Scientists - EAS503 Python classes and objects. In this notebook we will discuss the notion of classes and objects, which are a fundamental concept. Using the keyword `class`, one can define a class. Before learning about how to define classes, we will first understand the need for defining classes. ### A Simple Banking Application Read data from `csv` files containing customer and account information and find all customers with more than \$25,000 in their bank account, and send a letter to them with some scheme (find their address). ``` # Logical design import csv # load customer information customerMap = {} with open('customers.csv','r') as f: rd = csv.reader(f) next(rd) for row in rd: customerMap[int(row[0])] = (row[1],row[2]) # load account information accountsMap = {} with open('accounts.csv','r') as f: rd = csv.reader(f) next(rd) for row in rd: if int(row[1]) not in accountsMap.keys(): accountsMap[int(row[1])] = [] l = accountsMap[int(row[1])] l.append(int(row[2])) accountsMap[int(row[1])] = l customerMap accountsMap for k in accountsMap.keys(): if sum(accountsMap[k]) > 25000: print(customerMap[k]) # OOD class Customer: def __init__(self, customerid, name, address): self.__name = name self.__customerid = customerid self.__address = address self.__accounts = [] def add_account(self,account): self.__accounts.append(account) def get_total(self): s = 0 for a in self.__accounts: s = s + a.get_amount() return s def get_name(self): return self.__name class Account: def __init__(self,accounttype,amount): self.__accounttype = accounttype self.__amount = amount def get_amount(self): return self.__amount import csv customers = {} with open('./customers.csv') as f: reader = csv.reader(f) next(reader) for row in reader: customer = Customer(row[0],row[1],row[2]) customers[row[0]] = customer with open('./accounts.csv') as f: reader = csv.reader(f) next(reader) for row in reader: customerid = row[1] account = Account(row[0],int(row[2])) customers[customerid].add_account(account) for c in customers.keys(): if customers[c].get_total() > 25000: print(customers[c].get_name()) ``` ## Defining Classes More details about `class` definition ``` # this class has no __init__ function class myclass: def mymethod_myclass(self): print("hey") myobj = myclass() myobj.mymethod_myclass() # this class has no __init__ function class myclass: # we define a field __classtype='My Class' def mymethod(self): print("This is "+self.__classtype) def getClasstype(self): return self.__classtype # making fields private myobj = myclass() myobj.mymethod() print(myobj.getClasstype()) myobj = myclass() myobj.mymethod() # this class has not __init__ function class myclass: # we define a global field classtype='My Class' def mymethod(self): print("this is a method") self.a = 'g' #print("This is "+self.classtype) # note that we are explicitly referencing the field of the class def mymethod2(self): print("This is"+self.classtype) print(self.a) m = myclass() m.mymethod() type(m) myobj = myclass() myobj.mymethod() myobj.mymethod2() ``` #### Issues with defining fields outside the `__init__` function If global field is mutable ``` # this class has not __init__ function class myclass: # we define a field version='1.0.1' classtypes=['int'] def __init__(self): self.a = ['m'] def mymethod(self): print(self.classtypes) # note that we are explicitly referencing the field of the class print(self.a) def mystaticmethod(): print('This class is open source') myobj1 = myclass() myobj2 = myclass() myobj1.mymethod() myobj2.mymethod() myobj1.classtypes.append('float') myobj1.a.append('n') myobj1.mymethod() myobj2.mymethod() ``` #### How to avoid the above issue? Define mutable fields within `__init__` ``` # this class has an __init__ function class myclass: def __init__(self): # we define a field self.classtypes=['int'] def mymethod(self): print(self.classtypes) # note that we are explicitly referencing the field of the class myobj1 = myclass() myobj2 = myclass() myobj1.mymethod() myobj2.mymethod() myobj1.classtypes.append('float') myobj1.mymethod() myobj2.mymethod() # you can directly access the field myobj1.mymethod() ``` #### Hide fields from external use ``` class account: def __init__(self,u,p): self.username = u self.password = p act = account('chandola','chandola') print(act.password) class account: def __init__(self,u,p): self.__username = u self.__password = p def getUsername(self): return self.__username def checkPassword(self,p): if p == self.__getPassword(): return True else: return False def __getPassword(self): return self.__password act = account('chandola','chandola') print(act.getUsername()) print(act.checkPassword('chandola')) print(act.__getPassword()) # this class has an __init__ function class myclass: def __init__(self): # we define a field self.__classtypes=['int'] myobj1 = myclass() myobj1.__classtypes # the private field will be accessible to the class methods class myclass: def __init__(self): # we define a field self.__classtypes=['int'] def appendType(self,newtype): self.__classtypes.append(newtype) myobj1 = myclass() myobj1.appendType('float') # still cannot access the field outside myobj1.__classtypes # solution -- create a getter method class myclass: def __init__(self): # we define a field self.__classtypes=['int'] def appendType(self,newtype): self.__classtypes.append(newtype) def getClasstypes(self): return self.__classtypes myobj1 = myclass() myobj1.appendType('float') myobj1.getClasstypes() print(['s','g','h']) ``` One can create `getter` and `setter` methods to manipulate fields. While the name of the methods can be arbitrary, a good programming practice is to use get`FieldNameWithoutUnderscores()` and set`FieldNameWithoutUnderscores()` ## Inheritance in Python Ability to define subclasses. Let us assume that we want to have defined a class called `Employee` that has some information about a bank employee and some supporting methods. ``` class Employee: def __init__(self,firstname,lastname,empid): self.__firstname = firstname self.__lastname = lastname self.__empid = empid # following is a special function used by the Python in-built print() function def __str__(self): return "Employee name is "+self.__firstname+" "+self.__lastname def checkid(self,inputid): if inputid == self.__empid: return True else: return False def getfirstname(self): return self.__firstname def getlastname(self): return self.__lastname emp1 = Employee("Homer","Simpson",777) print(emp1) print(emp1.checkid(777)) ``` Now we want to create a new class called `Manager` which retains some properties of an `Employee` buts add some more ``` class Manager(Employee): def __init__(self,firstname,lastname,empid): super().__init__(firstname,lastname,empid) mng1 = Manager("Charles","Burns",666) print(mng1) ``` But we want to add extra fields and set them in the constructor ``` class Manager(Employee): def __init__(self,firstname,lastname,empid,managerid): super().__init__(firstname,lastname,empid) self.__managerid = managerid def checkmanagerid(self,inputid): if inputid == self.__managerid: return True else: return False mng1 = Manager("Charles","Burns",666,111) print(mng1) mng1.checkid(666) mng1.checkmanagerid(111) ``` You can modify methods of base classes ``` class Manager(Employee): def __init__(self,firstname,lastname,empid,managerid): super().__init__(firstname,lastname,empid) self.__managerid = managerid def checkmanagerid(self,inputid): if inputid == self.__managerid: return True else: return False def __str__(self): # why will the first line not work and the second one will #return "Manager name is "+self.__firstname+" "+self.__lastname return "Manager name is "+self.getfirstname()+" "+self.getlastname() mng1 = Manager("Charles","Burns",666,111) print(mng1) ``` **Remember** - Derived classes cannot access private fields of the base class directly ### Inheriting from multiple classes Consider a scenario where you have additional class, `Citizen`, that has other information about a person. Can we create a derived class that inherits properties of both `Employee` and `Citizen` class? ``` class Citizen: def __init__(self,ssn,homeaddress): self.__ssn = ssn self.__homeaddress = homeaddress def __str__(self): return "Person located at "+self.__homeaddress ctz1 = Citizen("123-45-6789","742 Evergreen Terrace") print(ctz1) # it is easy class Manager2(Employee,Citizen): def __init__(self,firstname,lastname,empid,managerid,ssn,homeaddress): Citizen.__init__(self,ssn,homeaddress) Employee.__init__(self,firstname,lastname,empid) self.__managerid = managerid def __str__(self): return "Manager name is "+Employee.getfirstname(self)+" "+Employee.getlastname(self)+", "+Citizen.__str__(self) mgr2 = Manager2("Charles","Burns",666,111,"123-45-6789","742 Evergreen Terrace") print(mgr2) ```
github_jupyter
# BigQuery ML models with feature engineering In this notebook, we will use BigQuery ML to build more sophisticated models for taxifare prediction. This is a continuation of our [first models](../../02_bqml/solution/first_model.ipynb) we created earlier with BigQuery ML but now with more feature engineering. ## Learning Objectives 1. Create and train a new Linear Regression model with BigQuery ML 2. Evaluate and predict with the linear model 3. Apply transformations using SQL to prune the taxi cab dataset 4. Create a feature cross for day-hour combination using SQL 5. Examine ways to reduce model overfitting with regularization 6. Create and train a DNN model with BigQuery ML Each learning objective will correspond to a __#TODO__ in this student lab notebook -- try to complete this notebook first and then review the [solution notebook](../solution/feateng_bqml.ipynb). ``` %%bash export PROJECT=$(gcloud config list project --format "value(core.project)") echo "Your current GCP Project Name is: "$PROJECT import os PROJECT = "your-gcp-project-here" # REPLACE WITH YOUR PROJECT NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["REGION"] = REGION os.environ["BUCKET"] = PROJECT # DEFAULT BUCKET WILL BE PROJECT ID if PROJECT == "your-gcp-project-here": print("Don't forget to update your PROJECT name! Currently:", PROJECT) ``` ## Create a BigQuery Dataset and Google Cloud Storage Bucket A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called __serverlessml__ if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too. ``` %%bash ## Create a BigQuery dataset for serverlessml if it doesn't exist datasetexists=$(bq ls -d | grep -w serverlessml) if [ -n "$datasetexists" ]; then echo -e "BigQuery dataset already exists, let's not recreate it." else echo "Creating BigQuery dataset titled: serverlessml" bq --location=US mk --dataset \ --description 'Taxi Fare' \ $PROJECT:serverlessml echo "\nHere are your current datasets:" bq ls fi ## Create GCS bucket if it doesn't exist already... exists=$(gsutil ls -d | grep -w gs://${PROJECT}/) if [ -n "$exists" ]; then echo -e "Bucket exists, let's not recreate it." else echo "Creating a new GCS bucket." gsutil mb -l ${REGION} gs://${PROJECT} echo "\nHere are your current buckets:" gsutil ls fi ``` ## Model 4: With some transformations BigQuery ML automatically scales the inputs. so we don't need to do scaling, but human insight can help. Since we we'll repeat this quite a bit, let's make a dataset with 1 million rows. ``` %%bigquery CREATE OR REPLACE TABLE serverlessml.feateng_training_data AS SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_datetime, 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` # The full dataset has 1+ Billion rows, let's take only 1 out of 1,000 (or 1 Million total) WHERE ABS(MOD(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING)), 1000)) = 1 # placeholder for additional filters as part of TODO 3 later %%bigquery # Tip: You can CREATE MODEL IF NOT EXISTS as well CREATE OR REPLACE MODEL serverlessml.model4_feateng TRANSFORM( * EXCEPT(pickup_datetime) , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean , CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek , CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday ) # TODO 1: Specify the BigQuery ML options for a linear model to predict fare amount # OPTIONS() AS SELECT * FROM serverlessml.feateng_training_data ``` Once the training is done, visit the [BigQuery Cloud Console](https://console.cloud.google.com/bigquery) and look at the model that has been trained. Then, come back to this notebook. Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We can look at eval statistics on that held-out data: ``` %%bigquery SELECT *, SQRT(loss) AS rmse FROM ML.TRAINING_INFO(MODEL serverlessml.model4_feateng) %%bigquery # TODO 2: Evaluate and predict with the linear model # Write a SQL query to take the SQRT() of the Mean Squared Error as your loss metric for evaluation # Hint: Use ML.EVALUATE on your newly trained model ``` What is the RMSE? Could we do any better? Try re-creating the above feateng_training_data table with additional filters and re-running training and evaluation. ### TODO 3: Apply transformations using SQL to prune the taxi cab dataset Now let's reduce the noise in our training dataset by only training on trips with a non-zero distance and fares above $2.50. Additionally, we will apply some geo location boundaries for New York City. Copy the below into your previous feateng_training_data table creation and re-train your model. ```sql AND 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 ``` Yippee! We're now below our target of 6 dollars in RMSE. We are now beating our goals, and with just a linear model. ## Making predictions with BigQuery ML This is how the prediction query would look that we saw earlier [heading 1.3 miles uptown](https://www.google.com/maps/dir/'40.742104,-73.982683'/'40.755174,-73.983766'/@40.7481394,-73.993579,15z/data=!3m1!4b1!4m9!4m8!1m3!2m2!1d-73.982683!2d40.742104!1m3!2m2!1d-73.983766!2d40.755174) in New York City. ``` %%bigquery SELECT * FROM ML.PREDICT(MODEL serverlessml.model4_feateng, ( SELECT -73.982683 AS pickuplon, 40.742104 AS pickuplat, -73.983766 AS dropofflon, 40.755174 AS dropofflat, 3.0 AS passengers, TIMESTAMP('2019-06-03 04:21:29.769443 UTC') AS pickup_datetime )) ``` ## Improving the model with feature crosses Let's do a [feature cross](https://developers.google.com/machine-learning/crash-course/feature-crosses/video-lecture) of the day-hour combination instead of using them raw ``` %%bigquery CREATE OR REPLACE MODEL serverlessml.model5_featcross TRANSFORM( * EXCEPT(pickup_datetime) , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean # TODO 4: Create a feature cross for day-hour combination using SQL , ML.( # <--- Enter the correct function for a BigQuery ML feature cross ahead of the ( STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek, CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday) ) AS day_hr ) OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg') AS SELECT * FROM serverlessml.feateng_training_data %%bigquery SELECT *, SQRT(loss) AS rmse FROM ML.TRAINING_INFO(MODEL serverlessml.model5_featcross) %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model5_featcross) ``` Sometimes (not the case above), the training RMSE is quite reasonable, but the evaluation RMSE is terrible. This is an indication of overfitting. When we do feature crosses, we run into the risk of overfitting (for example, when a particular day-hour combo doesn't have enough taxirides). ## Reducing overfitting Let's add [L2 regularization](https://developers.google.com/machine-learning/glossary/#L2_regularization) to help reduce overfitting. Let's set it to 0.1 ``` %%bigquery CREATE OR REPLACE MODEL serverlessml.model6_featcross_l2 TRANSFORM( * EXCEPT(pickup_datetime) , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean , ML.FEATURE_CROSS(STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek, CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday)) AS day_hr ) # TODO 5: Set the model options for a linear regression model to predict fare amount with 0.1 L2 Regularization # Tip: Refer to the documentation for syntax: # https://cloud.google.com/bigquery-ml/docs/reference/standard-sql/bigqueryml-syntax-create OPTIONS() AS SELECT * FROM serverlessml.feateng_training_data %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model6_featcross_l2) ``` These sorts of experiment would have taken days to do otherwise. We did it in minutes, thanks to BigQuery ML! The advantage of doing all this in the TRANSFORM is the client code doing the PREDICT doesn't change. Our model improvement is transparent to client code. ``` %%bigquery SELECT * FROM ML.PREDICT(MODEL serverlessml.model6_featcross_l2, ( SELECT -73.982683 AS pickuplon, 40.742104 AS pickuplat, -73.983766 AS dropofflon, 40.755174 AS dropofflat, 3.0 AS passengers, TIMESTAMP('2019-06-03 04:21:29.769443 UTC') AS pickup_datetime )) ``` ## Let's try feature crossing the locations too Because the lat and lon by themselves don't have meaning, but only in conjunction, it may be useful to treat the fields as a pair instead of just using them as numeric values. However, lat and lon are continuous numbers, so we have to discretize them first. That's what ML.BUCKETIZE does. Here are some of the preprocessing functions in BigQuery ML: * ML.FEATURE_CROSS(STRUCT(features)) does a feature cross of all the combinations * ML.POLYNOMIAL_EXPAND(STRUCT(features), degree) creates x, x^2, x^3, etc. * ML.BUCKETIZE(f, split_points) where split_points is an array ``` %%bigquery -- BQML chooses the wrong gradient descent strategy here. It will get fixed in (b/141429990) -- But for now, as a workaround, explicitly specify optimize_strategy='BATCH_GRADIENT_DESCENT' CREATE OR REPLACE MODEL serverlessml.model7_geo TRANSFORM( fare_amount , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean , ML.FEATURE_CROSS(STRUCT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING) AS dayofweek, CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING) AS hourofday), 2) AS day_hr , CONCAT( ML.BUCKETIZE(pickuplon, GENERATE_ARRAY(-78, -70, 0.01)), ML.BUCKETIZE(pickuplat, GENERATE_ARRAY(37, 45, 0.01)), ML.BUCKETIZE(dropofflon, GENERATE_ARRAY(-78, -70, 0.01)), ML.BUCKETIZE(dropofflat, GENERATE_ARRAY(37, 45, 0.01)) ) AS pickup_and_dropoff ) OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg', l2_reg=0.1, optimize_strategy='BATCH_GRADIENT_DESCENT') AS SELECT * FROM serverlessml.feateng_training_data %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model7_geo) ``` Yippee! We're now below our target of 6 dollars in RMSE. ## DNN You could, of course, train a more sophisticated model. Change "linear_reg" above to "dnn_regressor" and see if it improves things. __Note: This takes 20 - 25 minutes to run.__ ``` %%bigquery -- This is alpha and may not work for you. CREATE OR REPLACE MODEL serverlessml.model8_dnn TRANSFORM( fare_amount , ST_Distance(ST_GeogPoint(pickuplon, pickuplat), ST_GeogPoint(dropofflon, dropofflat)) AS euclidean , CONCAT(CAST(EXTRACT(DAYOFWEEK FROM pickup_datetime) AS STRING), CAST(EXTRACT(HOUR FROM pickup_datetime) AS STRING)) AS day_hr , CONCAT( ML.BUCKETIZE(pickuplon, GENERATE_ARRAY(-78, -70, 0.01)), ML.BUCKETIZE(pickuplat, GENERATE_ARRAY(37, 45, 0.01)), ML.BUCKETIZE(dropofflon, GENERATE_ARRAY(-78, -70, 0.01)), ML.BUCKETIZE(dropofflat, GENERATE_ARRAY(37, 45, 0.01)) ) AS pickup_and_dropoff ) -- at the time of writing, l2_reg wasn't supported yet. # TODO 6: Create a DNN model (dnn_regressor) with hidden_units [32,8] OPTIONS() AS SELECT * FROM serverlessml.feateng_training_data %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model8_dnn) ``` We really need the L2 reg (recall that we got 4.77 without the feateng). It's time to do [Feature Engineering in Keras](../../06_feateng_keras/labs/taxifare_fc.ipynb). Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
github_jupyter
# Tutorial 11: Normalizing Flows for image modeling ![Status](https://img.shields.io/static/v1.svg?label=Status&message=Finished&color=green) **Filled notebook:** [![View notebook on Github](https://img.shields.io/static/v1.svg?logo=github&label=Repo&message=View%20On%20Github&color=lightgrey)](https://github.com/phlippe/uvadlc_notebooks/blob/master/docs/tutorial_notebooks/tutorial11/NF_image_modeling.ipynb) [![Open In Collab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/phlippe/uvadlc_notebooks/blob/master/docs/tutorial_notebooks/tutorial11/NF_image_modeling.ipynb) **Pre-trained models:** [![View files on Github](https://img.shields.io/static/v1.svg?logo=github&label=Repo&message=View%20On%20Github&color=lightgrey)](https://github.com/phlippe/saved_models/tree/main/tutorial11) [![GoogleDrive](https://img.shields.io/static/v1.svg?logo=google-drive&logoColor=yellow&label=GDrive&message=Download&color=yellow)](https://drive.google.com/drive/folders/1gttZ5DSrpKwn9g3RcizqA5qG7NFLMgvv?usp=sharing) **Recordings:** [![YouTube - Part 1](https://img.shields.io/static/v1.svg?logo=youtube&label=YouTube&message=Part%201&color=red)](https://youtu.be/U1fwesIusbg) [![YouTube - Part 2](https://img.shields.io/static/v1.svg?logo=youtube&label=YouTube&message=Part%202&color=red)](https://youtu.be/qMoGcRhVrF8) [![YouTube - Part 3](https://img.shields.io/static/v1.svg?logo=youtube&label=YouTube&message=Part%203&color=red)](https://youtu.be/YoAWiaEt41Y) [![YouTube - Part 4](https://img.shields.io/static/v1.svg?logo=youtube&label=YouTube&message=Part%204&color=red)](https://youtu.be/nTyDvn-ADJ4) **Author:** Phillip Lippe In this tutorial, we will take a closer look at complex, deep normalizing flows. The most popular, current application of deep normalizing flows is to model datasets of images. As for other generative models, images are a good domain to start working on because (1) CNNs are widely studied and strong models exist, (2) images are high-dimensional and complex, and (3) images are discrete integers. In this tutorial, we will review current advances in normalizing flows for image modeling, and get hands-on experience on coding normalizing flows. Note that normalizing flows are commonly parameter heavy and therefore computationally expensive. We will use relatively simple and shallow flows to save computational cost and allow you to run the notebook on CPU, but keep in mind that a simple way to improve the scores of the flows we study here is to make them deeper. Throughout this notebook, we make use of [PyTorch Lightning](https://pytorch-lightning.readthedocs.io/en/latest/). The first cell imports our usual libraries. ``` ## Standard libraries import os import math import time import numpy as np ## Imports for plotting import matplotlib.pyplot as plt %matplotlib inline from IPython.display import set_matplotlib_formats set_matplotlib_formats('svg', 'pdf') # For export from matplotlib.colors import to_rgb import matplotlib matplotlib.rcParams['lines.linewidth'] = 2.0 import seaborn as sns sns.reset_orig() ## Progress bar from tqdm.notebook import tqdm ## PyTorch import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data as data import torch.optim as optim # Torchvision import torchvision from torchvision.datasets import MNIST from torchvision import transforms # PyTorch Lightning try: import pytorch_lightning as pl except ModuleNotFoundError: # Google Colab does not have PyTorch Lightning installed by default. Hence, we do it here if necessary !pip install --quiet pytorch-lightning>=1.4 import pytorch_lightning as pl from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint # Path to the folder where the datasets are/should be downloaded (e.g. MNIST) DATASET_PATH = "../data" # Path to the folder where the pretrained models are saved CHECKPOINT_PATH = "../saved_models/tutorial11" # Setting the seed pl.seed_everything(42) # Ensure that all operations are deterministic on GPU (if used) for reproducibility torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # Fetching the device that will be used throughout this notebook device = torch.device("cpu") if not torch.cuda.is_available() else torch.device("cuda:0") print("Using device", device) ``` Again, we have a few pretrained models. We download them below to the specified path above. ``` import urllib.request from urllib.error import HTTPError # Github URL where saved models are stored for this tutorial base_url = "https://raw.githubusercontent.com/phlippe/saved_models/main/tutorial11/" # Files to download pretrained_files = ["MNISTFlow_simple.ckpt", "MNISTFlow_vardeq.ckpt", "MNISTFlow_multiscale.ckpt"] # Create checkpoint path if it doesn't exist yet os.makedirs(CHECKPOINT_PATH, exist_ok=True) # For each file, check whether it already exists. If not, try downloading it. for file_name in pretrained_files: file_path = os.path.join(CHECKPOINT_PATH, file_name) if not os.path.isfile(file_path): file_url = base_url + file_name print(f"Downloading {file_url}...") try: urllib.request.urlretrieve(file_url, file_path) except HTTPError as e: print("Something went wrong. Please try to download the file from the GDrive folder, or contact the author with the full output including the following error:\n", e) ``` We will use the MNIST dataset in this notebook. MNIST constitutes, despite its simplicity, a challenge for small generative models as it requires the global understanding of an image. At the same time, we can easily judge whether generated images come from the same distribution as the dataset (i.e. represent real digits), or not. To deal better with the discrete nature of the images, we transform them from a range of 0-1 to a range of 0-255 as integers. ``` # Convert images from 0-1 to 0-255 (integers) def discretize(sample): return (sample * 255).to(torch.int32) # Transformations applied on each image => make them a tensor and discretize transform = transforms.Compose([transforms.ToTensor(), discretize]) # Loading the training dataset. We need to split it into a training and validation part train_dataset = MNIST(root=DATASET_PATH, train=True, transform=transform, download=True) pl.seed_everything(42) train_set, val_set = torch.utils.data.random_split(train_dataset, [50000, 10000]) # Loading the test set test_set = MNIST(root=DATASET_PATH, train=False, transform=transform, download=True) # We define a set of data loaders that we can use for various purposes later. # Note that for actually training a model, we will use different data loaders # with a lower batch size. train_loader = data.DataLoader(train_set, batch_size=256, shuffle=False, drop_last=False) val_loader = data.DataLoader(val_set, batch_size=64, shuffle=False, drop_last=False, num_workers=4) test_loader = data.DataLoader(test_set, batch_size=64, shuffle=False, drop_last=False, num_workers=4) ``` In addition, we will define below a function to simplify the visualization of images/samples. Some training examples of the MNIST dataset is shown below. ``` def show_imgs(imgs, title=None, row_size=4): # Form a grid of pictures (we use max. 8 columns) num_imgs = imgs.shape[0] if isinstance(imgs, torch.Tensor) else len(imgs) is_int = imgs.dtype==torch.int32 if isinstance(imgs, torch.Tensor) else imgs[0].dtype==torch.int32 nrow = min(num_imgs, row_size) ncol = int(math.ceil(num_imgs/nrow)) imgs = torchvision.utils.make_grid(imgs, nrow=nrow, pad_value=128 if is_int else 0.5) np_imgs = imgs.cpu().numpy() # Plot the grid plt.figure(figsize=(1.5*nrow, 1.5*ncol)) plt.imshow(np.transpose(np_imgs, (1,2,0)), interpolation='nearest') plt.axis('off') if title is not None: plt.title(title) plt.show() plt.close() show_imgs([train_set[i][0] for i in range(8)]) ``` ## Normalizing Flows as generative model In the previous lectures, we have seen Energy-based models, Variational Autoencoders (VAEs) and Generative Adversarial Networks (GANs) as example of generative models. However, none of them explicitly learn the probability density function $p(x)$ of the real input data. While VAEs model a lower bound, energy-based models only implicitly learn the probability density. GANs on the other hand provide us a sampling mechanism for generating new data, without offering a likelihood estimate. The generative model we will look at here, called Normalizing Flows, actually models the true data distribution $p(x)$ and provides us with an exact likelihood estimate. Below, we can visually compare VAEs, GANs and Flows (figure credit - [Lilian Weng](https://lilianweng.github.io/lil-log/2018/10/13/flow-based-deep-generative-models.html)): <center width="100%"><img src="comparison_GAN_VAE_NF.png" width="600px"></center> The major difference compared to VAEs is that flows use *invertible* functions $f$ to map the input data $x$ to a latent representation $z$. To realize this, $z$ must be of the same shape as $x$. This is in contrast to VAEs where $z$ is usually much lower dimensional than the original input data. However, an invertible mapping also means that for every data point $x$, we have a corresponding latent representation $z$ which allows us to perform lossless reconstruction ($z$ to $x$). In the visualization above, this means that $x=x'$ for flows, no matter what invertible function $f$ and input $x$ we choose. Nonetheless, how are normalizing flows modeling a probability density with an invertible function? The answer to this question is the rule for change of variables. Specifically, given a prior density $p_z(z)$ (e.g. Gaussian) and an invertible function $f$, we can determine $p_x(x)$ as follows: $$ \begin{split} \int p_x(x) dx & = \int p_z(z) dz = 1 \hspace{1cm}\text{(by definition of a probability distribution)}\\ \Leftrightarrow p_x(x) & = p_z(z) \left|\frac{dz}{dx}\right| = p_z(f(x)) \left|\frac{df(x)}{dx}\right| \end{split} $$ Hence, in order to determine the probability of $x$, we only need to determine its probability in latent space, and get the derivate of $f$. Note that this is for a univariate distribution, and $f$ is required to be invertible and smooth. For a multivariate case, the derivative becomes a Jacobian of which we need to take the determinant. As we usually use the log-likelihood as objective, we write the multivariate term with logarithms below: $$ \log p_x(\mathbf{x}) = \log p_z(f(\mathbf{x})) + \log{} \left|\det \frac{df(\mathbf{x})}{d\mathbf{x}}\right| $$ Although we now know how a normalizing flow obtains its likelihood, it might not be clear what a normalizing flow does intuitively. For this, we should look from the inverse perspective of the flow starting with the prior probability density $p_z(z)$. If we apply an invertible function on it, we effectively "transform" its probability density. For instance, if $f^{-1}(z)=z+1$, we shift the density by one while still remaining a valid probability distribution, and being invertible. We can also apply more complex transformations, like scaling: $f^{-1}(z)=2z+1$, but there you might see a difference. When you scale, you also change the volume of the probability density, as for example on uniform distributions (figure credit - [Eric Jang](https://blog.evjang.com/2018/01/nf1.html)): <center width="100%"><img src="uniform_flow.png" width="300px"></center> You can see that the height of $p(y)$ should be lower than $p(x)$ after scaling. This change in volume represents $\left|\frac{df(x)}{dx}\right|$ in our equation above, and ensures that even after scaling, we still have a valid probability distribution. We can go on with making our function $f$ more complex. However, the more complex $f$ becomes, the harder it will be to find the inverse $f^{-1}$ of it, and to calculate the log-determinant of the Jacobian $\log{} \left|\det \frac{df(\mathbf{x})}{d\mathbf{x}}\right|$. An easier trick to stack multiple invertible functions $f_{1,...,K}$ after each other, as all together, they still represent a single, invertible function. Using multiple, learnable invertible functions, a normalizing flow attempts to transform $p_z(z)$ slowly into a more complex distribution which should finally be $p_x(x)$. We visualize the idea below (figure credit - [Lilian Weng](https://lilianweng.github.io/lil-log/2018/10/13/flow-based-deep-generative-models.html)): <center width="100%"><img src="normalizing_flow_layout.png" width="700px"></center> Starting from $z_0$, which follows the prior Gaussian distribution, we sequentially apply the invertible functions $f_1,f_2,...,f_K$, until $z_K$ represents $x$. Note that in the figure above, the functions $f$ represent the inverted function from $f$ we had above (here: $f:Z\to X$, above: $f:X\to Z$). This is just a different notation and has no impact on the actual flow design because all $f$ need to be invertible anyways. When we estimate the log likelihood of a data point $x$ as in the equations above, we run the flows in the opposite direction than visualized above. Multiple flow layers have been proposed that use a neural network as learnable parameters, such as the planar and radial flow. However, we will focus here on flows that are commonly used in image modeling, and will discuss them in the rest of the notebook along with the details of how to train a normalizing flow. ## Normalizing Flows on images To become familiar with normalizing flows, especially for the application of image modeling, it is best to discuss the different elements in a flow along with the implementation. As a general concept, we want to build a normalizing flow that maps an input image (here MNIST) to an equally sized latent space: <center width="100%" style="padding: 10px"><img src="image_to_gaussian.svg" width="450px"></center> As a first step, we will implement a template of a normalizing flow in PyTorch Lightning. During training and validation, a normalizing flow performs density estimation in the forward direction. For this, we apply a series of flow transformations on the input $x$ and estimate the probability of the input by determining the probability of the transformed point $z$ given a prior, and the change of volume caused by the transformations. During inference, we can do both density estimation and sampling new points by inverting the flow transformations. Therefore, we define a function `_get_likelihood` which performs density estimation, and `sample` to generate new examples. The functions `training_step`, `validation_step` and `test_step` all make use of `_get_likelihood`. The standard metric used in generative models, and in particular normalizing flows, is bits per dimensions (bpd). Bpd is motivated from an information theory perspective and describes how many bits we would need to encode a particular example in our modeled distribution. The less bits we need, the more likely the example in our distribution. When we test for the bits per dimension of our test dataset, we can judge whether our model generalizes to new samples of the dataset and didn't memorize the training dataset. In order to calculate the bits per dimension score, we can rely on the negative log-likelihood and change the log base (as bits are binary while NLL is usually exponential): $$\text{bpd} = \text{nll} \cdot \log_2\left(\exp(1)\right) \cdot \left(\prod d_i\right)^{-1}$$ where $d_1,...,d_K$ are the dimensions of the input. For images, this would be the height, width and channel number. We divide the log likelihood by these extra dimensions to have a metric which we can compare for different image resolutions. In the original image space, MNIST examples have a bits per dimension score of 8 (we need 8 bits to encode each pixel as there are 256 possible values). ``` class ImageFlow(pl.LightningModule): def __init__(self, flows, import_samples=8): """ Inputs: flows - A list of flows (each a nn.Module) that should be applied on the images. import_samples - Number of importance samples to use during testing (see explanation below). Can be changed at any time """ super().__init__() self.flows = nn.ModuleList(flows) self.import_samples = import_samples # Create prior distribution for final latent space self.prior = torch.distributions.normal.Normal(loc=0.0, scale=1.0) # Example input for visualizing the graph self.example_input_array = train_set[0][0].unsqueeze(dim=0) def forward(self, imgs): # The forward function is only used for visualizing the graph return self._get_likelihood(imgs) def encode(self, imgs): # Given a batch of images, return the latent representation z and ldj of the transformations z, ldj = imgs, torch.zeros(imgs.shape[0], device=self.device) for flow in self.flows: z, ldj = flow(z, ldj, reverse=False) return z, ldj def _get_likelihood(self, imgs, return_ll=False): """ Given a batch of images, return the likelihood of those. If return_ll is True, this function returns the log likelihood of the input. Otherwise, the ouptut metric is bits per dimension (scaled negative log likelihood) """ z, ldj = self.encode(imgs) log_pz = self.prior.log_prob(z).sum(dim=[1,2,3]) log_px = ldj + log_pz nll = -log_px # Calculating bits per dimension bpd = nll * np.log2(np.exp(1)) / np.prod(imgs.shape[1:]) return bpd.mean() if not return_ll else log_px @torch.no_grad() def sample(self, img_shape, z_init=None): """ Sample a batch of images from the flow. """ # Sample latent representation from prior if z_init is None: z = self.prior.sample(sample_shape=img_shape).to(device) else: z = z_init.to(device) # Transform z to x by inverting the flows ldj = torch.zeros(img_shape[0], device=device) for flow in reversed(self.flows): z, ldj = flow(z, ldj, reverse=True) return z def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=1e-3) # An scheduler is optional, but can help in flows to get the last bpd improvement scheduler = optim.lr_scheduler.StepLR(optimizer, 1, gamma=0.99) return [optimizer], [scheduler] def training_step(self, batch, batch_idx): # Normalizing flows are trained by maximum likelihood => return bpd loss = self._get_likelihood(batch[0]) self.log('train_bpd', loss) return loss def validation_step(self, batch, batch_idx): loss = self._get_likelihood(batch[0]) self.log('val_bpd', loss) def test_step(self, batch, batch_idx): # Perform importance sampling during testing => estimate likelihood M times for each image samples = [] for _ in range(self.import_samples): img_ll = self._get_likelihood(batch[0], return_ll=True) samples.append(img_ll) img_ll = torch.stack(samples, dim=-1) # To average the probabilities, we need to go from log-space to exp, and back to log. # Logsumexp provides us a stable implementation for this img_ll = torch.logsumexp(img_ll, dim=-1) - np.log(self.import_samples) # Calculate final bpd bpd = -img_ll * np.log2(np.exp(1)) / np.prod(batch[0].shape[1:]) bpd = bpd.mean() self.log('test_bpd', bpd) ``` The `test_step` function differs from the training and validation step in that it makes use of importance sampling. We will discuss the motiviation and details behind this after understanding how flows model discrete images in continuous space. ### Dequantization Normalizing flows rely on the rule of change of variables, which is naturally defined in continuous space. Applying flows directly on discrete data leads to undesired density models where arbitrarly high likelihood are placed on a few, particular values. See the illustration below: <center><img src="dequantization_issue.svg" width="40%"/></center> The black points represent the discrete points, and the green volume the density modeled by a normalizing flow in continuous space. The flow would continue to increase the likelihood for $x=0,1,2,3$ while having no volume on any other point. Remember that in continuous space, we have the constraint that the overall volume of the probability density must be 1 ($\int p(x)dx=1$). Otherwise, we don't model a probability distribution anymore. However, the discrete points $x=0,1,2,3$ represent delta peaks with no width in continuous space. This is why the flow can place an infinite high likelihood on these few points while still representing a distribution in continuous space. Nonetheless, the learned density does not tell us anything about the distribution among the discrete points, as in discrete space, the likelihoods of those four points would have to sum to 1, not to infinity. To prevent such degenerated solutions, a common solution is to add a small amount of noise to each discrete value, which is also referred to as dequantization. Considering $x$ as an integer (as it is the case for images), the dequantized representation $v$ can be formulated as $v=x+u$ where $u\in[0,1)^D$. Thus, the discrete value $1$ is modeled by a distribution over the interval $[1.0, 2.0)$, the value $2$ by an volume over $[2.0, 3.0)$, etc. Our objective of modeling $p(x)$ becomes: $$ p(x) = \int p(x+u)du = \int \frac{q(u|x)}{q(u|x)}p(x+u)du = \mathbb{E}_{u\sim q(u|x)}\left[\frac{p(x+u)}{q(u|x)} \right]$$ with $q(u|x)$ being the noise distribution. For now, we assume it to be uniform, which can also be written as $p(x)=\mathbb{E}_{u\sim U(0,1)^D}\left[p(x+u) \right]$. In the following, we will implement Dequantization as a flow transformation itself. After adding noise to the discrete values, we additionally transform the volume into a Gaussian-like shape. This is done by scaling $x+u$ between $0$ and $1$, and applying the invert of the sigmoid function $\sigma(z)^{-1} = \log z - \log 1-z$. If we would not do this, we would face two problems: 1. The input is scaled between 0 and 256 while the prior distribution is a Gaussian with mean $0$ and standard deviation $1$. In the first iterations after initializing the parameters of the flow, we would have extremely low likelihoods for large values like $256$. This would cause the training to diverge instantaneously. 2. As the output distribution is a Gaussian, it is beneficial for the flow to have a similarly shaped input distribution. This will reduce the modeling complexity that is required by the flow. Overall, we can implement dequantization as follows: ``` class Dequantization(nn.Module): def __init__(self, alpha=1e-5, quants=256): """ Inputs: alpha - small constant that is used to scale the original input. Prevents dealing with values very close to 0 and 1 when inverting the sigmoid quants - Number of possible discrete values (usually 256 for 8-bit image) """ super().__init__() self.alpha = alpha self.quants = quants def forward(self, z, ldj, reverse=False): if not reverse: z, ldj = self.dequant(z, ldj) z, ldj = self.sigmoid(z, ldj, reverse=True) else: z, ldj = self.sigmoid(z, ldj, reverse=False) z = z * self.quants ldj += np.log(self.quants) * np.prod(z.shape[1:]) z = torch.floor(z).clamp(min=0, max=self.quants-1).to(torch.int32) return z, ldj def sigmoid(self, z, ldj, reverse=False): # Applies an invertible sigmoid transformation if not reverse: ldj += (-z-2*F.softplus(-z)).sum(dim=[1,2,3]) z = torch.sigmoid(z) else: z = z * (1 - self.alpha) + 0.5 * self.alpha # Scale to prevent boundaries 0 and 1 ldj += np.log(1 - self.alpha) * np.prod(z.shape[1:]) ldj += (-torch.log(z) - torch.log(1-z)).sum(dim=[1,2,3]) z = torch.log(z) - torch.log(1-z) return z, ldj def dequant(self, z, ldj): # Transform discrete values to continuous volumes z = z.to(torch.float32) z = z + torch.rand_like(z).detach() z = z / self.quants ldj -= np.log(self.quants) * np.prod(z.shape[1:]) return z, ldj ``` A good check whether a flow is correctly implemented or not, is to verify that it is invertible. Hence, we will dequantize a randomly chosen training image, and then quantize it again. We would expect that we would get the exact same image out: ``` ## Testing invertibility of dequantization layer pl.seed_everything(42) orig_img = train_set[0][0].unsqueeze(dim=0) ldj = torch.zeros(1,) dequant_module = Dequantization() deq_img, ldj = dequant_module(orig_img, ldj, reverse=False) reconst_img, ldj = dequant_module(deq_img, ldj, reverse=True) d1, d2 = torch.where(orig_img.squeeze() != reconst_img.squeeze()) if len(d1) != 0: print("Dequantization was not invertible.") for i in range(d1.shape[0]): print("Original value:", orig_img[0,0,d1[i], d2[i]].item()) print("Reconstructed value:", reconst_img[0,0,d1[i], d2[i]].item()) else: print("Successfully inverted dequantization") # Layer is not strictly invertible due to float precision constraints # assert (orig_img == reconst_img).all().item() ``` In contrast to our expectation, the test fails. However, this is no reason to doubt our implementation here as only one single value is not equal to the original. This is caused due to numerical inaccuracies in the sigmoid invert. While the input space to the inverted sigmoid is scaled between 0 and 1, the output space is between $-\infty$ and $\infty$. And as we use 32 bits to represent the numbers (in addition to applying logs over and over again), such inaccuries can occur and should not be worrisome. Nevertheless, it is good to be aware of them, and can be improved by using a double tensor (float64). Finally, we can take our dequantization and actually visualize the distribution it transforms the discrete values into: ``` def visualize_dequantization(quants, prior=None): """ Function for visualizing the dequantization values of discrete values in continuous space """ # Prior over discrete values. If not given, a uniform is assumed if prior is None: prior = np.ones(quants, dtype=np.float32) / quants prior = prior / prior.sum() * quants # In the following, we assume 1 for each value means uniform distribution inp = torch.arange(-4, 4, 0.01).view(-1, 1, 1, 1) # Possible continuous values we want to consider ldj = torch.zeros(inp.shape[0]) dequant_module = Dequantization(quants=quants) # Invert dequantization on continuous values to find corresponding discrete value out, ldj = dequant_module.forward(inp, ldj, reverse=True) inp, out, prob = inp.squeeze().numpy(), out.squeeze().numpy(), ldj.exp().numpy() prob = prob * prior[out] # Probability scaled by categorical prior # Plot volumes and continuous distribution sns.set_style("white") fig = plt.figure(figsize=(6,3)) x_ticks = [] for v in np.unique(out): indices = np.where(out==v) color = to_rgb(f"C{v}") plt.fill_between(inp[indices], prob[indices], np.zeros(indices[0].shape[0]), color=color+(0.5,), label=str(v)) plt.plot([inp[indices[0][0]]]*2, [0, prob[indices[0][0]]], color=color) plt.plot([inp[indices[0][-1]]]*2, [0, prob[indices[0][-1]]], color=color) x_ticks.append(inp[indices[0][0]]) x_ticks.append(inp.max()) plt.xticks(x_ticks, [f"{x:.1f}" for x in x_ticks]) plt.plot(inp,prob, color=(0.0,0.0,0.0)) # Set final plot properties plt.ylim(0, prob.max()*1.1) plt.xlim(inp.min(), inp.max()) plt.xlabel("z") plt.ylabel("Probability") plt.title(f"Dequantization distribution for {quants} discrete values") plt.legend() plt.show() plt.close() visualize_dequantization(quants=8) ``` The visualized distribution show the sub-volumes that are assigned to the different discrete values. The value $0$ has its volume between $[-\infty, -1.9)$, the value $1$ is represented by the interval $[-1.9, -1.1)$, etc. The volume for each discrete value has the same probability mass. That's why the volumes close to the center (e.g. 3 and 4) have a smaller area on the z-axis as others ($z$ is being used to denote the output of the whole dequantization flow). Effectively, the consecutive normalizing flow models discrete images by the following objective: $$\log p(x) = \log \mathbb{E}_{u\sim q(u|x)}\left[\frac{p(x+u)}{q(u|x)} \right] \geq \mathbb{E}_{u}\left[\log \frac{p(x+u)}{q(u|x)} \right]$$ Although normalizing flows are exact in likelihood, we have a lower bound. Specifically, this is an example of the Jensen inequality because we need to move the log into the expectation so we can use Monte-carlo estimates. In general, this bound is considerably smaller than the ELBO in variational autoencoders. Actually, we can reduce the bound ourselves by estimating the expectation not by one, but by $M$ samples. In other words, we can apply importance sampling which leads to the following inequality: $$\log p(x) = \log \mathbb{E}_{u\sim q(u|x)}\left[\frac{p(x+u)}{q(u|x)} \right] \geq \mathbb{E}_{u}\left[\log \frac{1}{M} \sum_{m=1}^{M} \frac{p(x+u_m)}{q(u_m|x)} \right] \geq \mathbb{E}_{u}\left[\log \frac{p(x+u)}{q(u|x)} \right]$$ The importance sampling $\frac{1}{M} \sum_{m=1}^{M} \frac{p(x+u_m)}{q(u_m|x)}$ becomes $\mathbb{E}_{u\sim q(u|x)}\left[\frac{p(x+u)}{q(u|x)} \right]$ if $M\to \infty$, so that the more samples we use, the tighter the bound is. During testing, we can make use of this property and have it implemented in `test_step` in `ImageFlow`. In theory, we could also use this tighter bound during training. However, related work has shown that this does not necessarily lead to an improvement given the additional computational cost, and it is more efficient to stick with a single estimate [5]. ### Variational Dequantization Dequantization uses a uniform distribution for the noise $u$ which effectively leads to images being represented as hypercubes (cube in high dimensions) with sharp borders. However, modeling such sharp borders is not easy for a flow as it uses smooth transformations to convert it into a Gaussian distribution. Another way of looking at it is if we change the prior distribution in the previous visualization. Imagine we have independent Gaussian noise on pixels which is commonly the case for any real-world taken picture. Therefore, the flow would have to model a distribution as above, but with the individual volumes scaled as follows: ``` visualize_dequantization(quants=8, prior=np.array([0.075, 0.2, 0.4, 0.2, 0.075, 0.025, 0.0125, 0.0125])) ``` Transforming such a probability into a Gaussian is a difficult task, especially with such hard borders. Dequantization has therefore been extended to more sophisticated, learnable distributions beyond uniform in a variational framework. In particular, if we remember the learning objective $\log p(x) = \log \mathbb{E}_{u}\left[\frac{p(x+u)}{q(u|x)} \right]$, the uniform distribution can be replaced by a learned distribution $q_{\theta}(u|x)$ with support over $u\in[0,1)^D$. This approach is called Variational Dequantization and has been proposed by Ho et al. [3]. How can we learn such a distribution? We can use a second normalizing flow that takes $x$ as external input and learns a flexible distribution over $u$. To ensure a support over $[0,1)^D$, we can apply a sigmoid activation function as final flow transformation. Inheriting the original dequantization class, we can implement variational dequantization as follows: ``` class VariationalDequantization(Dequantization): def __init__(self, var_flows, alpha=1e-5): """ Inputs: var_flows - A list of flow transformations to use for modeling q(u|x) alpha - Small constant, see Dequantization for details """ super().__init__(alpha=alpha) self.flows = nn.ModuleList(var_flows) def dequant(self, z, ldj): z = z.to(torch.float32) img = (z / 255.0) * 2 - 1 # We condition the flows on x, i.e. the original image # Prior of u is a uniform distribution as before # As most flow transformations are defined on [-infinity,+infinity], we apply an inverse sigmoid first. deq_noise = torch.rand_like(z).detach() deq_noise, ldj = self.sigmoid(deq_noise, ldj, reverse=True) for flow in self.flows: deq_noise, ldj = flow(deq_noise, ldj, reverse=False, orig_img=img) deq_noise, ldj = self.sigmoid(deq_noise, ldj, reverse=False) # After the flows, apply u as in standard dequantization z = (z + deq_noise) / 256.0 ldj -= np.log(256.0) * np.prod(z.shape[1:]) return z, ldj ``` Variational dequantization can be used as a substitute for dequantization. We will compare dequantization and variational dequantization in later experiments. ### Coupling layers Next, we look at possible transformations to apply inside the flow. A recent popular flow layer, which works well in combination with deep neural networks, is the coupling layer introduced by Dinh et al. [1]. The input $z$ is arbitrarily split into two parts, $z_{1:j}$ and $z_{j+1:d}$, of which the first remains unchanged by the flow. Yet, $z_{1:j}$ is used to parameterize the transformation for the second part, $z_{j+1:d}$. Various transformations have been proposed in recent time [3,4], but here we will settle for the simplest and most efficient one: affine coupling. In this coupling layer, we apply an affine transformation by shifting the input by a bias $\mu$ and scale it by $\sigma$. In other words, our transformation looks as follows: $$z'_{j+1:d} = \mu_{\theta}(z_{1:j}) + \sigma_{\theta}(z_{1:j}) \odot z_{j+1:d}$$ The functions $\mu$ and $\sigma$ are implemented as a shared neural network, and the sum and multiplication are performed element-wise. The LDJ is thereby the sum of the logs of the scaling factors: $\sum_i \left[\log \sigma_{\theta}(z_{1:j})\right]_i$. Inverting the layer can as simply be done as subtracting the bias and dividing by the scale: $$z_{j+1:d} = \left(z'_{j+1:d} - \mu_{\theta}(z_{1:j})\right) / \sigma_{\theta}(z_{1:j})$$ We can also visualize the coupling layer in form of a computation graph, where $z_1$ represents $z_{1:j}$, and $z_2$ represents $z_{j+1:d}$: <center width="100%" style="padding: 10px"><img src="coupling_flow.svg" width="450px"></center> In our implementation, we will realize the splitting of variables as masking. The variables to be transformed, $z_{j+1:d}$, are masked when passing $z$ to the shared network to predict the transformation parameters. When applying the transformation, we mask the parameters for $z_{1:j}$ so that we have an identity operation for those variables: ``` class CouplingLayer(nn.Module): def __init__(self, network, mask, c_in): """ Coupling layer inside a normalizing flow. Inputs: network - A PyTorch nn.Module constituting the deep neural network for mu and sigma. Output shape should be twice the channel size as the input. mask - Binary mask (0 or 1) where 0 denotes that the element should be transformed, while 1 means the latent will be used as input to the NN. c_in - Number of input channels """ super().__init__() self.network = network self.scaling_factor = nn.Parameter(torch.zeros(c_in)) # Register mask as buffer as it is a tensor which is not a parameter, # but should be part of the modules state. self.register_buffer('mask', mask) def forward(self, z, ldj, reverse=False, orig_img=None): """ Inputs: z - Latent input to the flow ldj - The current ldj of the previous flows. The ldj of this layer will be added to this tensor. reverse - If True, we apply the inverse of the layer. orig_img (optional) - Only needed in VarDeq. Allows external input to condition the flow on (e.g. original image) """ # Apply network to masked input z_in = z * self.mask if orig_img is None: nn_out = self.network(z_in) else: nn_out = self.network(torch.cat([z_in, orig_img], dim=1)) s, t = nn_out.chunk(2, dim=1) # Stabilize scaling output s_fac = self.scaling_factor.exp().view(1, -1, 1, 1) s = torch.tanh(s / s_fac) * s_fac # Mask outputs (only transform the second part) s = s * (1 - self.mask) t = t * (1 - self.mask) # Affine transformation if not reverse: # Whether we first shift and then scale, or the other way round, # is a design choice, and usually does not have a big impact z = (z + t) * torch.exp(s) ldj += s.sum(dim=[1,2,3]) else: z = (z * torch.exp(-s)) - t ldj -= s.sum(dim=[1,2,3]) return z, ldj ``` For stabilization purposes, we apply a $\tanh$ activation function on the scaling output. This prevents sudden large output values for the scaling that can destabilize training. To still allow scaling factors smaller or larger than -1 and 1 respectively, we have a learnable parameter per dimension, called `scaling_factor`. This scales the tanh to different limits. Below, we visualize the effect of the scaling factor on the output activation of the scaling terms: ``` with torch.no_grad(): x = torch.arange(-5,5,0.01) scaling_factors = [0.5, 1, 2] sns.set() fig, ax = plt.subplots(1, 3, figsize=(12,3)) for i, scale in enumerate(scaling_factors): y = torch.tanh(x / scale) * scale ax[i].plot(x.numpy(), y.numpy()) ax[i].set_title("Scaling factor: " + str(scale)) ax[i].set_ylim(-3, 3) plt.subplots_adjust(wspace=0.4) sns.reset_orig() plt.show() ``` Coupling layers generalize to any masking technique we could think of. However, the most common approach for images is to split the input $z$ in half, using a checkerboard mask or channel mask. A checkerboard mask splits the variables across the height and width dimensions and assigns each other pixel to $z_{j+1:d}$. Thereby, the mask is shared across channels. In contrast, the channel mask assigns half of the channels to $z_{j+1:d}$, and the other half to $z_{1:j+1}$. Note that when we apply multiple coupling layers, we invert the masking for each other layer so that each variable is transformed a similar amount of times. Let's implement a function that creates a checkerboard mask and a channel mask for us: ``` def create_checkerboard_mask(h, w, invert=False): x, y = torch.arange(h, dtype=torch.int32), torch.arange(w, dtype=torch.int32) xx, yy = torch.meshgrid(x, y) mask = torch.fmod(xx + yy, 2) mask = mask.to(torch.float32).view(1, 1, h, w) if invert: mask = 1 - mask return mask def create_channel_mask(c_in, invert=False): mask = torch.cat([torch.ones(c_in//2, dtype=torch.float32), torch.zeros(c_in-c_in//2, dtype=torch.float32)]) mask = mask.view(1, c_in, 1, 1) if invert: mask = 1 - mask return mask ``` We can also visualize the corresponding masks for an image of size $8\times 8\times 2$ (2 channels): ``` checkerboard_mask = create_checkerboard_mask(h=8, w=8).expand(-1,2,-1,-1) channel_mask = create_channel_mask(c_in=2).expand(-1,-1,8,8) show_imgs(checkerboard_mask.transpose(0,1), "Checkerboard mask") show_imgs(channel_mask.transpose(0,1), "Channel mask") ``` As a last aspect of coupling layers, we need to decide for the deep neural network we want to apply in the coupling layers. The input to the layers is an image, and hence we stick with a CNN. Because the input to a transformation depends on all transformations before, it is crucial to ensure a good gradient flow through the CNN back to the input, which can be optimally achieved by a ResNet-like architecture. Specifically, we use a Gated ResNet that adds a $\sigma$-gate to the skip connection, similarly to the input gate in LSTMs. The details are not necessarily important here, and the network is strongly inspired from Flow++ [3] in case you are interested in building even stronger models. ``` class ConcatELU(nn.Module): """ Activation function that applies ELU in both direction (inverted and plain). Allows non-linearity while providing strong gradients for any input (important for final convolution) """ def forward(self, x): return torch.cat([F.elu(x), F.elu(-x)], dim=1) class LayerNormChannels(nn.Module): def __init__(self, c_in): """ This module applies layer norm across channels in an image. Has been shown to work well with ResNet connections. Inputs: c_in - Number of channels of the input """ super().__init__() self.layer_norm = nn.LayerNorm(c_in) def forward(self, x): x = x.permute(0, 2, 3, 1) x = self.layer_norm(x) x = x.permute(0, 3, 1, 2) return x class GatedConv(nn.Module): def __init__(self, c_in, c_hidden): """ This module applies a two-layer convolutional ResNet block with input gate Inputs: c_in - Number of channels of the input c_hidden - Number of hidden dimensions we want to model (usually similar to c_in) """ super().__init__() self.net = nn.Sequential( nn.Conv2d(c_in, c_hidden, kernel_size=3, padding=1), ConcatELU(), nn.Conv2d(2*c_hidden, 2*c_in, kernel_size=1) ) def forward(self, x): out = self.net(x) val, gate = out.chunk(2, dim=1) return x + val * torch.sigmoid(gate) class GatedConvNet(nn.Module): def __init__(self, c_in, c_hidden=32, c_out=-1, num_layers=3): """ Module that summarizes the previous blocks to a full convolutional neural network. Inputs: c_in - Number of input channels c_hidden - Number of hidden dimensions to use within the network c_out - Number of output channels. If -1, 2 times the input channels are used (affine coupling) num_layers - Number of gated ResNet blocks to apply """ super().__init__() c_out = c_out if c_out > 0 else 2 * c_in layers = [] layers += [nn.Conv2d(c_in, c_hidden, kernel_size=3, padding=1)] for layer_index in range(num_layers): layers += [GatedConv(c_hidden, c_hidden), LayerNormChannels(c_hidden)] layers += [ConcatELU(), nn.Conv2d(2*c_hidden, c_out, kernel_size=3, padding=1)] self.nn = nn.Sequential(*layers) self.nn[-1].weight.data.zero_() self.nn[-1].bias.data.zero_() def forward(self, x): return self.nn(x) ``` ### Training loop Finally, we can add Dequantization, Variational Dequantization and Coupling Layers together to build our full normalizing flow on MNIST images. We apply 8 coupling layers in the main flow, and 4 for variational dequantization if applied. We apply a checkerboard mask throughout the network as with a single channel (black-white images), we cannot apply channel mask. The overall architecture is visualized below. <center width="100%" style="padding: 20px"><img src="vanilla_flow.svg" width="900px"></center> ``` def create_simple_flow(use_vardeq=True): flow_layers = [] if use_vardeq: vardeq_layers = [CouplingLayer(network=GatedConvNet(c_in=2, c_out=2, c_hidden=16), mask=create_checkerboard_mask(h=28, w=28, invert=(i%2==1)), c_in=1) for i in range(4)] flow_layers += [VariationalDequantization(var_flows=vardeq_layers)] else: flow_layers += [Dequantization()] for i in range(8): flow_layers += [CouplingLayer(network=GatedConvNet(c_in=1, c_hidden=32), mask=create_checkerboard_mask(h=28, w=28, invert=(i%2==1)), c_in=1)] flow_model = ImageFlow(flow_layers).to(device) return flow_model ``` For implementing the training loop, we use the framework of PyTorch Lightning and reduce the code overhead. If interested, you can take a look at the generated tensorboard file, in particularly the graph to see an overview of flow transformations that are applied. Note that we again provide pre-trained models (see later on in the notebook) as normalizing flows are particularly expensive to train. We have also run validation and testing as this can take some time as well with the added importance sampling. ``` def train_flow(flow, model_name="MNISTFlow"): # Create a PyTorch Lightning trainer trainer = pl.Trainer(default_root_dir=os.path.join(CHECKPOINT_PATH, model_name), gpus=1 if torch.cuda.is_available() else 0, max_epochs=200, gradient_clip_val=1.0, callbacks=[ModelCheckpoint(save_weights_only=True, mode="min", monitor="val_bpd"), LearningRateMonitor("epoch")]) trainer.logger._log_graph = True trainer.logger._default_hp_metric = None # Optional logging argument that we don't need train_data_loader = data.DataLoader(train_set, batch_size=128, shuffle=True, drop_last=True, pin_memory=True, num_workers=8) result = None # Check whether pretrained model exists. If yes, load it and skip training pretrained_filename = os.path.join(CHECKPOINT_PATH, model_name + ".ckpt") if os.path.isfile(pretrained_filename): print("Found pretrained model, loading...") ckpt = torch.load(pretrained_filename) flow.load_state_dict(ckpt['state_dict']) result = ckpt.get("result", None) else: print("Start training", model_name) trainer.fit(flow, train_data_loader, val_loader) # Test best model on validation and test set if no result has been found # Testing can be expensive due to the importance sampling. if result is None: val_result = trainer.test(flow, val_loader, verbose=False) start_time = time.time() test_result = trainer.test(flow, test_loader, verbose=False) duration = time.time() - start_time result = {"test": test_result, "val": val_result, "time": duration / len(test_loader) / flow.import_samples} return flow, result ``` ## Multi-scale architecture One disadvantage of normalizing flows is that they operate on the exact same dimensions as the input. If the input is high-dimensional, so is the latent space, which requires larger computational cost to learn suitable transformations. However, particularly in the image domain, many pixels contain less information in the sense that we could remove them without loosing the semantical information of the image. Based on this intuition, deep normalizing flows on images commonly apply a multi-scale architecture [1]. After the first $N$ flow transformations, we split off half of the latent dimensions and directly evaluate them on the prior. The other half is run through $N$ more flow transformations, and depending on the size of the input, we split it again in half or stop overall at this position. The two operations involved in this setup is `Squeeze` and `Split` which we will review more closely and implement below. ### Squeeze and Split When we want to remove half of the pixels in an image, we have the problem of deciding which variables to cut, and how to rearrange the image. Thus, the squeezing operation is commonly used before split, which divides the image into subsquares of shape $2\times 2\times C$, and reshapes them into $1\times 1\times 4C$ blocks. Effectively, we reduce the height and width of the image by a factor of 2 while scaling the number of channels by 4. Afterwards, we can perform the split operation over channels without the need of rearranging the pixels. The smaller scale also makes the overall architecture more efficient. Visually, the squeeze operation should transform the input as follows: <center><img src="Squeeze_operation.svg" width="40%"/></center> The input of $4\times 4\times 1$ is scaled to $2\times 2\times 4$ following the idea of grouping the pixels in $2\times 2\times 1$ subsquares. Next, let's try to implement this layer: ``` class SqueezeFlow(nn.Module): def forward(self, z, ldj, reverse=False): B, C, H, W = z.shape if not reverse: # Forward direction: H x W x C => H/2 x W/2 x 4C z = z.reshape(B, C, H//2, 2, W//2, 2) z = z.permute(0, 1, 3, 5, 2, 4) z = z.reshape(B, 4*C, H//2, W//2) else: # Reverse direction: H/2 x W/2 x 4C => H x W x C z = z.reshape(B, C//4, 2, 2, H, W) z = z.permute(0, 1, 4, 2, 5, 3) z = z.reshape(B, C//4, H*2, W*2) return z, ldj ``` Before moving on, we can verify our implementation by comparing our output with the example figure above: ``` sq_flow = SqueezeFlow() rand_img = torch.arange(1,17).view(1, 1, 4, 4) print("Image (before)\n", rand_img) forward_img, _ = sq_flow(rand_img, ldj=None, reverse=False) print("\nImage (forward)\n", forward_img.permute(0,2,3,1)) # Permute for readability reconst_img, _ = sq_flow(forward_img, ldj=None, reverse=True) print("\nImage (reverse)\n", reconst_img) ``` The split operation divides the input into two parts, and evaluates one part directly on the prior. So that our flow operation fits to the implementation of the previous layers, we will return the prior probability of the first part as the log determinant jacobian of the layer. It has the same effect as if we would combine all variable splits at the end of the flow, and evaluate them together on the prior. ``` class SplitFlow(nn.Module): def __init__(self): super().__init__() self.prior = torch.distributions.normal.Normal(loc=0.0, scale=1.0) def forward(self, z, ldj, reverse=False): if not reverse: z, z_split = z.chunk(2, dim=1) ldj += self.prior.log_prob(z_split).sum(dim=[1,2,3]) else: z_split = self.prior.sample(sample_shape=z.shape).to(device) z = torch.cat([z, z_split], dim=1) ldj -= self.prior.log_prob(z_split).sum(dim=[1,2,3]) return z, ldj ``` ### Building a multi-scale flow After defining the squeeze and split operation, we are finally able to build our own multi-scale flow. Deep normalizing flows such as Glow and Flow++ [2,3] often apply a split operation directly after squeezing. However, with shallow flows, we need to be more thoughtful about where to place the split operation as we need at least a minimum amount of transformations on each variable. Our setup is inspired by the original RealNVP architecture [1] which is shallower than other, more recent state-of-the-art architectures. Hence, for the MNIST dataset, we will apply the first squeeze operation after two coupling layers, but don't apply a split operation yet. Because we have only used two coupling layers and each the variable has been only transformed once, a split operation would be too early. We apply two more coupling layers before finally applying a split flow and squeeze again. The last four coupling layers operate on a scale of $7\times 7\times 8$. The full flow architecture is shown below. <center width="100%" style="padding: 20px"><img src="multiscale_flow.svg" width="1100px"></center> Note that while the feature maps inside the coupling layers reduce with the height and width of the input, the increased number of channels is not directly considered. To counteract this, we increase the hidden dimensions for the coupling layers on the squeezed input. The dimensions are often scaled by 2 as this approximately increases the computation cost by 4 canceling with the squeezing operation. However, we will choose the hidden dimensionalities $32, 48, 64$ for the three scales respectively to keep the number of parameters reasonable and show the efficiency of multi-scale architectures. ``` def create_multiscale_flow(): flow_layers = [] vardeq_layers = [CouplingLayer(network=GatedConvNet(c_in=2, c_out=2, c_hidden=16), mask=create_checkerboard_mask(h=28, w=28, invert=(i%2==1)), c_in=1) for i in range(4)] flow_layers += [VariationalDequantization(vardeq_layers)] flow_layers += [CouplingLayer(network=GatedConvNet(c_in=1, c_hidden=32), mask=create_checkerboard_mask(h=28, w=28, invert=(i%2==1)), c_in=1) for i in range(2)] flow_layers += [SqueezeFlow()] for i in range(2): flow_layers += [CouplingLayer(network=GatedConvNet(c_in=4, c_hidden=48), mask=create_channel_mask(c_in=4, invert=(i%2==1)), c_in=4)] flow_layers += [SplitFlow(), SqueezeFlow()] for i in range(4): flow_layers += [CouplingLayer(network=GatedConvNet(c_in=8, c_hidden=64), mask=create_channel_mask(c_in=8, invert=(i%2==1)), c_in=8)] flow_model = ImageFlow(flow_layers).to(device) return flow_model ``` We can show the difference in number of parameters below: ``` def print_num_params(model): num_params = sum([np.prod(p.shape) for p in model.parameters()]) print("Number of parameters: {:,}".format(num_params)) print_num_params(create_simple_flow(use_vardeq=False)) print_num_params(create_simple_flow(use_vardeq=True)) print_num_params(create_multiscale_flow()) ``` Although the multi-scale flow has almost 3 times the parameters of the single scale flow, it is not necessarily more computationally expensive than its counterpart. We will compare the runtime in the following experiments as well. ## Analysing the flows In the last part of the notebook, we will train all the models we have implemented above, and try to analyze the effect of the multi-scale architecture and variational dequantization. ### Training flow variants Before we can analyse the flow models, we need to train them first. We provide pre-trained models that contain the validation and test performance, and run-time information. As flow models are computationally expensive, we advice you to rely on those pretrained models for a first run through the notebook. ``` flow_dict = {"simple": {}, "vardeq": {}, "multiscale": {}} flow_dict["simple"]["model"], flow_dict["simple"]["result"] = train_flow(create_simple_flow(use_vardeq=False), model_name="MNISTFlow_simple") flow_dict["vardeq"]["model"], flow_dict["vardeq"]["result"] = train_flow(create_simple_flow(use_vardeq=True), model_name="MNISTFlow_vardeq") flow_dict["multiscale"]["model"], flow_dict["multiscale"]["result"] = train_flow(create_multiscale_flow(), model_name="MNISTFlow_multiscale") ``` ### Density modeling and sampling Firstly, we can compare the models on their quantitative results. The following table shows all important statistics. The inference time specifies the time needed to determine the probability for a batch of 64 images for each model, and the sampling time the duration it took to sample a batch of 64 images. ``` %%html <!-- Some HTML code to increase font size in the following table --> <style> th {font-size: 120%;} td {font-size: 120%;} </style> import tabulate from IPython.display import display, HTML table = [[key, "%4.3f bpd" % flow_dict[key]["result"]["val"][0]["test_bpd"], "%4.3f bpd" % flow_dict[key]["result"]["test"][0]["test_bpd"], "%2.0f ms" % (1000 * flow_dict[key]["result"]["time"]), "%2.0f ms" % (1000 * flow_dict[key]["result"].get("samp_time", 0)), "{:,}".format(sum([np.prod(p.shape) for p in flow_dict[key]["model"].parameters()]))] for key in flow_dict] display(HTML(tabulate.tabulate(table, tablefmt='html', headers=["Model", "Validation Bpd", "Test Bpd", "Inference time", "Sampling time", "Num Parameters"]))) ``` As we have intially expected, using variational dequantization improves upon standard dequantization in terms of bits per dimension. Although the difference with 0.04bpd doesn't seem impressive first, it is a considerably step for generative models (most state-of-the-art models improve upon previous models in a range of 0.02-0.1bpd on CIFAR with three times as high bpd). While it takes longer to evaluate the probability of an image due to the variational dequantization, which also leads to a longer training time, it does not have an effect on the sampling time. This is because inverting variational dequantization is the same as dequantization: finding the next lower integer. When we compare the two models to multi-scale architecture, we can see that the bits per dimension score again dropped by about 0.04bpd. Additionally, the inference time and sampling time improved notably despite having more parameters. Thus, we see that the multi-scale flow is not only stronger for density modeling, but also more efficient. Next, we can test the sampling quality of the models. We should note that the samples for variational dequantization and standard dequantization are very similar, and hence we visualize here only the ones for variational dequantization and the multi-scale model. However, feel free to also test out the `"simple"` model. The seeds are set to obtain reproducable generations and are not cherry picked. ``` pl.seed_everything(44) samples = flow_dict["vardeq"]["model"].sample(img_shape=[16,1,28,28]) show_imgs(samples.cpu()) pl.seed_everything(44) samples = flow_dict["multiscale"]["model"].sample(img_shape=[16,8,7,7]) show_imgs(samples.cpu()) ``` From the few samples, we can see a clear difference between the simple and the multi-scale model. The single-scale model has only learned local, small correlations while the multi-scale model was able to learn full, global relations that form digits. This show-cases another benefit of the multi-scale model. In contrast to VAEs, the outputs are sharp as normalizing flows can naturally model complex, multi-modal distributions while VAEs have the independent decoder output noise. Nevertheless, the samples from this flow are far from perfect as not all samples show true digits. ### Interpolation in latent space Another popular test for the smoothness of the latent space of generative models is to interpolate between two training examples. As normalizing flows are strictly invertible, we can guarantee that any image is represented in the latent space. We again compare the variational dequantization model with the multi-scale model below. ``` @torch.no_grad() def interpolate(model, img1, img2, num_steps=8): """ Inputs: model - object of ImageFlow class that represents the (trained) flow model img1, img2 - Image tensors of shape [1, 28, 28]. Images between which should be interpolated. num_steps - Number of interpolation steps. 8 interpolation steps mean 6 intermediate pictures besides img1 and img2 """ imgs = torch.stack([img1, img2], dim=0).to(model.device) z, _ = model.encode(imgs) alpha = torch.linspace(0, 1, steps=num_steps, device=z.device).view(-1, 1, 1, 1) interpolations = z[0:1] * alpha + z[1:2] * (1 - alpha) interp_imgs = model.sample(interpolations.shape[:1] + imgs.shape[1:], z_init=interpolations) show_imgs(interp_imgs, row_size=8) exmp_imgs, _ = next(iter(train_loader)) pl.seed_everything(42) for i in range(2): interpolate(flow_dict["vardeq"]["model"], exmp_imgs[2*i], exmp_imgs[2*i+1]) pl.seed_everything(42) for i in range(2): interpolate(flow_dict["multiscale"]["model"], exmp_imgs[2*i], exmp_imgs[2*i+1]) ``` The interpolations of the multi-scale model result in more realistic digits (first row $7\leftrightarrow 8\leftrightarrow 6$, second row $9\leftrightarrow 4\leftrightarrow 6$), while the variational dequantization model focuses on local patterns that globally do not form a digit. For the multi-scale model, we actually did not do the "true" interpolation between the two images as we did not consider the variables that were split along the flow (they have been sampled randomly for all samples). However, as we will see in the next experiment, the early variables do not effect the overall image much. ### Visualization of latents in different levels of multi-scale In the following we will focus more on the multi-scale flow. We want to analyse what information is being stored in the variables split at early layers, and what information for the final variables. For this, we sample 8 images where each of them share the same final latent variables, but differ in the other part of the latent variables. Below we visualize three examples of this: ``` pl.seed_everything(44) for _ in range(3): z_init = flow_dict["multiscale"]["model"].prior.sample(sample_shape=[1,8,7,7]) z_init = z_init.expand(8, -1, -1, -1) samples = flow_dict["multiscale"]["model"].sample(img_shape=z_init.shape, z_init=z_init) show_imgs(samples.cpu()) ``` We see that the early split variables indeed have a smaller effect on the image. Still, small differences can be spot when we look carefully at the borders of the digits. For instance, the hole at the top of the 8 changes for different samples although all of them represent the same coarse structure. This shows that the flow indeed learns to separate the higher-level information in the final variables, while the early split ones contain local noise patterns. ### Visualizing Dequantization As a final part of this notebook, we will look at the effect of variational dequantization. We have motivated variational dequantization by the issue of sharp edges/boarders being difficult to model, and a flow would rather prefer smooth, prior-like distributions. To check how what noise distribution $q(u|x)$ the flows in the variational dequantization module have learned, we can plot a histogram of output values from the dequantization and variational dequantization module. ``` def visualize_dequant_distribution(model : ImageFlow, imgs : torch.Tensor, title:str=None): """ Inputs: model - The flow of which we want to visualize the dequantization distribution imgs - Example training images of which we want to visualize the dequantization distribution """ imgs = imgs.to(device) ldj = torch.zeros(imgs.shape[0], dtype=torch.float32).to(device) with torch.no_grad(): dequant_vals = [] for _ in tqdm(range(8), leave=False): d, _ = model.flows[0](imgs, ldj, reverse=False) dequant_vals.append(d) dequant_vals = torch.cat(dequant_vals, dim=0) dequant_vals = dequant_vals.view(-1).cpu().numpy() sns.set() plt.figure(figsize=(10,3)) plt.hist(dequant_vals, bins=256, color=to_rgb("C0")+(0.5,), edgecolor="C0", density=True) if title is not None: plt.title(title) plt.show() plt.close() sample_imgs, _ = next(iter(train_loader)) visualize_dequant_distribution(flow_dict["simple"]["model"], sample_imgs, title="Dequantization") visualize_dequant_distribution(flow_dict["vardeq"]["model"], sample_imgs, title="Variational dequantization") ``` The dequantization distribution in the first plot shows that the MNIST images have a strong bias towards 0 (black), and the distribution of them have a sharp border as mentioned before. The variational dequantization module has indeed learned a much smoother distribution with a Gaussian-like curve which can be modeled much better. For the other values, we would need to visualize the distribution $q(u|x)$ on a deeper level, depending on $x$. However, as all $u$'s interact and depend on each other, we would need to visualize a distribution in 784 dimensions, which is not that intuitive anymore. ## Conclusion In conclusion, we have seen how to implement our own normalizing flow, and what difficulties arise if we want to apply them on images. Dequantization is a crucial step in mapping the discrete images into continuous space to prevent underisable delta-peak solutions. While dequantization creates hypercubes with hard border, variational dequantization allows us to fit a flow much better on the data. This allows us to obtain a lower bits per dimension score, while not affecting the sampling speed. The most common flow element, the coupling layer, is simple to implement, and yet effective. Furthermore, multi-scale architectures help to capture the global image context while allowing us to efficiently scale up the flow. Normalizing flows are an interesting alternative to VAEs as they allow an exact likelihood estimate in continuous space, and we have the guarantee that every possible input $x$ has a corresponding latent vector $z$. However, even beyond continuous inputs and images, flows can be applied and allow us to exploit the data structure in latent space, as e.g. on graphs for the task of molecule generation [6]. Recent advances in [Neural ODEs](https://arxiv.org/pdf/1806.07366.pdf) allow a flow with infinite number of layers, called Continuous Normalizing Flows, whose potential is yet to fully explore. Overall, normalizing flows are an exciting research area which will continue over the next couple of years. ## References [1] Dinh, L., Sohl-Dickstein, J., and Bengio, S. (2017). “Density estimation using Real NVP,” In: 5th International Conference on Learning Representations, ICLR 2017. [Link](https://arxiv.org/abs/1605.08803) [2] Kingma, D. P., and Dhariwal, P. (2018). “Glow: Generative Flow with Invertible 1x1 Convolutions,” In: Advances in Neural Information Processing Systems, vol. 31, pp. 10215--10224. [Link](http://papers.nips.cc/paper/8224-glow-generative-flow-with-invertible-1x1-convolutions.pdf) [3] Ho, J., Chen, X., Srinivas, A., Duan, Y., and Abbeel, P. (2019). “Flow++: Improving Flow-Based Generative Models with Variational Dequantization and Architecture Design,” in Proceedings of the 36th International Conference on Machine Learning, vol. 97, pp. 2722–2730. [Link](https://arxiv.org/abs/1902.00275) [4] Durkan, C., Bekasov, A., Murray, I., and Papamakarios, G. (2019). “Neural Spline Flows,” In: Advances in Neural Information Processing Systems, pp. 7509–7520. [Link](http://papers.neurips.cc/paper/8969-neural-spline-flows.pdf) [5] Hoogeboom, E., Cohen, T. S., and Tomczak, J. M. (2020). “Learning Discrete Distributions by Dequantization,” arXiv preprint arXiv2001.11235v1. [Link](https://arxiv.org/abs/2001.11235) [6] Lippe, P., and Gavves, E. (2021). “Categorical Normalizing Flows via Continuous Transformations,” In: International Conference on Learning Representations, ICLR 2021. [Link](https://openreview.net/pdf?id=-GLNZeVDuik) --- [![Star our repository](https://img.shields.io/static/v1.svg?logo=star&label=⭐&message=Star%20Our%20Repository&color=yellow)](https://github.com/phlippe/uvadlc_notebooks/) If you found this tutorial helpful, consider ⭐-ing our repository. [![Ask questions](https://img.shields.io/static/v1.svg?logo=star&label=❔&message=Ask%20Questions&color=9cf)](https://github.com/phlippe/uvadlc_notebooks/issues) For any questions, typos, or bugs that you found, please raise an issue on GitHub. ---
github_jupyter
``` !pip install beautifulsoup4 import urllib.request import pandas as pd import numpy as np from bs4 import BeautifulSoup,Comment import re url = "http://www.hanban.org/hanbancn/template/ciotab_cn1.htm?v1" response = urllib.request.urlopen(url) #webContent = response.read().decode(response.headers.get_content_charset()) webContent = response.read().decode("utf-8") print(len(webContent)) # info_dict->{name:{'country', 'city', 'type', 'date', 'status', 'url'}} info_dict = {} tabContent = BeautifulSoup(webContent).find("div", class_="tabContent") continents = tabContent.find_all("div", class_="tcon") for con in continents: # 得到此大洲国家名的box nations = con.find("div", class_=re.compile(r"nation\d*")) # 去掉被注释的国家 for comment_country in nations(text=lambda text: isinstance(text, Comment)): comment_country.extract() # 得到此大洲国家列表 counties = [c.string for c in nations.find_all("a")] # 得到此大洲的学校box schools = con.find("div", class_=re.compile("tcon_nationBox\d*")) # 得到此大洲里各个国家的学校tab # find_all()会忽视被注释的tab,不需要再去掉注释 schools_nation = schools.find_all("div", class_="tcon_nation") # 确认国家列表与学校列表是对应的 if len(schools_nation) != len(counties): print("ERROR: schools tab no match the country.") break # 处理各个国家的学校 for idx, sc in enumerate(counties): # 处理孔子学院 kys = schools_nation[idx].find("div", class_="KY") # 检查是否有被注释的学院 comment_kys = kys.find_all(string=lambda text: isinstance(text, Comment)) # 处理被注释的学院 if comment_kys: for ckys in comment_kys: # 由于注释没有建树,所以需要在创建一个BeautifulSoup进行解析 ckys_bs = BeautifulSoup(ckys) for cky in ckys_bs.find_all("a"): ky_name = cky.string if ky_name: ky_name = ky_name.strip() ky_url = cky.get("href") or "NaN" info_dict[ky_name] = {'type':"孔子学院", 'country':counties[idx], 'status': 'hide', 'url':ky_url} # 处理没有被注释的学院, 如果名字相同会覆盖 kys = kys.find_all("a") # 处理每个学院 for ky in kys: ky_name = ky.string if ky_name: ky_name = ky_name.strip() ky_url = ky.get("href") or "NaN" #ky_id = re.findall(r'\d+', ky_url.split('/')[-1])[0] # 将信息保存到汇总字典中 info_dict[ky_name] = {'type':"孔子学院", 'country':counties[idx], 'status': 'show', 'url':ky_url} # 处理孔子课堂 coures = schools_nation[idx].find("div", class_="coures") # 检查是否有被注释的课堂 comment_coures = coures.find_all(string=lambda text: isinstance(text, Comment)) # 处理被注释的课堂 if comment_coures: for ccoures in comment_coures: # 由于注释没有建树,所以需要在创建一个BeautifulSoup进行解析 ccoures_bs = BeautifulSoup(ccoures) for ccoure in ccoures_bs.find_all("a"): coure_name = ccoure.string if coure_name: coure_name = coure_name.strip() coure_url = ccoure.get("href") or "NaN" info_dict[coure_name] = {'type':"孔子课堂", 'country':counties[idx], 'status': 'hide', 'url':coure_url} # 处理没有被注释的课题 coures = coures.find_all("a") # 处理每个课堂 for coure in coures: coure_name = coure.string if coure_name: coure_name = coure_name.strip() coure_url = coure.get("href") or "NaN" #coure_id = re.findall(r'\d+', coure_url.split('/')[-1])[0] info_dict[coure_name] = {'type':"孔子课堂", 'country':counties[idx], 'status': 'show', 'url':coure_url} print(len(info_dict)) print(info_dict["伊利诺伊大学香槟分校孔子学院"]) print(info_dict["北佛罗里达大学孔子学院"]) # 爬取所有子页面内容,保存到一个字典中 subsite_dict = {} def is_url(string_url): urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string_url) return urls for idx, name in enumerate(info_dict.keys()): if is_url(info_dict[name]['url']) and name not in subsite_dict: # 爬取页面,如果中断则继续 print(idx, "\tHandling:", name, "\turl:", info_dict[name]['url']) response = urllib.request.urlopen(info_dict[name]['url']) subwebContent = response.read().decode("utf-8") subsite_dict[name] = subwebContent # 解析各个孔子学院和孔子课题url中的"城市"和"创立时间" for idx, name in enumerate(info_dict.keys()): print(idx, "\tHandling:", name) # 默认NaN info_dict[name]['city'] = "NaN" info_dict[name]['date'] = "NaN" # 处理没有爬取到内容的情况 if not subsite_dict[name]: print("Skip1", name) continue # 创建解析器 bs = BeautifulSoup(subsite_dict[name]) # 有两种格式:<p>和<tbody> if bs.find("table"): all_info = bs.find("div", class_="main_leftCon").find_all("table") else: all_info = bs.find("div", class_="main_leftCon").find_all("p") # 如果网页没有目标内容,跳过 if not all_info: print("Skip2", name) continue # 逐条解析 for line in all_info: info = [word for word in line.stripped_strings] if not info: continue if info[0].find("城市") != -1: if len(info) >= 2: # 确认城市名存在 info_dict[name]['city'] = info[1] if info[0].find("时间") != -1: # 匹配时间,格式****年**月**日 date_string = re.findall(r'\d{4}[-/.|年]\d{1,2}[-\/.|月]\d{1,2}[-/.|日]*', info[-1]) # debug # print(info) # 确认日期存在 if date_string: # 去掉中文,转成标准格式为 ****-**-** date_list = re.findall(r'\d+',date_string[0]) date = '-'.join(date_list) info_dict[name]['date'] = date print(info_dict["伊利诺伊大学香槟分校孔子学院"]) print(info_dict["北佛罗里达大学孔子学院"]) print(info_dict["南太平洋大学孔子学院"]) print(info_dict["斯科奇•欧克伯恩学院孔子课堂"]) # Save the information to file df = pd.DataFrame.from_dict(info_dict, orient='index') df.to_excel("./hanban.xlsx", encoding='utf-8') ```
github_jupyter
# Distributional DQN The final improvement to the DQN agent [1] is using distributions instead of simple average values for learning the q value function. This algorithm was presented by Bellemare et al. (2018) [2]. In their math heavy manuscript, the authors introduce the distributional Belman operator and show that it defines a contraction for the policy evaluation case. Bellemare et al. suggest that using distributions leads to a "significantly better behaved" [2] reinforcement learning and underline their theoretical findings with much better results on the Arcade Learning Environment [3]. Distributional DQN is also one of the improvements that seem to have one of the biggest impact in the Rainbow manuscript [4]. ## Implementation The distributional part of the algorithm is maybe the most influenced by the Deep Reinforcement Learning Hands-On book [5]. To get a good understanding of both, the distributional Bellman operator and how to use it in the DQN agent, I thoroughly studied the book's implementation as a starting point. I later implemented the distributional operator in a way that appears slightly more elegant to me, even though I still did not manage to get rid of the special treatment for the last step of an episode. Some of the functionality for distributions was implemented in a DistributionalNetHelper class. This way other neural network architectures can just inherit this functionality, even though at this point I only implemented DuelingDQN with distrbutions. ## Results I start by comparing the Distributional DQN agent with two other agents. The different agents I compare are: 1. run024, which is the DQN agent with DDQN, Dueling DQN, n-step-reward and Prioritized Experience Replay. This agent so far had the most convincing results over the entire set of experiments. 2. run028, which uses all of the improvements mentioned above as wel as using Noisy Networks 3. run029 as run028 but using distributions instead of simple averages. The values for the support in the distributional agent were chosen similar to the manuscript [2]; the number of atoms was 51 with values between -10 and 10. These values are not optimal for some of the experiments, as will become evident later. On the radar plot, it appears that the distributional agent has the worst performance of all three agents. However, the barplot reveals that the DistributionalDQN agent shows good results on bandit, catch and catch_scale. ![Radar plot of te three different agents.](./figures/distributional_radar.png) ![Barplot of te three different agents.](./figures/distributional_barplot.png) The problem that the DistributionalDQN agent faces is its use of a fixed support while the different experiments have very different reward scales. In the bandit experiment the final reward (and thus the q-value) varies between 0 and 1, while the cartpole experiment, for example, has q-values somewhere between 0 and 1001. To investigate if using more appropriate vmin and vmax values yields better performance, I ran four of the experiments one more time with slightly different settings: 4. run030 uses the same settings as run029 but vmin = -1000 and vmax = 0, these settings were used for mountaincar and mountaincar_scale 5. run032 uses the same settings as run29 but vmin = 0, vmax = 1000, these settings were used for cartpole and cartpole_scale. The results are shown below. It is apparent that the performance greatly improves when an appropriate scale is chosen. ![Barplot of the three different agents.](./figures/distributional_barplot_tuned.png) In the scaled versions of the experiments, one can observe that the fine-tuned agent (run031) only performed well for the scale of 1.0, while the first set of parameters was better for smaller scales. This shows how strongly the choice of the support for the distribution influences the results. ![Results for the mountain car experiment with different scales.](./figures/distributional_mountaincar_scale.png) ## Discussion The results above show that the DistributionalDQN agent can learn good policies very well if an appropriate scale for the support is chosen. However, this is also the obvious problem of the approach in the form presented in [2]. When the support is not chosen in an appropriate way, using a simple average value is probably more robust than using distributions. In [2], distributions were used to improve the convergence properties of the DQN algorithms. Using distributions has even more potential. One could use the distributions to improve action selection, for example in the case of multimodal distributions with very different (non-deterministic) rewards and probabilities. Consider one action that certainly gives a reward of +1 and another action that gives a reward of +100 with a probability of 1\%. Even though both actions yield an average reward of 1 they certainly have very different risk profiles, and this could be assesed when the whole distributional information is available. ## References The figures here were produced by the analysis Jupyter Notebook from [the BSuite code repository](https://github.com/deepmind/bsuite) and [6]. [1] Mnih, Volodymyr, et al. Human-level control through deep reinforcement learning. Nature, 2015. [2] Bellemare, Marc G., Will Dabney, and Rémi Munos. "A distributional perspective on reinforcement learning." Proceedings of the 34th International Conference on Machine Learning-Volume 70. JMLR. org, 2017. [3] Bellemare, Marc G., et al. "The arcade learning environment: An evaluation platform for general agents." Journal of Artificial Intelligence Research 47 (2013): 253-279. [4] Hessel, Matteo, et al. Rainbow: Combining improvements in deep reinforcement learning. In: Thirty-Second AAAI Conference on Artificial Intelligence. 2018. [5] Lapan, Maxim. Deep Reinforcement Learning Hands-On, Packt Publishing Ltd, 2018.
github_jupyter
# Regularization Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that it has never seen! **You will learn to:** Use regularization in your deep learning models. Let's first import the packages you are going to use. ``` # import packages import numpy as np import matplotlib.pyplot as plt from reg_utils import sigmoid, relu, plot_decision_boundary, initialize_parameters, load_2D_dataset, predict_dec from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters import sklearn import sklearn.datasets import scipy.io from testCases import * %matplotlib inline plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' ``` **Problem Statement**: You have just been hired as an AI expert by the French Football Corporation. They would like you to recommend positions where France's goal keeper should kick the ball so that the French team's players can then hit it with their head. <img src="images/field_kiank.png" style="width:600px;height:350px;"> <caption><center> <u> **Figure 1** </u>: **Football field**<br> The goal keeper kicks the ball in the air, the players of each team are fighting to hit the ball with their head </center></caption> They give you the following 2D dataset from France's past 10 games. ``` train_X, train_Y, test_X, test_Y = load_2D_dataset() ``` Each dot corresponds to a position on the football field where a football player has hit the ball with his/her head after the French goal keeper has shot the ball from the left side of the football field. - If the dot is blue, it means the French player managed to hit the ball with his/her head - If the dot is red, it means the other team's player hit the ball with their head **Your goal**: Use a deep learning model to find the positions on the field where the goalkeeper should kick the ball. **Analysis of the dataset**: This dataset is a little noisy, but it looks like a diagonal line separating the upper left half (blue) from the lower right half (red) would work well. You will first try a non-regularized model. Then you'll learn how to regularize it and decide which model you will choose to solve the French Football Corporation's problem. ## 1 - Non-regularized model You will use the following neural network (already implemented for you below). This model can be used: - in *regularization mode* -- by setting the `lambd` input to a non-zero value. We use "`lambd`" instead of "`lambda`" because "`lambda`" is a reserved keyword in Python. - in *dropout mode* -- by setting the `keep_prob` to a value less than one You will first try the model without any regularization. Then, you will implement: - *L2 regularization* -- functions: "`compute_cost_with_regularization()`" and "`backward_propagation_with_regularization()`" - *Dropout* -- functions: "`forward_propagation_with_dropout()`" and "`backward_propagation_with_dropout()`" In each part, you will run this model with the correct inputs so that it calls the functions you've implemented. Take a look at the code below to familiarize yourself with the model. ``` def model(X, Y, learning_rate = 0.3, num_iterations = 30000, print_cost = True, lambd = 0, keep_prob = 1): """ Implements a three-layer neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SIGMOID. Arguments: X -- input data, of shape (input size, number of examples) Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (output size, number of examples) learning_rate -- learning rate of the optimization num_iterations -- number of iterations of the optimization loop print_cost -- If True, print the cost every 10000 iterations lambd -- regularization hyperparameter, scalar keep_prob - probability of keeping a neuron active during drop-out, scalar. Returns: parameters -- parameters learned by the model. They can then be used to predict. """ grads = {} costs = [] # to keep track of the cost m = X.shape[1] # number of examples layers_dims = [X.shape[0], 20, 3, 1] # Initialize parameters dictionary. parameters = initialize_parameters(layers_dims) # Loop (gradient descent) for i in range(0, num_iterations): # Forward propagation: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID. if keep_prob == 1: a3, cache = forward_propagation(X, parameters) elif keep_prob < 1: a3, cache = forward_propagation_with_dropout(X, parameters, keep_prob) # Cost function if lambd == 0: cost = compute_cost(a3, Y) else: cost = compute_cost_with_regularization(a3, Y, parameters, lambd) # Backward propagation. assert(lambd==0 or keep_prob==1) # it is possible to use both L2 regularization and dropout, # but this assignment will only explore one at a time if lambd == 0 and keep_prob == 1: grads = backward_propagation(X, Y, cache) elif lambd != 0: grads = backward_propagation_with_regularization(X, Y, cache, lambd) elif keep_prob < 1: grads = backward_propagation_with_dropout(X, Y, cache, keep_prob) # Update parameters. parameters = update_parameters(parameters, grads, learning_rate) # Print the loss every 10000 iterations if print_cost and i % 10000 == 0: print("Cost after iteration {}: {}".format(i, cost)) if print_cost and i % 1000 == 0: costs.append(cost) # plot the cost plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (x1,000)') plt.title("Learning rate =" + str(learning_rate)) plt.show() return parameters ``` Let's train the model without any regularization, and observe the accuracy on the train/test sets. ``` parameters = model(train_X, train_Y) print ("On the training set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) ``` The train accuracy is 94.8% while the test accuracy is 91.5%. This is the **baseline model** (you will observe the impact of regularization on this model). Run the following code to plot the decision boundary of your model. ``` plt.title("Model without regularization") axes = plt.gca() axes.set_xlim([-0.75,0.40]) axes.set_ylim([-0.75,0.65]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) ``` The non-regularized model is obviously overfitting the training set. It is fitting the noisy points! Lets now look at two techniques to reduce overfitting. ## 2 - L2 Regularization The standard way to avoid overfitting is called **L2 regularization**. It consists of appropriately modifying your cost function, from: $$J = -\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} \tag{1}$$ To: $$J_{regularized} = \small \underbrace{-\frac{1}{m} \sum\limits_{i = 1}^{m} \large{(}\small y^{(i)}\log\left(a^{[L](i)}\right) + (1-y^{(i)})\log\left(1- a^{[L](i)}\right) \large{)} }_\text{cross-entropy cost} + \underbrace{\frac{1}{m} \frac{\lambda}{2} \sum\limits_l\sum\limits_k\sum\limits_j W_{k,j}^{[l]2} }_\text{L2 regularization cost} \tag{2}$$ Let's modify your cost and observe the consequences. **Exercise**: Implement `compute_cost_with_regularization()` which computes the cost given by formula (2). To calculate $\sum\limits_k\sum\limits_j W_{k,j}^{[l]2}$ , use : ```python np.sum(np.square(Wl)) ``` Note that you have to do this for $W^{[1]}$, $W^{[2]}$ and $W^{[3]}$, then sum the three terms and multiply by $ \frac{1}{m} \frac{\lambda}{2} $. ``` # GRADED FUNCTION: compute_cost_with_regularization def compute_cost_with_regularization(A3, Y, parameters, lambd): """ Implement the cost function with L2 regularization. See formula (2) above. Arguments: A3 -- post-activation, output of forward propagation, of shape (output size, number of examples) Y -- "true" labels vector, of shape (output size, number of examples) parameters -- python dictionary containing parameters of the model Returns: cost - value of the regularized loss function (formula (2)) """ m = Y.shape[1] W1 = parameters["W1"] W2 = parameters["W2"] W3 = parameters["W3"] cross_entropy_cost = compute_cost(A3, Y) # This gives you the cross-entropy part of the cost ### START CODE HERE ### (approx. 1 line) L2_regularization_cost = None ### END CODER HERE ### cost = cross_entropy_cost + L2_regularization_cost return cost A3, Y_assess, parameters = compute_cost_with_regularization_test_case() print("cost = " + str(compute_cost_with_regularization(A3, Y_assess, parameters, lambd = 0.1))) ``` **Expected Output**: <table> <tr> <td> **cost** </td> <td> 1.78648594516 </td> </tr> </table> Of course, because you changed the cost, you have to change backward propagation as well! All the gradients have to be computed with respect to this new cost. **Exercise**: Implement the changes needed in backward propagation to take into account regularization. The changes only concern dW1, dW2 and dW3. For each, you have to add the regularization term's gradient ($\frac{d}{dW} ( \frac{1}{2}\frac{\lambda}{m} W^2) = \frac{\lambda}{m} W$). ``` # GRADED FUNCTION: backward_propagation_with_regularization def backward_propagation_with_regularization(X, Y, cache, lambd): """ Implements the backward propagation of our baseline model to which we added an L2 regularization. Arguments: X -- input dataset, of shape (input size, number of examples) Y -- "true" labels vector, of shape (output size, number of examples) cache -- cache output from forward_propagation() lambd -- regularization hyperparameter, scalar Returns: gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables """ m = X.shape[1] (Z1, A1, W1, b1, Z2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y ### START CODE HERE ### (approx. 1 line) dW3 = 1./m * np.dot(dZ3, A2.T) + None ### END CODE HERE ### db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True) dA2 = np.dot(W3.T, dZ3) dZ2 = np.multiply(dA2, np.int64(A2 > 0)) ### START CODE HERE ### (approx. 1 line) dW2 = 1./m * np.dot(dZ2, A1.T) + None ### END CODE HERE ### db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True) dA1 = np.dot(W2.T, dZ2) dZ1 = np.multiply(dA1, np.int64(A1 > 0)) ### START CODE HERE ### (approx. 1 line) dW1 = 1./m * np.dot(dZ1, X.T) + None ### END CODE HERE ### db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients X_assess, Y_assess, cache = backward_propagation_with_regularization_test_case() grads = backward_propagation_with_regularization(X_assess, Y_assess, cache, lambd = 0.7) print ("dW1 = "+ str(grads["dW1"])) print ("dW2 = "+ str(grads["dW2"])) print ("dW3 = "+ str(grads["dW3"])) ``` **Expected Output**: <table> <tr> <td> **dW1** </td> <td> [[-0.25604646 0.12298827 -0.28297129] [-0.17706303 0.34536094 -0.4410571 ]] </td> </tr> <tr> <td> **dW2** </td> <td> [[ 0.79276486 0.85133918] [-0.0957219 -0.01720463] [-0.13100772 -0.03750433]] </td> </tr> <tr> <td> **dW3** </td> <td> [[-1.77691347 -0.11832879 -0.09397446]] </td> </tr> </table> Let's now run the model with L2 regularization $(\lambda = 0.7)$. The `model()` function will call: - `compute_cost_with_regularization` instead of `compute_cost` - `backward_propagation_with_regularization` instead of `backward_propagation` ``` parameters = model(train_X, train_Y, lambd = 0.7) print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) ``` Congrats, the test set accuracy increased to 93%. You have saved the French football team! You are not overfitting the training data anymore. Let's plot the decision boundary. ``` plt.title("Model with L2-regularization") axes = plt.gca() axes.set_xlim([-0.75,0.40]) axes.set_ylim([-0.75,0.65]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) ``` **Observations**: - The value of $\lambda$ is a hyperparameter that you can tune using a dev set. - L2 regularization makes your decision boundary smoother. If $\lambda$ is too large, it is also possible to "oversmooth", resulting in a model with high bias. **What is L2-regularization actually doing?**: L2-regularization relies on the assumption that a model with small weights is simpler than a model with large weights. Thus, by penalizing the square values of the weights in the cost function you drive all the weights to smaller values. It becomes too costly for the cost to have large weights! This leads to a smoother model in which the output changes more slowly as the input changes. <font color='blue'> **What you should remember** -- the implications of L2-regularization on: - The cost computation: - A regularization term is added to the cost - The backpropagation function: - There are extra terms in the gradients with respect to weight matrices - Weights end up smaller ("weight decay"): - Weights are pushed to smaller values. ## 3 - Dropout Finally, **dropout** is a widely used regularization technique that is specific to deep learning. **It randomly shuts down some neurons in each iteration.** Watch these two videos to see what this means! <!-- To understand drop-out, consider this conversation with a friend: - Friend: "Why do you need all these neurons to train your network and classify images?". - You: "Because each neuron contains a weight and can learn specific features/details/shape of an image. The more neurons I have, the more featurse my model learns!" - Friend: "I see, but are you sure that your neurons are learning different features and not all the same features?" - You: "Good point... Neurons in the same layer actually don't talk to each other. It should be definitly possible that they learn the same image features/shapes/forms/details... which would be redundant. There should be a solution." !--> <center> <video width="620" height="440" src="images/dropout1_kiank.mp4" type="video/mp4" controls> </video> </center> <br> <caption><center> <u> Figure 2 </u>: Drop-out on the second hidden layer. <br> At each iteration, you shut down (= set to zero) each neuron of a layer with probability $1 - keep\_prob$ or keep it with probability $keep\_prob$ (50% here). The dropped neurons don't contribute to the training in both the forward and backward propagations of the iteration. </center></caption> <center> <video width="620" height="440" src="images/dropout2_kiank.mp4" type="video/mp4" controls> </video> </center> <caption><center> <u> Figure 3 </u>: Drop-out on the first and third hidden layers. <br> $1^{st}$ layer: we shut down on average 40% of the neurons. $3^{rd}$ layer: we shut down on average 20% of the neurons. </center></caption> When you shut some neurons down, you actually modify your model. The idea behind drop-out is that at each iteration, you train a different model that uses only a subset of your neurons. With dropout, your neurons thus become less sensitive to the activation of one other specific neuron, because that other neuron might be shut down at any time. ### 3.1 - Forward propagation with dropout **Exercise**: Implement the forward propagation with dropout. You are using a 3 layer neural network, and will add dropout to the first and second hidden layers. We will not apply dropout to the input layer or output layer. **Instructions**: You would like to shut down some neurons in the first and second layers. To do that, you are going to carry out 4 Steps: 1. In lecture, we dicussed creating a variable $d^{[1]}$ with the same shape as $a^{[1]}$ using `np.random.rand()` to randomly get numbers between 0 and 1. Here, you will use a vectorized implementation, so create a random matrix $D^{[1]} = [d^{[1](1)} d^{[1](2)} ... d^{[1](m)}] $ of the same dimension as $A^{[1]}$. 2. Set each entry of $D^{[1]}$ to be 0 with probability (`1-keep_prob`) or 1 with probability (`keep_prob`), by thresholding values in $D^{[1]}$ appropriately. Hint: to set all the entries of a matrix X to 0 (if entry is less than 0.5) or 1 (if entry is more than 0.5) you would do: `X = (X < 0.5)`. Note that 0 and 1 are respectively equivalent to False and True. 3. Set $A^{[1]}$ to $A^{[1]} * D^{[1]}$. (You are shutting down some neurons). You can think of $D^{[1]}$ as a mask, so that when it is multiplied with another matrix, it shuts down some of the values. 4. Divide $A^{[1]}$ by `keep_prob`. By doing this you are assuring that the result of the cost will still have the same expected value as without drop-out. (This technique is also called inverted dropout.) ``` # GRADED FUNCTION: forward_propagation_with_dropout def forward_propagation_with_dropout(X, parameters, keep_prob = 0.5): """ Implements the forward propagation: LINEAR -> RELU + DROPOUT -> LINEAR -> RELU + DROPOUT -> LINEAR -> SIGMOID. Arguments: X -- input dataset, of shape (2, number of examples) parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": W1 -- weight matrix of shape (20, 2) b1 -- bias vector of shape (20, 1) W2 -- weight matrix of shape (3, 20) b2 -- bias vector of shape (3, 1) W3 -- weight matrix of shape (1, 3) b3 -- bias vector of shape (1, 1) keep_prob - probability of keeping a neuron active during drop-out, scalar Returns: A3 -- last activation value, output of the forward propagation, of shape (1,1) cache -- tuple, information stored for computing the backward propagation """ np.random.seed(1) # retrieve parameters W1 = parameters["W1"] b1 = parameters["b1"] W2 = parameters["W2"] b2 = parameters["b2"] W3 = parameters["W3"] b3 = parameters["b3"] # LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SIGMOID Z1 = np.dot(W1, X) + b1 A1 = relu(Z1) ### START CODE HERE ### (approx. 4 lines) # Steps 1-4 below correspond to the Steps 1-4 described above. D1 = None # Step 1: initialize matrix D1 = np.random.rand(..., ...) D1 = None # Step 2: convert entries of D1 to 0 or 1 (using keep_prob as the threshold) A1 = None # Step 3: shut down some neurons of A1 A1 = None # Step 4: scale the value of neurons that haven't been shut down ### END CODE HERE ### Z2 = np.dot(W2, A1) + b2 A2 = relu(Z2) ### START CODE HERE ### (approx. 4 lines) D2 = None # Step 1: initialize matrix D2 = np.random.rand(..., ...) D2 = None # Step 2: convert entries of D2 to 0 or 1 (using keep_prob as the threshold) A2 = None # Step 3: shut down some neurons of A2 A2 = None # Step 4: scale the value of neurons that haven't been shut down ### END CODE HERE ### Z3 = np.dot(W3, A2) + b3 A3 = sigmoid(Z3) cache = (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) return A3, cache X_assess, parameters = forward_propagation_with_dropout_test_case() A3, cache = forward_propagation_with_dropout(X_assess, parameters, keep_prob = 0.7) print ("A3 = " + str(A3)) ``` **Expected Output**: <table> <tr> <td> **A3** </td> <td> [[ 0.36974721 0.00305176 0.04565099 0.49683389 0.36974721]] </td> </tr> </table> ### 3.2 - Backward propagation with dropout **Exercise**: Implement the backward propagation with dropout. As before, you are training a 3 layer network. Add dropout to the first and second hidden layers, using the masks $D^{[1]}$ and $D^{[2]}$ stored in the cache. **Instruction**: Backpropagation with dropout is actually quite easy. You will have to carry out 2 Steps: 1. You had previously shut down some neurons during forward propagation, by applying a mask $D^{[1]}$ to `A1`. In backpropagation, you will have to shut down the same neurons, by reapplying the same mask $D^{[1]}$ to `dA1`. 2. During forward propagation, you had divided `A1` by `keep_prob`. In backpropagation, you'll therefore have to divide `dA1` by `keep_prob` again (the calculus interpretation is that if $A^{[1]}$ is scaled by `keep_prob`, then its derivative $dA^{[1]}$ is also scaled by the same `keep_prob`). ``` # GRADED FUNCTION: backward_propagation_with_dropout def backward_propagation_with_dropout(X, Y, cache, keep_prob): """ Implements the backward propagation of our baseline model to which we added dropout. Arguments: X -- input dataset, of shape (2, number of examples) Y -- "true" labels vector, of shape (output size, number of examples) cache -- cache output from forward_propagation_with_dropout() keep_prob - probability of keeping a neuron active during drop-out, scalar Returns: gradients -- A dictionary with the gradients with respect to each parameter, activation and pre-activation variables """ m = X.shape[1] (Z1, D1, A1, W1, b1, Z2, D2, A2, W2, b2, Z3, A3, W3, b3) = cache dZ3 = A3 - Y dW3 = 1./m * np.dot(dZ3, A2.T) db3 = 1./m * np.sum(dZ3, axis=1, keepdims = True) dA2 = np.dot(W3.T, dZ3) ### START CODE HERE ### (≈ 2 lines of code) dA2 = None # Step 1: Apply mask D2 to shut down the same neurons as during the forward propagation dA2 = None # Step 2: Scale the value of neurons that haven't been shut down ### END CODE HERE ### dZ2 = np.multiply(dA2, np.int64(A2 > 0)) dW2 = 1./m * np.dot(dZ2, A1.T) db2 = 1./m * np.sum(dZ2, axis=1, keepdims = True) dA1 = np.dot(W2.T, dZ2) ### START CODE HERE ### (≈ 2 lines of code) dA1 = None # Step 1: Apply mask D1 to shut down the same neurons as during the forward propagation dA1 = None # Step 2: Scale the value of neurons that haven't been shut down ### END CODE HERE ### dZ1 = np.multiply(dA1, np.int64(A1 > 0)) dW1 = 1./m * np.dot(dZ1, X.T) db1 = 1./m * np.sum(dZ1, axis=1, keepdims = True) gradients = {"dZ3": dZ3, "dW3": dW3, "db3": db3,"dA2": dA2, "dZ2": dZ2, "dW2": dW2, "db2": db2, "dA1": dA1, "dZ1": dZ1, "dW1": dW1, "db1": db1} return gradients X_assess, Y_assess, cache = backward_propagation_with_dropout_test_case() gradients = backward_propagation_with_dropout(X_assess, Y_assess, cache, keep_prob = 0.8) print ("dA1 = " + str(gradients["dA1"])) print ("dA2 = " + str(gradients["dA2"])) ``` **Expected Output**: <table> <tr> <td> **dA1** </td> <td> [[ 0.36544439 0. -0.00188233 0. -0.17408748] [ 0.65515713 0. -0.00337459 0. -0. ]] </td> </tr> <tr> <td> **dA2** </td> <td> [[ 0.58180856 0. -0.00299679 0. -0.27715731] [ 0. 0.53159854 -0. 0.53159854 -0.34089673] [ 0. 0. -0.00292733 0. -0. ]] </td> </tr> </table> Let's now run the model with dropout (`keep_prob = 0.86`). It means at every iteration you shut down each neurons of layer 1 and 2 with 24% probability. The function `model()` will now call: - `forward_propagation_with_dropout` instead of `forward_propagation`. - `backward_propagation_with_dropout` instead of `backward_propagation`. ``` parameters = model(train_X, train_Y, keep_prob = 0.86, learning_rate = 0.3) print ("On the train set:") predictions_train = predict(train_X, train_Y, parameters) print ("On the test set:") predictions_test = predict(test_X, test_Y, parameters) ``` Dropout works great! The test accuracy has increased again (to 95%)! Your model is not overfitting the training set and does a great job on the test set. The French football team will be forever grateful to you! Run the code below to plot the decision boundary. ``` plt.title("Model with dropout") axes = plt.gca() axes.set_xlim([-0.75,0.40]) axes.set_ylim([-0.75,0.65]) plot_decision_boundary(lambda x: predict_dec(parameters, x.T), train_X, train_Y) ``` **Note**: - A **common mistake** when using dropout is to use it both in training and testing. You should use dropout (randomly eliminate nodes) only in training. - Deep learning frameworks like [tensorflow](https://www.tensorflow.org/api_docs/python/tf/nn/dropout), [PaddlePaddle](http://doc.paddlepaddle.org/release_doc/0.9.0/doc/ui/api/trainer_config_helpers/attrs.html), [keras](https://keras.io/layers/core/#dropout) or [caffe](http://caffe.berkeleyvision.org/tutorial/layers/dropout.html) come with a dropout layer implementation. Don't stress - you will soon learn some of these frameworks. <font color='blue'> **What you should remember about dropout:** - Dropout is a regularization technique. - You only use dropout during training. Don't use dropout (randomly eliminate nodes) during test time. - Apply dropout both during forward and backward propagation. - During training time, divide each dropout layer by keep_prob to keep the same expected value for the activations. For example, if keep_prob is 0.5, then we will on average shut down half the nodes, so the output will be scaled by 0.5 since only the remaining half are contributing to the solution. Dividing by 0.5 is equivalent to multiplying by 2. Hence, the output now has the same expected value. You can check that this works even when keep_prob is other values than 0.5. ## 4 - Conclusions **Here are the results of our three models**: <table> <tr> <td> **model** </td> <td> **train accuracy** </td> <td> **test accuracy** </td> </tr> <td> 3-layer NN without regularization </td> <td> 95% </td> <td> 91.5% </td> <tr> <td> 3-layer NN with L2-regularization </td> <td> 94% </td> <td> 93% </td> </tr> <tr> <td> 3-layer NN with dropout </td> <td> 93% </td> <td> 95% </td> </tr> </table> Note that regularization hurts training set performance! This is because it limits the ability of the network to overfit to the training set. But since it ultimately gives better test accuracy, it is helping your system. Congratulations for finishing this assignment! And also for revolutionizing French football. :-) <font color='blue'> **What we want you to remember from this notebook**: - Regularization will help you reduce overfitting. - Regularization will drive your weights to lower values. - L2 regularization and Dropout are two very effective regularization techniques.
github_jupyter
# Style Transfer In this notebook we will implement the style transfer technique from ["Image Style Transfer Using Convolutional Neural Networks" (Gatys et al., CVPR 2015)](http://www.cv-foundation.org/openaccess/content_cvpr_2016/papers/Gatys_Image_Style_Transfer_CVPR_2016_paper.pdf). The general idea is to take two images, and produce a new image that reflects the content of one but the artistic "style" of the other. We will do this by first formulating a loss function that matches the content and style of each respective image in the feature space of a deep network, and then performing gradient descent on the pixels of the image itself. The deep network we use as a feature extractor is [SqueezeNet](https://arxiv.org/abs/1602.07360), a small model that has been trained on ImageNet. You could use any network, but we chose SqueezeNet here for its small size and efficiency. Here's an example of the images you'll be able to produce by the end of this notebook: ![caption](example_styletransfer.png) ## Setup ``` import os import numpy as np from scipy.misc import imread, imresize import matplotlib.pyplot as plt import tensorflow as tf # Helper functions to deal with image preprocessing from cs231n.image_utils import load_image, preprocess_image, deprocess_image from cs231n.classifiers.squeezenet import SqueezeNet %matplotlib inline %load_ext autoreload %autoreload 2 def rel_error(x,y): return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) # Older versions of scipy.misc.imresize yield different results # from newer versions, so we check to make sure scipy is up to date. def check_scipy(): import scipy version = scipy.__version__.split('.') if int(version[0]) < 1: assert int(version[1]) >= 16, "You must install SciPy >= 0.16.0 to complete this notebook." check_scipy() ``` Load the pretrained SqueezeNet model. This model has been ported from PyTorch, see `cs231n/classifiers/squeezenet.py` for the model architecture. To use SqueezeNet, you will need to first **download the weights** by descending into the `cs231n/datasets` directory and running `get_squeezenet_tf.sh` . Note that if you ran `get_assignment3_data.sh` then SqueezeNet will already be downloaded. ``` # Load pretrained SqueezeNet model SAVE_PATH = 'cs231n/datasets/squeezenet.ckpt' if not os.path.exists(SAVE_PATH + ".index"): raise ValueError("You need to download SqueezeNet!") model=SqueezeNet() model.load_weights(SAVE_PATH) model.trainable=False # Load data for testing content_img_test = preprocess_image(load_image('styles/tubingen.jpg', size=192))[None] style_img_test = preprocess_image(load_image('styles/starry_night.jpg', size=192))[None] answers = np.load('style-transfer-checks-tf.npz') ``` ## Computing Loss We're going to compute the three components of our loss function now. The loss function is a weighted sum of three terms: content loss + style loss + total variation loss. You'll fill in the functions that compute these weighted terms below. ## Content loss We can generate an image that reflects the content of one image and the style of another by incorporating both in our loss function. We want to penalize deviations from the content of the content image and deviations from the style of the style image. We can then use this hybrid loss function to perform gradient descent **not on the parameters** of the model, but instead **on the pixel values** of our original image. Let's first write the content loss function. Content loss measures how much the feature map of the generated image differs from the feature map of the source image. We only care about the content representation of one layer of the network (say, layer $\ell$), that has feature maps $A^\ell \in \mathbb{R}^{1 \times H_\ell \times W_\ell \times C_\ell}$. $C_\ell$ is the number of filters/channels in layer $\ell$, $H_\ell$ and $W_\ell$ are the height and width. We will work with reshaped versions of these feature maps that combine all spatial positions into one dimension. Let $F^\ell \in \mathbb{R}^{M_\ell \times C_\ell}$ be the feature map for the current image and $P^\ell \in \mathbb{R}^{M_\ell \times C_\ell}$ be the feature map for the content source image where $M_\ell=H_\ell\times W_\ell$ is the number of elements in each feature map. Each row of $F^\ell$ or $P^\ell$ represents the vectorized activations of a particular filter, convolved over all positions of the image. Finally, let $w_c$ be the weight of the content loss term in the loss function. Then the content loss is given by: $L_c = w_c \times \sum_{i,j} (F_{ij}^{\ell} - P_{ij}^{\ell})^2$ ``` def content_loss(content_weight, content_current, content_original): """ Compute the content loss for style transfer. Inputs: - content_weight: scalar constant we multiply the content_loss by. - content_current: features of the current image, Tensor with shape [1, height, width, channels] - content_target: features of the content image, Tensor with shape [1, height, width, channels] Returns: - scalar content loss """ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # We provide this helper code which takes an image, a model (cnn), and returns a list of # feature maps, one per layer. def extract_features(x, cnn): """ Use the CNN to extract features from the input image x. Inputs: - x: A Tensor of shape (N, H, W, C) holding a minibatch of images that will be fed to the CNN. - cnn: A Tensorflow model that we will use to extract features. Returns: - features: A list of feature for the input images x extracted using the cnn model. features[i] is a Tensor of shape (N, H_i, W_i, C_i); recall that features from different layers of the network may have different numbers of channels (C_i) and spatial dimensions (H_i, W_i). """ features = [] prev_feat = x for i, layer in enumerate(cnn.net.layers[:-2]): next_feat = layer(prev_feat) features.append(next_feat) prev_feat = next_feat return features ``` Test your content loss. The error should be less than 1e-8. ``` def content_loss_test(correct): content_layer = 2 content_weight = 6e-2 c_feats = extract_features(content_img_test, model)[content_layer] bad_img = tf.zeros(content_img_test.shape) feats = extract_features(bad_img, model)[content_layer] student_output = content_loss(content_weight, c_feats, feats) error = rel_error(correct, student_output) print('Maximum error is {:.3f}'.format(error)) content_loss_test(answers['cl_out']) ``` ## Style loss Now we can tackle the style loss. For a given layer $\ell$, the style loss is defined as follows: First, compute the Gram matrix G which represents the correlations between the responses of each filter, where F is as above. The Gram matrix is an approximation to the covariance matrix -- we want the activation statistics of our generated image to match the activation statistics of our style image, and matching the (approximate) covariance is one way to do that. There are a variety of ways you could do this, but the Gram matrix is nice because it's easy to compute and in practice shows good results. Given a feature map $F^\ell$ of shape $(M_\ell, C_\ell)$, the Gram matrix has shape $(C_\ell, C_\ell)$ and its elements are given by: $$G_{ij}^\ell = \sum_k F^{\ell}_{ki} F^{\ell}_{kj}$$ Assuming $G^\ell$ is the Gram matrix from the feature map of the current image, $A^\ell$ is the Gram Matrix from the feature map of the source style image, and $w_\ell$ a scalar weight term, then the style loss for the layer $\ell$ is simply the weighted Euclidean distance between the two Gram matrices: $$L_s^\ell = w_\ell \sum_{i, j} \left(G^\ell_{ij} - A^\ell_{ij}\right)^2$$ In practice we usually compute the style loss at a set of layers $\mathcal{L}$ rather than just a single layer $\ell$; then the total style loss is the sum of style losses at each layer: $$L_s = \sum_{\ell \in \mathcal{L}} L_s^\ell$$ Begin by implementing the Gram matrix computation below: ``` def gram_matrix(features, normalize=True): """ Compute the Gram matrix from features. Inputs: - features: Tensor of shape (1, H, W, C) giving features for a single image. - normalize: optional, whether to normalize the Gram matrix If True, divide the Gram matrix by the number of neurons (H * W * C) Returns: - gram: Tensor of shape (C, C) giving the (optionally normalized) Gram matrices for the input image. """ # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ``` Test your Gram matrix code. You should see errors less than 0.001. ``` def gram_matrix_test(correct): gram = gram_matrix(extract_features(style_img_test, model)[4]) ### 4 instead of 5 - second MaxPooling layer error = rel_error(correct, gram) print('Maximum error is {:.3f}'.format(error)) gram_matrix_test(answers['gm_out']) ``` Next, implement the style loss: ``` def style_loss(feats, style_layers, style_targets, style_weights): """ Computes the style loss at a set of layers. Inputs: - feats: list of the features at every layer of the current image, as produced by the extract_features function. - style_layers: List of layer indices into feats giving the layers to include in the style loss. - style_targets: List of the same length as style_layers, where style_targets[i] is a Tensor giving the Gram matrix of the source style image computed at layer style_layers[i]. - style_weights: List of the same length as style_layers, where style_weights[i] is a scalar giving the weight for the style loss at layer style_layers[i]. Returns: - style_loss: A Tensor containing the scalar style loss. """ # Hint: you can do this with one for loop over the style layers, and should # not be short code (~5 lines). You will need to use your gram_matrix function. # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ``` Test your style loss implementation. The error should be less than 0.001. ``` def style_loss_test(correct): style_layers = [0, 3, 5, 6] style_weights = [300000, 1000, 15, 3] c_feats = extract_features(content_img_test, model) feats = extract_features(style_img_test, model) style_targets = [] for idx in style_layers: style_targets.append(gram_matrix(feats[idx])) s_loss = style_loss(c_feats, style_layers, style_targets, style_weights) error = rel_error(correct, s_loss) print('Error is {:.3f}'.format(error)) style_loss_test(answers['sl_out']) ``` ## Total-variation regularization It turns out that it's helpful to also encourage smoothness in the image. We can do this by adding another term to our loss that penalizes wiggles or "total variation" in the pixel values. You can compute the "total variation" as the sum of the squares of differences in the pixel values for all pairs of pixels that are next to each other (horizontally or vertically). Here we sum the total-variation regualarization for each of the 3 input channels (RGB), and weight the total summed loss by the total variation weight, $w_t$: $L_{tv} = w_t \times \left(\sum_{c=1}^3\sum_{i=1}^{H-1}\sum_{j=1}^{W} (x_{i+1,j,c} - x_{i,j,c})^2 + \sum_{c=1}^3\sum_{i=1}^{H}\sum_{j=1}^{W - 1} (x_{i,j+1,c} - x_{i,j,c})^2\right)$ In the next cell, fill in the definition for the TV loss term. To receive full credit, your implementation should not have any loops. ``` def tv_loss(img, tv_weight): """ Compute total variation loss. Inputs: - img: Tensor of shape (1, H, W, 3) holding an input image. - tv_weight: Scalar giving the weight w_t to use for the TV loss. Returns: - loss: Tensor holding a scalar giving the total variation loss for img weighted by tv_weight. """ # Your implementation should be vectorized and not require any loops! # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** pass # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** ``` Test your TV loss implementation. Error should be less than 0.001. ``` def tv_loss_test(correct): tv_weight = 2e-2 t_loss = tv_loss(content_img_test, tv_weight) error = rel_error(correct, t_loss) print('Error is {:.3f}'.format(error)) tv_loss_test(answers['tv_out']) ``` ## Style Transfer Lets put it all together and make some beautiful images! The `style_transfer` function below combines all the losses you coded up above and optimizes for an image that minimizes the total loss. ``` def style_transfer(content_image, style_image, image_size, style_size, content_layer, content_weight, style_layers, style_weights, tv_weight, init_random = False): """Run style transfer! Inputs: - content_image: filename of content image - style_image: filename of style image - image_size: size of smallest image dimension (used for content loss and generated image) - style_size: size of smallest style image dimension - content_layer: layer to use for content loss - content_weight: weighting on content loss - style_layers: list of layers to use for style loss - style_weights: list of weights to use for each layer in style_layers - tv_weight: weight of total variation regularization term - init_random: initialize the starting image to uniform random noise """ # Extract features from the content image content_img = preprocess_image(load_image(content_image, size=image_size)) feats = extract_features(content_img[None], model) content_target = feats[content_layer] # Extract features from the style image style_img = preprocess_image(load_image(style_image, size=style_size)) s_feats = extract_features(style_img[None], model) style_targets = [] # Compute list of TensorFlow Gram matrices for idx in style_layers: style_targets.append(gram_matrix(s_feats[idx])) # Set up optimization hyperparameters initial_lr = 3.0 decayed_lr = 0.1 decay_lr_at = 180 max_iter = 200 step = tf.Variable(0, trainable=False) boundaries = [decay_lr_at] values = [initial_lr, decayed_lr] learning_rate_fn = tf.keras.optimizers.schedules.PiecewiseConstantDecay(boundaries, values) # Later, whenever we perform an optimization step, we pass in the step. learning_rate = learning_rate_fn(step) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) # Initialize the generated image and optimization variables f, axarr = plt.subplots(1,2) axarr[0].axis('off') axarr[1].axis('off') axarr[0].set_title('Content Source Img.') axarr[1].set_title('Style Source Img.') axarr[0].imshow(deprocess_image(content_img)) axarr[1].imshow(deprocess_image(style_img)) plt.show() plt.figure() # Initialize generated image to content image if init_random: initializer = tf.random_uniform_initializer(0, 1) img = initializer(shape=content_img[None].shape) img_var = tf.Variable(img) print("Intializing randomly.") else: img_var = tf.Variable(content_img[None]) print("Initializing with content image.") for t in range(max_iter): with tf.GradientTape() as tape: tape.watch(img_var) feats = extract_features(img_var, model) # Compute loss c_loss = content_loss(content_weight, feats[content_layer], content_target) s_loss = style_loss(feats, style_layers, style_targets, style_weights) t_loss = tv_loss(img_var, tv_weight) loss = c_loss + s_loss + t_loss # Compute gradient grad = tape.gradient(loss, img_var) optimizer.apply_gradients([(grad, img_var)]) img_var.assign(tf.clip_by_value(img_var, -1.5, 1.5)) if t % 100 == 0: print('Iteration {}'.format(t)) plt.imshow(deprocess_image(img_var[0].numpy(), rescale=True)) plt.axis('off') plt.show() print('Iteration {}'.format(t)) plt.imshow(deprocess_image(img_var[0].numpy(), rescale=True)) plt.axis('off') plt.show() ``` ## Generate some pretty pictures! Try out `style_transfer` on the three different parameter sets below. Make sure to run all three cells. Feel free to add your own, but make sure to include the results of style transfer on the third parameter set (starry night) in your submitted notebook. * The `content_image` is the filename of content image. * The `style_image` is the filename of style image. * The `image_size` is the size of smallest image dimension of the content image (used for content loss and generated image). * The `style_size` is the size of smallest style image dimension. * The `content_layer` specifies which layer to use for content loss. * The `content_weight` gives weighting on content loss in the overall loss function. Increasing the value of this parameter will make the final image look more realistic (closer to the original content). * `style_layers` specifies a list of which layers to use for style loss. * `style_weights` specifies a list of weights to use for each layer in style_layers (each of which will contribute a term to the overall style loss). We generally use higher weights for the earlier style layers because they describe more local/smaller scale features, which are more important to texture than features over larger receptive fields. In general, increasing these weights will make the resulting image look less like the original content and more distorted towards the appearance of the style image. * `tv_weight` specifies the weighting of total variation regularization in the overall loss function. Increasing this value makes the resulting image look smoother and less jagged, at the cost of lower fidelity to style and content. Below the next three cells of code (in which you shouldn't change the hyperparameters), feel free to copy and paste the parameters to play around them and see how the resulting image changes. ``` # Composition VII + Tubingen params1 = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/composition_vii.jpg', 'image_size' : 192, 'style_size' : 512, 'content_layer' : 2, 'content_weight' : 5e-2, 'style_layers' : (0, 3, 5, 6), 'style_weights' : (20000, 500, 12, 1), 'tv_weight' : 5e-2 } style_transfer(**params1) # Scream + Tubingen params2 = { 'content_image':'styles/tubingen.jpg', 'style_image':'styles/the_scream.jpg', 'image_size':192, 'style_size':224, 'content_layer':2, 'content_weight':3e-2, 'style_layers':[0, 3, 5, 6], 'style_weights':[200000, 800, 12, 1], 'tv_weight':2e-2 } style_transfer(**params2) # Starry Night + Tubingen params3 = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/starry_night.jpg', 'image_size' : 192, 'style_size' : 192, 'content_layer' : 2, 'content_weight' : 6e-2, 'style_layers' : [0, 3, 5, 6], 'style_weights' : [300000, 1000, 15, 3], 'tv_weight' : 2e-2 } style_transfer(**params3) ``` ## Feature Inversion The code you've written can do another cool thing. In an attempt to understand the types of features that convolutional networks learn to recognize, a recent paper [1] attempts to reconstruct an image from its feature representation. We can easily implement this idea using image gradients from the pretrained network, which is exactly what we did above (but with two different feature representations). Now, if you set the style weights to all be 0 and initialize the starting image to random noise instead of the content source image, you'll reconstruct an image from the feature representation of the content source image. You're starting with total noise, but you should end up with something that looks quite a bit like your original image. (Similarly, you could do "texture synthesis" from scratch if you set the content weight to 0 and initialize the starting image to random noise, but we won't ask you to do that here.) Run the following cell to try out feature inversion. [1] Aravindh Mahendran, Andrea Vedaldi, "Understanding Deep Image Representations by Inverting them", CVPR 2015 ``` # Feature Inversion -- Starry Night + Tubingen params_inv = { 'content_image' : 'styles/tubingen.jpg', 'style_image' : 'styles/starry_night.jpg', 'image_size' : 192, 'style_size' : 192, 'content_layer' : 2, 'content_weight' : 6e-2, 'style_layers' : [0, 3, 5, 6], 'style_weights' : [0, 0, 0, 0], # we discard any contributions from style to the loss 'tv_weight' : 2e-2, 'init_random': True # we want to initialize our image to be random } style_transfer(**params_inv) ```
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.metrics import accuracy_score, classification_report, confusion_matrix from sklearn.cross_validation import train_test_split, cross_val_score, KFold from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier, export_graphviz from sklearn.grid_search import GridSearchCV from IPython.display import Image pd.set_option('chained_assignment', None) plt.style.use('ggplot') plt.rc('xtick.major', size=0) plt.rc('ytick.major', size=0) user_tags = pd.read_csv("user_tags_merge.csv") user_tags X = user_tags[['nail', 'person', 'sport', 'food','hair', 'wedding']] X['mix'] = X['hair'] + X['nail'] + X['wedding'] X.tail() y = user_tags['gender_male'] X=X.drop(['nail', 'sport','hair', 'wedding','mix'], axis=1) X.tail() np.random.seed = 0 xmin, xmax = -2, 12 ymin, ymax = -2, 17 index_male = y[y==1].index index_female = y[y==0].index fig, ax = plt.subplots() cm = plt.cm.RdBu cm_bright = ListedColormap(['#FF0000', '#0000FF']) sc = ax.scatter(X.loc[index_male, 'food'], X.loc[index_male, 'person']+(np.random.rand(len(index_male))-0.5)*0.1, color='b', label='male', alpha=0.3) sc = ax.scatter(X.loc[index_female, 'food'], X.loc[index_female, 'person']+(np.random.rand(len(index_female))-0.5)*0.1, color='r', label='female', alpha=0.3) ax.set_xlabel('food') ax.set_ylabel('person') ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) ax.legend(bbox_to_anchor=(1.4, 1.03)) plt.show() X = user_tags[['nail', 'person', 'sport', 'food','coffee','cake','beer','sky']] y = user_tags["gender_male"] clf = LogisticRegression() def cross_val(clf, X, y, K, random_state=0): cv = KFold(len(y), K, shuffle=True, random_state=random_state) scores = cross_val_score(clf, X, y, cv=cv) return scores scores = cross_val(clf, X, y, 6) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) clf = DecisionTreeClassifier(criterion='entropy', max_depth=2, min_samples_leaf=2) scores = cross_val(clf, X, y, 5) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0) tuned_parameters = [{'kernel': ['rbf'], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100, 1000]}, {'kernel': ['linear'], 'C': [1, 10, 100, 1000]}] clf = SVC(kernel='rbf', C=100) X = user_tags[['nail', 'person', 'sport', 'food','coffee','wedding','cake','beer']] y = user_tags["gender_male"] X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.5, random_state=1) clf.fit(X_train, y_train) clf.predict(X_val) y_val clf.score(X_val, y_val) XX = user_tags XX.tail() XX=XX.drop(['user_id', 'user_name','gender_male'], axis=1) X XX_train, XX_val, y_train, y_val = train_test_split(XX, y, train_size=0.5, random_state=1) clf = LogisticRegression() def cross_val(clf, XX, y, K, random_state=0): cv = KFold(len(y), K, shuffle=True, random_state=random_state) scores = cross_val_score(clf, XX, y, cv=cv) return scores scores = cross_val(clf, XX, y, 3) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) X = user_tags[['nail','hair', 'person', 'sport', 'food','night','coffee','wedding','cake','beer', 'dog', 'animal', 'tree','blossom','cat', 'flower','sky','nature','cherry']] y = user_tags["gender_male"] X['animal']=X['animal']+X['dog']+X['cat'] X['cosme']=X['hair']+X['nail'] X['nature']=X['nature']+X['sky']+X['flower']+X['tree']+X['blossom']+X['cherry'] X = X.drop(['nail','hair', 'dog', 'cat', 'sky','flower','tree','blossom','cherry'],axis=1) X.tail() clf = LogisticRegression() def cross_val(clf, X, y, K, random_state=0): cv = KFold(len(y), K, shuffle=True, random_state=random_state) scores = cross_val_score(clf, X, y, cv=cv) return scores for i in range(2,12): scores = cross_val(clf, X, y, i) print(i) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) clf = SVC(kernel='rbf', C=1000) for i in range(2,12): scores = cross_val(clf, X, y, i) print(i) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) clf = DecisionTreeClassifier(criterion='entropy', max_depth=5, min_samples_leaf=2) for i in range(2,12): scores = cross_val(clf, X, y, i) print(i) print('Scores:', scores) print('Mean Score: {0:.3f} (+/-{1:.3f})'.format(scores.mean(), scores.std()*2)) from sklearn.externals import joblib clf = LogisticRegression() clf.fit(X,y) joblib.dump(clf, 'clf.pkl') X.tail() ```
github_jupyter
## Polygon Environment Building Devising scenarios for the polygon-based environments. ``` %load_ext autoreload %autoreload 2 from mpb import MPB, MultipleMPB from plot_stats import plot_planner_stats, plot_smoother_stats from utils import latexify from table import latex_table from definitions import * import matplotlib as mpl import sys, os mpl.rcParams['mathtext.fontset'] = 'cm' # make sure to not use Level-3 fonts mpl.rcParams['pdf.fonttype'] = 42 import matplotlib.pyplot as plt from copy import deepcopy %config InlineBackend.figure_format='retina' ``` ### Polygon Environments ``` def visualize(scenario: str, start: {str: float}, goal: {str: float}, robot_model: str = None): m = MPB() m["max_planning_time"] = 60 m["env.start"] = start m["env.goal"] = goal m["env.type"] = "polygon" m["env.polygon.source"] = "polygon_mazes/%s.svg" % scenario if robot_model: print("Using robot model %s." % robot_model) m["env.collision.robot_shape_source"] = robot_model m.set_planners(['informed_rrt_star']) m.set_planners(['bfmt']) m["steer.car_turning_radius"] = 2 # m.set_planners(["sbpl_mha"]) m["sbpl.scaling"] = 1 if m.run(id="test_%s" % scenario, runs=1) == 0: m.visualize_trajectories(draw_start_goal_thetas=True, plot_every_nth_polygon=10, silence=True, save_file="plots/%s.pdf" % scenario) m.print_info() # visualize("parking2", # {"theta": -1.57, "x": 12.3, "y": -2.73}, # {"theta": 0, "x": 2.5, "y": -7.27}) # visualize("parking2", # {"theta": -1.57, "x": 12.3, "y": -2.73}, # {"theta": 3.14, "x": 2.5, "y": -7.27}) scenarios = [ ("parking1", {"theta": 0, "x": 2, "y": -7.27}, {"theta": -1.58, "x": 9, "y": -11.72}), ("parking2", {"theta": 0, "x": 2.5, "y": -7.27}, {"theta": -1.57, "x": 12, "y": -3}), ("parking3", {"theta": 0, "x": 3.82, "y": -13}, {"theta": 0, "x": 29, "y": -15.5}), ("warehouse", {"theta": -1.58, "x": 7.5, "y": -10}, {"theta": 1.58, "x": 76.5, "y": -10}, "polygon_mazes/warehouse_robot.svg"), ("warehouse2", {"theta": -1.58, "x": 7.5, "y": -10}, {"theta": -1.58, "x": 116, "y": -70}, "polygon_mazes/warehouse_robot.svg") ] list(map(lambda x: visualize(*x), scenarios)); ``` # Figurehead Figure 1 to showcase Bench-MR. ``` m = MPB() scenario = "warehouse" m["max_planning_time"] = 30 m["env.start"] = {"theta": -1.58, "x": 7.5, "y": -10} m["env.goal"] = {"theta": 1.58, "x": 76.5, "y": -10} m["env.type"] = "polygon" m["env.polygon.source"] = "polygon_mazes/%s.svg" % scenario m["env.collision.robot_shape_source"] = "polygon_mazes/warehouse_robot.svg" m.set_planners([]) m.set_planners(['bfmt', 'cforest', 'prm', 'prm_star', 'informed_rrt_star', 'sbpl_mha']) m["steer.car_turning_radius"] = 2 m["sbpl.scaling"] = 1 m.run(id="test_%s" % scenario, runs=1) m.print_info() m.visualize_trajectories(ignore_planners='cforest, bfmt', draw_start_goal_thetas=True, plot_every_nth_polygon=8, fig_width=8, fig_height=8, silence=True, save_file="plots/%s.pdf" % scenario, num_colors=10) ```
github_jupyter
# Classical Logic Gates with Quantum Circuits ``` from qiskit import * from qiskit.tools.visualization import plot_histogram import numpy as np ``` Using the NOT gate (expressed as `x` in Qiskit), the CNOT gate (expressed as `cx` in Qiskit) and the Toffoli gate (expressed as `ccx` in Qiskit) create functions to implement the XOR, AND, NAND and OR gates. An implementation of the NOT gate is provided as an example. ## NOT gate This function takes a binary string input (`'0'` or `'1'`) and returns the opposite binary output'. ``` def NOT(input): q = QuantumRegister(1) # a qubit in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # We encode '0' as the qubit state |0⟩, and '1' as |1⟩ # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0' # For an input of '1', we do an x to rotate the |0⟩ to |1⟩ if input=='1': qc.x( q[0] ) # Now we've encoded the input, we can do a NOT on it using x qc.x( q[0] ) # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0] qc.measure( q[0], c[0] ) # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1) output = next(iter(job.result().get_counts())) return output ``` ## XOR gate Takes two binary strings as input and gives one as output. The output is `'0'` when the inputs are equal and `'1'` otherwise. ``` def XOR(input1,input2): q = QuantumRegister(2) # two qubits in which to encode and manipulate the input c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[1],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output ``` ## AND gate Takes two binary strings as input and gives one as output. The output is `'1'` only when both the inputs are `'1'`. ``` def AND(input1,input2): q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output ``` ## NAND gate Takes two binary strings as input and gives one as output. The output is `'0'` only when both the inputs are `'1'`. ``` def NAND(input1,input2): q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output ``` ## OR gate Takes two binary strings as input and gives one as output. The output is `'1'` if either input is `'1'`. ``` def OR(input1,input2): q = QuantumRegister(3) # two qubits in which to encode the input, and one for the output c = ClassicalRegister(1) # a bit to store the output qc = QuantumCircuit(q, c) # this is where the quantum program goes # YOUR QUANTUM PROGRAM GOES HERE qc.measure(q[2],c[0]) # YOU CAN CHANGE THIS IF YOU WANT TO # We'll run the program on a simulator backend = Aer.get_backend('qasm_simulator') # Since the output will be deterministic, we can use just a single shot to get it job = execute(qc,backend,shots=1,memory=True) output = job.result().get_memory()[0] return output ``` ## Tests The following code runs the functions above for all possible inputs, so that you can check whether they work. ``` print('\nResults for the NOT gate') for input in ['0','1']: print(' Input',input,'gives output',NOT(input)) print('\nResults for the XOR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',XOR(input1,input2)) print('\nResults for the AND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',AND(input1,input2)) print('\nResults for the NAND gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',NAND(input1,input2)) print('\nResults for the OR gate') for input1 in ['0','1']: for input2 in ['0','1']: print(' Inputs',input1,input2,'give output',OR(input1,input2)) import qiskit qiskit.__qiskit_version__ ```
github_jupyter
# Train a Simple Audio Recognition model for microcontroller use This notebook demonstrates how to train a 20kb [Simple Audio Recognition](https://www.tensorflow.org/tutorials/sequences/audio_recognition) model for [TensorFlow Lite for Microcontrollers](https://tensorflow.org/lite/microcontrollers/overview). It will produce the same model used in the [micro_speech](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/lite/micro/examples/micro_speech) example application. The model is designed to be used with [Google Colaboratory](https://colab.research.google.com). <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/micro/examples/micro_speech/train_speech_model.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/micro/examples/micro_speech/train_speech_model.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> The notebook runs Python scripts to train and freeze the model, and uses the TensorFlow Lite converter to convert it for use with TensorFlow Lite for Microcontrollers. **Training is much faster using GPU acceleration.** Before you proceed, ensure you are using a GPU runtime by going to **Runtime -> Change runtime type** and selecting **GPU**. Training 18,000 iterations will take 1.5-2 hours on a GPU runtime. ## Configure training The following `os.environ` lines can be customized to set the words that will be trained for, and the steps and learning rate of the training. The default values will result in the same model that is used in the micro_speech example. Run the cell to set the configuration: ``` import os # A comma-delimited list of the words you want to train for. # The options are: yes,no,up,down,left,right,on,off,stop,go # All other words will be used to train an "unknown" category. os.environ["WANTED_WORDS"] = "yes,no" # The number of steps and learning rates can be specified as comma-separated # lists to define the rate at each stage. For example, # TRAINING_STEPS=15000,3000 and LEARNING_RATE=0.001,0.0001 # will run 18,000 training loops in total, with a rate of 0.001 for the first # 15,000, and 0.0001 for the final 3,000. os.environ["TRAINING_STEPS"]="15000,3000" os.environ["LEARNING_RATE"]="0.001,0.0001" # Calculate the total number of steps, which is used to identify the checkpoint # file name. total_steps = sum(map(lambda string: int(string), os.environ["TRAINING_STEPS"].split(","))) os.environ["TOTAL_STEPS"] = str(total_steps) # Print the configuration to confirm it !echo "Training these words: ${WANTED_WORDS}" !echo "Training steps in each stage: ${TRAINING_STEPS}" !echo "Learning rate in each stage: ${LEARNING_RATE}" !echo "Total number of training steps: ${TOTAL_STEPS}" ``` ## Install dependencies Next, we'll install a GPU build of TensorFlow, so we can use GPU acceleration for training. ``` # Replace Colab's default TensorFlow install with a more recent # build that contains the operations that are needed for training !pip uninstall -y tensorflow tensorflow_estimator tensorboard !pip install -q tf-estimator-nightly==1.14.0.dev2019072901 tf-nightly-gpu==1.15.0.dev20190729 ``` We'll also clone the TensorFlow repository, which contains the scripts that train and freeze the model. ``` # Clone the repository from GitHub !git clone -q https://github.com/tensorflow/tensorflow # Check out a commit that has been tested to work # with the build of TensorFlow we're using !git -c advice.detachedHead=false -C tensorflow checkout 17ce384df70 ``` ## Load TensorBoard Now, set up TensorBoard so that we can graph our accuracy and loss as training proceeds. ``` # Delete any old logs from previous runs !rm -rf /content/retrain_logs # Load TensorBoard %load_ext tensorboard %tensorboard --logdir /content/retrain_logs ``` ## Begin training Next, run the following script to begin training. The script will first download the training data: ``` !python tensorflow/tensorflow/examples/speech_commands/train.py \ --model_architecture=tiny_conv --window_stride=20 --preprocess=micro \ --wanted_words=${WANTED_WORDS} --silence_percentage=25 --unknown_percentage=25 \ --quantize=1 --verbosity=WARN --how_many_training_steps=${TRAINING_STEPS} \ --learning_rate=${LEARNING_RATE} --summaries_dir=/content/retrain_logs \ --data_dir=/content/speech_dataset --train_dir=/content/speech_commands_train \ ``` ## Freeze the graph Once training is complete, run the following cell to freeze the graph. ``` !python tensorflow/tensorflow/examples/speech_commands/freeze.py \ --model_architecture=tiny_conv --window_stride=20 --preprocess=micro \ --wanted_words=${WANTED_WORDS} --quantize=1 --output_file=/content/tiny_conv.pb \ --start_checkpoint=/content/speech_commands_train/tiny_conv.ckpt-${TOTAL_STEPS} ``` ## Convert the model Run this cell to use the TensorFlow Lite converter to convert the frozen graph into the TensorFlow Lite format, fully quantized for use with embedded devices. ``` !toco \ --graph_def_file=/content/tiny_conv.pb --output_file=/content/tiny_conv.tflite \ --input_shapes=1,49,40,1 --input_arrays=Reshape_2 --output_arrays='labels_softmax' \ --inference_type=QUANTIZED_UINT8 --mean_values=0 --std_dev_values=9.8077 ``` The following cell will print the model size, which will be under 20 kilobytes. ``` import os model_size = os.path.getsize("/content/tiny_conv.tflite") print("Model is %d bytes" % model_size) ``` Finally, we use xxd to transform the model into a source file that can be included in a C++ project and loaded by TensorFlow Lite for Microcontrollers. ``` # Install xxd if it is not available !apt-get -qq install xxd # Save the file as a C source file !xxd -i /content/tiny_conv.tflite > /content/tiny_conv.cc # Print the source file !cat /content/tiny_conv.cc ```
github_jupyter
En el mundo Qt tenemos una herramienta [RAD (Rapid Application Development)](https://es.wikipedia.org/wiki/Desarrollo_r%C3%A1pido_de_aplicaciones). Esta herramienta se llama Qt DesigneEste nuevo capítulo es el último en los que enumeramos los widgets disponibles dentro de Designer, en este caso le toca el turno a los *display widgets* o widgets que nos permiten mostrar información en distintos "formatos".** Índice: * [Instalación de lo que vamos a necesitar](https://pybonacci.org/2019/11/12/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-00-instalacion/). * [Qt, versiones y diferencias](https://pybonacci.org/2019/11/21/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-01-qt-versiones-y-bindings/). * [Hola, Mundo](https://pybonacci.org/2019/11/26/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-02-hola-mundo/). * [Módulos en Qt](https://pybonacci.org/2019/12/02/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-03-modulos-qt/). * [Añadimos icono a la ventana principal](https://pybonacci.org/2019/12/26/curso-de-creacion-de-guis-con-qt5-y-python-capitulo-04-icono-de-la-ventana/). * [Tipos de ventana en un GUI](https://pybonacci.org/2020/01/31/curso-de-creacion-de-guis-con-qt-capitulo-05-ventanas-principales-diferencias/). * [Ventana inicial de carga o Splashscreen](https://pybonacci.org/2020/02/26/curso-de-creacion-de-guis-con-qt-capitulo-06-splash-screen/) * [Menu principal. Introducción](https://pybonacci.org/2020/03/18/curso-de-creacion-de-guis-con-qt-capitulo-07-menu/). * [Mejorando algunas cosas vistas](https://pybonacci.org/2020/03/26/curso-de-creacion-de-guis-con-qt-capitulo-08-mejorando-lo-visto/). * [Gestión de eventos o Acción y reacción](https://pybonacci.org/2020/03/27/curso-de-creacion-de-guis-con-qt-capitulo-09-signals-y-slots/). * [Introducción a Designer](https://pybonacci.org/2020/04/14/curso-de-creacion-de-guis-con-qt-capitulo-10-introduccion-a-designer/). * [Los Widgets vistos a través de Designer: Primera parte](https://pybonacci.org/2020/05/01/curso-de-creacion-de-guis-con-qt-capitulo-11-widgets-en-designer-i/). * [Los Widgets vistos a través de Designer: Segunda parte](https://pybonacci.org/2020/05/02/curso-de-creacion-de-guis-con-qt-capitulo-12:-widgets-en-designer-(ii)/). * [Los Widgets vistos a través de Designer: Tercera parte](https://pybonacci.org/2020/05/03/curso-de-creacion-de-guis-con-qt-capitulo-13-widgets-en-designer-iii/). * [Los Widgets vistos a través de Designer: Cuarta parte](https://pybonacci.org/2020/05/04/curso-de-creacion-de-guis-con-qt-capitulo-14-widgets-en-designer-iv/). * [Los Widgets vistos a través de Designer: Quinta parte](https://pybonacci.org/2020/05/05/curso-de-creacion-de-guis-con-qt-capitulo-15-widgets-en-designer-v/). * [Los Widgets vistos a través de Designer: Sexta parte](https://pybonacci.org/2020/05/06/curso-de-creacion-de-guis-con-qt-capitulo-16:-widgets-en-designer-(vi)/) (este capítulo). * TBD… (lo actualizaré cuando tenga más claro los siguientes pasos). [Los materiales para este capítulo los podéis descargar de [aquí](https://github.com/kikocorreoso/pyboqt/tree/chapter16)] **[INSTALACIÓN] Si todavía no has pasado por el [inicio del curso, donde explico cómo poner a punto todo](https://pybonacci.org/2019/11/12/curso-de-creacion-de-guis-con-qt-capitulo-00:-instalacion/), ahora es un buen momento para hacerlo y después podrás seguir con esta nueva receta.** En este último vídeo donde vemos los widgets que tenemos en Designer le damos un repaso a widgets que permiten mostrar información en distintas formas. El vídeo está a continuación: ``` from IPython.display import Video Video("https://libre.video/download/videos/9ee5e77e-5eac-4359-b75b-569060091a3b-360.mp4") ``` Transcripción del vídeo a continuación: *Y ya solo nos queda una sección, la de los Widgets de exhibir cosas o de display. Tenemos, por ejemplo, las etiquetas que podemos usar en múltiples sitios. Luego tenemos el textbrowser que es como una etiqueta grande. Extiende al TextEdit que vimos anteriormente, en los widgets de input, pero es de solo lectura. Se puede usar para mostrar texto que el usuario no pueda editar. Tenemos un GraphicView que nos puede valer para meter, por ejemplo, gráficos de Matplotlib. Tenemos un CalendarWidget para seleccionar fechas. Podemos usar un LCD para enseñar números, similar al de una calculadora de mano. Podemos usar barras de progreso. Líneas horizontales o verticales que nos permitan separar cosas dentro de la ventana. Un Widget para meter gráficos OpenGL. El QQuickWidget no lo voy a comentar ahora, quizá en el futuro hagamos algo con esto pero a día de hoy no lo tengo todavía muy claro. Por último, tenemos el QWebEngineView que nos permite visualizar documentos web. Por ejemplo, le puedo pedir que me muestre una url y podemos ver el curso de creación de GUIs con Qt dentro del GUI con el que estamos trasteando.* Y con todo esto creo que ya es suficiente. En el próximo capítulo más.
github_jupyter
``` import os, sys, glob, scipy import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns ``` ## Plan 1. Describe the task 2. Make the simplest visualization you can think of that contains: - the Dependent Variable, i.e. the behavior of the participants that you're trying to model/predict/explain/account for/etc - the Independent Variable(s), i.e. the features of the trial that you think might influence behavior - draw each trial as a point on this graph 3. Think of possible models that would generate similar values for the DV given the observed values for the IV ## 2. Make a visualization ##### Load some data ``` base_dir = os.path.realpath('') data_dir = base_dir + '/Data' data = pd.read_csv(data_dir + '/Study1_UG.csv') data = data[['sub','trial','unfairness','choice']] data['offer'] = 100 - data['unfairness'] data.head() ``` ##### Make a simple plot ``` sub = 2 sub_data = data.query('sub == 2') sub_data.head() ``` ##### Problem 1. Plot each trial independently, use transparency to visualize overlap ##### Problem 2. Plot the average over trials with the same offer ## 3. Think of a model that can recreate this plot ###### Problem 3. Define the following models - Model 1: always accept. - Model 2: always reject. - Model 3: act randomly. - Model 4: maximize payoff ('greed'). - Model 5: minimize payoff ('inverse greed'). - Model 6: unfairness punisher (reject with a probability P proportional to the unfairness of the offer). - Model 7: inequity aversion. ``` # Always accept def model_1(offer): return choice # Always reject def model_2(offer): return choice # Act random def model_3(offer): return choice # Maximize payoff def model_4(offer): return choice # Minimize payoff def model_5(offer): return choice # Unfairness punisher def model_6(offer): return choice # Inequity aversion def model_7(offer): return choice ``` ## 4. Simulating task data ``` simulated_sub_data = sub_data[['trial','offer','choice']].copy() simulated_sub_data['choice'] = np.nan simulated_sub_data.head() ``` ##### Problem 4. Simulate task data using a model Use one of the models you have defined above to simulate choices for the simulated_sub_data dataframe. So here we have a dataset – basically a list of trials that together constitute an experiment – with simulated task data! We've basically generated a pseudo-subject based on one of the models we defined. In the next steps, we will compare such simulated datasets to our actually observed subject data. The more similar a model's simulation is to observed task data, the better the model 'fits' the data. ## For next time - Get Joey's data from GitHub - Try to code models 5, 6, and 7 - Simulate data from each model
github_jupyter
<a href="https://colab.research.google.com/github/AnacletoLAB/grape/blob/main/tutorials/High_performance_graph_algorithms.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # High performance graph algorithms A number of high performance algorithms have been implemented in Ensmallen, a considerable portion of which is an implementation of algorithms described in the literature by [David Bader](https://davidbader.net/), who we thank for his contribution to the field of graph algorithms. See below for the algorithms available in Ensmallen. Note that all of these algorithms are highly parallel implementations, and these benchmarks are being run on COLAB which typically provides virtual machines with a very small number of cores: on a machine with a reasonable number of cores they will execute much faster. To install the GraPE library run: ```bash pip install grape ``` To install exclusively the Ensmallen module, which may be useful when the TensorFlow dependency causes problems, do run: ```bash pip install ensmallen ``` ``` ! pip install -q ensmallen ``` ## Retrieving a graph to run the sampling on In this tutorial we will run samples on one of the graph from the ones available from the automatic graph retrieval of Ensmallen, namely the [Homo Sapiens graph from STRING](https://string-db.org/cgi/organisms). If you want to load a graph from an edge list, just follow the examples provided from the [add reference to tutorial]. ``` from ensmallen.datasets.string import HomoSapiens ``` Retrieving and loading the graph ``` graph = HomoSapiens() ``` We compute the graph report: ``` graph ``` Enable the speedups ``` graph.enable() ``` ## Random Spanning arborescence The spanning arborescence algorithm computes a set of edges, an [Arborescence](https://en.wikipedia.org/wiki/Arborescence_(graph_theory)), that is spanning, i.e cover all the nodes in the graph. This is an implementation of [A fast, parallel spanning tree algorithm for symmetric multiprocessors (SMPs)](https://davidbader.net/publication/2005-bc/2005-bc.pdf). ``` %%time spanning_arborescence_edges = graph.spanning_arborescence() ``` ## Connected components The [connected components](https://en.wikipedia.org/wiki/Component_(graph_theory)) of a graph are the set of nodes connected one another by edges. ``` %%time ( connected_component_ids, number_of_connected_components, minimum_component_size, maximum_component_size ) = graph.connected_components() ``` ## Diameter The following is an implementation of [On computing the diameter of real-world undirected graphs](https://who.rocq.inria.fr/Laurent.Viennot/road/papers/ifub.pdf). ``` %%time diameter = graph.get_diameter(ignore_infinity=True) ``` Note that most properties that boil down to a single value once computed are stored in a cache structure, so recomputing the diameter once it is done takes a significant smaller time. ``` %%time diameter = graph.get_diameter(ignore_infinity=True) ``` ## Clustering coefficient and triangles This is an implementation of [Faster Clustering Coefficient Using Vertex Covers](https://davidbader.net/publication/2013-g-ba/2013-g-ba.pdf), proving the average clustering coefficient, the total number of triangles and the number of triangles per node. ``` %%time graph.get_number_of_triangles() %%time graph.get_number_of_triangles_per_node() %%time graph.get_average_clustering_coefficient() %%time graph.get_clustering_coefficient_per_node() ```
github_jupyter
``` %matplotlib inline import xarray as xr import os import pandas as pd import numpy as np import skdownscale import dask import dask.array as da import dask.distributed as dd import rhg_compute_tools.kubernetes as rhgk from utils import _convert_lons, _remove_leap_days, _convert_ds_longitude from regridding import apply_weights import intake import xesmf as xe import warnings warnings.filterwarnings("ignore") # output directory write_direc = '/gcs/rhg-data/climate/downscaled/workdir' ``` This notebook implements a scaling test for bias correction, using the BCSDTemperature model from `scikit-downscale`, with the daily BCSD bias correction method as implemented in the NASA-NEX dataset. Datasets used include a CMIP6 model from a historical run (`GISS-E2-1-G` from NASA) and GMFD (obs). Historical/training period is taken as 1980-1982, and the future/predict period is 1990-1991. GMFD is coarsened to the NASA `GISS-E2-1-G` grid for this bias correction test. Note that the purpose of this notebook is intended to allow us to get a better estimate of timing for global daily bias correction. Future work will build on this notebook to: - replace GMFD with ERA5 - combine this notebook with `SD_prototype.ipynb`, along with NASA-NEX data and a corresponding CMIP5 model, and over a limited domain, to test our implementation of BCSD against NASA-NEX for a limited domain. That notebook will be used as a prototype for our downscaling pipeline and can be modified to become a system test for the pipeline (1-3 gridcells for CI/CD, limited domain for science testing). This notebook was also used as a resource and checkpoint for this workflow: https://github.com/jhamman/scikit-downscale/blob/ecahm2020/examples/2020ECAHM-scikit-downscale.ipynb ``` # client, cluster = rhgk.get_standard_cluster(extra_pip_packages="git+https://github.com/dgergel/xsd.git@feature/implement_daily_bcsd") client, cluster = rhgk.get_standard_cluster(extra_pip_packages="git+https://github.com/jhamman/scikit-downscale.git") cluster cluster.scale(40) '''a = da.ones((1000, 1000, 1000)) a.mean().compute()''' from skdownscale.pointwise_models import PointWiseDownscaler, BcsdTemperature train_slice = slice('1980', '1989') # train time range holdout_slice = slice('1990', '2000') # prediction time range # client.get_versions(check=True) # use GMFD as standin for ERA-5 tmax_obs = xr.open_mfdataset(os.path.join('/gcs/rhg-data/climate/source_data/GMFD/tmax', 'tmax_0p25_daily_198*'), concat_dim='time', combine='nested', parallel=True).squeeze(drop=True).rename({'latitude': 'lat', 'longitude': 'lon'}) '''tmax_obs = xr.open_dataset(os.path.join('/gcs/rhg-data/climate/source_data/GMFD/tmax', 'tmax_0p25_daily_1980-1980.nc')).rename({'latitude': 'lat', 'longitude': 'lon'})''' # standardize longitudes tmax_obs = _convert_ds_longitude(tmax_obs, lon_name='lon') # remove leap days tmax_obs = _remove_leap_days(tmax_obs) obs_subset = tmax_obs.sel(time=train_slice) ``` get some CMIP6 data ``` # search the cmip6 catalog col = intake.open_esm_datastore("https://storage.googleapis.com/cmip6/pangeo-cmip6.json") cat = col.search(experiment_id=['historical', 'ssp585'], table_id='day', variable_id='tasmax', grid_label='gn') # cat['CMIP.NASA-GISS.GISS-E2-1-G.historical.day.gn'] # access the data and do some cleanup ds_model = cat['CMIP.NASA-GISS.GISS-E2-1-G.historical.day.gn'].to_dask( ).isel(member_id=0).squeeze(drop=True).drop(['height', 'lat_bnds', 'lon_bnds', 'time_bnds', 'member_id']) ds_model.lon.values[ds_model.lon.values > 180] -= 360 ds_model = ds_model.roll(lon=72, roll_coords=True) ``` regrid obs to model resolution ``` # first rechunk in space for xESMF chunks = {'lat': len(obs_subset.lat), 'lon': len(obs_subset.lon), 'time': 100} obs_subset = obs_subset.chunk(chunks) %%time obs_to_mod_weights = os.path.join(write_direc, 'bias_correction_bilinear_weights_new.nc') regridder_obs_to_mod = xe.Regridder(obs_subset.isel(time=0, drop=True), ds_model.isel(time=0, drop=True), 'bilinear', filename=obs_to_mod_weights, reuse_weights=True) obs_subset_modres_lazy = xr.map_blocks(apply_weights, regridder_obs_to_mod, args=[tmax_obs['tmax']]) obs_subset_modres = obs_subset_modres_lazy.compute() ``` ### subset datasets to get ready for bias correcting ``` chunks = {'lat': 10, 'lon': 10, 'time': -1} train_subset = ds_model['tasmax'].sel(time=train_slice) train_subset['time'] = train_subset.indexes['time'].to_datetimeindex() train_subset = train_subset.resample(time='1d').mean().load(scheduler='threads').chunk(chunks) holdout_subset = ds_model['tasmax'].sel(time=holdout_slice) holdout_subset['time'] = holdout_subset.indexes['time'].to_datetimeindex() holdout_subset = holdout_subset.resample(time='1d').mean().load(scheduler='threads').chunk(chunks) ``` ### fit BcsdTemperature models at each x/y point in domain using the `PointwiseDownscaler` with the `daily_nasa-nex` option ``` %%time # model = PointWiseDownscaler(BcsdTemperature(return_anoms=False, time_grouper='daily_nasa-nex')) model = PointWiseDownscaler(BcsdTemperature(return_anoms=False)) model = BcsdTemperature(return_anoms=False) # remove leap days from model data train_subset_noleap = _remove_leap_days(train_subset) holdout_subset_noleap = _remove_leap_days(holdout_subset) # chunk datasets train_subset_noleap = train_subset_noleap.chunk(chunks) holdout_subset_noleap = holdout_subset_noleap.chunk(chunks) obs_subset_modres = obs_subset_modres.chunk(chunks) %%time model.fit(train_subset_noleap, obs_subset_modres) model display(model, model._models) %%time predicted = model.predict(holdout_subset_noleap).load() predicted.isel(time=0).plot(vmin=250, vmax=325) predicted.sel(lat=47, lon=-122, method='nearest').plot() ``` ### save data ``` ds_predicted = predicted.to_dataset(name='tmax') ds_new_attrs = {"file description": "daily bias correction test for 1980s, output from global bias correction scaling test", "author": "Diana Gergel", "contact": "dgergel@rhg.com"} ds_predicted.attrs.update(ds_new_attrs) ds_predicted.to_netcdf(os.path.join(write_direc, 'global_bias_corrected_tenyears.nc')) ```
github_jupyter
# Jupyter Example 5 for HERMES: Neutrinos ``` from pyhermes import * from pyhermes.units import PeV, TeV, GeV, mbarn, kpc, pc, deg, rad import astropy.units as u import numpy as np import healpy import matplotlib.pyplot as plt ``` HEMRES has available two cross-section modules for $pp \rightarrow \nu$: * one built on top of cparamlib: Kamae et al. 2006 * one based on Kelner-Aharonian parametrization ``` kamae06 = interactions.Kamae06Neutrino() kelahar = interactions.KelnerAharonianNeutrino() E_neutrino_range = np.logspace(0,6,100)*GeV E_proton_list = [10*GeV, 100*GeV, 1*TeV, 100*TeV, 1*PeV] diff_sigma = lambda model, E_proton: [ E_neutrino*model.getDiffCrossSection(E_proton, E_neutrino)/mbarn for E_neutrino in E_neutrino_range ] diff_sigma_kamae06 = lambda E_proton: diff_sigma(kamae06, E_proton) diff_sigma_kelahar = lambda E_proton: diff_sigma(kelahar, E_proton) colors = ['tab:brown', 'tab:red', 'tab:green', 'tab:blue', 'tab:orange'] for E_proton, c in zip(E_proton_list, colors): plt.loglog(E_neutrino_range/GeV, diff_sigma_kamae06(E_proton), ls='-', color=c, label="{}".format(E_proton.toAstroPy().to('TeV').round(2))) plt.loglog(E_neutrino_range/GeV, diff_sigma_kelahar(E_proton), ls='--', color=c) plt.ylim(top=1e3, bottom=1e-2) plt.title("Kamae06 (solid) and K&A (dashed) for a list of $E_p$") plt.xlabel(r"$E_\nu$ / GeV") plt.ylabel(r"$E_\nu\, \mathrm{d}\sigma_{pp \rightarrow \nu} / \mathrm{d} E_\nu$ [mbarn]") _ = plt.legend(loc="upper right", frameon=False) def integrate_template(integrator, nside): integrator.setupCacheTable(60, 60, 12) sun_pos = Vector3QLength(8.0*kpc, 0*pc, 0*pc) integrator.setSunPosition(sun_pos) mask_edges = ([5*deg, 0*deg], [-5*deg, 180*deg]) mask = RectangularWindow(*mask_edges) skymap_range = GammaSkymapRange(nside, 0.05*TeV, 1e4*TeV, 20) skymap_range.setIntegrator(integrator) skymap_range.setMask(mask) skymap_range.compute() return skymap_range def integrate_neutrino(cosmicrays, gas, crosssection): nside = 256 integrator = PiZeroIntegrator(cosmicrays, gas, crosssection) return integrate_template(integrator, nside) neutral_gas_HI = neutralgas.RingModel(neutralgas.RingType.HI) proton = cosmicrays.Dragon2D(Proton) skymap_range_neutrino_HI_kamae06 = integrate_neutrino(proton, neutral_gas_HI, kamae06) skymap_range_neutrino_HI_kelahar = integrate_neutrino(proton, neutral_gas_HI, kelahar) #use_units = skymap_range_HI[0].getUnits() # default units for GammaSkymap (GeV^-1 m^-2 s^-1 sr^-1) use_units = "GeV^-1 cm^-2 s^-1 sr^-1" # override default skymap_units = u.Quantity(1, use_units) base_units = skymap_units.unit.si.scale def calc_mean_flux(skymap_range): energies = np.array([float(s.getEnergy()/GeV) for s in skymap_range]) fluxes = np.array([s.getMean() for s in skymap_range]) / base_units return energies, fluxes def plot_spectrum(skymap_range, label, style): energies, fluxes = calc_mean_flux(skymap_range) plt.plot(energies, fluxes*energies**2, style, label=label) def plot_total_spectrum(list_of_skymap_range, label, style): fluxes = QDifferentialIntensity(0) for skymap_range in list_of_skymap_range: energies, fluxes_i = calc_mean_flux(skymap_range) fluxes = fluxes + fluxes_i plt.plot(energies, fluxes*energies**2, style, label=label) fig, ax = plt.subplots() plot_spectrum(skymap_range_neutrino_HI_kamae06, r'$\nu $ @ p + HI (Kamae06)', '-') plot_spectrum(skymap_range_neutrino_HI_kelahar, r'$\nu $ @ p + HI (K&A)', '--') plt.title("Neutrinos from diffuse emission (Fornieri20, Remy18)\n $|b| < 5^\degree$, $0^\degree \leq l \leq 180^\degree$") plt.legend(loc="lower left") plt.xlabel(r"$E_\nu$ / GeV") plt.ylabel(r"$E_\nu\, \mathrm{d}\Phi_\gamma / \mathrm{d} E_\gamma$ / " + (skymap_units*u.GeV**2).unit.to_string(format='latex_inline')) ax.tick_params(which='minor', direction='in', axis='both', bottom=True, top=True, left=True, right=True, length=3) ax.tick_params(which='major', direction='in', axis='both', bottom=True, top=True, left=True, right=True, length=5) plt.xscale("log") plt.yscale("log") plt.ylim(10**(-9), 10**(-6)) plt.xlim(10**(2), 10**(6)) #plt.savefig("img/neutrinos-from-diffuse-emission-spectrum-180.pdf", dpi=150) ```
github_jupyter
# Facial Keypoint Detection This project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with. Let's take a look at some examples of images and corresponding facial keypoints. <img src='images/key_pts_example.png' width=50% height=50%/> Facial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face. <img src='images/landmarks_numbered.jpg' width=30% height=30%/> --- ## Load and Visualize Data The first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints. #### Training and Testing Data This facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data. * 3462 of these images are training images, for you to use as you create a model to predict keypoints. * 2308 are test images, which will be used to test the accuracy of your model. The information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y). --- First, before we do anything, we have to load in our image data. This data is stored in a zip file and in the below cell, we access it by it's URL and unzip the data in a `/data/` directory that is separate from the workspace home directory. ``` # -- DO NOT CHANGE THIS CELL -- # !mkdir /data !wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip !unzip -n /data/train-test-data.zip -d /data # import the required libraries import glob import os import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.image as mpimg import cv2 ``` Then, let's load in our training data and display some stats about that dat ato make sure it's been loaded in correctly! ``` key_pts_frame = pd.read_csv('/data/training_frames_keypoints.csv') n = 0 image_name = key_pts_frame.iloc[n, 0] key_pts = key_pts_frame.iloc[n, 1:].as_matrix() key_pts = key_pts.astype('float').reshape(-1, 2) print('Image name: ', image_name) print('Landmarks shape: ', key_pts.shape) print('First 4 key pts: {}'.format(key_pts[:4])) # print out some stats about the data print('Number of images: ', key_pts_frame.shape[0]) ``` ## Look at some images Below, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape. ``` def show_keypoints(image, key_pts): """Show image with keypoints""" plt.imshow(image) plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='x', c='orange') # Display a few different types of images by changing the index n # select an image by index in our data frame n = 84 image_name = key_pts_frame.iloc[n, 0] key_pts = key_pts_frame.iloc[n, 1:].as_matrix() key_pts = key_pts.astype('float').reshape(-1, 2) plt.figure(figsize=(5, 5)) show_keypoints(mpimg.imread(os.path.join('/data/training/', image_name)), key_pts) plt.show() ``` ## Dataset class and Transformations To prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html). #### Dataset class ``torch.utils.data.Dataset`` is an abstract class representing a dataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network. Your custom dataset should inherit ``Dataset`` and override the following methods: - ``__len__`` so that ``len(dataset)`` returns the size of the dataset. - ``__getitem__`` to support the indexing such that ``dataset[i]`` can be used to get the i-th sample of image/keypoint data. Let's create a dataset class for our face keypoints dataset. We will read the CSV file in ``__init__`` but leave the reading of images to ``__getitem__``. This is memory efficient because all the images are not stored in the memory at once but read as required. A sample of our dataset will be a dictionary ``{'image': image, 'keypoints': key_pts}``. Our dataset will take an optional argument ``transform`` so that any required processing can be applied on the sample. We will see the usefulness of ``transform`` in the next section. ``` from torch.utils.data import Dataset, DataLoader class FacialKeypointsDataset(Dataset): """Face Landmarks dataset.""" def __init__(self, csv_file, root_dir, transform=None): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.key_pts_frame = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.key_pts_frame) def __getitem__(self, idx): image_name = os.path.join(self.root_dir, self.key_pts_frame.iloc[idx, 0]) image = mpimg.imread(image_name) # if image has an alpha color channel, get rid of it if(image.shape[2] == 4): image = image[:,:,0:3] key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix() key_pts = key_pts.astype('float').reshape(-1, 2) sample = {'image': image, 'keypoints': key_pts} if self.transform: sample = self.transform(sample) return sample ``` Now that we've defined this class, let's instantiate the dataset and display some images. ``` # Construct the dataset face_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv', root_dir='/data/training/') # print some stats about the dataset print('Length of dataset: ', len(face_dataset)) # Display a few of the images from the dataset num_to_display = 5 for i in range(num_to_display): # define the size of images fig = plt.figure(figsize=(20,10)) # randomly select a sample rand_i = np.random.randint(0, len(face_dataset)) sample = face_dataset[rand_i] # print the shape of the image and keypoints print(i, sample['image'].shape, sample['keypoints'].shape) ax = plt.subplot(1, num_to_display, i + 1) ax.set_title('Sample #{}'.format(i)) # Using the same display function, defined earlier show_keypoints(sample['image'], sample['keypoints']) ``` ## Transforms Now, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors. Therefore, we will need to write some pre-processing code. Let's create four transforms: - ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1] - ``Rescale``: to rescale an image to a desired size. - ``RandomCrop``: to crop an image randomly. - ``ToTensor``: to convert numpy images to torch images. We will write them as callable classes instead of simple functions so that parameters of the transform need not be passed everytime it's called. For this, we just need to implement ``__call__`` method and (if we require parameters to be passed in), the ``__init__`` method. We can then use a transform like this: tx = Transform(params) transformed_sample = tx(sample) Observe below how these transforms are generally applied to both the image and its keypoints. ``` import torch from torchvision import transforms, utils # tranforms class Normalize(object): """Convert a color image to grayscale and normalize the color range to [0,1].""" def __call__(self, sample): image, key_pts = sample['image'], sample['keypoints'] image_copy = np.copy(image) key_pts_copy = np.copy(key_pts) # convert image to grayscale image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # scale color range from [0, 255] to [0, 1] image_copy= image_copy/255.0 # scale keypoints to be centered around 0 with a range of [-1, 1] # mean = 100, sqrt = 50, so, pts should be (pts - 100)/50 key_pts_copy = (key_pts_copy - 100)/50.0 return {'image': image_copy, 'keypoints': key_pts_copy} class Rescale(object): """Rescale the image in a sample to a given size. Args: output_size (tuple or int): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same. """ def __init__(self, output_size): assert isinstance(output_size, (int, tuple)) self.output_size = output_size def __call__(self, sample): image, key_pts = sample['image'], sample['keypoints'] h, w = image.shape[:2] if isinstance(self.output_size, int): if h > w: new_h, new_w = self.output_size * h / w, self.output_size else: new_h, new_w = self.output_size, self.output_size * w / h else: new_h, new_w = self.output_size new_h, new_w = int(new_h), int(new_w) img = cv2.resize(image, (new_w, new_h)) # scale the pts, too key_pts = key_pts * [new_w / w, new_h / h] return {'image': img, 'keypoints': key_pts} class RandomCrop(object): """Crop randomly the image in a sample. Args: output_size (tuple or int): Desired output size. If int, square crop is made. """ def __init__(self, output_size): assert isinstance(output_size, (int, tuple)) if isinstance(output_size, int): self.output_size = (output_size, output_size) else: assert len(output_size) == 2 self.output_size = output_size def __call__(self, sample): image, key_pts = sample['image'], sample['keypoints'] h, w = image.shape[:2] new_h, new_w = self.output_size top = np.random.randint(0, h - new_h) left = np.random.randint(0, w - new_w) image = image[top: top + new_h, left: left + new_w] key_pts = key_pts - [left, top] return {'image': image, 'keypoints': key_pts} class ToTensor(object): """Convert ndarrays in sample to Tensors.""" def __call__(self, sample): image, key_pts = sample['image'], sample['keypoints'] # if image has no grayscale color channel, add one if(len(image.shape) == 2): # add that third color dim image = image.reshape(image.shape[0], image.shape[1], 1) # swap color axis because # numpy image: H x W x C # torch image: C X H X W image = image.transpose((2, 0, 1)) return {'image': torch.from_numpy(image), 'keypoints': torch.from_numpy(key_pts)} ``` ## Test out the transforms Let's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size. ``` # test out some of these transforms rescale = Rescale(100) crop = RandomCrop(50) composed = transforms.Compose([Rescale(250), RandomCrop(224)]) # apply the transforms to a sample image test_num = 500 sample = face_dataset[test_num] fig = plt.figure() for i, tx in enumerate([rescale, crop, composed]): transformed_sample = tx(sample) ax = plt.subplot(1, 3, i + 1) plt.tight_layout() ax.set_title(type(tx).__name__) show_keypoints(transformed_sample['image'], transformed_sample['keypoints']) plt.show() ``` ## Create the transformed dataset Apply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size). ``` # define the data tranform # order matters! i.e. rescaling should come before a smaller crop data_transform = transforms.Compose([Rescale(250), RandomCrop(224), Normalize(), ToTensor()]) # create the transformed dataset transformed_dataset = FacialKeypointsDataset(csv_file='/data/training_frames_keypoints.csv', root_dir='/data/training/', transform=data_transform) transformed_dataset[3]['image'].shape # print some stats about the transformed data print('Number of images: ', len(transformed_dataset)) # make sure the sample tensors are the expected size for i in range(5): sample = transformed_dataset[i] print(i, sample['image'].size(), sample['keypoints'].size()) ``` ## Data Iteration and Batching Right now, we are iterating over this data using a ``for`` loop, but we are missing out on a lot of PyTorch's dataset capabilities, specifically the abilities to: - Batch the data - Shuffle the data - Load the data in parallel using ``multiprocessing`` workers. ``torch.utils.data.DataLoader`` is an iterator which provides all these features, and we'll see this in use in the *next* notebook, Notebook 2, when we load data in batches to train a neural network! --- ## Ready to Train! Now that you've seen how to load and transform our data, you're ready to build a neural network to train on this data. In the next notebook, you'll be tasked with creating a CNN for facial keypoint detection.
github_jupyter
# 04 Spark essentials ``` # Make it Python2 & Python3 compatible from __future__ import print_function import sys if sys.version[0] == 3: xrange = range ``` ## Spark context The notebook deployment includes Spark automatically within each Python notebook kernel. This means that, upon kernel instantiation, there is an [SparkContext](http://spark.apache.org/docs/latest/api/python/pyspark.html#pyspark.SparkContext) object called `sc` immediatelly available in the Notebook, as in a PySpark shell. Let's take a look at it: ``` ?sc ``` We can inspect some of the SparkContext properties: ``` # Spark version we are using print( sc.version ) # Name of the application we are running print(sc.appName) sc.appName # Some configuration variables print( sc.defaultParallelism ) print( sc.defaultMinPartitions ) # Username running all Spark processes # --> Note this is a method, not a property print( sc.sparkUser() ) ``` # Spark configuration ``` # Print out the SparkContext configuration print( sc._conf.toDebugString() ) # Another way to get similar information from pyspark import SparkConf, SparkContext SparkConf().getAll() ``` ## Spark execution modes We can also take a look at the Spark configuration this kernel is running under, by using the above configuration data: ``` print( sc._conf.toDebugString() ) ``` ... this includes the execution mode for Spark. The default mode is *local*, i.e. all Spark processes run locally in the launched Virtual Machine. This is fine for developing and testing with small datasets. But to run Spark applications on bigger datasets, they must be executed in a remote cluster. This deployment comes with configuration modes for that, which require: * network adjustments to make the VM "visible" from the cluster: the virtual machine must be started in _bridged_ mode (the default *Vagrantfile* already contains code for doingso, but it must be uncommented) * configuring the addresses for the cluster. This is done within the VM by using the `spark-notebook` script, such as sudo service spark-notebook set-addr <master-ip> <namenode-ip> <historyserver-ip> * activating the desired mode, by executing sudo service spark-notebook set-mode (local | standalone | yarn) These operations can also be performed outside the VM by telling vagrant to relay them, e.g. vagrant ssh -c "sudo service spark-notebook set-mode local" ## A trivial test Let's do a trivial operation that creates an RDD and executes an action on it. So that we can test that the kernel is capable of launching executors ``` from operator import add l = sc.range(10000) print( l.reduce(add) ) ```
github_jupyter
``` import pickle import numpy as np import mplhep import awkward import matplotlib.pyplot as plt import matplotlib.patches as mpatches import uproot import boost_histogram as bh physics_process = "qcd" data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/out.pkl", "rb"))) data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/out.pkl", "rb"))) fi1 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") fi2 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11843.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") physics_process = "ttbar" data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/out.pkl", "rb"))) data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/out.pkl", "rb"))) fi1 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.0/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") fi2 = uproot.open("/home/joosep/reco/mlpf/CMSSW_12_1_0_pre3/11834.13/DQM_V0001_R000000001__Global__CMSSW_X_Y_Z__RECO.root") # physics_process = "singlepi" # data_mlpf = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_11_3_0_pre2/11688.0_mlpf/out.pkl", "rb"))) # data_baseline = awkward.Array(pickle.load(open("/home/joosep/reco/mlpf/CMSSW_11_3_0_pre2/11688.0_baseline/out.pkl", "rb"))) def cms_label(x0=0.12, x1=0.23, x2=0.67, y=0.90): plt.figtext(x0, y,'CMS',fontweight='bold', wrap=True, horizontalalignment='left', fontsize=12) plt.figtext(x1, y,'Simulation Preliminary', style='italic', wrap=True, horizontalalignment='left', fontsize=10) plt.figtext(x2, y,'Run 3 (14 TeV)', wrap=True, horizontalalignment='left', fontsize=10) physics_process_str = { "ttbar": "$\mathrm{t}\overline{\mathrm{t}}$ events", "singlepi": "single $\pi^{\pm}$ events", "qcd": "QCD", } def sample_label(ax, x=0.03, y=0.98, additional_text="", physics_process=physics_process): plt.text(x, y, physics_process_str[physics_process]+additional_text, va="top", ha="left", size=10, transform=ax.transAxes) plt.figure(figsize=(5, 5)) ax = plt.axes() bins = np.linspace(0, 500, 61) plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["pt"]), bins=bins, histtype="step", lw=2, label="PF"); plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["pt"]), bins=bins, histtype="step", lw=2, label="MLPF"); plt.yscale("log") plt.ylim(top=1e5) cms_label() sample_label(ax, x=0.02) plt.xlabel("ak4PFJetsCHS $p_T$ [GeV]") plt.ylabel("Number of jets") plt.legend(loc="best") plt.savefig("ak4jet_pt_{}.pdf".format(physics_process), bbox_inches="tight") plt.figure(figsize=(5, 5)) bins = np.linspace(0, 2500, 61) plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["energy"]), bins=bins, histtype="step", lw=2, label="PF"); plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["energy"]), bins=bins, histtype="step", lw=2, label="MLPF"); plt.yscale("log") plt.ylim(top=1e5) cms_label() sample_label(ax, x=0.02) plt.xlabel("ak4PFJetsCHS $E$ [GeV]") plt.ylabel("Number of jets") plt.legend(loc="best") plt.savefig("ak4jet_energy_{}.pdf".format(physics_process), bbox_inches="tight") plt.figure(figsize=(5, 5)) bins = np.linspace(-6, 6, 101) plt.hist(awkward.flatten(data_baseline["ak4PFJetsCHS"]["eta"]), bins=bins, histtype="step", lw=2, label="PF"); plt.hist(awkward.flatten(data_mlpf["ak4PFJetsCHS"]["eta"]), bins=bins, histtype="step", lw=2, label="MLPF"); #plt.yscale("log") cms_label() sample_label(ax) plt.ylim(top=2000) plt.xlabel("ak4PFJetsCHS $\eta$") plt.ylabel("Number of jets") plt.legend(loc="best") plt.savefig("ak4jet_eta_{}.pdf".format(physics_process), bbox_inches="tight") color_map = { 1: "red", 2: "blue", 11: "orange", 22: "cyan", 13: "purple", 130: "green", 211: "black" } particle_labels = { 1: "HFEM", 2: "HFHAD", 11: "$e^\pm$", 22: "$\gamma$", 13: "$\mu$", 130: "neutral hadron", 211: "charged hadron" } def draw_event(iev): pt_0 = data_mlpf["particleFlow"]["pt"][iev] energy_0 = data_mlpf["particleFlow"]["energy"][iev] eta_0 = data_mlpf["particleFlow"]["eta"][iev] phi_0 = data_mlpf["particleFlow"]["phi"][iev] pdgid_0 = np.abs(data_mlpf["particleFlow"]["pdgId"][iev]) pt_1 = data_baseline["particleFlow"]["pt"][iev] energy_1 = data_baseline["particleFlow"]["energy"][iev] eta_1 = data_baseline["particleFlow"]["eta"][iev] phi_1 = data_baseline["particleFlow"]["phi"][iev] pdgid_1 = np.abs(data_baseline["particleFlow"]["pdgId"][iev]) plt.figure(figsize=(5, 5)) ax = plt.axes() plt.scatter(eta_0, phi_0, marker=".", s=energy_0, c=[color_map[p] for p in pdgid_0], alpha=0.6) pids = [211,130,1,2,22,11,13] for p in pids: plt.plot([], [], color=color_map[p], lw=0, marker="o", label=particle_labels[p]) plt.legend(loc=8, frameon=False, ncol=3, fontsize=8) cms_label() sample_label(ax) plt.xlim(-6,6) plt.ylim(-5,4) plt.xlabel("PFCandidate $\eta$") plt.ylabel("PFCandidate $\phi$") plt.title("MLPF (trained on PF), CMSSW-ONNX inference", y=1.05) plt.savefig("event_mlpf_{}_iev{}.pdf".format(physics_process, iev), bbox_inches="tight") plt.savefig("event_mlpf_{}_iev{}.png".format(physics_process, iev), bbox_inches="tight", dpi=300) plt.figure(figsize=(5, 5)) ax = plt.axes() plt.scatter(eta_1, phi_1, marker=".", s=energy_1, c=[color_map[p] for p in pdgid_1], alpha=0.6) # plt.scatter( # data_baseline["ak4PFJetsCHS"]["eta"][iev], # data_baseline["ak4PFJetsCHS"]["phi"][iev], # s=data_baseline["ak4PFJetsCHS"]["energy"][iev], color="gray", alpha=0.3 # ) cms_label() sample_label(ax) plt.xlim(-6,6) plt.ylim(-5,4) plt.xlabel("PFCandidate $\eta$") plt.ylabel("PFCandidate $\phi$") plt.title("Standard PF, CMSSW", y=1.05) pids = [211,130,1,2,22,11,13] for p in pids: plt.plot([], [], color=color_map[p], lw=0, marker="o", label=particle_labels[p]) plt.legend(loc=8, frameon=False, ncol=3, fontsize=8) plt.savefig("event_pf_{}_iev{}.pdf".format(physics_process, iev), bbox_inches="tight") plt.savefig("event_pf_{}_iev{}.png".format(physics_process, iev), bbox_inches="tight", dpi=300) draw_event(0) draw_event(1) draw_event(2) def plot_dqm(key, title, rebin=None): h1 = fi1.get(key).to_boost() h2 = fi2.get(key).to_boost() fig, (ax1, ax2) = plt.subplots(2, 1) plt.sca(ax1) if rebin: h1 = h1[bh.rebin(rebin)] h2 = h2[bh.rebin(rebin)] mplhep.histplot(h1, yerr=0, label="PF"); mplhep.histplot(h2, yerr=0, label="MLPF"); plt.legend(frameon=False) plt.ylabel("Number of particles / bin") sample_label(ax=ax1, additional_text=", "+title, physics_process=physics_process) plt.sca(ax2) ratio_hist = h2/h1 vals_y = ratio_hist.values() vals_y[np.isnan(vals_y)] = 0 plt.plot(ratio_hist.axes[0].centers, vals_y, color="gray", lw=0, marker=".") plt.ylim(0,2) plt.axhline(1.0, color="black", ls="--") plt.ylabel("MLPF / PF") return ax1, ax2 #plt.xscale("log") #plt.yscale("log") log10_pt = "$\log_{10}[p_T/\mathrm{GeV}]$" eta = "$\eta$" dqm_plots_ptcl = [ ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/chargedHadron/chargedHadronLog10Pt", "ch.had.", log10_pt, "ch_had_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/chargedHadron/chargedHadronEta", "ch.had.", eta, "ch_had_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronLog10Pt", "n.had.", log10_pt, "n_had_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronPtLow", "n.had.", "$p_T$ [GeV]", "n_had_ptlow"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronPtMid", "n.had.", "$p_T$ [GeV]", "n_had_ptmid"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/neutralHadron/neutralHadronEta", "n.had.", eta, "n_had_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_hadron/HF_hadronLog10Pt", "HFHAD", log10_pt, "hfhad_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_hadron/HF_hadronEta", "HFHAD", eta, "hfhad_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_EM_particle/HF_EM_particleLog10Pt", "HFEM", log10_pt, "hfem_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/HF_EM_particle/HF_EM_particleEta", "HFEM", eta, "hfem_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/photon/photonLog10Pt", "photon", log10_pt, "photon_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/photon/photonEta", "photon", eta, "photon_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/electron/electronLog10Pt", "electron", log10_pt, "electron_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/electron/electronEta", "electron", eta, "electron_eta"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/muon/muonLog10Pt", "muon", log10_pt, "muon_logpt"), ("DQMData/Run 1/ParticleFlow/Run summary/PackedCandidates/muon/muonEta", "muon", eta, "muon_eta"), ] dqm_plots_jetres = [ ("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/mean_delta_et_Over_et_VS_et_", "jets", "gen-jet $E_t$", "$\Delta E_t / E_t$"), ] for key, title, xlabel, plot_label in dqm_plots_ptcl: rh = plot_dqm(key, title) plt.xlabel(xlabel) cms_label() plt.savefig("dqm_{}_{}.pdf".format(plot_label, physics_process), bbox_inches="tight") plt.savefig("dqm_{}_{}.png".format(plot_label, physics_process), bbox_inches="tight", dpi=300) ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/Cleanedak4PFJetsCHS/Pt", "ak4PFCHS jets") ax2.set_xlabel("jet $p_t$ [GeV]") ax1.set_ylabel("number of jets / bin") #plt.xscale("log") #plt.ylim(bottom=1, top=1e4) ax1.set_yscale("log") ax1.set_ylim(bottom=1, top=1e5) #ax2.set_ylim(0,5) cms_label() plt.savefig("dqm_jet_pt_{}.pdf".format(physics_process), bbox_inches="tight") plt.savefig("dqm_jet_pt_{}.png".format(physics_process), bbox_inches="tight", dpi=300) ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/CleanedslimmedJetsPuppi/Pt", "ak4PFPuppi jets") ax2.set_xlabel("jet $p_t$ [GeV]") ax1.set_ylabel("number of jets / bin") #plt.xscale("log") #plt.ylim(bottom=1, top=1e4) ax1.set_yscale("log") ax1.set_ylim(bottom=1, top=1e5) #ax2.set_ylim(0,5) cms_label() plt.savefig("dqm_jet_pt_puppi_{}.pdf".format(physics_process), bbox_inches="tight") plt.savefig("dqm_jet_pt_puppi_{}.png".format(physics_process), bbox_inches="tight", dpi=300) ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/Cleanedak4PFJetsCHS/Eta", "ak4PFCHS jets") ax2.set_xlabel("jet $\eta$") ax1.set_ylabel("number of jets / bin") #plt.xscale("log") #plt.ylim(bottom=1, top=1e4) #ax1.set_yscale("log") ax1.set_ylim(bottom=0, top=1e3) #ax2.set_ylim(0,5) cms_label() plt.savefig("dqm_jet_eta_{}.pdf".format(physics_process), bbox_inches="tight") plt.savefig("dqm_jet_eta_{}.png".format(physics_process), bbox_inches="tight", dpi=300) ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/Jet/CleanedslimmedJetsPuppi/Eta", "ak4PFPuppi jets") ax2.set_xlabel("jet $\eta$") ax1.set_ylabel("number of jets / bin") #plt.xscale("log") #plt.ylim(bottom=1, top=1e4) #ax1.set_yscale("log") #ax1.set_ylim(bottom=0, top=20) #ax2.set_ylim(0,5) cms_label() plt.savefig("dqm_jet_eta_puppi_{}.pdf".format(physics_process), bbox_inches="tight") plt.savefig("dqm_jet_eta_puppi_{}.png".format(physics_process), bbox_inches="tight", dpi=300) # plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/mean_delta_et_Over_et_VS_et_", "AK4 PF jets") # plt.xlabel("gen-jet $E_t$ [GeV]") # plt.ylabel("profiled $\mu(\Delta E_t / E_t$)") # plt.xscale("log") # plt.ylim(0,3) # cms_label() # plt.savefig("dqm_jet_mean_delta_et_Over_et_VS_et.pdf", bbox_inches="tight") # plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFJetValidation/CompWithGenJet/sigma_delta_et_Over_et_VS_et_", "AK4 PF jets") # plt.xlabel("gen-jet $E_t$ [GeV]") # plt.ylabel("profiled $\sigma(\Delta E_t / E_t)$") # plt.xscale("log") # plt.ylim(0,10) # cms_label() # plt.savefig("dqm_jet_sigma_delta_et_Over_et_VS_et.pdf", bbox_inches="tight") ax1, ax2 = plot_dqm("DQMData/Run 1/JetMET/Run summary/METValidation/pfMet/MET", "PFMET", rebin=1) ax2.set_xlabel("$\sum E_t$ [GeV]") ax1.set_ylabel("number of events / bin") #ax1.set_xscale("log") ax1.set_ylim(bottom=1, top=1000) ax1.set_yscale("log") plt.savefig("dqm_met_sumet_{}.pdf".format(physics_process), bbox_inches="tight") plt.savefig("dqm_met_sumet_{}.png".format(physics_process), bbox_inches="tight", dpi=300) # plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFMETValidation/CompWithGenMET/profileRMS_delta_et_Over_et_VS_et_", "PFMET") # plt.xlabel("gen-MET $E_t$ [GeV]") # plt.ylabel("profiled RMS $\Delta E_t / E_t$") # plt.xscale("log") # plt.ylim(0,3) # cms_label() # plt.savefig("dqm_met_profileRMS_delta_et_Over_et_VS_et.pdf", bbox_inches="tight") # plot_dqm("DQMData/Run 1/ParticleFlow/Run summary/PFMETValidation/CompWithGenMET/profile_delta_et_VS_et_", "PFMET") # plt.xlabel("gen-MET $E_t$ [GeV]") # plt.ylabel("profiled $\Delta E_t$ [GeV]") # plt.xscale("log") # plt.ylim(0, 80) # cms_label() # plt.savefig("dqm_met_delta_et_VS_et.pdf", bbox_inches="tight") timing_output = """ Nelem=1600 mean_time=5.92 ms stddev_time=5.03 ms mem_used=1018 MB Nelem=1920 mean_time=6.57 ms stddev_time=1.01 ms mem_used=1110 MB Nelem=2240 mean_time=6.92 ms stddev_time=0.81 ms mem_used=1127 MB Nelem=2560 mean_time=7.37 ms stddev_time=0.66 ms mem_used=1136 MB Nelem=2880 mean_time=8.17 ms stddev_time=0.56 ms mem_used=1123 MB Nelem=3200 mean_time=8.88 ms stddev_time=1.09 ms mem_used=1121 MB Nelem=3520 mean_time=9.51 ms stddev_time=0.65 ms mem_used=1121 MB Nelem=3840 mean_time=10.48 ms stddev_time=0.93 ms mem_used=1255 MB Nelem=4160 mean_time=11.05 ms stddev_time=0.87 ms mem_used=1255 MB Nelem=4480 mean_time=12.07 ms stddev_time=0.81 ms mem_used=1230 MB Nelem=4800 mean_time=12.92 ms stddev_time=0.89 ms mem_used=1230 MB Nelem=5120 mean_time=13.44 ms stddev_time=0.75 ms mem_used=1230 MB Nelem=5440 mean_time=14.07 ms stddev_time=0.78 ms mem_used=1230 MB Nelem=5760 mean_time=15.00 ms stddev_time=0.84 ms mem_used=1230 MB Nelem=6080 mean_time=15.74 ms stddev_time=1.05 ms mem_used=1230 MB Nelem=6400 mean_time=16.32 ms stddev_time=1.30 ms mem_used=1230 MB Nelem=6720 mean_time=17.24 ms stddev_time=0.99 ms mem_used=1230 MB Nelem=7040 mean_time=17.74 ms stddev_time=0.85 ms mem_used=1230 MB Nelem=7360 mean_time=18.59 ms stddev_time=1.04 ms mem_used=1230 MB Nelem=7680 mean_time=19.33 ms stddev_time=0.93 ms mem_used=1499 MB Nelem=8000 mean_time=20.00 ms stddev_time=1.06 ms mem_used=1499 MB Nelem=8320 mean_time=20.55 ms stddev_time=1.13 ms mem_used=1499 MB Nelem=8640 mean_time=21.10 ms stddev_time=0.90 ms mem_used=1499 MB Nelem=8960 mean_time=22.88 ms stddev_time=1.24 ms mem_used=1499 MB Nelem=9280 mean_time=23.44 ms stddev_time=1.14 ms mem_used=1499 MB Nelem=9600 mean_time=23.93 ms stddev_time=1.04 ms mem_used=1499 MB Nelem=9920 mean_time=24.75 ms stddev_time=0.91 ms mem_used=1499 MB Nelem=10240 mean_time=25.47 ms stddev_time=1.33 ms mem_used=1499 MB Nelem=10560 mean_time=26.29 ms stddev_time=1.33 ms mem_used=1499 MB Nelem=10880 mean_time=26.72 ms stddev_time=1.18 ms mem_used=1490 MB Nelem=11200 mean_time=29.50 ms stddev_time=2.60 ms mem_used=1502 MB Nelem=11520 mean_time=28.50 ms stddev_time=0.91 ms mem_used=1491 MB Nelem=11840 mean_time=29.11 ms stddev_time=1.14 ms mem_used=1491 MB Nelem=12160 mean_time=30.01 ms stddev_time=1.15 ms mem_used=1499 MB Nelem=12480 mean_time=30.55 ms stddev_time=0.94 ms mem_used=1499 MB Nelem=12800 mean_time=31.31 ms stddev_time=1.08 ms mem_used=1499 MB Nelem=13120 mean_time=32.61 ms stddev_time=1.19 ms mem_used=1499 MB Nelem=13440 mean_time=33.37 ms stddev_time=1.01 ms mem_used=1499 MB Nelem=13760 mean_time=34.13 ms stddev_time=1.18 ms mem_used=1499 MB Nelem=14080 mean_time=34.73 ms stddev_time=1.40 ms mem_used=1499 MB Nelem=14400 mean_time=35.79 ms stddev_time=1.70 ms mem_used=2036 MB Nelem=14720 mean_time=36.68 ms stddev_time=1.37 ms mem_used=2036 MB Nelem=15040 mean_time=37.17 ms stddev_time=0.97 ms mem_used=2036 MB Nelem=15360 mean_time=38.73 ms stddev_time=1.19 ms mem_used=2036 MB Nelem=15680 mean_time=39.80 ms stddev_time=1.04 ms mem_used=2036 MB Nelem=16000 mean_time=40.87 ms stddev_time=1.46 ms mem_used=1996 MB Nelem=16320 mean_time=41.89 ms stddev_time=1.01 ms mem_used=1996 MB Nelem=16640 mean_time=43.36 ms stddev_time=1.08 ms mem_used=1996 MB Nelem=16960 mean_time=44.87 ms stddev_time=1.35 ms mem_used=1996 MB Nelem=17280 mean_time=46.04 ms stddev_time=0.96 ms mem_used=1996 MB Nelem=17600 mean_time=47.96 ms stddev_time=1.47 ms mem_used=1996 MB Nelem=17920 mean_time=49.01 ms stddev_time=1.35 ms mem_used=1996 MB Nelem=18240 mean_time=50.04 ms stddev_time=1.34 ms mem_used=1956 MB Nelem=18560 mean_time=51.34 ms stddev_time=1.49 ms mem_used=1956 MB Nelem=18880 mean_time=52.16 ms stddev_time=1.20 ms mem_used=1956 MB Nelem=19200 mean_time=53.19 ms stddev_time=1.20 ms mem_used=1956 MB Nelem=19520 mean_time=54.03 ms stddev_time=0.96 ms mem_used=1956 MB Nelem=19840 mean_time=55.68 ms stddev_time=1.05 ms mem_used=1956 MB Nelem=20160 mean_time=56.88 ms stddev_time=1.12 ms mem_used=1956 MB Nelem=20480 mean_time=57.49 ms stddev_time=1.50 ms mem_used=1956 MB Nelem=20800 mean_time=60.40 ms stddev_time=3.51 ms mem_used=1959 MB Nelem=21120 mean_time=61.30 ms stddev_time=3.90 ms mem_used=1959 MB Nelem=21440 mean_time=60.74 ms stddev_time=1.05 ms mem_used=1948 MB Nelem=21760 mean_time=61.66 ms stddev_time=1.29 ms mem_used=1948 MB Nelem=22080 mean_time=63.35 ms stddev_time=1.11 ms mem_used=1948 MB Nelem=22400 mean_time=64.70 ms stddev_time=1.16 ms mem_used=1948 MB Nelem=22720 mean_time=65.63 ms stddev_time=0.95 ms mem_used=1948 MB Nelem=23040 mean_time=67.09 ms stddev_time=1.02 ms mem_used=1948 MB Nelem=23360 mean_time=68.40 ms stddev_time=1.15 ms mem_used=1948 MB Nelem=23680 mean_time=69.76 ms stddev_time=0.88 ms mem_used=1948 MB Nelem=24000 mean_time=71.55 ms stddev_time=0.94 ms mem_used=1948 MB Nelem=24320 mean_time=73.04 ms stddev_time=1.46 ms mem_used=1948 MB Nelem=24640 mean_time=74.53 ms stddev_time=1.28 ms mem_used=1948 MB Nelem=24960 mean_time=76.03 ms stddev_time=1.07 ms mem_used=1948 MB Nelem=25280 mean_time=77.59 ms stddev_time=0.88 ms mem_used=1948 MB """ time_x = [] time_y = [] time_y_err = [] gpu_mem_use = [] for line in timing_output.split("\n"): if len(line)>0: spl = line.split() time_x.append(int(spl[0].split("=")[1])) time_y.append(float(spl[1].split("=")[1])) time_y_err.append(float(spl[3].split("=")[1])) gpu_mem_use.append(float(spl[5].split("=")[1])) import glob nelem = [] for fi in glob.glob("../data/TTbar_14TeV_TuneCUETP8M1_cfi/raw/*.pkl"): d = pickle.load(open(fi, "rb")) for elem in d: X = elem["Xelem"][(elem["Xelem"]["typ"]!=2)&(elem["Xelem"]["typ"]!=3)] nelem.append(X.shape[0]) plt.figure(figsize=(5,5)) ax = plt.axes() plt.hist(nelem, bins=np.linspace(2000,6000,100)); plt.ylabel("Number of events / bin") plt.xlabel("PFElements per event") cms_label() sample_label(ax, physics_process="ttbar") plt.figure(figsize=(10, 3)) plt.errorbar(time_x, time_y, yerr=time_y_err, marker=".", label="MLPF") plt.axvline(np.mean(nelem)-np.std(nelem), color="black", ls="--", lw=1.0, label=r"$t\bar{t}$+PU Run 3") plt.axvline(np.mean(nelem)+np.std(nelem), color="black", ls="--", lw=1.0) #plt.xticks(time_x, time_x); plt.xlim(0,30000) plt.ylim(0,100) plt.ylabel("Average runtime per event [ms]") plt.xlabel("PFElements per event") plt.legend(frameon=False) cms_label(x1=0.17, x2=0.8) plt.savefig("runtime_scaling.pdf", bbox_inches="tight") plt.savefig("runtime_scaling.png", bbox_inches="tight", dpi=300) plt.figure(figsize=(10, 3)) plt.plot(time_x, gpu_mem_use, marker=".", label="MLPF") plt.axvline(np.mean(nelem)-np.std(nelem), color="black", ls="--", lw=1.0, label=r"$t\bar{t}$+PU Run 3") plt.axvline(np.mean(nelem)+np.std(nelem), color="black", ls="--", lw=1.0) #plt.xticks(time_x, time_x); plt.xlim(0,30000) plt.ylim(0,3000) plt.ylabel("Maximum GPU memory used [MB]") plt.xlabel("PFElements per event") plt.legend(frameon=False, loc=4) cms_label(x1=0.17, x2=0.8) plt.savefig("memory_scaling.pdf", bbox_inches="tight") plt.savefig("memory_scaling.png", bbox_inches="tight", dpi=300) ```
github_jupyter
``` import pandas as pd import pyspark.sql.functions as F from datetime import datetime from pyspark.sql.types import * from pyspark import StorageLevel import numpy as np pd.set_option("display.max_rows", 1000) pd.set_option("display.max_columns", 1000) pd.set_option("mode.chained_assignment", None) from pyspark.ml import Pipeline from pyspark.ml.classification import GBTClassifier from pyspark.ml.feature import IndexToString, StringIndexer, VectorIndexer # from pyspark.ml.evaluation import MulticlassClassificationEvaluator from pyspark.ml.feature import OneHotEncoderEstimator, StringIndexer, VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml.tuning import CrossValidator, ParamGridBuilder from pyspark.sql import Row from pyspark.ml.linalg import Vectors # !pip install scikit-plot import sklearn import scikitplot as skplt from sklearn.metrics import classification_report, confusion_matrix, precision_score ``` <hr /> <hr /> <hr /> ``` result_schema = StructType([ StructField('experiment_filter', StringType(), True), StructField('undersampling_method', StringType(), True), StructField('undersampling_column', StringType(), True), StructField('filename', StringType(), True), StructField('experiment_id', StringType(), True), StructField('n_covid', IntegerType(), True), StructField('n_not_covid', IntegerType(), True), StructField('model_name', StringType(), True), StructField('model_seed', StringType(), True), StructField('model_maxIter', IntegerType(), True), StructField('model_maxDepth', IntegerType(), True), StructField('model_maxBins', IntegerType(), True), StructField('model_minInstancesPerNode', IntegerType(), True), StructField('model_minInfoGain', FloatType(), True), StructField('model_featureSubsetStrategy', StringType(), True), StructField('model_n_estimators', IntegerType(), True), StructField('model_learning_rate', FloatType(), True), StructField('model_impurity', StringType(), True), StructField('model_AUC_ROC', StringType(), True), StructField('model_AUC_PR', StringType(), True), StructField('model_covid_precision', StringType(), True), StructField('model_covid_recall', StringType(), True), StructField('model_covid_f1', StringType(), True), StructField('model_not_covid_precision', StringType(), True), StructField('model_not_covid_recall', StringType(), True), StructField('model_not_covid_f1', StringType(), True), StructField('model_avg_precision', StringType(), True), StructField('model_avg_recall', StringType(), True), StructField('model_avg_f1', StringType(), True), StructField('model_avg_acc', StringType(), True), StructField('model_TP', StringType(), True), StructField('model_TN', StringType(), True), StructField('model_FN', StringType(), True), StructField('model_FP', StringType(), True), StructField('model_time_exec', StringType(), True), StructField('model_col_set', StringType(), True) ]) ``` <hr /> <hr /> <hr /> ``` # undersamp_col = ['03-STRSAMP-AG', '04-STRSAMP-EW'] # dfs = ['ds-1', 'ds-2', 'ds-3'] # cols_sets = ['cols_set_1', 'cols_set_2', 'cols_set_3'] undersamp_col = ['03-STRSAMP-AG'] dfs = ['ds-3'] cols_sets = ['cols_set_3'] # lists of params model_maxIter = [20, 50, 100] model_maxDepth = [3, 5, 7] model_maxBins = [32, 64] # model_learningRate = [0.01, 0.1, 0.5] # model_loss = ['logLoss', 'leastSquaresError', 'leastAbsoluteError'] list_of_param_dicts = [] for maxIter in model_maxIter: for maxDepth in model_maxDepth: for maxBins in model_maxBins: params_dict = {} params_dict['maxIter'] = maxIter params_dict['maxDepth'] = maxDepth params_dict['maxBins'] = maxBins list_of_param_dicts.append(params_dict) print("There is {} set of params.".format(len(list_of_param_dicts))) # list_of_param_dicts prefix = 'gs://ai-covid19-datalake/trusted/experiment_map/' ``` <hr /> <hr /> <hr /> ``` # filename = 'gs://ai-covid19-datalake/trusted/experiment_map/03-STRSAMP-AG/ds-1/cols_set_1/experiment0.parquet' # df = spark.read.parquet(filename) # df.limit(2).toPandas() # params_dict = {'maxIter': 100, # 'maxDepth': 3, # 'maxBins': 32, # 'learningRate': 0.5, # 'loss': 'leastAbsoluteError'} # cols = 'cols_set_1' # experiment_filter = 'ds-1' # undersampling_method = '03-STRSAMP-AG', # experiment_id = 0 # run_gbt(df, params_dict, cols, filename, experiment_filter, undersampling_method, experiment_id) ``` <hr /> <hr /> <hr /> ``` def run_gbt(exp_df, params_dict, cols, filename, experiment_filter, undersampling_method, experiment_id): import time start_time = time.time() n_covid = exp_df.filter(F.col('CLASSI_FIN') == 1.0).count() n_not_covid = exp_df.filter(F.col('CLASSI_FIN') == 0.0).count() id_cols = ['NU_NOTIFIC', 'CLASSI_FIN'] labelIndexer = StringIndexer(inputCol="CLASSI_FIN", outputCol="indexedLabel").fit(exp_df) input_cols = [x for x in exp_df.columns if x not in id_cols] assembler = VectorAssembler(inputCols = input_cols, outputCol= 'features') exp_df = assembler.transform(exp_df) # Automatically identify categorical features, and index them. # Set maxCategories so features with > 4 distinct values are treated as continuous. featureIndexer = VectorIndexer(inputCol="features", outputCol="indexedFeatures", maxCategories=30).fit(exp_df) # Split the data into training and test sets (30% held out for testing) (trainingData, testData) = exp_df.randomSplit([0.7, 0.3]) trainingData = trainingData.persist(StorageLevel.MEMORY_ONLY) testData = testData.persist(StorageLevel.MEMORY_ONLY) # Train a RandomForest model. gbt = GBTClassifier(labelCol = "indexedLabel", featuresCol = "indexedFeatures", maxIter = params_dict['maxIter'], maxDepth = params_dict['maxDepth'], maxBins = params_dict['maxBins']) # Convert indexed labels back to original labels. labelConverter = IndexToString(inputCol="prediction", outputCol="predictedLabel", labels=labelIndexer.labels) # Chain indexers and forest in a Pipeline pipeline = Pipeline(stages=[labelIndexer, featureIndexer, gbt, labelConverter]) # Train model. This also runs the indexers. model = pipeline.fit(trainingData) # Make predictions. predictions = model.transform(testData) pred = predictions.select(['CLASSI_FIN', 'predictedLabel'])\ .withColumn('predictedLabel', F.col('predictedLabel').cast('double'))\ .withColumn('predictedLabel', F.when(F.col('predictedLabel') == 1.0, 'covid').otherwise('n-covid'))\ .withColumn('CLASSI_FIN', F.when(F.col('CLASSI_FIN') == 1.0, 'covid').otherwise('n-covid'))\ .toPandas() y_true = pred['CLASSI_FIN'].tolist() y_pred = pred['predictedLabel'].tolist() report = classification_report(y_true, y_pred, output_dict=True) evaluator_ROC = BinaryClassificationEvaluator(labelCol="indexedLabel", rawPredictionCol="prediction", metricName="areaUnderROC") accuracy_ROC = evaluator_ROC.evaluate(predictions) evaluator_PR = BinaryClassificationEvaluator(labelCol="indexedLabel", rawPredictionCol="prediction", metricName="areaUnderPR") accuracy_PR = evaluator_PR.evaluate(predictions) conf_matrix = confusion_matrix(y_true, y_pred) result_dict = {} result_dict['experiment_filter'] = experiment_filter result_dict['undersampling_method'] = undersampling_method result_dict['filename'] = filename result_dict['experiment_id'] = experiment_id result_dict['n_covid'] = n_covid result_dict['n_not_covid'] = n_not_covid result_dict['model_name'] = 'GBT' result_dict['params'] = params_dict result_dict['model_AUC_ROC'] = accuracy_ROC result_dict['model_AUC_PR'] = accuracy_PR result_dict['model_covid_precision'] = report['covid']['precision'] result_dict['model_covid_recall'] = report['covid']['recall'] result_dict['model_covid_f1'] = report['covid']['f1-score'] result_dict['model_not_covid_precision'] = report['n-covid']['precision'] result_dict['model_not_covid_recall'] = report['n-covid']['recall'] result_dict['model_not_covid_f1'] = report['n-covid']['f1-score'] result_dict['model_avg_precision'] = report['macro avg']['precision'] result_dict['model_avg_recall'] = report['macro avg']['recall'] result_dict['model_avg_f1'] = report['macro avg']['f1-score'] result_dict['model_avg_acc'] = report['accuracy'] result_dict['model_TP'] = conf_matrix[0][0] result_dict['model_TN'] = conf_matrix[1][1] result_dict['model_FN'] = conf_matrix[0][1] result_dict['model_FP'] = conf_matrix[1][0] result_dict['model_time_exec'] = time.time() - start_time result_dict['model_col_set'] = cols return result_dict ``` <hr /> <hr /> <hr /> # Running GBT on 10 samples for each experiment ### 3x col sets -> ['cols_set_1', 'cols_set_2', 'cols_set_3'] ### 3x model_maxIter -> [100, 200, 300] ### 3x model_maxDepth -> [5, 10, 15] ### 3x model_maxBins -> [16, 32, 64] Total: 10 * 3 * 3 * 3 * 3 = 810 ``` experiments = [] ``` ### Datasets: strat_samp_lab_agegrp ``` for uc in undersamp_col: for ds in dfs: for col_set in cols_sets: for params_dict in list_of_param_dicts: for id_exp in range(50): filename = prefix + uc + '/' + ds + '/' + col_set + '/' + 'experiment' + str(id_exp) + '.parquet' exp_dataframe = spark.read.parquet(filename) # if 'SG_UF_NOT' in exp_dataframe.columns: # exp_dataframe = exp_dataframe.withColumn('SG_UF_NOT', F.col('SG_UF_NOT').cast('float')) print('read {}'.format(filename)) undersampling_method = uc experiment_filter = ds experiment_id = id_exp try: model = run_gbt(exp_dataframe, params_dict, col_set, filename, experiment_filter, undersampling_method, experiment_id) experiments.append(model) print("Parameters ==> {}\n Results: \n AUC_PR: {} \n Precision: {} \n Time: {}".format(str(params_dict), str(model['model_AUC_PR']), str(model['model_avg_precision']), str(model['model_time_exec']))) print('=========================== \n') except: print('=========== W A R N I N G =========== \n') print('Something wrong with the exp: {}, {}, {}'.format(filename, params_dict, col_set)) ``` <hr /> <hr /> <hr /> ``` for i in range(len(experiments)): for d in list(experiments[i].keys()): experiments[i][d] = str(experiments[i][d]) # experiments cols = ['experiment_filter', 'undersampling_method', 'filename', 'experiment_id', 'n_covid', 'n_not_covid', 'model_name', 'params', 'model_AUC_ROC', 'model_AUC_PR', 'model_covid_precision', 'model_covid_recall', 'model_covid_f1', 'model_not_covid_precision', 'model_not_covid_recall', 'model_not_covid_f1', 'model_avg_precision', 'model_avg_recall', 'model_avg_f1', 'model_avg_acc', 'model_TP', 'model_TN', 'model_FN', 'model_FP', 'model_time_exec', 'model_col_set'] intermed_results = spark.createDataFrame(data=experiments).select(cols) intermed_results.toPandas() intermed_results.write.parquet('gs://ai-covid19-datalake/trusted/intermed_results/STRSAMP/GBT_experiments-AG-ds3-cs3.parquet', mode='overwrite') print('finished') intermed_results.show() ```
github_jupyter
<a href="https://colab.research.google.com/github/cdosrunwild/glide-text2im/blob/main/Copy_of_Disco_Diffusion_v4_1_%5Bw_Video_Inits%2C_Recovery_%26_DDIM_Sharpen%5D.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Disco Diffusion v4.1 - Now with Video Inits, Recovery, DDIM Sharpen and improved UI In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model For issues, message [@Somnai_dreams](https://twitter.com/Somnai_dreams) or Somnai#6855 Credits & Changelog ⬇️ Original notebook by Katherine Crowson (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images. Modified by Daniel Russell (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations. Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve. Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy. The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri) Advanced DangoCutn Cutout method is also from Dango223. -- I, Somnai (https://twitter.com/Somnai_dreams), have added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below. ``` # @title Licensed under the MIT License # Copyright (c) 2021 Katherine Crowson # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #@title <- View Changelog skip_for_run_all = True #@param {type: 'boolean'} if skip_for_run_all == False: print( ''' v1 Update: Oct 29th 2021 QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization. v1.1 Update: Nov 13th 2021 Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work v2 Update: Nov 22nd 2021 Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR) Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme. v3 Update: Dec 24th 2021 Implemented Dango's advanced cutout method Added SLIP models, thanks to NeuralDivergent Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you) v4 Update: Jan 2021 Implemented Diffusion Zooming Added Chigozie keyframing Made a bunch of edits to processes v4.1 Update: Jan 14th 2021 Added video input mode Added license that somehow went missing Added improved prompt keyframing, fixed image_prompts and multiple prompts Improved UI Significant under the hood cleanup and improvement Refined defaults for each mode Added latent-diffusion SuperRes for sharpening Added resume run mode ''' ) from google.colab import drive drive.mount('/content/drive') ``` #Tutorial **Diffusion settings** --- This section is outdated as of v2 Setting | Description | Default --- | --- | --- **Your vision:** `text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A `image_prompts` | Think of these images more as a description of their contents. | N/A **Image quality:** `clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000 `tv_scale` | Controls the smoothness of the final output. | 150 `range_scale` | Controls how far out of range RGB values are allowed to be. | 150 `sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0 `cutn` | Controls how many crops to take from the image. | 16 `cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts | 2 **Init settings:** `init_image` | URL or local path | None `init_scale` | This enhances the effect of the init image, a good value is 1000 | 0 `skip_steps Controls the starting point along the diffusion timesteps | 0 `perlin_init` | Option to start with random perlin noise | False `perlin_mode` | ('gray', 'color') | 'mixed' **Advanced:** `skip_augs` |Controls whether to skip torchvision augmentations | False `randomize_class` |Controls whether the imagenet class is randomly changed each iteration | True `clip_denoised` |Determines whether CLIP discriminates a noisy or denoised image | False `clamp_grad` |Experimental: Using adaptive clip grad in the cond_fn | True `seed` | Choose a random seed and print it at end of run for reproduction | random_seed `fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False `rand_mag` |Controls the magnitude of the random noise | 0.1 `eta` | DDIM hyperparameter | 0.5 .. **Model settings** --- Setting | Description | Default --- | --- | --- **Diffusion:** `timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100 `diffusion_steps` || 1000 **Diffusion:** `clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4 # 1. Set Up ``` #@title 1.1 Check GPU Status !nvidia-smi -L from google.colab import drive #@title 1.2 Prepare Folders #@markdown If you connect your Google Drive, you can save the final image of each run on your drive. google_drive = True #@param {type:"boolean"} #@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive: yes_please = True #@param {type:"boolean"} if google_drive is True: drive.mount('/content/drive') root_path = '/content/drive/MyDrive/AI/Disco_Diffusion' else: root_path = '/content' import os from os import path #Simple create paths taken with modifications from Datamosh's Batch VQGAN+CLIP notebook def createPath(filepath): if path.exists(filepath) == False: os.makedirs(filepath) print(f'Made {filepath}') else: print(f'filepath {filepath} exists.') initDirPath = f'{root_path}/init_images' createPath(initDirPath) outDirPath = f'{root_path}/images_out' createPath(outDirPath) if google_drive and not yes_please or not google_drive: model_path = '/content/models' createPath(model_path) if google_drive and yes_please: model_path = f'{root_path}/models' createPath(model_path) # libraries = f'{root_path}/libraries' # createPath(libraries) #@title ### 1.3 Install and import dependencies if google_drive is not True: root_path = f'/content' model_path = '/content/models' model_256_downloaded = False model_512_downloaded = False model_secondary_downloaded = False !git clone https://github.com/openai/CLIP # !git clone https://github.com/facebookresearch/SLIP.git !git clone https://github.com/crowsonkb/guided-diffusion !git clone https://github.com/assafshocher/ResizeRight.git !pip install -e ./CLIP !pip install -e ./guided-diffusion !pip install lpips datetime timm !apt install imagemagick import sys # sys.path.append('./SLIP') sys.path.append('./ResizeRight') from dataclasses import dataclass from functools import partial import cv2 import pandas as pd import gc import io import math import timm from IPython import display import lpips from PIL import Image, ImageOps import requests from glob import glob import json from types import SimpleNamespace import torch from torch import nn from torch.nn import functional as F import torchvision.transforms as T import torchvision.transforms.functional as TF from tqdm.notebook import tqdm sys.path.append('./CLIP') sys.path.append('./guided-diffusion') import clip from resize_right import resize # from models import SLIP_VITB16, SLIP, SLIP_VITL16 from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults from datetime import datetime import numpy as np import matplotlib.pyplot as plt import random from ipywidgets import Output import hashlib #SuperRes !git clone https://github.com/CompVis/latent-diffusion.git !git clone https://github.com/CompVis/taming-transformers !pip install -e ./taming-transformers !pip install ipywidgets omegaconf>=2.0.0 pytorch-lightning>=1.0.8 torch-fidelity einops wandb #SuperRes import ipywidgets as widgets import os sys.path.append(".") sys.path.append('./taming-transformers') from taming.models import vqgan # checking correct import from taming from torchvision.datasets.utils import download_url %cd '/content/latent-diffusion' from functools import partial from ldm.util import instantiate_from_config from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like # from ldm.models.diffusion.ddim import DDIMSampler from ldm.util import ismap %cd '/content' from google.colab import files from IPython.display import Image as ipyimg from numpy import asarray from einops import rearrange, repeat import torch, torchvision import time from omegaconf import OmegaConf import warnings warnings.filterwarnings("ignore", category=UserWarning) import torch device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print('Using device:', device) if torch.cuda.get_device_capability(device) == (8,0): ## A100 fix thanks to Emad print('Disabling CUDNN for A100 gpu', file=sys.stderr) torch.backends.cudnn.enabled = False #@title 1.4 Define necessary functions # https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 def interp(t): return 3 * t**2 - 2 * t ** 3 def perlin(width, height, scale=10, device=None): gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device) xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device) ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device) wx = 1 - interp(xs) wy = 1 - interp(ys) dots = 0 dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys) dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys) dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys)) dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys)) return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale) def perlin_ms(octaves, width, height, grayscale, device=device): out_array = [0.5] if grayscale else [0.5, 0.5, 0.5] # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0] for i in range(1 if grayscale else 3): scale = 2 ** len(octaves) oct_width = width oct_height = height for oct in octaves: p = perlin(oct_width, oct_height, scale, device) out_array[i] += p * oct scale //= 2 oct_width *= 2 oct_height *= 2 return torch.cat(out_array) def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True): out = perlin_ms(octaves, width, height, grayscale) if grayscale: out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0)) out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB') else: out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1]) out = TF.resize(size=(side_y, side_x), img=out) out = TF.to_pil_image(out.clamp(0, 1).squeeze()) out = ImageOps.autocontrast(out) return out def regen_perlin(): if perlin_mode == 'color': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) elif perlin_mode == 'gray': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) else: init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) del init2 return init.expand(batch_size, -1, -1, -1) def fetch(url_or_path): if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'): r = requests.get(url_or_path) r.raise_for_status() fd = io.BytesIO() fd.write(r.content) fd.seek(0) return fd return open(url_or_path, 'rb') def read_image_workaround(path): """OpenCV reads images as BGR, Pillow saves them as RGB. Work around this incompatibility to avoid colour inversions.""" im_tmp = cv2.imread(path) return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB) def parse_prompt(prompt): if prompt.startswith('http://') or prompt.startswith('https://'): vals = prompt.rsplit(':', 2) vals = [vals[0] + ':' + vals[1], *vals[2:]] else: vals = prompt.rsplit(':', 1) vals = vals + ['', '1'][len(vals):] return vals[0], float(vals[1]) def sinc(x): return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([])) def lanczos(x, a): cond = torch.logical_and(-a < x, x < a) out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([])) return out / out.sum() def ramp(ratio, width): n = math.ceil(width / ratio + 1) out = torch.empty([n]) cur = 0 for i in range(out.shape[0]): out[i] = cur cur += ratio return torch.cat([-out[1:].flip([0]), out])[1:-1] def resample(input, size, align_corners=True): n, c, h, w = input.shape dh, dw = size input = input.reshape([n * c, 1, h, w]) if dh < h: kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype) pad_h = (kernel_h.shape[0] - 1) // 2 input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect') input = F.conv2d(input, kernel_h[None, None, :, None]) if dw < w: kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype) pad_w = (kernel_w.shape[0] - 1) // 2 input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect') input = F.conv2d(input, kernel_w[None, None, None, :]) input = input.reshape([n, c, h, w]) return F.interpolate(input, size, mode='bicubic', align_corners=align_corners) class MakeCutouts(nn.Module): def __init__(self, cut_size, cutn, skip_augs=False): super().__init__() self.cut_size = cut_size self.cutn = cutn self.skip_augs = skip_augs self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=15, translate=(0.1, 0.1)), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomPerspective(distortion_scale=0.4, p=0.7), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.15), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) def forward(self, input): input = T.Pad(input.shape[2]//4, fill=0)(input) sideY, sideX = input.shape[2:4] max_size = min(sideX, sideY) cutouts = [] for ch in range(self.cutn): if ch > self.cutn - self.cutn//4: cutout = input.clone() else: size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.)) offsetx = torch.randint(0, abs(sideX - size + 1), ()) offsety = torch.randint(0, abs(sideY - size + 1), ()) cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] if not self.skip_augs: cutout = self.augs(cutout) cutouts.append(resample(cutout, (self.cut_size, self.cut_size))) del cutout cutouts = torch.cat(cutouts, dim=0) return cutouts cutout_debug = False padargs = {} class MakeCutoutsDango(nn.Module): def __init__(self, cut_size, Overview=4, InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2 ): super().__init__() self.cut_size = cut_size self.Overview = Overview self.InnerCrop = InnerCrop self.IC_Size_Pow = IC_Size_Pow self.IC_Grey_P = IC_Grey_P if args.animation_mode == 'None': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.1), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) elif args.animation_mode == 'Video Input': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=15, translate=(0.1, 0.1)), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomPerspective(distortion_scale=0.4, p=0.7), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.15), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) elif args.animation_mode == '2D': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.4), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.1), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3), ]) def forward(self, input): cutouts = [] gray = T.Grayscale(3) sideY, sideX = input.shape[2:4] max_size = min(sideX, sideY) min_size = min(sideX, sideY, self.cut_size) l_size = max(sideX, sideY) output_shape = [1,3,self.cut_size,self.cut_size] output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2] pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs) cutout = resize(pad_input, out_shape=output_shape) if self.Overview>0: if self.Overview<=4: if self.Overview>=1: cutouts.append(cutout) if self.Overview>=2: cutouts.append(gray(cutout)) if self.Overview>=3: cutouts.append(TF.hflip(cutout)) if self.Overview==4: cutouts.append(gray(TF.hflip(cutout))) else: cutout = resize(pad_input, out_shape=output_shape) for _ in range(self.Overview): cutouts.append(cutout) if cutout_debug: TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99) if self.InnerCrop >0: for i in range(self.InnerCrop): size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size) offsetx = torch.randint(0, sideX - size + 1, ()) offsety = torch.randint(0, sideY - size + 1, ()) cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] if i <= int(self.IC_Grey_P * self.InnerCrop): cutout = gray(cutout) cutout = resize(cutout, out_shape=output_shape) cutouts.append(cutout) if cutout_debug: TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99) cutouts = torch.cat(cutouts) if skip_augs is not True: cutouts=self.augs(cutouts) return cutouts def spherical_dist_loss(x, y): x = F.normalize(x, dim=-1) y = F.normalize(y, dim=-1) return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) def tv_loss(input): """L2 total variation loss, as in Mahendran et al.""" input = F.pad(input, (0, 1, 0, 1), 'replicate') x_diff = input[..., :-1, 1:] - input[..., :-1, :-1] y_diff = input[..., 1:, :-1] - input[..., :-1, :-1] return (x_diff**2 + y_diff**2).mean([1, 2, 3]) def range_loss(input): return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3]) stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete def do_run(): seed = args.seed print(range(args.start_frame, args.max_frames)) for frame_num in range(args.start_frame, args.max_frames): if stop_on_next_loop: break display.clear_output(wait=True) # Print Frame progress if animation mode is on if args.animation_mode != "None": batchBar = tqdm(range(args.max_frames), desc ="Frames") batchBar.n = frame_num batchBar.refresh() # Inits if not video frames if args.animation_mode != "Video Input": if args.init_image == '': init_image = None else: init_image = args.init_image init_scale = args.init_scale skip_steps = args.skip_steps if args.animation_mode == "2D": if args.key_frames: angle = args.angle_series[frame_num] zoom = args.zoom_series[frame_num] translation_x = args.translation_x_series[frame_num] translation_y = args.translation_y_series[frame_num] print( f'angle: {angle}', f'zoom: {zoom}', f'translation_x: {translation_x}', f'translation_y: {translation_y}', ) if frame_num > 0: seed = seed + 1 if resume_run and frame_num == start_frame: img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png") else: img_0 = cv2.imread('prevFrame.png') center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2) trans_mat = np.float32( [[1, 0, translation_x], [0, 1, translation_y]] ) rot_mat = cv2.getRotationMatrix2D( center, angle, zoom ) trans_mat = np.vstack([trans_mat, [0,0,1]]) rot_mat = np.vstack([rot_mat, [0,0,1]]) transformation_matrix = np.matmul(rot_mat, trans_mat) img_0 = cv2.warpPerspective( img_0, transformation_matrix, (img_0.shape[1], img_0.shape[0]), borderMode=cv2.BORDER_WRAP ) cv2.imwrite('prevFrameScaled.png', img_0) init_image = 'prevFrameScaled.png' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps if args.animation_mode == "Video Input": seed = seed + 1 init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps loss_values = [] if seed is not None: np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True target_embeds, weights = [], [] if args.prompts_series is not None and frame_num >= len(args.prompts_series): frame_prompt = args.prompts_series[-1] elif args.prompts_series is not None: frame_prompt = args.prompts_series[frame_num] else: frame_prompt = [] print(args.image_prompts_series) if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series): image_prompt = args.image_prompts_series[-1] elif args.image_prompts_series is not None: image_prompt = args.image_prompts_series[frame_num] else: image_prompt = [] print(f'Frame Prompt: {frame_prompt}') model_stats = [] for clip_model in clip_models: cutn = 16 model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]} model_stat["clip_model"] = clip_model for prompt in frame_prompt: txt, weight = parse_prompt(prompt) txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float() if args.fuzzy_prompt: for i in range(25): model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1)) model_stat["weights"].append(weight) else: model_stat["target_embeds"].append(txt) model_stat["weights"].append(weight) if image_prompt: model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs) for prompt in image_prompt: path, weight = parse_prompt(prompt) img = Image.open(fetch(path)).convert('RGB') img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS) batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1)) embed = clip_model.encode_image(normalize(batch)).float() if fuzzy_prompt: for i in range(25): model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1)) weights.extend([weight / cutn] * cutn) else: model_stat["target_embeds"].append(embed) model_stat["weights"].extend([weight / cutn] * cutn) model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"]) model_stat["weights"] = torch.tensor(model_stat["weights"], device=device) if model_stat["weights"].sum().abs() < 1e-3: raise RuntimeError('The weights must not sum to 0.') model_stat["weights"] /= model_stat["weights"].sum().abs() model_stats.append(model_stat) init = None if init_image is not None: init = Image.open(fetch(init_image)).convert('RGB') init = init.resize((args.side_x, args.side_y), Image.LANCZOS) init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1) if args.perlin_init: if args.perlin_mode == 'color': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) elif args.perlin_mode == 'gray': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) else: init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device) init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) del init2 cur_t = None def cond_fn(x, t, y=None): with torch.enable_grad(): x_is_NaN = False x = x.detach().requires_grad_() n = x.shape[0] if use_secondary_model is True: alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32) sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32) cosine_t = alpha_sigma_to_t(alpha, sigma) out = secondary_model(x, cosine_t[None].repeat([n])).pred fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] x_in = out * fac + x * (1 - fac) x_in_grad = torch.zeros_like(x_in) else: my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y}) fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] x_in = out['pred_xstart'] * fac + x * (1 - fac) x_in_grad = torch.zeros_like(x_in) for model_stat in model_stats: for i in range(args.cutn_batches): t_int = int(t.item())+1 #errors on last step without +1, need to find source #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution' try: input_resolution=model_stat["clip_model"].visual.input_resolution except: input_resolution=224 cuts = MakeCutoutsDango(input_resolution, Overview= args.cut_overview[1000-t_int], InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int] ) clip_in = normalize(cuts(x_in.add(1).div(2))) image_embeds = model_stat["clip_model"].encode_image(clip_in).float() dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0)) dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1]) losses = dists.mul(model_stat["weights"]).sum(2).mean(0) loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches tv_losses = tv_loss(x_in) if use_secondary_model is True: range_losses = range_loss(out) else: range_losses = range_loss(out['pred_xstart']) sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean() loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale if init is not None and args.init_scale: init_losses = lpips_model(x_in, init) loss = loss + init_losses.sum() * args.init_scale x_in_grad += torch.autograd.grad(loss, x_in)[0] if torch.isnan(x_in_grad).any()==False: grad = -torch.autograd.grad(x_in, x, x_in_grad)[0] else: # print("NaN'd") x_is_NaN = True grad = torch.zeros_like(x) if args.clamp_grad and x_is_NaN == False: magnitude = grad.square().mean().sqrt() return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, return grad if model_config['timestep_respacing'].startswith('ddim'): sample_fn = diffusion.ddim_sample_loop_progressive else: sample_fn = diffusion.p_sample_loop_progressive image_display = Output() for i in range(args.n_batches): if args.animation_mode == 'None': display.clear_output(wait=True) batchBar = tqdm(range(args.n_batches), desc ="Batches") batchBar.n = i batchBar.refresh() print('') display.display(image_display) gc.collect() torch.cuda.empty_cache() cur_t = diffusion.num_timesteps - skip_steps - 1 total_steps = cur_t if perlin_init: init = regen_perlin() if model_config['timestep_respacing'].startswith('ddim'): samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), clip_denoised=clip_denoised, model_kwargs={}, cond_fn=cond_fn, progress=True, skip_timesteps=skip_steps, init_image=init, randomize_class=randomize_class, eta=eta, ) else: samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), clip_denoised=clip_denoised, model_kwargs={}, cond_fn=cond_fn, progress=True, skip_timesteps=skip_steps, init_image=init, randomize_class=randomize_class, ) # with run_display: # display.clear_output(wait=True) imgToSharpen = None for j, sample in enumerate(samples): cur_t -= 1 intermediateStep = False if args.steps_per_checkpoint is not None: if j % steps_per_checkpoint == 0 and j > 0: intermediateStep = True elif j in args.intermediate_saves: intermediateStep = True with image_display: if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True: for k, image in enumerate(sample['pred_xstart']): # tqdm.write(f'Batch {i}, step {j}, output {k}:') current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f') percent = math.ceil(j/total_steps*100) if args.n_batches > 0: #if intermediates are saved to the subfolder, don't append a step or percentage to the name if cur_t == -1 and args.intermediates_in_subfolder is True: save_num = f'{frame_num:04}' if animation_mode != "None" else i filename = f'{args.batch_name}({args.batchNum})_{save_num}.png' else: #If we're working with percentages, append it if args.steps_per_checkpoint is not None: filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png' # Or else, iIf we're working with specific steps, append those else: filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png' image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1)) if j % args.display_rate == 0 or cur_t == -1: image.save('progress.png') display.clear_output(wait=True) display.display(display.Image('progress.png')) if args.steps_per_checkpoint is not None: if j % args.steps_per_checkpoint == 0 and j > 0: if args.intermediates_in_subfolder is True: image.save(f'{partialFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') else: if j in args.intermediate_saves: if args.intermediates_in_subfolder is True: image.save(f'{partialFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') if cur_t == -1: if frame_num == 0: save_settings() if args.animation_mode != "None": image.save('prevFrame.png') if args.sharpen_preset != "Off" and animation_mode == "None": imgToSharpen = image if args.keep_unsharp is True: image.save(f'{unsharpenFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') # if frame_num != args.max_frames-1: # display.clear_output() with image_display: if args.sharpen_preset != "Off" and animation_mode == "None": print('Starting Diffusion Sharpening...') do_superres(imgToSharpen, f'{batchFolder}/{filename}') display.clear_output() plt.plot(np.array(loss_values), 'r') def save_settings(): setting_list = { 'text_prompts': text_prompts, 'image_prompts': image_prompts, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, 'range_scale': range_scale, 'sat_scale': sat_scale, # 'cutn': cutn, 'cutn_batches': cutn_batches, 'max_frames': max_frames, 'interp_spline': interp_spline, # 'rotation_per_frame': rotation_per_frame, 'init_image': init_image, 'init_scale': init_scale, 'skip_steps': skip_steps, # 'zoom_per_frame': zoom_per_frame, 'frames_scale': frames_scale, 'frames_skip_steps': frames_skip_steps, 'perlin_init': perlin_init, 'perlin_mode': perlin_mode, 'skip_augs': skip_augs, 'randomize_class': randomize_class, 'clip_denoised': clip_denoised, 'clamp_grad': clamp_grad, 'clamp_max': clamp_max, 'seed': seed, 'fuzzy_prompt': fuzzy_prompt, 'rand_mag': rand_mag, 'eta': eta, 'width': width_height[0], 'height': width_height[1], 'diffusion_model': diffusion_model, 'use_secondary_model': use_secondary_model, 'steps': steps, 'diffusion_steps': diffusion_steps, 'ViTB32': ViTB32, 'ViTB16': ViTB16, 'ViTL14': ViTL14, 'RN101': RN101, 'RN50': RN50, 'RN50x4': RN50x4, 'RN50x16': RN50x16, 'RN50x64': RN50x64, 'cut_overview': str(cut_overview), 'cut_innercut': str(cut_innercut), 'cut_ic_pow': cut_ic_pow, 'cut_icgray_p': str(cut_icgray_p), 'key_frames': key_frames, 'max_frames': max_frames, 'angle': angle, 'zoom': zoom, 'translation_x': translation_x, 'translation_y': translation_y, 'video_init_path':video_init_path, 'extract_nth_frame':extract_nth_frame, } # print('Settings:', setting_list) with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings json.dump(setting_list, f, ensure_ascii=False, indent=4) #@title 1.5 Define the secondary diffusion model def append_dims(x, n): return x[(Ellipsis, *(None,) * (n - x.ndim))] def expand_to_planes(x, shape): return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]]) def alpha_sigma_to_t(alpha, sigma): return torch.atan2(sigma, alpha) * 2 / math.pi def t_to_alpha_sigma(t): return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) @dataclass class DiffusionOutput: v: torch.Tensor pred: torch.Tensor eps: torch.Tensor class ConvBlock(nn.Sequential): def __init__(self, c_in, c_out): super().__init__( nn.Conv2d(c_in, c_out, 3, padding=1), nn.ReLU(inplace=True), ) class SkipBlock(nn.Module): def __init__(self, main, skip=None): super().__init__() self.main = nn.Sequential(*main) self.skip = skip if skip else nn.Identity() def forward(self, input): return torch.cat([self.main(input), self.skip(input)], dim=1) class FourierFeatures(nn.Module): def __init__(self, in_features, out_features, std=1.): super().__init__() assert out_features % 2 == 0 self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std) def forward(self, input): f = 2 * math.pi * input @ self.weight.T return torch.cat([f.cos(), f.sin()], dim=-1) class SecondaryDiffusionImageNet(nn.Module): def __init__(self): super().__init__() c = 64 # The base channel count self.timestep_embed = FourierFeatures(1, 16) self.net = nn.Sequential( ConvBlock(3 + 16, c), ConvBlock(c, c), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c, c * 2), ConvBlock(c * 2, c * 2), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c * 2, c * 4), ConvBlock(c * 4, c * 4), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c * 4, c * 8), ConvBlock(c * 8, c * 4), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 8, c * 4), ConvBlock(c * 4, c * 2), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 4, c * 2), ConvBlock(c * 2, c), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 2, c), nn.Conv2d(c, 3, 3, padding=1), ) def forward(self, input, t): timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) v = self.net(torch.cat([input, timestep_embed], dim=1)) alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) pred = input * alphas - v * sigmas eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) class SecondaryDiffusionImageNet2(nn.Module): def __init__(self): super().__init__() c = 64 # The base channel count cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8] self.timestep_embed = FourierFeatures(1, 16) self.down = nn.AvgPool2d(2) self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) self.net = nn.Sequential( ConvBlock(3 + 16, cs[0]), ConvBlock(cs[0], cs[0]), SkipBlock([ self.down, ConvBlock(cs[0], cs[1]), ConvBlock(cs[1], cs[1]), SkipBlock([ self.down, ConvBlock(cs[1], cs[2]), ConvBlock(cs[2], cs[2]), SkipBlock([ self.down, ConvBlock(cs[2], cs[3]), ConvBlock(cs[3], cs[3]), SkipBlock([ self.down, ConvBlock(cs[3], cs[4]), ConvBlock(cs[4], cs[4]), SkipBlock([ self.down, ConvBlock(cs[4], cs[5]), ConvBlock(cs[5], cs[5]), ConvBlock(cs[5], cs[5]), ConvBlock(cs[5], cs[4]), self.up, ]), ConvBlock(cs[4] * 2, cs[4]), ConvBlock(cs[4], cs[3]), self.up, ]), ConvBlock(cs[3] * 2, cs[3]), ConvBlock(cs[3], cs[2]), self.up, ]), ConvBlock(cs[2] * 2, cs[2]), ConvBlock(cs[2], cs[1]), self.up, ]), ConvBlock(cs[1] * 2, cs[1]), ConvBlock(cs[1], cs[0]), self.up, ]), ConvBlock(cs[0] * 2, cs[0]), nn.Conv2d(cs[0], 3, 3, padding=1), ) def forward(self, input, t): timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) v = self.net(torch.cat([input, timestep_embed], dim=1)) alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) pred = input * alphas - v * sigmas eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) #@title 1.6 SuperRes Define class DDIMSampler(object): def __init__(self, model, schedule="linear", **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if type(attr) == torch.Tensor: if attr.device != torch.device("cuda"): attr = attr.to(torch.device("cuda")) setattr(self, name, attr) def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) alphas_cumprod = self.model.alphas_cumprod assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) self.register_buffer('betas', to_torch(self.model.betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) # ddim sampling parameters ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), ddim_timesteps=self.ddim_timesteps, eta=ddim_eta,verbose=verbose) self.register_buffer('ddim_sigmas', ddim_sigmas) self.register_buffer('ddim_alphas', ddim_alphas) self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) @torch.no_grad() def sample(self, S, batch_size, shape, conditioning=None, callback=None, normals_sequence=None, img_callback=None, quantize_x0=False, eta=0., mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, verbose=True, x_T=None, log_every_t=100, **kwargs ): if conditioning is not None: if isinstance(conditioning, dict): cbs = conditioning[list(conditioning.keys())[0]].shape[0] if cbs != batch_size: print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") else: if conditioning.shape[0] != batch_size: print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) # sampling C, H, W = shape size = (batch_size, C, H, W) # print(f'Data shape for DDIM sampling is {size}, eta {eta}') samples, intermediates = self.ddim_sampling(conditioning, size, callback=callback, img_callback=img_callback, quantize_denoised=quantize_x0, mask=mask, x0=x0, ddim_use_original_steps=False, noise_dropout=noise_dropout, temperature=temperature, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, x_T=x_T, log_every_t=log_every_t ) return samples, intermediates @torch.no_grad() def ddim_sampling(self, cond, shape, x_T=None, ddim_use_original_steps=False, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, log_every_t=100, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): device = self.model.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T if timesteps is None: timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps elif timesteps is not None and not ddim_use_original_steps: subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 timesteps = self.ddim_timesteps[:subset_end] intermediates = {'x_inter': [img], 'pred_x0': [img]} time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps) total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] print(f"Running DDIM Sharpening with {total_steps} timesteps") iterator = tqdm(time_range, desc='DDIM Sharpening', total=total_steps) for i, step in enumerate(iterator): index = total_steps - i - 1 ts = torch.full((b,), step, device=device, dtype=torch.long) if mask is not None: assert x0 is not None img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? img = img_orig * mask + (1. - mask) * img outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, quantize_denoised=quantize_denoised, temperature=temperature, noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs) img, pred_x0 = outs if callback: callback(i) if img_callback: img_callback(pred_x0, i) if index % log_every_t == 0 or index == total_steps - 1: intermediates['x_inter'].append(img) intermediates['pred_x0'].append(pred_x0) return img, intermediates @torch.no_grad() def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None): b, *_, device = *x.shape, x.device e_t = self.model.apply_model(x, t, c) if score_corrector is not None: assert self.model.parameterization == "eps" e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas # select parameters corresponding to the currently considered timestep a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) # current prediction for x_0 pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() if quantize_denoised: pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) # direction pointing to x_t dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise return x_prev, pred_x0 def download_models(mode): if mode == "superresolution": # this is the small bsr light model url_conf = 'https://heibox.uni-heidelberg.de/f/31a76b13ea27482981b4/?dl=1' url_ckpt = 'https://heibox.uni-heidelberg.de/f/578df07c8fc04ffbadf3/?dl=1' path_conf = f'{model_path}/superres/project.yaml' path_ckpt = f'{model_path}/superres/last.ckpt' download_url(url_conf, path_conf) download_url(url_ckpt, path_ckpt) path_conf = path_conf + '/?dl=1' # fix it path_ckpt = path_ckpt + '/?dl=1' # fix it return path_conf, path_ckpt else: raise NotImplementedError def load_model_from_config(config, ckpt): print(f"Loading model from {ckpt}") pl_sd = torch.load(ckpt, map_location="cpu") global_step = pl_sd["global_step"] sd = pl_sd["state_dict"] model = instantiate_from_config(config.model) m, u = model.load_state_dict(sd, strict=False) model.cuda() model.eval() return {"model": model}, global_step def get_model(mode): path_conf, path_ckpt = download_models(mode) config = OmegaConf.load(path_conf) model, step = load_model_from_config(config, path_ckpt) return model def get_custom_cond(mode): dest = "data/example_conditioning" if mode == "superresolution": uploaded_img = files.upload() filename = next(iter(uploaded_img)) name, filetype = filename.split(".") # todo assumes just one dot in name ! os.rename(f"{filename}", f"{dest}/{mode}/custom_{name}.{filetype}") elif mode == "text_conditional": w = widgets.Text(value='A cake with cream!', disabled=True) display.display(w) with open(f"{dest}/{mode}/custom_{w.value[:20]}.txt", 'w') as f: f.write(w.value) elif mode == "class_conditional": w = widgets.IntSlider(min=0, max=1000) display.display(w) with open(f"{dest}/{mode}/custom.txt", 'w') as f: f.write(w.value) else: raise NotImplementedError(f"cond not implemented for mode{mode}") def get_cond_options(mode): path = "data/example_conditioning" path = os.path.join(path, mode) onlyfiles = [f for f in sorted(os.listdir(path))] return path, onlyfiles def select_cond_path(mode): path = "data/example_conditioning" # todo path = os.path.join(path, mode) onlyfiles = [f for f in sorted(os.listdir(path))] selected = widgets.RadioButtons( options=onlyfiles, description='Select conditioning:', disabled=False ) display.display(selected) selected_path = os.path.join(path, selected.value) return selected_path def get_cond(mode, img): example = dict() if mode == "superresolution": up_f = 4 # visualize_cond_img(selected_path) c = img c = torch.unsqueeze(torchvision.transforms.ToTensor()(c), 0) c_up = torchvision.transforms.functional.resize(c, size=[up_f * c.shape[2], up_f * c.shape[3]], antialias=True) c_up = rearrange(c_up, '1 c h w -> 1 h w c') c = rearrange(c, '1 c h w -> 1 h w c') c = 2. * c - 1. c = c.to(torch.device("cuda")) example["LR_image"] = c example["image"] = c_up return example def visualize_cond_img(path): display.display(ipyimg(filename=path)) def sr_run(model, img, task, custom_steps, eta, resize_enabled=False, classifier_ckpt=None, global_step=None): # global stride example = get_cond(task, img) save_intermediate_vid = False n_runs = 1 masked = False guider = None ckwargs = None mode = 'ddim' ddim_use_x0_pred = False temperature = 1. eta = eta make_progrow = True custom_shape = None height, width = example["image"].shape[1:3] split_input = height >= 128 and width >= 128 if split_input: ks = 128 stride = 64 vqf = 4 # model.split_input_params = {"ks": (ks, ks), "stride": (stride, stride), "vqf": vqf, "patch_distributed_vq": True, "tie_braker": False, "clip_max_weight": 0.5, "clip_min_weight": 0.01, "clip_max_tie_weight": 0.5, "clip_min_tie_weight": 0.01} else: if hasattr(model, "split_input_params"): delattr(model, "split_input_params") invert_mask = False x_T = None for n in range(n_runs): if custom_shape is not None: x_T = torch.randn(1, custom_shape[1], custom_shape[2], custom_shape[3]).to(model.device) x_T = repeat(x_T, '1 c h w -> b c h w', b=custom_shape[0]) logs = make_convolutional_sample(example, model, mode=mode, custom_steps=custom_steps, eta=eta, swap_mode=False , masked=masked, invert_mask=invert_mask, quantize_x0=False, custom_schedule=None, decode_interval=10, resize_enabled=resize_enabled, custom_shape=custom_shape, temperature=temperature, noise_dropout=0., corrector=guider, corrector_kwargs=ckwargs, x_T=x_T, save_intermediate_vid=save_intermediate_vid, make_progrow=make_progrow,ddim_use_x0_pred=ddim_use_x0_pred ) return logs @torch.no_grad() def convsample_ddim(model, cond, steps, shape, eta=1.0, callback=None, normals_sequence=None, mask=None, x0=None, quantize_x0=False, img_callback=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, x_T=None, log_every_t=None ): ddim = DDIMSampler(model) bs = shape[0] # dont know where this comes from but wayne shape = shape[1:] # cut batch dim # print(f"Sampling with eta = {eta}; steps: {steps}") samples, intermediates = ddim.sample(steps, batch_size=bs, shape=shape, conditioning=cond, callback=callback, normals_sequence=normals_sequence, quantize_x0=quantize_x0, eta=eta, mask=mask, x0=x0, temperature=temperature, verbose=False, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, x_T=x_T) return samples, intermediates @torch.no_grad() def make_convolutional_sample(batch, model, mode="vanilla", custom_steps=None, eta=1.0, swap_mode=False, masked=False, invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, resize_enabled=False, custom_shape=None, temperature=1., noise_dropout=0., corrector=None, corrector_kwargs=None, x_T=None, save_intermediate_vid=False, make_progrow=True,ddim_use_x0_pred=False): log = dict() z, c, x, xrec, xc = model.get_input(batch, model.first_stage_key, return_first_stage_outputs=True, force_c_encode=not (hasattr(model, 'split_input_params') and model.cond_stage_key == 'coordinates_bbox'), return_original_cond=True) log_every_t = 1 if save_intermediate_vid else None if custom_shape is not None: z = torch.randn(custom_shape) # print(f"Generating {custom_shape[0]} samples of shape {custom_shape[1:]}") z0 = None log["input"] = x log["reconstruction"] = xrec if ismap(xc): log["original_conditioning"] = model.to_rgb(xc) if hasattr(model, 'cond_stage_key'): log[model.cond_stage_key] = model.to_rgb(xc) else: log["original_conditioning"] = xc if xc is not None else torch.zeros_like(x) if model.cond_stage_model: log[model.cond_stage_key] = xc if xc is not None else torch.zeros_like(x) if model.cond_stage_key =='class_label': log[model.cond_stage_key] = xc[model.cond_stage_key] with model.ema_scope("Plotting"): t0 = time.time() img_cb = None sample, intermediates = convsample_ddim(model, c, steps=custom_steps, shape=z.shape, eta=eta, quantize_x0=quantize_x0, img_callback=img_cb, mask=None, x0=z0, temperature=temperature, noise_dropout=noise_dropout, score_corrector=corrector, corrector_kwargs=corrector_kwargs, x_T=x_T, log_every_t=log_every_t) t1 = time.time() if ddim_use_x0_pred: sample = intermediates['pred_x0'][-1] x_sample = model.decode_first_stage(sample) try: x_sample_noquant = model.decode_first_stage(sample, force_not_quantize=True) log["sample_noquant"] = x_sample_noquant log["sample_diff"] = torch.abs(x_sample_noquant - x_sample) except: pass log["sample"] = x_sample log["time"] = t1 - t0 return log sr_diffMode = 'superresolution' sr_model = get_model('superresolution') def do_superres(img, filepath): if args.sharpen_preset == 'Faster': sr_diffusion_steps = "25" sr_pre_downsample = '1/2' if args.sharpen_preset == 'Fast': sr_diffusion_steps = "100" sr_pre_downsample = '1/2' if args.sharpen_preset == 'Slow': sr_diffusion_steps = "25" sr_pre_downsample = 'None' if args.sharpen_preset == 'Very Slow': sr_diffusion_steps = "100" sr_pre_downsample = 'None' sr_post_downsample = 'Original Size' sr_diffusion_steps = int(sr_diffusion_steps) sr_eta = 1.0 sr_downsample_method = 'Lanczos' gc.collect() torch.cuda.empty_cache() im_og = img width_og, height_og = im_og.size #Downsample Pre if sr_pre_downsample == '1/2': downsample_rate = 2 elif sr_pre_downsample == '1/4': downsample_rate = 4 else: downsample_rate = 1 width_downsampled_pre = width_og//downsample_rate height_downsampled_pre = height_og//downsample_rate if downsample_rate != 1: # print(f'Downsampling from [{width_og}, {height_og}] to [{width_downsampled_pre}, {height_downsampled_pre}]') im_og = im_og.resize((width_downsampled_pre, height_downsampled_pre), Image.LANCZOS) # im_og.save('/content/temp.png') # filepath = '/content/temp.png' logs = sr_run(sr_model["model"], im_og, sr_diffMode, sr_diffusion_steps, sr_eta) sample = logs["sample"] sample = sample.detach().cpu() sample = torch.clamp(sample, -1., 1.) sample = (sample + 1.) / 2. * 255 sample = sample.numpy().astype(np.uint8) sample = np.transpose(sample, (0, 2, 3, 1)) a = Image.fromarray(sample[0]) #Downsample Post if sr_post_downsample == '1/2': downsample_rate = 2 elif sr_post_downsample == '1/4': downsample_rate = 4 else: downsample_rate = 1 width, height = a.size width_downsampled_post = width//downsample_rate height_downsampled_post = height//downsample_rate if sr_downsample_method == 'Lanczos': aliasing = Image.LANCZOS else: aliasing = Image.NEAREST if downsample_rate != 1: # print(f'Downsampling from [{width}, {height}] to [{width_downsampled_post}, {height_downsampled_post}]') a = a.resize((width_downsampled_post, height_downsampled_post), aliasing) elif sr_post_downsample == 'Original Size': # print(f'Downsampling from [{width}, {height}] to Original Size [{width_og}, {height_og}]') a = a.resize((width_og, height_og), aliasing) display.display(a) a.save(filepath) return print(f'Processing finished!') ``` # 2. Diffusion and CLIP model settings ``` #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} timestep_respacing = '50' # param ['25','50','100','150','250','500','1000','ddim25','ddim50', 'ddim75', 'ddim100','ddim150','ddim250','ddim500','ddim1000'] diffusion_steps = 1000 # param {type: 'number'} use_checkpoint = True #@param {type: 'boolean'} ViTB32 = True #@param{type:"boolean"} ViTB16 = True #@param{type:"boolean"} ViTL14 = False #@param{type:"boolean"} RN101 = False #@param{type:"boolean"} RN50 = True #@param{type:"boolean"} RN50x4 = False #@param{type:"boolean"} RN50x16 = False #@param{type:"boolean"} RN50x64 = False #@param{type:"boolean"} SLIPB16 = False # param{type:"boolean"} SLIPL16 = False # param{type:"boolean"} #@markdown If you're having issues with model downloads, check this to compare SHA's: check_model_SHA = False #@param{type:"boolean"} model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' # Download the diffusion model if diffusion_model == '256x256_diffusion_uncond': if os.path.exists(model_256_path) and check_model_SHA: print('Checking 256 Diffusion File') with open(model_256_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_256_SHA: print('256 Model SHA matches') model_256_downloaded = True else: print("256 Model SHA doesn't match, redownloading...") !wget --continue {model_256_link} -P {model_path} model_256_downloaded = True elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: print('256 Model already downloaded, check check_model_SHA if the file is corrupt') else: !wget --continue {model_256_link} -P {model_path} model_256_downloaded = True elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': if os.path.exists(model_512_path) and check_model_SHA: print('Checking 512 Diffusion File') with open(model_512_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_512_SHA: print('512 Model SHA matches') model_512_downloaded = True else: print("512 Model SHA doesn't match, redownloading...") !wget --continue {model_512_link} -P {model_path} model_512_downloaded = True elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded == True: print('512 Model already downloaded, check check_model_SHA if the file is corrupt') else: !wget --continue {model_512_link} -P {model_path} model_512_downloaded = True # Download the secondary diffusion model v2 if use_secondary_model == True: if os.path.exists(model_secondary_path) and check_model_SHA: print('Checking Secondary Diffusion File') with open(model_secondary_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_secondary_SHA: print('Secondary Model SHA matches') model_secondary_downloaded = True else: print("Secondary Model SHA doesn't match, redownloading...") !wget --continue {model_secondary_link} -P {model_path} model_secondary_downloaded = True elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded == True: print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') else: !wget --continue {model_secondary_link} -P {model_path} model_secondary_downloaded = True model_config = model_and_diffusion_defaults() if diffusion_model == '512x512_diffusion_uncond_finetune_008100': model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, 'diffusion_steps': diffusion_steps, 'rescale_timesteps': True, 'timestep_respacing': timestep_respacing, 'image_size': 512, 'learn_sigma': True, 'noise_schedule': 'linear', 'num_channels': 256, 'num_head_channels': 64, 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, 'use_fp16': True, 'use_scale_shift_norm': True, }) elif diffusion_model == '256x256_diffusion_uncond': model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, 'diffusion_steps': diffusion_steps, 'rescale_timesteps': True, 'timestep_respacing': timestep_respacing, 'image_size': 256, 'learn_sigma': True, 'noise_schedule': 'linear', 'num_channels': 256, 'num_head_channels': 64, 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, 'use_fp16': True, 'use_scale_shift_norm': True, }) secondary_model_ver = 2 model_default = model_config['image_size'] if secondary_model_ver == 2: secondary_model = SecondaryDiffusionImageNet2() secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu')) secondary_model.eval().requires_grad_(False).to(device) clip_models = [] if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) ) if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) ) if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) if SLIPB16: SLIPB16model = SLIP_VITB16(ssl_mlp_dim=4096, ssl_emb_dim=256) if not os.path.exists(f'{model_path}/slip_base_100ep.pt'): !wget https://dl.fbaipublicfiles.com/slip/slip_base_100ep.pt -P {model_path} sd = torch.load(f'{model_path}/slip_base_100ep.pt') real_sd = {} for k, v in sd['state_dict'].items(): real_sd['.'.join(k.split('.')[1:])] = v del sd SLIPB16model.load_state_dict(real_sd) SLIPB16model.requires_grad_(False).eval().to(device) clip_models.append(SLIPB16model) if SLIPL16: SLIPL16model = SLIP_VITL16(ssl_mlp_dim=4096, ssl_emb_dim=256) if not os.path.exists(f'{model_path}/slip_large_100ep.pt'): !wget https://dl.fbaipublicfiles.com/slip/slip_large_100ep.pt -P {model_path} sd = torch.load(f'{model_path}/slip_large_100ep.pt') real_sd = {} for k, v in sd['state_dict'].items(): real_sd['.'.join(k.split('.')[1:])] = v del sd SLIPL16model.load_state_dict(real_sd) SLIPL16model.requires_grad_(False).eval().to(device) clip_models.append(SLIPL16model) normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) lpips_model = lpips.LPIPS(net='vgg').to(device) ``` # 3. Settings ``` #@markdown ####**Basic Settings:** batch_name = 'TimeToDisco60' #@param{type: 'string'} steps = 250#@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} width_height = [1280, 768]#@param{type: 'raw'} clip_guidance_scale = 5000 #@param{type: 'number'} tv_scale = 0#@param{type: 'number'} range_scale = 150#@param{type: 'number'} sat_scale = 0#@param{type: 'number'} cutn_batches = 1 #@param{type: 'number'} skip_augs = False#@param{type: 'boolean'} #@markdown --- #@markdown ####**Init Settings:** init_image = None #@param{type: 'string'} init_scale = 1000 #@param{type: 'integer'} skip_steps = 0 #@param{type: 'integer'} #@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.* #Get corrected sizes side_x = (width_height[0]//64)*64; side_y = (width_height[1]//64)*64; if side_x != width_height[0] or side_y != width_height[1]: print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.') #Update Model Settings timestep_respacing = f'ddim{steps}' diffusion_steps = (1000//steps)*steps if steps < 1000 else steps model_config.update({ 'timestep_respacing': timestep_respacing, 'diffusion_steps': diffusion_steps, }) #Make folder for batch batchFolder = f'{outDirPath}/{batch_name}' createPath(batchFolder) ``` ###Animation Settings ``` #@markdown ####**Animation Mode:** animation_mode = "None" #@param['None', '2D', 'Video Input'] #@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.* #@markdown --- #@markdown ####**Video Input Settings:** video_init_path = "/content/training.mp4" #@param {type: 'string'} extract_nth_frame = 2 #@param {type:"number"} if animation_mode == "Video Input": videoFramesFolder = f'/content/videoFrames' createPath(videoFramesFolder) print(f"Exporting Video Frames (1 every {extract_nth_frame})...") try: !rm {videoFramesFolder}/*.jpg except: print('') vf = f'"select=not(mod(n\,{extract_nth_frame}))"' !ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg #@markdown --- #@markdown ####**2D Animation Settings:** #@markdown `zoom` is a multiplier of dimensions, 1 is no zoom. key_frames = True #@param {type:"boolean"} max_frames = 100#@param {type:"number"} if animation_mode == "Video Input": max_frames = len(glob(f'{videoFramesFolder}/*.jpg')) interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"} angle = "0:(0)"#@param {type:"string"} zoom = "0: (1), 10: (1.05)"#@param {type:"string"} translation_x = "0: (0)"#@param {type:"string"} translation_y = "0: (0)"#@param {type:"string"} #@markdown --- #@markdown ####**Coherency Settings:** #@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500. frames_scale = 1500 #@param{type: 'integer'} #@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} def parse_key_frames(string, prompt_parser=None): """Given a string representing frame numbers paired with parameter values at that frame, return a dictionary with the frame numbers as keys and the parameter values as the values. Parameters ---------- string: string Frame numbers paired with parameter values at that frame number, in the format 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...' prompt_parser: function or None, optional If provided, prompt_parser will be applied to each string of parameter values. Returns ------- dict Frame numbers as keys, parameter values at that frame number as values Raises ------ RuntimeError If the input string does not match the expected format. Examples -------- >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)") {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'} >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower())) {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'} """ import re pattern = r'((?P<frame>[0-9]+):[\s]*[\(](?P<param>[\S\s]*?)[\)])' frames = dict() for match_object in re.finditer(pattern, string): frame = int(match_object.groupdict()['frame']) param = match_object.groupdict()['param'] if prompt_parser: frames[frame] = prompt_parser(param) else: frames[frame] = param if frames == {} and len(string) != 0: raise RuntimeError('Key Frame string not correctly formatted') return frames def get_inbetweens(key_frames, integer=False): """Given a dict with frame numbers as keys and a parameter value as values, return a pandas Series containing the value of the parameter at every frame from 0 to max_frames. Any values not provided in the input dict are calculated by linear interpolation between the values of the previous and next provided frames. If there is no previous provided frame, then the value is equal to the value of the next provided frame, or if there is no next provided frame, then the value is equal to the value of the previous provided frame. If no frames are provided, all frame values are NaN. Parameters ---------- key_frames: dict A dict with integer frame numbers as keys and numerical values of a particular parameter as values. integer: Bool, optional If True, the values of the output series are converted to integers. Otherwise, the values are floats. Returns ------- pd.Series A Series with length max_frames representing the parameter values for each frame. Examples -------- >>> max_frames = 5 >>> get_inbetweens({1: 5, 3: 6}) 0 5.0 1 5.0 2 5.5 3 6.0 4 6.0 dtype: float64 >>> get_inbetweens({1: 5, 3: 6}, integer=True) 0 5 1 5 2 5 3 6 4 6 dtype: int64 """ key_frame_series = pd.Series([np.nan for a in range(max_frames)]) for i, value in key_frames.items(): key_frame_series[i] = value key_frame_series = key_frame_series.astype(float) interp_method = interp_spline if interp_method == 'Cubic' and len(key_frames.items()) <=3: interp_method = 'Quadratic' if interp_method == 'Quadratic' and len(key_frames.items()) <= 2: interp_method = 'Linear' key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()] key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()] # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both') key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both') if integer: return key_frame_series.astype(int) return key_frame_series def split_prompts(prompts): prompt_series = pd.Series([np.nan for a in range(max_frames)]) for i, prompt in prompts.items(): prompt_series[i] = prompt # prompt_series = prompt_series.astype(str) prompt_series = prompt_series.ffill().bfill() return prompt_series if key_frames: try: angle_series = get_inbetweens(parse_key_frames(angle)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `angle` correctly for key frames.\n" "Attempting to interpret `angle` as " f'"0: ({angle})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) angle = f"0: ({angle})" angle_series = get_inbetweens(parse_key_frames(angle)) try: zoom_series = get_inbetweens(parse_key_frames(zoom)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `zoom` correctly for key frames.\n" "Attempting to interpret `zoom` as " f'"0: ({zoom})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) zoom = f"0: ({zoom})" zoom_series = get_inbetweens(parse_key_frames(zoom)) try: translation_x_series = get_inbetweens(parse_key_frames(translation_x)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `translation_x` correctly for key frames.\n" "Attempting to interpret `translation_x` as " f'"0: ({translation_x})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) translation_x = f"0: ({translation_x})" translation_x_series = get_inbetweens(parse_key_frames(translation_x)) try: translation_y_series = get_inbetweens(parse_key_frames(translation_y)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `translation_y` correctly for key frames.\n" "Attempting to interpret `translation_y` as " f'"0: ({translation_y})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) translation_y = f"0: ({translation_y})" translation_y_series = get_inbetweens(parse_key_frames(translation_y)) else: angle = float(angle) zoom = float(zoom) translation_x = float(translation_x) translation_y = float(translation_y) ``` ### Extra Settings Partial Saves, Diffusion Sharpening, Advanced Settings, Cutn Scheduling ``` #@markdown ####**Saving:** intermediate_saves = 150#@param{type: 'raw'} intermediates_in_subfolder = True #@param{type: 'boolean'} #@markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps #@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none. #@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets) if type(intermediate_saves) is not list: if intermediate_saves: steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1)) steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1 print(f'Will save every {steps_per_checkpoint} steps') else: steps_per_checkpoint = steps+10 else: steps_per_checkpoint = None if intermediate_saves and intermediates_in_subfolder is True: partialFolder = f'{batchFolder}/partials' createPath(partialFolder) #@markdown --- #@markdown ####**SuperRes Sharpening:** #@markdown *Sharpen each image using latent-diffusion. Does not run in animation mode. `keep_unsharp` will save both versions.* sharpen_preset = 'Fast' #@param ['Off', 'Faster', 'Fast', 'Slow', 'Very Slow'] keep_unsharp = True #@param{type: 'boolean'} if sharpen_preset != 'Off' and keep_unsharp is True: unsharpenFolder = f'{batchFolder}/unsharpened' createPath(unsharpenFolder) #@markdown --- #@markdown ####**Advanced Settings:** #@markdown *There are a few extra advanced settings available if you double click this cell.* #@markdown *Perlin init will replace your init, so uncheck if using one.* perlin_init = False #@param{type: 'boolean'} perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray'] set_seed = 'random_seed' #@param{type: 'string'} eta = 0.8#@param{type: 'number'} clamp_grad = True #@param{type: 'boolean'} clamp_max = 0.05 #@param{type: 'number'} ### EXTRA ADVANCED SETTINGS: randomize_class = True clip_denoised = False fuzzy_prompt = False rand_mag = 0.05 #@markdown --- #@markdown ####**Cutn Scheduling:** #@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000 #@markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn. cut_overview = "[12]*400+[4]*600" #@param {type: 'string'} cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'} cut_ic_pow = 1#@param {type: 'number'} cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'} ``` ###Prompts `animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one. ``` text_prompts = { 0: ["A scary painting of a man with the head of a lizard, and blood dripping from its fangs.", "red and blue color scheme"], 100: ["This set of prompts start at frame 100","This prompt has weight five:5"], } image_prompts = { # 0:['ImagePromptsWorkButArentVeryGood.png:2',], } ``` # 4. Diffuse! ``` #@title Do the Run! #@markdown `n_batches` ignored with animation modes. display_rate = 50 #@param{type: 'number'} n_batches = 1 #@param{type: 'number'} batch_size = 1 def move_files(start_num, end_num, old_folder, new_folder): for i in range(start_num, end_num): old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png' new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png' os.rename(old_file, new_file) #@markdown --- resume_run = True #@param{type: 'boolean'} run_to_resume = 'latest' #@param{type: 'string'} resume_from_frame = 'latest' #@param{type: 'string'} retain_overwritten_frames = True #@param{type: 'boolean'} if retain_overwritten_frames is True: retainFolder = f'{batchFolder}/retained' createPath(retainFolder) skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100 calc_frames_skip_steps = math.floor(steps * skip_step_ratio) if steps <= calc_frames_skip_steps: sys.exit("ERROR: You can't skip more steps than your total steps") if resume_run: if run_to_resume == 'latest': try: batchNum except: batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1 else: batchNum = int(run_to_resume) if resume_from_frame == 'latest': start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) else: start_frame = int(resume_from_frame)+1 if retain_overwritten_frames is True: existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) frames_to_save = existing_frames - start_frame print(f'Moving {frames_to_save} frames to the Retained folder') move_files(start_frame, existing_frames, batchFolder, retainFolder) else: start_frame = 0 batchNum = len(glob(batchFolder+"/*.txt")) while path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") is True or path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt") is True: batchNum += 1 print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}') if set_seed == 'random_seed': random.seed() seed = random.randint(0, 2**32) # print(f'Using seed: {seed}') else: seed = int(set_seed) args = { 'batchNum': batchNum, 'prompts_series':split_prompts(text_prompts) if text_prompts else None, 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None, 'seed': seed, 'display_rate':display_rate, 'n_batches':n_batches if animation_mode == 'None' else 1, 'batch_size':batch_size, 'batch_name': batch_name, 'steps': steps, 'width_height': width_height, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, 'range_scale': range_scale, 'sat_scale': sat_scale, 'cutn_batches': cutn_batches, 'init_image': init_image, 'init_scale': init_scale, 'skip_steps': skip_steps, 'sharpen_preset': sharpen_preset, 'keep_unsharp': keep_unsharp, 'side_x': side_x, 'side_y': side_y, 'timestep_respacing': timestep_respacing, 'diffusion_steps': diffusion_steps, 'animation_mode': animation_mode, 'video_init_path': video_init_path, 'extract_nth_frame': extract_nth_frame, 'key_frames': key_frames, 'max_frames': max_frames if animation_mode != "None" else 1, 'interp_spline': interp_spline, 'start_frame': start_frame, 'angle': angle, 'zoom': zoom, 'translation_x': translation_x, 'translation_y': translation_y, 'angle_series':angle_series, 'zoom_series':zoom_series, 'translation_x_series':translation_x_series, 'translation_y_series':translation_y_series, 'frames_scale': frames_scale, 'calc_frames_skip_steps': calc_frames_skip_steps, 'skip_step_ratio': skip_step_ratio, 'calc_frames_skip_steps': calc_frames_skip_steps, 'text_prompts': text_prompts, 'image_prompts': image_prompts, 'cut_overview': eval(cut_overview), 'cut_innercut': eval(cut_innercut), 'cut_ic_pow': cut_ic_pow, 'cut_icgray_p': eval(cut_icgray_p), 'intermediate_saves': intermediate_saves, 'intermediates_in_subfolder': intermediates_in_subfolder, 'steps_per_checkpoint': steps_per_checkpoint, 'perlin_init': perlin_init, 'perlin_mode': perlin_mode, 'set_seed': set_seed, 'eta': eta, 'clamp_grad': clamp_grad, 'clamp_max': clamp_max, 'skip_augs': skip_augs, 'randomize_class': randomize_class, 'clip_denoised': clip_denoised, 'fuzzy_prompt': fuzzy_prompt, 'rand_mag': rand_mag, } args = SimpleNamespace(**args) print('Prepping model...') model, diffusion = create_model_and_diffusion(**model_config) model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu')) model.requires_grad_(False).eval().to(device) for name, param in model.named_parameters(): if 'qkv' in name or 'norm' in name or 'proj' in name: param.requires_grad_() if model_config['use_fp16']: model.convert_to_fp16() gc.collect() torch.cuda.empty_cache() try: do_run() except KeyboardInterrupt: pass finally: print('Seed used:', seed) gc.collect() torch.cuda.empty_cache() ```
github_jupyter
``` # default_exp exec.parse_data ``` # uberduck_ml_dev.exec.parse_data Log a speech dataset to the filelist database Usage: ``` python -m uberduck_ml_dev.exec.parse_data \ --input ~/multispeaker-root \ --format standard-multispeaker \ --ouput list.txt ``` ### Supported formats: ### `standard-multispeaker` ``` root speaker1 list.txt wavs speaker2 list.txt wavs ``` ### `standard-singlespeaker` ``` root list.txt wavs ``` ### Unsupported formats (yet): ### `vctk` Format of the VCTK dataset as downloaded from the [University of Edinburgh](https://datashare.ed.ac.uk/handle/10283/3443). ``` root wav48_silence_trimmed p228 p228_166_mic1.flac ... txt p228 p228_166.txt ... ``` ``` # export import argparse import os from pathlib import Path import sqlite3 from tqdm import tqdm from uberduck_ml_dev.data.cache import ensure_speaker_table, CACHE_LOCATION from uberduck_ml_dev.data.parse import ( _cache_filelists, _write_db_to_csv, STANDARD_MULTISPEAKER, STANDARD_SINGLESPEAKER, ) FORMATS = [ STANDARD_MULTISPEAKER, STANDARD_SINGLESPEAKER, ] CACHE_LOCATION.parent.exists() # export from typing import List import sys def _parse_args(args: List[str]): parser = argparse.ArgumentParser() parser.add_argument( "-i", "--input", help="Path to input dataset file or directory", required=True ) parser.add_argument( "-f", "--format", help="Input dataset format", default=STANDARD_MULTISPEAKER ) parser.add_argument( "-n", "--name", help="Dataset name", default=STANDARD_MULTISPEAKER ) parser.add_argument( "-d", "--database", help="Output database", default=CACHE_LOCATION ) parser.add_argument("--csv_path", help="Path to save csv", default=None) return parser.parse_args(args) try: from nbdev.imports import IN_NOTEBOOK except: IN_NOTEBOOK = False if __name__ == "__main__" and not IN_NOTEBOOK: args = _parse_args(sys.argv[1:]) ensure_speaker_table(args.database) conn = sqlite3.connect(args.database) _cache_filelists( folder=args.input, fmt=args.format, conn=conn, dataset_name=args.name ) if args.csv_path is not None: _write_db_to_csv(conn, args.csv_path) # skip python -m uberduck_ml_dev.exec.parse_data -i /mnt/disks/uberduck-experiments-v0/data/eminem/ \ -f standard-singlespeaker \ -d /home/s_uberduck_ai/.cache/uberduck/uberduck-ml-exp.db \ --csv_path $UBMLEXP/filelist_list \ -n eminem # skip from tempfile import NamedTemporaryFile, TemporaryFile with NamedTemporaryFile("w") as f: _generate_filelist( str(Path("/Users/zwf/data/voice/dvc-managed/uberduck-multispeaker/").resolve()), "standard-multispeaker", f.name, ) with TemporaryFile("w") as f: _convert_to_multispeaker( f, str(Path("/Users/zwf/data/voice/dvc-managed/uberduck-multispeaker/").resolve()), "standard-multispeaker", ) ```
github_jupyter
# Amazon Fraud Detector - Data Profiler Notebook ### Dataset Guidance ------- AWS Fraud Detector's Online Fraud Insights(OFI) model supports a flexible schema, enabling you to train an OFI model to your specific data and business need. This notebook was developed to help you profile your data and identify potenital issues before you train an OFI model. The following summarizes the minimimum CSV File requirements: * The files are in CSV UTF-8 (comma delimited) format (*.csv). * The file should contain at least 10k rows and the following __four__ required fields: * Event timestamp * IP address * Email address * Fraud label * The maximum file size is 10 gigabytes (GB). * The following dates and datetime formats are supported: * Dates: YYYY-MM-DD (eg. 2019-03-21) * Datetime: YYYY-MM-DD HH:mm:ss (eg. 2019-03-21 12:01:32) * ISO 8601 Datetime: YYYY-MM-DDTHH:mm:ss+/-HH:mm (eg. 2019-03-21T20:58:41+07:00) * The decimal precision is up to four decimal places. * Numeric data should not contain commas and currency symbols. * Columns with values that could contain commas, such as address or custom text should be enclosed in double quotes. ### Getting Started with Data ------- The following general guidance is provided to get the most out of your AWS Fraud Detector Online Fraud Insights Model. * Gathering Data - The OFI model requires a minimum of 10k records. We recommend that a minimum of 6 weeks of historic data is collected, though 3 - 6 months of data is preferable. As part of the process the OFI model partitions your data based on the Event Timestamp such that performance metrics are calculated on the out of sample (latest) data, thus the format of the event timestamp is important. * Data & Label Maturity: As part of the data gathering process we want to insure that records have had sufficient time to “mature”, i.e. that enough time has passed to insure “non-fraud" and “fraud” records have been correctly identified. It often takes 30 - 45 days (or more) to correctly identify fraudulent events, because of this it is important to insure that the latest records are at least 30 days old or older. * Sampling: The OFI training process will sample and partition historic based on event timestamp. There is no need to manually sample the data and doing so may negatively influence your model’s results. * Fraud Labels: The OFI model requires that a minimum of 500 observations are identified and labeled as “fraud”. As noted above, fraud label maturity is important. Insure that extracted data has sufficiently matured to insure that fraudulent events have been reliably found. * Custom Fields: the OFI model requires 4 fields: event timestamp, IP address, email address and fraud label. The more custom fields you provide the better the OFI model can differentiate between fraud and not fraud. * Nulls and Missing Values: OFI model handles null and missing values, however the percentage of nulls in key fields should be limited. Especially timestamp and fraud label columns should not contain any missing values. If you would like to know more, please check out the [Fraud Detector's Documentation](https://docs.aws.amazon.com/frauddetector/). ``` from IPython.core.display import display, HTML from IPython.display import clear_output display(HTML("<style>.container { width:90% }</style>")) from IPython.display import IFrame # ------------------------------------------------------------------ import numpy as np import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) pd.options.display.float_format = '{:.4f}'.format # -- AWS stuff -- import boto3 ``` ### Amazon Fraud Detector Profiling ----- from github download and copy the afd_profile.py python program and template directory to your notebook <div class="alert alert-info"> <strong> afd_profile.py </strong> - afd_profile.py - is the python package which will generate your profile report. - /templates - directory contains the supporting profile templates </div> ``` # -- get this package from github -- import afd_profile ``` ### Intialize your S3 client ----- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html ``` client = boto3.client('s3') ``` ### File & Field Mapping ----- Simply map your file and field names to the required config values. <div class="alert alert-info"> <strong> Map the Required fields </strong> - input_file: this is your CSV file in your s3 bucket <b> required_features </b> are the minimally required freatures to run Amazon Fraud Detector - EVENT_TIMESTAMP: map this to your file's Date or Datetime field. - IP_ADDRESS: map this to your file's IP address field. - EMAIL_ADDRESS: map this to your file's email address field. - FRAUD_LABEL: map this to your file's fraud label field. **note: the profiler will identify the "rare" case and assume that it is fraud** </div> ``` # -- update your configuration -- config = { "input_file" : "<training dataset name>.csv", "required_features" : { "EVENT_TIMESTAMP" : "EVENT_DATE", "EVENT_LABEL" : "EVENT_LABEL", "IP_ADDRESS" : "ip_address", "EMAIL_ADDRESS" : "user_email" } } ``` #### Run Profiler ----- The profiler will read your file and produce an HTML file as a result which will be displayed inline within this notebook. Note: you can also open **report.html** in a separate browser tab. ``` # -- generate the report object -- report = afd_profile.profile_report(config) with open("report.html", "w") as file: file.write(report) IFrame(src='report.html', width=1500, height=800) ```
github_jupyter
# V0.1.6 - Simulate a Predefined Model Example created by Wilson Rocha Lacerda Junior ``` pip install sysidentpy import numpy as np import pandas as pd import matplotlib.pyplot as plt from sysidentpy.metrics import root_relative_squared_error from sysidentpy.utils.generate_data import get_miso_data, get_siso_data from sysidentpy.polynomial_basis.simulation import SimulatePolynomialNarmax ``` ## Generating 1 input 1 output sample data ### The data is generated by simulating the following model: $y_k = 0.2y_{k-1} + 0.1y_{k-1}x_{k-1} + 0.9x_{k-2} + e_{k}$ If *colored_noise* is set to True: $e_{k} = 0.8\nu_{k-1} + \nu_{k}$ where $x$ is a uniformly distributed random variable and $\nu$ is a gaussian distributed variable with $\mu=0$ and $\sigma=0.1$ In the next example we will generate a data with 1000 samples with white noise and selecting 90% of the data to train the model. ``` x_train, x_test, y_train, y_test = get_siso_data(n=1000, colored_noise=False, sigma=0.001, train_percentage=90) ``` ## Defining the model We already know that the generated data is a result of the model $𝑦_𝑘=0.2𝑦_{𝑘−1}+0.1𝑦_{𝑘−1}𝑥_{𝑘−1}+0.9𝑥_{𝑘−2}+𝑒_𝑘$ . Thus, we can create a model with those regressors follwing a codification pattern: - $0$ is the constant term, - $[1001] = y_{k-1}$ - $[100n] = y_{k-n}$ - $[200n] = x1_{k-n}$ - $[300n] = x2_{k-n}$ - $[1011, 1001] = y_{k-11} \times y_{k-1}$ - $[100n, 100m] = y_{k-n} \times y_{k-m}$ - $[12001, 1003, 1001] = x11_{k-1} \times y_{k-3} \times y_{k-1}$ - and so on ### Importante Note The order of the arrays matter. If you use [2001, 1001], it will work, but [1001, 2001] will not (the regressor will be ignored). Always put the highest value first: - $[2003, 2001]$ **works** - $[2001, 2003]$ **do not work** We will handle this limitation in upcoming update. ``` s = SimulatePolynomialNarmax() # the model must be a numpy array model = np.array( [ [1001, 0], # y(k-1) [2001, 1001], # x1(k-1)y(k-1) [2002, 0], # x1(k-2) ] ) # theta must be a numpy array of shape (n, 1) where n is the number of regressors theta = np.array([[0.2, 0.9, 0.1]]).T ``` ## Simulating the model After defining the model and theta we just need to use the simulate method. The simulate method returns the predicted values and the results where we can look at regressors, parameters and ERR values. ``` yhat, results = s.simulate( X_test=x_test, y_test=y_test, model_code=model, theta=theta, plot=True) results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR']) results ``` ### Options You can set the `steps_ahead` to run the prediction/simulation: ``` yhat, results = s.simulate( X_test=x_test, y_test=y_test, model_code=model, theta=theta, plot=False, steps_ahead=1) rrse = root_relative_squared_error(y_test, yhat) rrse yhat, results = s.simulate( X_test=x_test, y_test=y_test, model_code=model, theta=theta, plot=False, steps_ahead=21) rrse = root_relative_squared_error(y_test, yhat) rrse ``` ### Estimating the parameters If you have only the model strucuture, you can create an object with `estimate_parameter=True` and choose the methed for estimation using `estimator`. In this case, you have to pass the training data for parameters estimation. When `estimate_parameter=True`, we also computate the ERR considering only the regressors defined by the user. ``` s2 = SimulatePolynomialNarmax(estimate_parameter=True, estimator='recursive_least_squares') yhat, results = s2.simulate( X_train=x_train, y_train=y_train, X_test=x_test, y_test=y_test, model_code=model, # theta will be estimated using the defined estimator plot=True) results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR']) results yhat, results = s2.simulate( X_train=x_train, y_train=y_train, X_test=x_test, y_test=y_test, model_code=model, # theta will be estimated using the defined estimator plot=True, steps_ahead=8) results = pd.DataFrame(results, columns=['Regressors', 'Parameters', 'ERR']) results yhat, results = s2.simulate( X_train=x_train, y_train=y_train, X_test=x_test, y_test=y_test, model_code=model, # theta will be estimated using the defined estimator plot=True, steps_ahead=8) ```
github_jupyter
# Segmentation <div class="alert alert-info"> This tutorial is available as an IPython notebook at [Malaya/example/segmentation](https://github.com/huseinzol05/Malaya/tree/master/example/segmentation). </div> <div class="alert alert-info"> This module trained on both standard and local (included social media) language structures, so it is save to use for both. </div> ``` %%time import malaya ``` Common problem for social media texts, there are missing spaces in the text, so text segmentation can help you, 1. huseinsukamakan ayam,dia sgtrisaukan -> husein suka makan ayam, dia sgt risaukan. 2. drmahathir sangat menekankan budaya budakzamansekarang -> dr mahathir sangat menekankan budaya budak zaman sekarang. 3. ceritatunnajibrazak -> cerita tun najib razak. 4. TunM sukakan -> Tun M sukakan. Segmentation only, 1. Solve spacing error. 3. Not correcting any grammar. ``` string1 = 'huseinsukamakan ayam,dia sgtrisaukan' string2 = 'drmahathir sangat menekankan budaya budakzamansekarang' string3 = 'ceritatunnajibrazak' string4 = 'TunM sukakan' string_hard = 'IPOH-AhliDewanUndangan Negeri(ADUN) HuluKinta, MuhamadArafat Varisai Mahamadmenafikanmesejtularmendakwa beliau akan melompatparti menyokong UMNO membentuk kerajaannegeridiPerak.BeliauyangjugaKetua Penerangan Parti Keadilan Rakyat(PKR)Perak dalam satumesejringkaskepadaSinar Harian menjelaskan perkara itutidakbenarsama sekali.' string_socialmedia = 'aqxsukalah apeyg tejadidekat mamattu' ``` ### Viterbi algorithm Commonly people use Viterbi algorithm to solve this problem, we also added viterbi using ngram from bahasa papers and wikipedia. ```python def viterbi(max_split_length: int = 20, **kwargs): """ Load Segmenter class using viterbi algorithm. Parameters ---------- max_split_length: int, (default=20) max length of words in a sentence to segment validate: bool, optional (default=True) if True, malaya will check model availability and download if not available. Returns ------- result : malaya.segmentation.SEGMENTER class """ ``` ``` viterbi = malaya.segmentation.viterbi() ``` #### Segmentize ```python def segment(self, strings: List[str]): """ Segment strings. Example, "sayasygkan negarasaya" -> "saya sygkan negara saya" Parameters ---------- strings : List[str] Returns ------- result: List[str] """ ``` ``` %%time viterbi.segment([string1, string2, string3, string4]) %%time viterbi.segment([string_hard, string_socialmedia]) ``` ### List available Transformer model ``` malaya.segmentation.available_transformer() ``` ### Load Transformer model ```python def transformer(model: str = 'small', quantized: bool = False, **kwargs): """ Load transformer encoder-decoder model to Segmentize. Parameters ---------- model : str, optional (default='base') Model architecture supported. Allowed values: * ``'small'`` - Transformer SMALL parameters. * ``'base'`` - Transformer BASE parameters. 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.model.tf.Segmentation class """ ``` ``` model = malaya.segmentation.transformer(model = 'small') quantized_model = malaya.segmentation.transformer(model = 'small', quantized = True) model_base = malaya.segmentation.transformer(model = 'base') quantized_model_base = malaya.segmentation.transformer(model = 'base', quantized = True) ``` #### Predict using greedy decoder ```python def greedy_decoder(self, strings: List[str]): """ Segment strings using greedy decoder. Example, "sayasygkan negarasaya" -> "saya sygkan negara saya" Parameters ---------- strings : List[str] Returns ------- result: List[str] """ ``` ``` %%time model.greedy_decoder([string1, string2, string3, string4]) %%time quantized_model.greedy_decoder([string1, string2, string3, string4]) %%time model_base.greedy_decoder([string1, string2, string3, string4]) %%time quantized_model_base.greedy_decoder([string1, string2, string3, string4]) %%time model.greedy_decoder([string_hard, string_socialmedia]) %%time quantized_model.greedy_decoder([string_hard, string_socialmedia]) %%time model_base.greedy_decoder([string_hard, string_socialmedia]) %%time quantized_model_base.greedy_decoder([string_hard, string_socialmedia]) ``` **Problem with batching string, short string might repeating itself, so to solve this, you need to give a single string only**, ``` %%time quantized_model_base.greedy_decoder([string_socialmedia]) %%time quantized_model_base.greedy_decoder([string3]) %%time quantized_model_base.greedy_decoder([string4]) ``` #### Predict using beam decoder ```python def beam_decoder(self, strings: List[str]): """ Segment strings using beam decoder, beam width size 3, alpha 0.5 . Example, "sayasygkan negarasaya" -> "saya sygkan negara saya" Parameters ---------- strings : List[str] Returns ------- result: List[str] """ ``` ``` %%time quantized_model.beam_decoder([string_socialmedia]) %%time quantized_model_base.beam_decoder([string_socialmedia]) ``` **We can expect beam decoder is much more slower than greedy decoder**.
github_jupyter
``` import pandas as pd from sklearn.model_selection import train_test_split df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/' 'mushroom/agaricus-lepiota.data', header=None, engine='python') column_name = ['classes','cap-shape', 'cap-surface','cap-color','bruises?','odor', 'gill-attachment','gill-spacing','gill-size','gill-color', 'stalk-shape','stalk-root','stalk-surface-above-ring', 'stalk-surface-below-ring','stalk-color-above-ring', 'stalk-color-below-ring','veil-type','veil-color','ring-number', 'ring-type','spore-print-color','population','habitat'] df.columns = column_name df.head() import numpy as np from sklearn.preprocessing import LabelEncoder # Todo # deal missing value denoted by '?' # encode label first label_le = LabelEncoder() df['classes'] = label_le.fit_transform(df['classes'].values) catego_le = LabelEncoder() num_values = [] for i in column_name[1:]: df[i] = catego_le.fit_transform(df[i].values) classes_list = catego_le.classes_.tolist() # store the total number of values num_values.append(len(classes_list)) # replace '?' with 'NaN' if '?' in classes_list: idx = classes_list.index('?') df[i] = df[i].replace(idx, np.nan) from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.metrics import accuracy_score X = df.drop('classes', axis=1).values y = df['classes'].values X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=0) catego_features_idx = [] for fea in column_name[1:]: catego_features_idx.append(df.columns.tolist().index(fea)) # define pipeline with an arbitrary number of transformer in a tuple array pipe_knn = Pipeline([('imr', Imputer(missing_values='NaN', strategy='most_frequent', axis=0)), ('ohe', OneHotEncoder(n_values=num_values, sparse=False)), ('scl', StandardScaler()), ('clf', KNeighborsClassifier(n_neighbors=10, p=2, metric='minkowski'))]) pipe_svm = Pipeline([('imr', Imputer(missing_values='NaN', strategy='most_frequent', axis=0)), ('ohe', OneHotEncoder(n_values=num_values, sparse=False)), ('scl', StandardScaler()), ('clf', SVC(kernel='rbf', random_state=0, gamma=0.001, C=100.0))]) # use the pipeline model to train pipe_knn.fit(X_train, y_train) y_pred = pipe_knn.predict(X_test) print('[KNN]') print('Misclassified samples: %d' % (y_test != y_pred).sum()) print('Accuracy: %.4f' % accuracy_score(y_test, y_pred)) pipe_svm.fit(X_train, y_train) y_pred = pipe_svm.predict(X_test) print('\n[SVC]') print('Misclassified samples: %d' % (y_test != y_pred).sum()) print('Accuracy: %.4f' % accuracy_score(y_test, y_pred)) ``` ### Report ### In this homework, I tried two different models using the sklearn pipeline. For the preprocessing part, I used imputer to impute the missing data, and one-hot encoding for category features. And then I use KNN classifier for the first model, SVC for the second model. They both perform quite well, so I thought there's no need to do additional feature selection.
github_jupyter
# python behaves like a calculator ``` 8*8 ``` #### Predict the following output ``` print((5+5)/25) print(5 + 5/25) ``` python does order of operations, etc. just like a calculator #### Most of the notation is intuitive. Write out the following in a cell. What value to you get? $$ (5 \times 5 + \frac{4}{2} - 8)^{2}$$ Most notation is intuitive. Only weirdo is that "raise x to the power of y" is given by `x**y` rather than `x^y`. What is the value of $sin(2)$? ``` sin(2) ``` Python gives very informative errors (if you know how to read them). What do you think `NameError` means? `NameError` means that the current python "interpreter" does know what `sin` means To get access to more math, you need `import math` ``` import math math.sin(2) ``` Once you have math imported, you have access to a whole slew of math functions. ``` print(math.factorial(10)) print(math.sqrt(10)) print(math.sin(math.pi)) print(math.cos(10)) print(math.exp(10)) print(math.log(10)) print(math.log10(10)) ``` If you want to see what the `math` module has to offer, type `math.` and then hit `TAB`. <img src="python-as-a-calculator/math-dropdown.png" /> ``` # for example math. ``` You can also get information about a function by typing `help(FUNCTION)`. If you run the next cell, it will give you information about the `math.factorial` function. ``` help(math.factorial) ``` ### Variables #### Predict what will happen. ``` x = 5 print(x) x = 5 x = x + 2 print(x) ``` In python "`=`" means "assign the stuff on the right into the stuff on the left." #### Predict what will happen. ``` x = 7 5*5 = x print(x) ``` What happened? `SyntaxError` is something python can't interpret. In python, `=` means store the output of the stuff on the **right** in the variable on the **left**. It's nonsensical to try to store anything in `5*5`, so the command fails. #### Predict what will happen. ``` this_is_a_variable = 5 another_variable = 2 print(this_is_a_variable*another_variable) ``` Variables can (and **should**) have descriptive names. #### Implement Stirling's approximation says that you can approximate $n!$ using some nifty log tricks. $$ ln(n!) \approx nln(n) - n + 1 $$ Write code to check this approximation for **any** value of $n$. ## Summary + Python behaves like a calculator (order of operations, etc.). + You can assign the results of calculations to variables using "`=`" + Python does the stuff on the right first, then assigns it to the name on the left. + You can access more math by `import math`
github_jupyter
``` try: from openmdao.utils.notebook_utils import notebook_mode except ImportError: !python -m pip install openmdao[notebooks] ``` # How to know if a System is under FD or CS All Systems (Components and Groups) have two flags that indicate whether the System is running under finite difference or complex step. The `under_finite_difference` flag is True if the System is being finite differenced and the `under_complex_step` flag is True if the System is being complex stepped. ## Usage First we'll show how to detect when a component is being finite differenced: ``` import numpy as np import openmdao.api as om class MyFDPartialComp(om.ExplicitComponent): def setup(self): self.num_fd_computes = 0 self.add_input('x') self.add_output('y') def setup_partials(self): self.declare_partials('y', 'x', method='fd') def compute(self, inputs, outputs): outputs['y'] = 1.5 * inputs['x'] if self.under_finite_difference: self.num_fd_computes += 1 print(f"{self.pathname} is being finite differenced!") p = om.Problem() p.model.add_subsystem('comp', MyFDPartialComp()) p.setup() p.run_model() # there shouldn't be any finite difference computes yet print("Num fd calls = ", p.model.comp.num_fd_computes) totals = p.compute_totals(['comp.y'], ['comp.x']) # since we're doing forward difference, there should be 1 call to compute under fd print("Num fd calls =", p.model.comp.num_fd_computes) assert p.model.comp.num_fd_computes == 1 ``` Now we'll do the same thing for a complex stepped component: ``` import numpy as np import openmdao.api as om class MyCSPartialComp(om.ExplicitComponent): def setup(self): self.num_cs_computes = 0 self.add_input('x') self.add_output('y') def setup_partials(self): self.declare_partials('y', 'x', method='cs') def compute(self, inputs, outputs): outputs['y'] = 1.5 * inputs['x'] if self.under_complex_step: self.num_cs_computes += 1 print(f"{self.pathname} is being complex stepped!") p = om.Problem() p.model.add_subsystem('comp', MyCSPartialComp()) p.setup() p.run_model() # there shouldn't be any complex step computes yet print("Num cs calls =", p.model.comp.num_cs_computes) totals = p.compute_totals(['comp.y'], ['comp.x']) # there should be 1 call to compute under cs print("Num cs calls =", p.model.comp.num_cs_computes) assert p.model.comp.num_cs_computes == 1 ```
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import descartes import geopandas as gpd from shapely.geometry import Point, Polygon from shapely.ops import nearest_points import seaborn as sns from mpl_toolkits.axes_grid1 import make_axes_locatable import math import time from matplotlib import cm import matplotlib.lines as mlines %matplotlib inline ``` ### AIR POLLUTION MONITORING DATA FROM EDF ``` df = pd.read_csv('EDF_Data.csv', header = 1) df['TimePeriod'] = 'Jun2015-May2016' df.tail() df.shape geometry = [Point(xy) for xy in zip(df['Longitude'], df['Latitude'])] ``` ### Split the dataset into BC and NO2 since we are interested only in those two pollutants ``` BC_df = df[['Longitude', 'Latitude', 'BC Value', 'TimePeriod']] NO2_df = df[['Longitude', 'Latitude', 'NO2 Value', 'TimePeriod']] crs = {'init': 'epsg:4326'} geo_df = gpd.GeoDataFrame(df, crs = crs, geometry = geometry) ``` ## TRAFFIC DATA ``` ### Load Annual Average Daily Traffic (AADT) file from Caltrans traffic = pd.read_csv('Data/Traffic_Oakland_AADT.csv', header = 0) # Drop columns that are unneccessary and choose only Ahead_AADT, along with N/E latitude and longitude traffic.drop(columns = ['OBJECTID','District','Route','County', 'Postmile', 'Back_pk_h', 'Back_pk_m', 'Ahead_pk_h', 'Ahead_pk_m','Back_AADT','Lat_S_or_W', 'Lon_S_or_W'], inplace=True) traffic.rename(columns={"Ahead_AADT":"AADT", "Lat_N_or_E":"Latitude", "Lon_N_or_E":"Longitude", "Descriptn":"Description"}, inplace=True) traffic.head() # Taking a closer look at the traffic data, there are some intersections where the AADT is zero, or the latitude and longitude are zero. We want to drop these rows traffic = traffic[(traffic['Longitude']<-1) & (traffic['AADT']>1)] traffic.shape ``` ## Converting facility and traffic dataframe into a geopandas dataframe for plotting ``` # Create a geopandas dataframe with traffic data geometry_traffic = [Point(xy) for xy in zip(traffic['Longitude'], traffic['Latitude'])] geo_df_traffic = gpd.GeoDataFrame(traffic, crs = crs, geometry = geometry_traffic) # Create a list of x and y coordinates for the Black Carbon concentration data using geopandas geometry_df_BC = [Point(xy) for xy in zip(BC_df['Longitude'], BC_df['Latitude'])] geo_df_BC = gpd.GeoDataFrame(BC_df, crs = crs, geometry = geometry_df_BC) ``` ### Calculate distance between point of measurement and each facility and add it to the _dist column ``` ### Defining a function to calculate the distance between two GPS coordinates (latitude and longitude) def distance(origin, destination): lat1, lon1 = origin lat2, lon2 = destination radius = 6371 # km dlat = math.radians(lat2-lat1) dlon = math.radians(lon2-lon1) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \ * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d ``` #### Loading Traffic Data ``` traffic.head() ## Assign an intersection number to each traffic intersection instead of using description traffic.reset_index(inplace=True) #Rename index as Intersection traffic.rename(columns={"index":"Intersection"}, inplace=True) #Drop the description column traffic.drop(columns=['Description'], inplace=True) ### Add an empty column for distance traffic['dist'] = 0 traffic['dist'].astype(float) traffic_lat = traffic[['Intersection', 'Latitude']].T traffic_long = traffic[['Intersection', 'Longitude']].T traffic_AADT = traffic[['Intersection', 'AADT']].T traffic_dist = traffic[['Intersection', 'dist']].T traffic_geo = traffic[['Intersection', 'geometry']].T traffic_lat.head() ## Make the header as the first row in each transposed dataframe traffic_lat = traffic_lat.rename(columns=traffic_lat.iloc[0].astype(int)).drop(traffic_lat.index[0]) traffic_long = traffic_long.rename(columns=traffic_long.iloc[0].astype(int)).drop(traffic_long.index[0]) traffic_AADT = traffic_AADT.rename(columns=traffic_AADT.iloc[0].astype(int)).drop(traffic_AADT.index[0]) traffic_dist = traffic_dist.rename(columns=traffic_dist.iloc[0].astype(int)).drop(traffic_dist.index[0]) traffic_geo = traffic_geo.rename(columns=traffic_geo.iloc[0].astype(int)).drop(traffic_geo.index[0]) ## Add suffix to column header based on the dataframe type traffic_lat.columns = [str(col) + '_latitude' for col in traffic_lat.columns] traffic_long.columns = [str(col) + '_longitude' for col in traffic_long.columns] traffic_AADT.columns = [str(col) + '_AADT' for col in traffic_AADT.columns] traffic_dist.columns = [str(col) + '_traf_dist' for col in traffic_dist.columns] traffic_geo.columns = [str(col) + '_geo' for col in traffic_geo.columns] ## Remove index for each dataframe traffic_lat.reset_index(drop=True, inplace=True) traffic_long.reset_index(drop=True, inplace=True) traffic_AADT.reset_index(drop=True, inplace=True) traffic_dist.reset_index(drop=True, inplace=True) traffic_geo.reset_index(drop=True, inplace=True) traffic_combined = traffic_lat.join(traffic_long).join(traffic_AADT).join(traffic_dist).join(traffic_geo) traffic_combined traffic_combined = traffic_combined.reindex(columns=sorted(traffic_combined.columns)) #Create a datafram where each row contains emissions of PM10 and PM2.5 for each facility traffic_combined = traffic_combined.loc[traffic_combined.index.repeat(21488)].reset_index(drop=True) BC_Traffic = BC_df.join(traffic_combined) BC_Traffic.head() # Convert distance column to float type for idx, col in enumerate(BC_Traffic.columns): if "_traf_dist" in col: BC_Traffic[col] = pd.to_numeric(BC_Traffic[col], downcast="float") ``` #### Calculate distance between each traffic intersection and point of measurement and store this in the _dist column ``` for index, row in BC_Traffic.iterrows(): for idx, col in enumerate(BC_Traffic.columns): if "_traf_dist" in col: BC_Traffic.at[index,col] = float(distance((row.iloc[1], row.iloc[0]), (row.iloc[idx-2], row.iloc[idx-1])))*0.621 #BC_Facility_Traffic.at[index,col] = float(row.iloc[idx]) BC_Traffic.head() #### Write this to a dataframe BC_Traffic.to_csv("Data/BC_Traffic_ALL.csv") ``` #### Similar to the facility dataframe, drop latitude and longitude since its captured in the distance column. Also drop AADT ``` BC_Traffic.drop(list(BC_Traffic.filter(regex = '_latitude')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = '_longitude')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = '_AADT')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = '_geo')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = 'Longitude')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = 'Latitude')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = 'TimePeriod')), axis = 1, inplace = True) BC_Traffic.drop(list(BC_Traffic.filter(regex = 'geometry')), axis = 1, inplace = True) BC_Traffic.head() corr = BC_Traffic.corr() arr_corr = corr.as_matrix() arr_corr[0] ``` #### Plotting correlation between all features as a heatmap - but this visualization is not easy to follow.... fig, ax = plt.subplots(figsize=(100, 100)) ax = sns.heatmap( corr, vmin=-1, vmax=1, center=0, cmap=sns.diverging_palette(20, 220, n=500), square=False ) ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right' ); plt.show() ``` print(plt.get_backend()) # close any existing plots plt.close("all") # mask out the top triangle arr_corr[np.triu_indices_from(arr_corr)] = np.nan fig, ax = plt.subplots(figsize=(50, 50)) hm = sns.heatmap(arr_corr, cbar=True, vmin = -1, vmax = 1, center = 0, fmt='.2f', annot_kws={'size': 8}, annot=True, square=False, cmap = 'coolwarm') #cmap=plt.cm.Blues ticks = np.arange(corr.shape[0]) + 0.5 ax.set_xticks(ticks) ax.set_xticklabels(corr.columns, rotation=90, fontsize=8) ax.set_yticks(ticks) ax.set_yticklabels(corr.index, rotation=360, fontsize=8) ax.set_title('correlation matrix') plt.tight_layout() #plt.savefig("corr_matrix_incl_anno_double.png", dpi=300) ``` #### Once again there doesn't seem to be much correlation between BC concentrations and the closest major traffic intersection. Next option is to identify all the traffic intersections in the area. import chart_studio.plotly as py import plotly.graph_objs as go import chart_studio chart_studio.tools.set_credentials_file(username='varsha2509', api_key='QLfBsWWLPKoLjY5hW0Fu') heatmap = go.Heatmap(z=arr_corr, x=BC_Facility_Traffic_Met.columns, y=BC_Facility_Traffic_Met.index) data = [heatmap] py.iplot(data, filename='basic-heatmap')
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" href="https://nbviewer.jupyter.org/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=26px src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Jupyter_logo.svg/883px-Jupyter_logo.svg.png" />Notebook Viewer</a></td> <td><a target="_blank" href="https://mybinder.org/v2/gh/giswqs/earthengine-py-notebooks/master?filepath=Datasets/Vectors/world_database_on_protected_areas.ipynb"><img width=58px src="https://mybinder.org/static/images/logo_social.png" />Run in binder</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/giswqs/earthengine-py-notebooks/blob/master/Datasets/Vectors/world_database_on_protected_areas.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> Run in Google Colab</a></td> </table> ## Install Earth Engine API Install the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](https://github.com/python-visualization/folium) package and implements several methods for displaying Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, `Map.centerObject()`, and `Map.setOptions()`. The magic command `%%capture` can be used to hide output from a specific cell. Uncomment these lines if you are running this notebook for the first time. ``` # %%capture # !pip install earthengine-api # !pip install geehydro ``` Import libraries ``` import ee import folium import geehydro ``` Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for the first time or if you are getting an authentication error. ``` # ee.Authenticate() ee.Initialize() ``` ## Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`. ``` Map = folium.Map(location=[40, -100], zoom_start=4) Map.setOptions('HYBRID') ``` ## Add Earth Engine Python script ``` dataset = ee.FeatureCollection('WCMC/WDPA/current/polygons') visParams = { 'palette': ['2ed033', '5aff05', '67b9ff', '5844ff', '0a7618', '2c05ff'], 'min': 0.0, 'max': 1550000.0, 'opacity': 0.8, } image = ee.Image().float().paint(dataset, 'REP_AREA') Map.setCenter(41.104, -17.724, 6) Map.addLayer(image, visParams, 'WCMC/WDPA/current/polygons') # Map.addLayer(dataset, {}, 'for Inspector', False) dataset = ee.FeatureCollection('WCMC/WDPA/current/points') styleParams = { 'color': '#4285F4', 'width': 1, } protectedAreaPoints = dataset.style(**styleParams) # Map.setCenter(110.57, 0.88, 4) Map.addLayer(protectedAreaPoints, {}, 'WCMC/WDPA/current/points') ``` ## Display Earth Engine data layers ``` Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True) Map ```
github_jupyter
<table><tr> <td><img src="logos/JPL-NASA-logo_583x110.png" alt="JPL/NASA logo" style="height: 75px"/></td> <td><img src="logos/CEOS-LOGO.png" alt="CEOS logo" style="height: 75px"/></td> <td><img src="logos/CoverageLogoFullClear.png" alt="COVERAGE logo" style="height: 100px"/></td> </tr></table> # _Analytics Examples for COVERAGE_ # Important Notes When you first connected you should have seen two notebook folders, `coverage` and `work`. The original version of this notebook is in the `coverage` folder and is read-only. If you would like to modify the code samples in this notebook, please first click `File`->`Save as...` to save your own copy in the `work` folder instead, and make your modifications to that copy. We don't yet have resources in place to support a true multi-user environment for notebooks. This means that all saved notebooks are visible to all users. Thus, it would help to include your own unique identifier in the notebook name to avoid conflicts with others. Furthermore, we do not guarantee to preserve the saved notebooks for any period of time. If you would like to keep your notebook, please remember to click `File`->`Download as`->`Notebook (.ipynb)` to download your own copy of the notebook at the end of each editting session. # Notebook Setup In the cell below are a few functions that help with plotting data using matplotlib. You shouldn't need to modify or pay much attention to this cell. Just run the cell to define the functions so that they can be used in the rest of the notebook. ``` %matplotlib inline ####################################################################################### # In some jupyter deployments you will get an error about PROJ_LIB not being defined. # In that case, uncomment these lines and set the directory to the location of your # proj folder. # import os # import sys # # Find where we are on the computer and make sure it is the pyICM directory # HomeDir = os.path.expanduser('~') # get the home directory # ICMDir = HomeDir + "Desktop/AIST_Project/SDAP_Jupyter" # # Navigate to the home directory # os.chdir(ICMDir) # print('Moved to Directory',ICMDir) # module_path = os.path.join(ICMDir,'code') # print('Code Directory is',module_path) # print('Adding to the system path') # if module_path not in sys.path: # sys.path.append(module_path) ####################################################################################### import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.colors as mcolors import matplotlib.ticker as mticker # from mpl_toolkits.basemap import Basemap import cartopy.crs as ccrs #added by B Clark because Basemap is deprecated from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import numpy as np import types import math import sys import time import requests from datetime import datetime import itertools from shapely.geometry import box from pprint import pprint, pformat import textwrap import warnings warnings.filterwarnings("ignore") # ISO-8601 date format dt_format = "%Y-%m-%dT%H:%M:%SZ" def show_plot(x_data, y_data, x_label=None, y_label=None, title=None): """ Display a simple line plot. :param x_data: Numpy array containing data for the X axis :param y_data: Numpy array containing data for the Y axis :param x_label: Label applied to X axis :param y_label: Label applied to Y axis """ plt.figure(figsize=(6,3), dpi=100) plt.plot([datetime.fromtimestamp(x_val) for x_val in x_data], y_data, 'b-', marker='|', markersize=2.0, mfc='b') plt.grid(b=True, which='major', color='k', linestyle='-') if title is not None: plt.title(title) if x_label is not None: plt.xlabel(x_label) if y_label is not None: plt.ylabel (y_label) plt.xticks(rotation=45) ts_range = x_data[-1] - x_data[0] # Define the time formatting if ts_range > 189216000: # 6 years dtFmt = mdates.DateFormatter('%Y') elif ts_range > 15552000: # 6 months dtFmt = mdates.DateFormatter('%b %Y') else: # < 6 months dtFmt = mdates.DateFormatter('%b %-d, %Y') plt.gca().xaxis.set_major_formatter(dtFmt) plt.show() def plot_box(bbox): """ Display a Green bounding box on an image of the blue marble. :param bbox: Shapely Polygon that defines the bounding box to display """ min_lon, min_lat, max_lon, max_lat = bbox.bounds import matplotlib.pyplot as plt1 import cartopy.crs as ccrs #added by B Clark because Basemap is deprecated # modified 11/30/2021 to use Cartopy toolbox B Clark NASA GSFC # from matplotlib.patches import Polygon # from mpl_toolkits.basemap import Basemap from shapely.geometry.polygon import Polygon # map = Basemap() # map.bluemarble(scale=0.5) # poly = Polygon([(min_lon,min_lat),(min_lon,max_lat),(max_lon,max_lat),(max_lon,min_lat)], # facecolor=(0,0,0,0.0),edgecolor='green',linewidth=2) # plt1.gca().add_patch(poly) # plt1.gcf().set_size_inches(10,15) ax = plt1.axes(projection=ccrs.PlateCarree()) ax.stock_img() # plt.show() poly = Polygon(((min_lon,min_lat),(min_lon,max_lat),(max_lon,max_lat),(max_lon,min_lat),(min_lon,min_lat))) ax.add_geometries([poly],crs=ccrs.PlateCarree(),facecolor='b', edgecolor='red', alpha=0.8) # ax.fill(x, y, color='coral', alpha=0.4) # plt1.gca().add_patch(poly) # plt1.gcf().set_size_inches(10,15) plt1.show() def show_plot_two_series(x_data_a, x_data_b, y_data_a, y_data_b, x_label, y_label_a, y_label_b, series_a_label, series_b_label, title=''): """ Display a line plot of two series :param x_data_a: Numpy array containing data for the Series A X axis :param x_data_b: Numpy array containing data for the Series B X axis :param y_data_a: Numpy array containing data for the Series A Y axis :param y_data_b: Numpy array containing data for the Series B Y axis :param x_label: Label applied to X axis :param y_label_a: Label applied to Y axis for Series A :param y_label_b: Label applied to Y axis for Series B :param series_a_label: Name of Series A :param series_b_label: Name of Series B """ font_size=12 plt.rc('font', size=font_size) # controls default text sizes plt.rc('axes', titlesize=font_size) # fontsize of the axes title plt.rc('axes', labelsize=font_size) # fontsize of the x and y labels plt.rc('xtick', labelsize=font_size) # fontsize of the tick labels plt.rc('ytick', labelsize=font_size) # fontsize of the tick labels plt.rc('legend', fontsize=font_size) # legend fontsize plt.rc('figure', titlesize=font_size) # fontsize of the figure title fig, ax1 = plt.subplots(figsize=(10,5), dpi=100) series_a, = ax1.plot(x_data_a, y_data_a, 'b-', marker='|', markersize=2.0, mfc='b', label=series_a_label) ax1.set_ylabel(y_label_a, color='b') ax1.tick_params('y', colors='b') ax1.set_ylim(min(0, *y_data_a), max(y_data_a)+.1*max(y_data_a)) ax1.set_xlabel(x_label) ax2 = ax1.twinx() series_b, = ax2.plot(x_data_b, y_data_b, 'r-', marker='|', markersize=2.0, mfc='r', label=series_b_label) ax2.set_ylabel(y_label_b, color='r') ax2.set_ylim(min(0, *y_data_b), max(y_data_b)+.1*max(y_data_b)) ax2.tick_params('y', colors='r') plt.grid(b=True, which='major', color='k', linestyle='-') plt.legend(handles=(series_a, series_b), bbox_to_anchor=(1.1, 1), loc=2, borderaxespad=0.) plt.title(title) plt.show() def ts_plot_two(ts_json1, ts_json2, dataset1, dataset2, units1, units2, title='', t_name='time', val_name='mean'): t1 = np.array([ts[0][t_name] for ts in ts_json1["data"]]) t2 = np.array([ts[0][t_name] for ts in ts_json2["data"]]) vals1 = np.array([ts[0][val_name] for ts in ts_json1["data"]]) vals2 = np.array([ts[0][val_name] for ts in ts_json2["data"]]) show_plot_two_series(t1, t2, vals1, vals2, "time (sec since 1970-01-01T00:00:00)", units1, units2, dataset1, dataset2, title=title) def scatter_plot(ts_json1, ts_json2, t_name="time", val_name="mean", title="", xlabel="", ylabel=""): times1 = np.array([ts[0][t_name] for ts in ts_json1["data"]]) times2 = np.array([ts[0][t_name] for ts in ts_json2["data"]]) vals1 = np.array([ts[0][val_name] for ts in ts_json1["data"]]) vals2 = np.array([ts[0][val_name] for ts in ts_json2["data"]]) vals_x = [] vals_y = [] for i1,t1 in enumerate(times1): i = (np.abs(times2-times1[i1])).argmin() if np.abs(times1[i1]-times2[i]) < 86400: # 24 hrs vals_x.append(vals1[i1]) vals_y.append(vals2[i]) plt.scatter(vals_x, vals_y) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.show() def roundBorders(borders, borderSlop=10.): b0 = roundBorder(borders[0], 'down', borderSlop, 0.) b1 = roundBorder(borders[1], 'down', borderSlop, -90.) b2 = roundBorder(borders[2], 'up', borderSlop, 360.) b3 = roundBorder(borders[3], 'up', borderSlop, 90.) return [b0, b1, b2, b3] def roundBorder(val, direction, step, end): if direction == 'up': rounder = math.ceil slop = step else: rounder = math.floor slop = -step ### v = rounder(val/step) * step + slop v = rounder(val/step) * step if abs(v - end) < step+1.: v = end return v def normalizeLon(lon): if lon < 0.: return lon + 360. if lon > 360.: return lon - 360. return lon def normalizeLons(lons): return np.array([normalizeLon(lon) for lon in lons]) def ensureItems(d1, d2): for key in d2.keys(): if key not in d1: d1[key] = d2[key] CmdOptions = {'MCommand': ['title', 'xlabel', 'ylabel', 'xlim', 'ylim', 'show\ '], 'plot': ['label', 'linewidth', 'legend', 'axis'], 'map.plot': ['label', 'linewidth', 'axis'], 'map.scatter': ['norm', 'alpha', 'linewidths', 'faceted', 'hold'\ ], 'savefig': ['dpi', 'orientation'] } def die(*s): warn('Error,', *s); sys.exit() def evalKeywordCmds(options, cmdOptions=CmdOptions): for option in options: if option in cmdOptions['MCommand']: args = options[option] if args: if args is True: args = '' else: args = "'" + args + "'" if option in cmdOptions: args += dict2kwargs( validCmdOptions(options, cmdOptions[option]) ) try: eval('plt.' + option + '(%s)' % args) except: die('failed eval of keyword command option failed: %s=%s' % (option, args)) def validCmdOptions(options, cmd, possibleOptions=CmdOptions): return dict([(option, options[option]) for option in options.keys() if option in possibleOptions[cmd]]) def dict2kwargs(d): args = [',%s=%s' % (kw, d[kw]) for kw in d] return ', '.join(args) def imageMap(lons, lats, vals, vmin=None, vmax=None, imageWidth=None, imageHeight=None, outFile=None, projection='cyl', cmap=plt.cm.jet, logColors=False, makeFigure=False, borders=[0., -90., 360., 90.], autoBorders=True, borderSlop=10., meridians=[0, 360, 60], parallels=[-60, 90, 30], title='', normalizeLongs=True, **options): if normalizeLongs: lons = normalizeLons(lons) if vmin == 'auto': vmin = None if vmax == 'auto': vmax = None if imageWidth is not None: makeFigure = True if projection is None or projection == '': projection = 'cyl' if cmap is None or cmap == '': cmap = plt.cm.jet #if isinstance(cmap, types.StringType) and cmap != '': if isinstance(cmap, str) and cmap != '': try: cmap = eval('plt.cm.' + cmap) except: cmap = plt.cm.jet ensureItems(options, { \ 'title': title, 'dpi': 100, 'imageWidth': imageWidth or 1024, 'imageHeight': imageHeight or 768}) if autoBorders: borders = [min(lons), min(lats), max(lons), max(lats)] borders = roundBorders(borders, borderSlop) #m = Basemap(borders[0], borders[1], borders[2], borders[3], \ # projection=projection, lon_0=np.average([lons[0], lons[-1]])) if makeFigure: dpi = float(options['dpi']) width = float(imageWidth) / dpi height = width #if imageHeight is None: # height = width * m.aspect #else: # height = float(imageHeight) / dpi #plt.figure(figsize=(width,height)).add_axes([0.1,0.1,0.8,0.8], frameon=True) plt.figure(figsize=(width,height)) m = plt.axes(projection=ccrs.PlateCarree()) #m.set_extent([meridians[0], meridians[1], parallels[0], parallels[1]], # crs=ccrs.PlateCarree()) gl = m.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--') gl.xlabels_top = False gl.ylabels_left = True gl.ylabels_right = False gl.xlines = True gl.ylines = True gl.xlocator = mticker.FixedLocator(np.arange(meridians[0], meridians[1]+meridians[2], meridians[2])) gl.ylocator = mticker.FixedLocator(np.arange(parallels[0], parallels[1]+parallels[2], parallels[2])) gl.xformatter = LONGITUDE_FORMATTER gl.yformatter = LATITUDE_FORMATTER gl.xlabel_style = {'size': 12, 'color': 'black'} gl.ylabel_style = {'size': 12, 'color': 'black'} if vmin is not None or vmax is not None: if vmin is None: vmin = np.min(vals) else: vmin = float(vmin) if vmax is None: vmax = np.max(vals) else: vmax = float(vmax) #vrange = (vmax - vmin) / 255. #levels = np.arange(vmin, vmax, vrange/30.) levels = np.linspace(vmin, vmax, 256) else: levels = 30 if logColors: norm = mcolors.LogNorm(vmin=vmin, vmax=vmax) else: norm = None # x, y = m(*np.meshgrid(lons,lats)) x, y = np.meshgrid(lons,lats) c = m.contourf(x, y, vals, levels, cmap=cmap, colors=None, norm=norm) # m.drawcoastlines() m.coastlines() #m.drawmeridians(range(meridians[0], meridians[1], meridians[2]), labels=[0,0,0,1]) #m.drawparallels(range(parallels[0], parallels[1], parallels[2]), labels=[1,1,1,1]) plt.colorbar(c, ticks=np.linspace(vmin,vmax,7), shrink=0.6) evalKeywordCmds(options) if outFile: plt.savefig(outFile, **validCmdOptions(options, 'savefig')) def arr2d_from_json(js, var_name): return np.array([[js[i][j][var_name] for j in range(len(js[0]))] for i in range(len(js))]) def arr1d_from_json(js, var_name): return np.array([js[i][var_name] for i in range(len(js))]) def plot_map(map, val_key="mean", cnt_key="cnt", lon_key="lon", lat_key="lat", fill=-9999, grid_line_sep=10, border_slop=1, log_colors=False, title='', vmin=None, vmax=None, normalize_lons=False, image_width=1000, **options): # Parse values, longitudes and latitudes from JSON response. vals = arr2d_from_json(map, val_key) cnts = arr2d_from_json(map, cnt_key) lons = arr1d_from_json(map[0], lon_key) lats = arr1d_from_json([map[i][0] for i in range(len(map))], lat_key) # If cnt is 0, set value to fill vals[cnts==0] = fill # Plot time time-averaged map as an image. print("Creating plot of the results.") print("This will take a minute. Please wait...") min_val = np.min(vals[vals != fill]) if vmin is None: vmin = min_val max_val = np.max(vals[vals != fill]) if vmax is None: vmax = max_val min_lon = math.floor(np.min(lons)) - grid_line_sep max_lon = math.ceil(np.max(lons)) min_lat = math.floor(np.min(lats)) - grid_line_sep max_lat = math.ceil(np.max(lats)) imageMap(lons, lats, vals, imageWidth=image_width, vmin=vmin, vmax=vmax, logColors=log_colors, meridians=[min_lon, max_lon, grid_line_sep], parallels=[min_lat, max_lat, grid_line_sep], borderSlop=border_slop, title=title, normalizeLongs=normalize_lons, **options) def ts_plot(ts_json, t_name='time', val_name='mean', title='', units=''): t = np.array([ts[0][t_name] for ts in ts_json["data"]]) vals = np.array([ts[0][val_name] for ts in ts_json["data"]]) show_plot(t, vals, title=textwrap.fill(title,64), y_label=textwrap.fill(units,32)) def plot_hovmoller(hm, time_key="time", val_key="mean", coord_series_key="lats", coord_point_key="latitude", coord_axis_vert=True, fill=-9999., hovfig=None, subplot=111, add_color_bar=True, title=""): times = [d[time_key] for d in hm] times = mdates.epoch2num(times) coords = [[d[coord_point_key] for d in hvals[coord_series_key]] for hvals in hm] coords_flat = np.array(sorted(list(set(itertools.chain(*coords))))) coords_delta = np.median(coords_flat[1:] - coords_flat[:-1]) coords_min = np.amin(coords_flat) coords_max = np.amax(coords_flat) vals_fill = np.full((len(hm),len(coords_flat)), fill, dtype=np.float64) t_ind = 0 for hvals in hm: cur_vals = np.array([d[val_key] for d in hvals[coord_series_key]]) coords = np.array([d[coord_point_key] for d in hvals[coord_series_key]]) coords_inds = np.round((coords - coords_min) / coords_delta).astype(int) vals_fill[t_ind, coords_inds] = cur_vals t_ind += 1 vals = np.ma.array(data=vals_fill, mask=vals_fill == fill) extent = [np.min(times), np.max(times), coords_min, coords_max] dtFmt = mdates.DateFormatter('%b %Y') # define the formatting if hovfig is None: fig = plt.figure(figsize=(16,6)) else: fig = hovfig ax = fig.add_subplot(subplot) ax.set_title(title) if coord_axis_vert: vals = np.transpose(vals) ax.xaxis.set_major_formatter(dtFmt) ax.set_ylabel(coord_point_key) plt.xticks(rotation=45) else: extent = [extent[2], extent[3], extent[0], extent[1]] ax.yaxis.set_major_formatter(dtFmt) ax.set_xlabel(coord_point_key) cax = ax.imshow(vals, origin='lower', extent=extent) ax.set_aspect('auto') if add_color_bar: fig.colorbar(cax, ticks=np.linspace(np.min(vals), np.max(vals), 7), orientation='vertical') return fig def compute_ts_and_tam_no_plot(dataset, bbox, start_time, end_time, base_url="localhost", seasonal_filter="false"): url_params = 'ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\ format(dataset, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format)) ts_url = '{}/timeSeriesSpark?{}&seasonalFilter={}'.format(base_url, url_params, seasonal_filter) tam_url = '{}/timeAvgMapSpark?{}'.format(base_url, url_params) # Display some information about the job print(ts_url); print() print(tam_url); print() # Query SDAP to compute the time series print("Computing time series...") start = time.perf_counter() ts_json = requests.get(ts_url, verify=False).json() print("Area-averaged time series took {} seconds".format(time.perf_counter() - start)) print() # Query SDAP to compute the time averaged map print("Computing time averaged map...") start = time.perf_counter() tam_json = requests.get(tam_url, verify=False).json() print("Time averaged map took {} seconds".format(time.perf_counter() - start)) return ts_json, tam_json def compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url="localhost", seasonal_filter="false", title='', grid_line_sep=5, units=None, log_colors=False, normalize_lons=False, **options): ts_json, tam_json = compute_ts_and_tam_no_plot(dataset, bbox, start_time, end_time, base_url=base_url, seasonal_filter=seasonal_filter) print() print("Plot of area-average time series:") ts_plot(ts_json, val_name='mean', title=title, units=units) if seasonal_filter == "true": print("Plot of time series of difference with climatology:") ts_plot(ts_json, val_name='meanSeasonal', title=title, units=units) print() # Query SDAP to compute the time averaged map tam = tam_json["data"] plot_map(tam, log_colors=log_colors, grid_line_sep=grid_line_sep, title=title, normalize_lons=normalize_lons, **options) def show_sdap_json(j, nh=20, nt=10): out_str = pformat(j) for line in out_str.splitlines()[:nh]: print(line) print("\t\t.\n"*3) for line in out_str.splitlines()[-nt:]: print(line) print('Done with plotting setup.') ``` # Science Data Analytics Platform (SDAP) SDAP (https://sdap.apache.org/) provides advanced analytics capabilities to support NASA's New Observing Strategies (NOS) and Analytic Collaborative Frameworks (ACF) thrusts. In this demonstration we use SDAP with oceanographic datasets relevant to the CEOS Ocean Variables Enabling Research and Applications for GEO (COVERAGE) initiative. In this demonstration, two geographically distributed SDAP cloud computing deployments are used, one on Amazon Web Services (AWS, https://aws.amazon.com/) for analytics with datasets curated in the USA (e.g., from NASA or NOAA), and one on WEkEO (https://www.wekeo.eu/) for analytics with European datasets (e.g., from CMEMS). In this way we follow the strategy of performing the computations close to the data host providers. SDAP provides web service endpoints for each analytic algorithm, and can be accessed in a web browser or from a variety of programming languages. This notebook demonstrates the Python API to access SDAP. ## Demonstration Setup In the cell below, we specify the location of the SDAP deployments to use, a dataset to be used, the bounding box for an area of interest, and a time range for analysis. ``` # Base URLs for the USA (AWS) and European (WEkEO) SDAP deployments. base_url_us = "https://coverage.ceos.org/nexus" base_url_eu = "https://coverage.wekeo.eu" # Define bounding box and time period for analysis min_lon = -77; max_lon = -70 min_lat = 35; max_lat = 42 bbox = box(min_lon, min_lat, max_lon, max_lat) # Specify the SDAP name of the datasets dataset_us = "MUR25-JPL-L4-GLOB-v4.2_analysed_sst" dataset_eu = "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst" start_time = datetime(2018, 1, 1) end_time = datetime(2018, 12, 31) print("dataset_us: {}".format(dataset_us)) print("dataset_eu: {}".format(dataset_eu)) print("spatial region {}, and time range {} to {}.". format(bbox, start_time, end_time)) plot_box(bbox) ``` # Cloud Analytics ## Data Inventory We begin by querying the SDAP `/list` endpoint at each of our SDAP deployments to examine what data are available in each instantiation of SDAP. ``` def get_sdap_inv(base_url): url = '{}/list'.format(base_url) print("Web Service Endpoint:"); print(url); res = requests.get(url, verify=False).json() pprint(res) print("Response from AWS SDAP:") get_sdap_inv(base_url_us) print() print("Response from WEkEO SDAP:") get_sdap_inv(base_url_eu) ``` ## Area-Averaged Time Series Next we will make a simple web service call to the SDAP `/timeSeriesSpark` endpoint. This can also be done in a web browser or in a variety of programming languages. ``` # Compute time series using the SDAP/NEXUS web/HTTP interface # # Construct the URL url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\ format(base_url_us, dataset_us, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format), "false") # Display some information about the job print(url); print() # Query SDAP to compute the time averaged map print("Waiting for response from SDAP...") start = time.perf_counter() ts_json = requests.get(url, verify=False).json() print("Time series took {} seconds".format(time.perf_counter() - start)) ``` ### JSON response The SDAP web service calls return the result in `JSON`, a standard web services data interchange format. This makes it easy for another web service component to "consume" the SDAP output. Let's view the JSON response. It is long, so we'll show just the first few time values. ``` show_sdap_json(ts_json, nh=33, nt=10) ``` ### Plot the result Let's check our time series result with a plot. An SDAP dataset can also be associated with its climatology (long-term average for a given time period like monthly or daily). If this is the case, we can apply a "seasonal filter" to compute the spatial average of the difference between the dataset and its climatology as a time series. ``` # Plot the result print("Plot of area-average time series:") ts_plot(ts_json, val_name='mean', title=dataset_us, units='Degrees Celsius') ``` ## Time Averaged Map Next we will issue an SDAP web service call to compute a time averaged map. While the time series algorithm used above averages spatially to produce a single value for each time stamp, the time average map averages over time to produce a single value at each grid cell location. While the time series produces a 1D result indexed by time, the time averaged map produces a 2D map indexed by latitude and longitude. ``` # Compute time-averaged map using the SDAP/NEXUS web/HTTP interface # # Construct the URL url = '{}/timeAvgMapSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\ format(base_url_us, dataset_us, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format)) # Display some information about the job print(url); print() # Query SDAP to compute the time averaged map print("Waiting for response from SDAP...") start = time.perf_counter() tam_json = requests.get(url, verify=False).json() print("Time averaged map took {} seconds".format(time.perf_counter() - start)) ``` ### JSON response The SDAP web service calls return the result in `JSON`, a standard web services data interchange format. This makes it easy for another web service component to "consume" the SDAP output. Let's view the JSON response. It is long, so we'll show just the first few grid cells. ``` show_sdap_json(tam_json, nh=13, nt=10) ``` ### Extract the actual data and plot the result The actual time averaged map data is readily accessible for plotting. ``` # Extract the actual output data tam = tam_json["data"] # Create a plot of the Time Averaged Map results plot_map(tam, title=dataset_us+" (deg C)", grid_line_sep=2) ``` ## Hovmoller Maps Next we will issue an SDAP web service call to compute latitude-time and longitude-time Hovmoller maps and plot the results. ``` # Construct the URLs url_lat = '{}/latitudeTimeHofMoellerSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\ format(base_url_us, dataset_us, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format)) url_lon = '{}/longitudeTimeHofMoellerSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}'.\ format(base_url_us, dataset_us, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format)) # Query SDAP to compute the latitude-time Hovmoller map print(url_lat); print() print("Waiting for response from SDAP...") start = time.perf_counter() hm_lat_json = requests.get(url_lat, verify=False).json() print("Latitude-time Hovmoller map took {} seconds".format(time.perf_counter() - start)); print() # Query SDAP to compute the longitude-time Hovmoller map print(url_lon); print() print("Waiting for response from SDAP...") start = time.perf_counter() hm_lon_json = requests.get(url_lon, verify=False).json() print("Longitude-time Hovmoller map took {} seconds".format(time.perf_counter() - start)) ``` ### JSON response Let's view the JSON response. It is long, so we'll show just the first few grid cells. ``` # Show snippet of JSON response for latitude-time Hovmoller show_sdap_json(hm_lat_json, nh=19, nt=10) # Show snippet of JSON response for longitude-time Hovmoller show_sdap_json(hm_lon_json, nh=19, nt=10) ``` ### Extract the actual data and plot the results The actual map data is readily accessible for plotting. ``` # Extract the actual output data hm_lat = hm_lat_json["data"] hm_lon = hm_lon_json["data"] # Plot the Hovmoller maps hovfig = plot_hovmoller(hm_lat, coord_series_key="lats", coord_point_key="latitude", coord_axis_vert=True, subplot=121, title="Sea Surface Temperature (deg C)") hovfig = plot_hovmoller(hm_lon, coord_series_key="lons", coord_point_key="longitude", coord_axis_vert=False, hovfig=hovfig, subplot=122, title="Sea Surface Temperature (deg C)") ``` ## Joint Analytics Across AWS and WEkEO SDAP Deployments Next we can take advantage of the two SDAP deployments and conduct joint analytics across the two platforms. ### Compare two SST datasets, one from AWS SDAP and one from WEkEO SDAP ``` # Previous time series result was computed on AWS with # dataset "MUR25-JPL-L4-GLOB-v4.2_analysed_sst" ts_mur25_json = ts_json # Let's compute a 2nd SST time series, this time computed on WEkEO with # dataset "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst" # dataset_eu_gmpe_sst = "METOFFICE-GLO-SST-L4-NRT-OBS-GMPE-V3_analysed_sst" url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\ format(base_url_eu, dataset_eu_gmpe_sst, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format), "false") # Display some information about the job print(url); print() # Query SDAP to compute the time averaged map print("Waiting for response from SDAP...") start = time.perf_counter() ts_gmpe_json = requests.get(url, verify=False).json() print("Time series took {} seconds".format(time.perf_counter() - start)) # Plot the result ts_plot_two(ts_mur25_json, ts_gmpe_json, dataset_us, dataset_eu_gmpe_sst, "Degrees Celsius", "Degrees Celsius", title="SST Comparison", val_name="mean") scatter_plot(ts_mur25_json, ts_gmpe_json, title="SST Comparison", xlabel=dataset_us, ylabel=dataset_eu_gmpe_sst) ``` ### Compare SST from AWS SDAP and ADT from WEkEO SDAP ``` dataset_eu_cmems_adt = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_adt" url = '{}/timeSeriesSpark?ds={}&minLon={}&minLat={}&maxLon={}&maxLat={}&startTime={}&endTime={}&seasonalFilter={}'.\ format(base_url_eu, dataset_eu_cmems_adt, *bbox.bounds, start_time.strftime(dt_format), end_time.strftime(dt_format), "false") # Display some information about the job print(url); print() # Query SDAP to compute the time averaged map print("Waiting for response from SDAP...") start = time.perf_counter() ts_cmems_adt_json = requests.get(url, verify=False).json() print("Time series took {} seconds".format(time.perf_counter() - start)) # Plot the result ts_plot_two(ts_mur25_json, ts_cmems_adt_json, dataset_us, dataset_eu_cmems_adt, "Degrees Celsius", "Meters Above Geoid", title="SST vs ADT", val_name="mean") ``` # More SDAP Analytics In the rest of this notebook we use a helper function defined in the first notebook cell above to use SDAP to compute time series and time averaged map for a variety of other relevant datasets. In these results, SDAP is used in the same way as we demonstrated above. ## Absolute Dynamic Topography (ADT) from CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047 ``` dataset = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_adt" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_eu, units="meters", title=dataset, grid_line_sep=2) ``` ## Sea Level Anomaly (SLA) from CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047 ``` dataset = "CMEMS_AVISO_SEALEVEL_GLO_PHY_L4_REP_OBSERVATIONS_008_047_sla" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_eu, units="meters", title=dataset, grid_line_sep=2) ``` ## Sea Surface Salinity (SSS) from Multi-Mission Optimally Interpolated Sea Surface Salinity 7-Day Global Dataset V1 ``` start_time_oisss7d = datetime(2011, 8, 28) end_time_oisss7d = datetime(2021, 9, 8) dataset = "OISSS_L4_multimission_global_7d_v1.0_sss" compute_ts_and_tam(dataset, bbox, start_time_oisss7d, end_time_oisss7d, base_url=base_url_us, units="1e-3", title=dataset, grid_line_sep=2) ``` ## Sea Surface Salinity (SSS) Uncertainty from Multi-Mission Optimally Interpolated Sea Surface Salinity 7-Day Global Dataset V1 ``` dataset = "OISSS_L4_multimission_global_7d_v1.0_sss_uncertainty" start_time_oisss7d = datetime(2015, 7, 1) end_time_oisss7d = datetime(2021, 9, 8) compute_ts_and_tam(dataset, bbox, start_time_oisss7d, end_time_oisss7d, base_url=base_url_us, units="1e-3", title=dataset, grid_line_sep=2) ``` ## Sea Surface Salinity (SSS) from Multi-Mission Optimally Interpolated Sea Surface Salinity Monthly Global Dataset V1 ``` start_time_oisssmo = datetime(2011, 9, 16) end_time_oisssmo = datetime(2021, 8, 16) dataset = "OISSS_L4_multimission_global_monthly_v1.0_sss" compute_ts_and_tam(dataset, bbox, start_time_oisssmo, end_time_oisssmo, base_url=base_url_us, units="1e-3", title=dataset, grid_line_sep=2) ``` ## Sea Surface Salinity (SSS) Anomaly from Multi-Mission Optimally Interpolated Sea Surface Salinity Monthly Global Dataset V1 ``` dataset = "OISSS_L4_multimission_global_monthly_v1.0_sss_anomaly" compute_ts_and_tam(dataset, bbox, start_time_oisssmo, end_time_oisssmo, base_url=base_url_us, units="1e-3", title=dataset, grid_line_sep=2) ``` ## Sea Surface Temperature (SST) from MUR25-JPL-L4-GLOB-v4.2 ``` dataset = "MUR25-JPL-L4-GLOB-v4.2_analysed_sst" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_us, units="degrees celsius", title=dataset, grid_line_sep=2) ``` ## Chlorophyll-A from MODIS_Aqua_L3m_8D ``` # Define dataset and bounding box for analysis dataset = "MODIS_Aqua_L3m_8D_chlor_a" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_us, seasonal_filter="true", units="milligram m-3", title=dataset, log_colors=True, grid_line_sep=2) ``` ## Chlorophyll-A from JPL-MRVA25-CHL-L4-GLOB-v3.0_CHLA ``` dataset = "JPL-MRVA25-CHL-L4-GLOB-v3.0_CHLA_analysis" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_us, units="milligram m-3", title=dataset, log_colors=True, grid_line_sep=2) ``` ## Chlorophyll-A from CMEMS_OCEANCOLOUR_GLO_CHL_L4_REP_OBSERVATIONS_009_082 ``` dataset = "CMEMS_OCEANCOLOUR_GLO_CHL_L4_REP_OBSERVATIONS_009_082_CHL" compute_ts_and_tam(dataset, bbox, start_time, end_time, base_url=base_url_eu, units="milligram m-3", title=dataset, log_colors=True, grid_line_sep=2) ```
github_jupyter
``` import cv2 import os import torch,torchvision import torch.nn as nn import numpy as np import os from tqdm import tqdm import matplotlib.pyplot as plt import torch.optim as optim from torch.nn import * from torch.utils.tensorboard import SummaryWriter import matplotlib.pyplot as plt import wandb from ray import tune import os torch.cuda.empty_cache() device = 'cuda' PROJECT_NAME = 'Landscape-Pictures-GAN' IMG_SIZE = 224 def load_data(directory='./data/',img_size=IMG_SIZE,num_of_samples=500): idx = -1 data = [] for file in tqdm(os.listdir(directory)): idx += 1 file = directory + file img = cv2.imread(file) img = cv2.resize(img,(img_size,img_size)) data.append(img) print(idx) data = data[:num_of_samples] return torch.from_numpy(np.array(data)) # data = load_data() # torch.save(data,'./data.pt') # torch.save(data,'./data.pth') data = torch.load('./data.pth') data.shape plt.imshow(torch.tensor(data[0]).view(IMG_SIZE,IMG_SIZE,3)) class Desc(nn.Module): def __init__(self,linearactivation=nn.LeakyReLU()): super().__init__() self.linearactivation = linearactivation self.linear1 = nn.Linear(IMG_SIZE*IMG_SIZE*3,2) self.linear1batchnorm = nn.BatchNorm1d(2) self.linear2 = nn.Linear(2,4) self.linear2batchnorm = nn.BatchNorm1d(4) self.linear3 = nn.Linear(4,2) self.linear3batchnorm = nn.BatchNorm1d(2) self.output = nn.Linear(2,1) self.outputactivation = nn.Sigmoid() def forward(self,X,shape=True): preds = self.linearactivation(self.linear1batchnorm(self.linear1(X))) preds = self.linearactivation(self.linear2batchnorm(self.linear2(preds))) preds = self.linearactivation(self.linear3batchnorm(self.linear3(preds))) preds = self.outputactivation(self.output(preds)) return preds class Gen(nn.Module): def __init__(self,z_dim,linearactivation=nn.LeakyReLU()): super().__init__() self.linearactivation = linearactivation self.linear1 = nn.Linear(z_dim,256) self.linear1batchnorm = nn.BatchNorm1d(256) self.linear2 = nn.Linear(256,512) self.linear2batchnorm = nn.BatchNorm1d(512) self.linear3 = nn.Linear(512,256) self.linear3batchnorm = nn.BatchNorm1d(256) self.output = nn.Linear(256,IMG_SIZE*IMG_SIZE*3) self.outputactivation = nn.Tanh() def forward(self,X): preds = self.linearactivation(self.linear1batchnorm(self.linear1(X))) preds = self.linearactivation(self.linear2batchnorm(self.linear2(preds))) preds = self.linearactivation(self.linear3batchnorm(self.linear3(preds))) preds = self.outputactivation(self.output(preds)) return preds z_dim = 64 BATCH_SIZE = 32 lr = 3e-4 criterion = nn.BCELoss() epochs = 125 fixed_noise = torch.randn((BATCH_SIZE,z_dim)).to(device) gen = Gen(z_dim=z_dim).to(device) optimizer_gen = optim.Adam(gen.parameters(),lr=lr) desc = Desc().to(device) optimizer_desc = optim.Adam(desc.parameters(),lr=lr) def accuracy_fake(desc_fake): correct = 0 total = 0 preds = np.round(np.array(desc_fake.cpu().detach().numpy())) for pred in preds: if pred == 0: correct += 1 total += 1 return round(correct/total,3) def accuracy_real(desc_real): correct = 0 total = 0 preds = np.round(np.array(desc_real.cpu().detach().numpy())) for pred in preds: if pred == 1: correct += 1 total += 1 return round(correct/total,3) torch.cuda.empty_cache() msg = input('Msg : ') # 0.1-leaky-relu-desc wandb.init(project=PROJECT_NAME,name=f'baseline-{msg}') for epoch in tqdm(range(epochs)): torch.cuda.empty_cache() for idx in range(0,len(data),BATCH_SIZE): torch.cuda.empty_cache() X_batch = torch.tensor(np.array(data[idx:idx+BATCH_SIZE])).view(-1,IMG_SIZE*IMG_SIZE*3).to(device).float() batch_size = X_batch.shape[0] noise = torch.randn(batch_size, z_dim).to(device) fake = gen(noise).float() desc_real = desc(X_batch).view(-1) lossD_real = criterion(desc_real,torch.ones_like(desc_real)) desc_fake = desc(fake).view(-1) lossD_fake = criterion(desc_fake,torch.zeros_like(desc_fake)) lossD = (lossD_real+lossD_fake)/2 desc.zero_grad() lossD.backward(retain_graph=True) wandb.log({'lossD':lossD.item()}) optimizer_desc.step() output = desc(fake).view(-1) lossG = criterion(output, torch.ones_like(output)) gen.zero_grad() wandb.log({'lossG':lossG.item()}) lossG.backward() wandb.log({'lossG':lossG.item()}) optimizer_gen.step() wandb.log({'accuracy_fake':accuracy_fake(desc_fake)}) wandb.log({'accuracy_real':accuracy_real(desc_real)}) with torch.no_grad(): imgs = gen(fixed_noise).view(-1,3,IMG_SIZE,IMG_SIZE) imgs_all_grid = torchvision.utils.make_grid(imgs,normalize=True) wandb.log({'img':wandb.Image(imgs[0].cpu())}) wandb.log({'imgs':wandb.Image(imgs_all_grid)}) ```
github_jupyter
Definition of **DTLZ2 problem** with 3 objective functions: $f_1(X) = (1 + g(x_3)) \cdot cos(x_1 \cdot \frac{\pi}{2}) \cdot cos(x_2 \cdot \frac{\pi}{2})$ $f_2(X) = (1 + g(x_3)) \cdot cos(x_1 \cdot \frac{\pi}{2}) \cdot sin(x_2 \cdot \frac{\pi}{2})$ $f_3(x) = (1 + g(x_3)) \cdot sin(x_1 \cdot \frac{\pi}{2})$ with $-10 \leq x_1 \leq 10$ $-10 \leq x_2 \leq 10$ $-10 \leq x_3 \leq 10$ $g(x_3) = \sum_{x_i \in X_M} (x_i - 0.5)^2$ adapted from "*Scalable Test Problems for Evolutionary Multi-Objective Optimization*" section 8.2. ``` import sys sys.path.append('../..') import numpy as np import matplotlib.pyplot as plt import beagle as be np.random.seed(1997) # Problem definition def func_1(values): const = np.pi / 2 return (1 + g(values)) * np.cos(values[0]*const) * np.cos(values[1]*const) def func_2(values): const = np.pi / 2 return (1 + g(values)) * np.cos(values[0]*const) * np.sin(values[1]*const) def func_3(values): const = np.pi / 2 return (1 + g(values)) * np.sin(values[0]*const) def g(values): result = 0.0 for val in values: result += (val - 0.5)**2 return result x_1 = x_2 = x_3 = (-10.0, 10.0) representation = 'real' # Algorithm definition nsga2 = be.use_algorithm( 'experimental.NSGA2', fitness=be.Fitness(func_1, func_2, func_3), population_size=100, individual_representation='real', bounds = [x_1, x_2, x_3], alg_id='nsga2', evaluate_in_parallel=False ) spea2 = be.use_algorithm( 'experimental.SPEA2', fitness=be.Fitness(func_1, func_2, func_3), population_size=50, individual_representation='real', bounds = [x_1, x_2, x_3], spea2_archive=100, alg_id='spea2', evaluate_in_parallel=False ) wrapper = be.parallel(nsga2, spea2, generations=50) wrapper.algorithms # NSGA2 be.display(wrapper.algorithms[0], only_show=True) # SPEA2 be.display(wrapper.algorithms[1], only_show=True) # Obtain the solutions that make up the non-dominated front of each algorithm indices, values = be.pareto_front(wrapper.algorithms[0]) nsga2_sols = np.array([ wrapper.algorithms[0].population[idx].values for idx in indices['population'] ]) indices, values = be.pareto_front(wrapper.algorithms[0]) spea2_sols = np.array([ wrapper.algorithms[1].population['archive'][idx].values for idx in indices['population'] ]) fig = plt.figure(2, figsize=(15, 15)) ax1 = fig.add_subplot(221, projection='3d') ax2 = fig.add_subplot(222, projection='3d') ax3 = fig.add_subplot(223, projection='3d') ax4 = fig.add_subplot(224, projection='3d') # Problem definition def f_1_vec(x, y, z): const = np.pi / 2 values = np.array((x, y, z)) return (1 + g_vec(values)) * np.cos(x*const) * np.cos(y*const) def f_2_vec(x, y, z): const = np.pi / 2 values = np.array((x, y, z)) return (1 + g_vec(values)) * np.cos(x*const) * np.sin(y*const) def f_3_vec(x, y, z): const = np.pi / 2 values = np.array((x, y, z)) return (1 + g_vec(values)) * np.sin(x*const) def g_vec(values): result = np.power(values - 0.5, 2) return np.sum(result, axis=0) for ax in [ax1, ax2, ax3, ax4]: # Plot the obtained Pareto's front ax.scatter( f_1_vec(spea2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]), f_2_vec(nsga2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]), f_3_vec(nsga2_sols[:, 0], nsga2_sols[:, 1], nsga2_sols[:, 2]), color='red', alpha=0.7, linewidth=0, antialiased=False, label='SPEA2') ax.scatter( f_1_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]), f_2_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]), f_3_vec(spea2_sols[:, 0], spea2_sols[:, 1], spea2_sols[:, 2]), color='green', alpha=0.7, linewidth=0, antialiased=False, label='NSGA2') ax.set_xlabel('f1(x)', size=15) ax.set_ylabel('f2(x)', size=15) ax.set_zlabel('f3(x)', size=15) ax2.view_init(40, -20) ax3.view_init(40, 0) ax4.view_init(40, 30) handles, labels = ax1.get_legend_handles_labels() fig.legend(handles, labels, loc='lower center', fontsize=20, markerscale=2) plt.show() ```
github_jupyter
``` from subprocess import call from glob import glob from nltk.corpus import stopwords import os, struct from tensorflow.core.example import example_pb2 import pyrouge import shutil from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from nltk.stem.porter import * ratio = 1 duc_num = 7 max_len = 250 #cmd = '/root/miniconda2/bin/python ../pointer-generator-master/run_summarization.py --mode=decode --single_pass=1 --coverage=True --vocab_path=finished_files/vocab --log_root=log --exp_name=myexperiment --data_path=test/temp_file' #cmd = '/root/miniconda2/bin/python run_summarization.py --mode=decode --single_pass=1 --coverage=True --vocab_path=finished_files/vocab --log_root=log --exp_name=myexperiment --data_path=test/temp_file --max_enc_steps=4000' #cmd = cmd.split() #generated_path = '/gttp/pointer-generator-master/log/myexperiment/decode_test_4000maxenc_4beam_35mindec_120maxdec_ckpt-238410/' #generated_path = '/gttp/pointer-generator-tal/log/myexperiment/decode_test_4000maxenc_4beam_35mindec_100maxdec_ckpt-238410/' vocab_path = '../data/DMQA/finished_files/vocab' log_root = 'log' exp_name = 'myexperiment' data_path= 'test/temp_file' max_enc_steps = 4000 cmd = ['python', 'run_summarization.py', '--mode=decode', '--single_pass=1', '--coverage=True', '--vocab_path=' + vocab_path, '--log_root=' + log_root, '--exp_name=' + exp_name, '--data_path=' + data_path, '--max_enc_steps=' + str(max_enc_steps)] generated_path = 'log/myexperiment/decode_test_4000maxenc_4beam_35mindec_100maxdec_ckpt-238410/' stopwords = set(stopwords.words('english')) stemmer = PorterStemmer() def pp(string): return ' '.join([stemmer.stem(word.decode('utf8')) for word in string.lower().split() if not word in stopwords]) def write_to_file(article, abstract, rel, writer): abstract = '<s> '+' '.join(abstract)+' </s>' #abstract = abstract.encode('utf8', 'ignore') #rel = rel.encode('utf8', 'ignore') #article = article.encode('utf8', 'ignore') tf_example = example_pb2.Example() tf_example.features.feature['abstract'].bytes_list.value.extend([bytes(abstract)]) tf_example.features.feature['relevancy'].bytes_list.value.extend([bytes(rel)]) tf_example.features.feature['article'].bytes_list.value.extend([bytes(article)]) tf_example_str = tf_example.SerializeToString() str_len = len(tf_example_str) writer.write(struct.pack('q', str_len)) writer.write(struct.pack('%ds' % str_len, tf_example_str)) def duck_iterator(i): duc_folder = 'duc0' + str(i) + 'tokenized/' for topic in os.listdir(duc_folder + 'testdata/docs/'): topic_folder = duc_folder + 'testdata/docs/' + topic if not os.path.isdir(topic_folder): continue query = ' '.join(open(duc_folder + 'queries/' + topic).readlines()) model_files = glob(duc_folder + 'models/' + topic[:-1].upper() + '.*') topic_texts = [' '.join(open(topic_folder + '/' + file).readlines()).replace('\n', '') for file in os.listdir(topic_folder)] abstracts = [' '.join(open(f).readlines()) for f in model_files] yield topic_texts, abstracts, query def ones(sent, ref): return 1. def count_score(sent, ref): ref = pp(ref).split() sent = ' '.join(pp(w) for w in sent.lower().split() if not w in stopwords) return sum([1. if w in ref else 0. for w in sent.split()]) def get_w2v_score_func(magic = 10): import gensim google = gensim.models.KeyedVectors.load_word2vec_format( 'GoogleNews-vectors-negative300.bin', binary=True) def w2v_score(sent, ref): ref = ref.lower() sent = sent.lower() sent = [w for w in sent.split() if w in google] ref = [w for w in ref.split() if w in google] try: score = google.n_similarity(sent, ref) except: score = 0. return score * magic return w2v_score def get_tfidf_score_func_glob(magic = 1): corpus = [] for i in range(5, 8): for topic_texts, _, _ in duck_iterator(i): corpus += [pp(t) for t in topic_texts] vectorizer = TfidfVectorizer() vectorizer.fit_transform(corpus) def tfidf_score_func(sent, ref): #ref = [pp(s) for s in ref.split(' . ')] sent = pp(sent) v1 = vectorizer.transform([sent]) #v2s = [vectorizer.transform([r]) for r in ref] #return max([cosine_similarity(v1, v2)[0][0] for v2 in v2s]) v2 = vectorizer.transform([ref]) return cosine_similarity(v1, v2)[0][0] return tfidf_score_func tfidf_score = get_tfidf_score_func_glob() def get_tfidf_score_func(magic = 10): corpus = [] for i in range(5, 8): for topic_texts, _, _ in duck_iterator(i): corpus += [t.lower() for t in topic_texts] vectorizer = TfidfVectorizer() vectorizer.fit_transform(corpus) def tfidf_score_func(sent, ref): ref = ref.lower() sent = sent.lower() v1 = vectorizer.transform([sent]) v2 = vectorizer.transform([ref]) return cosine_similarity(v1, v2)[0][0]*magic return tfidf_score_func def just_relevant(text, query): text = text.split(' . ') score_per_sent = [count_score(sent, query) for sent in text] sents_gold = list(zip(*sorted(zip(score_per_sent, text), reverse=True)))[1] sents_gold = sents_gold[:int(len(sents_gold)*ratio)] filtered_sents = [] for s in text: if not s: continue if s in sents_gold: filtered_sents.append(s) return ' . '.join(filtered_sents) class Summary: def __init__(self, texts, abstracts, query): #texts = sorted([(tfidf_score(query, text), text) for text in texts], reverse=True) #texts = sorted([(tfidf_score(text, ' '.join(abstracts)), text) for text in texts], reverse=True) #texts = [text[1] for text in texts] self.texts = texts self.abstracts = abstracts self.query = query self.summary = [] self.words = set() self.length = 0 def add_sum(self, summ): for sent in summ: self.summary.append(sent) def get(self): text = max([(len(t.split()), t) for t in self.texts])[1] #text = texts[0] if ratio < 1: text = just_relevant(text, self.query) sents = text.split(' . ') score_per_sent = [(score_func(sent, self.query), sent) for sent in sents] #score_per_sent = [(count_score(sent, ' '.join(self.abstracts)), sent) for sent in sents] scores = [] for score, sent in score_per_sent: scores += [score] * (len(sent.split()) + 1) scores = str(scores[:-1]) return text, 'a', scores def get_summaries(path): path = path+'decoded/' out = {} for file_name in os.listdir(path): index = int(file_name.split('_')[0]) out[index] = open(path+file_name).readlines() return out def rouge_eval(ref_dir, dec_dir): """Evaluate the files in ref_dir and dec_dir with pyrouge, returning results_dict""" r = pyrouge.Rouge155() r.model_filename_pattern = '#ID#_reference_(\d+).txt' r.system_filename_pattern = '(\d+)_decoded.txt' r.model_dir = ref_dir r.system_dir = dec_dir return r.convert_and_evaluate() def evaluate(summaries): for path in ['eval/ref', 'eval/dec']: if os.path.exists(path): shutil.rmtree(path, True) os.mkdir(path) for i, summ in enumerate(summaries): for j,abs in enumerate(summ.abstracts): with open('eval/ref/'+str(i)+'_reference_'+str(j)+'.txt', 'w') as f: f.write(abs) with open('eval/dec/'+str(i)+'_decoded.txt', 'w') as f: f.write(' '.join(summ.summary)) print rouge_eval('eval/ref/', 'eval/dec/') #count_score #score_func = ones#get_w2v_score_func()#get_tfidf_score_func()#count_score score_func = get_tfidf_score_func() summaries = [Summary(texts, abstracts, query) for texts, abstracts, query in duck_iterator(duc_num)] with open('test/temp_file', 'wb') as writer: for summ in summaries: article, abstract, scores = summ.get() write_to_file(article, abstracts, scores, writer) call(['rm', '-r', generated_path]) call(cmd) generated_summaries = get_summaries(generated_path) for i in range(len(summaries)): summaries[i].add_sum(generated_summaries[i]) evaluate(summaries) print duc_num print score_func ```
github_jupyter
Based On the Canadian Marijuana Index these are the primary players in the Canadian Market. ``` from pandas_datareader import data as pdr import fix_yahoo_finance as fyf import matplotlib.pyplot as plt import datetime import numpy as np import pandas as pd import scipy # import statsmodels.api as sm from sklearn import mixture as mix from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC import bt import ffn import jhtalib as jhta import datetime # import matplotlib as plt import seaborn as sns sns.set() fyf.pdr_override() # If want Futures data call Quandl # # Dates start = datetime.datetime(2005, 1, 1) end = datetime.datetime(2019, 1, 27) pd.core.common.is_list_like = pd.api.types.is_list_like # import pandas_datareader as pdr %pylab # params = {'legend.fontsize': 'x-large', # 'figure.figsize': (15, 5), # 'axes.labelsize': 'x-large', # 'axes.titlesize':'x-large', # 'xtick.labelsize':'x-large', # 'ytick.labelsize':'x-large'} # pylab.rcParams.update(params) %matplotlib inline # stocks = ['WEED.TO','ACB.TO','TLRY', # 'CRON.TO', 'HEXO.TO', 'TRST.TO', # 'OGI.V', 'TGOD.TO', 'RIV.V', 'TER.CN', # 'XLY.V', 'FIRE.V', 'EMH.V', # 'N.V', 'VIVO.V', 'WAYL.CN', # 'HIP.V', 'APHA.TO', 'SNN.CN', 'ISOL.CN'] # Maijuana_Index = pdr.get_data_yahoo(stocks,start= start) # # # (Maijuana_Index['Adj Close']['2017':]).plot(figsize=(15,9), title='Canadain Cannibis Index Components') # Maijuana_Index = Maijuana_Index['Adj Close'] # Maijuana_Index = ffn.rebase(Maijuana_Index) # Real_Es_Sector = ['IIPR', 'MJNE', 'PRRE', # 'GRWC', 'ZDPY', 'TURV', # 'AGTK', 'DPWW', 'CGRA', # 'DPWW', 'FUTL', 'FTPM'] Real_Es_Sector = ['PRRE'] # list(dict.values(client.get_ticker_metadata(('HYYDF')))) # # def get_names(list): # try: # for i in range(len(Real_Es_Sector)): # # df = pd.DataFrame(len(Real_Es_Sector)) # x = print(list(dict.values(client.get_ticker_metadata((Real_Es_Sector[i]))))[5]) # except: # pass # # print(list(dict.values(client.get_ticker_metadata((Real_Es_Sector[i]))))[5]) # Canada_Index_Names = ['Canaopy Growth Corporation', 'Aurora Canabis Inc.', # 'Tilray Inc.', 'Cronos Group Inc.', 'Aphria Inc', 'HEXO Corp.' # 'CannTrust Holdings Inc.', 'OrganiGram Holdings Inc', # 'The Green Organic Dutchman','Canopy Rivers Inc.', # 'TerrAscend Corp.', 'Auxly Cannabis Group Inc.', # 'The Supreme Cannabis Company Inc.','Emerald Health Therapeutics Inc.', # 'Namaste Technologies Inc.', 'Vivo Cannabis Inc.','Newstrike Brands Ltd', # 'Wayland Group','Sunniva Inc - Ordinary Shares', # 'Isodiol International Inc.'] # list(dict.values(client.get_ticker_metadata(('CGRA')))) # %%html # <iframe src="https://www.bloomberg.com/quote/HEXO:CN" width="1400" height="1300"></iframe> ``` ###### source : http://marijuanaindex.com/stock-quotes/canadian-marijuana-index/ ###### source : https://www.bloomberg.com/quote/WEED:CN ## 1. Canopy Growth Corporation : ticker WEED ### - Mkt cap $13,126,000,000 CAD as of January 2019 ##### Canopy Growth Corporation, through its subsidiaries, is a producer of medical marijuana. The Company's group of brands represents distinct voices and market positions designed to appeal to an array of customers, doctors and strategic industry partners. Bloomberg Description: https://www.bloomberg.com/quote/WEED:CN CEO: Bruce Linton https://www.linkedin.com/in/bruce-linton-152137/ CFO: Tim Saunders https://www.linkedin.com/in/tsaunders/ ``` WEED = pdr.get_data_yahoo('WEED.TO',start= start) ``` # Canopy Growth Corporation ### Price Action ``` WEED['Adj Close']['2017':].plot(figsize=(15,9), title='Canopy Growth Corporation', fontsize=25) ``` ## 2. Aurora Cannabis Inc. : ticker ACB.TO ### - Mkt cap $6,970,000,000 CAD as of January 2019 ##### Overview source :https://www.linkedin.com/company/aurora-cannabis-inc-/about/ Aurora Cannabis Inc. is a world-renowned integrated cannabis company with an industry-leading reputation for continuously elevating and setting the global cannabis industry standard. Through our wholly owned subsidiaries, strategic investments, and global partnerships, Aurora provides a wide range of premium quality cannabis and hemp products and services, develops innovative technologies, promotes cannabis consumer health and wellness, and delivers an exceptional customer experience across all its brands. Aurora’s operations span multiple continents and focuses on both the medical and recreational cannabis production and sales, patient education and clinic counselling services, home hydroponic cultivation, extraction technologies and delivery systems, and hemp-based food health products. We operate around the globe pursuing new and emerging cannabis markets where possible through our owned network of import, export and wholesale distributors, and our e-commerce and mobile applications. Bloomberg Description: https://www.bloomberg.com/quote/ACB:CN CEO: Terry Booth https://www.linkedin.com/in/terry-booth-681806131/ CFO: Glen Ibbott https://www.linkedin.com/in/glenibbott/ ``` ACB = pdr.get_data_yahoo('ACB.TO',start= start) ``` # Aurora Cannabis Inc ### Price Action ``` ACB['Adj Close']['2017':].plot(figsize=(15,9), title='Aurora Cannabis Inc', fontsize=25) ``` ## 3. Tilray Inc. : ticker TLRY ### - Mkt cap $6,699,000,000 CAD as of January 2019 ##### Overview source :https://www.linkedin.com/company/tilray/about/ Tilray is a global leader in medical cannabis research and production dedicated to providing safe, consistent and reliable therapy to patients. We are the only GMP certified medical cannabis producer currently supplying products to thousands of patients, physicians, pharmacies, hospitals, governments and researchers in Australia, Canada, the European Union and the Americas. Bloomberg Description: https://www.bloomberg.com/quote/TLRY:US CEO: Brendan Kennedy https://www.linkedin.com/in/kennedybrendan/ CFO: Mark Castaneda https://www.linkedin.com/in/mark-castaneda-ba8315/ ``` TLRY = pdr.get_data_yahoo('TLRY',start= start) ``` # Tilray Inc ### Price Action ``` TLRY['Adj Close']['2017':].plot(figsize=(15,9), title='Tilray Inc', fontsize=25) top_three = pd.DataFrame(bt.merge(WEED['Adj Close'], ACB['Adj Close'], TLRY['Adj Close'])) top_three.columns = [['Canopy Growth Corporation', ' Aurora Cannabis Inc.', 'Tilray Inc.']] top_three = top_three.dropna() ffn.rebase(top_three).plot(figsize=(15,9), title='Top Cannibis Firms % Returns', fontsize=25) ``` ## 4. Cronos Group Inc. : ticker CRON.TO ### - Mkt cap $2,950,000,000 CAD as of January 2019 ##### Overview source :https://www.linkedin.com/company/cronos-group-mjn-/about/ Cronos Group is a globally diversified and vertically integrated cannabis company with a presence across four continents. The Company operates two wholly-owned Canadian Licensed Producers regulated under Health Canada’s Access to Cannabis for Medical Purposes Regulations: Peace Naturals Project Inc. (Ontario), which was the first non-incumbent medical cannabis license granted by Health Canada, and Original BC Ltd. (British Columbia), which is based in the Okanagan Valley. The Company has multiple international production and distribution platforms: Cronos Israel and Cronos Australia. Through an exclusive distribution agreement, Cronos also has access to over 12,000 pharmacies in Germany as the Company focuses on building an international iconic brand portfolio and developing disruptive intellectual property. Bloomberg Description: https://www.bloomberg.com/quote/CRON:CN CEO: Michael Gorenstein https://www.linkedin.com/in/michaelgorenstein/ CFO: Nauman Siddiqui https://www.linkedin.com/in/nauman-siddiqui-cpa-cma-bba-b068aa32/ ``` CRON = pdr.get_data_yahoo('CRON.TO',start= start) ``` # Cronos Group Inc ### Price Action ``` CRON['Adj Close']['2017':].plot(figsize=(15,9), title='Cronos Group Inc', fontsize=25) ``` ## 5. HEXO Corp : ticker HEXO.TO ### - Mkt cap $1,260,000,000 CAD as of January 2019 ##### Overview source : https://www.linkedin.com/company/hexo-corp/about/ HEXO Corp is one of Canada's lowest cost producers of easy-to-use and easy-to-understand products to serve the Canadian medical and adult-use cannabis markets. HEXO Corp's brands include Hydropothecary, an award-winning medical cannabis brand and HEXO, for the adult-use market. Bloomberg Description: https://www.bloomberg.com/quote/HEXO:CN CEO: Adam Miron https://www.linkedin.com/in/adammiron/ CFO: Ed Chaplin https://www.linkedin.com/in/echaplin/ ``` HEXO = pdr.get_data_yahoo('HEXO.TO',start= start) ``` # HEXO Inc ### Price Action ``` HEXO['Adj Close']['2017':].plot(figsize=(15,9), title='HEXO Corp', fontsize=25) bottom_30 = pd.read_csv('./bottom30.csv') ``` # Summary Information on the bottom 30% of the Canadian Marijuana Index ``` bottom_30.fillna('-') ```
github_jupyter
``` from hyppo.ksample import KSample from hyppo.independence import Dcorr from combat import combat import pandas as pd import glob import os import graspy as gp import numpy as np from dask.distributed import Client, progress import dask.dataframe as ddf from scipy.stats import zscore, rankdata, mannwhitneyu import copy import math import networkx as nx from graspy.models import SIEMEstimator as siem def get_sub(fname): stext = os.path.basename(fname).split('_') return('{}_{}_{}'.format(stext[0], stext[1], stext[3])) def get_sub_pheno_dat(subid, scan, pheno_dat): matches = pheno_dat.index[pheno_dat["SUBID"] == int(subid)].tolist() match = np.min(matches) return(int(pheno_dat.iloc[match]["SEX"])) def get_age_pheno_dat(subid, scan, pheno_dat): matches = pheno_dat.index[pheno_dat["SUBID"] == int(subid)].tolist() match = np.min(matches) return(int(pheno_dat.iloc[match]["AGE_AT_SCAN_1"])) def apply_along_dataset(scs, dsets, fn): scs_xfmd = np.zeros(scs.shape) for dset in np.unique(dsets): scs_xfmd[dsets == dset,:] = np.apply_along_axis(fn, 0, scs[dsets == dset,:]) return(scs_xfmd) def apply_along_individual(scs, fn): scs_xfmd = np.zeros(scs.shape) def zsc(x): x_ch = copy.deepcopy(x) if (np.var(x_ch) > 0): x_ch = (x_ch - np.mean(x_ch))/np.std(x_ch) return x_ch else: return np.zeros(x_ch.shape) def ptr(x): x_ch = copy.deepcopy(x) nz = x[x != 0] x_rank = rankdata(nz)*2/(len(nz) + 1) x_ch[x_ch != 0] = x_rank if (np.min(x_ch) != np.max(x_ch)): x_ch = (x_ch - np.min(x_ch))/(np.max(x_ch) - np.min(x_ch)) return(x_ch) basepath = '/mnt/nfs2/MR/cpac_3-9-2/' pheno_basepath = '/mnt/nfs2/MR/all_mr/phenotypic/' datasets = os.listdir(basepath) try: datasets.remove("phenotypic") except: print("No phenotypic folder in `datasets`.") print(datasets) fmri_dict = {} pheno_dat = {} for i, dataset in enumerate(datasets): try: try: pheno_dat[dataset] = pd.read_csv('{}{}_phenotypic_data.csv'.format(pheno_basepath, dataset)) except: raise ValueError("Dataset: {} does not have a phenotypic file.".format(dataset)) scan_dict = {} sex_dict = [] age_dict = [] dset_dir = os.path.join('{}{}/graphs/FSL_nff_nsc_gsr_des'.format(basepath, dataset), '*.ssv') files_ds = glob.glob(dset_dir) successes = len(files_ds) for f in files_ds: try: gr_dat = gp.utils.import_edgelist(f) sub = get_sub(f) scansub = sub.split('_') sex = get_sub_pheno_dat(scansub[1], scansub[2], pheno_dat[dataset]) age = get_age_pheno_dat(scansub[1], scansub[2], pheno_dat[dataset]) scan_dict[sub] = gr_dat.flatten() sex_dict.append(sex) age_dict.append(age) except Exception as e: successes -= 1 print("Dataset: {} has {}/{} successes.".format(dataset, successes, len(files_ds))) if (successes < 5): raise ValueError("Dataset: {} does not have enough successes.".format(dataset)) fmri_dict[dataset] = {} fmri_dict[dataset]["scans"] = np.vstack(list(scan_dict.values())) fmri_dict[dataset]["subs"] = list(scan_dict.keys()) fmri_dict[dataset]["sex"] = sex_dict fmri_dict[dataset]["age"] = age_dict fmri_dict[dataset]["dataset"] = [i + 1 for j in range(0, fmri_dict[dataset]["scans"].shape[0])] except Exception as e: print("Error in {} Dataset.".format(dataset)) print(e) def run_experiment(row): try: ds1 = row[0]; ds2 = row[1]; sxfm=row[2]; dxfm = row[3] scans = np.vstack((fmri_dict[ds1]["scans"], fmri_dict[ds2]["scans"])) scans = scans[:,~np.all(scans == 0, axis=0)] sex = np.array(fmri_dict[ds1]["sex"] + fmri_dict[ds2]["sex"]) age = np.array(fmri_dict[ds1]["age"] + fmri_dict[ds2]["age"]) datasets = np.array([1 for i in range(0, fmri_dict[ds1]["scans"].shape[0])] + [2 for i in range(0, fmri_dict[ds2]["scans"].shape[0])]) # apply per-individual transform if sxfm == "ptr": scans = np.apply_along_axis(ptr, 1, scans) # apply per-dataset edgewise transform if dxfm == "raw": scans = scans elif dxfm == "zscore": scans = apply_along_dataset(scans, datasets, zsc) elif dxfm == "ptr": scans = apply_along_dataset(scans, datasets, ptr) elif dxfm == "combat": scans = np.array(combat(pd.DataFrame(scans.T), datasets, model=None, numerical_covariates=None)).T try: eff_batch = KSample("DCorr").test(scans[datasets == 1,:], scans[datasets == 2,:]) except: eff_batch = (None, None) try: eff_sex = KSample("DCorr").test(scans[sex == 1,:], scans[sex == 2,:]) except: eff_sex = (None, None) try: eff_age = Dcorr().test(scans, age) except: eff_age = (None, None) except: eff_batch = (None, None) eff_sex = (None, None) eff_age = (None, None) return (row[0], row[1], row[2], row[3], eff_batch[0], eff_batch[1], eff_sex[0], eff_sex[1], eff_age[0], eff_age[1]) ``` # Experiments ## Effects ``` ncores = 99 client = Client(threads_per_worker=1, n_workers=ncores) exps = [] datasets = list(fmri_dict.keys()) for sxfm in ["raw", "ptr"]: for i, ds1 in enumerate(datasets): for j in range(i+1, len(datasets)): for dxfm in ["raw", "ptr", "zscore", "combat"]: exps.append([ds1, datasets[j], sxfm, dxfm]) sim_exps = pd.DataFrame(exps, columns=["Dataset1", "Dataset2", "Sxfm", "Dxfm"]) print(sim_exps.head(n=30)) sim_exps = ddf.from_pandas(sim_exps, npartitions=ncores) sim_results = sim_exps.apply(lambda x: run_experiment(x), axis=1, result_type='expand', meta={0: str, 1: str, 2: str, 3: str, 4: float, 5: float, 6: float, 7: float, 8: float, 9: float}) sim_results sim_results = sim_results.compute(scheduler="multiprocessing") sim_results = sim_results.rename(columns={0: "Dataset1", 1: "Dataset2", 2: "Sxfm", 3: "Dxfm", 4: "Effect.Batch", 5: "pvalue.Batch", 6: "Effect.Sex", 7: "pvalue.Sex", 8: "Effect.Age", 9: "pvalue.Age"}) sim_results.to_csv('../data/dcorr/batch_results.csv') sim_results.head(n=20) ```
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import math from plotnine import * from datetime import datetime import pytz %matplotlib inline memory_free = pd.read_parquet("path to machine metric dataset/node_memory_MemFree/") memory_free = memory_free / (1024 * 1024 * 1024) memory_total = pd.read_parquet("path to machine metric dataset/node_memory_MemTotal/") memory_total = memory_total / (1024 * 1024 * 1024) # print(memory_total.values.max()) # print(len(memory_total.columns)) for c in memory_total.columns: if memory_total[c].max() >= 257: print(c) mem_used_df = pd.read_parquet("path to machine metric dataset/node_memory_MemTotal%20-%20node_memory_MemFree%20-%20node_memory_Buffers%20-%20node_memory_Cached%20-%20node_memory_Slab%20-%20node_memory_PageTables%20-%20node_memory_SwapCached/") mem_used_df = mem_used_df / (1024 * 1024 * 1024) print(mem_used_df.max().max()) # memory_used_fraction_df = 1 - (df / mem_total_df) mean_memory_per_node = mem_used_df.mean() * 100 # TODO: rewrite this. Devide based on index and the column names to get the true utilization levels. fig = plt.figure(figsize=(40,12)) ax = mean_memory_per_node.plot.hist(bins=math.ceil(mean_memory_per_node.max())) ax.set_xlim(0,) ax.set_xlabel("Mean Memory Utilization (%)", fontsize=40) ax.set_ylabel("Frequency", fontsize=40) ax.tick_params(axis='both', which='major', labelsize=40) ax.tick_params(axis='both', which='minor', labelsize=32) ax.set_title("Histogram of Mean Memory Utilization in LISA", fontsize=50) plt.savefig("mean_memory_utilization_percentage.pdf") def normalize(df): df = df.value_counts(sort=False, normalize=True).rename_axis('target').reset_index(name='pdf') df["cdf"] = df["pdf"].cumsum() return df all_values_df = pd.DataFrame({"target": mem_used_df.values.ravel()}) count_df = normalize(all_values_df) del all_values_df # Add a row at the start so that the CDF starts at 0 and ends at 1 (in case we only have one datapoint in the DF) plot_df = count_df.copy() plot_df.index = plot_df.index + 1 # shifting index plot_df.reset_index(inplace=True) plot_df['index'] = plot_df['index'] + 1 plot_df.loc[0] = [0, -math.inf, 0, 0] # add a row at the start (index, count, pdf, cdf) plot_df.loc[len(plot_df)] = [len(plot_df), math.inf, 1, 1] plot_df.sort_index(inplace=True) ggplt = ggplot(plot_df) + \ theme_light(base_size=18) + \ theme(figure_size = (8,3)) + \ geom_step(aes(x="target", y="cdf"), size=1) +\ xlab("Node RAM Usage [GB]") + \ ylab("ECDF") marker_x = [96, 192, 256, 1024, 2048] marker_y = [] for i in marker_x: marker_y.append(count_df[count_df['target'].le(i) | np.isclose(count_df['target'], i, rtol=1e-10, atol=1e-12)].tail(1)['cdf'].iloc[0]) marker_labels = ["96GB", "192GB", "256GB", "1TB", "2TB"] markers = ['o', 'v', 'p', 's', 'd'] fig = ggplt.draw(return_ggplot=False) ax = plt.gca() for x_pos, y_pos, marker_symbol, marker_label in zip(marker_x, marker_y, markers, marker_labels): ax.scatter(x_pos, y_pos, marker=marker_symbol, label=marker_label, facecolors="None", edgecolors="black") ax.legend(ncol=len(marker_x), loc=4, prop={'size': 10}) date_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") fig.tight_layout() fig.savefig("memory_usage_cdf_nodes_{}.pdf".format(date_time)) count_df t = '''\\begin{{table}}[] \\caption{{RAM usage (GB) per percentage within Lisa.}} \\label{{surfing:tbl:ram-usage-percentiles}} \\begin{{tabular}}{{@{{}}lrrrrrrr@{{}}}} \\toprule & 1\\% & 25\\% & 50\\% & 75\\% & 90\\% & 99\\% & 100\\% \\\\ \\midrule RAM & {0} & {1} & {2} & {3} & {4} & {5} & {6} \\\\ \\bottomrule \\end{{tabular}} \\end{{table}}''' # print(count_df[-1:]['cdf'] - 1.0) # print(count_df[-1:]['cdf'] >= 1.0) # print(count_df[-1:]['cdf'].ge(1.0)) # print(np.isclose(count_df[-5:]['cdf'], 1.0, rtol=1e-10, atol=1e-12)) # print(count_df[count_df['cdf'].ge(0.25) | np.isclose(count_df['cdf'], .25, rtol=1e-10, atol=1e-12)].iloc[0]) percentages = [0.01, 0.25, 0.50, 0.75, 0.90, 0.99, 1] values = [] for p in percentages: values.append(count_df[count_df['cdf'].ge(p) | np.isclose(count_df['cdf'], p, rtol=1e-8, atol=1e-12)].iloc[0]['target']) print(t.format(*["{:.2f}".format(v) for v in values])) t = '''\\begin{{table}}[] \\caption{{Fraction of RAM usage below or at specified level.}} \\label{{surfing:tbl:ram-usage-fraction}} \\begin{{tabular}}{{@{{}}lrrrrrr@{{}}}} \\toprule & 96GB & 192GB & 256GB & 1TB & 2TB \\\\ \\midrule Percentage & {0} & {1} & {2} & {3} & {4} \\\\ \\bottomrule \\end{{tabular}} \\end{{table}}''' RAMs = [96, 192, 256, 1024, 2048] values = [] for r in RAMs: values.append(count_df[count_df['target'].le(r) | np.isclose(count_df['target'], r, rtol=1e-10, atol=1e-12)].tail(1)['cdf'].iloc[0]) print(t.format(*["{:.2f}".format(v) for v in values])) # This cell outputs the special node 1128 in rack 1128, the 2TB RAM node # Unobfuscated it is r23n23 memory_free_1128 = memory_free['r23n23'] memory_total_1128 = memory_total['r23n23'] df_1128 = memory_free_1128.to_frame(name = 'free').join(memory_total_1128.to_frame(name='total')).replace(-1, np.NaN) df_1128['util'] = 1 - (df_1128['free'] / df_1128['total']) df_1128["dt"] = pd.to_datetime(df_1128.index, utc=True, unit="s") df_1128["dt"] = df_1128["dt"].dt.tz_convert(pytz.timezone('Europe/Amsterdam')).dt.tz_localize(None) df_1128 = df_1128.set_index("dt") df_1128['util'] def get_converted_xticks(ax): """ :param ax: :return list of day and month strings """ return [pd.to_datetime(tick.get_text()).date().strftime("%d\n%b") for tick in ax.get_xticklabels()] median = df_1128['util'].median() * 100 median_zeroes_filtered = df_1128['util'][df_1128['util'] > 0].median() * 100 avg = df_1128['util'].mean() * 100 print(median, avg) # print(df_1128['util']) fig, ax = plt.subplots(figsize=(11, 5)) ax.plot(df_1128['util'] * 100, color="lightcoral") ax.set_ylabel("RAM Utilization [%]", fontsize=18) ax.set_xlabel("", fontsize=14) ax.tick_params(axis='both', which='major', labelsize=16) ax.tick_params(axis='both', which='minor', labelsize=16) ax.axhline(avg, label="Average ({:.3f})".format(avg), color="steelblue", linestyle="solid") ax.axhline(median, label="Median ({:.3f})".format(median), color="yellowgreen", linestyle="dashed") ax.axhline(median_zeroes_filtered, label="Median zeros filtered ({:.3f})".format(median_zeroes_filtered), color="black", linestyle="dotted") ax.legend(ncol=3, prop={"size": 14}, bbox_to_anchor=(0.5, 1.15), loc=9) fig.tight_layout() # This call needs to be after the tight_layout call so that the labels have been set! ax.set_xticklabels(get_converted_xticks(ax)) date_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") fig.savefig("ram_utilization_node1128_{}.pdf".format(date_time), bbox_inches='tight') ```
github_jupyter
# Inspecting ModelSelectorResult When we go down from multiple time-series to single time-series, the best way how to get access to all relevant information to use/access `ModelSelectorResult` objects ``` import pandas as pd import matplotlib.pyplot as plt plt.style.use('seaborn') plt.rcParams['figure.figsize'] = [12, 6] from hcrystalball.model_selection import ModelSelector from hcrystalball.utils import get_sales_data from hcrystalball.wrappers import get_sklearn_wrapper from sklearn.linear_model import LinearRegression from sklearn.ensemble import RandomForestRegressor df = get_sales_data(n_dates=365*2, n_assortments=1, n_states=1, n_stores=2) df.head() # let's start simple df_minimal = df[['Sales']] ms_minimal = ModelSelector(frequency='D', horizon=10) ms_minimal.create_gridsearch( n_splits=2, between_split_lag=None, sklearn_models=False, sklearn_models_optimize_for_horizon=False, autosarimax_models=False, prophet_models=False, tbats_models=False, exp_smooth_models=False, average_ensembles=False, stacking_ensembles=False) ms_minimal.add_model_to_gridsearch(get_sklearn_wrapper(LinearRegression, hcb_verbose=False)) ms_minimal.add_model_to_gridsearch(get_sklearn_wrapper(RandomForestRegressor, random_state=42, hcb_verbose=False)) ms_minimal.select_model(df=df_minimal, target_col_name='Sales') ``` ## Ways to access ModelSelectorResult There are three ways how you can get to single time-series result level. - First is over `.results[i]`, which is fast, but does not ensure, that results are loaded in the same order as when they were created (reason for that is hash used in the name of each result, that are later read in alphabetic order) - Second and third uses `.get_result_for_partition()` through `dict` based partition - Forth does that using `partition_hash` (also in results file name if persisted) ``` result = ms_minimal.results[0] result = ms_minimal.get_result_for_partition({'no_partition_label': ''}) result = ms_minimal.get_result_for_partition(ms_minimal.partitions[0]) result = ms_minimal.get_result_for_partition('fb452abd91f5c3bcb8afa4162c6452c2') ``` ## ModelSelectorResult is rich As you can see below, we try to store all relevant information to enable easy access to data, that is otherwise very lenghty. ``` result ``` ### Traning data ``` result.X_train result.y_train ``` ### Data behind plots Ready to be plotted or adjusted to your needs ``` result.df_plot result.df_plot.tail(50).plot(); result ``` ## Best Model Metadata That can help to filter for example `cv_data` or to get a glimpse on which parameters the best model has ``` result.best_model_hash result.best_model_name result.best_model_repr ``` ### CV Results Get information about how our model behaved in cross validation ``` result.best_model_cv_results['mean_fit_time'] ``` Or how all the models behaved ``` result.cv_results.sort_values('rank_test_score').head() ``` ### CV Data Access predictions made during cross validation with possible cv splits and true target values ``` result.cv_data.head() result.cv_data.drop(['split'], axis=1).plot(); result.best_model_cv_data.head() result.best_model_cv_data.plot(); ``` ## Plotting Functions With `**plot_params` that you can pass depending on your plotting backend ``` result.plot_result(plot_from='2015-06', title='Performance', color=['blue','green']); result.plot_error(title='Error'); ``` ## Convenient Persist Method ``` result.persist? ```
github_jupyter
# NumPy this notebook is based on the SciPy NumPy tutorial <div class="alert alert-block alert-warning"> Note that the traditional way to import numpy is to rename it np. This saves on typing and makes your code a little more compact.</div> ``` import numpy as np ``` NumPy provides a multidimensional array class as well as a _large_ number of functions that operate on arrays. NumPy arrays allow you to write fast (optimized) code that works on arrays of data. To do this, there are some restrictions on arrays: * all elements are of the same data type (e.g. float) * the size of the array is fixed in memory, and specified when you create the array (e.g., you cannot grow the array like you do with lists) The nice part is that arithmetic operations work on entire arrays&mdash;this means that you can avoid writing loops in python (which tend to be slow). Instead the "looping" is done in the underlying compiled code ## Array Creation and Properties There are a lot of ways to create arrays. Let's look at a few Here we create an array using `arange` and then change its shape to be 3 rows and 5 columns. Note the _row-major ordering_&mdash;you'll see that the rows are together in the inner `[]` (more on this in a bit) ``` a = np.arange(15) a a = np.arange(15).reshape(3,5) print(a) ``` an array is an object of the `ndarray` class, and it has methods that know how to work on the array data. Here, `.reshape()` is one of the many methods. A NumPy array has a lot of meta-data associated with it describing its shape, datatype, etc. ``` print(a.ndim) print(a.shape) print(a.size) print(a.dtype) print(a.itemsize) print(type(a)) help(a) ``` we can also create an array from a list ``` b = np.array( [1.0, 2.0, 3.0, 4.0] ) print(b) print(b.dtype) print(type(b)) ``` we can create a multi-dimensional array of a specified size initialized all to 0 easily, using the `zeros()` function. ``` b = np.zeros((10,8)) b ``` There is also an analogous ones() and empty() array routine. Note that here we can explicitly set the datatype for the array in this function if we wish. Unlike lists in python, all of the elements of a numpy array are of the same datatype ``` c = np.eye(10, dtype=np.float64) c ``` `linspace` creates an array with evenly space numbers. The `endpoint` optional argument specifies whether the upper range is in the array or not ``` d = np.linspace(0, 1, 10, endpoint=False) print(d) ``` <div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3> Analogous to `linspace()`, there is a `logspace()` function that creates an array with elements equally spaced in log. Use `help(np.logspace)` to see the arguments, and create an array with 10 elements from $10^{-6}$ to $10^3$. </div> we can also initialize an array based on a function ``` f = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int) f ``` ## Array Operations most operations (`+`, `-`, `*`, `/`) will work on an entire array at once, element-by-element. Note that that the multiplication operator is not a matrix multiply (there is a new operator in python 3.5+, `@`, to do matrix multiplicaiton. Let's create a simply array to start with ``` a = np.arange(12).reshape(3,4) print(a) ``` Multiplication by a scalar multiplies every element ``` a*2 ``` adding two arrays adds element-by-element ``` a + a ``` multiplying two arrays multiplies element-by-element ``` a*a ``` <div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3> What do you think `1./a` will do? Try it and see </div> We can think of our 2-d array as a 3 x 4 matrix (3 rows, 4 columns). We can take the transpose to geta 4 x 3 matrix, and then we can do a matrix multiplication ``` b = a.transpose() b a @ b ``` We can sum the elements of an array: ``` a.sum() ``` <div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3> `sum()` takes an optional argument, `axis=N`, where `N` is the axis to sum over. Sum the elements of `a` across rows to create an array with just the sum along each column of `a`. </div> We can also easily get the extrema ``` print(a.min(), a.max()) ``` ## Universal functions universal functions work element-by-element. Let's create a new array scaled by `pi` ``` b = a*np.pi/12.0 print(b) c = np.cos(b) print(c) d = b + c print(d) ``` <div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3> We will often want to write our own function that operates on an array and returns a new array. We can do this just like we did with functions previously&mdash;the key is to use the methods from the `np` module to do any operations, since they work on, and return, arrays. Write a simple function that returns $\sin(2\pi x)$ for an input array `x`. Then test it by passing in an array `x` that you create via `linspace()` </div> ## Slicing slicing works very similarly to how we saw with strings. Remember, python uses 0-based indexing ![](slicing.png) Let's create this array from the image: ``` a = np.arange(9) a ``` Now look at accessing a single element vs. a range (using slicing) Giving a single (0-based) index just references a single value ``` a[2] ``` Giving a range uses the range of the edges to return the values ``` print(a[2:3]) a[2:4] ``` The `:` can be used to specify all of the elements in that dimension ``` a[:] ``` ## Multidimensional Arrays Multidimensional arrays are stored in a contiguous space in memory -- this means that the columns / rows need to be unraveled (flattened) so that it can be thought of as a single one-dimensional array. Different programming languages do this via different conventions: ![](row_column_major.png) Storage order: * Python/C use *row-major* storage: rows are stored one after the other * Fortran/matlab use *column-major* storage: columns are stored one after another The ordering matters when * passing arrays between languages (we'll talk about this later this semester) * looping over arrays -- you want to access elements that are next to one-another in memory * e.g, in Fortran: ``` double precision :: A(M,N) do j = 1, N do i = 1, M A(i,j) = … enddo enddo ``` * in C ``` double A[M][N]; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { A[i][j] = … } } ``` In python, using NumPy, we'll try to avoid explicit loops over elements as much as possible Let's look at multidimensional arrays: ``` a = np.arange(15).reshape(3,5) a ``` Notice that the output of `a` shows the row-major storage. The rows are grouped together in the inner `[...]` Giving a single index (0-based) for each dimension just references a single value in the array ``` a[1,1] ``` Doing slices will access a range of elements. Think of the start and stop in the slice as referencing the left-edge of the slots in the array. ``` a[0:2,0:2] ``` Access a specific column ``` a[:,1] ``` Sometimes we want a one-dimensional view into the array -- here we see the memory layout (row-major) more explicitly ``` a.flatten() ``` we can also iterate -- this is done over the first axis (rows) ``` for row in a: print(row) ``` or element by element ``` for e in a.flat: print(e) ``` Generally speaking, we want to avoid looping over the elements of an array in python&mdash;this is slow. Instead we want to write and use functions that operate on the entire array at once. <div class="alert alert-block alert-info"><h3><span class="fa fa-flash"></span> Quick Exercise:</h3> Consider the array defined as: ``` q = np.array([[1, 2, 3, 2, 1], [2, 4, 4, 4, 2], [3, 4, 4, 4, 3], [2, 4, 4, 4, 2], [1, 2, 3, 2, 1]]) ``` * using slice notation, create an array that consists of only the `4`'s in `q` (this will be called a _view_, as we'll see shortly) * zero out all of the elements in your view * how does `q` change? </div>
github_jupyter
# 机器学习工程师纳米学位 ## 模型评价与验证 ## 项目 1: 预测波士顿房价 欢迎来到机器学习工程师纳米学位的第一个项目!在此文件中,有些示例代码已经提供给你,但你还需要实现更多的功能来让项目成功运行。除非有明确要求,你无须修改任何已给出的代码。以**'练习'**开始的标题表示接下来的内容中有需要你必须实现的功能。每一部分都会有详细的指导,需要实现的部分也会在注释中以**'TODO'**标出。请仔细阅读所有的提示! 除了实现代码外,你还**必须**回答一些与项目和实现有关的问题。每一个需要你回答的问题都会以**'问题 X'**为标题。请仔细阅读每个问题,并且在问题后的**'回答'**文字框中写出完整的答案。你的项目将会根据你对问题的回答和撰写代码所实现的功能来进行评分。 >**提示:**Code 和 Markdown 区域可通过 **Shift + Enter** 快捷键运行。此外,Markdown可以通过双击进入编辑模式。 ## 开始 在这个项目中,你将利用马萨诸塞州波士顿郊区的房屋信息数据训练和测试一个模型,并对模型的性能和预测能力进行测试。通过该数据训练后的好的模型可以被用来对房屋做特定预测---尤其是对房屋的价值。对于房地产经纪等人的日常工作来说,这样的预测模型被证明非常有价值。 此项目的数据集来自[UCI机器学习知识库](https://archive.ics.uci.edu/ml/datasets/Housing)。波士顿房屋这些数据于1978年开始统计,共506个数据点,涵盖了麻省波士顿不同郊区房屋14种特征的信息。本项目对原始数据集做了以下处理: - 有16个`'MEDV'` 值为50.0的数据点被移除。 这很可能是由于这些数据点包含**遗失**或**看不到的值**。 - 有1个数据点的 `'RM'` 值为8.78. 这是一个异常值,已经被移除。 - 对于本项目,房屋的`'RM'`, `'LSTAT'`,`'PTRATIO'`以及`'MEDV'`特征是必要的,其余不相关特征已经被移除。 - `'MEDV'`特征的值已经过必要的数学转换,可以反映35年来市场的通货膨胀效应。 运行下面区域的代码以载入波士顿房屋数据集,以及一些此项目所需的Python库。如果成功返回数据集的大小,表示数据集已载入成功。 ``` # Import libraries necessary for this project # 载入此项目所需要的库 import numpy as np import pandas as pd import visuals as vs # Supplementary code from sklearn.model_selection import ShuffleSplit # Pretty display for notebooks # 让结果在notebook中显示 %matplotlib inline # Load the Boston housing dataset # 载入波士顿房屋的数据集 data = pd.read_csv('housing.csv') prices = data['MEDV'] features = data.drop('MEDV', axis = 1) # Success # 完成 print "Boston housing dataset has {} data points with {} variables each.".format(*data.shape) ``` ## 分析数据 在项目的第一个部分,你会对波士顿房地产数据进行初步的观察并给出你的分析。通过对数据的探索来熟悉数据可以让你更好地理解和解释你的结果。 由于这个项目的最终目标是建立一个预测房屋价值的模型,我们需要将数据集分为**特征(features)**和**目标变量(target variable)**。**特征** `'RM'`, `'LSTAT'`,和 `'PTRATIO'`,给我们提供了每个数据点的数量相关的信息。**目标变量**:` 'MEDV'`,是我们希望预测的变量。他们分别被存在`features`和`prices`两个变量名中。 ## 练习:基础统计运算 你的第一个编程练习是计算有关波士顿房价的描述统计数据。我们已为你导入了` numpy `,你需要使用这个库来执行必要的计算。这些统计数据对于分析模型的预测结果非常重要的。 在下面的代码中,你要做的是: - 计算`prices`中的`'MEDV'`的最小值、最大值、均值、中值和标准差; - 将运算结果储存在相应的变量中。 ``` # TODO: Minimum price of the data #目标:计算价值的最小值 minimum_price = np.min(data['MEDV']) # TODO: Maximum price of the data #目标:计算价值的最大值 maximum_price = np.max(data['MEDV']) # TODO: Mean price of the data #目标:计算价值的平均值 mean_price = np.average(data['MEDV']) # TODO: Median price of the data #目标:计算价值的中值 median_price = np.median(data['MEDV']) # TODO: Standard deviation of prices of the data #目标:计算价值的标准差 std_price = np.std(data['MEDV']) # Show the calculated statistics #目标:输出计算的结果 print "Statistics for Boston housing dataset:\n" print "Minimum price: ${:,.2f}".format(minimum_price) print "Maximum price: ${:,.2f}".format(maximum_price) print "Mean price: ${:,.2f}".format(mean_price) print "Median price ${:,.2f}".format(median_price) print "Standard deviation of prices: ${:,.2f}".format(std_price) ``` ### 问题1 - 特征观察 如前文所述,本项目中我们关注的是其中三个值:`'RM'`、`'LSTAT'` 和`'PTRATIO'`,对每一个数据点: - `'RM'` 是该地区中每个房屋的平均房间数量; - `'LSTAT'` 是指该地区有多少百分比的房东属于是低收入阶层(有工作但收入微薄); - `'PTRATIO'` 是该地区的中学和小学里,学生和老师的数目比(`学生/老师`)。 _凭直觉,上述三个特征中对每一个来说,你认为增大该特征的数值,`'MEDV'`的值会是**增大**还是**减小**呢?每一个答案都需要你给出理由。_ **提示:**你预期一个`'RM'` 值是6的房屋跟`'RM'` 值是7的房屋相比,价值更高还是更低呢? **回答: ** - 'RM'增大'MEDV'会增大,因为某地区房间平均数量高的话,就意味着这个地方的房子比较好比较大,比如别墅式。而平均房间数量小的话可能是因为该地方比较贫穷,买不起较大的房子,房价自然就会低。 - 'LSTAT' 增大'MEDV'会减小,如果一个地区的房东是高收入阶层,那么这个地区应该是个富人聚集地,房价也会高,反之房价会比较低。 - 'PTRATIO'增大'MEDV'会减小,如果学生老师比较小的话,说明当地教育资源比较好,生活水平比较好,房价会高,反之说明教育资源比较少,房价比较低。 ## 建模 在项目的第二部分中,你需要了解必要的工具和技巧来让你的模型进行预测。用这些工具和技巧对每一个模型的表现做精确的衡量可以极大地增强你预测的信心。 ### 练习:定义衡量标准 如果不能对模型的训练和测试的表现进行量化地评估,我们就很难衡量模型的好坏。通常我们会定义一些衡量标准,这些标准可以通过对某些误差或者拟合程度的计算来得到。在这个项目中,你将通过运算[*决定系数*](http://stattrek.com/statistics/dictionary.aspx?definition=coefficient_of_determination) R<sup>2</sup> 来量化模型的表现。模型的决定系数是回归分析中十分常用的统计信息,经常被当作衡量模型预测能力好坏的标准。 R<sup>2</sup>的数值范围从0至1,表示**目标变量**的预测值和实际值之间的相关程度平方的百分比。一个模型的R<sup>2</sup> 值为0还不如直接用**平均值**来预测效果好;而一个R<sup>2</sup> 值为1的模型则可以对目标变量进行完美的预测。从0至1之间的数值,则表示该模型中目标变量中有百分之多少能够用**特征**来解释。_模型也可能出现负值的R<sup>2</sup>,这种情况下模型所做预测有时会比直接计算目标变量的平均值差很多。_ 在下方代码的 `performance_metric` 函数中,你要实现: - 使用 `sklearn.metrics` 中的 `r2_score` 来计算 `y_true` 和 `y_predict`的R<sup>2</sup>值,作为对其表现的评判。 - 将他们的表现评分储存到`score`变量中。 ``` # TODO: Import 'r2_score' from sklearn.metrics import r2_score def performance_metric(y_true, y_predict): """ Calculates and returns the performance score between true and predicted values based on the metric chosen. """ # TODO: Calculate the performance score between 'y_true' and 'y_predict' score = r2_score(y_true,y_predict) # Return the score return score ``` ### 问题2 - 拟合程度 假设一个数据集有五个数据且一个模型做出下列目标变量的预测: | 真实数值 | 预测数值 | | :-------------: | :--------: | | 3.0 | 2.5 | | -0.5 | 0.0 | | 2.0 | 2.1 | | 7.0 | 7.8 | | 4.2 | 5.3 | *你会觉得这个模型已成功地描述了目标变量的变化吗?如果成功,请解释为什么,如果没有,也请给出原因。* 运行下方的代码,使用`performance_metric`函数来计算模型的决定系数。 ``` # Calculate the performance of this model score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3]) print "Model has a coefficient of determination, R^2, of {:.3f}.".format(score) ``` **回答:** 我认为这个模型能够成功地描述目标变量的变化,因为真实值和预测值都比较接近,R^2系数也比较高。 ### 练习: 数据分割与重排 接下来,你需要把波士顿房屋数据集分成训练和测试两个子集。通常在这个过程中,数据也会被重新排序,以消除数据集中由于排序而产生的偏差。 在下面的代码中,你需要: - 使用 `sklearn.model_selection` 中的 `train_test_split`, 将`features`和`prices`的数据都分成用于训练的数据子集和用于测试的数据子集。 - 分割比例为:80%的数据用于训练,20%用于测试; - 选定一个数值以设定 `train_test_split` 中的 `random_state` ,这会确保结果的一致性; - 最终分离出的子集为`X_train`,`X_test`,`y_train`,和`y_test`。 ``` # TODO: Import 'train_test_split' from sklearn.model_selection import train_test_split # TODO: Shuffle and split the data into training and testing subsets X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.20, random_state=42) # Success print "Training and testing split was successful." ``` ### 问题 3- 训练及测试 *将数据集按一定比例分为训练用的数据集和测试用的数据集对学习算法有什么好处?* **提示:** 如果没有数据来对模型进行测试,会出现什么问题? **答案: ** 如果没有数据对模型进行测试,那么模型可能会存在过拟合的问题,也就是说,在训练集上,模型表现得很完美,而不在训练集上的数据,则表现的很差,过拟合是可能模型学习了训练集做特有的误差特征。分为训练用和测试用的数据集,可以检验学习算法对未知数据的性能。 ---- ## 分析模型的表现 在项目的第三部分,我们来看一下几个模型针对不同的数据集在学习和测试上的表现。另外,你需要专注于一个特定的算法,用全部训练集训练时,提高它的`'max_depth'` 参数,观察这一参数的变化如何影响模型的表现。把你模型的表现画出来对于分析过程十分有益。可视化可以让我们看到一些单看结果看不到的行为。 ### 学习曲线 下方区域内的代码会输出四幅图像,它们是一个决策树模型在不同最大深度下的表现。每一条曲线都直观的显示了随着训练数据量的增加,模型学习曲线的训练评分和测试评分的变化。注意,曲线的阴影区域代表的是该曲线的不确定性(用标准差衡量)。这个模型的训练和测试部分都使用决定系数R<sup>2</sup>来评分。 运行下方区域中的代码,并利用输出的图形回答下面的问题。 ``` # Produce learning curves for varying training set sizes and maximum depths vs.ModelLearning(features, prices) ``` ### 问题 4 - 学习数据 *选择上述图像中的其中一个,并给出其最大深度。随着训练数据量的增加,训练曲线的评分有怎样的变化?测试曲线呢?如果有更多的训练数据,是否能有效提升模型的表现呢?* **提示:**学习曲线的评分是否最终会收敛到特定的值? **答案: ** 第一幅图像,最大深度是1,训练曲线的评分从1.0开始逐渐下降,而测试曲线则从0.0开始逐渐上升,如果有更多的训练数据,训练模型也不会有更大的提升,因为深度有限,模型的表现能力趋于特定值。随着最大深度的增加,训练数据表现能力会逐渐提升,而测试曲线随着最大深度的增加,模型的能力会逐渐下降,也就是出现了过拟合,这就是第四幅图像出现的问题。 ### 复杂度曲线 下列代码内的区域会输出一幅图像,它展示了一个已经经过训练和验证的决策树模型在不同最大深度条件下的表现。这个图形将包含两条曲线,一个是训练的变化,一个是测试的变化。跟**学习曲线**相似,阴影区域代表该曲线的不确定性,模型训练和测试部分的评分都用的 `performance_metric` 函数。 运行下方区域中的代码,并利用输出的图形并回答下面的两个问题。 ``` vs.ModelComplexity(X_train, y_train) ``` ### 问题 5- 偏差与方差之间的权衡取舍 *当模型以最大深度 1训练时,模型的预测是出现很大的偏差还是出现了很大的方差?当模型以最大深度10训练时,情形又如何呢?图形中的哪些特征能够支持你的结论?* **提示:** 你如何得知模型是否出现了偏差很大或者方差很大的问题? **答案: ** 当最大深度为1时,模型有很大的偏差,以为此时训练数据表现得分和测试表现得分比较接近而且很低,所以模型应出现了较大的偏差,而当最大深度为10时,训练得分较高,而测试得分与训练得分有较大的差距,模型应该出现了较大的方差。因为训练得分很高但和测试得分差距较大。 ### 问题 6- 最优模型的猜测 *你认为最大深度是多少的模型能够最好地对未见过的数据进行预测?你得出这个答案的依据是什么?* **答案: ** 最大深度应该是4,因为在测试得分上,当最大深度为4时,模型的测试得分最高,此时模型的方差和偏差趋于平衡,如果深度再大,测会出现高方差,深度减小,则会出现高偏差。 ----- ## 评价模型表现 在这个项目的最后,你将自己建立模型,并使用最优化的`fit_model`函数,基于客户房子的特征来预测该房屋的价值。 ### 问题 7- 网格搜索(Grid Search) *什么是网格搜索法?如何用它来优化学习算法?* **回答: ** 网格搜索法是使用不同的参数组合来训练模型,通过开发人员指定的相关参数组合,例如在决策树里,不同的参数组合主要是决策树的最大深度。最后通过遍历不同的参数组合,得出一个最优的参数组合和模型,可以自动化搜索最优参数和最优模型 ### 问题 8- 交叉验证 *什么是K折交叉验证法(k-fold cross-validation)?优化模型时,使用这种方法对网格搜索有什么好处?网格搜索是如何结合交叉验证来完成对最佳参数组合的选择的?* **提示:** 跟为何需要一组测试集的原因差不多,网格搜索时如果不使用交叉验证会有什么问题?GridSearchCV中的[`'cv_results'`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html)属性能告诉我们什么? **答案: ** K折交叉验证法是将数据集等分成若干份,其中一份作为验证集而剩下的最为训练集,循环使用不同的验证集和训练集,最后对所有结果取平均,交叉验证能更好的训练模型,因为差不多使用了所有的数据集,通过使用交叉验证法,网格搜索能够更准确的搜索出最优的参数组合。 ### 练习:训练模型 在最后一个练习中,你将需要将所学到的内容整合,使用**决策树演算法**训练一个模型。为了保证你得出的是一个最优模型,你需要使用网格搜索法训练模型,以找到最佳的 `'max_depth'` 参数。你可以把`'max_depth'` 参数理解为决策树算法在做出预测前,允许其对数据提出问题的数量。决策树是**监督学习算法**中的一种。 此外,你会发现你的实现使用的是 `ShuffleSplit()` 。它也是交叉验证的一种方式(见变量 `'cv_sets'`)。虽然这不是**问题8**中描述的 K-Fold 交叉验证,这个教程验证方法也很有用!这里 `ShuffleSplit()` 会创造10个(`'n_splits'`)混洗过的集合,每个集合中20%(`'test_size'`)的数据会被用作**验证集**。当你在实现的时候,想一想这跟 K-Fold 交叉验证有哪些相同点,哪些不同点? 在下方 `fit_model` 函数中,你需要做的是: - 使用 `sklearn.tree` 中的 [`DecisionTreeRegressor`](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html) 创建一个决策树的回归函数; - 将这个回归函数储存到 `'regressor'` 变量中; - 为 `'max_depth'` 创造一个字典,它的值是从1至10的数组,并储存到 `'params'` 变量中; - 使用 `sklearn.metrics` 中的 [`make_scorer`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html) 创建一个评分函数; - 将 `performance_metric` 作为参数传至这个函数中; - 将评分函数储存到 `'scoring_fnc'` 变量中; - 使用 `sklearn.model_selection` 中的 [`GridSearchCV`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) 创建一个网格搜索对象; - 将变量`'regressor'`, `'params'`, `'scoring_fnc'`, 和 `'cv_sets'` 作为参数传至这个对象中; - 将 `GridSearchCV` 存到 `'grid'` 变量中。 如果有同学对python函数如何传递多个参数不熟悉,可以参考这个MIT课程的[视频](http://cn-static.udacity.com/mlnd/videos/MIT600XXT114-V004200_DTH.mp4)。 ``` # TODO: Import 'make_scorer', 'DecisionTreeRegressor', and 'GridSearchCV' from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import make_scorer from sklearn.model_selection import GridSearchCV def fit_model(X, y): """ Performs grid search over the 'max_depth' parameter for a decision tree regressor trained on the input data [X, y]. """ # Create cross-validation sets from the training data cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0) # TODO: Create a decision tree regressor object regressor = DecisionTreeRegressor() # TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10 params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]} # TODO: Transform 'performance_metric' into a scoring function using 'make_scorer' scoring_fnc = make_scorer(performance_metric) # TODO: Create the grid search object grid = GridSearchCV(regressor,params,scoring=scoring_fnc,cv=cv_sets) # Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y) # Return the optimal model after fitting the data return grid.best_estimator_ ``` ### 做出预测 当我们用数据训练出一个模型,它现在就可用于对新的数据进行预测。在决策树回归函数中,模型已经学会对新输入的数据*提问*,并返回对**目标变量**的预测值。你可以用这个预测来获取数据未知目标变量的信息,这些数据必须是不包含在训练数据之内的。 ### 问题 9- 最优模型 *最优模型的最大深度(maximum depth)是多少?此答案与你在**问题 6**所做的猜测是否相同?* 运行下方区域内的代码,将决策树回归函数代入训练数据的集合,以得到最优化的模型。 ``` # Fit the training data to the model using grid search reg = fit_model(X_train, y_train) # Produce the value for 'max_depth' print "Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth']) ``` **Answer: ** 最好的模型的深度是4 ### 问题 10 - 预测销售价格 想像你是一个在波士顿地区的房屋经纪人,并期待使用此模型以帮助你的客户评估他们想出售的房屋。你已经从你的三个客户收集到以下的资讯: | 特征 | 客戶 1 | 客戶 2 | 客戶 3 | | :---: | :---: | :---: | :---: | | 房屋内房间总数 | 5 间房间 | 4 间房间 | 8 间房间 | | 社区贫困指数(%被认为是贫困阶层) | 17% | 32% | 3% | | 邻近学校的学生-老师比例 | 15:1 | 22:1 | 12:1 | *你会建议每位客户的房屋销售的价格为多少?从房屋特征的数值判断,这样的价格合理吗?* **提示:**用你在**分析数据**部分计算出来的统计信息来帮助你证明你的答案。 运行下列的代码区域,使用你优化的模型来为每位客户的房屋价值做出预测。 ``` # Produce a matrix for client data client_data = [[5, 17, 15], # Client 1 [4, 32, 22], # Client 2 [8, 3, 12]] # Client 3 # Show predictions for i, price in enumerate(reg.predict(client_data)): print "Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price) ``` **答案: ** - Client 1's home: \$403,025.00 - Client 2's home: \$237,478.72 - Client 3's home: \$931,636.36 从上面的预测结果来看,这样的价格还算合理,房间多的价格教贵,学生老师比小的,社区贫困指数也较低,说明和预期分析的差不多。而且整体符合之前的统计量,都在最大值和最小值之间, ### 敏感度 一个最优的模型不一定是一个健壮模型。有的时候模型会过于复杂或者过于简单,以致于难以泛化新增添的数据;有的时候模型采用的学习算法并不适用于特定的数据结构;有的时候样本本身可能有太多噪点或样本过少,使得模型无法准确地预测目标变量。这些情况下我们会说模型是欠拟合的。执行下方区域中的代码,采用不同的训练和测试集执行 `fit_model` 函数10次。注意观察对一个特定的客户来说,预测是如何随训练数据的变化而变化的。 ``` vs.PredictTrials(features, prices, fit_model, client_data) ``` ### 问题 11 - 实用性探讨 *简单地讨论一下你建构的模型能否在现实世界中使用?* **提示:** 回答几个问题,并给出相应结论的理由: - *1978年所采集的数据,在今天是否仍然适用?* - *数据中呈现的特征是否足够描述一个房屋?* - *模型是否足够健壮来保证预测的一致性?* - *在波士顿这样的大都市采集的数据,能否应用在其它乡镇地区?* **答案: ** - 1978年所采集的数据,现在应该不使用了,因为随着时代的发展有些特征已经不再是影响房价的主要因素,而可能又出现新的特征影响房价。 - 数据中呈现的特征我认为不足以描述一个房屋,因为除了这些因素以外,可能还存在着别的,比如面积,房屋的面积和房间的数量不是严格成正比的,长宽比,方形的房屋要比细长的好等。 - 我认为模型已经相当健壮,多次预测同一个房屋,价格相近。 - 像波士顿这种大都市采集的数据,不能应用到乡镇地区,因为大都市和乡镇有着不一样的特征。 最后,我认为该模型还不足以在现实世界中使用,还有一些缺陷。 ### 可选问题 - 预测北京房价 (本题结果不影响项目是否通过)通过上面的实践,相信你对机器学习的一些常用概念有了很好的领悟和掌握。但利用70年代的波士顿房价数据进行建模的确对我们来说意义不是太大。现在你可以把你上面所学应用到北京房价数据集中`bj_housing.csv`。 免责声明:考虑到北京房价受到宏观经济、政策调整等众多因素的直接影响,预测结果仅供参考。 这个数据集的特征有: - Area:房屋面积,平方米 - Room:房间数,间 - Living: 厅数,间 - School: 是否为学区房,0或1 - Year: 房屋建造时间,年 - Floor: 房屋所处楼层,层 目标变量: - Value: 房屋人民币售价,万 你可以参考上面学到的内容,拿这个数据集来练习数据分割与重排、定义衡量标准、训练模型、评价模型表现、使用网格搜索配合交叉验证对参数进行调优并选出最佳参数,比较两者的差别,最终得出最佳模型对验证集的预测分数。 ``` ### 你的代码 bj_data = pd.read_csv('bj_housing.csv') bj_prices = bj_data['Value'] bj_features = bj_data.drop('Value', axis = 1) print "Boston housing dataset has {} data points with {} variables each.".format(*bj_data.shape) X_train_bj, X_test_bj, y_train_bj, y_test_bj = train_test_split(bj_features, bj_prices, test_size=0.20, random_state=23) vs.ModelComplexity(X_train_bj, y_train_bj) def fit_model_bj(X, y): """ Performs grid search over the 'max_depth' parameter for a decision tree regressor trained on the input data [X, y]. """ # Create cross-validation sets from the training data cv_sets = ShuffleSplit(n_splits = 10, test_size = 0.20, random_state = 0) # TODO: Create a decision tree regressor object regressor = DecisionTreeRegressor() # TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10 params = {'max_depth':[1,2,3,4,5,6,7,8,9,10]} # TODO: Transform 'performance_metric' into a scoring function using 'make_scorer' scoring_fnc = make_scorer(performance_metric) # TODO: Create the grid search object grid = GridSearchCV(regressor,params,scoring=scoring_fnc,cv=cv_sets) # Fit the grid search object to the data to compute the optimal model grid = grid.fit(X, y) # Return the optimal model after fitting the data return grid.best_estimator_ reg_bj = fit_model_bj(X_train_bj, y_train_bj) # Produce the value for 'max_depth' print "Parameter 'max_depth' is {} for the optimal model.".format(reg_bj.get_params()['max_depth']) y_pre_bj = reg_bj.predict(X_test_bj) y_pre = reg.predict(X_test) print performance_metric(y_test_bj,y_pre_bj) print performance_metric(y_test,y_pre) ``` 你成功的用新的数据集构建了模型了吗?他能对测试数据进行验证吗?它的表现是否符合你的预期?交叉验证是否有助于提升你模型的表现? **答案:** 成功用新的数据集构建了模型,能对测试数据进行验证,表现一般,交叉验证有助于提升模型表现。 如果你是从零开始构建机器学习的代码会让你一时觉得无从下手。这时不要着急,你要做的只是查看之前写的代码,把每一行都看明白,然后逐步构建你的模型。当中遇到什么问题也可以在我们论坛寻找答案。也许你会发现你所构建的模型的表现并没有达到你的预期,这说明机器学习并非是一项简单的任务,构建一个表现良好的模型需要长时间的研究和测试。这也是我们接下来的课程中会逐渐学到的。
github_jupyter
``` import glob import random import sys from itertools import chain from pathlib import Path import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.metrics import accuracy_score, confusion_matrix from thundersvm import SVC from tqdm import tqdm np.random.seed(0) random.seed(0) ``` ### TEST TRAIN INDEX GENERATION FOR FOLDS ``` attribute_map = [ # {"Race": ["African", "Asian", "Indian", "Caucasian"]}, {"skintype": ["type1", "type2", "type3", "type4", "type5", "type6"]}, {"eye": ["normal", "narrow"]}, {"haircolor": ["red", "black", "gray", "brown", "blonde"]}, {"hairtype": ["straight", "wavy", "bald", "curly"]}, {"lips": ["small", "big"]}, {"nose": ["wide", "narrow"]}, ] vgg = pd.read_csv("/mnt/HDD/FaceDatasetCenter/metadata/VGGFace2_metadata_FDA.csv") vgg_test = vgg[vgg.type == "test"] vgg_test.head() vgg_image = pd.read_csv( "/mnt/HDD/FaceDatasetCenter/metadata/VGGFace2_image_meta_test.csv" ) vgg_image_test = vgg_image[vgg_image.type == "test"] vgg_image_test = vgg_image_test.sort_values(by="file") vgg_image_test.head() NUM_FOLDS = 3 TEST_SAMPLE_SIZE = 50 folds_folder = Path("folds") folds_folder.mkdir(exist_ok=True) def generate_fold(): all_folds = [] for fold in range(0, NUM_FOLDS): print(TEST_SAMPLE_SIZE * NUM_FOLDS) print(f"Fold {fold+1}") class_folds = {"train": [], "test": []} for i, group in vgg_image_test.groupby("Class_ID"): num_samples = group.shape[0] test_mask = np.zeros(num_samples, dtype=np.bool) if TEST_SAMPLE_SIZE * NUM_FOLDS > num_samples: start = fold * TEST_SAMPLE_SIZE end = start + TEST_SAMPLE_SIZE ix = [i % num_samples for i in range(start, end)] # print(f"ClassID: {i}, fold: {fold} - [{ix[0]}:{ix[-1]}]") else: class_fold_size = num_samples // NUM_FOLDS start = fold * class_fold_size end = start + class_fold_size ix = range(start, end) test_mask[ix] = True try: class_folds["test"].append( group[test_mask].sample(n=TEST_SAMPLE_SIZE, random_state=0) ) except: import pdb pdb.set_trace() class_folds["train"].append(group[~test_mask]) all_folds.append(class_folds) return all_folds all_folds = generate_fold() print(len(all_folds)) for i, fold in enumerate(all_folds): train = pd.concat(fold["train"]) test = pd.concat(fold["test"]) train.to_parquet(folds_folder / f"fold_{i}_train.pq", compression="GZIP") test.to_parquet(folds_folder / f"fold_{i}_test.pq", compression="GZIP") ``` ### Feature loading ``` features = np.load("features/vggface2_test_features.npy",allow_pickle=True) path_arr = np.load("features/vggface2_test_paths.npy",allow_pickle=True) meta = pd.DataFrame(path_arr, columns=["full_path"]) meta["file"] = meta.full_path.apply(lambda x: "/".join(Path(x).parts[-2:])) labels = list(map(lambda x: str(x).split("/")[-2], path_arr)) le = preprocessing.LabelEncoder() labels = le.fit_transform(labels) meta["y_test"] = labels meta = meta.merge(vgg_image_test,how='left',on='file') meta.head() #Train CODE def train(X,y): all_predictions = [] for i,fold in enumerate(range(0, NUM_FOLDS)): train_ixs = pd.read_parquet(folds_folder / f"fold_{i}_100_train.pq") test_ixs = pd.read_parquet(folds_folder / f"fold_{i}_100_test.pq") print(folds_folder / f"fold_{i}_train.pq") print(test_ixs.shape) print(meta[meta.file.isin(test_ixs.file)].index.shape) test_index = meta[meta.file.isin(test_ixs.file)].index train_index = meta[meta.file.isin(train_ixs.file)].index X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] print(X_test.shape,y_test.shape) print('SVM Training...') svm_model_linear = SVC(kernel="linear", C=1).fit(X_train, y_train) print("Starting prediction (The computer can be unresponsive during the prediction).") TEST_BATCH_SIZE = 1000 preds = [] ys=[] with tqdm(total=X_test.shape[0], file=sys.stdout) as pbar: for i in range(0, X_test.shape[0], TEST_BATCH_SIZE): X_test_batch = X_test[i : i + TEST_BATCH_SIZE] pred = svm_model_linear.predict(X_test_batch) preds.append(pred) # update tqdm pbar.set_description("Processed: %d" % (1 + i)) pbar.update(TEST_BATCH_SIZE) all_predictions.append(preds)c return all_predictions X = np.asarray(features, dtype=np.float32) y = labels pred_list = train(X,y) ap = np.asarray(pred_list) ap = ap.reshape(ap.shape[0],ap.shape[1]*ap.shape[2]) ap.shape # TEST CODE result_dic = [] for i, fold in enumerate(range(0, 3)): train_ixs = pd.read_parquet(folds_folder / f"fold_{i}_train.pq") test_ixs = pd.read_parquet(folds_folder / f"fold_{i}_test.pq") print(meta.shape,test_ixs.index) meta_test = meta[meta.file.isin(test_ixs.file)] print(meta_test.shape) test_index = meta_test.index y_test = y[test_index] meta_test["y_pred"] = ap[i] print("Overall Accuracy:", accuracy_score(meta_test["y_test"], meta_test["y_pred"])) print("Group initilization!") for attr in attribute_map: # for one value of one attribute for key, value in attr.items(): for val in value: subgroup = meta_test[meta_test[key] == val] score= accuracy_score(subgroup["y_test"], subgroup["y_pred"]) print( key, val, ":", score, subgroup.shape, ) result_dic.append([key,val,score,subgroup.shape[0]]) subgroup.shape results = pd.DataFrame(result_dic,columns=['feature','category','acc','size']) results["attribute_name"] = results["feature"] +'_'+ results["category"] results = results.groupby('attribute_name').mean().sort_values(by='attribute_name') results = results.reset_index() results['attribute'] = results.attribute_name.apply(lambda x:x.split('_')[0]) total_size = results.groupby('attribute').sum()['size'][0] print('total size',total_size) results['Ratio']=results['size'].apply(lambda x: x/total_size) results results.to_csv('face_identifiacation_attribute_based_results.csv',index=False) print("std:", np.std(results.acc.values,ddof=1) * 100) print("bias:", (1-results.acc.values.min()) / (1-results.acc.values.max())) (1.0-results.acc.values.min())/(1-results.acc.values.max()) 1-results.acc.values.max() results (1.0-results.acc.values.min()),(1-results.acc.values.max()) # print(results[['feature_name','acc']].to_latex()) results["Ratio"] = results["Ratio"].apply(lambda x: f"{100*x:.2f}") results["Acc"] = results["acc"].apply(lambda x: f"{100*x:.2f}") results["attribute_name"] = results["attribute_name"].str.replace("skintype", "") results["attribute_name"] = results["attribute_name"].str.replace("haircolor", "hair ") results["attribute_name"] = results["attribute_name"].str.replace("hairtype", "hair ") results["attribute_name"] = results["attribute_name"].str.title() results["attribute_name"] = results["attribute_name"].apply( lambda x: " ".join(x.split("_")[::-1]) ) results = results.sort_values(by='Acc') attribute_res = results[["attribute_name","Ratio", "Acc"]] attribute_res = pd.concat( [ attribute_res.iloc[:11].reset_index(drop=True), attribute_res.iloc[11:].reset_index(drop=True), ], axis=1, ignore_index=True, ) attribute_res.columns = ["Attribute Category", "Ratio (%)","Accuracy (%)", "Attribute Category(%)", "Ratio","Accuracy(%)"] attribute_res print( attribute_res.to_latex( index=False, caption="Table Caption", label="tab:fi1", na_rep="" ) ) print(type(all_predictions), type(y_s)) for y_test, y_pred in zip(y_s, all_predictions): print(type(y_pred), type(y_test)) y_pred = np.array(list(chain(*y_pred))) print("Overall Accuracy:", accuracy_score(y_test, y_pred)) feature_arr = np.asarray(features, dtype=np.float32) print(feature_arr[0][0], np.mean(feature_arr), np.std(feature_arr)) feature_arr = preprocessing.normalize(feature_arr) print(feature_arr[0][0], np.mean(feature_arr), np.std(feature_arr)) labels = list(map(lambda x: x.split("/")[-2], path_arr)) le = preprocessing.LabelEncoder() labels = le.fit_transform(labels) X = feature_arr y = labels # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) print("Data is ready!", X.shape, X.shape) sss = StratifiedShuffleSplit(n_splits=1, test_size=0.1, random_state=0) for train_index, test_index in sss.split(X, y): print("TRAIN:", type(train_index), "TEST:", type(test_index)) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] svm_model_linear = SVC(kernel="linear", C=20).fit(X_train, y_train) print("Training is completed.") # import datetime # timestr = datetime.datetime.now().isoformat().replace(":", ".") # svm_model_file = f"svm_model_{timestr}" # svm_model_linear.save_to_file(svm_model_file) # print(f"Saved model to: {svm_model_file}") import sys from itertools import chain from tqdm import tqdm print("Starting prediction (The computer can be unresponsive during the prediction).") TEST_BATCH_SIZE = 1000 preds = [] with tqdm(total=X_test.shape[0], file=sys.stdout) as pbar: for i in range(0, X_test.shape[0], TEST_BATCH_SIZE): X_test_batch = X_test[i : i + TEST_BATCH_SIZE] pred = svm_model_linear.predict(X_test_batch) preds.append(pred) # update tqdm pbar.set_description("Processed: %d" % (1 + i)) pbar.update(TEST_BATCH_SIZE) y_pred = np.array(list(chain(*preds))) print("Overall Accuracy:", accuracy_score(y_test, y_pred)) test_ixs["y_pred"] = y_pred.astype(np.int) test_ixs["y_test"] = y_test test_ixs = test_ixs.rename(columns={"subject": "Class_ID"}) test_data = test_ixs.merge(vgg_test, on="Class_ID", how="left") attribute_map = [ {"skintype": ["type1", "type2", "type3", "type4", "type5", "type6"]}, {"hairtype": ["straight", "wavy", "bald", "curly"]}, {"haircolor": ["red", "black", "grey", "brown", "blonde"]}, {"lips": ["small", "big"]}, {"eye": ["normal", "narrow"]}, {"nose": ["wide", "narrow"]}, ] print("Group initilization!") for attr in attribute_map: # for one value of one attribute for key, value in attr.items(): for val in value: subgroup = test_data[test_data[key] == val] print( key, val, ":", accuracy_score(subgroup["y_test"], subgroup["y_pred"]), subgroup.shape, ) # y_pred = svm_model_linear.predict(X_test) # features = np.load('features/unlearn_races_r50_feat_05ep.npz') # meta_data = pd.read_csv('metadata/VGGFace2_200_Subjects_Test_Images.csv') # features = np.load('../FeatureEncodingsRFW/senet50_ft_features.npy') # train_ixs = pd.read_csv('../train_test_split/rfwtest_train_indexes.csv') # test_ixs = pd.read_csv('../train_test_split/rfwtest_test_indexes.csv') features = features["arr_0"] feature_arr = np.asarray(features[:][:, :-1], dtype=np.float64) path_arr = features[:][:, -1] labels = list(map(lambda x: x.split("/")[0], path_arr)) le = preprocessing.LabelEncoder() labels = le.fit_transform(labels) X = pd.DataFrame(feature_arr) y = pd.Series(labels) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) print("SVM!") svm_model_linear = SVC(kernel="linear", C=1).fit(X_train, y_train) y_pred = svm_model_linear.predict(X_test) print("Overall Accuracy:", accuracy_score(y_test.values, y_pred)) print("Group initilization!") test_pathes = path_arr[y_test.index.values] for race in ["African", "Asian", "Caucasian", "Indian"]: for gender in ["m", "f"]: main_group = meta_data[ (meta_data.race == race) & (meta_data.gender == gender) & (meta_data.generated_version == "original") ] group_file = main_group.filename.values indexes = [] for el in group_file: loc = np.argwhere(test_pathes == el) if loc.size != 0: indexes.append(int(loc[0][0])) if len(indexes) > 0: indexes = np.asarray(indexes) print(race, gender) print( " accuracy:%d %.3f" % ( len(y_test.values[indexes]), accuracy_score(y_test.values[indexes], y_pred[indexes]), ) ) from sklearn.model_selection import GridSearchCV feature_arr = np.asarray(features[:][:, :-1], dtype=np.float64) path_arr = features[:][:, -1] labels = list(map(lambda x: x.split("/")[0], path_arr)) le = preprocessing.LabelEncoder() labels = le.fit_transform(labels) X = pd.DataFrame(feature_arr) y = pd.Series(labels) param_grid = [ {"C": [1, 10, 100, 1000], "kernel": ["linear"]}, {"C": [1, 10, 100, 1000], "gamma": [0.001, 0.0001], "kernel": ["rbf"]}, ] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) grid_search = GridSearchCV(SVC(), param_grid, cv=2) svm_model = grid_search.fit(X_train, y_train) print(grid_search.best_params_) # y_pred = svm_model.predict(X_test) # print('Overall Accuracy:',accuracy_score(y_test.values, y_pred)) # print('Group initilization!') # test_pathes = path_arr[y_test.index.values] # for race in ['African','Asian','Caucasian', 'Indian']: # for gender in ['f','m']: # main_group = meta_data[(meta_data.race == race) & (meta_data.gender== gender) & (meta_data.generated_version== 'original') ] # group_file = main_group.filename.values # indexes = [] # for el in group_file: # loc = np.argwhere(test_pathes==el) # if loc.size != 0: # indexes.append(int(loc[0][0])) # if len(indexes)>0: # indexes = np.asarray(indexes) # print(race,gender) # print(' accuracy:%d %.3f'%(len(y_test.values[indexes]), accuracy_score(y_test.values[indexes], y_pred[indexes]))) ``` SVM! Overall Accuracy: 0.5139621028636558 Group initilization! African m accuracy:1551 0.454 African f accuracy:1953 0.473 Asian m accuracy:1610 0.496 Asian f accuracy:1516 0.383 Caucasian m accuracy:1797 0.559 Caucasian f accuracy:1959 0.590 Indian m accuracy:1964 0.615 Indian f accuracy:1688 0.498
github_jupyter
# Matplotlib - Intro * **matplotlib** is a Python plotting library for producing publication quality figures * allows for interactive, cross-platform control of plots * makes it easy to produce static raster or vector graphics * gives the developer complete control over the appearance of their plots, while still being usable through a powerful defaults system * standard scientific plotting library * online documentnation is on [matplotlib.org](https://matplotlib.org/index.html), with lots of examples in the [gallery](https://matplotlib.org/gallery.html) * behaves similarly to Matlab ``` import matplotlib.pyplot as plt import numpy as np ``` To be efficient with **matplotlib**, you first need to understand its termonology. ## Parts of a Figure <img src="../../figures/matplotlib_figure_parts.png" style="height:90%; width:90%;"> ### Figure, Axes, Axis * **Figure** is the whole image, the top-level 'container' that holds all objects of an image. * **Axes** is the region of a **Figure** that displays your data. Most plotting occurs here! Very similar to a subplot * **Axes** contains **Axis** objects (x axis,y axis) which control the data limits. * **Figure** can have any number of **Axes**, but to be useful should have at least one. ``` fig = plt.figure() # Create a figure axes = fig.add_subplot(111) # add one Axes to Figure ``` Usually an **Axes** is set up with a call to `fig.add_subplot()`, `plt.subplot()`, or `plt.subplots()` The most flexible option is `plt.subplots()` ``` fig,axes = plt.subplots(2,3,figsize=(12,6)) # This will create a figure and 6 axes arranged in 2 rows, 3 columns ``` ### Line plots Lets draw two cosine functions of different amplitude on the same **Axes**. ``` # Create data X = np.linspace(-np.pi, np.pi, 100, endpoint=True) Y1 = np.cos(X) Y2 = 2*np.cos(X) # Plot data fig, axes = plt.subplots() axes.plot(X, Y1) axes.plot(X, Y2); ``` ** Tip: by adding a semicolon at the end of a function, the output is suppressed. ### Default and named colors ![](../figures/dflt_style_changes-1.png) **Exercise 0 (10 mins)**. The figure before is generated using the default settings. The code below shows these settings explicitly. Play with the values to explore their effect. For details on changing properties see [line plots on the matplotlib website](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html) ``` # Plot data (with explicit plotting settings) fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6,4)) axes.plot(X, Y1, color='C0', linewidth=5.0, linestyle='-',alpha=0.5) axes.plot(X, Y2, color='r', linewidth=3.0, linestyle='--') # Your code here # Sample solution # Plot data (with explicit plotting settings) fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(8,4)) axes.plot(X, Y1, color='r', linewidth=4, linestyle='--') axes.plot(X, Y2, color='b', linewidth=2, linestyle='-.') axes.set_xlim(-8, 8) axes.set_ylim(-3, 3) axes.set_xticks(np.linspace(-4,4,9,endpoint=True)) axes.set_yticks(np.linspace(-3,3,11,endpoint=True)); ``` **Exercise 1 (10 mins)**. Having integer numbers on the x axis here might divert reader's attention from the critical points of the graph. 1. Change **xticks** and **xticklabels** into multiples of $\pi$. Use `axes.set_xticks()` and `axes.set_xticklabels()`. \*\* Tip: use `np.pi` for **xticks** and '\$\pi$' for **xticklabels**. format strings in LaTeX by prepending 'r'ie `axes.set_xticklabels([r'$\pi$'])` ``` # Your code here # Solution # Change xticks, yticks and xticklabels fig, axes = plt.subplots() axes.plot(X, Y1); axes.plot(X, Y2); axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]); axes.set_yticks([-2, -1, 0, 1, 2]); axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']); ``` **Exersise 2 (5 mins)**. Add a legend. 1. Give both cosine functions a name by adding an extra keyword argument, a label, to `axes.plot()`. 2. Add a legend object to **Axes**. ``` # Your code here # Solution # Add a legend fig, axes = plt.subplots() axes.plot(X, Y1, label='cos(x)'); axes.plot(X, Y2, label='2cos(x)'); axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]); axes.set_yticks([-2, -1, 0, 1, 2]); axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']); axes.legend(loc='upper left', frameon=False); ``` **Exercise 3 (10 mins)**. Annotate an interesting point on a graph, for example, $2\cos(\frac{\pi}{4})$. 1. Add a single point to the graph by using `axes.plot(..., marker='o')`. 2. Use `axes.annotate(s, xy=..., xytext=...)` to add annotation. ** Tip: visit [annotations](https://matplotlib.org/users/annotations_intro.html). ``` # Your code here fig, axes = plt.subplots() axes.plot(X, Y1, label='cos(x)'); axes.plot(X, Y2, label='2cos(x)'); axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]); axes.set_yticks([-2, -1, 0, 1, 2]); axes.set_xticklabels(['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$']); axes.legend(loc='upper left', frameon=False); point = np.pi/4 axes.plot(point, 2*np.cos(point), marker='o'); axes.annotate(r'$2\cos(\frac{\pi}{4})=\sqrt{2}$', xy=(point, 2*np.cos(point)), xytext=(1, 1.5), fontsize=16); ``` ### Demonstration of bar() on NAO index data Bar plots are created in much the same way as line plots, with two arrays of equal size. Here we use `bar()` to plot the data on North Atlantic oscillation from the NWS Climate Prediction Center. Data source: http://www.cpc.ncep.noaa.gov/products/precip/CWlink/pna/nao.shtml Variable: monthly mean NAO index since January 1950 til March 2019. Data stored in text file in the following way: Year | Month | Value 1950 1 0.92000E+00 # Read NAO data ``` nao_yr, nao_mn, nao_val = np.loadtxt('../../data/nao_monthly.txt', unpack=True) # Quick look at the data fig, ax = plt.subplots(figsize=(25, 5)) ax.plot(nao_val); ``` Let's focus on the last 5 years and slice `nao_yr`, `nao_mn`, `nao_val` arrays accordingly. ``` # Slicing nao_yr_sub = nao_yr[-12*5:] nao_mn_sub = nao_mn[-12*5:] nao_val_sub = nao_val[-12*5:] # Create an array of month numbers nao_time = np.arange(len(nao_val_sub)) nao_time # Plot bar fig, ax = plt.subplots(figsize=(15,4)) ax.bar(nao_time, nao_val_sub) ax.set_title('NAO index') ax.grid(True) ``` ### Scatter plots * display data as a collection of points, each having the value of one variable determining the position on the horizontal axis and the value of the other variable determining the position on the vertical axis * colorcode the data points to display an additional variable * good for non-gridded data `scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, edgecolors=None, **kwargs)` ``` # Generate some data (circles of random diameter) N = 50 x = np.random.rand(N) y = np.random.rand(N) area = np.pi*(15*np.random.rand(N))**2 # 0 to 15 point radii colors = np.random.rand(N) # Plot scatter plt.scatter(x, y, s=area, c=colors); ``` ### Multiple subplots `plt.subplots()` is a function that creates a figure and a grid of subplots with a single call, while providing reasonable control over how the individual plots are created. ``` fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15,5)) # or plt.subplots(2,3,figsize=(15,5)) axes[0,0].set_title('subplot[0,0]', fontsize=18); axes[0,1].set_title('subplot[0,1]', fontsize=18); axes[0,2].set_title('subplot[0,2]', fontsize=18); axes[1,0].set_title('subplot[1,0]', fontsize=18); axes[1,1].set_title('subplot[1,1]', fontsize=18); axes[1,2].set_title('subplot[1,2]', fontsize=18); for ax in axes.flat: # you can loop over axes ax.set_xticks([]); ax.set_yticks([]); ``` ### Subplots with real data To practice our plotting we are going to work with data from the NOAA ESRL Carbon Cycle Cooperative Global Air Sampling Network. Source: https://www.esrl.noaa.gov/gmd/dv/data/ Monthly averages of atmospheric carbon dioxide ($CO_2$) and methane ($CH_4$) Stations: * CGO = Cape Grim, Tasmania, Australia * MHD = Mace Head, County Galway, Ireland Units: * $CO_2$ - ppm * $CH_4$ - ppb Data stored in a text file. The top row states the number of header lines in the file. No title headers. The actual data is ogranized as following: |Station code | Year | Month | Measurement| | :------------- | :----------: | :----------| :---------- | |CGO | 1984 | 4 | 341.63 | #### Read data from a text file The simplest way to load data from a text file in `numpy` is to use `np.loadtxt()` function. ``` # np.loadtxt() # hit Shift+Tab+Tab ``` This function has a lot parameters that you can adjuct to fit your data format. Here we use only: `np.loadtxt(fname, skiprows=..., usecols=..., unpack=...)` ``` data = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', skiprows=68, usecols=(1, 2, 3)) data ``` If we want to have three separate arrays for year, month and value, we can set `unpack=True` and store the output from `np.loadtxt()` function in three separate arrays. ``` year, month, value = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', skiprows=68, usecols=(1, 2, 3), unpack=True) year[0:8] month[0:8] value[0:8] ``` #### Kwargs * remember from yesterday, you can store any number of keyword arguments in a dictionary, and later unpack it when calling a function ``` # Kwargs read_data_kwargs = dict(skiprows=68, usecols=(1, 2, 3), unpack=True) # Read data # CO2 cgo_co2_yr, cgo_co2_mn, cgo_co2_val = np.loadtxt('../../data/co2_cgo_surface-flask_1_ccgg_month.txt', **read_data_kwargs) mhd_co2_yr, mhd_co2_mn, mhd_co2_val = np.loadtxt('../../data/co2_mhd_surface-flask_1_ccgg_month.txt', **read_data_kwargs) # CH4 cgo_ch4_yr, cgo_ch4_mn, cgo_ch4_val = np.loadtxt('../../data/ch4_cgo_surface-flask_1_ccgg_month.txt', **read_data_kwargs) mhd_ch4_yr, mhd_ch4_mn, mhd_ch4_val = np.loadtxt('../../data/ch4_mhd_surface-flask_1_ccgg_month.txt', **read_data_kwargs) ``` We'll find out how to properly plot on a time axis soon! For now, create dummy time arrays by some arithmetic to numpy arrays. ``` cgo_co2_time_dummy = cgo_co2_yr*12 + cgo_co2_mn mhd_co2_time_dummy = mhd_co2_yr*12 + mhd_co2_mn cgo_ch4_time_dummy = cgo_ch4_yr*12 + cgo_ch4_mn mhd_ch4_time_dummy = mhd_ch4_yr*12 + mhd_ch4_mn ``` **Exercise 4a (20 mins)**. Construct two subplots using the arrays created above. Add titles, x and y labels, legend. If you have time, play with optional arguments of `plot()` and try to use **kwargs**. The desired outcome is something like this (time on x axis will follow in part b): <img src="../../figures/subplots_example.png"> ``` # Your code here # Solution # plt.rcParams['mathtext.default'] = 'regular' cgo_kwargs = dict(label='Cape Grim', color='C3', linestyle='-') mhd_kwargs = dict(label='Mace Head', color='C7', linestyle='-') fig, axes = plt.subplots(nrows=2, figsize=(9,9), sharex=True) axes[0].plot(cgo_co2_time_dummy, cgo_co2_val, **cgo_kwargs) axes[1].plot(cgo_ch4_time_dummy, cgo_ch4_val, **cgo_kwargs) axes[0].plot(mhd_co2_time_dummy, mhd_co2_val, **mhd_kwargs) axes[1].plot(mhd_ch4_time_dummy, mhd_ch4_val, **mhd_kwargs) axes[0].set_title('$CO_{2}$') axes[1].set_title('$CH_{4}$') axes[0].set_ylabel('ppm') axes[1].set_ylabel('ppb') axes[0].legend(); #fig.savefig('../../figures/subplots_example.png',bbox_inches='tight') ``` #### Datetime * `datetime` module helps to work with time arrays ``` from datetime import datetime datetime.now() a_date = datetime(2019, 5, 23) a_date python_course_dates = [datetime(2019, 5, i) for i in [22, 23, 24]] python_course_dates ``` Let's apply it to our arrays. ``` # Using list comprehension cgo_co2_time = [datetime(int(i), int(j), 1) for i, j in zip(cgo_co2_yr, cgo_co2_mn)] # Same as in previous cell but using a for loop cgo_co2_time = [] for i, j in zip(cgo_co2_yr, cgo_co2_mn): cgo_co2_time.append(datetime(int(i), int(j), 1)) mhd_co2_time = [datetime(int(i), int(j), 1) for i, j in zip(mhd_co2_yr, mhd_co2_mn)] cgo_ch4_time = [datetime(int(i), int(j), 1) for i, j in zip(cgo_ch4_yr, cgo_ch4_mn)] mhd_ch4_time = [datetime(int(i), int(j), 1) for i, j in zip(mhd_ch4_yr, mhd_ch4_mn)] ``` <b>Exercise 4b.</b> Improve your solution to exercise 4a by using the newly created datetime arrays. Note how matplotlib understands the datetime format. ``` # Solution # plt.rcParams['mathtext.default'] = 'regular' cgo_kwargs = dict(label='Cape Grim', color='C3', linestyle='-') mhd_kwargs = dict(label='Mace Head', color='C7', linestyle='-') fig, axes = plt.subplots(nrows=2, figsize=(9,9), sharex=True) axes[0].plot(cgo_co2_time, cgo_co2_val, **cgo_kwargs) axes[1].plot(cgo_ch4_time, cgo_ch4_val, **cgo_kwargs) axes[0].plot(mhd_co2_time, mhd_co2_val, **mhd_kwargs) axes[1].plot(mhd_ch4_time, mhd_ch4_val, **mhd_kwargs) axes[0].set_title('$CO_{2}$') axes[1].set_title('$CH_{4}$') axes[0].set_ylabel('ppm') axes[1].set_ylabel('ppb') axes[0].legend(); #fig.savefig('../../figures/subplots_example.png',bbox_inches='tight') ``` --- --- ## Plotting 2D data: contour (and contourf) plots ``` import matplotlib.pyplot as plt import numpy as np ``` * `contour()` and `contourf()` draw contour lines and filled contours, respectively * good for 2D gridded data ** Note: `contourf()` differs from the Matlab version in that it does not draw the polygon edges. To draw edges, add line contours with calls to `contour()`. `contour(Z)` - make a contour plot of an array Z. The level values are chosen automatically, axes will refer to indices in the array. `contour(X, Y, Z)` - X, Y specify the (x, y) coordinates of the surface `contour(X, Y, Z, N)` - contour up to N automatically-chosen levels `contour(X, Y, Z, [level1, level2])` - contour on specific levels, e.g. level1, level2. ``` # Let's create a function to generate some data def fun(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) # Create a regular (x,y) grid n = 200 x1d = np.linspace(-3,3,n) y1d = np.linspace(-3,3,n) X, Y = np.meshgrid(x1d, y1d) # repeat x y times and y x times # Calculate the data data = fun(X,Y) # A simple example first: plt.contour(data); #plt.contour(X, Y, data); # Plot subplots using contour and contourf fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4)) ax1.contour(X, Y, data, 10); ax2.contourf(X, Y, data, 10); #ax3.contour(X, Y, data, 10, colors='k'); #ax3.contourf(X, Y, data, 10); ``` ### How to add a colorbar? When adding a **colorbar**, it needs to know the relevant *axes* and *mappable* content - especially when working with subplots or layered figures. Note that a colorbar will also have its own axes properties... We tell matplotlib which plotted values to use for the colorbar content with: `fig.colorbar(mappable, ax=ax_no)` ``` # Plot contour and contourf with colorbars # By default matplotlib contours negative values with a dashed line. This behaviour can be changed with rcparams: #plt.rcParams['contour.negative_linestyle']= 'solid' # Reset to default with `= 'dashed'` fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4)) ax1.contour(X, Y, data, 10) mappable2 = ax2.contourf(X, Y, data, 10) #mappable2.set_clim(0,1) ax3.contour(X, Y, data, 10, colors='k') mappable3 = ax3.contourf(X, Y, data, 10) fig.colorbar(mappable2, ax=ax2) fig.colorbar(mappable3, ax=ax3); ``` #### Mini exercise: 10 min Play around with the lines of code in the cell above, and see how the figure changes, e.g. * What happens if you try to add a colorbar to ax1? *Answer: Lines appear rather than blocks of colour.* * Try plotting chosen contour levels for ax2 or ax3, and see what happens to the colorbar? *Answer: The max/min levels will set the limits of your colorbar. Values outside these limits will appear white unless you specify `extend='max'`, `'min'` or `'both'`.* ``` # Examples: fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 4)) mappable1 = ax1.contour(X, Y, data, 10) mappable2 = ax2.contourf(X, Y, data, levels=np.linspace(-0.5,0.5,11)) #mappable2.set_clim(0,1) ax3.contour(X, Y, data, 10, colors='k') mappable3 = ax3.contourf(X, Y, data, 10, levels=np.linspace(-0.5,0.5,11), extend='both') fig.colorbar(mappable1, ax=ax1) fig.colorbar(mappable2, ax=ax2) fig.colorbar(mappable3, ax=ax3); ``` --- ## Final matplotlib exercise (20 mins) Reproduce the figure below by using `contourf()` to show a map of sea surface temperature, and `plot()` for a zonally averaged temperature curve. The code for loading and processing the data is provided below, so you can focus on producing the figure... Data source: https://podaac-tools.jpl.nasa.gov/las/UI.vm Dataset: AMSR-E Level 3 Sea Surface Temperature for Climate Model Comparison. Variable: Sea Surface Temperature (K). Time : 16-JUN-2002 00:00. Spacial resolution: 1$^{\circ}$x1$^{\circ}$, 361 by 180 points (longitude by latitude). Total Number of Records: 64980. All the data processing is handled for you here, with the following steps: * Read the data using `np.genfromtxt` (very similar to `np.loadtxt`, but can handle missing values). * Reshape the 1D data into a 2D lat-lon grid. * Calculate the zonal-mean temperature. ``` # Read modelling sst data lon_raw, lat_raw, sst_raw = np.genfromtxt('../../data/AMSR-E_Level_3_Sea_Surface_Temperature_for_Climate_Model_Comparison.csv', delimiter=',', skip_header=10, missing_values='-1.E+34', usemask=True, usecols=(2, 3, 4), unpack=True) # Reshape into a grid of sst with corresponding lat and lon coordinates lon = np.unique(lon_raw) lat = np.unique(lat_raw) sst = np.reshape(sst_raw,(len(lat),len(lon))) # Calculate the zonal-mean temperature here temp_zonal_mean = np.nanmean(sst,1); ``` Now, plot the data... ``` # Example Solution # == Increasing the font size to improve readability == plt.rcParams.update({"font.size": 20}) # == set the subplot layout == fig, ax = plt.subplots(1, 2, figsize=(12,8), gridspec_kw={"width_ratios":[8, 1]}, sharey = True) fig.subplots_adjust(wspace=0.05) # plot the map on axis 0 cb = ax[0].contourf(lon, lat, sst, cmap='inferno') ax[0].set_title('Sea surface temperature 16 June 2002') ax[0].set(xlabel='Longitude', ylabel='Latitude', ylim = [-80,80]) # plot the zonal mean on axis 1 ax[1].plot(temp_zonal_mean, lat) ax[1].set(xlabel='Mean temp') # create a separate whole-width axis (cbar_ax) for the colorbar at the bottom # -> set position relative to other axes. fig.subplots_adjust(bottom=0.2) pos0 = ax[0].get_position() # [x0=left, y0=bottom, x1=right, y1=top] pos1 = ax[1].get_position() cbar_ax = fig.add_axes([pos0.x0, 0.08, pos1.x1-pos0.x0, 0.03]) # [left, bottom, width, height] fig.colorbar(cb, cax=cbar_ax, label=r"Temperature (K)", orientation='horizontal'); #fig.savefig('../../figures/matplotlib_map.png', dpi=300, bbox_inches='tight') ``` **NB. There is no "right" answer - you may find other ways to produce the same figure (or something better!)** ## References: * https://matplotlib.org/faq/usage_faq.html * http://www.labri.fr/perso/nrougier/teaching/matplotlib/matplotlib.html * https://matplotlib.org/stable/index.html * https://matplotlib.org/stable/gallery/index.html * https://github.com/matplotlib/cheatsheets
github_jupyter
``` # Let printing work the same in Python 2 and 3 from __future__ import print_function # Turning on inline plots -- just for use in ipython notebooks. import matplotlib matplotlib.use('nbagg') import numpy as np import matplotlib.pyplot as plt ``` # Artists Anything that can be displayed in a Figure is an [`Artist`](http://matplotlib.org/users/artists.html). There are two main classes of Artists: primatives and containers. Below is a sample of these primitives. ``` """ Show examples of matplotlib artists http://matplotlib.org/api/artist_api.html Several examples of standard matplotlib graphics primitives (artists) are drawn using matplotlib API. Full list of artists and the documentation is available at http://matplotlib.org/api/artist_api.html Copyright (c) 2010, Bartosz Telenczuk License: This work is licensed under the BSD. A copy should be included with this source code, and is also available at http://www.opensource.org/licenses/bsd-license.php """ from matplotlib.collections import PatchCollection import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.lines as mlines fig, ax = plt.subplots(1, 1, figsize=(7,7)) # create 3x3 grid to plot the artists pos = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1) patches = [] # add a circle art = mpatches.Circle(pos[:, 0], 0.1, ec="none") patches.append(art) plt.text(pos[0, 0], pos[1, 0] - 0.15, "Circle", ha="center", size=14) # add a rectangle art = mpatches.Rectangle(pos[:, 1] - [0.025, 0.05], 0.05, 0.1, ec="none") patches.append(art) plt.text(pos[0, 1], pos[1, 1] - 0.15, "Rectangle", ha="center", size=14) # add a wedge wedge = mpatches.Wedge(pos[:, 2], 0.1, 30, 270, ec="none") patches.append(wedge) plt.text(pos[0, 2], pos[1, 2] - 0.15, "Wedge", ha="center", size=14) # add a Polygon polygon = mpatches.RegularPolygon(pos[:, 3], 5, 0.1) patches.append(polygon) plt.text(pos[0, 3], pos[1, 3] - 0.15, "Polygon", ha="center", size=14) #add an ellipse ellipse = mpatches.Ellipse(pos[:, 4], 0.2, 0.1) patches.append(ellipse) plt.text(pos[0, 4], pos[1, 4] - 0.15, "Ellipse", ha="center", size=14) #add an arrow arrow = mpatches.Arrow(pos[0, 5] - 0.05, pos[1, 5] - 0.05, 0.1, 0.1, width=0.1) patches.append(arrow) plt.text(pos[0, 5], pos[1, 5] - 0.15, "Arrow", ha="center", size=14) # add a path patch Path = mpath.Path verts = np.array([ (0.158, -0.257), (0.035, -0.11), (-0.175, 0.20), (0.0375, 0.20), (0.085, 0.115), (0.22, 0.32), (0.3, 0.005), (0.20, -0.05), (0.158, -0.257), ]) verts = verts - verts.mean(0) codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.LINETO, Path.CURVE4, Path.CURVE4, Path.CURVE4, Path.CLOSEPOLY] path = mpath.Path(verts / 2.5 + pos[:, 6], codes) patch = mpatches.PathPatch(path) patches.append(patch) plt.text(pos[0, 6], pos[1, 6] - 0.15, "PathPatch", ha="center", size=14) # add a fancy box fancybox = mpatches.FancyBboxPatch( pos[:, 7] - [0.025, 0.05], 0.05, 0.1, boxstyle=mpatches.BoxStyle("Round", pad=0.02)) patches.append(fancybox) plt.text(pos[0, 7], pos[1, 7] - 0.15, "FancyBoxPatch", ha="center", size=14) # add a line x,y = np.array([[-0.06, 0.0, 0.1], [0.05,-0.05, 0.05]]) line = mlines.Line2D(x+pos[0, 8], y+pos[1, 8], lw=5.) plt.text(pos[0, 8], pos[1, 8] - 0.15, "Line2D", ha="center", size=14) collection = PatchCollection(patches) ax.add_collection(collection) ax.add_line(line) ax.set_axis_off() plt.show() ``` Containers are objects like *Figure* and *Axes*. Containers are given primitives to draw. The plotting functions we discussed back in Parts 1 & 2 are convenience functions that generate these primitives and places them into the appropriate containers. In fact, most of those functions will return artist objects (or a list of artist objects) as well as store them into the appropriate axes container. As discussed in Part 3, there is a wide range of properties that can be defined for your plots. These properties are processed and applied to their primitives. Ultimately, you can override anything you want just by directly setting a property to the object itself. ``` fig, ax = plt.subplots(1, 1) lines = plt.plot([1, 2, 3, 4], [1, 2, 3, 4], 'b', [1, 2, 3, 4], [4, 3, 2, 1], 'r') lines[0].set(linewidth=5) lines[1].set(linewidth=10, alpha=0.7) plt.show() ``` To see what properties are set for an artist, use [`getp()`](http://matplotlib.org/api/artist_api.html#matplotlib.artist.getp) ``` fig = plt.figure() print(plt.getp(fig.patch)) plt.close(fig) ``` # Collections In addition to the Figure and Axes containers, there is another special type of container called a [`Collection`](http://matplotlib.org/api/collections_api.html). A Collection usually contains a list of primitives of the same kind that should all be treated similiarly. For example, a [`CircleCollection`](http://matplotlib.org/api/collections_api.html#matplotlib.collections.CircleCollection) would have a list of [`Circle`](http://matplotlib.org/api/artist_api.html#matplotlib.patches.Circle) objects all with the same color, size, and edge width. Individual property values for artists in the collection can also be set (in some cases). ``` from matplotlib.collections import LineCollection fig, ax = plt.subplots(1, 1) # A collection of 3 lines lc = LineCollection([[(4, 10), (16, 10)], [(2, 2), (10, 15), (6, 7)], [(14, 3), (1, 1), (3, 5)]]) lc.set_color('r') lc.set_linewidth(5) ax.add_collection(lc) ax.set_xlim(0, 18) ax.set_ylim(0, 18) plt.show() # Now set individual properties in a collection fig, ax = plt.subplots(1, 1) lc = LineCollection([[(4, 10), (16, 10)], [(2, 2), (10, 15), (6, 7)], [(14, 3), (1, 1), (3, 5)]]) lc.set_color(['r', 'blue', (0.2, 0.9, 0.3)]) lc.set_linewidth([4, 3, 6]) ax.add_collection(lc) ax.set_xlim(0, 18) ax.set_ylim(0, 18) plt.show() ``` There are other kinds of collections that are not just simply a list of primitives, but are Artists in their own right. These special kinds of collections take advantage of various optimizations that can be assumed when rendering similar or identical things. You use these collections all the time whether you realize it or not! Markers are implemented this way (so, whenever you do `plot()` or `scatter()`, for example). ``` from matplotlib.collections import RegularPolyCollection fig, ax = plt.subplots(1, 1) offsets = np.random.rand(20, 2) collection = RegularPolyCollection( numsides=5, # a pentagon sizes=(150,), offsets=offsets, transOffset=ax.transData, ) ax.add_collection(collection) plt.show() ``` ## Exercise 5.1 Give yourselves 4 gold stars! Hint: [StarPolygonCollection](http://matplotlib.org/api/collections_api.html#matplotlib.collections.StarPolygonCollection) ``` %load exercises/5.1-goldstar.py from matplotlib.collections import StarPolygonCollection fig, ax = plt.subplots(1, 1) collection = StarPolygonCollection(5, offsets=[(0.5, 0.5)], transOffset=ax.transData) ax.add_collection(collection) plt.show() ```
github_jupyter
``` import pandas as pd import warnings warnings.filterwarnings("ignore") import seaborn as sns import matplotlib.pyplot as plt sns.set(style="white", color_codes=True) iris = pd.read_csv("iris.csv") # the iris dataset is now a Pandas DataFrame iris.head() iris["Species"].value_counts() # .plot extension from pandas framework is used to make scatterplots iris.plot(kind="scatter", x="SepalLengthCm", y="SepalWidthCm") #A seaborn jointplot shows bivariate scatterplots and univariate histograms sns.jointplot(x="SepalLengthCm", y="SepalWidthCm", data=iris, size=5) #Seaborn's FacetGrid is used to color the scatterplot by species sns.FacetGrid(iris, hue="Species", size=5) \ .map(plt.scatter, "SepalLengthCm", "SepalWidthCm") \ .add_legend() #Boxplots are used to examine the individual feature in seaborn. sns.boxplot(x="Species", y="PetalLengthCm", data=iris) #One way to extend this plot is by adding a layer of individual points on top of it through Seaborn's striplot. #We'll use jitter=True so that all the points don't fall in single vertical lines above the species ax = sns.boxplot(x="Species", y="PetalLengthCm", data=iris) ax = sns.stripplot(x="Species", y="PetalLengthCm", data=iris, jitter=True, edgecolor="gray") #A violin plot combines the benefits of the previous two plots and simplifies them denser regions of the data are fatter, and sparser thiner in a violin plot sns.violinplot(x="Species", y="PetalLengthCm", data=iris, size=6) #A final seaborn plot useful for looking at univariate relations is the kdeplot, which creates and visualizes a kernel density estimate of the underlying feature sns.FacetGrid(iris, hue="Species", size=6) \ .map(sns.kdeplot, "PetalLengthCm") \ .add_legend() #Another useful seaborn plot is the pairplot, which shows the bivariate relation between each pair of features. #From the pairplot, we'll see that the Iris-setosa species is separataed from the other two across all feature combinations sns.pairplot(iris.drop("Id", axis=1), hue="Species", size=3) #The diagonal elements in a pairplot show the histogram by default. #We can update these elements to show other things, such as a kde. sns.pairplot(iris.drop("Id", axis=1), hue="Species", size=3, diag_kind="kde") #Boxplot with Pandas iris.drop("Id", axis=1).boxplot(by="Species", figsize=(12, 6)) #One cool more sophisticated technique pandas has available is called Andrews Curves. #Andrews Curves involve using attributes of samples as coefficients for Fourier series and then plotting these from pandas.plotting import andrews_curves andrews_curves(iris.drop("Id", axis=1), "Species") #Another multivariate visualization technique pandas has is parallel_coordinates. #Parallel coordinates plots each feature on a separate column & then draws lines connecting the features for each data sample from pandas.plotting import parallel_coordinates parallel_coordinates(iris.drop("Id", axis=1), "Species") #A final multivariate visualization technique pandas has is radviz which puts each feature as a point on a 2D plane, #and then simulates having each sample attached to those points through a spring weighted by the relative value for that feature from pandas.plotting import radviz radviz(iris.drop("Id", axis=1), "Species") ```
github_jupyter
# Train with Scikit-learn on AzureML ## Prerequisites * Install the Azure Machine Learning Python SDK and create an Azure ML Workspace ``` import time #check core SDK version import azureml.core print("SDK version:", azureml.core.VERSION) # data_dir = '../../data_airline_updated' ``` ## Initialize workspace Initialize a [Workspace](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#workspace) object from the existing workspace you created in the Prerequisites step. `Workspace.from_config()` creates a workspace object from the details stored in `config.json`. ``` from azureml.core.workspace import Workspace # if a locally-saved configuration file for the workspace is not available, use the following to load workspace # ws = Workspace(subscription_id=subscription_id, resource_group=resource_group, workspace_name=workspace_name) ws = Workspace.from_config() print('Workspace name: ' + ws.name, 'Azure region: ' + ws.location, 'Subscription id: ' + ws.subscription_id, 'Resource group: ' + ws.resource_group, sep = '\n') datastore = ws.get_default_datastore() print("Default datastore's name: {}".format(datastore.name)) # datastore.upload(src_dir='../../data_airline_updated', target_path='data_airline', overwrite=False, show_progress=True) path_on_datastore = 'data_airline' ds_data = datastore.path(path_on_datastore) print(ds_data) ``` ## Create AmlCompute You will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#compute-target) for training your model. In this tutorial, we use Azure ML managed compute ([AmlCompute](https://docs.microsoft.com/azure/machine-learning/service/how-to-set-up-training-targets#amlcompute)) for our remote training compute resource. As with other Azure services, there are limits on certain resources (e.g. AmlCompute) associated with the Azure Machine Learning service. Please read [this article](https://docs.microsoft.com/en-us/azure/machine-learning/service/how-to-manage-quotas) on the default limits and how to request more quota. If we could not find the cluster with the given name, then we will create a new cluster here. We will create an `AmlCompute` cluster of `Standard_DS5_v2` GPU VMs. ``` from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException #choose a name for your cluster cpu_cluster_name = "cpu-cluster" if cpu_cluster_name in ws.compute_targets: cpu_cluster = ws.compute_targets[cpu_cluster_name] if cpu_cluster and type(cpu_cluster) is AmlCompute: print('Found compute target. Will use {0} '.format(cpu_cluster_name)) else: print("creating new cluster") provisioning_config = AmlCompute.provisioning_configuration(vm_size = 'Standard_DS5_v2', max_nodes = 1) #create the cluster cpu_cluster = ComputeTarget.create(ws, cpu_cluster_name, provisioning_config) #can poll for a minimum number of nodes and for a specific timeout. #if no min node count is provided it uses the scale settings for the cluster cpu_cluster.wait_for_completion(show_output=True, min_node_count=None, timeout_in_minutes=20) #use get_status() to get a detailed status for the current cluster. print(cpu_cluster.get_status().serialize()) ``` ## Train model on the remote compute Now that you have your data and training script prepared, you are ready to train on your remote compute. Create a directory that will contain all the necessary code from your local machine that you will need access to on the remote resource. This includes the training script and any additional files your training script depends on. ``` import os project_folder = './train_sklearn' os.makedirs(project_folder, exist_ok=True) ``` ### Prepare training script Now you will need to create your training script. We log the parameters and the highest accuracy the model achieves: ```python run.log('Accuracy', np.float(accuracy)) ``` These run metrics will become particularly important when we begin hyperparameter tuning our model in the "Tune model hyperparameters" section. Once your script is ready, copy the training script `train_sklearn_RF.py` into your project directory. ``` import shutil shutil.copy('train_sklearn_RF.py', project_folder) ``` ### Create an experiment Create an [Experiment](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecture#experiment) to track all the runs in your workspace. ``` from azureml.core import Experiment experiment_name = 'train_sklearn' experiment = Experiment(ws, name=experiment_name) ``` ### Create a scikit-learn estimator ``` from azureml.train.sklearn import SKLearn script_params = { '--data_dir': ds_data.as_mount(), '--n_estimators': 100, '--max_depth': 8, '--max_features': 0.6, } estimator = SKLearn(source_directory=project_folder, script_params=script_params, compute_target=cpu_cluster, entry_script='train_sklearn_RF.py', pip_packages=['pyarrow']) ``` The `script_params` parameter is a dictionary containing the command-line arguments to your training script `entry_script`. ### Submit job Run your experiment by submitting your estimator object. Note that this call is asynchronous. ``` run = experiment.submit(estimator) ``` ## Monitor your run Monitor the progress of the run with a Jupyter widget.The widget is asynchronous and provides live updates every 10-15 seconds until the job completes. ``` from azureml.widgets import RunDetails RunDetails(run).show() # run.cancel() ```
github_jupyter
``` import warnings from itertools import product import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from graspy.plot import heatmap from graspy.simulations import er_np, sbm from graspy.utils import symmetrize from joblib import Parallel, delayed from scipy.stats import ttest_ind, wilcoxon, mannwhitneyu, truncnorm warnings.filterwarnings("ignore") %matplotlib inline def generate_pop(m, var_1, var_2, seed, block_1 = 5, block_2=15): np.random.seed(seed) n = [block_1, block_2] p = [ [1, 1], [1, 1] ] sd_1 = np.sqrt(var_1) sd_2 = np.sqrt(var_2) wt_func = [ [truncnorm.rvs, truncnorm.rvs], [truncnorm.rvs, truncnorm.rvs] ] wt_args_1 = [ [dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed), dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed)], [dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed), dict(a=-1/sd_1, b=1/sd_1, scale=sd_1, random_state=seed)], ] wt_args_2 = [ [dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed), dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed)], [dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed), dict(a=-1/sd_2, b=1/sd_2, scale=sd_2, random_state=seed)], ] pop_1 = np.array([sbm(n, p, wt=wt_func, wtargs=wt_args_1) for _ in range(m)]) pop_2 = np.array([sbm(n, p, wt=wt_func, wtargs=wt_args_2) for _ in range(m)]) return pop_1, pop_2 def compute_statistic(test, pop1, pop2): if test.__name__ == 'ttest_ind': test_statistics, _ = ttest_ind(pop1, pop2, axis=0) np.nan_to_num(test_statistics, copy=False) else: n = pop1.shape[-1] test_statistics = np.zeros((n, n)) for i in range(n): for j in range(i, n): x_ij = pop1[:, i, j] y_ij = pop2[:, i, j] if np.array_equal(x_ij, y_ij): test_statistics[i, j] = 0 else: tmp, pval = test(x_ij, y_ij) test_statistics[i, j] = tmp test_statistics = symmetrize(test_statistics) return test_statistics def compute_pr_at_k(different_n, k, test_statistics, test): n = test_statistics.shape[0] labels = np.zeros((n, n)) labels[0:different_n, 0:different_n] = 1 triu_idx = np.triu_indices_from(test_statistics, k=1) test_statistics_ = np.abs(test_statistics[triu_idx]) labels_ = labels[triu_idx] if test.__name__ == 'ttest_ind': idx = np.argsort(test_statistics_)[::-1] else: idx = np.argsort(test_statistics_) sorted_labels = labels_[idx] precision_at_k = sorted_labels[:k].mean() recall_at_k = sorted_labels[:k].sum() / sorted_labels.sum() return precision_at_k, recall_at_k def compute_trustworthiness(pvals): idx = np.triu_indices(pvals.shape[0], k=1) res = pvals[idx] fraction_correct = (res <=0.05).mean() all_correct = np.all(res <= 0.05) return fraction_correct, all_correct def run_experiment(m, var_1, var_2, seed, reps): tests = ttest_ind, wilcoxon, mannwhitneyu precisions = [] recalls = [] for i in range(reps): tmp_precisions = [] tmp_recalls = [] pop1, pop2 = generate_pop(m=m, var_1=var_1, var_2=var_2, seed = seed+i) for test in tests: test_statistics = compute_statistic(test, pop1, pop2) for k in range(1, 11): precision, recall = compute_pr_at_k(5, k, test_statistics, test) tmp_precisions.append(precision) tmp_recalls.append(recall) precisions.append(tmp_precisions) recalls.append(tmp_recalls) precisions = np.array(precisions).mean(axis=0) recalls = np.array(recalls).mean(axis=0) to_append = [var_1, var_2, m, *precisions, *recalls] return to_append spacing = 50 delta = 0.05 var_1s = np.linspace(1, 3, spacing) var_2s = np.ones(spacing) ms = np.linspace(0, 500, spacing +1).astype(int)[1:] reps=100 args = [ (m, var_1, var_2, seed*reps, reps) for seed, (m, (var_1, var_2)) in enumerate(product(ms, zip(var_1s, var_2s))) ] res = Parallel(n_jobs=-3, verbose=1)( delayed(run_experiment)( *arg ) for arg in args ) cols = [ 'var1', 'var2', 'm', *[f"{test.__name__}_precision_at_{k}" for test in [ttest_ind, wilcoxon, mannwhitneyu] for k in range(1, 11)], *[f"{test.__name__}_recall_at_{k}" for test in [ttest_ind, wilcoxon, mannwhitneyu] for k in range(1, 11)]] res_df = pd.DataFrame(res, columns = cols) res_df.to_csv("20200120_precision_recall_results.csv", index=False) ``` # Figures ``` size = np.sqrt(res_df.shape[0]).astype(int) ttest_prec = np.flipud(res_df.ttest_ind_precision_at_10.values.reshape(-1, spacing)) wilcoxon_prec = np.flipud(res_df.wilcoxon_precision_at_10.values.reshape(-1, spacing)) mannwhitney_prec = np.flipud(res_df.mannwhitneyu_precision_at_10.values.reshape(-1, spacing)) samples = np.linspace(0, 500, spacing +1).astype(int)[1:] *2 samples = [str(i) for i in samples] vmin = -.5 vmax = -vmin fmt = lambda x: "{:.2f}".format(x) with sns.plotting_context('talk', font_scale=1.25): # fig, ax = plt.subplots(figsize=(10, 10)) fig, ax = plt.subplots(1, 4, gridspec_kw={'width_ratios': [1, 1, 1, 0.05]}, figsize=(20, 8)) sns.heatmap( ttest_prec - wilcoxon_prec, ax = ax[0], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_1s], yticklabels=[f"{int(m*2)}" for m in ms][::-1], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[0].set_xticks(np.arange(0, ax[0].get_xlim()[1]+1, 10)) #ax[0].set_yticks(np.arange(0, ax[0].get_ylim()[0]+1, 10)[::-1]) ax[0].set_title("T-Test - Wilcoxon") sns.heatmap( ttest_prec - mannwhitney_prec, ax = ax[1], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_1s], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[1].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10)) #ax[1].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1]) ax[1].yaxis.set_major_formatter(plt.NullFormatter()) ax[1].set_title("T-Test - Mann-Whitney") sns.heatmap( wilcoxon_prec - mannwhitney_prec, ax = ax[2], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_2s], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[2].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10)) #ax[2].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1]) ax[2].yaxis.set_major_formatter(plt.NullFormatter()) ax[2].set_title("Wilcoxon - Mann-Whitney") fig.text(-0.01, 0.5, "Sample Size", va='center', rotation='vertical') fig.text(0.5, -0.03, "Mu", va='center', ha='center') fig.tight_layout() #fig.savefig("./figures/20191209_precision_diff.png", dpi=300, bbox_inches='tight') #fig.savefig("./figures/20191209_precision_diff.pdf", dpi=300, bbox_inches='tight') size = np.sqrt(res_df.shape[0]).astype(int) ttest_prec = np.flipud(res_df.ttest_ind_precision_at_10.values.reshape(-1, spacing)) wilcoxon_prec = np.flipud(res_df.wilcoxon_precision_at_10.values.reshape(-1, spacing)) mannwhitney_prec = np.flipud(res_df.mannwhitneyu_precision_at_10.values.reshape(-1, spacing)) samples = np.arange(0, 501, spacing)[1:] *2 samples[0] += 10 samples = [str(i) for i in samples] vmin = -0.05 vmax = -vmin fmt = lambda x: "{:.2f}".format(x) with sns.plotting_context('talk', font_scale=1.25): # fig, ax = plt.subplots(figsize=(10, 10)) fig, ax = plt.subplots(1, 4, gridspec_kw={'width_ratios': [1, 1, 1, 0.05]}, figsize=(20, 8)) sns.heatmap( ttest_prec - wilcoxon_prec, ax = ax[0], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_1s], yticklabels=[f"{int(m*2)}" for m in ms][::-1], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[0].set_xticks(np.arange(0, ax[0].get_xlim()[1]+1, 10)) #ax[0].set_yticks(np.arange(0, ax[0].get_ylim()[0]+1, 10)[::-1]) ax[0].set_title("T-Test - Wilcoxon") sns.heatmap( ttest_prec - mannwhitney_prec, ax = ax[1], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_1s], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[1].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10)) #ax[1].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1]) ax[1].yaxis.set_major_formatter(plt.NullFormatter()) ax[1].set_title("T-Test - Mann-Whitney") sns.heatmap( wilcoxon_prec - mannwhitney_prec, ax = ax[2], square=True, center=0, cmap="RdBu_r", cbar_kws = dict(shrink=0.7), xticklabels=[f"{mu1:.02f}" for mu1 in var_2s], cbar_ax=ax[-1], vmin=vmin, vmax=vmax ) #ax[2].set_xticks(np.arange(0, ax[1].get_xlim()[1]+1, 10)) #ax[2].set_yticks(np.arange(0, ax[1].get_ylim()[0]+1, 10)[::-1]) ax[2].yaxis.set_major_formatter(plt.NullFormatter()) ax[2].set_title("Wilcoxon - Mann-Whitney") fig.text(-0.01, 0.5, "Sample Size", va='center', rotation='vertical') fig.text(0.5, -0.03, "Mu", va='center', ha='center') fig.tight_layout() #fig.savefig("./figures/20191209_precision_diff.png", dpi=300, bbox_inches='tight') #fig.savefig("./figures/20191209_precision_diff.pdf", dpi=300, bbox_inches='tight') ```
github_jupyter
# Simple Image Classifier - Bring Your Own Data ## Neuronale Netze auf https://bootcamp.codecentric.ai Jetzt wird es Zeit, mit einem eigenen Dataset zu experimentieren. Hinweis: Wenn du auf einem Rechner trainierst, wo keine gut GPU verfügbar ist, kann dies sehr lange dauern. Evtl. möchtest du in dem Fall das Kapitel zu "Training in der Cloud" vorziehen und das Experiment dort durchführen. Imports und Settings ``` from fastai.basics import * from fastai.vision import * ``` ### Ordner festlegen, wo Daten liegen Überlege dir, welche Bilder du klassifizieren möchtest. Wenn du dich zum Beispiel für Vogel vs. Turnschuh entscheidest, lege eine Ordnerstruktur an - z.B.: - /data/byod/train/ - vogel/bild1.jpg - vogel/bild2.jpg - vogel/... - turnschuh/bild1.jpg - turnschuh/... Die Namen der Ordner sind wichtig - das sind deine Label. Die Namen der Bilder sind egal (es müssen auch nicht nur jpg sein). Die Bilder werden anhand der Ordner "gelabelt". Wieviele Bilder braucht man dafür? Fang doch einfach mal mit 10-20 Bildern pro Kategorie an und probiere es aus ... Vllt. findest du auch eine Möglichkeit "automatisiert" mehrere Bilder herunter zu laden. Oft ist es ein großer Aufwand erstmal genügend Daten in der entsprechenden Qualität zu bekommen. ``` DATA = "/data/byod/" TRAIN = DATA + "train/" ``` Der folgende Befehl macht: * Daten aus Ordner laden (bzw. einen Loader definieren) * Labels aus Ordner Namen zuordnen (alle Bilder im Ordner Kiwi sind Kiwis) * Split Train/Valid (20 %) * Bilder verkleinern (wenn du nur auf CPU trainierst wähle eine kleine Size, sonst dauert das Training sehr lang) * (und einiges mehr) ``` data = ImageDataBunch.from_folder(TRAIN, valid_pct=0.2, size=200, bs=20) ``` Wie sehen unsere Daten aus? Einfach mal ein paar Beispiele der Trainigsdaten anzeigen: ``` data.show_batch(rows=3, figsize=(6, 6)) ``` Der folgende Befehl macht: * Erzeuge ein CNN * mit einer Standard Architektur (vortrainiertes ResNet) * Architektur wird automatisch auf neue Daten angepasst (Bildgrößen, Klassen, etc.) * gebe im Trainingsloop die Metrik "Accuracy" aus * unter der Haube werden viele Standard-Werte gesetzt (welcher Optimizer, Hyperparameter, Best Practices, ...) ``` learn = cnn_learner(data, models.resnet18, metrics=accuracy) ``` ### Start Training ``` learn.fit(1) ``` ### Jetzt mit dem trainierten Modell eine Vorhersage machen Wenn du ein paar Bilder testen möchtest, dann lege unter /data/byod/ einen test Ordner an und kopiere ein paar Bilder hinein (Bilder, die nicht beim Training verwendet wurden). Hierbei musst du keine Unterordner anlegen (das Modell soll ja vorhersagen, welche Klasse es ist) Jetzt nehmen wir ein random Bild aus dem Test Ordner: ``` TEST = DATA + "test/" TEST_IMAGES = os.listdir(TEST) TEST_IMAGES test_img = open_image(TEST + random.choice(TEST_IMAGES)) test_img ``` und machen eine prediction mit dem Modell: ``` learn.predict(test_img) ``` ## Credits Für die Übung verwenden wir die fast.ai Library - siehe http://fast.ai
github_jupyter
# Network based predictions The state of the art in crime predication increasingly appears to be "network based". That is, looking at real street networks, and assigning risk to streets, rather than areal grid cells. This is currently an introduction, a very brief literature review, and a plan of action. # Literature review Not complete. 1. Rosser at al. "Predictive Crime Mapping: Arbitrary Grids or Street Networks?" J Quant Criminol (2016). https://doi.org/10.1007/s10940-016-9321-x 2. Shiode, Shiode, "Microscale Prediction of Near-Future Crime Concentrations with Street-Level Geosurveillance" Geographical Analysis (2014) 46 435–455 https://doi.org/10.1111/gean.12065 3. Okabe et al. "A kernel density estimation method for networks, its computational method and a GIS‐based tool", International Journal of Geographical Information Science (2009) 23 https://doi.org/10.1080/13658810802475491 Some comments: 1. "Prospective hotspotting on a network". Algorithm is fairly clear. Some useful info on estimating parameters. 2. Uses a space/time search window to form a statistical test of whether there is an "outbreak" of crime (so similar-ish to SatScan in some sense). 3. Not about _crime_ as such, but the details on how to adapt KDE methods to a network are very detailed and will be useful. # Action plan ## Network data - Open street map. I started to look at off-line processing of data with this repository: https://github.com/MatthewDaws/OSMDigest - Might also consider [OSMNX](https://github.com/gboeing/osmnx) - [TIGER/Line shapefiles](https://www.census.gov/geo/maps-data/data/tiger-line.html) USA only, but a canonical source. - [Ordnance Survey](https://www.ordnancesurvey.co.uk/) is the canonical source of data in the UK. - I am very keen to use only [freely available](https://www.ordnancesurvey.co.uk/business-and-government/products/opendata-products.html) (potentially, as in Beer) data - I think the two appropriate products for us are: - [OS Open Roads](https://www.ordnancesurvey.co.uk/business-and-government/products/os-open-roads.html) This is vector data, and a single download. - [OS OpenMap Local](https://www.ordnancesurvey.co.uk/business-and-government/products/os-open-map-local.html) Available as vector and raster for each national grid reference square. (Or for all of the UK, but a massive download). The raster maps are very detailed. The vector data, for _roads_, seems no more complete than the "Open Roads" download. But does include _buildings_ in vector format (but no address level data). - [OS VectorMap](https://www.ordnancesurvey.co.uk/business-and-government/products/vectormap-district.html) Shape files are slightly less detailed than OpenMap; raster format is 1/2 the detail. Might want to support optionally.
github_jupyter
Experimenting with my hack `star_so.py` ``` #!/usr/bin/env python # All of the argument parsing is done in the `parallel.py` module. import numpy as np import Starfish from Starfish.model import ThetaParam, PhiParam #import argparse #parser = argparse.ArgumentParser(prog="star_so.py", description="Run Starfish fitting model in single order mode with many walkers.") #parser.add_argument("--sample", choices=["ThetaCheb", "ThetaPhi", "ThetaPhiLines"], help="Sample the all stellar and nuisance parameters at the same time.") #parser.add_argument("--samples", type=int, default=5, help="How many samples to run?") #parser.add_argument("--incremental_save", type=int, default=0, help="How often to save incremental progress of MCMC samples.") #parser.add_argument("--use_cov", action="store_true", help="Use the local optimal jump matrix if present.") #args = parser.parse_args() import os import Starfish.grid_tools from Starfish.samplers import StateSampler from Starfish.spectrum import DataSpectrum, Mask, ChebyshevSpectrum from Starfish.emulator import Emulator import Starfish.constants as C from Starfish.covariance import get_dense_C, make_k_func, make_k_func_region from scipy.special import j1 from scipy.interpolate import InterpolatedUnivariateSpline from scipy.linalg import cho_factor, cho_solve from numpy.linalg import slogdet from astropy.stats import sigma_clip import gc import logging from itertools import chain from collections import deque from operator import itemgetter import yaml import shutil import json Starfish.routdir = "" # list of keys from 0 to (norders - 1) order_keys = np.arange(1) DataSpectra = [DataSpectrum.open(os.path.expandvars(file), orders=Starfish.data["orders"]) for file in Starfish.data["files"]] # list of keys from 0 to (nspectra - 1) Used for indexing purposes. spectra_keys = np.arange(len(DataSpectra)) #Instruments are provided as one per dataset Instruments = [eval("Starfish.grid_tools." + inst)() for inst in Starfish.data["instruments"]] logging.basicConfig(format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", filename="{}log.log".format( Starfish.routdir), level=logging.DEBUG, filemode="w", datefmt='%m/%d/%Y %I:%M:%S %p') class Order: def __init__(self, debug=False): ''' This object contains all of the variables necessary for the partial lnprob calculation for one echelle order. It is designed to first be instantiated within the main processes and then forked to other subprocesses. Once operating in the subprocess, the variables specific to the order are loaded with an `INIT` message call, which tells which key to initialize on in the `self.initialize()`. ''' self.lnprob = -np.inf self.lnprob_last = -np.inf self.debug = debug def initialize(self, key): ''' Initialize to the correct chunk of data (echelle order). :param key: (spectrum_id, order_key) :param type: (int, int) This method should only be called after all subprocess have been forked. ''' self.id = key spectrum_id, self.order_key = self.id # Make sure these are ints self.spectrum_id = int(spectrum_id) self.instrument = Instruments[self.spectrum_id] self.dataSpectrum = DataSpectra[self.spectrum_id] self.wl = self.dataSpectrum.wls[self.order_key] self.fl = self.dataSpectrum.fls[self.order_key] self.sigma = self.dataSpectrum.sigmas[self.order_key] self.ndata = len(self.wl) self.mask = self.dataSpectrum.masks[self.order_key] self.order = int(self.dataSpectrum.orders[self.order_key]) self.logger = logging.getLogger("{} {}".format(self.__class__.__name__, self.order)) if self.debug: self.logger.setLevel(logging.DEBUG) else: self.logger.setLevel(logging.INFO) self.logger.info("Initializing model on Spectrum {}, order {}.".format(self.spectrum_id, self.order_key)) self.npoly = Starfish.config["cheb_degree"] self.chebyshevSpectrum = ChebyshevSpectrum(self.dataSpectrum, self.order_key, npoly=self.npoly) # If the file exists, optionally initiliaze to the chebyshev values fname = Starfish.specfmt.format(self.spectrum_id, self.order) + "phi.json" if os.path.exists(fname): self.logger.debug("Loading stored Chebyshev parameters.") phi = PhiParam.load(fname) self.chebyshevSpectrum.update(phi.cheb) self.resid_deque = deque(maxlen=500) #Deque that stores the last residual spectra, for averaging self.counter = 0 self.emulator = Emulator.open() self.emulator.determine_chunk_log(self.wl) self.pca = self.emulator.pca self.wl_FFT = self.pca.wl # The raw eigenspectra and mean flux components self.EIGENSPECTRA = np.vstack((self.pca.flux_mean[np.newaxis,:], self.pca.flux_std[np.newaxis,:], self.pca.eigenspectra)) self.ss = np.fft.rfftfreq(self.pca.npix, d=self.emulator.dv) self.ss[0] = 0.01 # junk so we don't get a divide by zero error # Holders to store the convolved and resampled eigenspectra self.eigenspectra = np.empty((self.pca.m, self.ndata)) self.flux_mean = np.empty((self.ndata,)) self.flux_std = np.empty((self.ndata,)) self.sigma_mat = self.sigma**2 * np.eye(self.ndata) self.mus, self.C_GP, self.data_mat = None, None, None self.lnprior = 0.0 # Modified and set by NuisanceSampler.lnprob # self.nregions = 0 # self.exceptions = [] # Update the outdir based upon id self.noutdir = Starfish.routdir + "{}/{}/".format(self.spectrum_id, self.order) def lnprob_Theta(self, p): ''' Update the model to the Theta parameters and then evaluate the lnprob. Intended to be called from the master process via the command "LNPROB". ''' try: self.update_Theta(p) lnp = self.evaluate() # Also sets self.lnprob to new value return lnp except C.ModelError: self.logger.debug("ModelError in stellar parameters, sending back -np.inf {}".format(p)) return -np.inf def evaluate(self): ''' Return the lnprob using the current version of the C_GP matrix, data matrix, and other intermediate products. ''' self.lnprob_last = self.lnprob X = (self.chebyshevSpectrum.k * self.flux_std * np.eye(self.ndata)).dot(self.eigenspectra.T) CC = X.dot(self.C_GP.dot(X.T)) + self.data_mat try: factor, flag = cho_factor(CC) except np.linalg.linalg.LinAlgError: print("Spectrum:", self.spectrum_id, "Order:", self.order) self.CC_debugger(CC) raise try: R = self.fl - self.chebyshevSpectrum.k * self.flux_mean - X.dot(self.mus) logdet = np.sum(2 * np.log((np.diag(factor)))) self.lnprob = -0.5 * (np.dot(R, cho_solve((factor, flag), R)) + logdet) self.logger.debug("Evaluating lnprob={}".format(self.lnprob)) return self.lnprob # To give us some debugging information about what went wrong. except np.linalg.linalg.LinAlgError: print("Spectrum:", self.spectrum_id, "Order:", self.order) raise def update_Theta(self, p): ''' Update the model to the current Theta parameters. :param p: parameters to update model to :type p: model.ThetaParam ''' # durty HACK to get fixed logg # Simply fixes the middle value to be 4.29 # Check to see if it exists, as well fix_logg = Starfish.config.get("fix_logg", None) if fix_logg is not None: p.grid[1] = fix_logg print("grid pars are", p.grid) self.logger.debug("Updating Theta parameters to {}".format(p)) # Store the current accepted values before overwriting with new proposed values. self.flux_mean_last = self.flux_mean.copy() self.flux_std_last = self.flux_std.copy() self.eigenspectra_last = self.eigenspectra.copy() self.mus_last = self.mus self.C_GP_last = self.C_GP # Local, shifted copy of wavelengths wl_FFT = self.wl_FFT * np.sqrt((C.c_kms + p.vz) / (C.c_kms - p.vz)) # If vsini is less than 0.2 km/s, we might run into issues with # the grid spacing. Therefore skip the convolution step if we have # values smaller than this. # FFT and convolve operations if p.vsini < 0.0: raise C.ModelError("vsini must be positive") elif p.vsini < 0.2: # Skip the vsini taper due to instrumental effects eigenspectra_full = self.EIGENSPECTRA.copy() else: FF = np.fft.rfft(self.EIGENSPECTRA, axis=1) # Determine the stellar broadening kernel ub = 2. * np.pi * p.vsini * self.ss sb = j1(ub) / ub - 3 * np.cos(ub) / (2 * ub ** 2) + 3. * np.sin(ub) / (2 * ub ** 3) # set zeroth frequency to 1 separately (DC term) sb[0] = 1. # institute vsini taper FF_tap = FF * sb # do ifft eigenspectra_full = np.fft.irfft(FF_tap, self.pca.npix, axis=1) # Spectrum resample operations if min(self.wl) < min(wl_FFT) or max(self.wl) > max(wl_FFT): raise RuntimeError("Data wl grid ({:.2f},{:.2f}) must fit within the range of wl_FFT ({:.2f},{:.2f})".format(min(self.wl), max(self.wl), min(wl_FFT), max(wl_FFT))) # Take the output from the FFT operation (eigenspectra_full), and stuff them # into respective data products for lres, hres in zip(chain([self.flux_mean, self.flux_std], self.eigenspectra), eigenspectra_full): interp = InterpolatedUnivariateSpline(wl_FFT, hres, k=5) lres[:] = interp(self.wl) del interp # Helps keep memory usage low, seems like the numpy routine is slow # to clear allocated memory for each iteration. gc.collect() # Adjust flux_mean and flux_std by Omega Omega = 10**p.logOmega self.flux_mean *= Omega self.flux_std *= Omega # Now update the parameters from the emulator # If pars are outside the grid, Emulator will raise C.ModelError self.emulator.params = p.grid self.mus, self.C_GP = self.emulator.matrix class SampleThetaPhi(Order): def initialize(self, key): # Run through the standard initialization super().initialize(key) # for now, start with white noise self.data_mat = self.sigma_mat.copy() self.data_mat_last = self.data_mat.copy() #Set up p0 and the independent sampler fname = Starfish.specfmt.format(self.spectrum_id, self.order) + "phi.json" phi = PhiParam.load(fname) # Set the regions to None, since we don't want to include them even if they # are there phi.regions = None #Loading file that was previously output # Convert PhiParam object to an array self.p0 = phi.toarray() jump = Starfish.config["Phi_jump"] cheb_len = (self.npoly - 1) if self.chebyshevSpectrum.fix_c0 else self.npoly cov_arr = np.concatenate((Starfish.config["cheb_jump"]**2 * np.ones((cheb_len,)), np.array([jump["sigAmp"], jump["logAmp"], jump["l"]])**2 )) cov = np.diag(cov_arr) def lnfunc(p): # Convert p array into a PhiParam object ind = self.npoly if self.chebyshevSpectrum.fix_c0: ind -= 1 cheb = p[0:ind] sigAmp = p[ind] ind+=1 logAmp = p[ind] ind+=1 l = p[ind] par = PhiParam(self.spectrum_id, self.order, self.chebyshevSpectrum.fix_c0, cheb, sigAmp, logAmp, l) self.update_Phi(par) # sigAmp must be positive (this is effectively a prior) # See https://github.com/iancze/Starfish/issues/26 if not (0.0 < sigAmp): self.lnprob_last = self.lnprob lnp = -np.inf self.logger.debug("sigAmp was negative, returning -np.inf") self.lnprob = lnp # Same behavior as self.evaluate() else: lnp = self.evaluate() self.logger.debug("Evaluated Phi parameters: {} {}".format(par, lnp)) return lnp def update_Phi(self, p): self.logger.debug("Updating nuisance parameters to {}".format(p)) # Read off the Chebyshev parameters and update self.chebyshevSpectrum.update(p.cheb) # Check to make sure the global covariance parameters make sense #if p.sigAmp < 0.1: # raise C.ModelError("sigAmp shouldn't be lower than 0.1, something is wrong.") max_r = 6.0 * p.l # [km/s] # Create a partial function which returns the proper element. k_func = make_k_func(p) # Store the previous data matrix in case we want to revert later self.data_mat_last = self.data_mat self.data_mat = get_dense_C(self.wl, k_func=k_func, max_r=max_r) + p.sigAmp*self.sigma_mat ``` # Run the program. ``` model = SampleThetaPhi(debug=True) model.initialize((0,0)) def lnprob_all(p): pars1 = ThetaParam(grid=p[0:3], vz=p[3], vsini=p[4], logOmega=p[5]) model.update_Theta(pars1) # hard code npoly=3 (for fixc0 = True with npoly=4) ! pars2 = PhiParam(0, 0, True, p[6:9], p[9], p[10], p[11]) model.update_Phi(pars2) lnp = model.evaluate() return lnp import emcee start = Starfish.config["Theta"] fname = Starfish.specfmt.format(model.spectrum_id, model.order) + "phi.json" phi0 = PhiParam.load(fname) p0 = np.array(start["grid"] + [start["vz"], start["vsini"], start["logOmega"]] + phi0.cheb.tolist() + [phi0.sigAmp, phi0.logAmp, phi0.l]) p0 sampler = emcee.EnsembleSampler(32, 12, lnprob_all) sampler.lnprobfn.f(p0) p0.shape p0.shape p0_std = [5, 0.02, 0.02, 0.5, 0.5, -0.01, -0.005, -0.005, -0.005, 0.01, 0.001, 0.5] nwalkers=36 p0_ball = emcee.utils.sample_ball(p0, p0_std, size=nwalkers) p0_ball.shape ``` # This will take a while: ``` #val = sampler.run_mcmc(p0_ball, 10) np.save('emcee_chain.npy',sampler.chain) print("The end.") ``` The end.
github_jupyter
# Linear Regression <img src="https://raw.githubusercontent.com/glazec/practicalAI/master/images/logo.png" width=150> In this lesson we will learn about linear regression. We will first understand the basic math behind it and then implement it in Python. We will also look at ways of interpreting the linear model. # Overview <img src="https://raw.githubusercontent.com/glazec/practicalAI/master/images/linear.png" width=250> $\hat{y} = XW$ *where*: * $\hat{y}$ = prediction | $\in \mathbb{R}^{NX1}$ ($N$ is the number of samples) * $X$ = inputs | $\in \mathbb{R}^{NXD}$ ($D$ is the number of features) * $W$ = weights | $\in \mathbb{R}^{DX1}$ * **Objective:** Use inputs $X$ to predict the output $\hat{y}$ using a linear model. The model will be a line of best fit that minimizes the distance between the predicted and target outcomes. Training data $(X, y)$ is used to train the model and learn the weights $W$ using stochastic gradient descent (SGD). * **Advantages:** * Computationally simple. * Highly interpretable. * Can account for continuous and categorical features. * **Disadvantages:** * The model will perform well only when the data is linearly separable (for classification). * Usually not used for classification and only for regression. * **Miscellaneous:** You can also use linear regression for binary classification tasks where if the predicted continuous value is above a threshold, it belongs to a certain class. But we will cover better techniques for classification is future lessons and will focus on linear regression for continuos regression tasks only. # Training *Steps*: 1. Randomly initialize the model's weights $W$. 2. Feed inputs $X$ into the model to receive the predictions $\hat{y}$. 3. Compare the predictions $\hat{y}$ with the actual target values $y$ with the objective (cost) function to determine loss $J$. A common objective function for linear regression is mean squarred error (MSE). This function calculates the difference between the predicted and target values and squares it. (the $\frac{1}{2}$ is just for convenicing the derivative operation). * $MSE = J(\theta) = \frac{1}{2}\sum_{i}(\hat{y}_i - y_i)^2$ 4. Calculate the gradient of loss $J(\theta)$ w.r.t to the model weights. * $J(\theta) = \frac{1}{2}\sum_{i}(\hat{y}_i - y_i)^2 = \frac{1}{2}\sum_{i}(X_iW - y_i)^2 $ * $\frac{\partial{J}}{\partial{W}} = X(\hat{y} - y)$ 4. Apply backpropagation to update the weights $W$ using a learning rate $\alpha$ and an optimization technique (ie. stochastic gradient descent). The simplified intuition is that the gradient tells you the direction for how to increase something so subtracting it will help you go the other way since we want to decrease loss $J(\theta)$. * $W = W- \alpha\frac{\partial{J}}{\partial{W}}$ 5. Repeat steps 2 - 4 until model performs well. # Data We're going to create some simple dummy data to apply linear regression on. ``` from argparse import Namespace import matplotlib.pyplot as plt import numpy as np import pandas as pd # Arguments args = Namespace( seed=1234, data_file="sample_data.csv", num_samples=100, train_size=0.75, test_size=0.25, num_epochs=100, ) # Set seed for reproducability np.random.seed(args.seed) # Generate synthetic data def generate_data(num_samples): X = np.array(range(num_samples)) y = 3.65*X + 10 return X, y # Generate random (linear) data X, y = generate_data(args.num_samples) data = np.vstack([X, y]).T df = pd.DataFrame(data, columns=['X', 'y']) df.head() # Scatter plot plt.title("Generated data") plt.scatter(x=df["X"], y=df["y"]) plt.show() ``` # Scikit-learn implementation **Note**: The `LinearRegression` class in Scikit-learn uses the normal equation to solve the fit. However, we are going to use Scikit-learn's `SGDRegressor` class which uses stochastic gradient descent. We want to use this optimization approach because we will be using this for the models in subsequent lessons. ``` # Import packages from sklearn.linear_model.stochastic_gradient import SGDRegressor from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split # Create data splits X_train, X_test, y_train, y_test = train_test_split( df["X"].values.reshape(-1, 1), df["y"], test_size=args.test_size, random_state=args.seed) print ("X_train:", X_train.shape) print ("y_train:", y_train.shape) print ("X_test:", X_test.shape) print ("y_test:", y_test.shape) ``` We need to standardize our data (zero mean and unit variance) in order to properly use SGD and optimize quickly. ``` # Standardize the data (mean=0, std=1) using training data X_scaler = StandardScaler().fit(X_train) y_scaler = StandardScaler().fit(y_train.values.reshape(-1,1)) # Apply scaler on training and test data standardized_X_train = X_scaler.transform(X_train) standardized_y_train = y_scaler.transform(y_train.values.reshape(-1,1)).ravel() standardized_X_test = X_scaler.transform(X_test) standardized_y_test = y_scaler.transform(y_test.values.reshape(-1,1)).ravel() # Check print ("mean:", np.mean(standardized_X_train, axis=0), np.mean(standardized_y_train, axis=0)) # mean should be ~0 print ("std:", np.std(standardized_X_train, axis=0), np.std(standardized_y_train, axis=0)) # std should be 1 # Initialize the model lm = SGDRegressor(loss="squared_loss", penalty="none", max_iter=args.num_epochs) # Train lm.fit(X=standardized_X_train, y=standardized_y_train) # Predictions (unstandardize them) pred_train = (lm.predict(standardized_X_train) * np.sqrt(y_scaler.var_)) + y_scaler.mean_ pred_test = (lm.predict(standardized_X_test) * np.sqrt(y_scaler.var_)) + y_scaler.mean_ ``` # Evaluation There are several evaluation techniques to see how well our model performed. ``` import matplotlib.pyplot as plt # Train and test MSE train_mse = np.mean((y_train - pred_train) ** 2) test_mse = np.mean((y_test - pred_test) ** 2) print ("train_MSE: {0:.2f}, test_MSE: {1:.2f}".format(train_mse, test_mse)) ``` Besides MSE, when we only have one feature, we can visually inspect the model. ``` # Figure size plt.figure(figsize=(15,5)) # Plot train data plt.subplot(1, 2, 1) plt.title("Train") plt.scatter(X_train, y_train, label="y_train") plt.plot(X_train, pred_train, color="red", linewidth=1, linestyle="-", label="lm") plt.legend(loc='lower right') # Plot test data plt.subplot(1, 2, 2) plt.title("Test") plt.scatter(X_test, y_test, label="y_test") plt.plot(X_test, pred_test, color="red", linewidth=1, linestyle="-", label="lm") plt.legend(loc='lower right') # Show plots plt.show() ``` # Inference ``` # Feed in your own inputs X_infer = np.array((0, 1, 2), dtype=np.float32) standardized_X_infer = X_scaler.transform(X_infer.reshape(-1, 1)) pred_infer = (lm.predict(standardized_X_infer) * np.sqrt(y_scaler.var_)) + y_scaler.mean_ print (pred_infer) df.head(3) ``` # Interpretability Linear regression offers the great advantage of being highly interpretable. Each feature has a coefficient which signifies it's importance/impact on the output variable y. We can interpret our coefficient as follows: By increasing X by 1 unit, we increase y by $W$ (~3.65) units. **Note**: Since we standardized our inputs and outputs for gradient descent, we need to apply an operation to our coefficients and intercept to interpret them. See proof below. ``` # Unstandardize coefficients coef = lm.coef_ * (y_scaler.scale_/X_scaler.scale_) intercept = lm.intercept_ * y_scaler.scale_ + y_scaler.mean_ - np.sum(coef*X_scaler.mean_) print (coef) # ~3.65 print (intercept) # ~10 ``` ### Proof for unstandardizing coefficients: Note that both X and y were standardized. $\frac{\mathbb{E}[y] - \hat{y}}{\sigma_y} = W_0 + \sum_{j=1}^{k}W_jz_j$ $z_j = \frac{x_j - \bar{x}_j}{\sigma_j}$ $ \hat{y}_{scaled} = \frac{\hat{y}_{unscaled} - \bar{y}}{\sigma_y} = \hat{W_0} + \sum_{j=1}^{k} \hat{W}_j (\frac{x_j - \bar{x}_j}{\sigma_j}) $ $\hat{y}_{unscaled} = \hat{W}_0\sigma_y + \bar{y} - \sum_{j=1}^{k} \hat{W}_j(\frac{\sigma_y}{\sigma_j})\bar{x}_j + \sum_{j=1}^{k}(\frac{\sigma_y}{\sigma_j})x_j $ # Regularization Regularization helps decrease over fitting. Below is L2 regularization (ridge regression). There are many forms of regularization but they all work to reduce overfitting in our models. With L2 regularization, we are penalizing the weights with large magnitudes by decaying them. Having certain weights with high magnitudes will lead to preferential bias with the inputs and we want the model to work with all the inputs and not just a select few. There are also other types of regularization like L1 (lasso regression) which is useful for creating sparse models where some feature cofficients are zeroed out, or elastic which combines L1 and L2 penalties. **Note**: Regularization is not just for linear regression. You can use it to regualr any model's weights including the ones we will look at in future lessons. * $ J(\theta) = = \frac{1}{2}\sum_{i}(X_iW - y_i)^2 + \frac{\lambda}{2}\sum\sum W^2$ * $ \frac{\partial{J}}{\partial{W}} = X (\hat{y} - y) + \lambda W $ * $W = W- \alpha\frac{\partial{J}}{\partial{W}}$ where: * $\lambda$ is the regularzation coefficient ``` # Initialize the model with L2 regularization lm = SGDRegressor(loss="squared_loss", penalty='l2', alpha=1e-2, max_iter=args.num_epochs) # Train lm.fit(X=standardized_X_train, y=standardized_y_train) # Predictions (unstandardize them) pred_train = (lm.predict(standardized_X_train) * np.sqrt(y_scaler.var_)) + y_scaler.mean_ pred_test = (lm.predict(standardized_X_test) * np.sqrt(y_scaler.var_)) + y_scaler.mean_ # Train and test MSE train_mse = np.mean((y_train - pred_train) ** 2) test_mse = np.mean((y_test - pred_test) ** 2) print ("train_MSE: {0:.2f}, test_MSE: {1:.2f}".format( train_mse, test_mse)) ``` Regularization didn't help much with this specific example because our data is generation from a perfect linear equation but for realistic data, regularization can help our model generalize well. ``` # Unstandardize coefficients coef = lm.coef_ * (y_scaler.scale_/X_scaler.scale_) intercept = lm.intercept_ * y_scaler.scale_ + y_scaler.mean_ - (coef*X_scaler.mean_) print (coef) # ~3.65 print (intercept) # ~10 ``` # Categorical variables In our example, the feature was a continuous variable but what if we also have features that are categorical? One option is to treat the categorical variables as one-hot encoded variables. This is very easy to do with Pandas and once you create the dummy variables, you can use the same steps as above to train your linear model. ``` # Create data with categorical features cat_data = pd.DataFrame(['a', 'b', 'c', 'a'], columns=['favorite_letter']) cat_data.head() dummy_cat_data = pd.get_dummies(cat_data) dummy_cat_data.head() ``` Now you can concat this with your continuous features and train the linear model. # TODO - polynomial regression - simple example with normal equation method (sklearn.linear_model.LinearRegression) with pros and cons vs. SGD linear regression
github_jupyter
``` %matplotlib notebook import control as c import ipywidgets as w import numpy as np from IPython.display import display, HTML import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as animation display(HTML('<script> $(document).ready(function() { $("div.input").hide(); }); </script>')) ``` ## Control design for a 1DoF mass-spring-damper system The following example is a control design task for a mass-spring-damper system, a typical second-order model. The structure consists of a sliding mass (friction is ignored), connected to a reference point with an infinitely expandable string-damper pair.<br><br> <img src="Images/mbk.png" width="40%" /> <br> Its equation of motion can be stated as: <br> $$m\cdot\ddot{x}+b\cdot\dot{x}+k\cdot{x}=F$$ <br> After the Laplace transformation of the differential equation, the transfer function can be expressed as: <br> $$G(s)=\frac{1}{m\cdot s^2 +b\cdot s + k}$$ <br> Your task is to choose a controller type, and tune it to acceptable levels of performance! <b>First, choose a system model!</b><br> Toggle between different realistic models with randomly preselected values (buttons *Model 1* - *Model 6*). By clicking the *Preset* button default, valid predetermined controller parameters are set and cannot be tuned further. ``` # Figure definition fig1, ((f1_ax1), (f1_ax2)) = plt.subplots(2, 1) fig1.set_size_inches((9.8, 5)) fig1.set_tight_layout(True) f1_line1, = f1_ax1.plot([], []) f1_line2, = f1_ax2.plot([], []) f1_ax1.grid(which='both', axis='both', color='lightgray') f1_ax2.grid(which='both', axis='both', color='lightgray') f1_ax1.autoscale(enable=True, axis='both', tight=True) f1_ax2.autoscale(enable=True, axis='both', tight=True) f1_ax1.set_title('Bode magnitude plot', fontsize=11) f1_ax1.set_xscale('log') f1_ax1.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=10) f1_ax1.set_ylabel(r'$A\/$[dB]', labelpad=0, fontsize=10) f1_ax1.tick_params(axis='both', which='both', pad=0, labelsize=8) f1_ax2.set_title('Bode phase plot', fontsize=11) f1_ax2.set_xscale('log') f1_ax2.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=10) f1_ax2.set_ylabel(r'$\phi\/$[°]', labelpad=0, fontsize=10) f1_ax2.tick_params(axis='both', which='both', pad=0, labelsize=8) # System parameters def build_base_model(m, k, b): W_sys = c.tf([1], [m, b, k]) print('System transfer function:') print(W_sys) # System analysis poles = c.pole(W_sys) # Poles print('System poles:\n') print(poles) global f1_line1, f1_line2 f1_ax1.lines.remove(f1_line1) f1_ax2.lines.remove(f1_line2) mag, phase, omega = c.bode_plot(W_sys, Plot=False) # Bode-plot f1_line1, = f1_ax1.plot(omega/2/np.pi, 20*np.log10(mag), lw=1, color='blue') f1_line2, = f1_ax2.plot(omega/2/np.pi, phase*180/np.pi, lw=1, color='blue') f1_ax1.relim() f1_ax2.relim() f1_ax1.autoscale_view() f1_ax2.autoscale_view() # GUI widgets typeSelect = w.ToggleButtons( options=[('Model 1', 0), ('Model 2', 1), ('Model 3', 2), ('Model 4', 3), ('Model 5', 4), ('Model 6', 5), ('Preset', -1)], value =-1, description='System: ', layout=w.Layout(width='60%')) m_slider = w.FloatLogSlider(value=0.5, base=10, min=-3, max=3, description='m [kg] :', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) k_slider = w.FloatLogSlider(value=100, base=10, min=-2, max=4, description='k [N/m] :', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) b_slider = w.FloatLogSlider(value=50, base=10, min=-2, max=4, description='b [Ns/m] :', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) input_data = w.interactive_output(build_base_model, {'m':m_slider, 'k':k_slider, 'b':b_slider}) def update_sliders(index): global m_slider, k_slider, b_slider mval = [0.05, 0.1, 0.25, 0.5, 1, 5, 0.25] kval = [1.25, 10, 100, 10, 50, 1000, 50] bval = [1, 0.5, 2, 10, 10, 20, 1] m_slider.value = mval[index] k_slider.value = kval[index] b_slider.value = bval[index] if index == -1: m_slider.disabled = True k_slider.disabled = True b_slider.disabled = True else: m_slider.disabled = False k_slider.disabled = False b_slider.disabled = False input_data2 = w.interactive_output(update_sliders, {'index':typeSelect}) display(typeSelect, input_data2) display(w.HBox([m_slider, k_slider, b_slider]), input_data) ``` Depending on your selection, the system is either under- or overdamped. <br> <b>Select an appropriate controller configuration! Which one is the best for your system? Why?<br> Set up your controller for the fastest settling time with at most 25% overshoot!</b> You can turn on/off each of the I and D components, and if D is active, you can apply the first-order filter as well, based on the derivating time constant. ``` # PID position control fig2, ((f2_ax1, f2_ax2, f2_ax3), (f2_ax4, f2_ax5, f2_ax6)) = plt.subplots(2, 3) fig2.set_size_inches((9.8, 5)) fig2.set_tight_layout(True) f2_line1, = f2_ax1.plot([], []) f2_line2, = f2_ax2.plot([], []) f2_line3, = f2_ax3.plot([], []) f2_line4, = f2_ax4.plot([], []) f2_line5, = f2_ax5.plot([], []) f2_line6, = f2_ax6.plot([], []) f2_ax1.grid(which='both', axis='both', color='lightgray') f2_ax2.grid(which='both', axis='both', color='lightgray') f2_ax3.grid(which='both', axis='both', color='lightgray') f2_ax4.grid(which='both', axis='both', color='lightgray') f2_ax5.grid(which='both', axis='both', color='lightgray') f2_ax6.grid(which='both', axis='both', color='lightgray') f2_ax1.autoscale(enable=True, axis='both', tight=True) f2_ax2.autoscale(enable=True, axis='both', tight=True) f2_ax3.autoscale(enable=True, axis='both', tight=True) f2_ax4.autoscale(enable=True, axis='both', tight=True) f2_ax5.autoscale(enable=True, axis='both', tight=True) f2_ax6.autoscale(enable=True, axis='both', tight=True) f2_ax1.set_title('Closed loop step response', fontsize=9) f2_ax1.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8) f2_ax1.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8) f2_ax1.tick_params(axis='both', which='both', pad=0, labelsize=6) f2_ax2.set_title('Nyquist diagram', fontsize=9) f2_ax2.set_xlabel(r'Re', labelpad=0, fontsize=8) f2_ax2.set_ylabel(r'Im', labelpad=0, fontsize=8) f2_ax2.tick_params(axis='both', which='both', pad=0, labelsize=6) f2_ax3.set_title('Bode magniture plot', fontsize=9) f2_ax3.set_xscale('log') f2_ax3.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=8) f2_ax3.set_ylabel(r'$A\/$[dB]', labelpad=0, fontsize=8) f2_ax3.tick_params(axis='both', which='both', pad=0, labelsize=6) f2_ax4.set_title('Closed loop impulse response', fontsize=9) f2_ax4.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8) f2_ax4.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8) f2_ax4.tick_params(axis='both', which='both', pad=0, labelsize=6) f2_ax5.set_title('Load transfer step response', fontsize=9) f2_ax5.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=8) f2_ax5.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=8) f2_ax5.tick_params(axis='both', which='both', pad=0, labelsize=6) f2_ax6.set_title('Bode phase plot', fontsize=9) f2_ax6.set_xscale('log') f2_ax6.set_xlabel(r'$f\/$[Hz]', labelpad=0, fontsize=8) f2_ax6.set_ylabel(r'$\phi\/$[°]', labelpad=0, fontsize=8) f2_ax6.tick_params(axis='both', which='both', pad=0, labelsize=6) def position_control(Kp, Ti, Td, Fd, Ti0, Td0, Fd0, m, k, b): W_sys = c.tf([1], [m, b, k]) # PID Controller P = Kp # Proportional term I = Kp / Ti # Integral term D = Kp * Td # Derivative term Td_f = Td / Fd # Derivative term filter W_PID = c.parallel(c.tf([P], [1]), c.tf([I * Ti0], [1 * Ti0, 1 * (not Ti0)]), c.tf([D * Td0, 0], [Td_f * Td0 * Fd0, 1])) # PID controller in time constant format W_open = c.series(W_PID, W_sys) # Open loop with two integrators added for position output W_closed = c.feedback(W_open, 1, -1) # Closed loop with negative feedback W_load = c.feedback(W_sys, W_PID, -1) # Transfer function of the load based errors # Display global f2_line1, f2_line2, f2_line3, f2_line4, f2_line5, f2_line6 f2_ax1.lines.remove(f2_line1) f2_ax2.lines.remove(f2_line2) f2_ax3.lines.remove(f2_line3) f2_ax4.lines.remove(f2_line4) f2_ax5.lines.remove(f2_line5) f2_ax6.lines.remove(f2_line6) tout, yout = c.step_response(W_closed) f2_line1, = f2_ax1.plot(tout, yout, lw=1, color='blue') _, _, ob = c.nyquist_plot(W_open, Plot=False) # Small resolution plot to determine bounds real, imag, freq = c.nyquist_plot(W_open, omega=np.logspace(np.log10(ob[0]), np.log10(ob[-1]), 1000), Plot=False) f2_line2, = f2_ax2.plot(real, imag, lw=1, color='blue') mag, phase, omega = c.bode_plot(W_open, Plot=False) f2_line3, = f2_ax3.plot(omega/2/np.pi, 20*np.log10(mag), lw=1, color='blue') f2_line6, = f2_ax6.plot(omega/2/np.pi, phase*180/np.pi, lw=1, color='blue') tout, yout = c.impulse_response(W_closed) f2_line4, = f2_ax4.plot(tout, yout, lw=1, color='blue') tout, yout = c.step_response(W_load) f2_line5, = f2_ax5.plot(tout, yout, lw=1, color='blue') f2_ax1.relim() f2_ax2.relim() f2_ax3.relim() f2_ax4.relim() f2_ax5.relim() f2_ax6.relim() f2_ax1.autoscale_view() f2_ax2.autoscale_view() f2_ax3.autoscale_view() f2_ax4.autoscale_view() f2_ax5.autoscale_view() f2_ax6.autoscale_view() def update_controller(index): global Kp_slider, Ti_slider, Td_slider, Fd_slider, Ti_button, Td_button, Fd_button if index == -1: Kp_slider.value = 100 Td_slider.value = 0.05 Fd_slider.value = 10 Ti_button.value = False Td_button.value = True Fd_button.value = True Kp_slider.disabled = True Ti_slider.disabled = True Td_slider.disabled = True Fd_slider.disabled = True Ti_button.disabled = True Td_button.disabled = True Fd_button.disabled = True else: Kp_slider.disabled = False Ti_slider.disabled = False Td_slider.disabled = False Fd_slider.disabled = False Ti_button.disabled = False Td_button.disabled = False Fd_button.disabled = False # GUI widgets Kp_slider = w.FloatLogSlider(value=0.5, base=10, min=-1, max=4, description='Kp:', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) Ti_slider = w.FloatLogSlider(value=0.0035, base=10, min=-4, max=1, description='', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) Td_slider = w.FloatLogSlider(value=1, base=10, min=-4, max=1, description='', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) Fd_slider = w.FloatLogSlider(value=1, base=10, min=0, max=3, description='', continuous_update=False, layout=w.Layout(width='auto', flex='5 5 auto')) Ti_button = w.ToggleButton(value=True, description='Ti', layout=w.Layout(width='auto', flex='1 1 0%')) Td_button = w.ToggleButton(value=False, description='Td', layout=w.Layout(width='auto', flex='1 1 0%')) Fd_button = w.ToggleButton(value=False, description='Fd', layout=w.Layout(width='auto', flex='1 1 0%')) input_data = w.interactive_output(position_control, {'Kp': Kp_slider, 'Ti': Ti_slider, 'Td': Td_slider, 'Fd': Fd_slider, 'Ti0' : Ti_button, 'Td0': Td_button, 'Fd0': Fd_button, 'm':m_slider, 'k':k_slider, 'b':b_slider}) w.interactive_output(update_controller, {'index': typeSelect}) display(w.HBox([Kp_slider, Ti_button, Ti_slider, Td_button, Td_slider, Fd_button, Fd_slider]), input_data) ``` In the following simulation, you can observe the movement of your system based on your controller setup. You can create reference signals and even apply some disturbance and see how the system reacts. <b>Is your configuration suitable for signal-following? Readjust your controller so that it can follow a sine wave acceptably!</b> <br><br> <i>(The animations are scaled to fit the frame through the whole simulation. Because of this, unstable solutions might not seem to move until the very last second.)</i> ``` # Simulation data anim_fig = plt.figure() anim_fig.set_size_inches((9.8, 6)) anim_fig.set_tight_layout(True) anim_ax1 = anim_fig.add_subplot(211) anim_ax2 = anim_ax1.twinx() frame_count=1000 l1 = anim_ax1.plot([], [], lw=1, color='blue') l2 = anim_ax1.plot([], [], lw=2, color='red') l3 = anim_ax2.plot([], [], lw=1, color='grey') line1 = l1[0] line2 = l2[0] line3 = l3[0] anim_ax1.legend(l1+l2+l3, ['Reference [m]', 'Output [m]', 'Load [N]'], loc=1) anim_ax1.set_title('Time response simulation', fontsize=12) anim_ax1.set_xlabel(r'$t\/$[s]', labelpad=0, fontsize=10) anim_ax1.set_ylabel(r'$x\/$[m]', labelpad=0, fontsize=10) anim_ax1.tick_params(axis='both', which='both', pad=0, labelsize=8) anim_ax2.set_ylabel(r'$F\/$[N]', labelpad=0, fontsize=10) anim_ax2.tick_params(axis='both', which='both', pad=0, labelsize=8) anim_ax1.grid(which='both', axis='both', color='lightgray') T_plot = [] X_plot = [] L_plot = [] R_plot = [] # Scene data scene_ax = anim_fig.add_subplot(212) scene_ax.set_xlim((-3, 4)) scene_ax.set_ylim((-0.5, 1.5)) scene_ax.axis('off') scene_ax.plot([-2.5, -2.3, -2.3, -0.3, -2.3, -2.3, -0.3], [0.75, 0.75, 0.9, 0.9, 0.9, 0.6, 0.6], lw=2, color='blue', zorder=0) scene_ax.plot([-2.5, -2.3], [0.25, 0.25], lw=2, color='red', zorder=0) scene_ax.plot([-2.5, -2.5], [1.25, -0.25], lw=4, color='gray', zorder=2) scene_ax.text(-1.3, 1, 'b', fontsize=14, color='blue', va='bottom', zorder=5) scene_ax.text(-1.3, 0, 'k', fontsize=14, color='red', va='top', zorder=5) b_line, = scene_ax.plot([], [], lw=2, color='blue') k_line, = scene_ax.plot([], [], lw=2, color='red') m_text = scene_ax.text(1.75, 0.5, 'm', fontsize=14, color='green', va='center', ha='center', zorder=5) m_box = patches.Rectangle((1, 0), 1.5, 1, lw=2, color='green', fill=False, zorder=10) scene_ax.add_patch(m_box) x_arrow = scene_ax.arrow(1.75, -0.5, 0, 0.25, color='blue', head_width=0.1, length_includes_head=True, lw=1, fill=False, zorder=5) r_arrow = scene_ax.arrow(1.75, -0.5, 0, 0.25, color='red', head_width=0.1, length_includes_head=True, lw=1, fill=False, zorder=5) base_arrow = x_arrow.xy pos_var = [] ref_var = [] #Simulation function def simulation(Kp, Ti, Td, Fd, Ti0, Td0, Fd0, m, k, b, T, dt, X, Xf, Xa, Xo, L, Lf, La, Lo): # Controller P = Kp # Proportional term I = Kp / Ti # Integral term D = Kp * Td # Derivative term Td_f = Td / Fd # Derivative term filter W_PID = c.parallel(c.tf([P], [1]), c.tf([I * Ti0], [1 * Ti0, 1 * (not Ti0)]), c.tf([D * Td0, 0], [Td_f * Td0 * Fd0, 1])) # PID controller # System W_sys = c.tf([1], [m, b, k]) # Model W_open = c.series(W_PID, W_sys) # Open loop with two integrators added for position output W_closed = c.feedback(W_open, 1, -1) # Closed loop with negative feedback W_load = c.feedback(W_sys, W_PID, -1) # Transfer function of the load based errors # Reference and disturbance signals T_sim = np.arange(0, T, dt, dtype=np.float64) if X == 0: # Constant reference X_sim = np.full_like(T_sim, Xa * Xo) elif X == 1: # Sine wave reference X_sim = (np.sin(2 * np.pi * Xf * T_sim) + Xo) * Xa elif X == 2: # Square wave reference X_sim = (np.sign(np.sin(2 * np.pi * Xf * T_sim)) + Xo) * Xa if L == 0: # Constant load L_sim = np.full_like(T_sim, La * Lo) elif L == 1: # Sine wave load L_sim = (np.sin(2 * np.pi * Lf * T_sim) + Lo) * La elif L == 2: # Square wave load L_sim = (np.sign(np.sin(2 * np.pi * Lf * T_sim)) + Lo) * La elif L_type.value == 3: # Noise form load L_sim = np.interp(T_sim, np.linspace(0, T, int(T * Lf) + 2), np.random.normal(loc=(Lo * La), scale=La, size=int(T * Lf) + 2)) # System response Tx, youtx, xoutx = c.forced_response(W_closed, T_sim, X_sim) Tl, youtl, xoutl = c.forced_response(W_load, T_sim, L_sim) R_sim = np.nan_to_num(youtx + youtl) # Display XR_max = max(np.amax(np.absolute(np.concatenate((X_sim, R_sim)))), Xa) L_max = max(np.amax(np.absolute(L_sim)), La) anim_ax1.set_xlim((0, T)) anim_ax1.set_ylim((-1.2 * XR_max, 1.2 * XR_max)) anim_ax2.set_ylim((-1.5 * L_max, 1.5 * L_max)) global T_plot, X_plot, L_plot, R_plot, pos_var, ref_var T_plot = np.linspace(0, T, frame_count, dtype=np.float32) X_plot = np.interp(T_plot, T_sim, X_sim) L_plot = np.interp(T_plot, T_sim, L_sim) R_plot = np.interp(T_plot, T_sim, R_sim) pos_var = R_plot/XR_max ref_var = X_plot/XR_max def anim_init(): line1.set_data([], []) line2.set_data([], []) line3.set_data([], []) b_line.set_data([], []) k_line.set_data([], []) x_arrow.set_xy(base_arrow) r_arrow.set_xy(base_arrow) m_text.set_position((1.75, 0.5)) m_box.set_xy((1, 0)) return (line1, line2, line3, m_text, m_box, b_line, k_line,) def animate(i): line1.set_data(T_plot[0:i], X_plot[0:i]) line2.set_data(T_plot[0:i], R_plot[0:i]) line3.set_data(T_plot[0:i], L_plot[0:i]) b_line.set_data([-1.3, -1.3, -1.3, 1]+pos_var[i], [0.66, 0.84, 0.75, 0.75]) k_line.set_data(np.append(np.array([0, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 22])*(pos_var[i]+2)/20-2.3, pos_var[i]+1), [0.25, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.16, 0.34, 0.25, 0.25]) x_arrow.set_xy(base_arrow+[ref_var[i], 0]) r_arrow.set_xy(base_arrow+[pos_var[i], 0]) m_text.set_position((pos_var[i]+1.75, 0.5)) m_box.set_x(pos_var[i]+1) return (line1, line2, line3, m_text, m_box, b_line, k_line,) anim = animation.FuncAnimation(anim_fig, animate, init_func=anim_init, frames=frame_count, interval=10, blit=True, repeat=True) # Controllers T_slider = w.FloatLogSlider(value=10, base=10, min=-0.7, max=1, step=0.01, description='Duration [s]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) dt_slider = w.FloatLogSlider(value=0.1, base=10, min=-3, max=-1, step=0.01, description='Timestep [s]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) X_type = w.Dropdown(options=[('Constant', 0), ('Sine', 1), ('Square', 2)], value=1, description='Reference: ', continuous_update=False, layout=w.Layout(width='auto', flex='3 3 auto')) Xf_slider = w.FloatLogSlider(value=0.5, base=10, min=-2, max=2, step=0.01, description='Frequency [Hz]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) Xa_slider = w.FloatLogSlider(value=1, base=10, min=-2, max=2, step=0.01, description='Amplitude [m]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) Xo_slider = w.FloatSlider(value=0, min=-10, max=10, description='Offset/Ampl:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) L_type = w.Dropdown(options=[('Constant', 0), ('Sine', 1), ('Square', 2), ('Noise', 3)], value=2, description='Load: ', continuous_update=False, layout=w.Layout(width='auto', flex='3 3 auto')) Lf_slider = w.FloatLogSlider(value=1, base=10, min=-2, max=2, step=0.01, description='Frequency [Hz]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) La_slider = w.FloatLogSlider(value=0.1, base=10, min=-2, max=2, step=0.01, description='Amplitude [N]:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) Lo_slider = w.FloatSlider(value=0, min=-10, max=10, description='Offset/Ampl:', continuous_update=False, orientation='vertical', layout=w.Layout(width='auto', height='auto', flex='1 1 auto')) input_data = w.interactive_output(simulation, {'Kp': Kp_slider, 'Ti': Ti_slider, 'Td': Td_slider, 'Fd': Fd_slider, 'Ti0' : Ti_button, 'Td0': Td_button, 'Fd0': Fd_button, 'm':m_slider, 'k':k_slider, 'b':b_slider, 'T': T_slider, 'dt': dt_slider, 'X': X_type, 'Xf': Xf_slider, 'Xa': Xa_slider, 'Xo': Xo_slider, 'L': L_type, 'Lf': Lf_slider, 'La': La_slider, 'Lo': Lo_slider}) display(w.HBox([w.HBox([T_slider, dt_slider], layout=w.Layout(width='25%')), w.Box([], layout=w.Layout(width='5%')), w.VBox([X_type, w.HBox([Xf_slider, Xa_slider, Xo_slider])], layout=w.Layout(width='30%')), w.Box([], layout=w.Layout(width='5%')), w.VBox([L_type, w.HBox([Lf_slider, La_slider, Lo_slider])], layout=w.Layout(width='30%'))], layout=w.Layout(width='100%', justify_content='center')), input_data) ``` The duration parameter controls the simulated timeframe and does not affect the runtime of the animation. In contrast, the timestep controls the model sampling and can refine the results in exchange for higher computational resources.
github_jupyter
<a href="https://colab.research.google.com/github/kartikgill/The-GAN-Book/blob/main/Skill-07/W-GAN.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Importing useful Libraries ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm_notebook %matplotlib inline import tensorflow print (tensorflow.__version__) ``` # Download and show data ``` from tensorflow.keras.datasets import fashion_mnist, mnist (trainX, trainY), (testX, testY) = mnist.load_data() print('Training data shapes: X=%s, y=%s' % (trainX.shape, trainY.shape)) print('Testing data shapes: X=%s, y=%s' % (testX.shape, testY.shape)) for k in range(9): plt.figure(figsize=(9, 6)) for j in range(9): i = np.random.randint(0, 10000) plt.subplot(990 + 1 + j) plt.imshow(trainX[i], cmap='gray_r') #plt.title(trainY[i]) plt.axis('off') plt.show() #Ten classes set(trainY) ``` # Data Normalization ``` trainX = [(image-127.5)/127.5 for image in trainX] testX = [(image-127.5)/127.5 for image in testX] trainX = np.reshape(trainX, (60000, 28, 28, 1)) testX = np.reshape(testX, (10000, 28, 28, 1)) print (trainX.shape, testX.shape, trainY.shape, testY.shape) ``` # Define Generator Model ``` random_input = tensorflow.keras.layers.Input(shape = 100) x = tensorflow.keras.layers.Dense(7*7*128)(random_input) x = tensorflow.keras.layers.Reshape((7, 7, 128))(x) x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), strides=2, padding='same')(x) x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x) x = tensorflow.keras.layers.Activation('relu')(x) x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), strides=2, padding='same')(x) x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x) x = tensorflow.keras.layers.Activation('relu')(x) x = tensorflow.keras.layers.Conv2DTranspose(filters=128, kernel_size=(3,3), padding='same')(x) x = tensorflow.keras.layers.Activation('relu')(x) x = tensorflow.keras.layers.Conv2DTranspose(filters=1, kernel_size=(4,4), padding='same')(x) generated_image = tensorflow.keras.layers.Activation('tanh')(x) generator_network = tensorflow.keras.models.Model(inputs=random_input, outputs=generated_image) generator_network.summary() ``` # Define Critic ``` image_input = tensorflow.keras.layers.Input(shape=(28, 28, 1)) x = tensorflow.keras.layers.Conv2D(filters=64, kernel_size=(3,3), strides=2, padding='same')(image_input) x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x) x = tensorflow.keras.layers.Dropout(0.25)(x) x = tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), strides=2, padding='same')(x) x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x) x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x) x = tensorflow.keras.layers.Dropout(0.25)(x) x = tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), strides=2, padding='same')(x) x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x) x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x) x = tensorflow.keras.layers.Dropout(0.25)(x) x = tensorflow.keras.layers.Conv2D(filters=256, kernel_size=(3,3), padding='same')(x) x = tensorflow.keras.layers.BatchNormalization(momentum=0.8)(x) x = tensorflow.keras.layers.LeakyReLU(alpha=0.2)(x) x = tensorflow.keras.layers.Dropout(0.25)(x) x = tensorflow.keras.layers.Flatten()(x) # No activation in final layer c_out = tensorflow.keras.layers.Dense(1)(x) critic_network = tensorflow.keras.models.Model(inputs=image_input, outputs=c_out) print (critic_network.summary()) ``` # Define Wasserstein Loss ``` # custom loss function def wasserstein_loss(y_true, y_pred): return tensorflow.keras.backend.mean(y_true * y_pred) ``` # Compiling Critic Network ``` RMSprop_optimizer = tensorflow.keras.optimizers.RMSprop(lr=0.00005) critic_network.compile(loss=wasserstein_loss, optimizer=RMSprop_optimizer, metrics=['accuracy']) ``` # Define Wasserstein GAN (W-GAN) ``` critic_network.trainable=False g_output = generator_network(random_input) c_output = critic_network(g_output) wgan_model = tensorflow.keras.models.Model(inputs = random_input, outputs = c_output) wgan_model.summary() ``` # Compiling WGAN ``` wgan_model.compile(loss=wasserstein_loss, optimizer=RMSprop_optimizer) ``` # Define Data Generators ``` indices = [i for i in range(0, len(trainX))] def get_random_noise(batch_size, noise_size): random_values = np.random.randn(batch_size*noise_size) random_noise_batches = np.reshape(random_values, (batch_size, noise_size)) return random_noise_batches def get_fake_samples(generator_network, batch_size, noise_size): random_noise_batches = get_random_noise(batch_size, noise_size) fake_samples = generator_network.predict_on_batch(random_noise_batches) return fake_samples def get_real_samples(batch_size): random_indices = np.random.choice(indices, size=batch_size) real_images = trainX[np.array(random_indices),:] return real_images def show_generator_results(generator_network): for k in range(7): plt.figure(figsize=(9, 6)) random_noise_batches = get_random_noise(7, noise_size) fake_samples = generator_network.predict_on_batch(random_noise_batches) for j in range(7): i = j plt.subplot(770 + 1 + j) plt.imshow(((fake_samples[i,:,:,-1])/2.0)+0.5, cmap='gray_r') plt.axis('off') plt.show() return ``` # Training W-GAN ``` epochs = 500 batch_size = 64 steps = 500 noise_size = 100 for i in range(0, epochs): if (i%1 == 0): op = show_generator_results(generator_network) #print (op) for j in range(steps): # With Number of Critics=5 for _ in range(5): fake_samples = get_fake_samples(generator_network, batch_size//2, noise_size) real_samples = get_real_samples(batch_size=batch_size//2) fake_y = np.ones((batch_size//2, 1)) real_y = -1 * np.ones((batch_size//2, 1)) # Updating Critic weights critic_network.trainable=True loss_c_real = critic_network.train_on_batch(real_samples, real_y) loss_c_fake = critic_network.train_on_batch(fake_samples, fake_y) loss_c = np.add(loss_c_real, loss_c_fake)/2.0 # Clip critic weights for l in critic_network.layers: weights = l.get_weights() weights = [np.clip(w, -0.01, 0.01) for w in weights] l.set_weights(weights) if False: print ("C_real_loss: %.3f, C_fake_loss: %.3f, C_loss: %.3f"%(loss_c_real[0], loss_c_fake[0], loss_c[0])) noise_batches = get_random_noise(batch_size, noise_size) wgan_input = noise_batches # Make the Discriminator belive that these are real samples and calculate loss to train the generator wgan_output = -1 * np.ones((batch_size, 1)) # Updating Generator weights critic_network.trainable=False loss_g = wgan_model.train_on_batch(wgan_input, wgan_output) if j%50 == 0: print ("Epoch:%.0f, Step:%.0f, C-Loss:%.6f, G-Loss:%.6f"%(i,j,loss_c[0] ,loss_g)) ``` # Results ``` for i in range(2): show_generator_results(generator_network) print("-"*100) ```
github_jupyter
<i>Copyright (c) Microsoft Corporation. All rights reserved.</i> <i>Licensed under the MIT License.</i> # Bayesian Personalized Ranking (BPR) This notebook serves as an introduction to Bayesian Personalized Ranking (BPR) model for implicit feedback. In this tutorial, we focus on learning the BPR model using matrix factorization approach, hence, the model is sometimes also named BPRMF. The implementation of the model is from [Cornac](https://github.com/PreferredAI/cornac), which is a framework for recommender systems with a focus on models leveraging auxiliary data (e.g., item descriptive text and image, social network, etc). ## 0 Global Settings and Imports ``` import sys import os import cornac import papermill as pm import scrapbook as sb import pandas as pd from recommenders.datasets import movielens from recommenders.datasets.python_splitters import python_random_split from recommenders.evaluation.python_evaluation import map_at_k, ndcg_at_k, precision_at_k, recall_at_k from recommenders.models.cornac.cornac_utils import predict_ranking from recommenders.utils.timer import Timer from recommenders.utils.constants import SEED print("System version: {}".format(sys.version)) print("Cornac version: {}".format(cornac.__version__)) # Select MovieLens data size: 100k, 1m, 10m, or 20m MOVIELENS_DATA_SIZE = '100k' # top k items to recommend TOP_K = 10 # Model parameters NUM_FACTORS = 200 NUM_EPOCHS = 100 ``` ## 1 BPR Algorithm ### 1.1 Personalized Ranking from Implicit Feedback The task of personalized ranking aims at providing each user a ranked list of items (recommendations). This is very common in scenarios where recommender systems are based on implicit user behavior (e.g. purchases, clicks). The available observations are only positive feedback where the non-observed ones are a mixture of real negative feedback and missing values. One usual approach for item recommendation is directly predicting a preference score $\hat{x}_{u,i}$ given to item $i$ by user $u$. BPR uses a different approach by using item pairs $(i, j)$ and optimizing for the correct ranking given preference of user $u$, thus, there are notions of *positive* and *negative* items. The training data $D_S : U \times I \times I$ is defined as: $$D_S = \{(u, i, j) \mid i \in I^{+}_{u} \wedge j \in I \setminus I^{+}_{u}\}$$ where user $u$ is assumed to prefer $i$ over $j$ (i.e. $i$ is a *positive item* and $j$ is a *negative item*). ### 1.2 Objective Function From the Bayesian perspective, BPR maximizes the posterior probability over the model parameters $\Theta$ by optimizing the likelihood function $p(i >_{u} j | \Theta)$ and the prior probability $p(\Theta)$. $$p(\Theta \mid >_{u}) \propto p(i >_{u} j \mid \Theta) \times p(\Theta)$$ The joint probability of the likelihood over all users $u \in U$ can be simplified to: $$ \prod_{u \in U} p(>_{u} \mid \Theta) = \prod_{(u, i, j) \in D_S} p(i >_{u} j \mid \Theta) $$ The individual probability that a user $u$ prefers item $i$ to item $j$ can be defined as: $$ p(i >_{u} j \mid \Theta) = \sigma (\hat{x}_{uij}(\Theta)) $$ where $\sigma$ is the logistic sigmoid: $$ \sigma(x) = \frac{1}{1 + e^{-x}} $$ The preference scoring function $\hat{x}_{uij}(\Theta)$ could be an arbitrary real-valued function of the model parameter $\Theta$. Thus, it makes BPR a general framework for modeling the relationship between triplets $(u, i, j)$ where different model classes like matrix factorization could be used for estimating $\hat{x}_{uij}(\Theta)$. For the prior, one of the common pratices is to choose $p(\Theta)$ following a normal distribution, which results in a nice form of L2 regularization in the final log-form of the objective function. $$ p(\Theta) \sim N(0, \Sigma_{\Theta}) $$ To reduce the complexity of the model, all parameters $\Theta$ are assumed to be independent and having the same variance, which gives a simpler form of the co-variance matrix $\Sigma_{\Theta} = \lambda_{\Theta}I$. Thus, there are less number of hyperparameters to be determined. The final objective of the maximum posterior estimator: $$ J = \sum_{(u, i, j) \in D_S} \text{ln } \sigma(\hat{x}_{uij}) - \lambda_{\Theta} ||\Theta||^2 $$ where $\lambda_\Theta$ are the model specific regularization paramerters. ### 1.3 Learning with Matrix Factorization #### Stochastic Gradient Descent As the defined objective function is differentible, gradient descent based method for optimization is naturally adopted. The gradient of the objective $J$ with respect to the model parameters: $$ \begin{align} \frac{\partial J}{\partial \Theta} & = \sum_{(u, i, j) \in D_S} \frac{\partial}{\partial \Theta} \text{ln} \ \sigma(\hat{x}_{uij}) - \lambda_{\Theta} \frac{\partial}{\partial \Theta} ||\Theta||^2 \\ & \propto \sum_{(u, i, j) \in D_S} \frac{-e^{-\hat{x}_{uij}}}{1 + e^{-\hat{x}_{uij}}} \cdot \frac{\partial}{\partial \Theta} \hat{x}_{uij} - \lambda_{\Theta} \Theta \end{align} $$ Due to slow convergence of full gradient descent, we prefer using stochastic gradient descent to optimize the BPR model. For each triplet $(u, i, j) \in D_S$, the update rule for the parameters: $$ \Theta \leftarrow \Theta + \alpha \Big( \frac{e^{-\hat{x}_{uij}}}{1 + e^{-\hat{x}_{uij}}} \cdot \frac{\partial}{\partial \Theta} \hat{x}_{uij} + \lambda_\Theta \Theta \Big) $$ #### Matrix Factorization for Preference Approximation As mentioned earlier, the preference scoring function $\hat{x}_{uij}(\Theta)$ could be approximated by any real-valued function. First, the estimator $\hat{x}_{uij}$ is decomposed into: $$ \hat{x}_{uij} = \hat{x}_{ui} - \hat{x}_{uj} $$ The problem of estimating $\hat{x}_{ui}$ is a standard collaborative filtering formulation, where matrix factorization approach has shown to be very effective. The prediction formula can written as dot product between user feature vector $w_u$ and item feature vector $h_i$: $$ \hat{x}_{ui} = \langle w_u , h_i \rangle = \sum_{f=1}^{k} w_{uf} \cdot h_{if} $$ The derivatives of matrix factorization with respect to the model parameters are: $$ \frac{\partial}{\partial \theta} \hat{x}_{uij} = \begin{cases} (h_{if} - h_{jf}) & \text{if } \theta = w_{uf} \\ w_{uf} & \text{if } \theta = h_{if} \\ -w_{uf} & \text{if } \theta = h_{jf} \\ 0 & \text{else} \end{cases} $$ In theory, any kernel can be used to estimate $\hat{x}_{ui}$ besides the dot product $ \langle \cdot , \cdot \rangle $. For example, k-Nearest-Neighbor (kNN) has also been shown to achieve good performance. #### Analogies to AUC optimization By optimizing the objective function of BPR model, we effectively maximizing [AUC](https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5) measurement. To keep the notebook focused, please refer to the [paper](https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf) for details of the analysis (Section 4.1.1). ## 2 Cornac implementation of BPR BPR is implemented in the [Cornac](https://cornac.readthedocs.io/en/latest/index.html) framework as part of the model collections. * Detailed documentations of the BPR model in Cornac can be found [here](https://cornac.readthedocs.io/en/latest/models.html#bayesian-personalized-ranking-bpr). * Source codes of the BPR implementation is available on the Cornac Github repository, which can be found [here](https://github.com/PreferredAI/cornac/blob/master/cornac/models/bpr/recom_bpr.pyx). ## 3 Cornac BPR movie recommender ### 3.1 Load and split data To evaluate the performance of item recommendation, we adopted the provided `python_random_split` tool for the consistency. Data is randomly split into training and test sets with the ratio of 75/25. Note that Cornac also cover different [built-in schemes](https://cornac.readthedocs.io/en/latest/eval_methods.html) for model evaluation. ``` data = movielens.load_pandas_df( size=MOVIELENS_DATA_SIZE, header=["userID", "itemID", "rating"] ) data.head() train, test = python_random_split(data, 0.75) ``` ### 3.2 Cornac Dataset To work with models implemented in Cornac, we need to construct an object from [Dataset](https://cornac.readthedocs.io/en/latest/data.html#module-cornac.data.dataset) class. Dataset Class in Cornac serves as the main object that the models will interact with. In addition to data transformations, Dataset provides a bunch of useful iterators for looping through the data, as well as supporting different negative sampling techniques. ``` train_set = cornac.data.Dataset.from_uir(train.itertuples(index=False), seed=SEED) print('Number of users: {}'.format(train_set.num_users)) print('Number of items: {}'.format(train_set.num_items)) ``` ### 3.3 Train the BPR model The BPR has a few important parameters that we need to consider: - `k`: controls the dimension of the latent space (i.e. the size of the vectors $w_u$ and $h_i$ ). - `max_iter`: defines the number of iterations of the SGD procedure. - `learning_rate`: controls the step size $\alpha$ in the gradient update rules. - `lambda_reg`: controls the L2-Regularization $\lambda$ in the objective function. Note that different values of `k` and `max_iter` will affect the training time. We will here set `k` to 200, `max_iter` to 100, `learning_rate` to 0.01, and `lambda_reg` to 0.001. To train the model, we simply need to call the `fit()` method. ``` bpr = cornac.models.BPR( k=NUM_FACTORS, max_iter=NUM_EPOCHS, learning_rate=0.01, lambda_reg=0.001, verbose=True, seed=SEED ) with Timer() as t: bpr.fit(train_set) print("Took {} seconds for training.".format(t)) ``` ### 3.4 Prediction and Evaluation Now that our model is trained, we can produce the ranked lists for recommendation. Every recommender models in Cornac provide `rate()` and `rank()` methods for predicting item rated value as well as item ranked list for a given user. To make use of the current evaluation schemes, we will through `predict()` and `predict_ranking()` functions inside `cornac_utils` to produce the predictions. Note that BPR model is effectively designed for item ranking. Hence, we only measure the performance using ranking metrics. ``` with Timer() as t: all_predictions = predict_ranking(bpr, train, usercol='userID', itemcol='itemID', remove_seen=True) print("Took {} seconds for prediction.".format(t)) all_predictions.head() k = 10 eval_map = map_at_k(test, all_predictions, col_prediction='prediction', k=k) eval_ndcg = ndcg_at_k(test, all_predictions, col_prediction='prediction', k=k) eval_precision = precision_at_k(test, all_predictions, col_prediction='prediction', k=k) eval_recall = recall_at_k(test, all_predictions, col_prediction='prediction', k=k) print("MAP:\t%f" % eval_map, "NDCG:\t%f" % eval_ndcg, "Precision@K:\t%f" % eval_precision, "Recall@K:\t%f" % eval_recall, sep='\n') # Record results with papermill for tests sb.glue("map", eval_map) sb.glue("ndcg", eval_ndcg) sb.glue("precision", eval_precision) sb.glue("recall", eval_recall) ``` ## References 1. Rendle, S., Freudenthaler, C., Gantner, Z., & Schmidt-Thieme, L. (2009, June). BPR: Bayesian personalized ranking from implicit feedback. https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf 2. Pan, R., Zhou, Y., Cao, B., Liu, N. N., Lukose, R., Scholz, M., & Yang, Q. (2008, December). One-class collaborative filtering. https://cseweb.ucsd.edu/classes/fa17/cse291-b/reading/04781145.pdf 3. **Cornac** - A Comparative Framework for Multimodal Recommender Systems. https://cornac.preferred.ai/
github_jupyter
# Day 13 - Prime number factors * https://adventofcode.com/2020/day/13 For part 1, we need to find the next multiple of a bus ID that's equal to or greater than our earliest departure time. The bus IDs, which determine their frequency, are all prime numbers, of course. We can calculate the next bus departure $t$ for a given ID $b$ on or after earliest departure time $T$ as $t = b * \lceil T / b \rceil$ ($b$ multiplied by the ceiling of the division of $T$ by $b$). ``` import math def parse_bus_ids(line: str) -> list[int]: return [int(b) for b in line.split(",") if b[0] != "x"] def parse_input(lines: str) -> [int, list[int]]: return int(lines[0]), parse_bus_ids(lines[1]) def earliest_departure(earliest: int, bus_ids: list[int]) -> tuple[int, int]: t, bid = min((bid * math.ceil(earliest / bid), bid) for bid in bus_ids) return t - earliest, bid test_earliest, test_bus_ids = parse_input(["939", "7,13,x,x,59,x,31,19"]) assert earliest_departure(test_earliest, test_bus_ids) == (5, 59) import aocd data = aocd.get_data(day=13, year=2020).splitlines() earliest, bus_ids = parse_input(data) wait_time, bus_id = earliest_departure(earliest, bus_ids) print("Part 1:", wait_time * bus_id) ``` ## Part 2: Chinese remainder theorem. For part 2, we need to use the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem); this theorem was first introduced by the Chinese mathematician Sun-tzu (quote from the Wikipedia article): > There are certain things whose number is unknown. If we count them by threes, we have two left over; by fives, we have three left over; and by sevens, two are left over. How many things are there? We need to find a number that if counted in prime number steps, have an offset left over, where the offset is the prime number minus the index in the bus ids list, modulo the bus id (the matching time stamp lies X minutes *before* the next bus departs). I only remembered about the theorem as it was also applicable to [Advent of Code 2017, day 13](../2017/Day%2013.ipynb) (although I didn't know it at the time). I adapted the [Rossetta Stone Python implementation](https://rosettacode.org/wiki/Chinese_remainder_theorem#Python) for this: ``` from functools import reduce from operator import mul from typing import Optional def solve_chinese_remainder(bus_times: list[Optional[int]]) -> int: product = reduce(mul, (bid for bid in filter(None, bus_times))) summed = sum( ((bid - i) % bid) * mul_inv((factor := product // bid), bid) * factor for i, bid in enumerate(bus_times) if bid is not None ) return summed % product def mul_inv(a: int, b: int) -> int: if b == 1: return 1 b0, x0, x1 = b, 0, 1 while a > 1: q = a // b a, b = b, a % b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 def parse_bus_times(line: str) -> list[Optional[int]]: return [None if bus_id == "x" else int(bus_id) for bus_id in line.split(",")] tests = { "7,13,x,x,59,x,31,19": 1068781, "17,x,13,19": 3417, "67,7,59,61": 754018, "67,x,7,59,61": 779210, "67,7,x,59,61": 1261476, "1789,37,47,1889": 1202161486, } for times, expected in tests.items(): assert solve_chinese_remainder(parse_bus_times(times)) == expected print("Part 2:", solve_chinese_remainder(parse_bus_times(data[1]))) ```
github_jupyter
<a href="https://colab.research.google.com/github/jeffheaton/t81_558_deep_learning/blob/master/tensorflow-install-mac-metal-jul-2021.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # T81-558: Applications of Deep Neural Networks **Manual Python Setup** * Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) * For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-558/). # Software Installation (Mac on Apple Metal M1) This class is technically oriented. A successful student needs to be able to compile and execute Python code that makes use of TensorFlow for deep learning. There are two options for you to accomplish this: * Install Python, TensorFlow, and some IDE (Jupyter, TensorFlow, and others) * Use Google CoLab in the cloud ## Installing Python and TensorFlow Is your Mac Intel or Apple Metal (ARM)? The newer Mac ARM M1-based machines have considerably better deep learning support than their older Intel-based counterparts. Mac has not supported NVIDIA GPUs since 2016; however, the new M1 chips offer similar capabilities that will allow you to run most of the code in this course. You can run any code not supported by the Apple M1 chip through Google CoLab, a free GPU-based Python environment. If you are running an older Intel Mac, there still are some options. Refer to my [Intel Mac installation guide](tensorflow-install-mac-jan-2021.ipynb). With the introduction of the M1 chip, Apple introduced a system on a chip. The new Mac M1 contains CPU, GPU, and deep learning hardware support, all on a single chip. The Mac M1 can run software created for the older Intel Mac's using an emulation layer called [Rosetta](https://en.wikipedia.org/wiki/Rosetta_(software)). To leverage the new M1 chip from Python, you must use a special Python distribution called [Miniforge](https://github.com/conda-forge/miniforge). Miniforge replaces other Python distributions that you might have installed, such as Anaconda or Miniconda. Apple instructions suggest that you remove Anaconda or Miniconda before installing Miniforge. Because the Mac M1 is a very different architecture than Intel, the Miniforge distribution will maximize your performance. Be aware that once you install Miniforge, it will become your default Python interpreter. ## Install Miniforge There are a variety of methods for installing Miniforge. If you have trouble following my instructions, you may refer to this [installation process](https://developer.apple.com/metal/tensorflow-plugin/), upon which I base these instructions. I prefer to use [Homebrew](https://brew.sh/) to install Miniforge. Homebrew is a package manager for the Mac, similar to **yum** or **apt-get** for Linux. To install Homebrew, follow this [link](https://brew.sh/) and copy/paste the installation command into a Mac terminal window. Once you have installed Homebrew, I suggest closing the terminal window and opening a new one to complete the installation. Next, you should install the xcode-select command-line utilities. Use the following command to install: ``` xcode-select --install ``` If the above command gives an error, you should install XCode from the App Store. You will now use Homebrew to install Miniforge with the following command: ``` brew install miniforge ``` You should note which directory ## Initiate Miniforge Run the following command to initiate your conda base environment: ``` conda init ``` This will set the python `PATH` to the Miniforge base in your profile (`~/.bash_profile` if bash or `~/.zshenv` if zsh) and create the base virtual environment. ## Make Sure you Have the Correct Python (when things go wrong) Sometimes previous versions of Python might have been installed, and when you attempt to run the install script below you will recieve an error: ``` Collecting package metadata (repodata.json): done Solving environment: failed ResolvePackageNotFound: - tensorflow-deps ``` To verify that you have the correct Python version registered, close and reopen your terminal window. Issue the following command: ``` which python ``` This command should respond with something similar to: ``` /opt/homebrew/Caskroom/miniforge/base/bin/python ``` The key things to look for in the above response are "homebrew" and "miniforge". If you see "anaconda" or "miniconda" your path is pointing to the wrong Python. You will need to modify your ".zshrc", make sure that the three Python paths match the path that "brew" installed it into earlier. Most likely your "miniforge" is installed in one of these locations: * /usr/local/Caskroom/miniforge/base * /opt/homebrew/Caskroom/miniforge/base More info [here](https://github.com/conda-forge/miniforge/issues/127). ## Install Jupyter and Create Environment Next, lets install Jupyter, which is the editor you will use in this course. ``` conda install -y jupyter ``` We will actually launch Jupyter later. First, we deactivate the base environment. ``` conda deactivate ``` Next, we will install the Mac M1 [tensorflow-apple-metal.yml](https://raw.githubusercontent.com/jeffheaton/t81_558_deep_learning/master/tensorflow-apple-metal.yml) file that I provide. Run the following command from the same directory that contains **tensorflow-apple-metal.yml**. ``` conda env create -f tensorflow-apple-metal.yml -n tensorflow ``` # Issues Creating Environment (when things go wrong) Due to some [recent changes](https://github.com/grpc/grpc/issues/25082) in one of the TensorFlow dependancies you may get the following error when installing the YML file. ``` Collecting grpcio Using cached grpcio-1.34.0.tar.gz (21.0 MB) ERROR: Command errored out with exit status 1: ``` If you encounter this error, remove your environment, define two environmental variables, and try again: ``` conda env remove --name tensorflow export GRPC_PYTHON_BUILD_SYSTEM_OPENSSL=1 export GRPC_PYTHON_BUILD_SYSTEM_ZLIB=1 conda env create -f tensorflow-apple-metal.yml -n tensorflow ``` # Activating New Environment To enter this environment, you must use the following command: ``` conda activate tensorflow ``` For now, let's add Jupyter support to your new environment. ``` conda install nb_conda ``` ## Register your Environment The following command registers your **tensorflow** environment. Again, make sure you "conda activate" your new **tensorflow** environment. ``` python -m ipykernel install --user --name tensorflow --display-name "Python 3.9 (tensorflow)" ``` ## Testing your Environment You can now start Jupyter notebook. Use the following command. ``` jupyter notebook ``` You can now run the following code to check that you have the versions expected. ``` # What version of Python do you have? import sys import tensorflow.keras import pandas as pd import sklearn as sk import tensorflow as tf print(f"Tensor Flow Version: {tf.__version__}") print(f"Keras Version: {tensorflow.keras.__version__}") print() print(f"Python {sys.version}") print(f"Pandas {pd.__version__}") print(f"Scikit-Learn {sk.__version__}") gpu = len(tf.config.list_physical_devices('GPU'))>0 print("GPU is", "available" if gpu else "NOT AVAILABLE") ```
github_jupyter
``` cat ratings_train.txt | head -n 10 def read_data(filename): with open(filename, 'r') as f: data = [line.split('\t') for line in f.read().splitlines()] # txt 파일의 헤더(id document label)는 제외하기 data = data[1:] return data train_data = read_data('ratings_train.txt') test_data = read_data('ratings_test.txt') print(len(train_data)) print(train_data[0]) print(len(test_data)) print(len(test_data[0])) from konlpy.tag import Okt okt = Okt() print(okt.pos(u'이 밤 그날의 반딧불을 당신의 창 가까이 보낼게요')) import json import os from pprint import pprint def tokenize(doc): # norm은 정규화, stem은 근어로 표시하기를 나타냄 return ['/'.join(t) for t in okt.pos(doc, norm=True, stem=True)] if os.path.isfile('train_docs.json'): with open('train_docs.json') as f: train_docs = json.load(f) with open('test_docs.json') as f: test_docs = json.load(f) else: train_docs = [(tokenize(row[1]), row[2]) for row in train_data] test_docs = [(tokenize(row[1]), row[2]) for row in test_data] # JSON 파일로 저장 with open('train_docs.json', 'w', encoding="utf-8") as make_file: json.dump(train_docs, make_file, ensure_ascii=False, indent="\t") with open('test_docs.json', 'w', encoding="utf-8") as make_file: json.dump(test_docs, make_file, ensure_ascii=False, indent="\t") # 예쁘게(?) 출력하기 위해서 pprint 라이브러리 사용 pprint(train_docs[0]) tokens = [t for d in train_docs for t in d[0]] print(len(tokens)) import nltk text = nltk.Text(tokens, name='NMSC') # 전체 토큰의 개수 print(len(text.tokens)) # 중복을 제외한 토큰의 개수 print(len(set(text.tokens))) # 출현 빈도가 높은 상위 토큰 10개 pprint(text.vocab().most_common(10)) import matplotlib.pyplot as plt from matplotlib import font_manager, rc %matplotlib inline font_fname = '/Library/Fonts/NanumGothic.ttf' font_name = font_manager.FontProperties(fname=font_fname).get_name() rc('font', family=font_name) plt.figure(figsize=(20,10)) text.plot(50) selected_words = [f[0] for f in text.vocab().most_common(100)] def term_frequency(doc): return [doc.count(word) for word in selected_words] train_x = [term_frequency(d) for d, _ in train_docs] test_x = [term_frequency(d) for d, _ in test_docs] train_y = [c for _, c in train_docs] test_y = [c for _, c in test_docs] import tensorflow as tf checkpoint_path = "training_1/cp.ckpt" checkpoint_dir = os.path.dirname(checkpoint_path) cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, save_weights_only=True, verbose=1) import numpy as np x_train = np.asarray(train_x).astype('float32') x_test = np.asarray(test_x).astype('float32') y_train = np.asarray(train_y).astype('float32') y_test = np.asarray(test_y).astype('float32') from tensorflow.keras import models from tensorflow.keras import layers from tensorflow.keras import optimizers from tensorflow.keras import losses from tensorflow.keras import metrics model = models.Sequential() model.add(layers.Dense(64, activation='relu', input_shape=(100,))) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy]) model.fit(x_train, y_train, epochs=10, batch_size=512, callbacks=[cp_callback]) results = model.evaluate(x_test, y_test) results def predict_pos_neg(review): token = tokenize(review) tf = term_frequency(token) data = np.expand_dims(np.asarray(tf).astype('float32'), axis=0) score = float(model.predict(data)) if(score > 0.5): #print("[{}]는 {:.2f}% 확률로 긍정 리뷰이지 않을까 추측해봅니다.^^\n".format(review, score * 100)) return score else: #print("[{}]는 {:.2f}% 확률로 부정 리뷰이지 않을까 추측해봅니다.^^;\n".format(review, (1 - score) * 100)) return -score ''' predict_pos_neg("올해 최고의 영화! 세 번 넘게 봐도 질리지가 않네요.") predict_pos_neg("배경 음악이 영화의 분위기랑 너무 안 맞았습니다. 몰입에 방해가 됩니다.") predict_pos_neg("주연 배우가 신인인데 연기를 진짜 잘 하네요. 몰입감 ㅎㄷㄷ") predict_pos_neg("믿고 보는 감독이지만 이번에는 아니네요") predict_pos_neg("주연배우 때문에 봤어요") ''' ''' predict_pos_neg("혹시 UCPC 본선") predict_pos_neg("진출한 팀 있나요") predict_pos_neg("3분 후 본선 끝나는데") predict_pos_neg("우리팀만 했나 해서..") ''' def read_chat_data(filename): with open(filename, 'r') as f: data = [line.split('\t') for line in f.read().splitlines()] return data def make_score_dictionary(data): score_list = {} for chat in data: if(chat[0] in score_list): score_list[chat[0]].append(predict_pos_neg(chat[1])) else: score_list[chat[0]] = [predict_pos_neg(chat[1])] return score_list def make_average_score_dictionary(score_dictionary): average_score_dictionary = {} for key in score_dictionary.keys(): average_score_dictionary[key] = sum(score_dictionary[key])/len(score_dictionary[key]) return average_score_dictionary print(make_average_score_dictionary(make_score_dictionary(read_chat_data('test.txt')))) ```
github_jupyter
``` import pandas as pd import numpy as np import zucaml.zucaml as ml import matplotlib.pyplot as plt %matplotlib inline pd.set_option('display.max_columns', None) ``` #### gold ``` df_gold = ml.get_csv('data/gold/', 'gold', []) df_gold = df_gold.sort_values(['date', 'x', 'y', 'z'], ascending = [True, True, True, True]) results_grid = pd.DataFrame({}, index = []) ml.print_memory(df_gold) df_gold[:5] ``` #### features ``` target = 'target' time_ref = 'date' pid = 'zone_frame' all_features = { 'x': { 'class': 'location', 'type': 'categorical', 'subtype': 'onehot', 'level': 0, }, 'y': { 'class': 'location', 'type': 'categorical', 'subtype': 'onehot', 'level': 0, }, 'z': { 'class': 'location', 'type': 'categorical', 'subtype': 'onehot', 'level': 0, }, 'energy|rolling.mean#30': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#90': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#180': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#330': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#360': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy_neighbours|rolling.mean#30': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy_neighbours|rolling.mean#90': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy_neighbours|rolling.mean#180': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy_neighbours|rolling.mean#330': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy_neighbours|rolling.mean#360': { 'class': 'energy.ma', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#30||ratio||energy|rolling.mean#360': { 'class': 'energy.ratio', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#90||ratio||energy|rolling.mean#360': { 'class': 'energy.ratio', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#180||ratio||energy|rolling.mean#360': { 'class': 'energy.ratio', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'energy|rolling.mean#330||ratio||energy|rolling.mean#360': { 'class': 'energy.ratio', 'type': 'numeric', 'subtype': 'float', 'level': 0, }, 'days.since.last': { 'class': 'info', 'type': 'numeric', 'subtype': 'int', 'level': 0, }, } discarded_features = [feat for feat in df_gold if feat not in [feat2 for feat2 in all_features] + [target, time_ref, pid]] onehot_features = [feat for feat in all_features if all_features[feat]['type'] == 'categorical' and all_features[feat]['subtype'] == 'onehot'] print('Total features\t\t ' + str(len(all_features))) if len(discarded_features) > 0: print('Discarded features\t ' + str(len(discarded_features)) + '\t\t' + str(discarded_features)) print('Numerical features\t ' + str(sum([all_features[i]['type'] == 'numeric' for i in all_features]))) print('Categorical features\t ' + str(sum([all_features[i]['type'] == 'categorical' for i in all_features]))) if len(onehot_features) > 0: print('One-hot features\t ' + str(len(onehot_features)) + '\t\t' + str(onehot_features)) ``` #### Problem ``` this_problem = ml.problems.BINARY metrics = ['F0.5', 'precision', 'recall', 'roc_auc'] ``` #### split train test ``` df_train, df_test = ml.split_by_time_ref(df_gold, 0.88, target, time_ref, this_problem, True) ``` #### model ``` level_0_features = [feat for feat in all_features if all_features[feat]['level'] == 0] level_0_features_numeric = [feat for feat in level_0_features if feat not in onehot_features] level_0_features_onehot = [feat for feat in level_0_features if feat in onehot_features] level_0_features_energy_ma = [feat for feat in level_0_features if all_features[feat]['class'] == 'energy.ma'] level_0_features_energy_ratio = [feat for feat in level_0_features if all_features[feat]['class'] == 'energy.ratio'] number_categorical_onehot = df_train['x'].nunique() + df_train['y'].nunique() + df_train['z'].nunique() level_0_features_numeric_clip = [feat for feat in level_0_features_numeric if df_train[feat].abs().max() == np.inf] level_0_features_numeric_not_clip = [feat for feat in level_0_features_numeric if feat not in level_0_features_numeric_clip] level_0_features_location = [feat for feat in all_features if all_features[feat]['level'] == 0 and all_features[feat]['class'] == 'location'] %%time # ########################## # # linear models # ########################## lin_basic_config = { 'features': level_0_features, 'target': target, 'family': ml.lin(this_problem), 'algo': { 'penalty': 'l2', 'class_weight': 'balanced', }, 'preprocess': { 'original': { 'features': level_0_features, 'transformer': ['filler', 'clipper', 'standard_scaler'], }, }, } lin_params = { 'algo:C' : [0.01, 0.1, 1.0], 'algo:solver': ['lbfgs', 'newton-cg'], 'preprocess:iforest': [None, { 'features': level_0_features, 'transformer': ['filler', 'clipper', 'iforest_score'], }, ], 'preprocess:kmeans': [None, { 'features': [feat for feat in level_0_features if all_features[feat]['type'] == 'numeric' or all_features[feat]['subtype'] == 'bool'], 'transformer': ['filler', 'clipper', 'kmeans_distances'], }, ], } # ########################## # # rft models # ########################## rft_basic_config = { 'features': level_0_features, 'target': target, 'family': ml.rft(this_problem), 'algo': { 'criterion': 'entropy', 'class_weight': 'balanced', }, 'preprocess': { 'original': { 'features': level_0_features, 'transformer': ['filler', 'clipper'], }, }, } rft_params = { 'algo:max_depth': [6, 7, 8], 'algo:n_estimators': [25, 50, 75, 100, 150], 'preprocess:iforest': [None, { 'features': level_0_features, 'transformer': ['filler', 'clipper', 'iforest_score'], }, ], 'preprocess:kmeans': [None, { 'features': [feat for feat in level_0_features if all_features[feat]['type'] == 'numeric' or all_features[feat]['subtype'] == 'bool'], 'transformer': ['filler', 'clipper', 'kmeans_distances'], }, ], } # ########################## # # xgb models # ########################## xgb_basic_config = { 'features': level_0_features, 'target': target, 'family': ml.xgb(this_problem), 'algo': { 'criterion': 'entropy', 'scale_pos_weight': 'balanced', }, 'preprocess': { 'original': { 'features': level_0_features, 'transformer': ['filler', 'clipper'], }, }, } xgb_params = { 'algo:max_depth': [5, 6, 7], 'algo:n_estimators': [15, 25, 35], 'preprocess:iforest': [None, { 'features': level_0_features, 'transformer': ['filler', 'clipper', 'iforest_score'], }, ], 'preprocess:kmeans': [None, { 'features': [feat for feat in level_0_features if all_features[feat]['type'] == 'numeric' or all_features[feat]['subtype'] == 'bool'], 'transformer': ['filler', 'clipper', 'kmeans_distances'], }, ], } # ########################## # # search # ########################## basic_configs_and_params = [] basic_configs_and_params.append((lin_basic_config, lin_params)) basic_configs_and_params.append((rft_basic_config, rft_params)) basic_configs_and_params.append((xgb_basic_config, xgb_params)) grid_board, best_model = ml.grid_search( train = df_train, target = target, time_ref = time_ref, problem = this_problem, metrics = metrics, cv_strategy = ml.cv_strategies.TIME, k_fold = 3, percentage_test = 0.1, basic_configs_and_params = basic_configs_and_params, ) grid_board.sort_values(metrics[0], ascending = False).style.format(ml.results_format) label, results, register, model, final_features = ml.train_score_model(best_model, df_train, df_test, metrics) ml.results_add_all(results_grid, label, results, register) results_grid.style.format(ml.results_format) importances_groups = { '|kmeans': 'sum', } ml.plot_features_importances(model, final_features, importances_groups, True, False) shap_values = ml.get_shap_values(df_test[level_0_features], model, None) ml.plot_beeswarm(shap_values, final_features) residuals = ml.get_residuals(df_test, level_0_features, target, model, results['Threshold']) residuals['tp'].sum(), residuals['fp'].sum(), residuals['fn'].sum() notes = {} notes['number_features'] = len(level_0_features) for name_df, df in {'train': df_train, 'test': df_test}.items(): notes[name_df + '_lenght'] = len(df) notes[name_df + '_balance'] = df[target].sum() / len(df) notes[name_df + '_number_id'] = df[pid].nunique() notes[name_df + '_number_time'] = df[time_ref].nunique() notes[name_df + '_min_time'] = df[time_ref].min().strftime("%Y%m%d") notes[name_df + '_max_time'] = df[time_ref].max().strftime("%Y%m%d") for feature in ['x', 'y', 'z']: notes[name_df + '_' + feature] = list(np.sort(df[feature].unique().astype(str))) ml.save_model(model, label, results, df_train, notes) ```
github_jupyter
``` #format the book %matplotlib inline from __future__ import division, print_function import sys sys.path.insert(0, '..') import book_format book_format.set_style() ``` # Converting the Multivariate Equations to the Univariate Case The multivariate Kalman filter equations do not resemble the equations for the univariate filter. However, if we use one dimensional states and measurements the equations do reduce to the univariate equations. This section will provide you with a strong intuition into what the Kalman filter equations are actually doing. While reading this section is not required to understand the rest of the book, I recommend reading this section carefully as it should make the rest of the material easier to understand. Here are the multivariate equations for the prediction. $$ \begin{aligned} \mathbf{\bar{x}} &= \mathbf{F x} + \mathbf{B u} \\ \mathbf{\bar{P}} &= \mathbf{FPF}^\mathsf{T} + \mathbf Q \end{aligned} $$ For a univariate problem the state $\mathbf x$ only has one variable, so it is a $1\times 1$ matrix. Our motion $\mathbf{u}$ is also a $1\times 1$ matrix. Therefore, $\mathbf{F}$ and $\mathbf B$ must also be $1\times 1$ matrices. That means that they are all scalars, and we can write $$\bar{x} = Fx + Bu$$ Here the variables are not bold, denoting that they are not matrices or vectors. Our state transition is simple - the next state is the same as this state, so $F=1$. The same holds for the motion transition, so, $B=1$. Thus we have $$x = x + u$$ which is equivalent to the Gaussian equation from the last chapter $$ \mu = \mu_1+\mu_2$$ Hopefully the general process is clear, so now I will go a bit faster on the rest. We have $$\mathbf{\bar{P}} = \mathbf{FPF}^\mathsf{T} + \mathbf Q$$ Again, since our state only has one variable $\mathbf P$ and $\mathbf Q$ must also be $1\times 1$ matrix, which we can treat as scalars, yielding $$\bar{P} = FPF^\mathsf{T} + Q$$ We already know $F=1$. The transpose of a scalar is the scalar, so $F^\mathsf{T} = 1$. This yields $$\bar{P} = P + Q$$ which is equivalent to the Gaussian equation of $$\sigma^2 = \sigma_1^2 + \sigma_2^2$$ This proves that the multivariate prediction equations are performing the same math as the univariate equations for the case of the dimension being 1. These are the equations for the update step: $$ \begin{aligned} \mathbf{K}&= \mathbf{\bar{P}H}^\mathsf{T} (\mathbf{H\bar{P}H}^\mathsf{T} + \mathbf R)^{-1} \\ \textbf{y} &= \mathbf z - \mathbf{H \bar{x}}\\ \mathbf x&=\mathbf{\bar{x}} +\mathbf{K\textbf{y}} \\ \mathbf P&= (\mathbf{I}-\mathbf{KH})\mathbf{\bar{P}} \end{aligned} $$ As above, all of the matrices become scalars. $H$ defines how we convert from a position to a measurement. Both are positions, so there is no conversion, and thus $H=1$. Let's substitute in our known values and convert to scalar in one step. The inverse of a 1x1 matrix is the reciprocal of the value so we will convert the matrix inversion to division. $$ \begin{aligned} K &=\frac{\bar{P}}{\bar{P} + R} \\ y &= z - \bar{x}\\ x &=\bar{x}+Ky \\ P &= (1-K)\bar{P} \end{aligned} $$ Before we continue with the proof, I want you to look at those equations to recognize what a simple concept these equations implement. The residual $y$ is nothing more than the measurement minus the prediction. The gain $K$ is scaled based on how certain we are about the last prediction vs how certain we are about the measurement. We choose a new state $x$ based on the old value of $x$ plus the scaled value of the residual. Finally, we update the uncertainty based on how certain we are about the measurement. Algorithmically this should sound exactly like what we did in the last chapter. Let's finish off the algebra to prove this. Recall that the univariate equations for the update step are: $$ \begin{aligned} \mu &=\frac{\sigma_1^2 \mu_2 + \sigma_2^2 \mu_1} {\sigma_1^2 + \sigma_2^2}, \\ \sigma^2 &= \frac{1}{\frac{1}{\sigma_1^2} + \frac{1}{\sigma_2^2}} \end{aligned} $$ Here we will say that $\mu_1$ is the state $x$, and $\mu_2$ is the measurement $z$. Thus it follows that that $\sigma_1^2$ is the state uncertainty $P$, and $\sigma_2^2$ is the measurement noise $R$. Let's substitute those in. $$\begin{aligned} \mu &= \frac{Pz + Rx}{P+R} \\ \sigma^2 &= \frac{1}{\frac{1}{P} + \frac{1}{R}} \end{aligned}$$ I will handle $\mu$ first. The corresponding equation in the multivariate case is $$ \begin{aligned} x &= x + Ky \\ &= x + \frac{P}{P+R}(z-x) \\ &= \frac{P+R}{P+R}x + \frac{Pz - Px}{P+R} \\ &= \frac{Px + Rx + Pz - Px}{P+R} \\ &= \frac{Pz + Rx}{P+R} \end{aligned} $$ Now let's look at $\sigma^2$. The corresponding equation in the multivariate case is $$ \begin{aligned} P &= (1-K)P \\ &= (1-\frac{P}{P+R})P \\ &= (\frac{P+R}{P+R}-\frac{P}{P+R})P \\ &= (\frac{P+R-P}{P+R})P \\ &= \frac{RP}{P+R}\\ &= \frac{1}{\frac{P+R}{RP}}\\ &= \frac{1}{\frac{R}{RP} + \frac{P}{RP}} \\ &= \frac{1}{\frac{1}{P} + \frac{1}{R}} \quad\blacksquare \end{aligned} $$ We have proven that the multivariate equations are equivalent to the univariate equations when we only have one state variable. I'll close this section by recognizing one quibble - I hand waved my assertion that $H=1$ and $F=1$. In general we know this is not true. For example, a digital thermometer may provide measurement in volts, and we need to convert that to temperature, and we use $H$ to do that conversion. I left that issue out to keep the explanation as simple and streamlined as possible. It is very straightforward to add that generalization to the equations above, redo the algebra, and still have the same results.\\\
github_jupyter
``` import glob, sys from IPython.display import HTML import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from astropy.io import fits from pyflowmaps.flow import flowLCT import warnings warnings.filterwarnings("ignore") ``` # Load the data We include in the folder *data/* a cube fits file with the data coaligned and centered in a active region NOAA 1757. ``` cube = fits.getdata('data/cube_sunspot.fits') print(cube.shape) ``` Look into one of the frames in the cube. ``` fig, ax = plt.subplots(figsize=(10,10)) im=ax.imshow(cube[15],origin='lower',cmap='gray') ax.set_title('NOAA 1757 frame no. 15') ax.set_xlabel('X-axis [pix]') ax.set_ylabel('Y-axis [pix]') fig.colorbar(im,ax=ax,label='Intensity',shrink=0.82,aspect=15) ``` The shape of the data corresponds to 30 images with 128x128 pix dimesions per image. The frames are cut off from HMI/SDO data from 2013-01-05, intensity product, wtih a cadence of $720 s$, and the pixel size is around $\sim 0.504$. Other parameter we need is the size of the apodization window $FWHM$ which for this example will be $3\, arcsec$. This size depends on the size of the feature you want to study, as well as the resolution of your instrument. Other parameter that is neccesary is the average time over which the velocities will be calculated, but actually, it is included on the size of the input cube. For this example, the time over the average will be calculate is 6 hours ($30\times720 s=21600 s=6 h$). ``` flows = flowLCT(cube, 3, 0.504, 720,method='square',interpolation='fivepoint',window='boxcar') ``` We extract the velocities ``` vx = flows.vx vy = flows.vy vz = flows.vz ``` Velocities are returned in $kms^{-1}$. The velocity $v_z$ comes from $$ v_z = h_m\nabla\cdot v_h(v_x,v_y) $$ where $v_h$ are the horizontal velocities which depends on $v_x$ and $v_y$, whereas $h_m=150\,km$ is the mass-flux scale-heigth [(November 1989, ApJ,344,494)](https://ui.adsabs.harvard.edu/abs/1989ApJ...344..494N/abstract). Some authors prefer to show the divergences instead of the $v_z$, so the user just need to divide $v_z/h_m$. Next, the users can also create colormaps and personlize them. ``` from matplotlib import cm from matplotlib.colors import ListedColormap top = cm.get_cmap('Reds_r', 128) bottom = cm.get_cmap('YlGn', 128) newcolors = np.vstack((top(np.linspace(0.3, 1, 128)), bottom(np.linspace(0, 0.75, 128)))) newcmp = ListedColormap(newcolors, name='RdYlGn') ``` Now, we will plot the flows in each horizontal direction, and the divergence. ``` fig, ax = plt.subplots(1,3,figsize=(15,8),sharey=True) plt.subplots_adjust(wspace=0.03) flowx=ax[0].imshow(vx,origin='lower',cmap='RdYlGn',vmin = vx.mean()-3*vx.std(),vmax=vx.mean()+3*vx.std()) ax[0].set_title('Horizontal flowmap vx') ax[0].set_xlabel('X-axis [pix]') ax[0].set_ylabel('Y-axis [pix]') flowy=ax[1].imshow(vy,origin='lower',cmap='RdYlGn',vmin = vy.mean()-3*vy.std(),vmax=vy.mean()+3*vy.std()) ax[1].set_title('Horizontal flowmap vy') ax[1].set_xlabel('X-axis [pix]') div = vz/150 flowz=ax[2].imshow(div,origin='lower',cmap='RdYlGn',vmin = div.mean()-3*div.std(),vmax=div.mean()+3*div.std()) ax[2].set_title('Horizontal flowmap divergence') ax[2].set_xlabel('X-axis [pix]') fig.colorbar(flowx,ax=ax[0],orientation='horizontal',shrink=1,label='vx [km/s]') fig.colorbar(flowy,ax=ax[1],orientation='horizontal',shrink=1,label='vy [km/s]') fig.colorbar(flowz,ax=ax[2],orientation='horizontal',shrink=1,label='divergence') fig.savefig('/Users/joseivan/pyflowmaps/images/flowmaps.jpg',format='jpeg',bbox_inches='tight') ``` Finally, we can also plot the arrows associated with the horizontal velocities ``` xx,yy = np.meshgrid(np.arange(128),np.arange(128)) # we create a grid dense = 2 # each how many pixels you want to plot arrows fig,ax = plt.subplots(figsize=(10,10)) Q = ax.quiver(xx[::dense,::dense],yy[::dense,::dense],vx[::dense,::dense],vy[::dense,::dense], color='k', scale=8, headwidth= 4, headlength=4, width=0.0012) im = ax.imshow(cube[15],cmap='gray',origin='lower') ax.set_title('Flowmap horizontal velocities overplotted') ax.set_xlabel('X-axis [pix]') ax.set_ylabel('Y-axis [pix]') fig.colorbar(im,ax=ax,label='Intensity',shrink=0.82,aspect=15) fig.savefig('/Users/joseivan/pyflowmaps/images/flowmaps_arrows.jpg',format='jpeg',bbox_inches='tight') ```
github_jupyter