repo_name
stringlengths 6
77
| path
stringlengths 8
215
| license
stringclasses 15
values | cells
list | types
list |
|---|---|---|---|---|
snucsne/CSNE-Course-Source-Code
|
CSNE2444-Intro-to-CS-I/jupyter-notebooks/ch10-lists.ipynb
|
mit
|
[
"Chapter 10: Lists\n\nContents\n- A list is a sequence\n- Lists are mutable\n- Traversing a list\n- List operations\n- List slices\n- List methods\n- Map, filter and reduce\n- Deleting elements\n- Lists and strings\n- Objects and values\n- Aliasing\n- List arguments\n- Debugging\n- Exercises\n\nThis notebook is based on \"Think Python, 2Ed\" by Allen B. Downey <br>\nhttps://greenteapress.com/wp/think-python-2e/\n\nA list is a sequence\n\nA list is a sequence of values (like a string)\nThe values are referred to as elements or items\nThe simplest way to create a list is using square brackets",
"[10, 20, 30, 40]\n['dog', 'fish', 'bird']",
"The elements of a list don't have to be the same data type in Python (in other languages they do)\nHowever, if you want a sequence with different data types there are better alternatives",
"['bob', 3.14, 42, ['sam', 55]]",
"As you can see, lists can be nested\nA list containing no elements is an empty list\nAn empty list is created using empty brackets []\nYou can assign a list to a variable",
"cheeses = ['Chedder', 'Pepper Jack', 'Queso Fresca']\ngrades = [99, 84, 91]\nempty = []",
"Lists are mutable\n\nUnlike strings, lists are mutable\nThis means we can change them",
"cheeses = ['Chedder', 'Pepper Jack', 'Queso Fresca']\ncheeses[0] = 'Gouda'\nprint( cheeses )",
"Note that like strings, indices start at 0\nIn fact, all the things you can use for indices and use indices for in strings, you can do in lists\nThis includes the in operator\nOne way to think of the relationship between indices and elements is that it is a mapping\nEach index maps to one of the elements\nMuch like a word maps to a definition in a dictionary\nTODO State diagram for some lists\n\nTraversing a list\n\nThe most common way to traverse a list is with a for loop\nIt is the same approach we used with strings",
"for cheese in cheeses:\n print( cheese )",
"However, if you need the index, you need to use the range and len functions\nFor example, you may want to update the values in the list as you traverse it",
"numbers = [1, 2, 3]\n\nfor i in range( len( numbers ) ):\n numbers[i] = numbers[i] * 2\n\nprint( numbers )",
"A for loop over an empty list never executes the body of the loop\nIf you have a nested list, the nested list still counts as a single element",
"nested_list = ['spam', 1, [ 'Brie', 'Roquefort' , 'Pol le Veq'], [1, 2, 3] ]\nlen( nested_list )",
"List operations\n\nThe + operator concatenates lists\nThis means that it links them together into a single list",
"a = [ 1, 2, 3 ]\nb = [ 4, 5, 6 ]\nc = a + b\nprint( c )",
"Similarly, the * operator repeats a list a specified number of times",
"d = [ 0 ] * 4\nprint( d )\n\ne = [ 1, 2, 3 ] * 3\nprint( e )",
"List slices\n\nThe slice operator also works on lists:",
"f = [ 'a', 'b', 'c', 'd', 'e', 'f' ]\nprint( f[1:3] )\nprint( f[:4] )\nprint( f[3:] )",
"Just as with strings, if you omit the first index the slice starts at the beginning\nIf you omit the second, the slice goes to the end\nIf you omit both, the slice is th entire list\nSince lists are mutable, sometimes it is important to make a copy of a list before you change it\nYou can use a slice to update multiple elements",
"f[1:3] = [ 'x', 'y' ]\nprint( f )",
"List methods\n\nappend will add a new element to the end of a list",
"list1 = [ 'a', 'b', 'c' ]\nlist1.append( 'd' )\nprint( list1 )",
"extend takes a list as an argument and appends all of the elements",
"list2 = [ 'a', 'b', 'c' ]\nlist3 = [ 'd', 'e', ]\nlist2.extend( list3 )\n\nprint( list2 )\nprint( list3 )",
"Note that list3 is unmodified\nsort arranges the elements of a list from low to high",
"list4 = [ 'd', 'c', 'e', 'a', 'b' ]\nlist4.sort()\nprint( list4 )",
"All of these list methods are void\nThis means that they modify the list argument and return None\n\nMap, filter and reduce\n\nTo add up all the numbers in a list, use a loop",
"def add_all( a_list ):\n total = 0\n\n for value in a_list:\n total += value\n\n return total",
"As we have seen before, the += operator updates a variable\nIt is referred to as an augmented assignment statement\nIn the code, total is used in the loop as an accumulator\nPython provides the sum function to sum the elements of a list",
"list_of_numbers = [ 1, 2, 3 ]\nsum( list_of_numbers )",
"A function that combines a sequence of elements into a single value is sometimes called a reduce function\nSometimes you want to build a new list from an existing list",
"def capitalize_all( a_list ):\n result = []\n for a_string in a_list:\n result.append( a_string.capitalize() )\n return result\n\nwords = [ 'life', 'the', 'universe', 'and', 'everything' ]\ncapitalized_words = capitalize_all( words )\nprint( capitalized_words )",
"This is sometimes called a map function since it \"maps\" a function onto each of the elements in a sequence\nNote that a map is more commonly used to refer to a specific data structure (e.g., a dictionary)\nAnother common operation is to filter elements from one list to another",
"def only_upper( a_list ):\n result = []\n for a_string in a_list:\n if( a_string.isupper() ):\n result.append( a_string )\n return result\n\nwords = [ 'LIFE', 'The', 'uNiverse', 'AND', 'everything' ]\nsome_words = only_upper( words )\nprint( some_words )",
"Deleting elements\n\nThe pop function can be used to delete an element from a list if you know the index",
"a_list = [ 'a', 'b', 'c' ]\nvalue = a_list.pop( 1 )\nprint( a_list )\nprint( value )",
"Note that the function returns the deleted element\nIf you don’t specify an index, it operates on the last element\nIf you don’t need the deleted value, use the del operator",
"a_list = [ 'a', 'b', 'c' ]\ndel a_list[1]\nprint( a_list )",
"del can also be used with a slice index to remove more than one element",
"a_list = [ 'a', 'b', 'c', 'd', 'e', 'f' ]\ndel a_list[1:5]\nprint( a_list )",
"If you know the element you want to remove, but not the index, use the remove operator\nNote that it only removes the first matching element if there are duplicates",
"a_list = [ 'a', 'b', 'c', 'a', 'b', 'c' ]\na_list.remove( 'b' )\nprint( a_list )",
"Lists and strings\n\nA list of characters is not the same as a string\nTo convert a string to a list, use the list operator",
"a_string = 'spam'\na_list = list( a_string )\nprint( a_list )",
"Since it is an operator, don’t use list as a variable name\nDon’t use l either since it looks like a 1\nUse a_list or something more descriptive detailing a value in your algorithm\nIf you want to split a string into words and not letters, use split",
"a_string = 'pining for the fjords'\na_list = a_string.split()\nprint( a_list )",
"By default, the delimiter is a space\nYou can change that by passing it as an argument",
"a_string = 'spam-spam-spam'\ndelimiter = '-'\na_string.split( delimiter )",
"join is the inverse of split\nSince it is a string method, you have to invoke it on a string\nIn this case, invoke it on the delimiter",
"a_list = [ 'pining', 'for', 'the', 'fjords' ]\ndelimiter = ' '\ndelimiter.join( a_list )",
"Objects and values\n\nTo check whether two variables refer to the same object, use the is operator",
"a = 'banana'\nb = 'banana'\na is b",
"Note that this is different from the values of the two objects being equivalent",
"a = [ 1, 2, 3 ]\nb = [ 1, 2, 3 ]\na is b",
"In the first example, Python only create one string object\nIn the second, Python created two lists that are equivalent, but not identical\nWhy the difference?\n\nAliasing\n\nA variable doesn’t actually hold an object, it has a reference to it\nWhen two variables refer to the same object, it is called aliasing\nIf an object is mutable, changes made to one affect the other",
"a = [ 1, 2, 3 ]\nb = a\nb[0] = 17\nprint( a )",
"Be careful because this can cause problems if you aren’t paying attention\nFor immutable objects (like strings), it isn’t a problem\n\nList arguments\n\nWhen you pass a list as an argument to a function, it gets a reference to the list\nWhat does this mean?\nIf the list modifies the list, it is the same list as in the calling function",
"def delete_head( a_list )\n del a_list[0]\n\nletters = [ 'a', 'b', 'c' ]\ndelete_head( letters )\nprint( letters )",
"See the stack diagram on pg. 97 of the textbook\nMake sure you know if the function you are using modifies the list argument or returns a new list",
"list1 = [ 1, 2 ]\nlist2 = list1.append( 3 )\nprint( list1 )\nprint( list2 )",
"Debugging\n\nBe careful of common pitfalls when using lists and other mutable objects:\nMost list methods modify the argument and return None. This is the opposite of string methods.\nPick an idiom (or way of doing things) and stick with it\nMake copies to avoid aliasing and accidental modifications\n\nExercises\n\nWrite a function called cumulative_sum that takes a list of numbers and returns the cumulative sum; that is, a new list where the $i$-th element is the sum of the furst $i$ elements from the list.",
"def cumulative_sum( a_list ):\n # INSERT YOUR CODE HERE\n return []\n\nnumbers = [ 1, 2, 3 ]\nresult = cumulative_sum( numbers )\n# The answer should be:\n# [ 1, 3, 6 ]",
"Write a function called chop that takes a list and modifies it by removing the first and last element. The function should return None.",
"def chop( a_list ):\n # INSERT YOUR CODE HERE\n print( 'Remove this line' ) # Jupyter needs a statement to compile\n\nnumbers = [ 1, 2, 3, 4 ]\nchop( numbers )\nprint( numbers )\n# Should print: [ 2, 3 ]",
"Two words are anagrams if you can rearrange the letters from one to spell the other. Write a function called is_anagram that takes two strings and returns True if they are anagrams."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
empet/geom_modeling
|
FP-Bezier-Bspline.ipynb
|
bsd-2-clause
|
[
"<center> Interactive generation of Bézier and B-spline curves.<br> Python functional programming implementation of the <br> de Casteljau and Cox-de Boor algorithms </center>\nThe aim of this IPython notebook is twofold: \n- first to illustrate the interactive generation of Bézier and B-spline curves using the matplotlib backend nbagg, and second\n- to give a functional programming implementation of the basic algorithms related to these classes of curves. \nBézier and B-spline curves are widely used for interactive heuristic design of free-form curves in Geometric modeling.\nTheir properties are usually illustrated through interactive generation using C and OpenGL or Java applets. The new\nmatplotlib nbagg backend enables the interactive generation of Bézier and B-spline curves in an IPython Notebook.\nWhy functional programming (FP)?\nLately there has been an increasing interest in pure functional programming and an active debate on whether we can do FP in Python or not.\nBy Wikipedia:\n\nFunctional programming is a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.\n\nPython is a multi-paradigm programming language: it is both imperative and object-oriented programming language and provides a few constructs for a functional programming style, as well.\nHere is a discussion on why Python is not very good for FP.\nInstead of discussing pros and cons of Python FP we decided to start a small project and implement it as much as possible in a FP style.\nBefore starting let us recall a few characteristics of FP: \n- functions are building blocks of FP. They are first class objects, meaning that they are treated like any other objects. Functions can be passed as arguments to other functions (called higher order functions) or be returned by another functions.\n- FP defines only pure functions, i.e. functions without side effects. Such a function acts only on its input to produce output (like mathematical functions). A pure function never interact with the outside world (it does not perform any I/O operation or modify an instance of a class).\n- a FP program consists in evaluating expressions, unlike imperative programming where programs are composed of statements which change global state when executed. \n- FP avoids looping and uses recursion instead.\nIn this IPython Notebook we try to implement algorithms related to Bézier and B-spline curves, \nusing recursion, iterators, higher order functions.\nWe also define a class to build interactively a curve. The code for class methods will be imperative \nas well as for the last function that prepares data for a closed B-spline curve.\nBézier curves. de Casteljau algorithm\nA Bézier curve of degree $n$ in the $2$-dimensional space is a polynomial curve defined by an ordered set $({\\bf b}_0, {\\bf b}_1, \\ldots, {\\bf b}_n)$ of $n+1$ points, called control points. This set is also called control polygon of the Bézier curve.\nIts parameterization, $p:t\\in [0,1]\\mapsto p(t)\\in\\mathbb{R}^2$, is defined by:\n $$p(t)=\\sum_{k=0}^n{\\bf b}_k B^n_k(t), \\quad t\\in[0,1]$$\nwhere $B^n_k(t)=\\binom nk t^k(1-t)^{n-k}, k=0,1,\\ldots, n$, are Bernstein polynomials.\nTo compute a point on a Bézier curve theoretically we have to evaluate the above parameterization $p$ at a parameter $t\\in[0,1]$. In Geometric Modeling a more stable algorithm is used instead, namely the de Casteljau algorithm.\nDe Casteljau algorithm provides a procedural method to compute recursively a point, $p(t)$, on a Bezier curve. \nGiven the control points $({\\bf b}0, {\\bf b}_1, \\ldots, {\\bf b}_n)$, and a parameter $t\\in [0,1]$, one computes in each step $r=\\overline{1,n}$ of the recursion, the points:\n $$ {\\bf\nb}{i}^{r}(t)=(1-t)\\,{\\bf b}{i}^{r-1}(t)+t\\,{\\bf b}{i+1}^{r-1}(t),\\:\n i=\\overline{0,n-r}, $$ \ni.e. the $i^{th}$ point ${\\bf\nb}_{i}^{r}(t)$, from the step $r$, is a convex combination of the $i^{th}$ and $(i+1)^{th}$ point from the step $r-1$:\n$$\n\\begin{array}{lll} {\\bf b}^{r-1}i&\\stackrel{1-t}{\\rightarrow}&{\\bf\nb}^{r}_i\\\n{\\bf b}^{r-1}{i+1}&\\stackrel{\\nearrow}{t}&\\end{array}$$\nThe control points calculated in the intermediate steps can be displayed in a triangular array:\n $$\n\\begin{array}{llllll} \n{\\bf b}0^0 & {\\bf b}{0}^1 & {\\bf b}{0}^2& \\cdots & {\\bf b}_0^{n-1}& {\\bf b}^n_0\\\n{\\bf b}_1^0 & {\\bf b}{1}^1 & {\\bf b}{1}^2& \\cdots & {\\bf b}_1^{n-1}& \\\n{\\bf b}_2^0 & {\\bf b}{2}^1 & {\\bf b}{2}^2 & \\cdots & & \\\n\\vdots & \\vdots &\\vdots & & & \\\n{\\bf b}{n-2}^0 & {\\bf b}{n-2}^1& {\\bf b}{n-2}^2& & & \\\n{\\bf b}{n-1}^0 & {\\bf b}{n-1}^1 & & & & \\\n{\\bf b}_n^0 & & & & & \\end{array} $$\nThe points ${\\bf b}_i^0$ denote the given control points ${\\bf b}_i$, $i=\\overline{0,n}$.\nThe number of points reduces by 1, from a step to the next one, such that at the final step, $r=n$, we get only one point, ${\\bf b}_0^n(t)$, which is the point $p(t)$\non the Bézier curve.\nThe image below illustrates the points computed by de Casteljau algorithm for a Bézier curve defined by 4 control points, and a fixed parameter $t\\in[0,1]$:",
"from IPython.display import Image\nImage(filename='Imag/Decast4p.png')",
"We define two functions that implement this recursive scheme. In both cases \nwe consider 2D points as tuples of float numbers and control polygons as lists of tuples.\nFirst an imperative programming implementation of the de Casteljau algorithm:",
"import numpy as np\n\nclass InvalidInputError(Exception):\n pass\n\ndef deCasteljauImp(b,t): \n N=len(b) \n if(N<2):\n raise InvalidInputError(\"The control polygon must have at least two points\")\n a=np.copy(b) #shallow copy of the list of control points and its conversion to a numpy.array \n for r in range(1,N): \n a[:N-r,:]=(1-t)*a[:N-r,:]+t*a[1:N-r+1,:]# convex combinations in step r \n return a[0,:]",
"This is a typical imperative programming code: assignment statements, for looping.\nEach call of this function copies the control points into a numpy array a. \nThe convex combinations a[i,:] =(1-t) *a[i,:]+t*a[i-1,:], $i=\\overline{1,n-r}$, that must be calculated in each step $r$ \nare vectorized, computing convex combinations of points from two slices in the numpy.array a.\nA discrete version of a Bezier curve, of nr points is computed by this function:",
"def BezierCv(b, nr=200):# compute nr points on the Bezier curve of control points in list bom\n t=np.linspace(0, 1, nr)\n return [deCasteljauImp(b, t[k]) for k in range(nr)] ",
"For a FP implementation of de Casteljau algorithm we use standard Python.\nFirst we define functions that return an affine/ convex combination of two numbers, two 2D points, respectively of each pair of consecutive points in a list of 2D control points:",
"cvx=lambda x, y, t: (1-t) * x + t * y # affine/convex combination of two numbers x, y\n\ncvxP=lambda (P, Q, t): (cvx(P[0], Q[0], t), cvx(P[1], Q[1], t))# affine/cvx comb of two points P,Q\n\n \ndef cvxCtrlP(ctrl, t):# affine/cvx combination of each two consecutive points in a list ctrl \n # with the same coefficient t \n return map(cvxP, zip(ctrl[:-1], ctrl[1:], [t]*(len(ctrl)-1))) ",
"The recursive function implementing de Casteljau scheme:",
"def deCasteljauF(b, t):\n # de Casteljau scheme - computes the point p(t) on the Bezier curve of control polygon b\n \n if len(b)>1:\n return deCasteljauF(cvxCtrlP( b, t), t)\n else: \n return b[0]\n",
"A Bézier curve of control polygon ${\\bf b}$ is discretized calling deCasteljauF function for each\nparameter $t_j=j/(nr-1)$, $j=\\overline{0,nr-1}$, where $nr$ is the number of points to be calculated:",
"def BezCurve(b, nr=200):\n #computes nr points on the Bezier curve of control points b \n \n return map(lambda s: deCasteljauF(b,s), map(lambda j: j*1.0/(nr-1), xrange(nr)))\n ",
"map(lambda s: deCasteljauF(b,s), map(lambda j: j*1.0/(nr-1), xrange(nr)) means that the function\n deCasteljauF with fixed list of control points, b, and the variable parameter s is mapped to the list\n of parameters $t_j$ defined above. Instead of defining the list of parameters through comprehension [j*1.0/(nr-1) for j in xrange(nr)]\n we created it calling the higher order function map:\nmap(lambda j: j*1.0/(nr-1), xrange(nr))\nObvioulsly the FP versions of de Casteljau algorithm and BezCurve are more compact\nthan the corresponding imperative versions, but they are not quite readable at the first sight.\nTo choose interactively the control points of a Bézier curve (and later of a B-spline curve) and to plot the curve, we set now the matplotlib nbagg backend, and define the class BuildB, below:",
"%matplotlib notebook\n\nimport matplotlib.pyplot as plt\n\ndef Curve_plot(ctrl, func):\n # plot the control polygon and the corresponding curve discretized by the function func\n xc, yc = zip(*func(ctrl))\n xd, yd = zip(*ctrl)\n plt.plot(xd,yd , 'bo-', xc,yc, 'r') \n\nclass BuildB(object): #Build a Bezier/B-spline Curve\n \n def __init__(self, xlims=[0,1], ylims=[0,1], func=BezCurve):\n self.ctrl=[] # list of control points\n self.xlims=xlims # limits for x coordinate of control points\n self.ylims=ylims # limits for y coordinate\n self.func=func # func - function that discretizes a curve defined by the control polygon ctrl\n \n def callback(self, event): #select control points with left mouse button click\n if event.button==1 and event.inaxes:\n x,y = event.xdata,event.ydata\n self.ctrl.append((x,y)) \n plt.plot(x, y, 'bo') \n \n elif event.button==3: #press right button to plot the curve\n Curve_plot(self.ctrl, self.func) \n plt.draw() \n \n else: pass\n \n def B_ax(self):#define axes lims\n\n fig = plt.figure(figsize=(6, 5))\n ax = fig.add_subplot(111)\n ax.set_xlim(self.xlims)\n ax.set_ylim(self.ylims)\n ax.grid('on') \n ax.set_autoscale_on(False)\n fig.canvas.mpl_connect('button_press_event', self.callback)",
"Now we build the object C, set the axes for the curve to be generated, and choose the control points\nwith the left mouse button click. A right button click generates the corresponding curve:",
"C=BuildB()\nC.B_ax()",
"Subdividing a Bézier curve\nLet $\\Gamma$ be a Bézier curve of control points $({\\bf b}_0, {\\bf b}_1, \\ldots, {\\bf b}_n)$, and\n $s\\in (0,1)$ a parameter. Cutting (dividing) the curve at the point $p(s)$ we get two arcs of polynomial curves, which can be also expressed as Bezier\n curves. The problem of finding the control polygons of the two arcs is called subdivision of the Bézier curve at $s$.\nThe control points ${\\bf d}r$, $r=\\overline{0,n}$, of the right arc of Bezier curve are:\n $${\\bf d}_r={\\bf b}{n-r}^r(s),$$\nwhere ${\\bf b}^r_{n-r}(s)$ are points generated in the $r^{th}$ step of the de Casteljau algorithm from the control points\n$({\\bf b}_0, {\\bf b}_1, \\ldots, {\\bf b}_n)$, and the parameter $s$ [Farin].\nMore precisely, the right polygon consists in last points computed in each step, $r=0,1,\\ldots, n$, of the de Casteljau algorithm (see the triangular matrix of points displayed above):\n${\\bf b}^0_n(s), {\\bf b}^1_{n-1}(s), \\ldots, {\\bf b}^n_0(s)$.\nThe recursive function get_right_subPol returns the right subpolygon of a subdivision at parameter $s$:",
"def get_right_subpol(b,s, right=[]): # right is the list of control points for the right subpolygon\n \n right.append(b[-1]) # append the last point in the list\n if len(b)==1:\n return right\n else:\n return get_right_subpol(cvxCtrlP(b,s), s, right)",
"To get the left subpolygon we exploit the invariance of a Bézier curve to reversing its control points.\nThe Bézier curve defined by the control points \n${\\bf b}n,{\\bf b}{n-1}, \\ldots, {\\bf b}0$, coincides with that defined by\n${\\bf b}_0,{\\bf b}{1}, \\ldots, {\\bf b}_n$. \nIf $p$ is the Bernstein parameterization of the curve defined by \n${\\bf b}0,{\\bf b}{1}, \\ldots, {\\bf b}n$\n and $\\tilde{p}$ of that defined by the reversed control polygon, ${\\bf b}_n,{\\bf b}{n-1}, \\ldots, {\\bf b}_0$, then $p(t)=\\tilde{p}(1-t)$ [Farin].\nThis means that the left subpolygon of the subdivision of the former curve at $s$,\n is the right subpolygon resulted by dividing the latter curve at $1-s$.\nNow we can define the function that returns the left and right subpolygon of a Bézier curve subdivision:",
"def subdivision(b, s):\n #returns the left and right subpolygon, resulted dividing the curve of control points b, at s\n #if(s<=0 or s>=1):\n #raise InvalidInputError('The subdivision parameter must be in the interval (0,1)')\n \n return (get_right_subpol( b[::-1], 1-s, right=[]), get_right_subpol( b, s, right=[]))\n ",
"Define a function to plot the subpolygons:",
"def plot_polygon(pol, ch):# plot a control polygon computed by an algorithm from a Bezier curve\n \n plt.plot(zip(*pol)[0], zip(*pol)[1], linestyle='-', marker='o', color=ch)\n ",
"Let us generate a Bézier curve and subdivide it at $s=0.47$:",
"cv=BuildB()\ncv.B_ax()\n\nleft, right=subdivision(cv.ctrl, 0.47)\nplot_polygon(left, 'g')\nplot_polygon(right, 'm')",
"Multi-affine de Casteljau algorithm\nThe above de Casteljau algorithm is the classical one. There is a newer approach to define and study Bézier\ncurves through polarization.\nEvery polynomial curve of degree n, parameterized by $p:[a,b]\\to\\mathbb{R}^2$ defines a symmetric multiaffine\n map $g:\\underbrace{[a,b]\\times[a,b]\\times[a,b]}{n}\\to \\mathbb{R}^d$, such that\n $p(t)=g(\\underbrace{t,t,\\ldots,t }{n})$, for every $t\\in[a,b]$.\n$g$ is called the polar form of the polynomial curve. An argument $(u_1, u_2, \\ldots, u_n)$ of the polar form $g$ is called polar bag. \nIf $p(t)$ is the Bernstein parameterization of a Bezier curve of control points \n${\\bf b}0,{\\bf b}{1}, \\ldots, {\\bf b}_n$, and $g:[0,1]^n\\to\\mathbb{R}^2$ its polar form, then the control points are related to $g$ as follows [Gallier]:\n$${\\bf b}j=g(\\underbrace{0, 0, \\ldots, 0}{n-j}, \\underbrace{1,1, \\ldots, 1}_{j}), \\quad j=0,1, \\ldots, n$$\nThis relationship allows to define Bézier curves by a parameterization $P$ defined not only on the interval $[0,1]$ but also on an arbitrary interval $[r,s]$. Namely, given a symmetric multiaffine map $g:[r,s]^n\\to\\mathbb{R}^2$\nthe associated polynomial curve $P(t)=g(\\underbrace{t,t,\\ldots, t}{n})$, $t\\in[r,s]$, expressed as a Bézier curve has the control points defined by [Gallier]:\n$${\\bf b}_j=g(\\underbrace{r, r, \\ldots, r}{n-j}, \\underbrace{s,s, \\ldots, s}_{j}), \\quad j=0,1, \\ldots, n$$\nGiven the control points ${\\bf b}0,{\\bf b}{1}, \\ldots, {\\bf b}_n$ of a Bézier curve, and a polar bag $(u_1, u_2, \\ldots, u_n)\\in[r,s]^n$ the multi-affine de Casteljau algorithm\nevaluates the corresponding multi-affine map, $g$, at this polar bag through a recursive formula similar to the classical\nde Casteljau formula:\n$${\\bf b}^k_i= \\displaystyle\\frac{s-u_k}{s-r}\\:{\\bf b}i^{k-1}+ \\displaystyle\\frac{u_k-r}{s-r}\\:{\\bf b}{i+1}^{k-1}, \\quad k=\\overline{1,n}, i=\\overline{0,n-k}$$ \nThe point $b_0^n$ computed in the last step is the polar value, $g(u_1,u_2, \\ldots, u_n)$.\nUnlike the classical de Casteljau formula, where in each step the parameter for the convex combination\nis the same, here in each step $k$ the parameter involved in convex combinations changes, namely it is \n$\\displaystyle\\frac{u_k-r}{s-r}$. \nIn order to define a recursive function to implement this scheme\nwe consider the polar bag as an iterator associated to the list containing its coordinates, i.e. if L=[u[0], u[1], ..., u[n-1]] is the list, iter(L) is its iterator:",
"def deCasteljauAff(b, r, s, u): #multi-affine de Casteljau algorithm\n \n # b is the list of control points b_0, b_1, ..., b_n\n # [r,s] is a subinterval \n # u is the iterator associated to the polar bag [u_0, u_1, u_{n-1}], n=len(b)-1 \n \n if len(b)>1:\n return deCasteljauAff(cvxCtrlP( b, (u.next()-r)/(s-r)), r, s, u)\n else: return b[0]\n ",
"Usually we should test the concordance between the length (n+1) of the control polygon and the number of elements of the iterator \nu. Since a listiterator has no length we have to count its elements. Functionally this number would get as:\nlen(map(lambda item: item, u))\nWhat characteristic elements of a Bézier curve can the multi-affine de Casteljau algorithm compute?\n1. The direction of the tangent to a Bézier curve of degree $n$, at a point $p(t)$, is defined by the vector\n$\\overrightarrow{{\\bf b}^{n-1}_0{\\bf b}^{n-1}_1}$. The end points of this vector are the points computed in\nthe $(n-1)^{th}$\nstep of the classical de Casteljauscheme. On the other hand, these points are polar values of the corresponding\nmultiaffine map $g$ [Gallier], namely:\n$${\\bf b}^{n-1}0=g(\\underbrace{t,t,\\ldots, t}{n-1}, 0), \\quad {\\bf b}^{n-1}1=g(\\underbrace{t,t,\\ldots, t}{n-1}, 1)$$\nThus they can be computed by the function deCasteljauAff.\nLet us generate a Bézier curve and draw the tangent at the point corresponding to $t=0.45$:",
"ct=BuildB()\nct.B_ax()\n\nn=len(ct.ctrl)-1\n\n\nt=0.45\nu=[t]*(n-1)+[0]\nv=[t]*(n-1)+[1]\n\nA=deCasteljauAff(ct.ctrl, 0,1, iter(u))\nB=deCasteljauAff(ct.ctrl, 0,1, iter(v))\nplt.plot([A[0], B[0]], [A[1], B[1]], 'g')",
"2. The multi-affine de Casteljau algorithm can also be applied to redefine a subarc of a Bézier curve as a Bézier curve.\nMore precisely, let us assume that a Bézier curve of control points ${\\bf b}j$, $j=\\overline{0,n}$,\nand parameterization $p$ defined on the interval [0,1] is cut at the points corresponding to the parameters $r<s$, $r, s\\in[0,1]$.\nThe arc between $p(r)$ and $p(s)$ is also a polynomial curve and its control points are [Gallier]:\n $${\\bf c}_j=g(\\underbrace{r,r,\\ldots, r}{n-j}, \\underbrace{s,s\\ldots, s}_{j}),\\quad j=\\overline{0,n}$$\nwhere $g$ is the polar form of the initial curve.\nThe function polar_bags below defines the list of polar bags involved in computation of the control points ${\\bf c}_j$:",
"def polar_bags(r,s, n):\n \n return map(lambda j: [r]*(n-j)+[s]*j, xrange(n+1)) \n\n\nr=0.3\ns=0.67\nn=3\nL=polar_bags(r, s, n)\nprint L\n\ndef redefineBezier(b, r, s):\n # returns the control polygon for the subarc of ends p(r), p(s)\n #of a Bezier curve defined by control polygon b\n \n \n #if(r<0 or s>1 or r>s or s-r<0.1):\n #raise InvalidInputError('innapropriate interval ends')\n \n return map(lambda u: deCasteljauAff(b, 0, 1, iter(u)), polar_bags(r,s, len(b)-1))",
"Now let us test this function:",
"Bez=BuildB()\nBez.B_ax()\n\nbr=redefineBezier(Bez.ctrl, 0.3, 0.67)\nplot_polygon(br, 'g')",
"3. The function redefineBezier can also be invoked to compute the left and right subpolygons resulted from a subdivision of a Bézier curve, \nat a point corresponding to the paramater $s$. Namely the left subpolygon is returned by\nredefineBezier(b, 0, s), whereas the right subpolygon by redefineBezier(b, s, 1) \nB-spline curves\nWe give a procedural definition of a B-spline curve of degree $k$, not an analytical one.\nThe following data: \n\n\nan interval $[a,b]$;\n\n\nan integer $k\\geq 1$;\n\n\na sequence of knots:\n$$u_0 = u_1 = \\cdots = u_k< u_{k+1} \\leq \\cdots \\leq u_{m−k−1} < u_{m−k} = \\cdots = u_{m−1} = u_m$$\n\n\nwith $u_0 = a, u_m = b$, $m−k > k$, and each knot $u_{k+1}, \\ldots, u_{m-k-1}$ of multiplicity at most $k$;\n- the control points ${\\bf d}0, {\\bf d}_1, \\ldots, {\\bf d}{m-k-1}$, called de Boor points;\ndefine a curve $s:[a,b]\\to\\mathbb{R}^2$, such that for each $t$ in an interval $[u_J, u_{J+1}]$, with\n$u_J<u_{J+1}$, $s(t)$ is computed in the last step of the Cox-de Boor recursive formula [Gallier]:\n $$\\begin{array}{lll}\n{\\bf d}^0_i&=&{\\bf d}i,\\quad i=\\overline{J-k,J}\\\n {\\bf d}_i^r(t)&=&(1-\\omega_i^r(t))\\,{\\bf d}{i-1}^{r-1}(t)+\\omega_i^r(t)\\,{\\bf d}{i}^{r-1}(t),\\,\\,\nr=\\overline{1, k}, i=\\overline{J-k, J}\\end{array}$$\nwith $\\omega_i^r(t)=\\displaystyle\\frac{t-u{i}}{u_{i+k-r+1}-u_{i}}$ \nThe curve defined in this way is called B-spline curve. It is a piecewise polynomial curve of degree\n at most $k$, i.e. it is a polynomial curve on each nondegenerate interval $[u_J, u_{J+1}]$, and at each knot $u_J$ of multiplicity $1\\leq p\\leq k$, it is of class $C^{k-p}$. \nThe points computed in the steps $r=\\overline{1,k}$ of the recursion can be written in a lower triangular matrix:\n$$ \n\\begin{array}{ccccc}\n{\\bf d}^0_{0}& & & & \\\n{\\bf d}^0_{1} & {\\bf d}{1}^1& & & \\\n\\vdots & \\vdots & & & \\\n{\\bf d}^0{k-1} & {\\bf d}{k-1}^1 &\\ldots & {\\bf d}{k-1}^{k-1}& \\\n{\\bf d}^0_{k}& {\\bf d}{k}^1 &\\ldots & {\\bf d}{k}^{k-1} &{\\bf d}_{k}^{k}\n\\end{array}\n$$\nUnlike the classical de Casteljau or the multi-affine de Casteljau scheme, in the de Boor-formula\nfor each pair of consecutive points ${\\bf d}^{r-1}_{i-1}, {\\bf d}_i^{r-1}$, one computes a convex combination with the \ncoefficient $\\omega_i^r$ depending both on $r$ and $i$.\nIn a first attempt to write a recursive function that implements the Cox-de Boor formula we defined an\nauxiliary function Omegas, that returns a list of lists. An inner list contains the elements $\\omega^r_i$, involved in a step of the recursive formula.\nUsing list comprehension the function Omegas returns:\n[[(t-u[j])/(u[j+k-r+1]-u[j]) for j in range(r, k+1) ] for r in range(1,k+1)] \nAlthough later we chose another solution, we give this function as an interesting example of FP code (avoiding list comprehension):",
"from functools import partial\n\ndef Omegas(u, k, t): \n # compute a list of lists \n #an inner list contains the values $\\omega_j^r(t)$ values from a step r\n \n #if (len(u)!=2*k+1):\n #raise InvalidInputError('the list u must have length 2k+1')\n return map(lambda r: map(partial(lambda r, j: (t-u[j])/(u[j+k-r+1]-u[j]), r), \\\n xrange(r,k+1)), xrange(1, k+1)) ",
"The function functools.partial associates to a multiargument function\na partial function in the same way as in mathematics, i.e. if $f(x_1, x_2, \\ldots, x_n)$ is a n-variable function\n $g(x_2, \\ldots, x_n)=f(a, x_2, \\ldots, x_n)$, with $a$ fixed, is a partial function. More details here.\nIn Omegas is involved the partial function of the anonymous function \nlambda r, j: (t-u[j])/(u[j+k-r+1]-u[j])\ndefined by freezing r.\nLet us test it:",
"k=3\nu=[j for j in range(7)]\n\nLL=Omegas( u, k, 3.5)\nprint LL",
"Noticing that in each step $r>1$, the coefficients $\\omega^r_i$ are computed with the same formula as for\n$r=1$, i.e. $\\omega_i^r=\\displaystyle\\frac{t-u_i}{u_i+k-u_i}$ but for the knots in the list\nu[r-1: -r+1] and $k=k-r+1$ we \ndefine the function omega below, instead of Omegas:",
"def omega(u, k, t):\n # defines the list of coefficients for the convex combinations performed in a step of de Boor algo\n \n #if (len(u)!=2*k+1 or t<u[k] or t>u[k+1]):\n #raise InvalidInputError('the list u has not the length 2k+1 or t isn't within right interval')\n \n return map(lambda j: (t-u[j]) / (u[j+k]-u[j]), xrange(1,k+1))",
"We also need a new function that calculates the convex combinations of each pair of points in a list,\nwith distinct coefficients given in a list alpha:",
"def cvxList(d, alpha):\n #len(d)=len(alpha)+1\n return map(cvxP, zip(d[:-1], d[1:], alpha))",
"The recursive Cox-de Boor formula is now implemented in the following way:",
"def DeBoor(d, u, k, t):\n #len(d) must be (k+1) and len(u)=2*k+1:\n # this algorithm evaluates a point c(t) on an arc of B-spline curve\n # of degree k, defined by:\n # u_0<=u_1<=... u_k<u_{k+1}<=...u_{2k} the sequence of knots\n # d_0, d_1, ... d_k de Boor points \n \n if(len(d)==1):\n return d[0] \n else: \n return DeBoor(cvxList(d, omega(u, k,t)), u[1:-1], k-1,t)\n",
"To experiment the interactive generation of B-spline curves we give the restrictions on input data that lead to a closed B-spline curve:\nA B-spline curve of degree k, defined on an interval $[a,b]$ by the following data:\n\nde Boor control polygon:\n $({\\bf d}0, \\ldots, {\\bf d}{n-k},\\ldots,{\\bf d}{n-1})$ such that\n $$\\begin{array}{llllllll}\n{\\bf d}_0,&{\\bf d_1},&\\ldots,& {\\bf d}{n-k-1}, & {\\bf d}{n-k}, & {\\bf d}{n-k+1}, & \\ldots& {\\bf d}{n-1}\\\n & & & & \\shortparallel &\\shortparallel & &\\shortparallel\\\n & & & & {\\bf d}_0 & {\\bf d}_1\n &\\ldots& {\\bf d}{k-1}\\end{array}$$\na knot sequence obtained by extending through periodicity of period $T=b-a$ of the sequence of knots $a=u_k\\leq\\cdots\\leq u_n=b$ ($n\\geq 2k$):\n\n$$\\begin{array}{lll}u_{k-j}&=&u_{n-j}-T\\ u_{n+j}&=&u_{k+j}+T\\& & j=1,\\ldots k\\end{array}$$\nis a closed B-spline curve.\nIn our implementation we take a uniform sequence of knots of the interval $[a,b]$\n\nThe de Boor points are chosen interactively with the left mouse button click within the plot window.\nA point is a tuple of real numbers, and the control polygon is a list of tuples.\n\nThe next function constructs the periodic sequence of knots and the de Boor polygon such that to\ngenerate from the interactively chosen control points a closed B-spline curve, of degree $3$, and\nof class $C^{2}$ at each knot.\nThe function's code is imperative:",
"def Bspline(d, k=3, N=100):\n L=len(d)-1\n n=L+k+1\n #extend the control polygon\n d+=[d[j] for j in range (k+1)]\n \n #make uniform knots\n u=np.arange(n+k+1)\n # define the period T\n T=u[n]-u[k]\n #extend the sequence of knots\n u[:k]=u[n-k:n]-T\n u[n+1:n+k+1]=u[k+1:2*k+1]+T\n u=list(u)\n \n curve=[]#the list of points to be computed on the closed B-spline curve\n for J in range(k, n+1):\n \n if u[J]<u[J+1]:\n t=np.linspace(u[J], u[J+1], N)\n else: continue \n \n curve+=[DeBoor(d[J-k:J+1], u[J-k:J+k+1], k, t[j]) for j in range (N) ]\n return curve",
"We build the control polygon and draw the corresponding closed B-spline curve:",
"D=BuildB(func=Bspline)\n\nD.B_ax()",
"After these experiments our conclusion is that you can insert functional programming code in your imperative Python code, but trying to write pure functions could be difficult, sometimes impossible.\nWriting FP style Python code is challenging, but the code is not so easy to read, unlike the imperative Python code which is characterized as a readable one.\nThe next step in experimenting FP will be to use a Python implementation of monads (see for example Pymonad or fn.py.\nIn this IPython Notebook we avoided to raise errors and commented the lines handling errors.\nThe algorithms implemented in this IPython Notebook are presented in detail in:\n 1. G Farin, Curves and Surfaces for Computer Aided Geometric Design: A Practical Guide, Morgan Kaufmann, 2002.\n 2. J. Gallier, Curves and Surfaces in Geometric Modeling: Theory and Algorithms, Morgan Kaufmann, 1999. Free electronic version can be downloaded here.\n2/10/2015",
"from IPython.core.display import HTML\ndef css_styling():\n styles = open(\"./custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
jepegit/cellpy
|
examples/jupyter notebooks/EasyPlot_Demo.ipynb
|
mit
|
[
"Easyplot user guide\nEasyplot is a submodule found in the utils of cellpy. It takes a list of filenames and plots these corresponding to the users input configuration. Please follow the example below to learn how to use it.\n1: Import cellpy and easyplot",
"from cellpy.utils import easyplot",
"2: Specify a list of datafiles\nYou can insert different filetypes as long as they are supported by the automatic detection of cellpy. Currently, if you want to use data from an SQL database, you can only plot other data from the same database. In addition you must specify the server credentials. See step below.\nIf the file you want is in an arbin SQL database, insert the testname.",
"files = [\n # \"./data/raw/20160805_test001_45_cc_01.res\",\n # \"./data/raw/20160805_test001_45_cc_01_copy.res\",\n # \"./data/20210430_seam10_01_01_cc_01_Channel_48_Wb_1.xlsx.csv\",\n # \"./data/20210430_seam10_01_02_cc_01_Channel_49_Wb_1.xlsx.csv\",\n # \"20210630_seam13_03_02_cc_01\",\n # \"20210630_seam13_03_03_cc_01\",\n \"20210630_seam13_04_01_cc_01\",\n \"20210630_seam13_04_02_cc_01\",\n # \"20210630_seam13_04_03_cc_01\",\n]",
"3: Spawn easyplot object with desired settings\nAll possible settings can be printed by running \neasyplot.help()",
"easyplot.help()\n\nezplt = easyplot.EasyPlot(\n files,\n None,\n cyclelife_plot=True,\n cyclelife_percentage=False,\n cyclelife_coulombic_efficiency=True,\n cyclelife_coulombic_efficiency_ylabel=\"Coulombic efficiency [%]\",\n cyclelife_xlabel=\"Cycles\",\n cyclelife_ylabel=r\"Capacity $\\left[\\frac{mAh}{g}\\right]$\",\n cyclelife_ylabel_percent=\"Capacity retention [%]\",\n cyclelife_legend_outside=True, # if True, the legend is placed outside the plot\n galvanostatic_plot=True,\n galvanostatic_potlim=(0, 1), # min and max limit on potential-axis\n galvanostatic_caplim=None,\n galvanostatic_xlabel=r\"Capacity $\\left[\\frac{mAh}{g}\\right]$\",\n galvanostatic_ylabel=\"Cell potential [V]\",\n dqdv_plot=True,\n dqdv_potlim=None, # min and max limit on potential-axis\n dqdv_dqlim=None,\n dqdv_xlabel=\"Cell potential [V]\",\n dqdv_ylabel=r\"dQ/dV $\\left[\\frac{mAh}{gV}\\right]$\",\n specific_cycles=None, # []\n exclude_cycles=[1, 2],\n all_in_one=False,\n # only_dischg = True,\n only_chg=False,\n outpath=\"./ezplots/deleteme/\",\n figsize=(6, 4), # 6 inches wide, 4 inches tall\n figres=100, # Dots per inch\n figtitle=None, # None = original filepath\n)",
"3a: SQL settings\nIf you want to use the Arbin SQL database reader, you must insert the necessary details. This is done by the easyplot function set_arbin_sql_credentials\n\\\neasyplot.set_arbin_sql_credentials(<IP Address>, <Username>, <Password>, <SQL driver type>)",
"ezplt.set_arbin_sql_credentials(\"localhost\", \"sa\", \"Amund1234\", \"SQL Server\")",
"4: Run easyplot!",
"ezplt.plot()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
Python4AstronomersAndParticlePhysicists/PythonWorkshop-ICE
|
notebooks/10_03_Astronomy_PhotUtils.ipynb
|
mit
|
[
"Photometry with Photutils\nPhotutils is an affiliated package of Astropy to provide tools for detecting and performing photometry of astronomical sources.\nIt contains tools for:\n\nBackground Estimation (photutils.background)\nSource Detection (photutils.detection)\nGrouping Algorithms\nAperture Photometry (photutils.aperture)\nPSF Photometry (photutils.psf)\nPSF Matching (photutils.psf.matching)\nImage Segmentation (photutils.segmentation)\nCentroids (photutils.centroids)\nMorphological Properties (photutils.morphology)\nGeometry Functions (photutils.geometry)\nDatasets (photutils.datasets)\nUtility Functions (photutils.utils)",
"%matplotlib inline\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport seaborn\nfrom astropy.io import fits\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nplt.rcParams['figure.figsize'] = (12, 8)\nplt.rcParams['font.size'] = 14\nplt.rcParams['lines.linewidth'] = 2\nplt.rcParams['xtick.labelsize'] = 13\nplt.rcParams['ytick.labelsize'] = 13\nplt.rcParams['axes.titlesize'] = 14\nplt.rcParams['legend.fontsize'] = 13",
"As we will be using the image visualization several times, let's make a function that makes our code cleaner:",
"from astropy.visualization import ZScaleInterval\n\ndef my_python_ds9(data):\n norm = ZScaleInterval()\n vmin, vmax = norm.get_limits(data)\n plt.imshow(data, vmin=vmin, vmax=vmax, interpolation='none', origin='lower')\n plt.colorbar()",
"Before performing any photometry we need to have a first guess of the image background properties. For this section we will use a simpler optical image from the Sloan Digital Sky Survey (SDSS). This image contains the Spindle Galaxy, also known as Messier 102 or NGC 5866.",
"sdss_g_hdu_list = fits.open('../resources/sdss_g.fits')\nsdss_g_hdu_list.info()\n\nmy_python_ds9(sdss_g_hdu_list[0].data)\n\nplt.imshow(np.power(sdss_g_hdu_list[0].data[580:730, 500:750], 0.5), cmap='inferno', origin='lower')\nplt.grid('off')",
"Let's get the basic statistics of it. For that we will need to remove the sources using a sigma clipping routine:",
"from astropy.stats import sigma_clipped_stats\n\nmean, median, std = sigma_clipped_stats(sdss_g_hdu_list[0].data, sigma=3.0, iters=5) \nprint((mean, median, std)) ",
"We will need also the pixel scale that we can retrieve from the WCS:",
"from astropy import wcs\n\nsdss_g_image_wcs = wcs.WCS(sdss_g_hdu_list[0].header)\nsdss_pixelscale = np.mean(wcs.utils.proj_plane_pixel_scales(sdss_g_image_wcs) * u.degree).to('arcsec')\nsdss_pixelscale",
"Object detection\nTo detect the sources inside a astronomical image PhotUtils provides DAO Phot implementations to detect",
"from photutils import DAOStarFinder\nsigma_detection = 5.0\ndaofind = DAOStarFinder(fwhm=1.5 * u.arcsec / sdss_pixelscale, threshold=sigma_detection*std) \nsources = daofind(sdss_g_hdu_list[0].data - median) \nprint(sources)\n\nmy_python_ds9(sdss_g_hdu_list[0].data)\n\nplt.scatter(sources['xcentroid'], sources['ycentroid'], alpha=0.5, color='limegreen')",
"PSF Modelling\nWe assumed that the image had a typical value of 1.5\" per pixel. But we can make a more accurate estimation by fitting the pixels to a moffat profile around a detected star.\nFirst, let's select the source we want to use for PSF modelling:",
"isource = sources[50]\n\n# High SN - 50\n# Low SN - 33\n# Non-uniform background - 78\n\nprint (\"x pos: \" + str(isource['xcentroid']))\nprint (\"y pos: \" + str(isource['ycentroid']))\n\nstamp_radius = 50\nmy_python_ds9(sdss_g_hdu_list[0].data[int(isource['ycentroid'] - stamp_radius):\n int(isource['ycentroid'] + stamp_radius), \n int(isource['xcentroid'] - stamp_radius): \n int(isource['xcentroid'] + stamp_radius)])",
"As we intend to find the profile of the source, we need to remove the possible sky background that lies behind:",
"# Median bkg subtracted image\nbkg_subtracted_image = sdss_g_hdu_list[0].data - median\n\n# 2D background subtracted - For later\n#bkg_subtracted_image = sdss_g_hdu_list[0].data - bkg.background",
"To simplify the problem, we turn the 2D profile into a 1D distance array from the center of each pixel to the centroid of the source estimated by DAO Phot:",
"flux_counts = []\npixel_distance = []\n\nx_cen = int(isource['xcentroid'])\ny_cen = int(isource['ycentroid'])\n\n# Pixels around detection loop\nanalysis_radius = 10\nfor x in range(x_cen - analysis_radius, x_cen + analysis_radius):\n for y in range(y_cen - analysis_radius, y_cen + analysis_radius):\n flux_counts.append(((bkg_subtracted_image[y][x]) / isource['peak']))\n pixel_distance.append(np.linalg.norm((isource['xcentroid'] - x, isource['ycentroid'] - y)))",
"Here we present two possible models that can fit the PSF distribution. A Gaussian and a Moffat profile:",
"from astropy.modeling import models, fitting\n\nmodel = 'moffat'\n\nif model == 'gaussian':\n # Fit the data using a Gaussian\n fwhm_best_guess = 1.5\n model_init = models.Gaussian1D(amplitude=1.0, mean=0, stddev=fwhm_best_guess)\nelif model == 'moffat':\n # Fit the data using a Moffat\n model_init = models.Moffat1D(amplitude=1.0, x_0=0, gamma=2., alpha=3.5)\nelse:\n raise Exception(\"Unknown model type: %s. Must be gaussian or moffat.\" % model)\n\nfitter = fitting.SimplexLSQFitter()\nfitted_model = fitter(model_init, pixel_distance, flux_counts)\n\nprint (\"Fit value:\", fitter.fit_info['final_func_val'])\nprint (\"SN:\", isource['flux'] * sigma_detection)",
"Once fitted the models, we need to convert from the parameters to the actual FWHM estimate.",
"# FHWM conversion\nif model == 'gaussian':\n iFWHM = 2.355 * fitted_model.stddev * sdss_pixelscale.value\nelif model == 'moffat':\n iFWHM = fitted_model.gamma * 2 * np.sqrt(2 ** (1. / fitted_model.alpha) - 1) * sdss_pixelscale.value\nelse:\n raise Exception(\"Unknown model type: %s. Must be gaussian or moffat.\" % model)\n\nprint (\"FWHM estimated: \", iFWHM)",
"We can finally plot and see how the model traces the pixel values traces our fitted model.",
"# Check fitting\nif fitter.fit_info['final_func_val'] < 5.0:\n color = 'green'\nelse:\n color = 'red'\n \n# Plot the data with the best-fit model\nplt.figure()\nplt.plot(pixel_distance, flux_counts, 'ko')\nrx = np.linspace(0, int(max(pixel_distance)), int(max(pixel_distance)) * 10)\nplt.plot(rx,\n fitted_model(rx),\n color=color,\n lw=3.0,\n label='SN: %.2f, Fit: %.2f, FWHM: %.2f\"' % (isource['flux'] * sigma_detection,\n fitter.fit_info['final_func_val'],\n iFWHM))\nplt.xlabel('Distance (pixels)')\nplt.ylabel('Normalized flux (ADU)')\nplt.title('%s profile fit' % model)\nplt.legend()\nplt.show()",
"Background modelling\nAs we have seen in the case with non-uniform background, the constant median can be insuficient. Here we produce a 2D model of the background that can be subtracted from the original image to improve the modelling of the stars close to a very large extended source (or when the backrgound is not flat for any other reason)",
"from photutils import Background2D, SigmaClip, MedianBackground\nsigma_clip = SigmaClip(sigma=3., iters=10)\nbkg_estimator = MedianBackground()\nbkg = Background2D(data=sdss_g_hdu_list[0].data, \n box_size=(100, 100), \n filter_size=(3, 3),\n sigma_clip=sigma_clip, \n bkg_estimator=bkg_estimator)\nmy_python_ds9(bkg.background)",
"Now let's go back to where the background was subtracted to verify the difference.\nAperture photometry\nWe will work with the simple circular apertures. First we need to set the size we want and create the aperture objects:",
"from photutils import CircularAperture\n\naperture_radius = 5.0\n\npositions = (sources['xcentroid'], sources['ycentroid'])\napertures = CircularAperture(positions, r=aperture_radius)\n\nmy_python_ds9(sdss_g_hdu_list[0].data[0:400, 0:400])\napertures.plot(color='limegreen', lw=2)",
"Global Background subtraction\nAs we only want the flux from the sources we are interested in, we need to remove the contribution from the background. The simplest way is to remove the median value constant of the sigma clipped image that we calculated before to the entire array:",
"from photutils import aperture_photometry\n\nbkg_subtracted_image = sdss_g_hdu_list[0].data - median\nphot_table_global_bkg = aperture_photometry(bkg_subtracted_image, apertures)\nprint (phot_table_global_bkg)",
"Local Background subtraction\nWe could also remove the 2D background model that we calculated before, but it is usually more precise to create an annulus around the source we are interested in, and estimate the background level there.",
"from photutils import CircularAnnulus\n\nr_in = 10\nr_out = 15\n\nannulus_apertures = CircularAnnulus(positions, r_in=r_in, r_out=r_out)\n\nmy_python_ds9(sdss_g_hdu_list[0].data[0:400, 0:400])\napertures.plot(color='limegreen', lw=2)\nannulus_apertures.plot(color='purple', lw=2, alpha=1)",
"The circular apertures and the annulus can be joined for a common photometry processing.",
"apers = [apertures, annulus_apertures]\nphot_table_local_bkg = aperture_photometry(sdss_g_hdu_list[0].data, apers)\nprint(phot_table_local_bkg) ",
"Now we use the aperture_sum_1 to estimate the level of background around the source. We need to know the area of the annulus for this estimation:",
"bkg_mean = phot_table_local_bkg['aperture_sum_1'] / annulus_apertures.area()",
"And finally we can remove the background estimation to all pixels in the aperture:",
"bkg_sum = bkg_mean * apertures.area()\nfinal_sum = phot_table_local_bkg['aperture_sum_0'] - bkg_sum\nphot_table_local_bkg['residual_aperture_sum'] = final_sum\nprint(phot_table_local_bkg['residual_aperture_sum']) ",
"In this comparison we see that many sources have the same flux with both methods but a significant amount of sources (the ones in the galaxy halo) have significantly more flux in the global subtraction method, as the flux from M102 is added to the one of the stars.",
"plt.scatter(phot_table_local_bkg['residual_aperture_sum'], phot_table_global_bkg['aperture_sum'])\nplt.xlim(0,100)\nplt.ylim(0,100)\nplt.xlabel('Local background')\nplt.ylabel('Global background')",
"Let's make a plot to verify this! Astropy qtables work similarly to Pandas, so we can make iloc searches.\n<span style=\"color:blue\">Exercise PhotUtils:</span> Identify problematic sources\nLocate which sources differ their flux in more than 50% between the measurement with local and global background estimation. Plot the results on the image.\nTIP: Using the \"pandas-like\" tools can facilitate the selection",
"# %load -r 43-52 solutions/10_Astronomy.py",
"Accessing to annulus pixels\nBy default when calling aperture_photometry, we only receive the sum of pixels and therefore we can only access to the mean of the pixel values inside an aperture. To properly measure the local background, we would need to get the median of the pixels in the annulus and preferably, perform a sigma clipping over the values.\nRecently photutils enabled masks so we can actually do that!",
"# Flat annulus - 11\n# Source in annulus - 12\n\nsource_num = 12\n\nx = phot_table_local_bkg[source_num]['xcenter'].value\ny = phot_table_local_bkg[source_num]['ycenter'].value\n\nstamp_radius = 20\nmy_python_ds9(sdss_g_hdu_list[0].data[int(y - stamp_radius):\n int(y + stamp_radius), \n int(x - stamp_radius): \n int(x + stamp_radius)])\nplt.grid('off')",
"We can access to the annulus mask:",
"# Create annulus mask\nannulus_apertures = CircularAnnulus((x, y), r_in=r_in, r_out=r_out)\nmasks = annulus_apertures.to_mask(method='center')\nm0 = masks[0]\n\nplt.imshow(m0)\nplt.grid('off')",
"And apply it to the data:",
"# Cut to data\ncutout_data = m0.apply(sdss_g_hdu_list[0].data)\n\nplt.imshow(cutout_data)\nplt.grid('off')",
"Now that we have access to the pixels, we can perform the median and compare to the mean",
"annulus_array = cutout_data[cutout_data != 0]\n\n# Apply statistics to masked data\nmean = np.mean(annulus_array)\nmedian = np.median(annulus_array)\nstd = np.std(annulus_array)\nprint (mean, median, std)",
"And even sigma-clip the sources that may appear on top of the background. This creates a numpy.masked array:",
"from astropy.stats import sigma_clip\n\nclip_annulus_array = sigma_clip(annulus_array, sigma=3, iters=2)\n\nmean_clipped = np.ma.mean(clip_annulus_array)\nmedian_clipped = np.ma.median(clip_annulus_array)\nstd_clipped = np.ma.std(clip_annulus_array)\nprint (mean_clipped, median_clipped, std_clipped)",
"<span style=\"color:blue\">Exercise PhotUtils 2:</span> Estimate aperture error\nCompute what would be the measurement error for the last aperture (the one with sigma clipping)\n$$\n\\sigma^2_{F} = \\sum_i{\\sigma^2_{i}+F/g}\n$$\nTIP: Gain is the exposure time when pixels are in e/s",
"# %load -r 56-61 solutions/10_Astronomy.py",
"In this link you can find details on how to estimate the error:\nhttp://photutils.readthedocs.io/en/stable/photutils/aperture.html#error-estimation\nMatching catalogues\nastropy.coordinates contains commonly-used tools for comparing or matching coordinate objects. It supports leverages the coordinate framework to make it straightforward to find the closest coordinates in a catalog to a desired set of other coordinates. \nLet's do a new catalogue with the SDSS r band image on the same location in the sky",
"sdss_r_hdu_list = fits.open('../resources/sdss_r.fits')\nsdss_r_hdu_list.info()",
"If we plot the previous apertures in the sky, we realize that there is a slight offset (either due to pointing inaccuracy or dithering observarions)",
"my_python_ds9(sdss_r_hdu_list[0].data[0:200, 0:300])\napertures.plot(color='limegreen', lw=2)",
"In order to make a r band catalogue, we follow the same process as before \n[ don't replicate code like we do here... you should create a function or Scott will get mad!! ]",
"print (\"Image statistics...\")\nmean_r, median_r, std_r = sigma_clipped_stats(sdss_r_hdu_list[0].data, sigma=3.0, iters=5) \n\nprint (\"Source detection...\")\nsources_r = daofind(sdss_r_hdu_list[0].data - median_r) \n\nprint (\"Aperture definition...\")\npositions_r = (sources_r['xcentroid'], sources_r['ycentroid'])\napertures_r = CircularAperture(positions_r, r=aperture_radius)\nannulus_apertures_r = CircularAnnulus(positions_r, r_in=10, r_out=15)\n\nprint (\"Photometry calculation...\")\napers_r = [apertures_r, annulus_apertures_r]\nphot_table_local_bkg_r = aperture_photometry(sdss_r_hdu_list[0].data, apers_r)\nbkg_mean_r = phot_table_local_bkg_r['aperture_sum_1'] / annulus_apertures_r.area()\nbkg_sum_r = bkg_mean_r * apertures_r.area()\nfinal_sum_r = phot_table_local_bkg_r['aperture_sum_0'] - bkg_sum_r\nphot_table_local_bkg_r['residual_aperture_sum'] = final_sum_r\n\nprint (\"..ready!\")",
"In addition we se that more/different objects have been detected due to the different spectral emission of the sources",
"my_python_ds9(sdss_r_hdu_list[0].data[0:200, 0:300])\napertures.plot(color='limegreen', lw=2)\napertures_r.plot(color='red', lw=2)",
"First we create the two catalogues in sky coordinates using the WCS information as matching needs to be happen the same frame",
"origin = 0\n### g band catalogue ###\n# Create wcs object\nsdss_g_image_wcs = wcs.WCS(sdss_g_hdu_list[0].header)\n\n# Pixels to Sky\nlon_g, lat_g = sdss_g_image_wcs.all_pix2world(phot_table_local_bkg['xcenter'], \n phot_table_local_bkg['ycenter'], \n origin)\ncat_g = SkyCoord(ra=lon_g*u.degree, dec=lat_g*u.degree) \n\n\n### r band catalogue ###\n# Create wcs object\nsdss_r_image_wcs = wcs.WCS(sdss_r_hdu_list[0].header)\n\n# Pixels to Sky\nlon_r, lat_r = sdss_r_image_wcs.all_pix2world(phot_table_local_bkg_r['xcenter'], \n phot_table_local_bkg_r['ycenter'], \n origin)\ncat_r = SkyCoord(ra=lon_r*u.degree, dec=lat_r*u.degree) ",
"Closest catalogue matching\nThe following function performs the matching between the two catalogues, and returns what is the closest \"r\" source to each of the \"g\" sources. Therefore the resulting arrays contain the same number of indices than the catalogue \"g\".",
"id_r, d2d, d3d = cat_g.match_to_catalog_sky(cat_r)\n\nprint (len(id_r))\n\nhist_data = plt.hist(d2d.to('arcsec'), bins=100)\nplt.xlabel('distance (arcsec)')\nplt.ylabel('counts')",
"Comparing the fluxes, some matches show a very large difference, due to source mismatch and not due to color.",
"plt.scatter(phot_table_local_bkg['residual_aperture_sum'], phot_table_local_bkg_r[id_r]['residual_aperture_sum'])\nplt.xlabel('g flux')\nplt.ylabel('r flux')",
"Search around coordinates matching\nThe following function performs the matching between the two catalogues, returning only those sources that match within certain tolerance in the sky. Therefore",
"id_r_around, id_g_around, d2d_around, d3d_around = cat_g.search_around_sky(cat_r, 1*u.arcsec) \n\nprint (len(id_r_around))\n\nhist_data = plt.hist(d2d_around.to('arcsec'), bins=100)\nplt.xlabel('distance (arcsec)')\nplt.ylabel('counts')",
"Now we can see how the biggest outliers have disappeared, remaining only the difference in flux due to color.",
"plt.scatter(phot_table_local_bkg[id_g_around]['residual_aperture_sum'], phot_table_local_bkg_r[id_r_around]['residual_aperture_sum'])\nplt.xlabel('g flux')\nplt.ylabel('r flux')",
"From fluxes to magnitudes (in SDSS)\nThe images we use are already calibrated in photometry, and the units used are nanomaggies. Therefore\nm = [22.5 mag] – 2.5 log10 f.\nhttp://www.sdss.org/dr12/algorithms/magnitudes/#nmgy",
"def to_sdss_mag(fluxes):\n return 22.5 - np.log(fluxes)",
"Checking relation between measured flux and calibrated magnitude",
"mags_g = to_sdss_mag(phot_table_local_bkg['residual_aperture_sum'])\nplt.scatter(mags_g, phot_table_local_bkg['residual_aperture_sum'])",
"Matching to an external catalogue\nLoad the SDSS catalogue with astroquery that overlaps the image",
"from astroquery.sdss import SDSS\nfrom astropy import coordinates as coords\n\nregion = np.mean(sdss_r_image_wcs.calc_footprint(), axis=0)\nc = SkyCoord(region[0] * u.degree, region[1] * u.degree, frame='icrs')\n\nsdss_query = SDSS.query_region(c,\n spectro=False,\n radius=20*u.arcmin,\n photoobj_fields=['ra','dec','u','g','r','i','z'])\nprint(sdss_query)",
"Checking the catalogue: Color - Color plot",
"from matplotlib.colors import LogNorm\n\nplt.hist2d(sdss_query['g'] - sdss_query['r'], \n sdss_query['r'] - sdss_query['i'],\n range=[(-0.5,2), (-0.5,2)], \n bins=50, \n norm=LogNorm(),\n cmap='hot')\nplt.colorbar()\nplt.xlabel('g-r')\nplt.ylabel('r-i')",
"Finally we can check that calibrated photometry matches within some margin (probably due to different extraction method - Aperture vs Model)",
"cat_sdss_query = SkyCoord(ra=sdss_query['ra'] * u.degree, dec=sdss_query['dec'] * u.degree) \n\nid_query_around, id_g_around, d2d_around, d3d_around = cat_g.search_around_sky(cat_sdss_query, 0.5*u.arcsec) \n\nprint (len(id_query_around))\n\nplt.scatter(sdss_query[id_query_around]['g'], to_sdss_mag(phot_table_local_bkg[id_g_around]['residual_aperture_sum']))\nplt.xlim(15, 25)\nplt.ylim(15,25)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
EnergyID/opengrid
|
scripts/TimeSeries.ipynb
|
gpl-2.0
|
[
"This script shows how to use the existing code in opengrid to create a baseload electricity consumption benchmark.",
"import os, sys\nimport inspect\nimport numpy as np\n\n\nimport datetime as dt\nimport time\nimport pytz\nimport pandas as pd\nimport pdb\n\nscript_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n# add the path to opengrid to sys.path\nsys.path.append(os.path.join(script_dir, os.pardir, os.pardir))\nfrom opengrid.library import config\nc=config.Config()\nDEV = c.get('env', 'type') == 'dev' # DEV is True if we are in development environment, False if on the droplet\n\nif not DEV:\n # production environment: don't try to display plots\n import matplotlib\n matplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import HourLocator, DateFormatter, AutoDateLocator\n\n# find tmpo\nsys.path.append(c.get('tmpo', 'folder'))\n\ntry:\n if os.path.exists(c.get('tmpo', 'data')):\n path_to_tmpo_data = c.get('tmpo', 'data')\nexcept:\n path_to_tmpo_data = None\n\nfrom opengrid.library.houseprint import houseprint\n\nif DEV:\n if c.get('env', 'plots') == 'inline':\n %matplotlib inline\n else:\n %matplotlib qt\nelse:\n pass # don't try to render plots\nplt.rcParams['figure.figsize'] = 12,8\n\nimport charts",
"Script settings",
"number_of_days = 7",
"We create one big dataframe, the columns are the sensors",
"hp = houseprint.load_houseprint_from_file('new_houseprint.pkl')\nhp.init_tmpo(path_to_tmpo_data=path_to_tmpo_data)\n\nstart = pd.Timestamp(time.time() - number_of_days*86400, unit='s')\n\nsensors = hp.get_sensors()\n#sensors.remove('b325dbc1a0d62c99a50609e919b9ea06')\n\nfor sensor in sensors:\n s = sensor.get_data(head=start, resample='s')\n try: \n s = s.resample(rule='60s', how='max')\n s = s.diff()*3600/60\n\n # plot with charts (don't show it) and save html\n\n charts.plot(pd.DataFrame(s), stock=True, \n save=os.path.join(c.get('data', 'folder'), 'figures', 'TimeSeries_'+sensor.key+'.html'), show=True)\n except:\n pass\n\nlen(sensors)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
mikekestemont/lot2016
|
Chapter 4 - Loops.ipynb
|
mit
|
[
"Chapter 4: Loops\nIn programming, it is often very useful do carry out a the same action for a series of different items. You might, for instance, want to go through a list of words and count and print the number of characters in each word. Now, you could do this for each word individually and access every word, one item at a time",
"my_fruits = [\"apple\", \"pear\", \"peach\", \"banana\", \"peach\", \"cherry\", \"orange\", \"kiwi\"]\nprint(len(my_fruits[0]))\nprint(len(my_fruits[1]))\nprint(len(my_fruits[2]))\n# and so on...\nprint(len(my_fruits[-2]))\nprint(len(my_fruits[-1]))",
"Needless to say, this is rather cumbersome. Luckily, Python provides the so-called for-statements for this. The for loop allows us to iterate through any iteratable object, such as a list, and do the same thing with each of its elements. The basic format of a for-statement is: \nfor a_single_item in an_iterable_something:\n do_something_with(a_single_item)\n\nThat almost reads like English. We can print all letters of the word banana as follows:",
"for letter in \"banana\":\n print(letter)",
"The code in the loop is executed as many times as their are letters, with a different value for the variable letter at each iteration. (Read the previous sentence again, until you fully understand it.)\nLikewise, we can print all the items that are contained in a list:",
"colors = [\"yellow\", \"red\", \"green\", \"blue\", \"purple\"]\nfor color in colors:\n print(color)",
"Since dictionaries are iterable objects as well, we can iterate through our good reads collection as well. This will iterate over the keys of a dictionary:",
"for book in good_reads:\n print(book)",
"DIY\nThe function len() returns the length of an iterable item:",
"len(\"banana\")",
"We can use this function to print the length of each word in the color list. Write your code in the box below:",
"colors = [\"yellow\", \"red\", \"green\", \"blue\", \"purple\"]\n# insert your code here",
"Now write a small program that iterates through the list colors and appends all colors that contain the letter r to the list colors_with_r. (Tip: use the append() function!)",
"colors = [\"yellow\", \"red\", \"green\", \"blue\", \"purple\"]\ncolors_with_r = []\n# insert you code here\n\nfor color in colors:\n l = len(color)\n colors_with_r.append(l)\n print(colors_with_r) ",
"DIY\nWe have already covered a lot of ground. Now it is time to put some of the things that we have learned together. The following quiz might be quite hard and we would be very impressed if you get it right! \nWhat we want you to do is write code that counts how often the letter a occurs in a text. You cannot do this, however, on the basis of the text itself. Instead, you need to do this on the basis of a frequency dictionary of the test. In this dictionary frequency_dictionary, keys are words and values are the frequencies. Assign your value to the variable number_of_words_as.",
"frequency_dictionary = {\"Beg\": 1, \"Goddard's\": 1, \"I\": 3, \"them\": 2, \"absent\": 1, \"already\": 1,\n \"alteration\": 1, \"amazement\": 2, \"appeared\": 1, \"apprehensively\": 1, \n \"associations\": 1, 'clever': 1, 'clock': 1, 'composedly': 1, \n 'deeply': 7, 'do': 7, 'encouragement': 1, 'entrapped': 1,\n 'expressed': 1, 'flatterers': 1, 'following': 12, 'gone': 9, \n 'happening': 4, 'hero': 2, 'housekeeper': 1, 'ingratitude': 1, \n 'like': 1, 'marriage': 15, 'not': 25, 'opportunities': 1,\n 'outgrown': 1, 'playfully': 2, 'remain': 1, 'required': 2, \n 'ripening': 1, 'slippery': 1, 'touch': 1, 'twenty-five': 1,\n 'ungracious': 2, 'unwell': 1, 'verses': 1, 'yards': 5}\nnumber_of_as = 0\nprint(number_of_as != 0)\n\n\n# insert your code here\n\nfor word in frequency_dictionary:\n if 'a' in word:\n cnt = 0\n for character in word:\n if character == 'a':\n cnt += 1\n freq = frequency_dictionary[word]\n number_of_as += freq*cnt\n \n\nprint(number_of_as)\n\n# if your code is correct, the following line should print True!\n#print(number_of_as == 42)\n\n",
"while loop\nThere is also another form of looping in Python: the while loop. This is a loop that is tied to a logical expression. A while loop will run as long the specified expression is evaluated to be True. Check out the following example to see how this works:",
"number = 5\nwhile number < 21:\n number += 3\n print(number)",
"What we have learned\nHere is an overview of the new concepts, statements and functions we have learned in this section. Again, go through the list and make sure you understand them all.\n\nloop\nfor statement\nwhile statement\niterable objects\nvariable assignment in a for loop\n\n\nIterables, Iteration & Loops\nTuples & Sets\nLists and dictionaries are hugely important data structures and you will see a lot of them. They are almost always combined with the power of iteration using either for loops or other methods.\nIn addition to these data structures, there are two others which should be mentioned, these are tuples and sets. Lists, sets, tuples, dictionaries and even strings are often called iterables, as they are all collections over which can be iterated. \nTuples are ordered collections like lists, but they are immutable. Once created, nothing can be added, inserted, deleted or substituted. The main advantage is that they can be faster than lists, which is interesting if you have to process a lot of data. The syntax for creating a tuple involves round brackets (). For example:",
"fruittuple = ('banana','apple','pear')\nprint(fruittuple)\nprint(fruittuple[0])",
"Does notice a difference between the way Python prints lists, and the way it prints tuples to your screen? The following would have worked for lists, but does not for tuples (nor strings as we have seen before):",
"#fruittuple[0] = 'orange' # will raise an error, tuples are immutable!\nfor fruit in fruittuple:\n print(fruit)",
"A set is an unordered data collection in which an each element can only occur once, elements can be appended or deleted. It is unordered so this implies that you never really know in what order you get the elements when you iterate over the set. The syntax for creating a set is {}. This is not to be confused with dictionaries, those take key: value pairs where sets just take single elements.",
"fruitset = {'banana', 'apple', 'pear'}\nfruitset.add('banana') # will have no effect, banana already exists\nprint(fruitset)\nfruitset.add('orange')\nprint(fruitset)",
"Note that the order of the elements maybe different from the order you initialised the fruitset. This is because order has no meaning in the context of sets and neither in that of dictionaries.\nIn the previous chapter you learnt how to convert strings that contains numbers to integers, and how to turn integers and floats to strings. Such a kind of type casting can also be done for iterables, allowing you to turn almost any iterable into any other.",
"fruitlist = ['banana', 'apple', 'pear', 'banana', 'pear', 'kiwi']\nfruitset = set(fruitlist)\nprint(fruitset)\n\nfor fruit in fruitset:\n print(fruit)\n\n\n",
"sorted() and reverse()\nOften you want to iterate over your data in a sorted manner. The sorted() function will take any iterable and return the elements in sorted order. For strings this is alphabetical order, for numbers this is numerical order.",
"fruits = ['banana', 'apple', 'pear']\nfor fruit in sorted(fruits):\n print(fruit)",
"Reverse order is also possible by using reversed(), which simply returns the elements in any iterable in reverse order:",
"for fruit in reversed(fruits):\n print(fruit)",
"DIY\n\nGiven a list of words, output only the ones that are palindromes. As you know, a palindrome is a word that does not change when read backwards. If you need an extra challenge, try to print the palindromes in alphabetic order!",
"words = ['bicycle', 'radar', 'origin', 'tie', 'level', 'poop', 'solar', 'nun']\n# insert your code here\n\npalindromes = []\n\nfor original_word in words:\n reversed_word = ''\n for character in reversed(original_word):\n reversed_word += character\n if original_word == reversed_word:\n palindromes.append(original_word)\n\nprint(palindromes)\n",
"Extra Brownie points!\n\nThere are also words which are not palindromes, but when reversed another existing word emerges. Consider the words stressed and desserts. We give you a text that contains a few of them, output all pairs that occur in the text (regardless of case), but exclude words with a length of one.",
"text = \"I just live for desserts , I really love them . My dog does too . I saw he ate mine . I was very stressed because of that . If dogs steal desserts God can't be real , for it is pure evil .\" \n# insert your code here",
"min(), max() and sum()\nWhen dealing with lists of numbers, there are three functions which come in handy:",
"numbers = [1, 2, 3, 4, 5]\nprint(min(numbers))\nprint(max(numbers))\nprint(sum(numbers))",
"DIY\n\nCompute the average of numbers:",
"# insert your code here",
"Final Exercises Chapter 4\nInspired by Think Python by Allen B. Downey (http://thinkpython.com), Introduction to Programming Using Python by Y. Liang (Pearson, 2013). Some exercises below have been taken from: http://www.ling.gu.se/~lager/python_exercises.html.\n\nDefine a sentence and split it into words along whitespace. Now fill a dictionary that holds the frequencies (value) for each word (key) in the sentence. You should first check whether a word is already present in your dictionary. If it is, augment its frequency. Else, you should first initialize its frequency.",
"# fill dictionary code\n",
"By now, you already know that Python has the len() function built-in, but can you write yourself a code block that prints the length of the string lengthy_word that you will define? First use a for loop; then try to achieve the same results with a while loop, but watch out that you don't get stuck an infinite loop!",
"# lengthy word (1) code",
"Have another look at the string variable lenghty_word that you defined in the previous exercices. Can you write a code block that fills a dictionary char_freqs containing the frequency of the different individual characters in length_word?",
"# lengty_word (2) code",
"Let's have yet another at lengthy_word. Can you write code that creates the dictionary next_char, holding for each first occurence of a character (key) the next character in the word as value. If the character is already in the dictionary, do nothing and if you're dealing with the last character in the word, add \"Last word!\" as value to the dictionary for this character.",
"# lengthy_word (3) code",
"Write a code block that defines a list of integers and prints them as a histogram to the screen. For example, for histogram = [4, 9, 7, 2, 16, 8, 3], the code should print the following:\n\n++++\n+++++++++\n+++++++\n++\n++++++++++++++++\n++++++++\n+++",
"# histogram",
"\"99 Bottles of Beer\" is a traditional song in the United States and Canada. It is popular to sing on long trips, as it has a very repetitive format which is easy to memorize, and can take a long time to sing. The song's simple lyrics are as follows: \"99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall.\" The same verse is repeated, each time with one fewer bottle. The song is completed when the singer or singers reach zero. Your task here is write a Python code block capable of generating all the verses of the song. Use a counter integer variable and a while loop. Make sure that your loop will come to an end and that the inflection of the word bottle is adapted to the counter!",
"# bottles of beer",
"The third person singular verb form in English is distinguished by the suffix -s, which is added to the stem of the infinitive form: run -> runs. A simple set of rules can be given as follows: \"If the verb ends in y, remove it and add ies. If the verb ends in o, ch, s, sh, x or z, add es. By default just add s.\" Your task in this exercise is to write a code block which given a verb in infinitive form, prints its third person singular form. Test your function with words like \"try\", \"brush\", \"run\" and \"fix\". Can you think of verbs for which your code doesn't work? Check out the string method .endswith() online!",
"# verbs code",
"ROT13 is a way to encode secret messages in cryptography. The name comes from Julius Caesar, who used it to communicate with his generals. ROT13 (\"rotate by 13 places\") is a widely used example of a Caesar cipher. The idea is to rotate or augment the position of each character in the alphabet with thirteen places. Your task in this exercise is to implement an encoder/decoder of ROT-13. For this, you will need to create a list containing each letter in the (lowercase) roman alphabet as well as the whitespace character. Next, you will have to create an encode_dict and a decode_dict. Once you're done, you will be able to read the following secret message: \"Pnrfne pvcure? V zhpu cersre Pnrfne fnynq!\" (Hint: you can use .index() to retrieve the position of an item in a list!)",
"# Caesar code",
"Congrats: you've reached the end of Chapter 4! Ignore the code block below; it's only here to make the page prettier.",
"from IPython.core.display import HTML\ndef css_styling():\n styles = open(\"styles/custom.css\", \"r\").read()\n return HTML(styles)\ncss_styling()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
minxuancao/shogun
|
doc/ipython-notebooks/classification/MKL.ipynb
|
gpl-3.0
|
[
"Multiple Kernel Learning\nBy Saurabh Mahindre - <a href=\"https://github.com/Saurabh7\">github.com/Saurabh7</a>\nThis notebook is about multiple kernel learning in shogun. We will see how to construct a combined kernel, determine optimal kernel weights using MKL and use it for different types of classification and novelty detection.\n\nIntroduction\nMathematical formulation\nUsing a Combined kernel\nExample: Toy Data\nGenerating Kernel weights\nBinary classification using MKL\nMKL for knowledge discovery\nMulticlass classification using MKL\nOne-class classification using MKL",
"%pylab inline\n%matplotlib inline\nimport os\nSHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')\n# import all shogun classes\nfrom modshogun import *",
"Introduction\n<em>Multiple kernel learning</em> (MKL) is about using a combined kernel i.e. a kernel consisting of a linear combination of arbitrary kernels over different domains. The coefficients or weights of the linear combination can be learned as well.\nKernel based methods such as support vector machines (SVMs) employ a so-called kernel function $k(x_{i},x_{j})$ which intuitively computes the similarity between two examples $x_{i}$ and $x_{j}$. </br>\nSelecting the kernel function\n$k()$ and it's parameters is an important issue in training. Kernels designed by humans usually capture one aspect of data. Choosing one kernel means to select exactly one such aspect. Which means combining such aspects is often better than selecting.\nIn shogun the CMKL is the base class for MKL. We can do classifications: binary, one-class, multiclass and regression too: regression.\nMathematical formulation (skip if you just want code examples)\n</br>In a SVM, defined as:\n$$f({\\bf x})=\\text{sign} \\left(\\sum_{i=0}^{N-1} \\alpha_i k({\\bf x}, {\\bf x_i})+b\\right)$$</br>\nwhere ${\\bf x_i},{i = 1,...,N}$ are labeled training examples ($y_i \\in {±1}$).\nOne could make a combination of kernels like:\n$${\\bf k}(x_i,x_j)=\\sum_{k=0}^{K} \\beta_k {\\bf k_k}(x_i, x_j)$$\nwhere $\\beta_k > 0$ and $\\sum_{k=0}^{K} \\beta_k = 1$\nIn the multiple kernel learning problem for binary classification one is given $N$ data points ($x_i, y_i$ )\n ($y_i \\in {±1}$), where $x_i$ is translated via $K$ mappings $\\phi_k(x) \\rightarrow R^{D_k} $, $k=1,...,K$ , from the input into $K$ feature spaces $(\\phi_1(x_i),...,\\phi_K(x_i))$ where $D_k$ denotes dimensionality of the $k$-th feature space.\nIn MKL $\\alpha_i$,$\\beta$ and bias are determined by solving the following optimization program. For details see [1].\n$$\\mbox{min} \\hspace{4mm} \\gamma-\\sum_{i=1}^N\\alpha_i$$\n$$ \\mbox{w.r.t.} \\hspace{4mm} \\gamma\\in R, \\alpha\\in R^N \\nonumber$$\n$$\\mbox {s.t.} \\hspace{4mm} {\\bf 0}\\leq\\alpha\\leq{\\bf 1}C,\\;\\;\\sum_{i=1}^N \\alpha_i y_i=0 \\nonumber$$\n$$ {\\frac{1}{2}\\sum_{i,j=1}^N \\alpha_i \\alpha_j y_i y_j \\leq \\gamma}, \\forall k=1,\\ldots,K\\nonumber\\\n$$\nHere C is a pre-specified regularization parameter.\nWithin shogun this optimization problem is solved using semi-infinite programming. For 1-norm MKL one of the two approaches described in [1] is used.\nThe first approach (also called the wrapper algorithm) wraps around a single kernel SVMs, alternatingly solving for $\\alpha$ and $\\beta$. It is using a traditional SVM to generate new violated constraints and thus requires a single kernel SVM and any of the SVMs contained in shogun can be used. In the MKL step either a linear program is solved via glpk or cplex or analytically or a newton (for norms>1) step is performed.\nThe second much faster but also more memory demanding approach performing interleaved optimization, is integrated into the chunking-based SVMlight.\nUsing a Combined kernel\nShogun provides an easy way to make combination of kernels using the CombinedKernel class, to which we can append any kernel from the many options shogun provides. It is especially useful to combine kernels working on different domains and to combine kernels looking at independent features and requires CombinedFeatures to be used. Similarly the CombinedFeatures is used to combine a number of feature objects into a single CombinedFeatures object",
"kernel = CombinedKernel()",
"Prediction on toy data\nIn order to see the prediction capabilities, let us generate some data using the GMM class. The data is sampled by setting means (GMM notebook) such that it sufficiently covers X-Y grid and is not too easy to classify.",
"num=30;\nnum_components=4\nmeans=zeros((num_components, 2))\nmeans[0]=[-1,1]\nmeans[1]=[2,-1.5]\nmeans[2]=[-1,-3]\nmeans[3]=[2,1]\n\ncovs=array([[1.0,0.0],[0.0,1.0]])\n\ngmm=GMM(num_components)\n[gmm.set_nth_mean(means[i], i) for i in range(num_components)]\n[gmm.set_nth_cov(covs,i) for i in range(num_components)]\ngmm.set_coef(array([1.0,0.0,0.0,0.0]))\nxntr=array([gmm.sample() for i in xrange(num)]).T\nxnte=array([gmm.sample() for i in xrange(5000)]).T\ngmm.set_coef(array([0.0,1.0,0.0,0.0]))\nxntr1=array([gmm.sample() for i in xrange(num)]).T\nxnte1=array([gmm.sample() for i in xrange(5000)]).T\ngmm.set_coef(array([0.0,0.0,1.0,0.0]))\nxptr=array([gmm.sample() for i in xrange(num)]).T\nxpte=array([gmm.sample() for i in xrange(5000)]).T\ngmm.set_coef(array([0.0,0.0,0.0,1.0]))\nxptr1=array([gmm.sample() for i in xrange(num)]).T\nxpte1=array([gmm.sample() for i in xrange(5000)]).T\ntraindata=concatenate((xntr,xntr1,xptr,xptr1), axis=1)\ntrainlab=concatenate((-ones(2*num), ones(2*num)))\n\ntestdata=concatenate((xnte,xnte1,xpte,xpte1), axis=1)\ntestlab=concatenate((-ones(10000), ones(10000)))\n\n#convert to shogun features and generate labels for data\nfeats_train=RealFeatures(traindata) \nlabels=BinaryLabels(trainlab) \n\n_=jet()\nfigure(figsize(18,5))\nsubplot(121)\n# plot train data\n_=scatter(traindata[0,:], traindata[1,:], c=trainlab, s=100)\ntitle('Toy data for classification')\naxis('equal')\ncolors=[\"blue\",\"blue\",\"red\",\"red\"]\n# a tool for visualisation\nfrom matplotlib.patches import Ellipse\ndef get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color=\"red\", linewidth=3):\n vals, vecs = eigh(cov)\n order = vals.argsort()[::-1]\n vals, vecs = vals[order], vecs[:, order] \n theta = numpy.degrees(arctan2(*vecs[:, 0][::-1]))\n width, height = 2 * nstd * sqrt(vals)\n e = Ellipse(xy=mean, width=width, height=height, angle=theta, \\\n edgecolor=color, fill=False, linewidth=linewidth)\n \n return e\nfor i in range(num_components):\n gca().add_artist(get_gaussian_ellipse_artist(means[i], covs, color=colors[i]))",
"Generating Kernel weights\nJust to help us visualize let's use two gaussian kernels (CGaussianKernel) with considerably different widths. As required in MKL, we need to append them to the Combined kernel. To generate the optimal weights (i.e $\\beta$s in the above equation), training of MKL is required. This generates the weights as seen in this example.",
"width0=0.5\nkernel0=GaussianKernel(feats_train, feats_train, width0)\n\nwidth1=25\nkernel1=GaussianKernel(feats_train, feats_train, width1)\n\n#combine kernels\nkernel.append_kernel(kernel0) \nkernel.append_kernel(kernel1)\nkernel.init(feats_train, feats_train)\n\nmkl = MKLClassification()\n#set the norm, weights sum to 1.\nmkl.set_mkl_norm(1) \nmkl.set_C(1, 1)\nmkl.set_kernel(kernel)\nmkl.set_labels(labels)\n\n#train to get weights\nmkl.train() \n\nw=kernel.get_subkernel_weights()\nprint w",
"Binary classification using MKL\nNow with the data ready and training done, we can do the binary classification. The weights generated can be intuitively understood. We will see that on plotting individual subkernels outputs and outputs of the MKL classification. To apply on test features, we need to reinitialize the kernel with kernel.init and pass the test features. After that it's just a matter of doing mkl.apply to generate outputs.",
"size=100\nx1=linspace(-5, 5, size)\nx2=linspace(-5, 5, size)\nx, y=meshgrid(x1, x2)\n#Generate X-Y grid test data\ngrid=RealFeatures(array((ravel(x), ravel(y))))\n\nkernel0t=GaussianKernel(feats_train, grid, width0)\nkernel1t=GaussianKernel(feats_train, grid, width1)\n\nkernelt=CombinedKernel()\nkernelt.append_kernel(kernel0t)\nkernelt.append_kernel(kernel1t)\n#initailize with test grid\nkernelt.init(feats_train, grid)\n\nmkl.set_kernel(kernelt)\n#prediction\ngrid_out=mkl.apply() \n\nz=grid_out.get_values().reshape((size, size))\n\nfigure(figsize=(10,5))\ntitle(\"Classification using MKL\")\nc=pcolor(x, y, z)\n_=contour(x, y, z, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\n\n",
"To justify the weights, let's train and compare two subkernels with the MKL classification output. Training MKL classifier with a single kernel appended to a combined kernel makes no sense and is just like normal single kernel based classification, but let's do it for comparison.",
"z=grid_out.get_labels().reshape((size, size))\n\n# MKL\nfigure(figsize=(20,5))\nsubplot(131, title=\"Multiple Kernels combined\")\nc=pcolor(x, y, z)\n_=contour(x, y, z, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\n\ncomb_ker0=CombinedKernel()\ncomb_ker0.append_kernel(kernel0)\ncomb_ker0.init(feats_train, feats_train)\nmkl.set_kernel(comb_ker0)\nmkl.train()\ncomb_ker0t=CombinedKernel()\ncomb_ker0t.append_kernel(kernel0)\ncomb_ker0t.init(feats_train, grid)\nmkl.set_kernel(comb_ker0t)\nout0=mkl.apply()\n\n# subkernel 1\nz=out0.get_labels().reshape((size, size)) \nsubplot(132, title=\"Kernel 1\")\nc=pcolor(x, y, z)\n_=contour(x, y, z, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\n\ncomb_ker1=CombinedKernel()\ncomb_ker1.append_kernel(kernel1)\ncomb_ker1.init(feats_train, feats_train)\nmkl.set_kernel(comb_ker1)\nmkl.train()\ncomb_ker1t=CombinedKernel()\ncomb_ker1t.append_kernel(kernel1)\ncomb_ker1t.init(feats_train, grid)\nmkl.set_kernel(comb_ker1t)\nout1=mkl.apply()\n\n# subkernel 2\nz=out1.get_labels().reshape((size, size)) \nsubplot(133, title=\"kernel 2\")\nc=pcolor(x, y, z)\n_=contour(x, y, z, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\n\n",
"As we can see the multiple kernel output seems just about right. Kernel 1 gives a sort of overfitting output while the kernel 2 seems not so accurate. The kernel weights are hence so adjusted to get a refined output. We can have a look at the errors by these subkernels to have more food for thought. Most of the time, the MKL error is lesser as it incorporates aspects of both kernels. One of them is strict while other is lenient, MKL finds a balance between those.",
"kernelt.init(feats_train, RealFeatures(testdata))\nmkl.set_kernel(kernelt)\nout=mkl.apply()\n\nevaluator=ErrorRateMeasure()\nprint \"Test error is %2.2f%% :MKL\" % (100*evaluator.evaluate(out,BinaryLabels(testlab)))\n\n\ncomb_ker0t.init(feats_train,RealFeatures(testdata)) \nmkl.set_kernel(comb_ker0t)\nout=mkl.apply()\n\nevaluator=ErrorRateMeasure()\nprint \"Test error is %2.2f%% :Subkernel1\"% (100*evaluator.evaluate(out,BinaryLabels(testlab)))\n\ncomb_ker1t.init(feats_train, RealFeatures(testdata))\nmkl.set_kernel(comb_ker1t)\nout=mkl.apply()\n\nevaluator=ErrorRateMeasure()\nprint \"Test error is %2.2f%% :subkernel2\" % (100*evaluator.evaluate(out,BinaryLabels(testlab)))\n",
"MKL for knowledge discovery\nMKL can recover information about the problem at hand. Let us see this with a binary classification problem. The task is to separate two concentric classes shaped like circles. By varying the distance between the boundary of the circles we can control the separability of the problem. Starting with an almost non-separable scenario, the data quickly becomes separable as the distance between the circles increases.",
"def circle(x, radius, neg):\n y=sqrt(square(radius)-square(x))\n if neg:\n return[x, -y]\n else:\n return [x,y]\n \ndef get_circle(radius):\n neg=False\n range0=linspace(-radius,radius,100)\n pos_a=array([circle(i, radius, neg) for i in range0]).T\n neg=True\n neg_a=array([circle(i, radius, neg) for i in range0]).T\n c=concatenate((neg_a,pos_a), axis=1)\n return c\n\ndef get_data(r1, r2):\n c1=get_circle(r1)\n c2=get_circle(r2)\n c=concatenate((c1, c2), axis=1)\n feats_tr=RealFeatures(c)\n return c, feats_tr\n\nl=concatenate((-ones(200),ones(200)))\nlab=BinaryLabels(l)\n\n#get two circles with radius 2 and 4\nc, feats_tr=get_data(2,4)\nc1, feats_tr1=get_data(2,3)\n_=gray()\nfigure(figsize=(10,5))\nsubplot(121)\ntitle(\"Circles with different separation\")\np=scatter(c[0,:], c[1,:], c=lab)\nsubplot(122)\nq=scatter(c1[0,:], c1[1,:], c=lab)\n",
"These are the type of circles we want to distinguish between. We can try classification with a constant separation between the circles first.",
"def train_mkl(circles, feats_tr):\n #Four kernels with different widths \n kernel0=GaussianKernel(feats_tr, feats_tr, 1) \n kernel1=GaussianKernel(feats_tr, feats_tr, 5)\n kernel2=GaussianKernel(feats_tr, feats_tr, 7)\n kernel3=GaussianKernel(feats_tr, feats_tr, 10)\n kernel = CombinedKernel()\n kernel.append_kernel(kernel0)\n kernel.append_kernel(kernel1)\n kernel.append_kernel(kernel2)\n kernel.append_kernel(kernel3)\n \n kernel.init(feats_tr, feats_tr)\n mkl = MKLClassification()\n mkl.set_mkl_norm(1)\n mkl.set_C(1, 1)\n mkl.set_kernel(kernel)\n mkl.set_labels(lab)\n \n mkl.train()\n \n w=kernel.get_subkernel_weights()\n return w, mkl\n\ndef test_mkl(mkl, grid):\n kernel0t=GaussianKernel(feats_tr, grid, 1)\n kernel1t=GaussianKernel(feats_tr, grid, 5)\n kernel2t=GaussianKernel(feats_tr, grid, 7)\n kernel3t=GaussianKernel(feats_tr, grid, 10)\n kernelt = CombinedKernel()\n kernelt.append_kernel(kernel0t)\n kernelt.append_kernel(kernel1t)\n kernelt.append_kernel(kernel2t)\n kernelt.append_kernel(kernel3t)\n kernelt.init(feats_tr, grid)\n mkl.set_kernel(kernelt)\n out=mkl.apply()\n return out\n\nsize=50\nx1=linspace(-10, 10, size)\nx2=linspace(-10, 10, size)\nx, y=meshgrid(x1, x2)\ngrid=RealFeatures(array((ravel(x), ravel(y))))\n\n\nw, mkl=train_mkl(c, feats_tr)\nprint w\nout=test_mkl(mkl,grid)\n\nz=out.get_values().reshape((size, size))\n\nfigure(figsize=(5,5))\nc=pcolor(x, y, z)\n_=contour(x, y, z, linewidths=1, colors='black', hold=True)\ntitle('classification with constant separation')\n_=colorbar(c)",
"As we can see the MKL classifier classifies them as expected. Now let's vary the separation and see how it affects the weights.The choice of the kernel width of the Gaussian kernel used for classification is expected to depend on the separation distance of the learning problem. An increased distance between the circles will correspond to a larger optimal kernel width. This effect should be visible in the results of the MKL, where we used MKL-SVMs with four kernels with different widths (1,5,7,10).",
"range1=linspace(5.5,7.5,50)\nx=linspace(1.5,3.5,50)\ntemp=[]\n\nfor i in range1:\n #vary separation between circles\n c, feats=get_data(4,i) \n w, mkl=train_mkl(c, feats)\n temp.append(w)\ny=array([temp[i] for i in range(0,50)]).T\n\n\nfigure(figsize=(20,5))\n_=plot(x, y[0,:], color='k', linewidth=2)\n_=plot(x, y[1,:], color='r', linewidth=2)\n_=plot(x, y[2,:], color='g', linewidth=2)\n_=plot(x, y[3,:], color='y', linewidth=2)\ntitle(\"Comparison between kernel widths and weights\")\nylabel(\"Weight\")\nxlabel(\"Distance between circles\")\n_=legend([\"1\",\"5\",\"7\",\"10\"])\n ",
"In the above plot we see the kernel weightings obtained for the four kernels. Every line shows one weighting. The courses of the kernel weightings reflect the development of the learning problem: as long as the problem is difficult the best separation can be obtained when using the kernel with smallest width. The low width kernel looses importance when the distance between the circle increases and larger kernel widths obtain a larger weight in MKL. Increasing the distance between the circles, kernels with greater widths are used. \nMulticlass classification using MKL\nMKL can be used for multiclass classification using the MKLMulticlass class. It is based on the GMNPSVM Multiclass SVM. Its termination criterion is set by set_mkl_epsilon(float64_t eps ) and the maximal number of MKL iterations is set by set_max_num_mkliters(int32_t maxnum). The epsilon termination criterion is the L2 norm between the current MKL weights and their counterpart from the previous iteration. We set it to 0.001 as we want pretty accurate weights.\nTo see this in action let us compare it to the normal GMNPSVM example as in the KNN notebook, just to see how MKL fares in object recognition. We use the USPS digit recognition dataset.",
"from scipy.io import loadmat, savemat\nfrom os import path, sep\n\nmat = loadmat(sep.join(['..','..','..','data','multiclass', 'usps.mat']))\nXall = mat['data']\nYall = array(mat['label'].squeeze(), dtype=double)\n\n# map from 1..10 to 0..9, since shogun\n# requires multiclass labels to be\n# 0, 1, ..., K-1\nYall = Yall - 1\n\nrandom.seed(0)\n\nsubset = random.permutation(len(Yall))\n\n#get first 1000 examples\nXtrain = Xall[:, subset[:1000]]\nYtrain = Yall[subset[:1000]]\n\nNsplit = 2\nall_ks = range(1, 21)\n\nprint Xall.shape\nprint Xtrain.shape",
"Let's plot five of the examples to get a feel of the dataset.",
"def plot_example(dat, lab):\n for i in xrange(5):\n ax=subplot(1,5,i+1)\n title(int(lab[i]))\n ax.imshow(dat[:,i].reshape((16,16)), interpolation='nearest')\n ax.set_xticks([])\n ax.set_yticks([])\n \n \n_=figure(figsize=(17,6))\ngray()\nplot_example(Xtrain, Ytrain)\n",
"We combine a Gaussian kernel and a PolyKernel. To test, examples not included in training data are used.\nThis is just a demonstration but we can see here how MKL is working behind the scene. What we have is two kernels with significantly different properties. The gaussian kernel defines a function space that is a lot larger than that of the linear kernel or the polynomial kernel. The gaussian kernel has a low width, so it will be able to represent more and more complex relationships between the training data. But it requires enough data to train on. The number of training examples here is 1000, which seems a bit less as total examples are 10000. We hope the polynomial kernel can counter this problem, since it will fit the polynomial for you using a lot less data than the squared exponential. The kernel weights are printed below to add some insight.",
"# MKL training and output\nlabels = MulticlassLabels(Ytrain)\nfeats = RealFeatures(Xtrain)\n#get test data from 5500 onwards\nXrem=Xall[:,subset[5500:]]\nYrem=Yall[subset[5500:]]\n\n#test features not used in training\nfeats_rem=RealFeatures(Xrem) \nlabels_rem=MulticlassLabels(Yrem)\n\nkernel = CombinedKernel()\nfeats_train = CombinedFeatures()\nfeats_test = CombinedFeatures()\n\n#append gaussian kernel\nsubkernel = GaussianKernel(10,15) \nfeats_train.append_feature_obj(feats)\nfeats_test.append_feature_obj(feats_rem)\nkernel.append_kernel(subkernel)\n\n#append PolyKernel\nfeats = RealFeatures(Xtrain)\nsubkernel = PolyKernel(10,2) \nfeats_train.append_feature_obj(feats)\nfeats_test.append_feature_obj(feats_rem)\nkernel.append_kernel(subkernel)\n\nkernel.init(feats_train, feats_train)\n\nmkl = MKLMulticlass(1.2, kernel, labels)\n\nmkl.set_epsilon(1e-2)\nmkl.set_mkl_epsilon(0.001)\nmkl.set_mkl_norm(1)\n\nmkl.train()\n\n#initialize with test features\nkernel.init(feats_train, feats_test) \n\nout = mkl.apply()\nevaluator = MulticlassAccuracy()\naccuracy = evaluator.evaluate(out, labels_rem)\nprint \"Accuracy = %2.2f%%\" % (100*accuracy)\n\nidx=where(out.get_labels() != Yrem)[0]\nXbad=Xrem[:,idx]\nYbad=Yrem[idx]\n_=figure(figsize=(17,6))\ngray()\nplot_example(Xbad, Ybad)\n\nw=kernel.get_subkernel_weights()\nprint w\n\n# Single kernel:PolyKernel\nC=1\n\npk=PolyKernel(10,2) \n\nsvm=GMNPSVM(C, pk, labels)\n_=svm.train(feats)\nout=svm.apply(feats_rem)\nevaluator = MulticlassAccuracy()\naccuracy = evaluator.evaluate(out, labels_rem)\n\nprint \"Accuracy = %2.2f%%\" % (100*accuracy)\n\nidx=np.where(out.get_labels() != Yrem)[0]\nXbad=Xrem[:,idx]\nYbad=Yrem[idx]\n_=figure(figsize=(17,6))\ngray()\nplot_example(Xbad, Ybad)\n\n#Single Kernel:Gaussian kernel\nwidth=15\nC=1\n\ngk=GaussianKernel()\ngk.set_width(width)\n\nsvm=GMNPSVM(C, gk, labels)\n_=svm.train(feats)\nout=svm.apply(feats_rem)\nevaluator = MulticlassAccuracy()\naccuracy = evaluator.evaluate(out, labels_rem)\n\nprint \"Accuracy = %2.2f%%\" % (100*accuracy)\n\nidx=np.where(out.get_labels() != Yrem)[0]\nXbad=Xrem[:,idx]\nYbad=Yrem[idx]\n_=figure(figsize=(17,6))\ngray()\nplot_example(Xbad, Ybad)",
"The misclassified examples are surely pretty tough to predict. As seen from the accuracy MKL seems to work a shade better in the case. One could try this out with more and different types of kernels too.\nOne-class classification using MKL\nOne-class classification can be done using MKL in shogun. This is demonstrated in the following simple example using CMKLOneClass. We will see how abnormal data is detected. This is also known as novelty detection. Below we generate some toy data and initialize combined kernels and features.",
"X = -0.3 * random.randn(100,2)\ntraindata=r_[X + 2, X - 2].T\n\nX = -0.3 * random.randn(20, 2)\ntestdata = r_[X + 2, X - 2].T\n\ntrainlab=concatenate((ones(99),-ones(1)))\n#convert to shogun features and generate labels for data\nfeats=RealFeatures(traindata) \nlabels=BinaryLabels(trainlab) \n\nxx, yy = meshgrid(linspace(-5, 5, 500), linspace(-5, 5, 500))\ngrid=RealFeatures(array((ravel(xx), ravel(yy))))\n#test features\nfeats_t=RealFeatures(testdata) \nx_out=(random.uniform(low=-4, high=4, size=(20, 2))).T\nfeats_out=RealFeatures(x_out)\n\nkernel=CombinedKernel()\nfeats_train=CombinedFeatures()\nfeats_test=CombinedFeatures()\nfeats_test_out=CombinedFeatures()\nfeats_grid=CombinedFeatures()\n\n#append gaussian kernel\nsubkernel=GaussianKernel(10,8) \nfeats_train.append_feature_obj(feats)\nfeats_test.append_feature_obj(feats_t)\nfeats_test_out.append_feature_obj(feats_out)\nfeats_grid.append_feature_obj(grid)\nkernel.append_kernel(subkernel)\n\n#append PolyKernel\nfeats = RealFeatures(traindata)\nsubkernel = PolyKernel(10,3) \nfeats_train.append_feature_obj(feats)\nfeats_test.append_feature_obj(feats_t)\nfeats_test_out.append_feature_obj(feats_out)\nfeats_grid.append_feature_obj(grid)\nkernel.append_kernel(subkernel)\n\nkernel.init(feats_train, feats_train)\n\nmkl = MKLOneClass()\nmkl.set_kernel(kernel)\nmkl.set_labels(labels)\nmkl.set_interleaved_optimization_enabled(False)\n\nmkl.set_epsilon(1e-2)\nmkl.set_mkl_epsilon(0.1)\nmkl.set_mkl_norm(1)",
"Now that everything is initialized, let's see MKLOneclass in action by applying it on the test data and on the X-Y grid.",
"mkl.train()\nprint \"Weights:\"\nw=kernel.get_subkernel_weights()\nprint w\n\n#initialize with test features\nkernel.init(feats_train, feats_test) \nnormal_out = mkl.apply()\n\n#test on abnormally generated data\nkernel.init(feats_train, feats_test_out) \nabnormal_out = mkl.apply()\n\n#test on X-Y grid\nkernel.init(feats_train, feats_grid)\ngrid_out=mkl.apply()\nz=grid_out.get_values().reshape((500,500))\nz_lab=grid_out.get_labels().reshape((500,500))\n\na=abnormal_out.get_labels()\nn=normal_out.get_labels()\n\n#check for normal and abnormal classified data\nidx=where(normal_out.get_labels() != 1)[0]\nabnormal=testdata[:,idx]\n\nidx=where(normal_out.get_labels() == 1)[0]\nnormal=testdata[:,idx]\n\nfigure(figsize(15,6))\npl =subplot(121)\ntitle(\"One-class classification using MKL\")\n_=pink()\nc=pcolor(xx, yy, z)\n_=contour(xx, yy, z_lab, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\np1=pl.scatter(traindata[0, :], traindata[1,:], cmap=gray(), s=100)\np2=pl.scatter(normal[0,:], normal[1,:], c=\"red\", s=100)\np3=pl.scatter(abnormal[0,:], abnormal[1,:], c=\"blue\", s=100)\np4=pl.scatter(x_out[0,:], x_out[1,:], c=a, cmap=jet(), s=100)\n_=pl.legend((p1, p2, p3), [\"Training samples\", \"normal samples\", \"abnormal samples\"], loc=2)\n\n\n\nsubplot(122)\nc=pcolor(xx, yy, z)\ntitle(\"One-class classification output\")\n_=gray()\n_=contour(xx, yy, z, linewidths=1, colors='black', hold=True)\n_=colorbar(c)\n\n",
"MKL one-class classification will give you a bit more flexibility compared to normal classifications. The kernel weights are expected to be more or less similar here since the training data is not overly complicated or too easy, which means both the gaussian and polynomial kernel will be involved. If you don't know the nature of the training data and lot of features are invoved, you could easily use kernels with much different properties and benefit from their combination.\nReferences:\n[1] Soeren Sonnenburg, Gunnar Raetsch, Christin Schaefer, and Bernhard Schoelkopf. Large Scale Multiple Kernel Learning. Journal of Machine Learning Research, 7:1531-1565, July 2006.\n[2]F. R. Bach, G. R. G. Lanckriet, and M. I. Jordan. Multiple kernel learning, conic duality, and\nthe SMO algorithm. In C. E. Brodley, editor, Twenty-first international conference on Machine\nlearning. ACM, 2004\n[3] Kernel Methods for Object Recognition , Christoph H. Lampert"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
ghvn7777/ghvn7777.github.io
|
content/fluent_python/9_python_object.ipynb
|
apache-2.0
|
[
"得益于 Python 数据模型,自定义类型行为可以像内置类型那样自然。实现如此自然的行为,靠的不是继承,而是鸭子类型,我们只需要按照预定行为实现对象所需方法即可\n这一章我们定义自己的类,而且让类的行为跟真正的 Python 对象一样,这一章延续第一章,说明如何实现在很多 Python 类型中常见的特殊方法。\n本章包含以下话题:\n\n支持用于生成对象其他表示形式的内置函数(如 repr(), bytes() 等等)\n使用一个类方法实现备选构造方法\n扩展内置的 format() 函数和 str.format() 方法使用的格式微语言\n实现只读属性\n把对象变成可散列的,以便在集合中及作为 dict 的键使用\n利用 __slots__ 节省内存\n\n我们将开发一个二维欧几里得向量模型,这个过程中覆盖上面所有话题。这个过程中我们会讨论两个概念\n\n如何以及何时利用 @classmethod 和 @staticmethod 装饰器\nPython 的私有属性和受保护属性的用法,约定和局限\n\n对象表示形式\n每门面向对象的语言至少都有一种获取对象的字符串表示形式的标准方式。Python 提供了两种方式\nrepr(): 便于开发者理解的方式返回对象的字符串表示形式\nstr(): 便于用户理解的方式返回对象的字符串表示形式\n为了给对象提供其他的表现形式,还会用到两个特殊的方法, __bytes__ 和 __format__。__bytes__ 方法与 __str__方法类似:bytes() 函数调用它获取对象的字节序列表示形式。而 __format__ 方法会被内置的 format() 和 str.format() 调用。使用特殊的格式代码显示对象的字符串表示形式。\n注意:Python3 中 __repr__, __str__, __format__ 方法都必须返回 Unicode 字符串(str)类型。只有 __bytes__ 方法应该返回字节序列(bytes 类型)\n再谈向量类\n为了说明用于生成对象表示形式的众多方法,我们将使用一个 Vector2d 类,与第一章的类似。这几节会不断完善这个类,我们期望这个类行为如下所示:",
"v1 = Vector2d(3, 4)\nprint(v1.x, v1.y) # 可以直接通过属性访问\n\nx, y = v1 # 可以拆包成元祖\nx, y\n\nv1\n\nv1_clone = eval(repr(v1)) # repr 函数调用 Vector2d 实例,结果类似于构建实例的源码\nv1 == v1_clone # 支持 == 比较\n\nprint(v1) # 会调用 str 函数,对 Vector2d 来说,输出的是一个有序对\n\noctets = bytes(v1) # 调用 __bytes__ 方法,生成实例的二进制表示形式\noctets\n\nabs(v1) # 会调用 __abs__ 方法,返回 Vector2d 实例的模\n\nbool(v1), bool(Vector2d(0, 0)) # 会调用 __bool__ 方法,判断 Vector2d 的实例的向量长度\n\nfrom array import array\nimport math\n\nclass Vector2d:\n typecode = 'd' # 类属性,Vector2d 实例和字节序之间转换使用\n \n def __init__(self, x, y):\n self.x = float(x) # 转换成浮点数,尽早捕捉错误,防止传入不当参数\n self.y = float(y)\n \n def __iter__(self):\n return (i for i in (self.x, self.y)) # 将 Vector2d 变成可迭代对象,这样才可以拆包\n \n def __repr__(self):\n class_name = type(self).__name__\n # {!r} 获取各个分量的表示形式,然后插值,构成一个字符串。因为 Vector2d 是可迭代对象,所以用 *self 会把 x 和 y 分量提供给 format 函数\n return '{}({!r},{!r})'.format(class_name, *self)\n \n def __str__(self):\n return str(tuple(self))\n \n def __bytes__(self):\n # 我们使用 typecode 转换成字节序列然后返回\n return (bytes([ord(self.typecode)]) +\n bytes(array(self.typecode, self)))\n \n def __eq__(self, other):\n #为了快速比较所有分量,在操作数中构建元祖,对 Vector2d 实例来说,这样做还有问题,看下面的警告\n return tuple(self) == tuple(other) \n \n def __abs__(self):\n return math.hypot(self.x, self.y)\n \n def __bool__(self):\n return bool(abs(self))",
"上面的 __eq__ 方法,在两个操作数都是 Vector2d 的时候可用,不过拿 Vector2d 实例和其他具有相同数值的可迭代对象相比,结果也是 True(如 Vector2d(3, 4) == [3, 4])。这个行为可以视为特性,也可以视为缺陷在第 13 章运算符重载时候进一步讨论\n我们已经定义了许多基本方法,但是显然少了一个操作:使用 bytes() 函数生成的二进制重建 Vecotr2d 实例\n备选构造方法\n我们可以把 Vector2d 实例转成字节序列;同理,也应该能从字节序列转换成 Vector2d 实例。在标准库中探索一番之后,我们发现 array.array 有个类方法 .frombytes(2.91 章介绍过,从文件读取数据) 正好符合需求。下面为 Vector2d 定义一个同名的类方法",
"from array import array\nimport math\n\nclass Vector2d:\n typecode = 'd' \n \n def __init__(self, x, y):\n self.x = float(x) \n self.y = float(y)\n \n @classmethod # 类方法使用 @classmethod 装饰器\n def frombytes(cls, octets): # 不用传入 self 参数,相反,要通过 cls 传入类本身\n typecode = chr(octets[0]) #从第一个字节中读取 typecode\n # 用传入的 octets 字节序列创建一个 memoryview,然后使用 typecode 转换\n memv = memoryview(octets[1:]).cast(typecode) # 2.92 章介绍了 cast 方法,将一段内存转换成指定的类型,d 代表 float\n return cls(*memv) #拆包转换后的 memoryview,得到构造方法所需的一对参数\n\n def __iter__(self):\n return (i for i in (self.x, self.y)) \n \n def __repr__(self):\n class_name = type(self).__name__\n return '{}({!r},{!r})'.format(class_name, *self)\n \n def __str__(self):\n return str(tuple(self))\n \n def __bytes__(self):\n return (bytes([ord(self.typecode)]) +\n bytes(array(self.typecode, self)))\n \n def __eq__(self, other):\n return tuple(self) == tuple(other) \n \n def __abs__(self):\n return math.hypot(self.x, self.y)\n \n def __bool__(self):\n return bool(abs(self))\n\nv1 = Vector2d(3, 4)\noctets = bytes(v1)\nprint(octets)\nv2 = Vector2d.frombytes(octets)\nv2",
"我们上面用的 classmethod 装饰器是 Python 专用的,下面解释一下\nclassmethod 和 staticmethod\n我们来看一下 classmethod 装饰器,上面已经展示了它的用法,定义操作类,而不是操作实例的方法。classmethod 改变了调用方法的方式,因此类方法的第一个参数是类本身,而不是实例。classmethod 最常用的用途是定义备选构造方法。例如上面的 frombytes,注意,frombytes 最后一行使用 cls 参数构建了一个新实例,即 cls(*memv),按照约定,类方法的第一个参数为 cls(但不是强制的)\nstaticmethod 装饰器也会改变方法的调用方式,但是第一个参数不是特殊值。其实,静态方法就是普通的函数,只是碰巧在类的定义体中,而不是在模块层定义。下面对这两种装饰器行为做了对比:",
"class Demo:\n @classmethod\n def klassmeth(*args):\n return args\n \n @staticmethod\n def statmeth(*args):\n return args\n\nDemo.klassmeth()\n\nDemo.klassmeth('kaka')\n\nDemo.statmeth()\n\nDemo.statmeth('kaka')",
"不管怎么调用 class.klassmeth,它的第一个参数都是 Demo 类。而 Demo.statmeth 的行为和普通函数类似。一般情况下,都是使用 classmethod,staticmethod 不是特别有用\n格式化显示\n内置的 format() 函数和 str.format() 方法把各个类型的格式化方式委托给相应的 .__format__(format_spec) 方法。format_spec 是格式说明符,它是:\n\nformat(my_obj, format_spec) 的第二个参数\nstr.format() 方法的格式字符串,{} 里代换字段中冒号后面的部分",
"brl = 1 / 2.43\nbrl\n\nformat(brl, '0.4f')\n\n'1 BRL = {rate:0.2f} USD'.format(rate = brl)",
"'{0.mass:5.3e}' 这样的格式字符串其实包含两部分,冒号左边的 0.mass 在代换字段语法中是字段名,冒号后面的 5.3e 是格式说明符。如果对这些陌生的话,先学 format() 函数,掌握格式规范微语言,然后再阅读格式字符串语法(\"Format String Syntax\",https://docs.python.org/3/library/string.html#formatspec)。学习 str.format() 方法使用的 {:} 代换字段表示法(包含转换标志 !s, !r, !a)\n格式规范微语言为一些内置类型提供了专用的表示代码。例如,b 和 x 分别代表 二进制和十六进制的 int 类型。f 表示 float 类型,而 % 表示百分数形式",
"format(42, 'b')\n\nformat(2 / 3, '.1%')",
"格式规范微语言是可扩展的,因为各个类可以自行决定如何解释 format_spec 参数。例如,datetime 模块中的类,它们的 __format__ 方法使用的格式代码与 strftime() 函数一样。下面是内置的 format() 函数和 str.format() 方法的几个示例:",
"from datetime import datetime\nnow = datetime.now()\nformat(now, '%H:%M:%s')\n\n\"It's now {:%I:%M %p}\".format(now)",
"如果类没有定义 __format__ 方法,从 object 继承的方法会返回 str(my_object)。我们为 Vector2d 类定义了 __str__ 方法,因此可以这样:",
"v1 = Vector2d(3, 4)\nformat(v1)",
"然而,传入格式说明符,object.__format__ 方法会抛出 TypeError",
"format(v1, '.3f')",
"我们将实现自己的微语言解决这个问题。首先,假设用户提供的格式说明符是用于格式化向量中各个浮点数分量的。我们想达到的效果如下:",
"v1 = Vector2d(3, 4)\nformat(v1)\n\nformat(v1, '.2f')\n\nformat(v1, '3e')",
"实现这种输出的 __format__ 方法是:",
"def __format__(self, fmt_spec=''):\n components = (format(c, fmt_spec) for c in self)\n return '({}, {})'.format(*components)",
"下面要在微语言添加一个自定义格式的代码:如果格式说明以 'p' 为结尾,那么在极坐标中显示向量,即 <r, theta>,其中 r 是 模,theta 是弧度,其他部分('p' 之前的部分像往常一样解释)\n注意自定义的格式代码不要和已有的重复,整数使用的有 'bcdoxXn', 浮点数使用的有 'eEfFgGn%', 字符串有的是 's'。所以我们选的极坐标代码是 'p',各个类都有自己的方式解释格式代码,自定义格式代码中重复使用代码字母不会出错,但是可能会让用户迷惑。\n对于极坐标来说,我们已经定义了计算模的 __abs__ 方法,因此还要定义一个简单的 angle 方法,使用 math.atan2() 函数计算角度。angle 方法的代码如下:",
"def angle(self):\n return math.atan2(self.y, self.x)",
"这样方便增强 __format__ 方法,现在我们可以让其计算极坐标:",
"def __format__(self, fmt_spec=''):\n if fmt_spec.endswith('p'):\n fmt_spec = fmt_spec[:-1] # 删除 p 后缀\n coords = (abs(self), self.angle()) # 构建元组,表示极坐标\n outer_fmt = '<{}, {}>' \n else:\n coords = self\n outer_fmt = '({}, {})'\n components = (format(c, fmt_spec) for c in coords)\n return outer_fmt.format(*components)",
"可散列的 Vector2d\n按照定义,我们现在的 Vector2d 是不可散列的,因此不能放入集合 (set) 中:",
"v1 = Vector2d(3, 4)\nhash(v1)",
"为了将其设成可散列的,必须使用 __hash__ 方法(还需要 __eq__ 方法,前面实现了)。此外,还要让向量不可变。\n目前我们可以为分量赋新值,如 v1.x = 7,我们应该让其无法赋值。",
"class Vector2d:\n typecode = 'd'\n \n def __init__(self, x, y):\n self.__x = float(x) # 有两个前导下划线,或一个,把属性标记为私有的\n self.__y = float(y)\n \n @property # property 把读值方法标记为特性\n def x(self): # 读值方法与公开属性名一样,x\n return self.__x\n @property\n def y(self):\n return self.__y\n \n def __iter__(self):\n return (i for i in (self.x, self.y))\n \n # ...下面省略了。",
"注意,我们让这些向量不可变是有原因的,因为这样才能实现 __hash__ 方法。这个方法应该返回一个整数,理想情况下还要考虑对象属性的散列值(__eq__ 方法也要使用),因为相等的对象应该具有相同的散列值。根据官方文档,最好使用 异或(^)来混合各个分量的散列值",
"def __hash__(self):\n return hash(self.x) ^ hash(self.y)",
"如果创建可散列的类型,不一定实现特性,也不一定要保护实例属性。只需要正确的实现 __hash__ 和 __eq__ 方法即可。但是,实例的散列值绝不应该变化,因此我们借机提到了只读属性。\n如果定义的类型有标量数值,可能还要实现 __int__ 和 __float__ 方法(分别被 int() 和 float() 构造函数调用),以便在某些情况下用于强制类型转换,此外,还有用于支持内置的 complex() 构造函数的 __complex__ 方法。\n下面是完整的代码:",
"from array import array\nimport math\n\nclass Vector2d:\n typecode = 'd' \n \n def __init__(self, x, y):\n self.__x = float(x) \n self.__y = float(y)\n\n @property # property 把读值方法标记为特性\n def x(self): # 读值方法与公开属性名一样,x\n return self.__x\n \n @property\n def y(self):\n return self.__y\n \n def __iter__(self):\n return (i for i in (self.x, self.y)) \n \n def __repr__(self):\n class_name = type(self).__name__\n return '{}({!r},{!r})'.format(class_name, *self)\n \n def __str__(self):\n return str(tuple(self))\n \n def __bytes__(self):\n return (bytes([ord(self.typecode)]) +\n bytes(array(self.typecode, self)))\n \n def __eq__(self, other):\n return tuple(self) == tuple(other) \n \n def __hash__(self):\n return hash(self.x) ^ hash(self.y)\n\n def __abs__(self):\n return math.hypot(self.x, self.y) # 返回欧几里德范数 sqrt(x*x + y*y)。\n \n def __bool__(self):\n return bool(abs(self))\n\n def angle(self):\n return math.atan2(self.y, self.x)\n \n def __format__(self, fmt_spec=''):\n if fmt_spec.endswith('p'):\n fmt_spec = fmt_spec[:-1] # 删除 p 后缀\n coords = (abs(self), self.angle()) # 构建元组,表示极坐标\n outer_fmt = '<{}, {}>' \n else:\n coords = self\n outer_fmt = '({}, {})'\n components = (format(c, fmt_spec) for c in coords)\n return outer_fmt.format(*components)\n\n @classmethod # 类方法使用 @classmethod 装饰器\n def frombytes(cls, octets): # 不用传入 self 参数,相反,要通过 cls 传入类本身\n typecode = chr(octets[0]) #从第一个字节中读取 typecode\n # 用传入的 octets 字节序列创建一个 memoryview,然后使用 typecode 转换\n memv = memoryview(octets[1:]).cast(typecode) # 2.92 章介绍了 cast 方法,将一段内存转换成指定的类型,d 代表 float\n return cls(*memv) #拆包转换后的 memoryview,得到构造方法所需的一对参数",
"测试:",
"v1 = Vector2d(3, 4)\nprint(v1.x, v1.y)\n\nx, y = v1\nx, y\n\nv1\n\nv1_clone = eval(repr(v1))\nv1 == v1_clone\n\nprint(v1)\n\noctets = bytes(v1)\noctets\n\nabs(v1)\n\nbool(v1), bool(Vector2d(0, 0))\n\nv1_clone = Vector2d.frombytes(bytes(v1))\nv1_clone\n\nv1 == v1_clone\n\nformat(v1)\n\nformat(v1, '.2f')\n\nformat(v1, '.3e')\n\nVector2d(0, 0).angle()\n\nVector2d(1, 0).angle()\n\nepsilon = 10 ** -8\nabs(Vector2d(0, 1).angle() - math.pi / 2) < epsilon\n\nabs(Vector2d(1, 1).angle() - math.pi / 4) < epsilon\n\nformat(Vector2d(1, 1), 'p')\n\nformat(Vector2d(1, 1), '.3ep')\n\nformat(Vector2d(1, 1), '.5fp')\n\nv1.x, v1.y\n\nv1.x = 123\n\nv1 = Vector2d(3, 4)\nv2 = Vector2d(3.1, 4.2)\nhash(v1), hash(v2)\n\nlen(set([v1, v2]))",
"Python 的私有属性和 “受保护” 的属性\nPython 不能像 Java 一样使用 private 修饰符创建私有属性,但是 Python 有个简单的机制,能避免子类意外覆盖 “私有” 属性\n举个例子,如果有人编写了一个 Dog 类,有一个 mood 实例属性,但是没有开放,你创建了 Dog 子类,你在毫不知情的情况下又创建了 mood 的实例属性,那么会在继承方法中会把 Dog 类的 mood 属性覆盖掉。这是难以调试的问题\n为了避免这种情况,如果以 __mood 的形式(两个前导下划线,尾部没有或最多有一个前导下划线)命名实例属性,Python 会把属性名存到实例的 __dict__ 属性中,而且会在前面加上一个下划线和类名。因此,对于 Dog 类来说,__mood 会变成 _Dog__mood,对于 Beagle 类来说,会变成 _Beagle__mood。这个语言特性叫名称改写",
"v1 = Vector2d(3, 4)\nv1.__dict__",
"名称改写是一种安全措施,不能保证万无一失,它的目的是避免意外访问,不能防止故意做错事。\n但不是所有 Python 程序员都喜欢这个功能,他们不喜欢两个下划线的这种特别不对称的写法,所以约定使用一个下划线编写受保护的属性(例如 self.x)。Python 不会对单下划线进行特殊处理,不过这是很多 Python 程序员严格遵守的约定,他们不会在外部访问这种属性。\nPython 文档的某些角落将使用一个下划线前缀标记为受保护的属性。\n总之,Vector2d 的分量都是 “私有的”,而 Vector2d 实例都是 “不可变” 的。这里用了两对引号是因为不能真正实现私有和不可变\n使用 __slots__ 类属性节省空间\n默认情况下,Python 在各个实例名为 __dict__ 字典里存储实例属性,如第三章所说,为了使用底层的散列表提升访问速度,字典会消耗大量内存,通过 __slots__ 类属性,能节省大量内存,方法是让解释器在元祖中存储实例属性,而不用字典\n\n继承自超类的 __slots__ 属性没有效果。Python 只会使用各个类中定义的 __slots__ 属性。\n\n定义 __slots__ 的方式是,创建一个类属性,使用 __slots__ 这个名字,并把它的值设为一个字符串构成的可迭代对象,其中各个元素表示各个实例属性。我喜欢使用元组,因为这样定义的 __slots__ 所含的信息不会变化,如下所示:",
"class Vector2d:\n __slots__ = ('__x', '__y')\n # 下面是各个方法,省略",
"在类中定义 __slots__ 属性的目的是告诉解释器:这个类中的所有实例属性都在这了,这样,Python 会在各个实例中使用类似元祖的结构存储实例变量,从而避免使用消耗内存的 __dict__ 属性。如果有数百万个实例同时活动,这样能大量节省内存\n\n如果要处理数百万个数值对象,应该使用 Numpy 数组,它能高效使用内存,而且提供了高度优化的数值处理函数,其中很多都一次操作整个数组\n\n然而,节省的内存也可能被再次吃掉,如果把 __dict__ 这个名称添加到 __slots__ 中,实例会在元祖中保存各个实例的属性。此外还支持动态创建属性,这些属性存储在常规的 __dict__ 中。当然,把 __dict__ 加到 __slots__ 中可能完全违背了初衷,这取决于各个实例的静态属性和动态属性的数量及其用法。粗心的优化甚至比提早优化还糟糕\n此外,还有一个实例属性值得注意,__weakref__ 属性,为了让对象支持弱引用,必须有这个属性,用户定义的类中默认就有 __weakref__ 属性。可是如果类中定义了 __slots__ 属性,而且想把实例作为弱引用的目标,就要把 __weakref__ 添加到 __slots__ 中。\n综上,__slots__ 属性有些需要注意的地方,而且不能滥用。不能使用它来限制用户能赋值的属性。处理列表中数据时,__slots__ 属性最有用,例如模式固定的数据库记录,大型数据集。然而,如果你经常处理大量数据,一定要看一下 Numpy,此外 Pandas 也值得了解\n__slots__ 的问题\n总之,如果使用得当,__slots__ 能显著节省内存,不过有几点需要注意。\n\n每个子类都要定义 __slots__ 属性,因为解释器会忽略继承的 __slots__ 属性\n每个实例只能拥有 __slots__ 列出来的属性,除非把 __dict__ 加入 __slots__ 中(这样做失去了节省内存的功效)\n如果不把 __weakref__ 加入 __slots__,实例就不能作为弱引用的目标\n\n如果你的程序不用处理百万个实例,或许不值得费劲去创建不寻常的类,那就禁止它创建动态属性或者不支持弱引用。与其它优化措施一样,仅当权衡当下的需求并仔细搜集资料后证明确实有必要使用,才使用 __slots__ 属性\n覆盖类属性\nPython 有一个很独特的特性,类属性可用于为实例属性提供默认值。Vector2d 中有个 typecode 类属性,__bytes__ 方法两次用到了它,而且都故意使用 self.typecode 读取它的值,因为 Vector2d 实例本身没有 typecode 属性,所以 self.typecode 默认获取的是 Vector2d.typecode 的值\n但是,如果为不存在的实例属性赋值,会新建实例属性。假如我们为 typecode 实例属性赋值,那么同名类属性不受影响。然而,自此以后,实例读取的 self.typecode 是实例属性 typecode,也就是把同名类属性遮盖了。借助这一特性,可以为各个实例的 typecode 属性定制不同的值。\nVector2d.typecode 属性默认值是 'd',即转换成字节序列时使用 8 字节双精度浮点数表示各个分量。如果在转换之前把 typecode 属性改成 'f',那么使用 4 字节单精度浮点数表示各个分量。",
"v1 = Vector2d(1.1, 2.2)\ndumpd = bytes(v1)\ndumpd\n\nlen(dumpd)\n\nv1.typecode = 'f'\ndumpf = bytes(v1)\ndumpf\n\nlen(dumpf)",
"这就是我们为什么要在字节序列之前加上 typecode 的值的原因:为了支持不同格式\n如果想修改类属性的值,必须直接在类上修改,不能通过实例修改。如果想修改所有实例(没有 typecode 实例变量)的 typecode 属性的默认值,可以这么做:",
"Vector2d.typecode = 'f'",
"然而,有种修改方法更符合 Python 风格,而且效果更持久,也更有针对性。类属性是公开的,因此会被子类继承,于是经常会创建一个子类,只用于定制类的属性。Django 基于类的视图就大量使用了这种技术。就像下面这样:",
"class ShortVector2d(Vector2d):\n typecode = 'f'\n\nsv = ShortVector2d(1 / 11, 1 / 27)\nsv # 查看 sv 的 repr 形式\n\nlen(bytes(sv))",
"这也说明了我们在 Vector2d.__repr__ 方法中为什么没有硬编码 class_name 的值,而是使用 type(self).__name__ 获取。因为如果硬编码,子类继承的时候还要重写 __repr__ 方法,这样从实例读取类名,__repr__ 方法就可以放心的继承\n至此,我们通过一个简单的类说明了如何利用数据模型处理 Python 的其他功能:提供不同的对象表示形式,实现自定义格式代码,公开只读属性,以及通过 hash() 函数支持集合和映射"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
ES-DOC/esdoc-jupyterhub
|
notebooks/mohc/cmip6/models/hadgem3-gc31-lm/land.ipynb
|
gpl-3.0
|
[
"ES-DOC CMIP6 Model Properties - Land\nMIP Era: CMIP6\nInstitute: MOHC\nSource ID: HADGEM3-GC31-LM\nTopic: Land\nSub-Topics: Soil, Snow, Vegetation, Energy Balance, Carbon Cycle, Nitrogen Cycle, River Routing, Lakes. \nProperties: 154 (96 required)\nModel descriptions: Model description details\nInitialized From: -- \nNotebook Help: Goto notebook help page\nNotebook Initialised: 2018-02-15 16:54:14\nDocument Setup\nIMPORTANT: to be executed each time you run the notebook",
"# DO NOT EDIT ! \nfrom pyesdoc.ipython.model_topic import NotebookOutput \n\n# DO NOT EDIT ! \nDOC = NotebookOutput('cmip6', 'mohc', 'hadgem3-gc31-lm', 'land')",
"Document Authors\nSet document authors",
"# Set as follows: DOC.set_author(\"name\", \"email\") \n# TODO - please enter value(s)",
"Document Contributors\nSpecify document contributors",
"# Set as follows: DOC.set_contributor(\"name\", \"email\") \n# TODO - please enter value(s)",
"Document Publication\nSpecify document publication status",
"# Set publication status: \n# 0=do not publish, 1=publish. \nDOC.set_publication_status(0)",
"Document Table of Contents\n1. Key Properties\n2. Key Properties --> Conservation Properties\n3. Key Properties --> Timestepping Framework\n4. Key Properties --> Software Properties\n5. Grid\n6. Grid --> Horizontal\n7. Grid --> Vertical\n8. Soil\n9. Soil --> Soil Map\n10. Soil --> Snow Free Albedo\n11. Soil --> Hydrology\n12. Soil --> Hydrology --> Freezing\n13. Soil --> Hydrology --> Drainage\n14. Soil --> Heat Treatment\n15. Snow\n16. Snow --> Snow Albedo\n17. Vegetation\n18. Energy Balance\n19. Carbon Cycle\n20. Carbon Cycle --> Vegetation\n21. Carbon Cycle --> Vegetation --> Photosynthesis\n22. Carbon Cycle --> Vegetation --> Autotrophic Respiration\n23. Carbon Cycle --> Vegetation --> Allocation\n24. Carbon Cycle --> Vegetation --> Phenology\n25. Carbon Cycle --> Vegetation --> Mortality\n26. Carbon Cycle --> Litter\n27. Carbon Cycle --> Soil\n28. Carbon Cycle --> Permafrost Carbon\n29. Nitrogen Cycle\n30. River Routing\n31. River Routing --> Oceanic Discharge\n32. Lakes\n33. Lakes --> Method\n34. Lakes --> Wetlands \n1. Key Properties\nLand surface key properties\n1.1. Model Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of land surface model.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.model_overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.2. Model Name\nIs Required: TRUE Type: STRING Cardinality: 1.1\nName of land surface model code (e.g. MOSES2.2)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.model_name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.3. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral description of the processes modelled (e.g. dymanic vegation, prognostic albedo, etc.)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.4. Land Atmosphere Flux Exchanges\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nFluxes exchanged with the atmopshere.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.land_atmosphere_flux_exchanges') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"water\" \n# \"energy\" \n# \"carbon\" \n# \"nitrogen\" \n# \"phospherous\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"1.5. Atmospheric Coupling Treatment\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the treatment of land surface coupling with the Atmosphere model component, which may be different for different quantities (e.g. dust: semi-implicit, water vapour: explicit)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.atmospheric_coupling_treatment') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.6. Land Cover\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nTypes of land cover defined in the land surface model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.land_cover') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"bare soil\" \n# \"urban\" \n# \"lake\" \n# \"land ice\" \n# \"lake ice\" \n# \"vegetated\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"1.7. Land Cover Change\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe how land cover change is managed (e.g. the use of net or gross transitions)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.land_cover_change') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.8. Tiling\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general tiling procedure used in the land surface (if any). Include treatment of physiography, land/sea, (dynamic) vegetation coverage and orography/roughness",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"2. Key Properties --> Conservation Properties\nTODO\n2.1. Energy\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe if/how energy is conserved globally and to what level (e.g. within X [units]/year)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.conservation_properties.energy') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"2.2. Water\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe if/how water is conserved globally and to what level (e.g. within X [units]/year)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.conservation_properties.water') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"2.3. Carbon\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe if/how carbon is conserved globally and to what level (e.g. within X [units]/year)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.conservation_properties.carbon') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"3. Key Properties --> Timestepping Framework\nTODO\n3.1. Timestep Dependent On Atmosphere\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs a time step dependent on the frequency of atmosphere coupling?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.timestepping_framework.timestep_dependent_on_atmosphere') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"3.2. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nOverall timestep of land surface model (i.e. time between calls)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.timestepping_framework.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"3.3. Timestepping Method\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral description of time stepping method and associated time step(s)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.timestepping_framework.timestepping_method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"4. Key Properties --> Software Properties\nSoftware properties of land surface code\n4.1. Repository\nIs Required: FALSE Type: STRING Cardinality: 0.1\nLocation of code for this component.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.software_properties.repository') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"4.2. Code Version\nIs Required: FALSE Type: STRING Cardinality: 0.1\nCode version identifier.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.software_properties.code_version') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"4.3. Code Languages\nIs Required: FALSE Type: STRING Cardinality: 0.N\nCode language(s).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.key_properties.software_properties.code_languages') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"5. Grid\nLand surface grid\n5.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of the grid in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.grid.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"6. Grid --> Horizontal\nThe horizontal grid in the land surface\n6.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general structure of the horizontal grid (not including any tiling)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.grid.horizontal.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"6.2. Matches Atmosphere Grid\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nDoes the horizontal grid match the atmosphere?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.grid.horizontal.matches_atmosphere_grid') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"7. Grid --> Vertical\nThe vertical grid in the soil\n7.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general structure of the vertical grid in the soil (not including any tiling)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.grid.vertical.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"7.2. Total Depth\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe total depth of the soil (in metres)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.grid.vertical.total_depth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"8. Soil\nLand surface soil\n8.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of soil in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"8.2. Heat Water Coupling\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the coupling between heat and water in the soil",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_water_coupling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"8.3. Number Of Soil layers\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of soil layers",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.number_of_soil layers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"8.4. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the soil scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9. Soil --> Soil Map\nKey properties of the land surface soil map\n9.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral description of soil map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.2. Structure\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil structure map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.structure') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.3. Texture\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil texture map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.texture') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.4. Organic Matter\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil organic matter map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.organic_matter') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.5. Albedo\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil albedo map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.albedo') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.6. Water Table\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil water table map, if any",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.water_table') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9.7. Continuously Varying Soil Depth\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nDoes the soil properties vary continuously with depth?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.continuously_varying_soil_depth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"9.8. Soil Depth\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil depth map",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.soil_map.soil_depth') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"10. Soil --> Snow Free Albedo\nTODO\n10.1. Prognostic\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs snow free albedo prognostic?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.snow_free_albedo.prognostic') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"10.2. Functions\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nIf prognostic, describe the dependancies on snow free albedo calculations",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.snow_free_albedo.functions') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"vegetation type\" \n# \"soil humidity\" \n# \"vegetation state\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"10.3. Direct Diffuse\nIs Required: FALSE Type: ENUM Cardinality: 0.1\nIf prognostic, describe the distinction between direct and diffuse albedo",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.snow_free_albedo.direct_diffuse') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"distinction between direct and diffuse albedo\" \n# \"no distinction between direct and diffuse albedo\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"10.4. Number Of Wavelength Bands\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nIf prognostic, enter the number of wavelength bands used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.snow_free_albedo.number_of_wavelength_bands') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"11. Soil --> Hydrology\nKey properties of the land surface soil hydrology\n11.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral description of the soil hydrological model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.2. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of river soil hydrology in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"11.3. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil hydrology tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.4. Vertical Discretisation\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the typical vertical discretisation",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.vertical_discretisation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.5. Number Of Ground Water Layers\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of soil layers that may contain water",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.number_of_ground_water_layers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"11.6. Lateral Connectivity\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nDescribe the lateral connectivity between tiles",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.lateral_connectivity') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"perfect connectivity\" \n# \"Darcian flow\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"11.7. Method\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nThe hydrological dynamics scheme in the land surface model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Bucket\" \n# \"Force-restore\" \n# \"Choisnel\" \n# \"Explicit diffusion\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"12. Soil --> Hydrology --> Freezing\nTODO\n12.1. Number Of Ground Ice Layers\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nHow many soil layers may contain ground ice",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.freezing.number_of_ground_ice_layers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"12.2. Ice Storage Method\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the method of ice storage",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.freezing.ice_storage_method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"12.3. Permafrost\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the treatment of permafrost, if any, within the land surface scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.freezing.permafrost') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"13. Soil --> Hydrology --> Drainage\nTODO\n13.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral describe how drainage is included in the land surface scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.drainage.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"13.2. Types\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nDifferent types of runoff represented by the land surface model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.hydrology.drainage.types') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Gravity drainage\" \n# \"Horton mechanism\" \n# \"topmodel-based\" \n# \"Dunne mechanism\" \n# \"Lateral subsurface flow\" \n# \"Baseflow from groundwater\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"14. Soil --> Heat Treatment\nTODO\n14.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral description of how heat treatment properties are defined",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"14.2. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of soil heat scheme in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"14.3. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the soil heat treatment tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"14.4. Vertical Discretisation\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the typical vertical discretisation",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.vertical_discretisation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"14.5. Heat Storage\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nSpecify the method of heat storage",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.heat_storage') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Force-restore\" \n# \"Explicit diffusion\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"14.6. Processes\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nDescribe processes included in the treatment of soil heat",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.soil.heat_treatment.processes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"soil moisture freeze-thaw\" \n# \"coupling with snow temperature\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15. Snow\nLand surface snow\n15.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of snow in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"15.2. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the snow tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"15.3. Number Of Snow Layers\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of snow levels used in the land surface scheme/model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.number_of_snow_layers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"15.4. Density\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescription of the treatment of snow density",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.density') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"constant\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.5. Water Equivalent\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescription of the treatment of the snow water equivalent",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.water_equivalent') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.6. Heat Content\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescription of the treatment of the heat content of snow",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.heat_content') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.7. Temperature\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescription of the treatment of snow temperature",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.temperature') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.8. Liquid Water Content\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescription of the treatment of snow liquid water",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.liquid_water_content') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.9. Snow Cover Fractions\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nSpecify cover fractions used in the surface snow scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.snow_cover_fractions') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"ground snow fraction\" \n# \"vegetation snow fraction\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.10. Processes\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nSnow related processes in the land surface scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.processes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"snow interception\" \n# \"snow melting\" \n# \"snow freezing\" \n# \"blowing snow\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"15.11. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the snow scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"16. Snow --> Snow Albedo\nTODO\n16.1. Type\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescribe the treatment of snow-covered land albedo",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.snow_albedo.type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"prescribed\" \n# \"constant\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"16.2. Functions\nIs Required: FALSE Type: ENUM Cardinality: 0.N\n*If prognostic, *",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.snow.snow_albedo.functions') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"vegetation type\" \n# \"snow age\" \n# \"snow density\" \n# \"snow grain type\" \n# \"aerosol deposition\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17. Vegetation\nLand surface vegetation\n17.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of vegetation in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.2. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of vegetation scheme in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"17.3. Dynamic Vegetation\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs there dynamic evolution of vegetation?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.dynamic_vegetation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"17.4. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the vegetation tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.5. Vegetation Representation\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nVegetation classification used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.vegetation_representation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"vegetation types\" \n# \"biome types\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.6. Vegetation Types\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nList of vegetation types in the classification, if any",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.vegetation_types') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"broadleaf tree\" \n# \"needleleaf tree\" \n# \"C3 grass\" \n# \"C4 grass\" \n# \"vegetated\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.7. Biome Types\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nList of biome types in the classification, if any",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.biome_types') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"evergreen needleleaf forest\" \n# \"evergreen broadleaf forest\" \n# \"deciduous needleleaf forest\" \n# \"deciduous broadleaf forest\" \n# \"mixed forest\" \n# \"woodland\" \n# \"wooded grassland\" \n# \"closed shrubland\" \n# \"opne shrubland\" \n# \"grassland\" \n# \"cropland\" \n# \"wetlands\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.8. Vegetation Time Variation\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nHow the vegetation fractions in each tile are varying with time",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.vegetation_time_variation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"fixed (not varying)\" \n# \"prescribed (varying from files)\" \n# \"dynamical (varying from simulation)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.9. Vegetation Map\nIs Required: FALSE Type: STRING Cardinality: 0.1\nIf vegetation fractions are not dynamically updated , describe the vegetation map used (common name and reference, if possible)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.vegetation_map') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.10. Interception\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs vegetation interception of rainwater represented?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.interception') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"17.11. Phenology\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nTreatment of vegetation phenology",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.phenology') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic (vegetation map)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.12. Phenology Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of the treatment of vegetation phenology",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.phenology_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.13. Leaf Area Index\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nTreatment of vegetation leaf area index",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.leaf_area_index') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prescribed\" \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.14. Leaf Area Index Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of the treatment of leaf area index",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.leaf_area_index_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.15. Biomass\nIs Required: TRUE Type: ENUM Cardinality: 1.1\n*Treatment of vegetation biomass *",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.biomass') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.16. Biomass Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of the treatment of vegetation biomass",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.biomass_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.17. Biogeography\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nTreatment of vegetation biogeography",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.biogeography') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.18. Biogeography Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of the treatment of vegetation biogeography",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.biogeography_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.19. Stomatal Resistance\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nSpecify what the vegetation stomatal resistance depends on",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.stomatal_resistance') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"light\" \n# \"temperature\" \n# \"water availability\" \n# \"CO2\" \n# \"O3\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"17.20. Stomatal Resistance Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of the treatment of vegetation stomatal resistance",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.stomatal_resistance_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"17.21. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the vegetation scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.vegetation.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"18. Energy Balance\nLand surface energy balance\n18.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of energy balance in land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.energy_balance.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"18.2. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the energy balance tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.energy_balance.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"18.3. Number Of Surface Temperatures\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe maximum number of distinct surface temperatures in a grid cell (for example, each subgrid tile may have its own temperature)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.energy_balance.number_of_surface_temperatures') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"18.4. Evaporation\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nSpecify the formulation method for land surface evaporation, from soil and vegetation",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.energy_balance.evaporation') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"alpha\" \n# \"beta\" \n# \"combined\" \n# \"Monteith potential evaporation\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"18.5. Processes\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nDescribe which processes are included in the energy balance scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.energy_balance.processes') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"transpiration\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"19. Carbon Cycle\nLand surface carbon cycle\n19.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of carbon cycle in land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"19.2. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the carbon cycle tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"19.3. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of carbon cycle in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"19.4. Anthropogenic Carbon\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nDescribe the treament of the anthropogenic carbon pool",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.anthropogenic_carbon') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"grand slam protocol\" \n# \"residence time\" \n# \"decay time\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"19.5. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the carbon scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"20. Carbon Cycle --> Vegetation\nTODO\n20.1. Number Of Carbon Pools\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nEnter the number of carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.number_of_carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"20.2. Carbon Pools\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"20.3. Forest Stand Dynamics\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the treatment of forest stand dyanmics",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.forest_stand_dynamics') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"21. Carbon Cycle --> Vegetation --> Photosynthesis\nTODO\n21.1. Method\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the general method used for photosynthesis (e.g. type of photosynthesis, distinction between C3 and C4 grasses, Nitrogen depencence, etc.)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.photosynthesis.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"22. Carbon Cycle --> Vegetation --> Autotrophic Respiration\nTODO\n22.1. Maintainance Respiration\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the general method used for maintainence respiration",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.maintainance_respiration') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"22.2. Growth Respiration\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the general method used for growth respiration",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.growth_respiration') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"23. Carbon Cycle --> Vegetation --> Allocation\nTODO\n23.1. Method\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general principle behind the allocation scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"23.2. Allocation Bins\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nSpecify distinct carbon bins used in allocation",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_bins') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"leaves + stems + roots\" \n# \"leaves + stems + roots (leafy + woody)\" \n# \"leaves + fine roots + coarse roots + stems\" \n# \"whole plant (no distinction)\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"23.3. Allocation Fractions\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescribe how the fractions of allocation are calculated",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_fractions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"fixed\" \n# \"function of vegetation type\" \n# \"function of plant allometry\" \n# \"explicitly calculated\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"24. Carbon Cycle --> Vegetation --> Phenology\nTODO\n24.1. Method\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general principle behind the phenology scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.phenology.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"25. Carbon Cycle --> Vegetation --> Mortality\nTODO\n25.1. Method\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general principle behind the mortality scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.vegetation.mortality.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"26. Carbon Cycle --> Litter\nTODO\n26.1. Number Of Carbon Pools\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nEnter the number of carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.litter.number_of_carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"26.2. Carbon Pools\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.litter.carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"26.3. Decomposition\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the decomposition methods used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.litter.decomposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"26.4. Method\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the general method used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.litter.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"27. Carbon Cycle --> Soil\nTODO\n27.1. Number Of Carbon Pools\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nEnter the number of carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.soil.number_of_carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"27.2. Carbon Pools\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the carbon pools used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.soil.carbon_pools') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"27.3. Decomposition\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the decomposition methods used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.soil.decomposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"27.4. Method\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the general method used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.soil.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"28. Carbon Cycle --> Permafrost Carbon\nTODO\n28.1. Is Permafrost Included\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs permafrost included?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.is_permafrost_included') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"28.2. Emitted Greenhouse Gases\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the GHGs emitted",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.emitted_greenhouse_gases') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"28.3. Decomposition\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList the decomposition methods used",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.decomposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"28.4. Impact On Soil Properties\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the impact of permafrost on soil properties",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.impact_on_soil_properties') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"29. Nitrogen Cycle\nLand surface nitrogen cycle\n29.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of the nitrogen cycle in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.nitrogen_cycle.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"29.2. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the notrogen cycle tiling, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.nitrogen_cycle.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"29.3. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of nitrogen cycle in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.nitrogen_cycle.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"29.4. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the nitrogen scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.nitrogen_cycle.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30. River Routing\nLand surface river routing\n30.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of river routing in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30.2. Tiling\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the river routing, if any.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.tiling') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30.3. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of river routing scheme in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"30.4. Grid Inherited From Land Surface\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs the grid inherited from land surface?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.grid_inherited_from_land_surface') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"30.5. Grid Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nGeneral description of grid, if not inherited from land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.grid_description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30.6. Number Of Reservoirs\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nEnter the number of reservoirs",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.number_of_reservoirs') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"30.7. Water Re Evaporation\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nTODO",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.water_re_evaporation') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"flood plains\" \n# \"irrigation\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"30.8. Coupled To Atmosphere\nIs Required: FALSE Type: BOOLEAN Cardinality: 0.1\nIs river routing coupled to the atmosphere model component?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.coupled_to_atmosphere') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"30.9. Coupled To Land\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the coupling between land and rivers",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.coupled_to_land') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30.10. Quantities Exchanged With Atmosphere\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nIf couple to atmosphere, which quantities are exchanged between river routing and the atmosphere model components?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.quantities_exchanged_with_atmosphere') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"heat\" \n# \"water\" \n# \"tracers\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"30.11. Basin Flow Direction Map\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nWhat type of basin flow direction map is being used?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.basin_flow_direction_map') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"present day\" \n# \"adapted for other periods\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"30.12. Flooding\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the representation of flooding, if any",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.flooding') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"30.13. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the river routing",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"31. River Routing --> Oceanic Discharge\nTODO\n31.1. Discharge Type\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nSpecify how rivers are discharged to the ocean",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.oceanic_discharge.discharge_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"direct (large rivers)\" \n# \"diffuse\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"31.2. Quantities Transported\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nQuantities that are exchanged from river-routing to the ocean model component",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.river_routing.oceanic_discharge.quantities_transported') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"heat\" \n# \"water\" \n# \"tracers\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"32. Lakes\nLand surface lakes\n32.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of lakes in the land surface",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"32.2. Coupling With Rivers\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nAre lakes coupled to the river routing model component?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.coupling_with_rivers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"32.3. Time Step\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTime step of lake scheme in seconds",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.time_step') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"32.4. Quantities Exchanged With Rivers\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nIf coupling with rivers, which quantities are exchanged between the lakes and rivers",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.quantities_exchanged_with_rivers') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"heat\" \n# \"water\" \n# \"tracers\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"32.5. Vertical Grid\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the vertical grid of lakes",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.vertical_grid') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"32.6. Prognostic Variables\nIs Required: TRUE Type: STRING Cardinality: 1.1\nList the prognostic variables of the lake scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.prognostic_variables') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"33. Lakes --> Method\nTODO\n33.1. Ice Treatment\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs lake ice included?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.method.ice_treatment') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"33.2. Albedo\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nDescribe the treatment of lake albedo",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.method.albedo') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"prognostic\" \n# \"diagnostic\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"33.3. Dynamics\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nWhich dynamics of lakes are treated? horizontal, vertical, etc.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.method.dynamics') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"No lake dynamics\" \n# \"vertical\" \n# \"horizontal\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"33.4. Dynamic Lake Extent\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs a dynamic lake extent scheme included?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.method.dynamic_lake_extent') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"33.5. Endorheic Basins\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nBasins not flowing to ocean included?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.method.endorheic_basins') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"34. Lakes --> Wetlands\nTODO\n34.1. Description\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe the treatment of wetlands, if any",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.land.lakes.wetlands.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"©2017 ES-DOC"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
anhiga/poliastro
|
docs/source/examples/Going to Mars with Python using poliastro.ipynb
|
mit
|
[
"Going to Mars with Python using poliastro\n<img src=\"http://docs.poliastro.space/en/latest/_images/logo_text.png\" />\nThis is an example on how to use poliastro, a little library I've been working on to use in my Astrodynamics lessons. It features conversion between classical orbital elements and position vectors, propagation of Keplerian orbits, initial orbit determination using the solution of the Lambert's problem and orbit plotting.\nIn this example we're going to draw the trajectory of the mission Mars Science Laboratory (MSL), which carried the rover Curiosity to the surface of Mars in a period of something less than 9 months.\nNote: This is a very simplistic analysis which doesn't take into account many important factors of the mission, but can serve as an starting point for more serious computations (and as a side effect produces a beautiful plot at the end).\n<div class=\"alert alert-info\">An earlier version of this notebook allowed for more flexibility and interactivity, but was considerably more complex. Future versions of poliastro and plotly might bring back part of that functionality, depending on user feedback. You can still download the older version <a href=\"https://github.com/poliastro/poliastro/blob/0.7.x/docs/source/examples/Going%20to%20Mars%20with%20Python%20using%20poliastro.ipynb\">here</a>.</div>\n\nFirst of all, we import the necessary modules. Apart from poliastro we will make use of astropy to deal with physical units and time definitions and jplephem to compute the positions and velocities of the planets.",
"import numpy as np\n\nimport astropy.units as u\nfrom astropy import time\n\nfrom poliastro import iod\nfrom poliastro.bodies import Sun\nfrom poliastro.twobody import Orbit\n\nfrom poliastro.util import time_range",
"We need a binary file from NASA called SPICE kernel to compute the position and velocities of the planets. Astropy downloads it for us:",
"from astropy.coordinates import solar_system_ephemeris, get_body_barycentric_posvel\nsolar_system_ephemeris.set(\"jpl\")",
"The initial data was gathered from Wikipedia: the date of the launch was on November 26, 2011 at 15:02 UTC and landing was on August 6, 2012 at 05:17 UTC. We compute then the time of flight, which is exactly what it sounds. It is a crucial parameter of the mission.",
"# Initial data\nN = 50\n\ndate_launch = time.Time('2011-11-26 15:02', scale='utc')\ndate_arrival = time.Time('2012-08-06 05:17', scale='utc')\ntof = (date_arrival - date_launch)\n\ntof.to(u.h)",
"Once we have the vector of times we can use get_body_barycentric_posvel to compute the array of positions and velocities of the Earth and Mars.",
"times_vector = time_range(date_launch, end=date_arrival, periods=N)\ntimes_vector[:5]\n\nrr_earth, vv_earth = get_body_barycentric_posvel(\"earth\", times_vector)\n\nrr_earth[:3]\n\nvv_earth[:3]\n\nrr_mars, vv_mars = get_body_barycentric_posvel(\"mars\", times_vector)\n\nrr_mars[:3]\n\nvv_mars[:3]",
"<div class=\"alert alert-info\">The positions and velocities are in the <strong>International Standard Reference Frame</strong>, which has the Equator as the fundamental plane</div>\n\nTo compute the transfer orbit, we have the useful function lambert: according to a theorem with the same name, the transfer orbit between two points in space only depends on those two points and the time it takes to go from one to the other. We have the starting and final position and we have the time of flight: there we go!",
"# Compute the transfer orbit!\nr0 = rr_earth[0].xyz\nrf = rr_mars[-1].xyz\n\n(va, vb), = iod.lambert(Sun.k, r0, rf, tof)\n\nss0_trans = Orbit.from_vectors(Sun, r0, va, date_launch)\nssf_trans = Orbit.from_vectors(Sun, rf, vb, date_arrival)",
"And finally, we can plot the figure! There is no more magic here, just passing the position vectors to matplotlib plot function and adding some style to the plot.",
"from plotly.offline import init_notebook_mode\ninit_notebook_mode(connected=True)\n\nfrom poliastro.plotting import OrbitPlotter3D\nfrom poliastro.bodies import Earth, Mars\n\n# I like color\ncolor_earth0 = '#3d4cd5'\ncolor_earthf = '#525fd5'\ncolor_mars0 = '#ec3941'\ncolor_marsf = '#ec1f28'\ncolor_sun = '#ffcc00'\ncolor_orbit = '#888888'\ncolor_trans = '#444444'\n\nframe = OrbitPlotter3D()\n\nframe.set_attractor(Sun)\n\nframe.plot_trajectory(rr_earth, label=Earth, color=color_earth0)\nframe.plot_trajectory(rr_mars, label=Mars, color=color_marsf)\n\nframe.plot_trajectory(ss0_trans.sample(times_vector), label=\"MSL trajectory\", color=color_trans)\n\nframe.set_view(30 * u.deg, 260 * u.deg, distance=3 * u.km)\nframe.show(title=\"MSL Mission: from Earth to Mars\")",
"This line opens a new browser tab and saves the resulting image:",
"#frame.savefig(\"msl3d.png\", title=\"MSL Mission: from Earth to Mars\")",
"Not bad! Let's celebrate with some music!",
"from IPython.display import YouTubeVideo\nYouTubeVideo('zSgiXGELjbc')"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
tcstewar/testing_notebooks
|
Cosine tuning curves.ipynb
|
gpl-2.0
|
[
"First, here is a quick way to determine what the intercepts should be, given a desired angle that you want the neurons to be sensitive to. Here, we want neurons that are sensitive to between +-15 degrees up to +-35 degrees.",
"# How to compute intercept range given an angle range\n\nimport numpy as np\nangle_range_degrees = np.array([15.0, 35.0])\nangle_range = angle_range_degrees * np.pi / 180\n\nprint np.cos(angle_range)",
"So, in order to have tuning curves lke that, we want to have neurons with intercepts=nengo.dists.Uniform(0.82, 0.97) which is close enough to what It looks like you used in the paper.",
"import nengo\nmodel = nengo.Network()\nwith model:\n ens = nengo.Ensemble(n_neurons=400, dimensions=2,\n intercepts=nengo.dists.Uniform(0.81, 0.97),\n )\n \nsim = nengo.Simulator(model)\n",
"Now we compute the tuning curves. Instead of getting tuning curves for every possible value, we just evaluate it along the unit circle.",
"import numpy as np\ntheta_degrees = np.linspace(-100, 100, 201) # in degrees\ntheta = theta_degrees * np.pi / 180\n\nx = np.vstack([np.sin(theta), np.cos(theta)]).T\n\nresponse_curves = np.zeros((ens.n_neurons, len(theta)))\n\ninputs, activity = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=x)\n \n ",
"Plot the results, showing the first 20 neurons only",
"%matplotlib inline\nimport pylab\n\npylab.plot(theta_degrees, activity[:,:20])\npylab.xlabel('represented angle')\npylab.ylabel('firing rate (Hz)')\npylab.show()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
AllenDowney/ModSimPy
|
notebooks/chap16.ipynb
|
mit
|
[
"Modeling and Simulation in Python\nChapter 16\nCopyright 2017 Allen Downey\nLicense: Creative Commons Attribution 4.0 International",
"# Configure Jupyter so figures appear in the notebook\n%matplotlib inline\n\n# Configure Jupyter to display the assigned value after an assignment\n%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'\n\n# import functions from the modsim.py module\nfrom modsim import *",
"Code from previous notebooks",
"def update_func(state, t, system):\n \"\"\"Update the thermal transfer model.\n \n state: State (temp)\n t: time\n system: System object\n \n returns: State (temp)\n \"\"\"\n r, T_env, dt = system.r, system.T_env, system.dt\n \n T = state.T\n T += -r * (T - T_env) * dt\n \n return State(T=T)\n\ndef run_simulation(system, update_func):\n \"\"\"Runs a simulation of the system.\n \n Add a TimeFrame to the System: results\n \n system: System object\n update_func: function that updates state\n \"\"\"\n init = system.init\n t_0, t_end, dt = system.t_0, system.t_end, system.dt\n \n frame = TimeFrame(columns=init.index)\n frame.row[t_0] = init\n ts = linrange(t_0, t_end, dt)\n \n for t in ts:\n frame.row[t+dt] = update_func(frame.row[t], t, system)\n \n return frame\n\ndef make_system(T_init, r, volume, t_end):\n \"\"\"Makes a System object with the given parameters.\n\n T_init: initial temperature in degC\n r: heat transfer rate, in 1/min\n volume: volume of liquid in mL\n t_end: end time of simulation\n \n returns: System object\n \"\"\"\n init = State(T=T_init)\n \n return System(init=init,\n r=r, \n volume=volume,\n temp=T_init,\n t_0=0, \n t_end=t_end, \n dt=1,\n T_env=22)",
"Using root_bisect\nAs a simple example, let's find the roots of this function; that is, the values of x that make the result 0.",
"def func(x):\n return (x-1) * (x-2) * (x-3)",
"modsim.py provides root_bisect, which searches for a root by bisection. The first argument is the function whose roots we want. The second argument is an interval that contains a root.",
"res = root_bisect(func, [0.5, 1.5])",
"The result is an object that contains the root that was found and other information.",
"res.root",
"If we provide a different interval, we find a different root.",
"res = root_bisect(func, [1.5, 2.5])\n\nres.root",
"If the interval doesn't contain a root, the results explain the error.",
"res = root_bisect(func, [4, 5])",
"We want to find the value of r that makes the final temperature 70, so we define an \"error function\" that takes r as a parameter and returns the difference between the final temperature and the goal.",
"def error_func1(r):\n \"\"\"Runs a simulation and returns the `error`.\n \n r: heat transfer rate, in 1/min\n \n returns: difference between final temp and 70 C\n \"\"\"\n system = make_system(T_init=90, r=r, volume=300, t_end=30)\n results = run_simulation(system, update_func)\n T_final = get_last_value(results.T)\n return T_final - 70",
"With r=0.01, we end up a little too warm.",
"error_func1(r=0.01)",
"With r=0.02, we end up too cold.",
"error_func1(r=0.02)",
"The return value from root_bisect is an array with a single element, the estimated value of r.",
"res = root_bisect(error_func1, [0.01, 0.02])\n\nr_coffee = res.root",
"If we run the simulation with the estimated value of r, the final temperature is 70 C, as expected.",
"coffee = make_system(T_init=90, r=r_coffee, volume=300, t_end=30)\nresults = run_simulation(coffee, update_func)\nT_final = get_last_value(results.T)",
"Exercise: When you call root_bisect, it calls error_func1 several times. To see how this works, add a print statement to error_func1 and run root_bisect again.\nExercise: Repeat this process to estimate r_milk, given that it starts at 5 C and reaches 20 C after 15 minutes. \nBefore you use root_bisect, you might want to try a few values for r_milk and see how close you can get by trial and error. Here's an initial guess to get you started:",
"r_milk = 0.1\nmilk = make_system(T_init=5, r=r_milk, volume=50, t_end=15)\nresults = run_simulation(milk, update_func)\nT_final = get_last_value(results.T)\n\n# Solution goes here\n\n# Solution goes here\n\n# Solution goes here\n\n# Solution goes here\n\n# Solution goes here\n\n# Solution goes here",
"Mixing liquids\nThe following function takes System objects that represent two liquids, computes the temperature of the mixture, and returns a new System object that represents the mixture.",
"def mix(system1, system2):\n \"\"\"Simulates the mixture of two liquids.\n \n system1: System representing coffee\n system2: System representing milk\n \n returns: System representing the mixture\n \"\"\"\n assert system1.t_end == system2.t_end\n \n V1, V2 = system1.volume, system2.volume\n T1, T2 = system1.temp, system2.temp\n \n V_mix = V1 + V2\n T_mix = (V1 * T1 + V2 * T2) / V_mix\n \n return make_system(T_init=T_mix,\n r=system1.r,\n volume=V_mix,\n t_end=30)",
"mix requires the System objects to have temp as a system variable. make_system initializes this variable;\nthe following function makes sure it gets updated when we run a simulation.",
"def run_and_set(system):\n \"\"\"Run a simulation and set the final temperature.\n \n system: System\n \n returns: TimeFrame\n \"\"\"\n results = run_simulation(system, update_func)\n system.temp = get_last_value(results.T)\n return results",
"Mixing immediately\nNext here's what we get if we add the milk immediately.",
"coffee = make_system(T_init=90, r=r_coffee, volume=300, t_end=30)\ncoffee.temp\n\nmilk = make_system(T_init=5, r=r_milk, volume=50, t_end=30)\nmilk.temp\n\nmix_first = mix(coffee, milk)\nmix_first.temp\n\nmix_results = run_and_set(mix_first)\nmix_first.temp",
"Mixing at the end\nFirst we'll see what happens if we add the milk at the end. We'll simulate the coffee and the milk separately.",
"coffee_results = run_and_set(coffee)\ncoffee.temp\n\nmilk_results = run_and_set(milk)\nmilk.temp",
"Here's what the results look like.",
"plot(coffee_results.T, label='coffee')\nplot(milk_results.T, '--', label='milk')\n\ndecorate(xlabel='Time (minutes)',\n ylabel='Temperature (C)',\n loc='center left')\n\nsavefig('figs/chap16-fig01.pdf')",
"Here's what happens when we mix them.",
"mix_last = mix(coffee, milk)\nmix_last.temp\n\nmix_last.temp - mix_first.temp",
"The following function takes t_add, which is the time when the milk is added, and returns the final temperature.",
"def run_and_mix(t_add, t_total):\n \"\"\"Simulates two liquids and them mixes them at t_add.\n \n t_add: time in minutes\n t_total: total time to simulate, min\n \n returns: final temperature\n \"\"\"\n coffee = make_system(T_init=90, r=r_coffee, volume=300, t_end=t_add)\n coffee_results = run_and_set(coffee)\n \n milk = make_system(T_init=5, r=r_milk, volume=50, t_end=t_add)\n milk_results = run_and_set(milk)\n \n mixture = mix(coffee, milk)\n mixture.t_end = t_total - t_add\n results = run_and_set(mixture)\n\n return mixture.temp",
"We can try it out with a few values.",
"run_and_mix(t_add=0, t_total=30)\n\nrun_and_mix(t_add=15, t_total=30)\n\nrun_and_mix(t_add=30, t_total=30)",
"And then sweep a range of values for t_add",
"sweep = SweepSeries()\nfor t_add in linspace(0, 30, 11):\n sweep[t_add] = run_and_mix(t_add, 30)",
"Here's what the result looks like.",
"plot(sweep, label='final temp', color='C2')\ndecorate(xlabel='Time added (min)',\n ylabel='Final temperature (C)')\n\nsavefig('figs/chap16-fig02.pdf')",
"Analysis\nNow we can use the analytic result to compute temperature as a function of time. The following function is similar to run_simulation.",
"def run_analysis(system):\n \"\"\"Computes temperature using the analytic solution.\n \n system: System object\n \n returns: TimeFrame\n \"\"\"\n T_env, r = system.T_env, system.r\n \n T_init = system.init.T \n ts = linspace(0, system.t_end)\n \n T_array = T_env + (T_init - T_env) * exp(-r * ts)\n \n # to be consistent with run_simulation,\n # we put the array into a TimeFrame\n return TimeFrame(T_array, index=ts, columns=['T'])",
"Here's how we run it. From the analysis (see chap16sympy.ipynb), we have the computed value of r_coffee2",
"r_coffee2 = 0.011610223142273859\ncoffee2 = make_system(T_init=90, r=r_coffee2, volume=300, t_end=30)\n\nresults = run_analysis(coffee2)\nT_final_analysis = get_last_value(results.T)",
"And we can compare to the results from simulation.",
"coffee = make_system(T_init=90, r=r_coffee, volume=300, t_end=30)\nresults = run_simulation(coffee, update_func)\nT_final_simulation = get_last_value(results.T)",
"They are identical except for a small roundoff error.",
"T_final_analysis - T_final_simulation",
"Exercises\nExercise: Suppose the coffee shop won't let me take milk in a separate container, but I keep a bottle of milk in the refrigerator at my office. In that case is it better to add the milk at the coffee shop, or wait until I get to the office?\nHint: Think about the simplest way to represent the behavior of a refrigerator in this model. The change you make to test this variation of the problem should be very small!",
"# Solution goes here"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
ellisztamas/faps
|
docs/tutorials/.ipynb_checkpoints/02_genotype_data-checkpoint.ipynb
|
mit
|
[
"Genotype data in FAPS",
"import numpy as np\nimport faps as fp\nprint(\"Created using FAPS version {}.\".format(fp.__version__))",
"Tom Ellis, March 2017\nIn most cases, researchers will have a sample of offspring, maternal and candidate paternal individuals typed at a set of markers. In this section we'll look in more detail at how FAPS deals with genotype data to build a matrix we can use for sibship inference.\nThis notebook will examine how to:\n\nGenerate simple genotypeArray objects and explore what information is contained in them.\nImport external genotype data.\nWork with genotype data from multiple half sib families.\n\nChecking genotype data is an important step before committing to a full analysis. A case study of data checking and cleaning using an empirical dataset is given in here.\nIn the next section we'll see how to combine genotype information on offspring and a set of candidate parents to create an array of likelihoods of paternity for dyads of offspring and candidate fathers.\nNote that the first half of this tutorial only deals with the case where you have a genotypeArray object for a single maternal family. If you have multiple families, you can apply what is here to each one, but at some point you'll have to iterate over those families. See below and the specific tutorial on that.\nCurrently, FAPS genotypeArray objects assume you are using biallelic, unlinked SNPs for a diploid. If your system deviates from these criteria in some way you can also skip this stage by creating your own array of paternity likelihoods using an appropriate likelihood function, and importing this directly as a paternityArrays. See the next section for more on paternityArray objects and how they should look.\ngenotypeArray objects\nBasic genotype information\nGenotype data are stored in a class of objects called a genotypeArray. We'll illustrate how these work with simulated data, since not all information is available for real-world data sets. We first generate a vector of population allele frequencies for 10 unlinked SNP markers, and use these to create a population of five adult individuals. This is obviously an unrealisticaly small dataset, but serves for illustration. The optional argument family_names allows you to name this generation.",
"allele_freqs = np.random.uniform(0.3,0.5,10)\nmypop = fp.make_parents(5, allele_freqs, family_name='my_population')",
"The object we just created contains information about the genotypes of each of the ten parent individuals. Genotypes are stored as NxLx2-dimensional arrays, where N is the number of individuals and L is the number of loci. We can view the genotype for the first parent like so (recall that Python starts counting from zero, not one):",
"mypop.geno[0]",
"You could subset the array by indexes the genotypes, for example by taking only the first two individuals and the first five loci:",
"mypop.geno[:2, :5]",
"For realistic examples with many more loci, this obviously gets unwieldy pretty soon. It's cleaner to supply a list of individuals to keep or remove to the subset and drop functions. These return return a new genotypeArray for the individuals of interest.",
"print(mypop.subset([0,2]).names)\nprint(mypop.drop([0,2]).names)",
"Information on individuals\nA genotypeArray contains other useful information about the individuals:",
"print(mypop.names) # individual names\nprint(mypop.size) # number of individuals\nprint(mypop.nloci) # numbe of loci typed.",
"make_sibships is a convenient way to generate a single half-sibling array from individuals in mypop. This code mates makes a half-sib array with individual 0 as the mothers, with individuals 1, 2 and 3 contributing male gametes. Each father has four offspring each.",
"progeny = fp.make_sibships(mypop, 0, [1,2,3], 4, 'myprogeny')",
"With this generation we can extract a little extra information from the genotypeArray than we could from the parents about their parents and family structure.",
"print(progeny.fathers)\nprint(progeny.mothers)\nprint(progeny.families)\nprint(progeny.nfamilies)",
"Of course with real data we would not normally know the identity of the father or the number of families, but this is useful for checking accuracy in simulations. It can also be useful to look up the positions of the parents in another list of names. This code finds the indices of the mothers and fathers of the offspring in the names listed in mypop.",
"print(progeny.parent_index('mother', mypop.names))\nprint(progeny.parent_index('father', mypop.names))",
"Information on markers\nPull out marker names with marker. The names here are boring because they are simulated, but your data can have as exciting names as you'd like.",
"mypop.markers",
"Check whether the locus names for parents and offspring match. This is obvious vital for determining who shares alleles with whom, but easy to overlook! If they don't match, the most likely explanation is that you have imported genotype data and misspecified where the genotype data start (the genotype_col argument).",
"mypop.markers == progeny.markers",
"FAPS uses population allele frequencies to calculate the likelihood that paternal alleles are drawn at random.\nThey are are useful to check the markers are doing what you think they are.\nPull out the population allele frequencies for each locus:",
"mypop.allele_freqs()",
"We can also check for missing data and heterozygosity for each marker and individual. By default, data for each marker are returned:",
"print(mypop.missing_data())\nprint(mypop.heterozygosity())",
"To get summaries for each individual:",
"print(mypop.missing_data(by='individual'))\nprint(mypop.heterozygosity(by='individual'))",
"In this instance there is no missing data, because data are simulated to be error-free. See the next section on an empircal example where this is not true.\nImporting genotype data\nYou can import genotype data from a text or CSV (comma-separated text) file. Both can be easily exported from a spreadsheet program. Rows index individuals, and columns index each typed locus. More specifically:\n\nOffspring names should be given in the first column\nIf the data are offspring, names of the mothers are given in the second column.\nIf known for some reason, names of fathers can be given as well.\nGenotype information should be given to the right of columns indicating individual or parental names, with locus names in the column headers.\n\nSNP genotype data must be biallelic, that is they can only be homozygous for the first allele, heterozygous, or homozygous for the second allele. These should be given as 0, 1 and 2 respectively. If genotype data is missing this should be entered as NA.\nThe following code imports genotype information on real samples of offspring from half-sibling array of wild-pollinated snpadragon seedlings collected in the Spanish Pyrenees. The candidate parents are as many of the wild adult plants as we could find. You will find the data files on the IST Austria data repository (DOI:10.15479/AT:ISTA:95). Aside from the path to where the data file is stored, the two other arguments specify the column containing names of the mothers, and the first column containing genotype data of the offspring.",
"offspring = fp.read_genotypes(\n path = '../../data/offspring_2012_genotypes.csv',\n mothers_col=1,\n genotype_col=2)",
"Again, Python starts counting from zero rather than one, so the first column is really column zero, and so on. Because these are CSV, there was no need to specify that data are delimited by commas, but this is included for illustration.\nOffspring are divided into 60 maternal families of different sizes. You can call the name of the mother of each offspring. You can also call the names of the fathers, with offspring.fathers, but since these are unknown this is not informative.",
"np.unique(offspring.mothers)",
"Offspring names are a combination of maternal family and a unique ID for ecah offspring.",
"offspring.names",
"You can call summaries of genotype data to help in data cleaning. For example, this code shows the proportion of loci with missing genotype data for the first ten offspring individuals.",
"print(offspring.missing_data('individual')[:10])",
"This snippet shows the proportion of missing data points and heterozygosity for the first ten loci. These can be helpful in identifying dubious loci.",
"print(offspring.missing_data('marker')[:10])\nprint(offspring.heterozygosity()[:10])",
"Multiple families\nIn real data set we generally work with multplie half-sibling arrays at once. For downstream analyses we need to split up the genotype data into families to reflect this. This is easy to do with split and a vector of labels to group offspring by. This returns a dictionary of genotypeArray objects labelled by maternal family. These snippet splits up the data and prints the maternal family names.",
"offs_split = offspring.split(by = offspring.mothers)\noffs_split.keys()",
"Each entry is an individual genotypeArray. You can pull out individual families by indexing the dictionary by name. For example, here are the names of the offspring in family J1246:",
"offs_split[\"J1246\"].names",
"To perform operations on each genotypeArray we now have to iterate over each element. A convenient way to do this is with dictionary comprehensions by separating out the labels from the genotypeArray objects using items.\nAs an example, here's how you call the number of offspring in each family. It splits up the dictionary into keys for each family, and calls size on each genotypeArray (labelled genArray in the comprehension).",
"{family : genArray.size for family,genArray in offs_split.items()}",
"You can achieve the same thing with a list comprehension, but you lose information about family ID. It is also more difficult to pass a list on to downstream functions. This snippet shows the first ten items.",
"[genArray.size for genArray in offs_split.values()][:10]"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
pdwyys20/deep-learning
|
intro-to-tensorflow/intro_to_tensorflow.ipynb
|
mit
|
[
"<h1 align=\"center\">TensorFlow Neural Network Lab</h1>\n\n<img src=\"image/notmnist.png\">\nIn this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of English letters! The data you are using, <a href=\"http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html\">notMNIST</a>, consists of images of a letter from A to J in different fonts.\nThe above images are a few examples of the data you'll be training on. After training the network, you will compare your prediction model against test data. Your goal, by the end of this lab, is to make predictions against that test set with at least an 80% accuracy. Let's jump in!\nTo start this lab, you first need to import all the necessary modules. Run the code below. If it runs successfully, it will print \"All modules imported\".",
"import hashlib\nimport os\nimport pickle\nfrom urllib.request import urlretrieve\n\nimport numpy as np\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.utils import resample\nfrom tqdm import tqdm\nfrom zipfile import ZipFile\n\nprint('All modules imported.')",
"The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J).",
"def download(url, file):\n \"\"\"\n Download file from <url>\n :param url: URL to file\n :param file: Local file path\n \"\"\"\n if not os.path.isfile(file):\n print('Downloading ' + file + '...')\n urlretrieve(url, file)\n print('Download Finished')\n\n# Download the training and test dataset.\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_train.zip', 'notMNIST_train.zip')\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_test.zip', 'notMNIST_test.zip')\n\n# Make sure the files aren't corrupted\nassert hashlib.md5(open('notMNIST_train.zip', 'rb').read()).hexdigest() == 'c8673b3f28f489e9cdf3a3d74e2ac8fa',\\\n 'notMNIST_train.zip file is corrupted. Remove the file and try again.'\nassert hashlib.md5(open('notMNIST_test.zip', 'rb').read()).hexdigest() == '5d3c7e653e63471c88df796156a9dfa9',\\\n 'notMNIST_test.zip file is corrupted. Remove the file and try again.'\n\n# Wait until you see that all files have been downloaded.\nprint('All files downloaded.')\n\ndef uncompress_features_labels(file):\n \"\"\"\n Uncompress features and labels from a zip file\n :param file: The zip file to extract the data from\n \"\"\"\n features = []\n labels = []\n\n with ZipFile(file) as zipf:\n # Progress Bar\n filenames_pbar = tqdm(zipf.namelist(), unit='files')\n \n # Get features and labels from all files\n for filename in filenames_pbar:\n # Check if the file is a directory\n if not filename.endswith('/'):\n with zipf.open(filename) as image_file:\n image = Image.open(image_file)\n image.load()\n # Load image data as 1 dimensional array\n # We're using float32 to save on memory space\n feature = np.array(image, dtype=np.float32).flatten()\n\n # Get the the letter from the filename. This is the letter of the image.\n label = os.path.split(filename)[1][0]\n\n features.append(feature)\n labels.append(label)\n return np.array(features), np.array(labels)\n\n# Get the features and labels from the zip files\ntrain_features, train_labels = uncompress_features_labels('notMNIST_train.zip')\ntest_features, test_labels = uncompress_features_labels('notMNIST_test.zip')\n\n# Limit the amount of data to work with a docker container\ndocker_size_limit = 150000\ntrain_features, train_labels = resample(train_features, train_labels, n_samples=docker_size_limit)\n\n# Set flags for feature engineering. This will prevent you from skipping an important step.\nis_features_normal = False\nis_labels_encod = False\n\n# Wait until you see that all features and labels have been uncompressed.\nprint('All features and labels uncompressed.')",
"<img src=\"image/Mean_Variance_Image.png\" style=\"height: 75%;width: 75%; position: relative; right: 5%\">\nProblem 1\nThe first problem involves normalizing the features for your training and test data.\nImplement Min-Max scaling in the normalize_grayscale() function to a range of a=0.1 and b=0.9. After scaling, the values of the pixels in the input data should range from 0.1 to 0.9.\nSince the raw notMNIST image data is in grayscale, the current values range from a min of 0 to a max of 255.\nMin-Max Scaling:\n$\nX'=a+{\\frac {\\left(X-X_{\\min }\\right)\\left(b-a\\right)}{X_{\\max }-X_{\\min }}}\n$\nIf you're having trouble solving problem 1, you can view the solution here.",
"# Problem 1 - Implement Min-Max scaling for grayscale image data\ndef normalize_grayscale(image_data):\n \"\"\"\n Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]\n :param image_data: The image data to be normalized\n :return: Normalized image data\n \"\"\"\n # TODO: Implement Min-Max scaling for grayscale image data\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Test Cases\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 255])),\n [0.1, 0.103137254902, 0.106274509804, 0.109411764706, 0.112549019608, 0.11568627451, 0.118823529412, 0.121960784314,\n 0.125098039216, 0.128235294118, 0.13137254902, 0.9],\n decimal=3)\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 10, 20, 30, 40, 233, 244, 254,255])),\n [0.1, 0.103137254902, 0.13137254902, 0.162745098039, 0.194117647059, 0.225490196078, 0.830980392157, 0.865490196078,\n 0.896862745098, 0.9])\n\nif not is_features_normal:\n train_features = normalize_grayscale(train_features)\n test_features = normalize_grayscale(test_features)\n is_features_normal = True\n\nprint('Tests Passed!')\n\nif not is_labels_encod:\n # Turn labels into numbers and apply One-Hot Encoding\n encoder = LabelBinarizer()\n encoder.fit(train_labels)\n train_labels = encoder.transform(train_labels)\n test_labels = encoder.transform(test_labels)\n\n # Change to float32, so it can be multiplied against the features in TensorFlow, which are float32\n train_labels = train_labels.astype(np.float32)\n test_labels = test_labels.astype(np.float32)\n is_labels_encod = True\n\nprint('Labels One-Hot Encoded')\n\nassert is_features_normal, 'You skipped the step to normalize the features'\nassert is_labels_encod, 'You skipped the step to One-Hot Encode the labels'\n\n# Get randomized datasets for training and validation\ntrain_features, valid_features, train_labels, valid_labels = train_test_split(\n train_features,\n train_labels,\n test_size=0.05,\n random_state=832289)\n\nprint('Training features and labels randomized and split.')\n\n# Save the data for easy access\npickle_file = 'notMNIST.pickle'\nif not os.path.isfile(pickle_file):\n print('Saving data to pickle file...')\n try:\n with open('notMNIST.pickle', 'wb') as pfile:\n pickle.dump(\n {\n 'train_dataset': train_features,\n 'train_labels': train_labels,\n 'valid_dataset': valid_features,\n 'valid_labels': valid_labels,\n 'test_dataset': test_features,\n 'test_labels': test_labels,\n },\n pfile, pickle.HIGHEST_PROTOCOL)\n except Exception as e:\n print('Unable to save data to', pickle_file, ':', e)\n raise\n\nprint('Data cached in pickle file.')",
"Checkpoint\nAll your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed.",
"%matplotlib inline\n\n# Load the modules\nimport pickle\nimport math\n\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n# Reload the data\npickle_file = 'notMNIST.pickle'\nwith open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f)\n train_features = pickle_data['train_dataset']\n train_labels = pickle_data['train_labels']\n valid_features = pickle_data['valid_dataset']\n valid_labels = pickle_data['valid_labels']\n test_features = pickle_data['test_dataset']\n test_labels = pickle_data['test_labels']\n del pickle_data # Free up memory\n\nprint('Data and modules loaded.')",
"Problem 2\nNow it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer.\n<img src=\"image/network_diagram.png\" style=\"height: 40%;width: 40%; position: relative; right: 10%\">\nFor the input here the images have been flattened into a vector of $28 \\times 28 = 784$ features. Then, we're trying to predict the image digit so there are 10 output units, one for each label. Of course, feel free to add hidden layers if you want, but this notebook is built to guide you through a single layer network. \nFor the neural network to train on your data, you need the following <a href=\"https://www.tensorflow.org/resources/dims_types.html#data-types\">float32</a> tensors:\n - features\n - Placeholder tensor for feature data (train_features/valid_features/test_features)\n - labels\n - Placeholder tensor for label data (train_labels/valid_labels/test_labels)\n - weights\n - Variable Tensor with random numbers from a truncated normal distribution.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/constant_op.html#truncated_normal\">tf.truncated_normal() documentation</a> for help.\n - biases\n - Variable Tensor with all zeros.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/constant_op.html#zeros\"> tf.zeros() documentation</a> for help.\nIf you're having trouble solving problem 2, review \"TensorFlow Linear Function\" section of the class. If that doesn't help, the solution for this problem is available here.",
"# All the pixels in the image (28 * 28 = 784)\nfeatures_count = 784\n# All the labels\nlabels_count = 10\n\n# TODO: Set the features and labels tensors\n# features = \n# labels = \n\n# TODO: Set the weights and biases tensors\n# weights = \n# biases = \n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n\n#Test Cases\nfrom tensorflow.python.ops.variables import Variable\n\nassert features._op.name.startswith('Placeholder'), 'features must be a placeholder'\nassert labels._op.name.startswith('Placeholder'), 'labels must be a placeholder'\nassert isinstance(weights, Variable), 'weights must be a TensorFlow variable'\nassert isinstance(biases, Variable), 'biases must be a TensorFlow variable'\n\nassert features._shape == None or (\\\n features._shape.dims[0].value is None and\\\n features._shape.dims[1].value in [None, 784]), 'The shape of features is incorrect'\nassert labels._shape == None or (\\\n labels._shape.dims[0].value is None and\\\n labels._shape.dims[1].value in [None, 10]), 'The shape of labels is incorrect'\nassert weights._variable._shape == (784, 10), 'The shape of weights is incorrect'\nassert biases._variable._shape == (10), 'The shape of biases is incorrect'\n\nassert features._dtype == tf.float32, 'features must be type float32'\nassert labels._dtype == tf.float32, 'labels must be type float32'\n\n# Feed dicts for training, validation, and test session\ntrain_feed_dict = {features: train_features, labels: train_labels}\nvalid_feed_dict = {features: valid_features, labels: valid_labels}\ntest_feed_dict = {features: test_features, labels: test_labels}\n\n# Linear Function WX + b\nlogits = tf.matmul(features, weights) + biases\n\nprediction = tf.nn.softmax(logits)\n\n# Cross entropy\ncross_entropy = -tf.reduce_sum(labels * tf.log(prediction), reduction_indices=1)\n\n# Training loss\nloss = tf.reduce_mean(cross_entropy)\n\n# Create an operation that initializes all variables\ninit = tf.global_variables_initializer()\n\n# Test Cases\nwith tf.Session() as session:\n session.run(init)\n session.run(loss, feed_dict=train_feed_dict)\n session.run(loss, feed_dict=valid_feed_dict)\n session.run(loss, feed_dict=test_feed_dict)\n biases_data = session.run(biases)\n\nassert not np.count_nonzero(biases_data), 'biases must be zeros'\n\nprint('Tests Passed!')\n\n# Determine if the predictions are correct\nis_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels, 1))\n# Calculate the accuracy of the predictions\naccuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))\n\nprint('Accuracy function created.')",
"<img src=\"image/Learn_Rate_Tune_Image.png\" style=\"height: 70%;width: 70%\">\nProblem 3\nBelow are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy.\nParameter configurations:\nConfiguration 1\n* Epochs: 1\n* Learning Rate:\n * 0.8\n * 0.5\n * 0.1\n * 0.05\n * 0.01\nConfiguration 2\n* Epochs:\n * 1\n * 2\n * 3\n * 4\n * 5\n* Learning Rate: 0.2\nThe code will print out a Loss and Accuracy graph, so you can see how well the neural network performed.\nIf you're having trouble solving problem 3, you can view the solution here.",
"# Change if you have memory restrictions\nbatch_size = 128\n\n# TODO: Find the best parameters for each configuration\n# epochs = \n# learning_rate = \n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Gradient Descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) \n\n# The accuracy measured against the validation set\nvalidation_accuracy = 0.0\n\n# Measurements use for graphing loss and accuracy\nlog_batch_step = 50\nbatches = []\nloss_batch = []\ntrain_acc_batch = []\nvalid_acc_batch = []\n\nwith tf.Session() as session:\n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer and get loss\n _, l = session.run(\n [optimizer, loss],\n feed_dict={features: batch_features, labels: batch_labels})\n\n # Log every 50 batches\n if not batch_i % log_batch_step:\n # Calculate Training and Validation accuracy\n training_accuracy = session.run(accuracy, feed_dict=train_feed_dict)\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\n # Log batches\n previous_batch = batches[-1] if batches else 0\n batches.append(log_batch_step + previous_batch)\n loss_batch.append(l)\n train_acc_batch.append(training_accuracy)\n valid_acc_batch.append(validation_accuracy)\n\n # Check accuracy against Validation data\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\nloss_plot = plt.subplot(211)\nloss_plot.set_title('Loss')\nloss_plot.plot(batches, loss_batch, 'g')\nloss_plot.set_xlim([batches[0], batches[-1]])\nacc_plot = plt.subplot(212)\nacc_plot.set_title('Accuracy')\nacc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')\nacc_plot.plot(batches, valid_acc_batch, 'x', label='Validation Accuracy')\nacc_plot.set_ylim([0, 1.0])\nacc_plot.set_xlim([batches[0], batches[-1]])\nacc_plot.legend(loc=4)\nplt.tight_layout()\nplt.show()\n\nprint('Validation accuracy at {}'.format(validation_accuracy))",
"Test\nYou're going to test your model against your hold out dataset/testing data. This will give you a good indicator of how well the model will do in the real world. You should have a test accuracy of at least 80%.",
"### DON'T MODIFY ANYTHING BELOW ###\n# The accuracy measured against the test set\ntest_accuracy = 0.0\n\nwith tf.Session() as session:\n \n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer\n _ = session.run(optimizer, feed_dict={features: batch_features, labels: batch_labels})\n\n # Check accuracy against Test data\n test_accuracy = session.run(accuracy, feed_dict=test_feed_dict)\n\n\nassert test_accuracy >= 0.80, 'Test accuracy at {}, should be equal to or greater than 0.80'.format(test_accuracy)\nprint('Nice Job! Test Accuracy is {}'.format(test_accuracy))",
"Multiple layers\nGood job! You built a one layer TensorFlow network! However, you might want to build more than one layer. This is deep learning after all! In the next section, you will start to satisfy your need for more layers."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
ibm-cds-labs/pixiedust
|
notebook/PixieDust 4 - Add External Spark Packages.ipynb
|
apache-2.0
|
[
"Add Spark packages and run inside your notebook\nPixieDust PackageManager lets you install spark packages inside your notebook. This is especailly useful when you're working in a hosted cloud environment without access to configuration files. Use PixieDust Package Manager to install:\n\na spark package from spark-packages.org\nfrom maven search repository\na jar file directly from URL\n\n\nNote: After you install a package, you must restart the kernel.\n\nView list of packages\nTo see the packages installed on your system, run the following command:",
"import pixiedust\npixiedust.printAllPackages()",
"Add a package from spark-packages.org\nRun the following cell to install GraphFrames.",
"pixiedust.installPackage(\"graphframes:graphframes:0\")",
"Restart your kernel\nFrom the menu at the top of this notebook, choose Kernel > Restart, then run the next cell.\nView updated list of packages\nRun printAllPackages again to see that GraphFrames is now in your list:",
"pixiedust.printAllPackages()",
"Display a GraphFrames data sample\nGraphGrames comes with sample data sets. Even if GraphFrames is already installed, running the install command loads the Python that comes along with the package and enables features like the one you're about to see. Run the following cell and PixieDust displays a sample graph data set called friends. On the upper left of the display, click the table dropdown and switch between views of nodes and edges.",
"#import the Graphs example\nfrom graphframes.examples import Graphs\n#create the friends example graph\ng=Graphs(sqlContext).friends()\n#use the pixiedust display\ndisplay(g)",
"Install from maven\nTo install a package from Maven, visist the project and find its groupId and artifactId, then enter it in the following install command. Read more. For example, the following cell installs Apache Commons:",
"pixiedust.installPackage(\"org.apache.commons:commons-csv:0\")",
"Install a jar file directly from a URL\nTo install a jar file that is not packaged in a maven repository, provide its URL.",
"pixiedust.installPackage(\"https://github.com/ibm-watson-data-lab/spark.samples/raw/master/dist/streaming-twitter-assembly-1.6.jar\")",
"Follow the tutorial\nTo understand what you can do with this jar file, read David Taieb's latest Realtime Sentiment Analysis of Twitter Hashtags with Spark tutorial.\nUninstall a package\nIt's just as easy to get rid of a package you installed. Just run the command pixiedust.uninstallPackage(\"<<mypackage>>\"). For example, you can uninstall Apache Commons:",
"pixiedust.uninstallPackage(\"org.apache.commons:commons-csv:0\")"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
NYUDataBootcamp/Projects
|
UG_S17/Chen-Zheng-SkyscraperIndex&Recession.ipynb
|
mit
|
[
"Skyscraper Index and Recession\nData Bootcamp Final Report\nZhenyu Chen (zc676) & Yue Zheng (yz3152)\n5/5/2017",
"%matplotlib inline \n\nimport pandas as pd # data package\nimport matplotlib.pyplot as plt # graphics module \nimport datetime as dt # date and time module\nimport numpy as np # foundation for Pandas\nimport xlwt # package to create a new excel\nimport seaborn as sns # package for better graph look\nimport statsmodels.api as sm # package for statical analysis \nimport statsmodels.formula.api as smf # package for statical analysis that specifying formula\nfrom patsy import dmatrices # package for transforming matrix",
"1. Project Overview\n1.1 Background and justification of the project\nHumans are ambitious of getting closer to the sky, so breaking the record of “the tallest\nskyscraper” seems to be a heated competition worldwide. For now, the winner goes to Burj\nKhalifa, a megatall skyscraper in Dubai.\nA whimsical concept called the “skyscraper index” proposed by Andrew Lawrence in 1999 has\ncaught the attention of economists. According to Lawrence, “Business cycles and skyscraper\nconstruction correlate in such a way that investment in skyscrapers peaks when cyclical growth\nis exhausted and the economy is ready for recession”. For this project, we are interested in\nexploring the correlation between skyscraper construction and recession.\nTaking a step further to fulfill Lawrence’s idea, the Barclay Capital actually calculate their own skyscraper index and use it as an index for real estate and microeconomics analysis. \nGiven that the Barclay Skyscraper Index is unreleased, we decide to organize the database of skyscraper index by ourselves, with information obtained from www.skyscraper.com and Penn World Table. By exploring the topics discussed in the following section, we want to find out answer for the big question: whether the skyscraper index is a good indicator for recession?....\n1.2 Objectives and Methods of the project\nThe skyscrapercenter.com website contains useful information about the skyscrapers in the\nworld, including building name, city and its country code, height, completed year, etc. We transfrom data in the website to excel since the dataset is in manageable size (Scrapping doesn't work out nicely in our case). At the same time, countries’ macro statistical numbers are easy to get (GDP, inflation, etc.). \nAs introduced above, we would like to find out the correlations between the skyscraper data and macroeconomics data by graphing and doing data analysis. For better presentation purpose, we mainly focus on country Japan. It is known that Japan had a recession period starting 1980s. Also, its record of skyscraper construction is complete and eaily to obtain. We assume that such strong recession in Japan will give more explanatory power to the “skyscraper theorem” if it holds. Of course, using our data, we can easily analyze other countires by changing the country code.\n1.3 Expected results of the project\nWe expect to see that the “skyscraper theorem” will hold during the recession period. Countries that built more skyscrapers may have more severe period of recession.\nBy running through detailed topics, we expect to see that the skyscraper index has correlation\nwith recession. However, whether the correlation implies strong predicting power for future\nrecession needs further research.\n2. Clean Data\n2.1 Clean the Skyscrapers Data\nThe skyscrapers data comes from Skyscraper Center. The website is written in JavaScript so that we cannot use the method we learned in class to scrap the data. We still tried to scrap it but we failed to do so. However, the website allows us to download the data in pdf format. We then manually copy and paste the data into the excel. The data is well tabulated so the process is actually not complicated.",
"data_clean = 'C:\\\\Users\\\\lenovo\\\\Documents\\\\Data_Bootcamp\\\\Project\\\\data_clean.xlsx'\n\ndf1 = pd.read_excel(data_clean)\ndf1.head()",
"We want to know for each country, how many Skyscrapers were built in each year. We found a package called 'xlwt' which help us create a new excel file and clean the data more efficiently. By saving our output into a new excel, we do not need to re-run the code every time we open the jupyter notebook.",
"sheet_range = list(range(0, 5)) # There are 5 sheets in the file, and we convert the range into a list for future use.\nyear_range = list(range(1909, 2018)) # The earliest skyscrapers data was built in 1909 in New York according to our data.\n\n# Create a new excel to record the counts, using the xlwt package.\nfile = xlwt.Workbook() \ntable = file.add_sheet('sheet_1', cell_overwrite_ok=True)\n\n# \"cell_overwrite_ok=True\" allows Python to overwrite the cells. In our practice we found it useful to prevent errors.\n\n# Set the column names for the new excel, using the function table.write(row, column, text).\ntable.write(0, 0, 'Country')\ntable.write(0, 1, 'Year')\ntable.write(0, 2, 'Count')",
"The skyscrapers data excel have 5 sheets, and each of them contains the skyscrapers data for a specific contury (Japan, Singarpore, China, US and UAE). The idea is that, we first go through all the 5 sheets, and within a sheet, we count the number of skyscrapers built in each year. By using the \"groupby\" function and boolean selection we could also achieve this. However, when we wrote those codes, those concepts were not introduced, so we used two loops to get the same result. The method works great so we decide to keep those codes. As we mentioned, we will focus on the Japanese data in this project, but we clean the data for all 5 countries in case of future use.",
"row = 1\nfor sheetnumber in sheet_range:\n df1 = pd.read_excel(data_clean, sheetname=sheetnumber) # Read a sheet, from the first one to the fifth.\n country = df1.iat[1, 2] # Get the country name by reading the specific value in cell (2, 3).\n for year in year_range:\n Years = [year]\n year_data = df1[df1['Completed'].isin(Years)] # Group all the skyscrapers that were built in the same year.\n count = len(year_data.index) # Count how many skyscrapers were built in each year group, using the length of the index.\n print(country, year, count) # To show the result and check if the results are correct.\n table.write(row, 0, country) # Record the county, year and count data in the new excel we created.\n table.write(row, 1, year)\n table.write(row, 2, count)\n row += 1\n file.save('year_count_data.xls') \n # Save the file. Next time we can directly use the data from this excel without re-running all the code again.",
"2.2 Clean the PWT90 Data\nThe GDP data comes from Penn World Table. Here we clean the data for Japan as an example. For other countries, it is easy to repeat the same process by changing the country code.",
"url = \"http://www.rug.nl/ggdc/docs/pwt90.xlsx\" # The url link from PWT\npwt = pd.read_excel(url, sheetname='Data', # Use data from the sheet named 'Data'\n parse_cols=[0,1,2,3,4]) # Extarct the 1-5 collums of the data\n\npwt.head()",
"So now we hava a data that contans information of countrycode, country name, curreny_unit, year and real GDP.",
"pwt1=pwt.loc[pwt['countrycode'] == ('JPN')] # Extract data of Japan by using boolean\npwt2=pwt1.loc[pwt1['year'].isin(range(1970,2017))] # Change the year range, from 1970 to 2016\npwt2.head()",
"We further extract information of Japan by setting boolean statement, and set year to range from 1970 to 1974. The number of skyscrapers built in each year is an annual change, so it makes more sense to compare it with the annual change of GDP, which is the GDP growth rate. See section 2.3,2.4 for calculation of GDP growth rate and combinaiton of data.\n2.3 Combine the Two Data Set\nAgain, we use Japan as an example to combine the skyscrapers data and the GDP data into one data set.",
"year_count_data = 'C:\\\\Users\\\\lenovo\\\\Documents\\\\Data_Bootcamp\\\\Project\\\\year_count_data.xls'\ndf2 = pd.read_excel(year_count_data)\ndf2.head()\n\ndf_JPN = df2[df2['Country']=='Japan']\ncombo_1 = df_JPN.merge(pwt2, how='left', left_on='Year', right_on='year')\ncombo_1 = combo_1.rename(columns={'rgdpe':'GDP'})\ncombo_1.tail()\n\ncombo_JPN = combo_1[['Country', 'Year', 'Count', 'GDP', 'currency_unit']]\ncombo_JPN.tail()",
"There is an error saying that \"A value is trying to be set on a copy of a slice from a DataFrame\" and there is a better way to do it. However, the current method works well. So far we get the clean data we need to continue our project. \n2.4 Calculate GDP Growth from PWT90\nSince we have the cleaned PWT90 data, we can calculate GDP growth by dividing a year's GDP by the previous year's GDP and minus 1. The loop gives us a list. We have to convert it into a series in order to concat it with dataframes.",
"i = 0\nGDP_growth = []\n\nfor i in range(0, 109):\n if i == 0:\n c = 0 # set 0 as our first year's GDP growth since we do not have previous year's information. We are not likely to use the first year's GDP growth anyways.\n GDP_growth.append(c)\n else:\n a = combo_JPN.loc[i-1, 'GDP']\n b = combo_JPN.loc[i, 'GDP']\n c = b/a-1\n GDP_growth.append(c)\n i += 1\n \nGDP_growth = pd.Series(GDP_growth)\n\nGDP_growth.tail()",
"Combine the GDP_growth series and the combo_JPN dataframe together.",
"combo_JPN = pd.concat([combo_JPN, GDP_growth], axis=1, join_axes=[combo_JPN.index])\n\ncombo_JPN = combo_JPN.rename(columns={0: 'GDP_growth'})\ncombo_JPN = combo_JPN.set_index('Year')\ncombo_JPN.tail()",
"2.5 Clean the GDP and Inflation Data\nIn order to better understand the information about recession, we obtain data from IMF,specifically its World Economic Outlook database. By using selective variables related to GDP and inflation rates, we extract information within certain countries that are reasonable for our purpose of doing analysis.",
"url = 'https://www.imf.org/external/pubs/ft/weo/2016/02/weodata/WEOOct2016all.xls' ###weo link\n\nweo = pd.read_csv(url, sep='\\t', # read csv document fron url\n usecols = [1, 2] + list(range(19,46)), # use the 2nd, 3rd and 20-47 columns\n thousands=',', # change thousands\n na_values=['n/a', '--']) # change NA values",
"Now we obtain the dataFrame called weo. It contains information from different countries from Year 1990 to Year 2011. This year range is sufficient for now considered our puropose of doing simple recession analysis. To continue, we extraxt specific vairiables and countires that we are looking for.",
"variables1 = ['NGDPRPC','NGDPD','PCPIPCH','PCPIE'] # Define a list of variables1\ndf = weo[weo['WEO Subject Code'].isin(variables1)] # Find variables1 in this column\nvariables2 = ['JPN','USA','CHN','ARE','SGP'] # Define a list of variables12\ndf = weo[weo['ISO'].isin(variables2)] # Find variables2 in this column\ndf = df[0:-5] # Extract only Data without additional info\n\npv2 = pd.pivot_table(df,index=['WEO Subject Code','ISO'], dropna=False, fill_value=0.0)\n # reindex teh table to a pivot view\npv2.columns= np.arange(1990,2017) # set year range\n\nimport seaborn as sns # import seaborn package\npalette = sns.color_palette(\"Paired\", 10) # set palette style\nsns.set_palette(palette)\n\npv2.loc['NGDPRPC', 'JPN'] # Test data by get GDP from Japan",
"Now we have the data ready for inflation and GDP analysis, see the next section for graphs.\n3. Data Analysis\n3.1 Understanding Recession\nBefore we get in to the analysis of skycraper index and recession, we want to show that the time period and countries that we selected are valid for the purpose of illustration. For the purpose of simplicity, we focus mainly on the country Japan, and the time frame 1990-2016. We choose Japan as our main research target for two reaons. On the one hand, Japan goes through great recession period as Japan government tighted their monetary policy during 1985-1990, the market collapsed from then on, so the signs for recession should be clear. On the other hand, Japan have relativly sufficent record of construction of skycrapers. We choose other control countires such as United States, China, Singpapre and United Arab Emirates for comparison and illustration purpose (Extraction of countries shown in part 2.5).",
"pv2.loc['NGDPD'].T.plot(alpha=0.75, rot=45, title=\"Real GDP per capita (current US$)\")",
"This graph demonstrates real GDP per capita across different countires (scaled through US dollar). In this graph , it is clear that Japan (Labelld in Green)goes through decline in GDP starting around Year1995, while other countries in the same period had increasing GDP. The volatility of Japan GDP is also relatively large, implying that the economy of Japan was not stable over time.",
"pv2.loc['PCPIPCH'].T.plot(alpha=0.75, rot=45, title=\"Inflation (% change)\")",
"This graph demonstrates information about inflation.It can be seen that starting Year 1990, Japan had decreasing rate of change in CPI. Compared with other countries, it had a relatively long peiord of deflation, the inflation (negative) index is lower in value compared with other countries. Japan seems to be influenced by this recession shock and finds it hard to recover.",
"plot_data = pv2.loc['NGDPD'].T.reset_index() # focus on real GDP data\nplot_data.rename(columns={'index':'Years'}, inplace=True) # rename the index\nmelt_data = pd.melt(plot_data, id_vars=['Years'],var_name='Country') # x value: Year\nmelt_data.rename(columns={'value':'GDP'}, inplace=True) # y value: Country GDP\nsns.lmplot(x=\"Years\", y=\"GDP\", hue=\"Country\", data=melt_data, palette=\"Set1\")",
"By running out a linear regression, we see that the regression line of Japan for GDP over years are relatively flat. After fluctuations around Year 1995, the downward trending GDP restrain economic growth of Japan, while other countires have faster increase.",
"pv2T = pv2.T # Transpose\nf, ax = plt.subplots(figsize=(16, 5)) # Set fig size\nsns.barplot(x='Years',y='JPN', data=plot_data,label=\"JPN\", color=sns.xkcd_rgb[\"lime\"])\nax.legend(ncol=2, loc=\"upper left\", frameon=True) # Set legend \nax.set(xlim=(-1, 28), ylabel=\"\",xlabel=\"gdp\") # Set label\nplt.xticks(rotation=90) # rotate the year on x value for better look\nsns.despine(left=True, bottom=True) # Adjust size\nplt.show()",
"At last, we are plotting a histogram to show the real GDP of Japan from year 1990 to 2016. With a clearer distribution, we will go into details about whether Skycraper index relates to recession in the following section.\n3.2 Skyscraper, GDP, and Recession\nThe data we use for 3.2 starts from 1980, which is the year before the recession happened.",
"combo_JPN_subset = combo_JPN[combo_JPN.index.isin(range(1980, 2015))]\ncombo_JPN_subset.head()",
"We multiply GDP growth by 1000 and then divide GDP by a 100000, so that they can be shown in the same graph with skyscrapers counts. By observing the graph we can have a basic idea of the relationship between skyscrapers index and GDP.",
"fix, ax = plt.subplots()\n\nx1 = combo_JPN_subset['GDP']/100000\nx2 = combo_JPN_subset['GDP_growth']*1000\n \ncombo_JPN_subset['Count'].plot(ax=ax, label='Skyscrapers Built in Each Year')\nx1.plot(ax=ax, label='GDP, 100 Thousand Yen')\nx2.plot(ax=ax, label='GDP Growth, 1000%')\n\nax.set_title('GDP, Growth and Numbers of Skyscrapers Built', fontsize=16, loc='left')\nax.legend(loc='best')",
"Given skyscraper count, GDP and GDP growth are measured in different units (1 for count, 100k for GDP and 1000% for growth), it is not reasonable to compare them on the value basis. From the graph we may still say there is some kind of correlation between skyscrapers index and GDP growth, because in some years, they move up and down together. For example, during 2000 and 2005, this correlation is very strong. However, this is our intuition thus we cannot make this argument without further quantitative analysis.\n3.3 Correlation Analysis\nCorrelation analysis is the simplest model but it may offer us some useful information. If the “skyscraper theorem” holds, then there might be a negative correlation between skyscrapers count and GDP growth in the long run. The correlation is -0.27 using the data from 1980 to 2014. This negative correlation somehow meets our expectation. At the same time, however, the absolute value of which is not large, indicating that the correlation is not that strong.",
"combo_JPN_subset['Count'].corr(combo_JPN_subset['GDP_growth'])",
"We also notice that the correlation results are various when we split the data into several subsets. Here we split the data in to pre-crisis time (1980-1985), crisis time (1986-1991) and post-crisis time (1992-2014). We see there is a strong positive correlation during pre-crisis time. This may result from Japan's rapid economic growth before crisis. During the crisis time and post-crisis time, the correlations between skyscrapers count and GDP growth are weak.",
"combo_JPN_subset_1 = combo_JPN[combo_JPN.index.isin(range(1980, 1985))]\ncombo_JPN_subset_1['Count'].corr(combo_JPN_subset_1['GDP_growth'])\n\ncombo_JPN_subset_2 = combo_JPN[combo_JPN.index.isin(range(1986, 1991))]\ncombo_JPN_subset_2['Count'].corr(combo_JPN_subset_2['GDP_growth'])\n\ncombo_JPN_subset_3 = combo_JPN[combo_JPN.index.isin(range(1992, 2014))]\ncombo_JPN_subset_3['Count'].corr(combo_JPN_subset_3['GDP_growth'])",
"The numbers make sense to us, but correlation cannot show the predictive power of skyscrapers index towards recession. Thus, further analysis is needed.\n3.4 Regression Analysis\nSince the correlation result does not seem to have much explanatory power, we now take a step further to do a simple regression. We want to conduct a linear regression model, setting the independent varialble (x) to be count, and the dependent variable (y) to be GDP growth.",
"combo_JPN_subset1 = combo_JPN_subset [['Count','GDP_growth']] # Extract the two varaibles we need\ncombo_JPN_subset1.tail()\n\n# Now tarnsform the variables into matrix for clearer presentation\ny,X = dmatrices('GDP_growth~Count', data=combo_JPN_subset1, return_type = 'dataframe')\nprint (y.head()) # printting y variable to be GDP_growth\nprint (X.head()) # printting X variable to be Count\n\nmod = sm.OLS(y,X) # choosing to run OLS estimation\nres = mod.fit() # setting the residual value\nprint (res.summary()) # print out the OLS result",
"This regression result gives us more insight about our hypothesis. First of all, the independent variable (count) has negative coefficient, and this is significant in the 95% Confidence Level. That is to say, the skyscraper index is indeed negatively related to to GDP growth In Japan from Year 1980 to year 2014. However, the R-Square and adjusted R-square is extremely low, this makes sense since we only regress on one dependent variable, while there are many other factors influencing the change in GDP growth. Another thing that we notice is the Durbin_Watson result. The value 0.832 is between (0,2), indicating that there is a positive auto correlation. That is to say, there is probably a time lag in the count seires data. Also, it can be assumed that when economy is generally good, more buildings are built within these years, while recession might lead to decrease in constructions of skyscrapers in following years. \n4. Conclusion\n\nIn our specific example of Japan, we can draw a conclusion that skyscrapers index can be used as an indicator of GDP growth. Therefore, it is a good indicator for recession since recession is tightly connnected to GDP growth. However, it is inappropriate to use it as the only indicator. The reasons are given in 3.4.\nFor better presentation purpose, we are not showing the analysis for the other 4 countries here because it only requires us to change the country name and code based on our current code. However, we find that in some other countries, for example in China, the coefficient for skyscrapers count in the regression is actually positive: skyscrapers count and GDP growth move in the same direction. So, the skyscrapers index does not have predicting power in those conutries. We come up with two possible explanations for China. The first explanation is China has never suffered from a \"real\" recession even in 2008. The economic growth allows the country to build more and more skyscrapers. If it is true, we can add China into a validation set to check if the huge number of skyscrapers built will lead to China's future recession. The second explanation is the country has a tradition of \"showing off\". People build skyscrapers even in bad years. If it is ture, we may confirm skyscrapers index is not a good indicator of recession for China and similar countries.\nTo figure out the features for countries in which the skyscrapers index has a strong predictive power for recession is a topic worth further researching. The further research requires more countries' data in more dimensions. Principal component analysis, cluster analysis and some machine learning models would help."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
eds-uga/csci1360e-su17
|
assignments/A1/A1_Q2.ipynb
|
mit
|
[
"Q2\nIn this question, we'll dive a bit deeper into some arithmetic operations.\nPart A\nFive numbers are given below. Keeping them in that same order, compute a single result with Python addition, multiplication, subtraction, and division, respectively.\nPut another way--add the first and second numbers, multiply the second and third numbers, subtract the third and fourth numbers, and divide the fourth and fifth numbers. Don't use any parentheses; let order of operations take care of things. Do this in a single statement, and store the result in the result variable below.",
"n1 = 0.4589\nn2 = 13\nn3 = -59\nn4 = 8.43333333\nn5 = 2.1\n\nresult = -1\n\n### BEGIN SOLUTION\n\n### END SOLUTION\n\nimport numpy as np\nnp.testing.assert_allclose(result, -770.5569730142857)",
"Part B\nUsing the same five numbers as before, this time use parentheses around your arithmetic operation to enforce that the addition and subtraction operations should happen before the others. Again, store your result in the variable result.",
"n1 = 0.4589\nn2 = 13\nn3 = -59\nn4 = 8.43333333\nn5 = 2.1\n\nresult = -1\n\n### BEGIN SOLUTION\n\n### END SOLUTION\n\nimport numpy as np\nnp.testing.assert_allclose(result, -432.1802333119699)",
"Part C\nRepeat the steps you took in Part B, this time casting each variable to an integer data type before performing any computation. Store your answer in the variable result.",
"n1 = 0.4589\nn2 = 13\nn3 = -59\nn4 = 8.43333333\nn5 = 2.1\n\nresult = -1\n\n### BEGIN SOLUTION\n\n### END SOLUTION\n\nassert result == -435.5",
"Part D\nTwo numbers are given below. When you perform the operation n1 / n2, what is the quotient? Store this quantity in the variable named quotient.",
"n1 = 20344983945038.48374839\nn2 = 984374.783894273\n\nquotient = -1\n\n### BEGIN SOLUTION\n\n### END SOLUTION\n\nimport numpy as np\nnp.testing.assert_allclose(quotient, 20667924.735487375)",
"Part E\nYou've seen in lecture how, when two numbers in Python are divided, their result is a float. What if you really wanted the output of division to be an integer? See if you can make that happen by modifying the following single line of code.\n(You are not allowed to add any numbers or additional lines of code!)",
"integer_quotient = 32 / 16\n\nassert type(integer_quotient) == int"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
rochefort-lab/fissa
|
examples/Basic usage - Function.ipynb
|
gpl-3.0
|
[
"Basic FISSA usage\nThis notebook contains a step-by-step example of how to use the function-based high-level interface to the FISSA toolbox, fissa.run_fissa.\nFor more details about the methodology behind FISSA, please see our paper:\nKeemink, S. W., Lowe, S. C., Pakan, J. M. P., Dylda, E., van Rossum, M. C. W., and Rochefort, N. L. FISSA: A neuropil decontamination toolbox for calcium imaging signals, Scientific Reports, 8(1):3493, 2018. doi: 10.1038/s41598-018-21640-2.\nSee basic_usage_func.py (or basic_usage_func_windows.py for Windows users) for a short example script outside of a notebook interface.\nImport packages\nFirst, we need to import fissa.",
"# Import the FISSA toolbox\nimport fissa",
"We also need to import some plotting dependencies which we'll make use in this notebook to display the results.",
"# For plotting our results, import numpy and matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Fetch the colormap object for Cynthia Brewer's Paired color scheme\ncolors = plt.get_cmap(\"Paired\")",
"Running FISSA\nWith the function-based interface to FISSA, everything is handled in a single function call to fissa.run_fissa. The function takes as its input is the raw signals, and returns the decontaminated signals.\nThe mandatory inputs to fissa.run_fissa are:\n\nthe experiment images\nthe regions of interest (ROIs) to extract\n\nImages can be given as a path to a folder containing tiff stacks:\npython\nimages = \"folder\"\nEach of these tiff-stacks in the folder (e.g. \"folder/trial_001.tif\") is a trial with many frames.\nAlthough we refer to one trial as an image, it is actually a video recording.\nAlternatively, the image data can be given as a list of paths to tiffs:\npython\nimages = [\"folder/trial_001.tif\", \"folder/trial_002.tif\", \"folder/trial_003.tif\"]\nor as a list of arrays which you have already loaded into memory:\npython\nimages = [array1, array2, array3, ...]\nFor the regions of interest (ROIs) input, you can either provide a single set of ROIs, or a set of ROIs for every image.\nIf the ROIs were defined using ImageJ, use ImageJ's export function to save them in a zip.\nThen, provide the ROI filename.\npython\nrois = \"rois.zip\" # for a single set of ROIs used across all images\nThe same set of ROIs will be used for every image in images.\nSometimes there is motion between trials causing the alignment of the ROIs to drift.\nIn such a situation, you may need to use a slightly different location of the ROIs for each trial.\nThis can be handled by providing FISSA with a list of ROI sets — one ROI set (i.e. one ImageJ zip file) per trial.\npython\nrois = [\"rois1.zip\", \"rois2.zip\", ...] # for a unique roiset for each image\nPlease note that the ROIs defined in each ROI set must correspond to the same physical reigons across all trials, and that the order must be consistent.\nThat is to say, the 1st ROI listed in each ROI set must correspond to the same item appearing in each trial, etc.\nIn this notebook, we will demonstrate how to use FISSA with ImageJ ROI sets, saved as zip files.\nHowever, you are not restricted to providing your ROIs to FISSA in this format.\nFISSA will also accept ROIs which are arbitrarily defined by providing them as arrays (numpy.ndarray objects).\nROIs provided in this way can be defined either as boolean-valued masks indicating the presence of a ROI per-pixel in the image, or defined as a list of coordinates defining the boundary of the ROI.\nFor examples of such usage, see our Suite2p, CNMF, and SIMA example notebooks.\nAs an example, we will run FISSA on a small test dataset.\nThe test dataset can be found and downloaded from the examples folder of the fissa repository, along with the source for this example notebook.",
"# Define path to imagery and to the ROI set\nimages_location = \"exampleData/20150529\"\nrois_location = \"exampleData/20150429.zip\"\n\n# Call FISSA using the function-based interface\nresult, raw = fissa.run_fissa(images_location, rois_location)",
"The function-based interface is very straight forward, but note that you can only access the result which is returned by the function.\nIf you need to access the raw traces, ROI masks, or demixing matrix, you need to use the more flexible object-oriented (class based) interface using fissa.Experiment instead.\nAn example of this is given in our object-oriented example usage notebook.\nWorking with results\nThe output of fissa.run_fissa is structured as a 2-d array of 2-d arrays (it can't be a 4-d array because of trials generally don't have the same number of frames).\nThe results from the cell (ROI) numbered c and the trial (TIFF) numbered t are located at result[c, t][0, :].\nThe fourth and final dimension works through frames within the TIFF file (time).\nThe third dimension iterates over output signals.\nThe 0-th entry of this is the signal which most closely corresponds to the raw signal within the ROI, and is FISSA's best guess for the decontaminated cell source signal.\nThe other signals are the isolated signals from contaminants such as neuropil and neighbouring cells.\nLet's compare the raw signal to the separated signal for a single trial from an example ROI.",
"# Plot sample trace\n\n# Select the ROI and trial to plot\nroi = 2\ntrial = 1\n\n# Create the figure\nplt.figure(figsize=(12, 6))\n\nplt.plot(\n raw[roi, trial][0, :],\n lw=2,\n label=\"Raw\",\n color=colors((roi * 2) % colors.N),\n)\nplt.plot(\n result[roi, trial][0, :],\n lw=2,\n label=\"Decontaminated\",\n color=colors((roi * 2 + 1) % colors.N),\n)\n\nplt.title(\"ROI {}, Trial {}\".format(roi, trial), fontsize=15)\nplt.xlabel(\"Time (frame number)\", fontsize=15)\nplt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\nplt.grid()\nplt.legend()\nplt.show()",
"Let's next plot the traces across all ROIs and trials.",
"# Plot all ROIs and trials\n\n# Get the number of ROIs and trials\nn_roi = result.shape[0]\nn_trial = result.shape[1]\n\n# Find the maximum signal intensities for each ROI\nroi_max_raw = [\n np.max([np.max(raw[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n for i_roi in range(n_roi)\n]\nroi_max_result = [\n np.max([np.max(result[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n for i_roi in range(n_roi)\n]\nroi_max = np.maximum(roi_max_raw, roi_max_result)\n\n# Plot our figure using subplot panels\nplt.figure(figsize=(16, 10))\nfor i_roi in range(n_roi):\n for i_trial in range(n_trial):\n # Make subplot axes\n i_subplot = 1 + i_trial * n_roi + i_roi\n plt.subplot(n_trial, n_roi, i_subplot)\n # Plot the data\n plt.plot(\n raw[i_roi][i_trial][0, :],\n label=\"Raw\",\n color=colors((i_roi * 2) % colors.N),\n )\n plt.plot(\n result[i_roi][i_trial][0, :],\n label=\"Decontaminated\",\n color=colors((i_roi * 2 + 1) % colors.N),\n )\n # Labels and boiler plate\n plt.ylim([-0.05 * roi_max[i_roi], roi_max[i_roi] * 1.05])\n if i_roi == 0:\n plt.ylabel(\n \"Trial {}\\n\\nSignal intensity\\n(candela per unit area)\".format(\n i_trial + 1\n )\n )\n if i_trial == 0:\n plt.title(\"ROI {}\".format(i_roi))\n plt.legend()\n if i_trial == n_trial - 1:\n plt.xlabel(\"Time (frame number)\")\n\nplt.show()",
"Comparing ROI signal to neuropil region signals\nIt can be very instructive to compare the signal in the central ROI with the surrounding neuropil regions. These can be found for cell c and trial t in raw[c, t][i, :], with i=0 being the cell, and i=1,2,3,... indicating the surrounding regions.\nBelow we compare directly the raw ROI trace, the decontaminated trace, and the surrounding neuropil region traces.",
"# Get the number of neuropil/surrounding regions.\n# The raw data has the raw ROI signal in raw[:, :][0] and raw surround\n# signals in the rest of the 3rd dimension.\nnRegions = raw[0, 0].shape[0] - 1\n\n# Select the ROI and trial to plot\nroi = 2\ntrial = 1\n\n# Create the figure\nplt.figure(figsize=(12, 12))\n\n# Plot extracted traces for each neuropil subregion\nplt.subplot(2, 1, 1)\n# Plot trace of raw ROI signal\nplt.plot(\n raw[roi, trial][0, :],\n lw=2,\n label=\"Raw ROI signal\",\n color=colors((roi * 2) % colors.N),\n)\n# Plot traces from each neuropil region\nfor i_neuropil in range(1, nRegions + 1):\n alpha = i_neuropil / nRegions\n plt.plot(\n raw[roi, trial][i_neuropil, :],\n lw=2,\n label=\"Neuropil region {}\".format(i_neuropil),\n color=\"k\",\n alpha=alpha,\n )\nplt.ylim([0, 125])\nplt.grid()\nplt.legend()\nplt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\nplt.title(\"ROI {}, Trial {}, neuropil region traces\".format(roi, trial), fontsize=15)\n\n# Plot the ROI signal\nplt.subplot(2, 1, 2)\n# Plot trace of raw ROI signal\nplt.plot(raw[roi, trial][0, :], lw=2, label=\"Raw\", color=colors((roi * 2) % colors.N))\n# Plot decontaminated signal matched to the ROI\nplt.plot(\n result[roi, trial][0, :],\n lw=2,\n label=\"Decontaminated\",\n color=colors((roi * 2 + 1) % colors.N),\n)\n\nplt.ylim([0, 125])\nplt.grid()\nplt.legend()\nplt.xlabel(\"Time (frame number)\", fontsize=15)\nplt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\nplt.title(\"ROI {}, Trial {}, raw and decontaminated\".format(roi, trial), fontsize=15)\n\nplt.show()",
"df/f<sub>0</sub>\nThe default output from fissa.run_fissa is in the same units as the raw input (candelas per unit area).\nIt is often desirable to calculate the intensity of a signal relative to the baseline value, df/f<sub>0</sub>, for the traces.\nfissa.run_fissa will do this for you provide the argument return_deltaf=True, and the sampling frequency of your TIFF files with freq=sample_frequency.\nThe sampling frequency must be provided because the data is smoothed in order to determine the baseline value f<sub>0</sub>.\nWhen return_deltaf=True, run_fissa will return the df/f<sub>0</sub> output instead of the source signal traces scaled at the recording intensity.\nIf you need to access both the standard FISSA output and the df/f<sub>0</sub> output at the same time, you need to use the more flexible fissa.Experiment FISSA interface instead, as described in this example.",
"sample_frequency = 10 # Hz\n\ndeltaf_result, deltaf_raw = fissa.run_fissa(\n images_location, rois_location, freq=sample_frequency, return_deltaf=True\n)",
"Note that by default, f<sub>0</sub> is determined as the minimum across all trials (all TIFFs) to ensure that results are directly comparable between trials, but you can normalise each trial individually instead if you prefer by providing the parameter deltaf_across_trials=False.",
"# Plot sample trace\n\n# Select the ROI and trial to plot\nroi = 2\ntrial = 1\n\n# Create the figure\nplt.figure(figsize=(12, 6))\n\nplt.plot(\n deltaf_raw[roi, trial][0, :],\n lw=2,\n label=\"Raw\",\n color=colors((roi * 2) % colors.N),\n)\nplt.plot(\n deltaf_result[roi, trial][0, :],\n lw=2,\n label=\"Decontaminated\",\n color=colors((roi * 2 + 1) % colors.N),\n)\n\nplt.title(\"ROI {}, Trial {}\".format(roi, trial), fontsize=15)\nplt.xlabel(\"Time (frame number)\", fontsize=15)\nplt.ylabel(r\"$\\Delta f\\,/\\,f_0$\", fontsize=15)\nplt.grid()\nplt.legend()\nplt.show()",
"Since FISSA is very good at removing contamination from the ROI signals, the minimum value on the decontaminated trace will typically be 0..\nConsequently, we use the minimum value of the (smoothed) raw signal to provide the f<sub>0</sub> from the raw trace for both the raw and decontaminated df/f<sub>0</sub>.\nWe can plot the df/f<sub>0</sub> for every cell during every trial as follows.",
"# Get the number of ROIs and trials\nn_roi = result.shape[0]\nn_trial = result.shape[1]\n\n# Find the maximum signal intensities for each ROI,\n# so we can scale ylim the same across subplots\nroi_max = [\n np.max([np.max(result[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n for i_roi in range(n_roi)\n]\n\n# Plot our figure using subplot panels\nplt.figure(figsize=(16, 10))\nfor i_roi in range(n_roi):\n for i_trial in range(n_trial):\n # Make subplot axes\n i_subplot = 1 + i_trial * n_roi + i_roi\n plt.subplot(n_trial, n_roi, i_subplot)\n # Plot the data\n plt.plot(\n result[i_roi][i_trial][0, :],\n color=colors((i_roi * 2 + 1) % colors.N),\n )\n # Labels and boiler plate\n plt.ylim([-0.05 * roi_max[i_roi], roi_max[i_roi] * 1.05])\n if i_roi == 0:\n plt.ylabel(\"Trial {}\\n\\n\".format(i_trial + 1) + r\"$\\Delta f\\,/\\,f_0$\")\n if i_trial == 0:\n plt.title(\"ROI {}\".format(i_roi))\n if i_trial == n_trial - 1:\n plt.xlabel(\"Time (frame number)\")\n\nplt.show()",
"For comparison purposes, we can also plot the df/f<sub>0</sub> for the raw data against the decontaminated signal.",
"# Plot all ROIs and trials\n\n# Get the number of ROIs and trials\nn_roi = deltaf_result.shape[0]\nn_trial = deltaf_result.shape[1]\n\n# Find the maximum signal intensities for each ROI\nroi_max_raw = [\n np.max([np.max(deltaf_raw[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n for i_roi in range(n_roi)\n]\nroi_max_result = [\n np.max([np.max(deltaf_result[i_roi, i_trial][0]) for i_trial in range(n_trial)])\n for i_roi in range(n_roi)\n]\nroi_max = np.maximum(roi_max_raw, roi_max_result)\n\n# Plot our figure using subplot panels\nplt.figure(figsize=(16, 10))\nfor i_roi in range(n_roi):\n for i_trial in range(n_trial):\n # Make subplot axes\n i_subplot = 1 + i_trial * n_roi + i_roi\n plt.subplot(n_trial, n_roi, i_subplot)\n # Plot the data\n plt.plot(\n deltaf_raw[i_roi][i_trial][0, :],\n label=\"Raw\",\n color=colors((i_roi * 2) % colors.N),\n )\n plt.plot(\n deltaf_result[i_roi][i_trial][0, :],\n label=\"Decontaminated\",\n color=colors((i_roi * 2 + 1) % colors.N),\n )\n # Labels and boiler plate\n plt.ylim([-0.05 * roi_max[i_roi], roi_max[i_roi] * 1.05])\n if i_roi == 0:\n plt.ylabel(\"Trial {}\\n\\n\".format(i_trial + 1) + r\"$\\Delta f\\,/\\,f_0$\")\n if i_trial == 0:\n plt.title(\"ROI {}\".format(i_roi))\n plt.legend()\n if i_trial == n_trial - 1:\n plt.xlabel(\"Time (frame number)\")\n\nplt.show()",
"Caching\nAfter using FISSA to decontaminate the data collected in an experiment, you will probably want to save the output for later use, so you don't have to keep re-running FISSA on the data.\nTo facilitate this, an option to cache the outputs is built into FISSA.\nIf you provide fissa.run_fissa with an identifier to the experiment being analysed in the folder argument, it will cache results into the corresponding directory.\nLater, if you call fissa.run_fissa again with the same folder argument, it will load the saved results from that cache folder instead of recomputing them.",
"# Define the folder where FISSA's outputs will be cached, so they can be\n# quickly reloaded in the future without having to recompute them.\n#\n# This argument is optional; if it is not provided, FISSA will not save its\n# results for later use.\n#\n# If the output directory already exists, FISSA will load the contents of\n# the cache instead of recomputing it.\n#\n# Note: you *must* use a different folder for each experiment, otherwise\n# FISSA will load the existing data instead of computing results for the\n# new experiment.\n#\n# In this example, we will use the current datetime as the name of the\n# experiment, but you can name your experiments however you want to.\n# If you want to take advantage of the caching of results, you should use\n# a more descriptive name than this so you can identify the actual\n# dataset that the FISSA results correspond to, and load them appropriately.\n\nimport datetime\n\noutput_folder = \"fissa-example_{}\".format(\n datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n)\n\nprint(output_folder)",
"Let's run FISSA on this experiment again, but this time save the results to the experiment's output directory.",
"# Run FISSA, saving to results to output_folder\nresult, raw = fissa.run_fissa(images_location, rois_location, folder=output_folder)",
"A subsequent call to fissa.run_fissa which uses the same experiment folder argument will load the cached data instead of re-running the FISSA signal separation routine from scratch.",
"# Run FISSA, loading results from cache in output_folder\nresult, raw = fissa.run_fissa(images_location, rois_location, folder=output_folder)",
"Exporting to MATLAB\nThe results can easily be exported to a MATLAB-compatible MAT-file as follows.\nIf we provide export_to_matfile=True to fissa.run_fissa, it will export the data a matfile named \"separated.mat\" within the cache directory (the cache directory as provided with the folder argument).",
"result, raw = fissa.run_fissa(\n images_location, rois_location, folder=output_folder, export_to_matfile=True\n)",
"Alternatively, we can export to a matfile with a custom file name by setting the export_to_matfile argument to the target path.",
"result, raw = fissa.run_fissa(\n images_location, rois_location, export_to_matfile=\"experiment_results.mat\"\n)",
"Loading the generated file (e.g. \"output_folder/separated.mat\") in MATLAB will provide you with all of FISSA's outputs.\nThese are structured in the same way as the raw and result variables returned by fissa.run_fissa.\nWith the python interface, the outputs are 2d numpy.ndarrays each element of which is itself a 2d numpy.ndarrays.\nMeanwhile, when the output is loaded into MATLAB the data is structured as a 2d cell-array each element of which is a 2d matrix.\nAdditionally, note that whilst Python indexes from 0, MATLAB indexes from 1 instead.\nAs a consequence of this, the results seen on Python for a given roi and trial experiment.result[roi, trial] correspond to the index S.result{roi + 1, trial + 1} on MATLAB.\nOur first plot in this notebook can be replicated in MATLAB as follows:\noctave\n%% Plot example traces in MATLAB\n% Load FISSA output data in MATLAB\n% ... either from the automatic file name within a cache\n% S = load('fissa-example/separated.mat')\n% ... or from a custom output path\nS = load('experiment_results.mat')\n% Select the second trial\n% (On Python, this would be trial = 1)\ntrial = 2;\n% Plot the result traces for each ROI\nfigure;\nhold on;\nfor i_roi = 1:size(S.result, 1);\n plot(S.result{i_roi, trial}(1, :));\nend\nxlabel('Time (frame number)');\nylabel('Signal intensity (candela per unit area)');\ngrid on;\nbox on;\nset(gca,'TickDir','out');\nCustomisation\nControlling verbosity\nThe level of verbosity of FISSA can be controlled with the verbosity parameter.\nThe default is verbosity=1.\nIf the verbosity parameter is higher, FISSA will print out more information while it is processing.\nThis can be helpful for debugging puproses.\nThe verbosity reaches its maximum at verbosity=6.\nIf verbosity=0, FISSA will run silently.",
"# Call FISSA with elevated verbosity\nresult = fissa.run_fissa(images_location, rois_location, verbosity=2)",
"Analysis parameters\nFISSA has several user-definable settings, which can be set as optional arguments to fissa.run_fissa.",
"# FISSA uses multiprocessing to speed up its processing.\n# By default, it will spawn one worker per CPU core on your machine.\n# However, if you have a lot of cores and not much memory, you many not\n# be able to suport so many workers simultaneously.\n# In particular, this can be problematic during the data preparation step\n# in which TIFFs are loaded into memory.\n# The default number of cores for the data preparation and separation steps\n# can be changed as follows.\nncores_preparation = 4 # If None, uses all available cores\nncores_separation = None # if None, uses all available cores\n\n# By default, FISSA uses 4 subregions for the neuropil region.\n# If you have very dense data with a lot of different signals per unit area,\n# you may wish to increase the number of regions.\nn_regions = 8\n\n# By default, each surrounding region has the same area as the central ROI.\n# i.e. expansion = 1\n# However, you may wish to increase or decrease this value.\nexpansion = 0.75\n\n# The degree of signal sparsity can be controlled with the alpha parameter.\nalpha = 0.02\n\n# If you change the experiment parameters, you need to change the cache directory too.\n# Otherwise FISSA will try to reload the results from the previous run instead of\n# computing the new results. FISSA will throw an error if you try to load data which\n# was generated with different analysis parameters to the current parameters.\noutput_folder2 = output_folder + \"_alt\"\n\n# Run FISSA with these parameters\nresult, raw = fissa.run_fissa(\n images_location,\n rois_location,\n output_folder2,\n nRegions=n_regions,\n expansion=expansion,\n alpha=alpha,\n ncores_preparation=ncores_preparation,\n ncores_separation=ncores_separation,\n)",
"We can plot the new results for our example trace from before. Although we doubled the number of neuropil regions around the cell, very little has changed for this example because there were not many sources of contamination.\nHowever, there will be more of a difference if your data has more neuropil sources per unit area within the image.",
"n_roi = result.shape[0]\nn_trial = result.shape[1]\n\ni_roi = 3\n\nplt.figure(figsize=(12, 6))\n\nfor i_trial in range(n_trial):\n plt.plot(result[i_roi, i_trial][0, :], label=\"Trial {}\".format(i_trial + 1))\n\nplt.title(\"ROI {}\".format(i_roi), fontsize=15)\nplt.xlabel(\"Time (Frame number)\", fontsize=15)\nplt.ylabel(\"Signal intensity (candela per unit area)\", fontsize=15)\nplt.grid()\nplt.legend()\nplt.show()",
"Working with very large tiff files\nBy default, FISSA loads entire TIFF files into memory at once and then manipulates all ROIs within the TIFF.\nThis is more efficient, but can be problematic when working with very large TIFF files which are too big to be loaded into memory all at once.\nIf you run out of memory when running FISSA, you can try reducing the number of workers during the memory-intensive preparation step.",
"result = fissa.run_fissa(images_location, rois_location, ncores_preparation=1)",
"Alternatively, you can activate FISSA's low memory mode.\nIn this mode, it will load and process frames one at a time.\nThis will run a fair bit slower than the default mode, but has a much lower memory requirement.",
"result, raw = fissa.run_fissa(images_location, rois_location, lowmemory_mode=True)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
ThyrixYang/LearningNotes
|
MOOC/stanford_cnn_cs231n/assignment2/BatchNormalization.ipynb
|
gpl-3.0
|
[
"Batch Normalization\nOne way to make deep networks easier to train is to use more sophisticated optimization procedures such as SGD+momentum, RMSProp, or Adam. Another strategy is to change the architecture of the network to make it easier to train. One idea along these lines is batch normalization which was recently proposed by [3].\nThe idea is relatively straightforward. Machine learning methods tend to work better when their input data consists of uncorrelated features with zero mean and unit variance. When training a neural network, we can preprocess the data before feeding it to the network to explicitly decorrelate its features; this will ensure that the first layer of the network sees data that follows a nice distribution. However even if we preprocess the input data, the activations at deeper layers of the network will likely no longer be decorrelated and will no longer have zero mean or unit variance since they are output from earlier layers in the network. Even worse, during the training process the distribution of features at each layer of the network will shift as the weights of each layer are updated.\nThe authors of [3] hypothesize that the shifting distribution of features inside deep neural networks may make training deep networks more difficult. To overcome this problem, [3] proposes to insert batch normalization layers into the network. At training time, a batch normalization layer uses a minibatch of data to estimate the mean and standard deviation of each feature. These estimated means and standard deviations are then used to center and normalize the features of the minibatch. A running average of these means and standard deviations is kept during training, and at test time these running averages are used to center and normalize features.\nIt is possible that this normalization strategy could reduce the representational power of the network, since it may sometimes be optimal for certain layers to have features that are not zero-mean or unit variance. To this end, the batch normalization layer includes learnable shift and scale parameters for each feature dimension.\n[3] Sergey Ioffe and Christian Szegedy, \"Batch Normalization: Accelerating Deep Network Training by Reducing\nInternal Covariate Shift\", ICML 2015.",
"# As usual, a bit of setup\nfrom __future__ import print_function\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom cs231n.classifiers.fc_net import *\nfrom cs231n.data_utils import get_CIFAR10_data\nfrom cs231n.gradient_check import eval_numerical_gradient, eval_numerical_gradient_array\nfrom cs231n.solver import Solver\n\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# for auto-reloading external modules\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\ndef rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n\n# Load the (preprocessed) CIFAR10 data.\n\ndata = get_CIFAR10_data()\nfor k, v in data.items():\n print('%s: ' % k, v.shape)",
"Batch normalization: Forward\nIn the file cs231n/layers.py, implement the batch normalization forward pass in the function batchnorm_forward. Once you have done so, run the following to test your implementation.",
"# Check the training-time forward pass by checking means and variances\n# of features both before and after batch normalization\n\n# Simulate the forward pass for a two-layer network\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nX = np.random.randn(N, D1)\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\na = np.maximum(0, X.dot(W1)).dot(W2)\n\nprint('Before batch normalization:')\nprint(' means: ', a.mean(axis=0))\nprint(' stds: ', a.std(axis=0))\n\n# Means should be close to zero and stds close to one\nprint('After batch normalization (gamma=1, beta=0)')\na_norm, _ = batchnorm_forward(a, np.ones(D3), np.zeros(D3), {'mode': 'train'})\nprint(' mean: ', a_norm.mean(axis=0))\nprint(' std: ', a_norm.std(axis=0))\n\n# Now means should be close to beta and stds close to gamma\ngamma = np.asarray([1.0, 2.0, 3.0])\nbeta = np.asarray([11.0, 12.0, 13.0])\na_norm, _ = batchnorm_forward(a, gamma, beta, {'mode': 'train'})\nprint('After batch normalization (nontrivial gamma, beta)')\nprint(' means: ', a_norm.mean(axis=0))\nprint(' stds: ', a_norm.std(axis=0))\n\n# Check the test-time forward pass by running the training-time\n# forward pass many times to warm up the running averages, and then\n# checking the means and variances of activations after a test-time\n# forward pass.\nnp.random.seed(231)\nN, D1, D2, D3 = 200, 50, 60, 3\nW1 = np.random.randn(D1, D2)\nW2 = np.random.randn(D2, D3)\n\nbn_param = {'mode': 'train'}\ngamma = np.ones(D3)\nbeta = np.zeros(D3)\nfor t in range(50):\n X = np.random.randn(N, D1)\n a = np.maximum(0, X.dot(W1)).dot(W2)\n batchnorm_forward(a, gamma, beta, bn_param)\nbn_param['mode'] = 'test'\nX = np.random.randn(N, D1)\na = np.maximum(0, X.dot(W1)).dot(W2)\na_norm, _ = batchnorm_forward(a, gamma, beta, bn_param)\n\n# Means should be close to zero and stds close to one, but will be\n# noisier than training-time forward passes.\nprint('After batch normalization (test-time):')\nprint(' means: ', a_norm.mean(axis=0))\nprint(' stds: ', a_norm.std(axis=0))",
"Batch Normalization: backward\nNow implement the backward pass for batch normalization in the function batchnorm_backward.\nTo derive the backward pass you should write out the computation graph for batch normalization and backprop through each of the intermediate nodes. Some intermediates may have multiple outgoing branches; make sure to sum gradients across these branches in the backward pass.\nOnce you have finished, run the following to numerically check your backward pass.",
"# Gradient check batchnorm backward pass\nnp.random.seed(231)\nN, D = 4, 5\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nfx = lambda x: batchnorm_forward(x, gamma, beta, bn_param)[0]\nfg = lambda a: batchnorm_forward(x, a, beta, bn_param)[0]\nfb = lambda b: batchnorm_forward(x, gamma, b, bn_param)[0]\n\ndx_num = eval_numerical_gradient_array(fx, x, dout)\nda_num = eval_numerical_gradient_array(fg, gamma.copy(), dout)\ndb_num = eval_numerical_gradient_array(fb, beta.copy(), dout)\n\n_, cache = batchnorm_forward(x, gamma, beta, bn_param)\ndx, dgamma, dbeta = batchnorm_backward(dout, cache)\nprint('dx error: ', rel_error(dx_num, dx))\nprint('dgamma error: ', rel_error(da_num, dgamma))\nprint('dbeta error: ', rel_error(db_num, dbeta))",
"Batch Normalization: alternative backward (OPTIONAL, +3 points extra credit)\nIn class we talked about two different implementations for the sigmoid backward pass. One strategy is to write out a computation graph composed of simple operations and backprop through all intermediate values. Another strategy is to work out the derivatives on paper. For the sigmoid function, it turns out that you can derive a very simple formula for the backward pass by simplifying gradients on paper.\nSurprisingly, it turns out that you can also derive a simple expression for the batch normalization backward pass if you work out derivatives on paper and simplify. After doing so, implement the simplified batch normalization backward pass in the function batchnorm_backward_alt and compare the two implementations by running the following. Your two implementations should compute nearly identical results, but the alternative implementation should be a bit faster.\nNOTE: This part of the assignment is entirely optional, but we will reward 3 points of extra credit if you can complete it.",
"np.random.seed(231)\nN, D = 100, 500\nx = 5 * np.random.randn(N, D) + 12\ngamma = np.random.randn(D)\nbeta = np.random.randn(D)\ndout = np.random.randn(N, D)\n\nbn_param = {'mode': 'train'}\nout, cache = batchnorm_forward(x, gamma, beta, bn_param)\n\nt1 = time.time()\ndx1, dgamma1, dbeta1 = batchnorm_backward(dout, cache)\nt2 = time.time()\ndx2, dgamma2, dbeta2 = batchnorm_backward_alt(dout, cache)\nt3 = time.time()\n\nprint('dx difference: ', rel_error(dx1, dx2))\nprint('dgamma difference: ', rel_error(dgamma1, dgamma2))\nprint('dbeta difference: ', rel_error(dbeta1, dbeta2))\nprint('speedup: %.2fx' % ((t2 - t1) / (t3 - t2)))",
"Fully Connected Nets with Batch Normalization\nNow that you have a working implementation for batch normalization, go back to your FullyConnectedNet in the file cs2312n/classifiers/fc_net.py. Modify your implementation to add batch normalization.\nConcretely, when the flag use_batchnorm is True in the constructor, you should insert a batch normalization layer before each ReLU nonlinearity. The outputs from the last layer of the network should not be normalized. Once you are done, run the following to gradient-check your implementation.\nHINT: You might find it useful to define an additional helper layer similar to those in the file cs231n/layer_utils.py. If you decide to do so, do it in the file cs231n/classifiers/fc_net.py.",
"np.random.seed(231)\nN, D, H1, H2, C = 2, 15, 20, 30, 10\nX = np.random.randn(N, D)\ny = np.random.randint(C, size=(N,))\n\nfor reg in [0, 3.14]:\n print('Running check with reg = ', reg)\n model = FullyConnectedNet([H1, H2], input_dim=D, num_classes=C,\n reg=reg, weight_scale=5e-2, dtype=np.float64,\n use_batchnorm=True)\n\n loss, grads = model.loss(X, y)\n print('Initial loss: ', loss)\n\n for name in sorted(grads):\n f = lambda _: model.loss(X, y)[0]\n grad_num = eval_numerical_gradient(f, model.params[name], verbose=False, h=1e-5)\n print('%s relative error: %.2e' % (name, rel_error(grad_num, grads[name])))\n if reg == 0: print()",
"Batchnorm for deep networks\nRun the following to train a six-layer network on a subset of 1000 training examples both with and without batch normalization.",
"np.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [100, 100, 100, 100, 100]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nweight_scale = 2e-2\nbn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=True)\nmodel = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=False)\n\nbn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=200)\nbn_solver.train()\n\nsolver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=True, print_every=200)\nsolver.train()",
"Run the following to visualize the results from two networks trained above. You should find that using batch normalization helps the network to converge much faster.",
"plt.subplot(3, 1, 1)\nplt.title('Training loss')\nplt.xlabel('Iteration')\n\nplt.subplot(3, 1, 2)\nplt.title('Training accuracy')\nplt.xlabel('Epoch')\n\nplt.subplot(3, 1, 3)\nplt.title('Validation accuracy')\nplt.xlabel('Epoch')\n\nplt.subplot(3, 1, 1)\nplt.plot(solver.loss_history, 'o', label='baseline')\nplt.plot(bn_solver.loss_history, 'o', label='batchnorm')\n\nplt.subplot(3, 1, 2)\nplt.plot(solver.train_acc_history, '-o', label='baseline')\nplt.plot(bn_solver.train_acc_history, '-o', label='batchnorm')\n\nplt.subplot(3, 1, 3)\nplt.plot(solver.val_acc_history, '-o', label='baseline')\nplt.plot(bn_solver.val_acc_history, '-o', label='batchnorm')\n \nfor i in [1, 2, 3]:\n plt.subplot(3, 1, i)\n plt.legend(loc='upper center', ncol=4)\nplt.gcf().set_size_inches(15, 15)\nplt.show()",
"Batch normalization and initialization\nWe will now run a small experiment to study the interaction of batch normalization and weight initialization.\nThe first cell will train 8-layer networks both with and without batch normalization using different scales for weight initialization. The second layer will plot training accuracy, validation set accuracy, and training loss as a function of the weight initialization scale.",
"np.random.seed(231)\n# Try training a very deep net with batchnorm\nhidden_dims = [50, 50, 50, 50, 50, 50, 50]\n\nnum_train = 1000\nsmall_data = {\n 'X_train': data['X_train'][:num_train],\n 'y_train': data['y_train'][:num_train],\n 'X_val': data['X_val'],\n 'y_val': data['y_val'],\n}\n\nbn_solvers = {}\nsolvers = {}\nweight_scales = np.logspace(-4, 0, num=20)\nfor i, weight_scale in enumerate(weight_scales):\n print('Running weight scale %d / %d' % (i + 1, len(weight_scales)))\n bn_model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=True)\n model = FullyConnectedNet(hidden_dims, weight_scale=weight_scale, use_batchnorm=False)\n\n bn_solver = Solver(bn_model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n bn_solver.train()\n bn_solvers[weight_scale] = bn_solver\n\n solver = Solver(model, small_data,\n num_epochs=10, batch_size=50,\n update_rule='adam',\n optim_config={\n 'learning_rate': 1e-3,\n },\n verbose=False, print_every=200)\n solver.train()\n solvers[weight_scale] = solver\n\n# Plot results of weight scale experiment\nbest_train_accs, bn_best_train_accs = [], []\nbest_val_accs, bn_best_val_accs = [], []\nfinal_train_loss, bn_final_train_loss = [], []\n\nfor ws in weight_scales:\n best_train_accs.append(max(solvers[ws].train_acc_history))\n bn_best_train_accs.append(max(bn_solvers[ws].train_acc_history))\n \n best_val_accs.append(max(solvers[ws].val_acc_history))\n bn_best_val_accs.append(max(bn_solvers[ws].val_acc_history))\n \n final_train_loss.append(np.mean(solvers[ws].loss_history[-100:]))\n bn_final_train_loss.append(np.mean(bn_solvers[ws].loss_history[-100:]))\n \nplt.subplot(3, 1, 1)\nplt.title('Best val accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best val accuracy')\nplt.semilogx(weight_scales, best_val_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_val_accs, '-o', label='batchnorm')\nplt.legend(ncol=2, loc='lower right')\n\nplt.subplot(3, 1, 2)\nplt.title('Best train accuracy vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Best training accuracy')\nplt.semilogx(weight_scales, best_train_accs, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_best_train_accs, '-o', label='batchnorm')\nplt.legend()\n\nplt.subplot(3, 1, 3)\nplt.title('Final training loss vs weight initialization scale')\nplt.xlabel('Weight initialization scale')\nplt.ylabel('Final training loss')\nplt.semilogx(weight_scales, final_train_loss, '-o', label='baseline')\nplt.semilogx(weight_scales, bn_final_train_loss, '-o', label='batchnorm')\nplt.legend()\nplt.gca().set_ylim(1.0, 3.5)\n\nplt.gcf().set_size_inches(10, 15)\nplt.show()",
"Question:\nDescribe the results of this experiment, and try to give a reason why the experiment gave the results that it did.\nAnswer:"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
quoniammm/happy-machine-learning
|
Udacity-DL/image_classification_2/dlnd_image_classification.ipynb
|
mit
|
[
"Image Classification\nIn this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images.\nGet the Data\nRun the following cell to download the CIFAR-10 dataset for python.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\nfrom urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\nimport problem_unittests as tests\nimport tarfile\n\ncifar10_dataset_folder_path = 'cifar-10-batches-py'\n\n# Use Floyd's cifar-10 dataset if present\nfloyd_cifar10_location = '/input/cifar-10/python.tar.gz'\nif isfile(floyd_cifar10_location):\n tar_gz_path = floyd_cifar10_location\nelse:\n tar_gz_path = 'cifar-10-python.tar.gz'\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(tar_gz_path):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar:\n urlretrieve(\n 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',\n tar_gz_path,\n pbar.hook)\n\nif not isdir(cifar10_dataset_folder_path):\n with tarfile.open(tar_gz_path) as tar:\n tar.extractall()\n tar.close()\n\n\ntests.test_folder_path(cifar10_dataset_folder_path)",
"Explore the Data\nThe dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:\n* airplane\n* automobile\n* bird\n* cat\n* deer\n* dog\n* frog\n* horse\n* ship\n* truck\nUnderstanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch.\nAsk yourself \"What are all possible labels?\", \"What is the range of values for the image data?\", \"Are the labels in order or random?\". Answers to questions like these will help you preprocess the data and end up with better predictions.",
"%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport helper\nimport numpy as np\n\n# Explore the dataset\nbatch_id = 1\nsample_id = 5\nhelper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)",
"Implement Preprocess Functions\nNormalize\nIn the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x.",
"def normalize(x):\n \"\"\"\n Normalize a list of sample image data in the range of 0 to 1\n : x: List of image data. The image shape is (32, 32, 3)\n : return: Numpy array of normalize data\n \"\"\"\n mini = np.min(x)\n maxi = np.max(x)\n \n return (x-mini)/(maxi-mini)\n # TODO: Implement Function\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_normalize(normalize)",
"One-hot encode\nJust like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function.\nHint: Don't reinvent the wheel.",
"def one_hot_encode(x):\n \"\"\"\n One hot encode a list of sample labels. Return a one-hot encoded vector for each label.\n : x: List of sample Labels\n : return: Numpy array of one-hot encoded labels\n \"\"\"\n # TODO: Implement Function\n values = x\n n_values = np.max(values) + 1\n return np.eye(n_values)[values]\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_one_hot_encode(one_hot_encode)",
"Randomize Data\nAs you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset.\nPreprocess all the data and save it\nRunning the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Preprocess Training, Validation, and Testing Data\nhelper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode)",
"Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport pickle\nimport problem_unittests as tests\nimport helper\n\n# Load the Preprocessed Validation data\nvalid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb'))",
"Build the network\nFor the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project.\n\nNote: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the \"Convolutional and Max Pooling Layer\" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup.\nHowever, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d. \n\nLet's begin!\nInput\nThe neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions\n* Implement neural_net_image_input\n * Return a TF Placeholder\n * Set the shape using image_shape with batch size set to None.\n * Name the TensorFlow placeholder \"x\" using the TensorFlow name parameter in the TF Placeholder.\n* Implement neural_net_label_input\n * Return a TF Placeholder\n * Set the shape using n_classes with batch size set to None.\n * Name the TensorFlow placeholder \"y\" using the TensorFlow name parameter in the TF Placeholder.\n* Implement neural_net_keep_prob_input\n * Return a TF Placeholder for dropout keep probability.\n * Name the TensorFlow placeholder \"keep_prob\" using the TensorFlow name parameter in the TF Placeholder.\nThese names will be used at the end of the project to load your saved model.\nNote: None for shapes in TensorFlow allow for a dynamic size.",
"import tensorflow as tf\n\ndef neural_net_image_input(image_shape):\n \"\"\"\n Return a Tensor for a batch of image input\n : image_shape: Shape of the images\n : return: Tensor for image input.\n \"\"\"\n # TODO: Implement Function\n image_height, image_width, color_channels = image_shape\n return tf.placeholder(tf.float32, shape=[None, image_height, image_width, color_channels], name='x')\n\n\ndef neural_net_label_input(n_classes):\n \"\"\"\n Return a Tensor for a batch of label input\n : n_classes: Number of classes\n : return: Tensor for label input.\n \"\"\"\n return tf.placeholder(tf.float32, [None, n_classes], name='y')\n\n\ndef neural_net_keep_prob_input():\n \"\"\"\n Return a Tensor for keep probability\n : return: Tensor for keep probability.\n \"\"\"\n # TODO: Implement Function\n return tf.placeholder(tf.float32, name='keep_prob')\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntf.reset_default_graph()\ntests.test_nn_image_inputs(neural_net_image_input)\ntests.test_nn_label_inputs(neural_net_label_input)\ntests.test_nn_keep_prob_inputs(neural_net_keep_prob_input)",
"Convolution and Max Pooling Layer\nConvolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:\n* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.\n* Apply a convolution to x_tensor using weight and conv_strides.\n * We recommend you use same padding, but you're welcome to use any padding.\n* Add bias\n* Add a nonlinear activation to the convolution.\n* Apply Max Pooling using pool_ksize and pool_strides.\n * We recommend you use same padding, but you're welcome to use any padding.\nNote: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers.",
"def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):\n \"\"\"\n Apply convolution then max pooling to x_tensor\n :param x_tensor: TensorFlow Tensor\n :param conv_num_outputs: Number of outputs for the convolutional layer\n :param conv_ksize: kernal size 2-D Tuple for the convolutional layer\n :param conv_strides: Stride 2-D Tuple for convolution\n :param pool_ksize: kernal size 2-D Tuple for pool\n :param pool_strides: Stride 2-D Tuple for pool\n : return: A tensor that represents convolution and max pooling of x_tensor\n \"\"\"\n # TODO: Implement Function \n #print(type(conv_ksize[0]))\n #print(type(conv_ksize[1]))\n #print(type(int(x_tensor.get_shape()[3])))\n #print(type(conv_num_outputs))\n \n #conv_ksize[0], conv_ksize[1], int(x_tensor.get_shape()[3]), conv_num_outputs\n \n weight = tf.Variable(tf.truncated_normal([conv_ksize[0], conv_ksize[1], int(x_tensor.get_shape()[3]), conv_num_outputs], stddev=0.1))\n \n bias = tf.Variable(tf.zeros(conv_num_outputs))\n \n conv_layer = tf.nn.conv2d(x_tensor, weight, strides=[1] + list(conv_strides) + [1], padding='SAME')\n conv_layer = tf.nn.bias_add(conv_layer, bias)\n conv_layer = tf.nn.relu(conv_layer)\n conv_layer = tf.nn.max_pool(conv_layer, ksize=[1] + list(pool_ksize) + [1], strides=[1] + list(pool_strides) + [1], padding='SAME')\n \n #print(conv_layer)\n return conv_layer\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_con_pool(conv2d_maxpool)",
"Flatten Layer\nImplement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.",
"def flatten(x_tensor):\n \"\"\"\n Flatten x_tensor to (Batch Size, Flattened Image Size)\n : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.\n : return: A tensor of size (Batch Size, Flattened Image Size).\n \"\"\"\n # TODO: Implement Function\n return tf.contrib.layers.flatten(x_tensor)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_flatten(flatten)",
"Fully-Connected Layer\nImplement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.",
"def fully_conn(x_tensor, num_outputs):\n \"\"\"\n Apply a fully connected layer to x_tensor using weight and bias\n : x_tensor: A 2-D tensor where the first dimension is batch size.\n : num_outputs: The number of output that the new tensor should be.\n : return: A 2-D tensor where the second dimension is num_outputs.\n \"\"\"\n # TODO: Implement Function\n return tf.contrib.layers.fully_connected(x_tensor, num_outputs, activation_fn=None)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_fully_conn(fully_conn)",
"Output Layer\nImplement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.\nNote: Activation, softmax, or cross entropy should not be applied to this.",
"def output(x_tensor, num_outputs):\n \"\"\"\n Apply a output layer to x_tensor using weight and bias\n : x_tensor: A 2-D tensor where the first dimension is batch size.\n : num_outputs: The number of output that the new tensor should be.\n : return: A 2-D tensor where the second dimension is num_outputs.\n \"\"\"\n # TODO: Implement Function\n return tf.contrib.layers.fully_connected(x_tensor, num_outputs, activation_fn=tf.nn.relu)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_output(output)",
"Create Convolutional Model\nImplement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:\n\nApply 1, 2, or 3 Convolution and Max Pool layers\nApply a Flatten Layer\nApply 1, 2, or 3 Fully Connected Layers\nApply an Output Layer\nReturn the output\nApply TensorFlow's Dropout to one or more layers in the model using keep_prob.",
"def conv_net(x, keep_prob):\n \"\"\"\n Create a convolutional neural network model\n : x: Placeholder tensor that holds image data.\n : keep_prob: Placeholder tensor that hold dropout keep probability.\n : return: Tensor that represents logits\n \"\"\"\n # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers\n # Play around with different number of outputs, kernel size and stride\n # Function Definition from Above:\n # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides)\n c1s2 = conv2d_maxpool(x, 6, (5,5), (1,1), (2, 2), (2, 2))\n c3s4 = conv2d_maxpool(c1s2, 16, (5,5), (1,1), (2, 2), (2, 2))\n # TODO: Apply a Flatten Layer\n # Function Definition from Above:\n # flatten(x_tensor)\n c5 = flatten(c3s4)\n c5 = tf.nn.dropout(c5, keep_prob)\n # TODO: Apply 1, 2, or 3 Fully Connected Layers\n # Play around with different number of outputs\n # Function Definition from Above:\n # fully_conn(x_tensor, num_outputs)\n f6 = fully_conn(c5, 84)\n \n \n # TODO: Apply an Output Layer\n # Set this to the number of classes\n # Function Definition from Above:\n # output(x_tensor, num_outputs)\n f7 = output(f6, 10)\n \n # TODO: return output\n return f7\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\n\n##############################\n## Build the Neural Network ##\n##############################\n\n# Remove previous weights, bias, inputs, etc..\ntf.reset_default_graph()\n\n# Inputs\nx = neural_net_image_input((32, 32, 3))\ny = neural_net_label_input(10)\nkeep_prob = neural_net_keep_prob_input()\n\n# Model\nlogits = conv_net(x, keep_prob)\n\n# Name logits Tensor, so that is can be loaded from disk after training\nlogits = tf.identity(logits, name='logits')\n\n# Loss and Optimizer\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y))\noptimizer = tf.train.AdamOptimizer().minimize(cost)\n\n# Accuracy\ncorrect_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy')\n\ntests.test_conv_net(conv_net)",
"Train the Neural Network\nSingle Optimization\nImplement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following:\n* x for image input\n* y for labels\n* keep_prob for keep probability for dropout\nThis function will be called for each batch, so tf.global_variables_initializer() has already been called.\nNote: Nothing needs to be returned. This function is only optimizing the neural network.",
"def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):\n \"\"\"\n Optimize the session on a batch of images and labels\n : session: Current TensorFlow session\n : optimizer: TensorFlow optimizer function\n : keep_probability: keep probability\n : feature_batch: Batch of Numpy image data\n : label_batch: Batch of Numpy label data\n \"\"\"\n # TODO: Implement Function\n session.run(optimizer, feed_dict={x: feature_batch, y: label_batch, keep_prob: keep_probability})\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_train_nn(train_neural_network)",
"Show Stats\nImplement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.",
"def print_stats(session, feature_batch, label_batch, cost, accuracy):\n \"\"\"\n Print information about loss and validation accuracy\n : session: Current TensorFlow session\n : feature_batch: Batch of Numpy image data\n : label_batch: Batch of Numpy label data\n : cost: TensorFlow cost function\n : accuracy: TensorFlow accuracy function\n \"\"\"\n # TODO: Implement Function\n loss = session.run(cost, feed_dict={x: feature_batch, y: label_batch,keep_prob: 1.})\n valid_acc = session.run(accuracy, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.})\n \n print('loss is {}'.format(loss))\n print('validation_accuracy is {}'.format(valid_acc)) ",
"Hyperparameters\nTune the following parameters:\n* Set epochs to the number of iterations until the network stops learning or start overfitting\n* Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:\n * 64\n * 128\n * 256\n * ...\n* Set keep_probability to the probability of keeping a node using dropout",
"# TODO: Tune Parameters\nepochs = 10\nbatch_size = 128\nkeep_probability = 0.75",
"Train on a Single CIFAR-10 Batch\nInstead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nprint('Checking the Training on a Single Batch...')\nwith tf.Session() as sess:\n # Initializing the variables\n sess.run(tf.initialize_all_variables())\n \n # Training cycle\n for epoch in range(epochs):\n batch_i = 1\n for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')\n print_stats(sess, batch_features, batch_labels, cost, accuracy)",
"Fully Train the Model\nNow that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nsave_model_path = './image_classification'\n\nprint('Training...')\nwith tf.Session() as sess:\n # Initializing the variables\n sess.run(tf.initialize_all_variables())\n \n # Training cycle\n for epoch in range(epochs):\n # Loop over all batches\n n_batches = 5\n for batch_i in range(1, n_batches + 1):\n for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size):\n train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels)\n print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='')\n print_stats(sess, batch_features, batch_labels, cost, accuracy)\n \n # Save Model\n saver = tf.train.Saver()\n save_path = saver.save(sess, save_model_path)",
"Checkpoint\nThe model has been saved to disk.\nTest Model\nTest your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport tensorflow as tf\nimport pickle\nimport helper\nimport random\n\n# Set batch size if not already set\ntry:\n if batch_size:\n pass\nexcept NameError:\n batch_size = 64\n\nsave_model_path = './image_classification'\nn_samples = 4\ntop_n_predictions = 3\n\ndef test_model():\n \"\"\"\n Test the saved model against the test dataset\n \"\"\"\n\n test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb'))\n loaded_graph = tf.Graph()\n\n with tf.Session(graph=loaded_graph) as sess:\n # Load model\n loader = tf.train.import_meta_graph(save_model_path + '.meta')\n loader.restore(sess, save_model_path)\n\n # Get Tensors from loaded model\n loaded_x = loaded_graph.get_tensor_by_name('x:0')\n loaded_y = loaded_graph.get_tensor_by_name('y:0')\n loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n loaded_logits = loaded_graph.get_tensor_by_name('logits:0')\n loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0')\n \n # Get accuracy in batches for memory limitations\n test_batch_acc_total = 0\n test_batch_count = 0\n \n for test_feature_batch, test_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size):\n test_batch_acc_total += sess.run(\n loaded_acc,\n feed_dict={loaded_x: test_feature_batch, loaded_y: test_label_batch, loaded_keep_prob: 1.0})\n test_batch_count += 1\n\n print('Testing Accuracy: {}\\n'.format(test_batch_acc_total/test_batch_count))\n\n # Print Random Samples\n random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples)))\n random_test_predictions = sess.run(\n tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions),\n feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0})\n helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions)\n\n\ntest_model()",
"Why 50-80% Accuracy?\nYou might be wondering why you can't get an accuracy any higher. First things first, 50% isn't bad for a simple CNN. Pure guessing would get you 10% accuracy. However, you might notice people are getting scores well above 80%. That's because we haven't taught you all there is to know about neural networks. We still need to cover a few more techniques.\nSubmitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_image_classification.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
tuanavu/coursera-university-of-washington
|
machine_learning/2_regression/assignment/week3/week-3-polynomial-regression-assignment-exercise.ipynb
|
mit
|
[
"Regression Week 3: Assessing Fit (polynomial regression)\nIn this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will:\n* Write a function to take an SArray and a degree and return an SFrame where each column is the SArray to a polynomial value up to the total degree e.g. degree = 3 then column 1 is the SArray column 2 is the SArray squared and column 3 is the SArray cubed\n* Use matplotlib to visualize polynomial regressions\n* Use matplotlib to visualize the same polynomial degree on different subsets of the data\n* Use a validation set to select a polynomial degree\n* Assess the final fit using test data\nWe will continue to use the House data from previous notebooks.\nFire up graphlab create",
"import sys\nsys.path.append('C:\\Anaconda2\\envs\\dato-env\\Lib\\site-packages')\nimport graphlab",
"Next we're going to write a polynomial function that takes an SArray and a maximal degree and returns an SFrame with columns containing the SArray to all the powers up to the maximal degree.\nThe easiest way to apply a power to an SArray is to use the .apply() and lambda x: functions. \nFor example to take the example array and compute the third power we can do as follows: (note running this cell the first time may take longer than expected since it loads graphlab)",
"tmp = graphlab.SArray([1., 2., 3.])\ntmp_cubed = tmp.apply(lambda x: x**3)\nprint tmp\nprint tmp_cubed",
"We can create an empty SFrame using graphlab.SFrame() and then add any columns to it with ex_sframe['column_name'] = value. For example we create an empty SFrame and make the column 'power_1' to be the first power of tmp (i.e. tmp itself).",
"ex_sframe = graphlab.SFrame()\nex_sframe['power_1'] = tmp\nprint ex_sframe",
"Polynomial_sframe function\nUsing the hints above complete the following function to create an SFrame consisting of the powers of an SArray up to a specific degree:",
"def polynomial_sframe(feature, degree):\n # assume that degree >= 1\n # initialize the SFrame:\n poly_sframe = graphlab.SFrame()\n # and set poly_sframe['power_1'] equal to the passed feature\n poly_sframe['power_1'] = feature\n # first check if degree > 1\n if degree > 1:\n # then loop over the remaining degrees:\n # range usually starts at 0 and stops at the endpoint-1. We want it to start at 2 and stop at degree\n for power in range(2, degree+1): \n # first we'll give the column a name:\n name = 'power_' + str(power)\n # then assign poly_sframe[name] to the appropriate power of feature\n poly_sframe[name] = feature ** power\n return poly_sframe",
"To test your function consider the smaller tmp variable and what you would expect the outcome of the following call:",
"print polynomial_sframe(tmp, 3)",
"Visualizing polynomial regression\nLet's use matplotlib to visualize what a polynomial regression looks like on some real data.",
"sales = graphlab.SFrame('kc_house_data.gl/')",
"As in Week 3, we will use the sqft_living variable. For plotting purposes (connecting the dots), you'll need to sort by the values of sqft_living. For houses with identical square footage, we break the tie by their prices.",
"sales = sales.sort(['sqft_living', 'price'])",
"Let's start with a degree 1 polynomial using 'sqft_living' (i.e. a line) to predict 'price' and plot what it looks like.",
"poly1_data = polynomial_sframe(sales['sqft_living'], 1)\npoly1_data['price'] = sales['price'] # add price to the data since it's the target\n\nprint poly1_data",
"NOTE: for all the models in this notebook use validation_set = None to ensure that all results are consistent across users.",
"model1 = graphlab.linear_regression.create(poly1_data, target = 'price', features = ['power_1'], validation_set = None)\n\n#let's take a look at the weights before we plot\nmodel1.get(\"coefficients\")\n\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\nplt.plot(poly1_data['power_1'],poly1_data['price'],'.',\n poly1_data['power_1'], model1.predict(poly1_data),'-')",
"Let's unpack that plt.plot() command. The first pair of SArrays we passed are the 1st power of sqft and the actual price we then ask it to print these as dots '.'. The next pair we pass is the 1st power of sqft and the predicted values from the linear model. We ask these to be plotted as a line '-'. \nWe can see, not surprisingly, that the predicted values all fall on a line, specifically the one with slope 280 and intercept -43579. What if we wanted to plot a second degree polynomial?",
"poly2_data = polynomial_sframe(sales['sqft_living'], 2)\nmy_features = poly2_data.column_names() # get the name of the features\npoly2_data['price'] = sales['price'] # add price to the data since it's the target\nmodel2 = graphlab.linear_regression.create(poly2_data, target = 'price', features = my_features, validation_set = None)\n\nmodel2.get(\"coefficients\")\n\nplt.plot(poly2_data['power_1'],poly2_data['price'],'.',\n poly2_data['power_1'], model2.predict(poly2_data),'-')",
"The resulting model looks like half a parabola. Try on your own to see what the cubic looks like:",
"poly3_data = polynomial_sframe(sales['sqft_living'], 3)\npoly3_features = poly3_data.column_names() # get the name of the features\npoly3_data['price'] = sales['price'] # add price to the data since it's the target\nmodel3 = graphlab.linear_regression.create(poly3_data, target = 'price', features = poly3_features, validation_set = None)\n\nmodel3.get(\"coefficients\")\n\nplt.plot(poly3_data['power_1'],poly3_data['price'],'.',\n poly3_data['power_1'], model3.predict(poly3_data),'-')",
"Now try a 15th degree polynomial:",
"poly15_data = polynomial_sframe(sales['sqft_living'], 15)\npoly15_features = poly15_data.column_names() # get the name of the features\npoly15_data['price'] = sales['price'] # add price to the data since it's the target\nmodel15 = graphlab.linear_regression.create(poly15_data, target = 'price', features = poly15_features, validation_set = None)\n\nmodel15.get(\"coefficients\")\n\nplt.plot(poly15_data['power_1'],poly15_data['price'],'.',\n poly15_data['power_1'], model15.predict(poly15_data),'-')",
"What do you think of the 15th degree polynomial? Do you think this is appropriate? If we were to change the data do you think you'd get pretty much the same curve? Let's take a look.\nChanging the data and re-learning\nWe're going to split the sales data into four subsets of roughly equal size. Then you will estimate a 15th degree polynomial model on all four subsets of the data. Print the coefficients (you should use .print_rows(num_rows = 16) to view all of them) and plot the resulting fit (as we did above). The quiz will ask you some questions about these results.\nTo split the sales data into four subsets, we perform the following steps:\n* First split sales into 2 subsets with .random_split(0.5, seed=0). \n* Next split the resulting subsets into 2 more subsets each. Use .random_split(0.5, seed=0).\nWe set seed=0 in these steps so that different users get consistent results.\nYou should end up with 4 subsets (set_1, set_2, set_3, set_4) of approximately equal size.",
"bigset_1, bigset_2 = sales.random_split(0.5, seed=0)\nset_1, set_2 = bigset_1.random_split(0.5, seed=0)\nset_3, set_4 = bigset_2.random_split(0.5, seed=0)",
"Fit a 15th degree polynomial on set_1, set_2, set_3, and set_4 using sqft_living to predict prices. Print the coefficients and make a plot of the resulting model.",
"def get_poly_model(set_data):\n poly15_data = polynomial_sframe(set_data['sqft_living'], 15)\n poly15_features = poly15_data.column_names() # get the name of the features\n poly15_data['price'] = set_data['price'] # add price to the data since it's the target\n model15 = graphlab.linear_regression.create(poly15_data, target = 'price', features = poly15_features, validation_set = None)\n return poly15_data, model15\n \n\ndef get_coef(set_data):\n poly15_data, model15 = get_poly_model(set_data)\n return model15.get(\"coefficients\")\n\ndef plot_fitted_line(set_data):\n poly15_data, model15 = get_poly_model(set_data)\n return plt.plot(poly15_data['power_1'],poly15_data['price'],'.',\n poly15_data['power_1'], model15.predict(poly15_data),'-')\n\nset_1_coef = get_coef(set_1)\nprint set_1_coef[set_1_coef['name'] == 'power_15']\n\nplot_fitted_line(set_1)\n\nset_2_coef = get_coef(set_2)\nprint set_2_coef[set_2_coef['name'] == 'power_15']\n\nplot_fitted_line(set_2)\n\nset_3_coef = get_coef(set_3)\nprint set_3_coef[set_3_coef['name'] == 'power_15']\n\nplot_fitted_line(set_3)\n\nset_4_coef = get_coef(set_4)\nprint set_4_coef[set_4_coef['name'] == 'power_15']\n\nplot_fitted_line(set_4)",
"Some questions you will be asked on your quiz:\nQuiz Question: Is the sign (positive or negative) for power_15 the same in all four models?\nQuiz Question: (True/False) the plotted fitted lines look the same in all four plots\nSelecting a Polynomial Degree\nWhenever we have a \"magic\" parameter like the degree of the polynomial there is one well-known way to select these parameters: validation set. (We will explore another approach in week 4).\nWe split the sales dataset 3-way into training set, test set, and validation set as follows:\n\nSplit our sales data into 2 sets: training_and_validation and testing. Use random_split(0.9, seed=1).\nFurther split our training data into two sets: training and validation. Use random_split(0.5, seed=1).\n\nAgain, we set seed=1 to obtain consistent results for different users.",
"training_and_validation_data, test_data = sales.random_split(0.9, seed=1)\ntrain_data, validation_data = training_and_validation_data.random_split(0.5, seed=1)",
"Next you should write a loop that does the following:\n* For degree in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] (to get this in python type range(1, 15+1))\n * Build an SFrame of polynomial data of train_data['sqft_living'] at the current degree\n * hint: my_features = poly_data.column_names() gives you a list e.g. ['power_1', 'power_2', 'power_3'] which you might find useful for graphlab.linear_regression.create( features = my_features)\n * Add train_data['price'] to the polynomial SFrame\n * Learn a polynomial regression model to sqft vs price with that degree on TRAIN data\n * Compute the RSS on VALIDATION data (here you will want to use .predict()) for that degree and you will need to make a polynmial SFrame using validation data.\n* Report which degree had the lowest RSS on validation data (remember python indexes from 0)\n(Note you can turn off the print out of linear_regression.create() with verbose = False)",
"arr = []\nfor degree in range(1, 16):\n poly_data = polynomial_sframe(train_data['sqft_living'], degree) \n my_features = poly_data.column_names()\n poly_data['price'] = train_data['price']\n model = graphlab.linear_regression.create(poly_data, target = 'price', features = my_features, \n validation_set = None, verbose = False)\n validation_data_poly = polynomial_sframe(validation_data['sqft_living'], degree)\n predictions = model.predict(validation_data_poly)\n residuals = validation_data['price'] - predictions\n rss = sum(residuals * residuals)\n arr.append(rss)\n# print degree\n# print rss \n\n# for degree, rss in enumerate(arr):\n# print degree, rss\n\n# Note that list index starts from 0, so degree = index + 1\nprint arr.index(min(arr)), min(arr)",
"Quiz Question: Which degree (1, 2, …, 15) had the lowest RSS on Validation data?\nNow that you have chosen the degree of your polynomial using validation data, compute the RSS of this model on TEST data. Report the RSS on your quiz.",
"arr2 = []\nfor degree in range(1, 16):\n poly_data = polynomial_sframe(train_data['sqft_living'], degree) \n my_features = poly_data.column_names()\n poly_data['price'] = train_data['price']\n model = graphlab.linear_regression.create(poly_data, target = 'price', features = my_features, \n validation_set = None, verbose = False)\n test_data_poly = polynomial_sframe(test_data['sqft_living'], degree)\n predictions = model.predict(test_data_poly)\n residuals = test_data['price'] - predictions\n rss_test = sum(residuals * residuals)\n arr2.append(rss_test)\n# print degree\n# print rss \n\nfor degree, rss in enumerate(arr2):\n print degree, rss\n\nprint arr2.index(min(arr2)), min(arr2)",
"Quiz Question: what is the RSS on TEST data for the model with the degree selected from Validation data? (Make sure you got the correct degree from the previous question)",
"print arr2[6]"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
rishuatgithub/MLPy
|
nlp/UPDATED_NLP_COURSE/02-Parts-of-Speech-Tagging/02-NER-Named-Entity-Recognition.ipynb
|
apache-2.0
|
[
"<a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>\n\nNamed Entity Recognition (NER)\nspaCy has an 'ner' pipeline component that identifies token spans fitting a predetermined set of named entities. These are available as the ents property of a Doc object.",
"# Perform standard imports\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\n# Write a function to display basic entity info:\ndef show_ents(doc):\n if doc.ents:\n for ent in doc.ents:\n print(ent.text+' - '+ent.label_+' - '+str(spacy.explain(ent.label_)))\n else:\n print('No named entities found.')\n\ndoc = nlp(u'May I go to Washington, DC next May to see the Washington Monument?')\n\nshow_ents(doc)",
"Here we see tokens combine to form the entities Washington, DC, next May and the Washington Monument\nEntity annotations\nDoc.ents are token spans with their own set of annotations.\n<table>\n<tr><td>`ent.text`</td><td>The original entity text</td></tr>\n<tr><td>`ent.label`</td><td>The entity type's hash value</td></tr>\n<tr><td>`ent.label_`</td><td>The entity type's string description</td></tr>\n<tr><td>`ent.start`</td><td>The token span's *start* index position in the Doc</td></tr>\n<tr><td>`ent.end`</td><td>The token span's *stop* index position in the Doc</td></tr>\n<tr><td>`ent.start_char`</td><td>The entity text's *start* index position in the Doc</td></tr>\n<tr><td>`ent.end_char`</td><td>The entity text's *stop* index position in the Doc</td></tr>\n</table>",
"doc = nlp(u'Can I please borrow 500 dollars from you to buy some Microsoft stock?')\n\nfor ent in doc.ents:\n print(ent.text, ent.start, ent.end, ent.start_char, ent.end_char, ent.label_)",
"NER Tags\nTags are accessible through the .label_ property of an entity.\n<table>\n<tr><th>TYPE</th><th>DESCRIPTION</th><th>EXAMPLE</th></tr>\n<tr><td>`PERSON`</td><td>People, including fictional.</td><td>*Fred Flintstone*</td></tr>\n<tr><td>`NORP`</td><td>Nationalities or religious or political groups.</td><td>*The Republican Party*</td></tr>\n<tr><td>`FAC`</td><td>Buildings, airports, highways, bridges, etc.</td><td>*Logan International Airport, The Golden Gate*</td></tr>\n<tr><td>`ORG`</td><td>Companies, agencies, institutions, etc.</td><td>*Microsoft, FBI, MIT*</td></tr>\n<tr><td>`GPE`</td><td>Countries, cities, states.</td><td>*France, UAR, Chicago, Idaho*</td></tr>\n<tr><td>`LOC`</td><td>Non-GPE locations, mountain ranges, bodies of water.</td><td>*Europe, Nile River, Midwest*</td></tr>\n<tr><td>`PRODUCT`</td><td>Objects, vehicles, foods, etc. (Not services.)</td><td>*Formula 1*</td></tr>\n<tr><td>`EVENT`</td><td>Named hurricanes, battles, wars, sports events, etc.</td><td>*Olympic Games*</td></tr>\n<tr><td>`WORK_OF_ART`</td><td>Titles of books, songs, etc.</td><td>*The Mona Lisa*</td></tr>\n<tr><td>`LAW`</td><td>Named documents made into laws.</td><td>*Roe v. Wade*</td></tr>\n<tr><td>`LANGUAGE`</td><td>Any named language.</td><td>*English*</td></tr>\n<tr><td>`DATE`</td><td>Absolute or relative dates or periods.</td><td>*20 July 1969*</td></tr>\n<tr><td>`TIME`</td><td>Times smaller than a day.</td><td>*Four hours*</td></tr>\n<tr><td>`PERCENT`</td><td>Percentage, including \"%\".</td><td>*Eighty percent*</td></tr>\n<tr><td>`MONEY`</td><td>Monetary values, including unit.</td><td>*Twenty Cents*</td></tr>\n<tr><td>`QUANTITY`</td><td>Measurements, as of weight or distance.</td><td>*Several kilometers, 55kg*</td></tr>\n<tr><td>`ORDINAL`</td><td>\"first\", \"second\", etc.</td><td>*9th, Ninth*</td></tr>\n<tr><td>`CARDINAL`</td><td>Numerals that do not fall under another type.</td><td>*2, Two, Fifty-two*</td></tr>\n</table>\n\n\nAdding a Named Entity to a Span\nNormally we would have spaCy build a library of named entities by training it on several samples of text.<br>In this case, we only want to add one value:",
"doc = nlp(u'Tesla to build a U.K. factory for $6 million')\n\nshow_ents(doc)",
"<font color=green>Right now, spaCy does not recognize \"Tesla\" as a company.</font>",
"from spacy.tokens import Span\n\n# Get the hash value of the ORG entity label\nORG = doc.vocab.strings[u'ORG'] \n\n# Create a Span for the new entity\nnew_ent = Span(doc, 0, 1, label=ORG)\n\n# Add the entity to the existing Doc object\ndoc.ents = list(doc.ents) + [new_ent]",
"<font color=green>In the code above, the arguments passed to Span() are:</font>\n- doc - the name of the Doc object\n- 0 - the start index position of the span\n- 1 - the stop index position (exclusive)\n- label=ORG - the label assigned to our entity",
"show_ents(doc)",
"Adding Named Entities to All Matching Spans\nWhat if we want to tag all occurrences of \"Tesla\"? In this section we show how to use the PhraseMatcher to identify a series of spans in the Doc:",
"doc = nlp(u'Our company plans to introduce a new vacuum cleaner. '\n u'If successful, the vacuum cleaner will be our first product.')\n\nshow_ents(doc)\n\n# Import PhraseMatcher and create a matcher object:\nfrom spacy.matcher import PhraseMatcher\nmatcher = PhraseMatcher(nlp.vocab)\n\n# Create the desired phrase patterns:\nphrase_list = ['vacuum cleaner', 'vacuum-cleaner']\nphrase_patterns = [nlp(text) for text in phrase_list]\n\n# Apply the patterns to our matcher object:\nmatcher.add('newproduct', None, *phrase_patterns)\n\n# Apply the matcher to our Doc object:\nmatches = matcher(doc)\n\n# See what matches occur:\nmatches\n\n# Here we create Spans from each match, and create named entities from them:\nfrom spacy.tokens import Span\n\nPROD = doc.vocab.strings[u'PRODUCT']\n\nnew_ents = [Span(doc, match[1],match[2],label=PROD) for match in matches]\n\ndoc.ents = list(doc.ents) + new_ents\n\nshow_ents(doc)",
"Counting Entities\nWhile spaCy may not have a built-in tool for counting entities, we can pass a conditional statement into a list comprehension:",
"doc = nlp(u'Originally priced at $29.50, the sweater was marked down to five dollars.')\n\nshow_ents(doc)\n\nlen([ent for ent in doc.ents if ent.label_=='MONEY'])",
"<font color=blue>Problem with Line Breaks</font>\n<div class=\"alert alert-info\" style=\"margin: 20px\">There's a <a href='https://github.com/explosion/spaCy/issues/1717'>known issue</a> with <strong>spaCy v2.0.12</strong> where some linebreaks are interpreted as `GPE` entities:</div>",
"spacy.__version__\n\ndoc = nlp(u'Originally priced at $29.50,\\nthe sweater was marked down to five dollars.')\n\nshow_ents(doc)",
"<font color=blue>However, there is a simple fix that can be added to the nlp pipeline:</font>",
"# Quick function to remove ents formed on whitespace:\ndef remove_whitespace_entities(doc):\n doc.ents = [e for e in doc.ents if not e.text.isspace()]\n return doc\n\n# Insert this into the pipeline AFTER the ner component:\nnlp.add_pipe(remove_whitespace_entities, after='ner')\n\n# Rerun nlp on the text above, and show ents:\ndoc = nlp(u'Originally priced at $29.50,\\nthe sweater was marked down to five dollars.')\n\nshow_ents(doc)",
"For more on Named Entity Recognition visit https://spacy.io/usage/linguistic-features#101\n\nNoun Chunks\nDoc.noun_chunks are base noun phrases: token spans that include the noun and words describing the noun. Noun chunks cannot be nested, cannot overlap, and do not involve prepositional phrases or relative clauses.<br>\nWhere Doc.ents rely on the ner pipeline component, Doc.noun_chunks are provided by the parser.\nnoun_chunks components:\n<table>\n<tr><td>`.text`</td><td>The original noun chunk text.</td></tr>\n<tr><td>`.root.text`</td><td>The original text of the word connecting the noun chunk to the rest of the parse.</td></tr>\n<tr><td>`.root.dep_`</td><td>Dependency relation connecting the root to its head.</td></tr>\n<tr><td>`.root.head.text`</td><td>The text of the root token's head.</td></tr>\n</table>",
"doc = nlp(u\"Autonomous cars shift insurance liability toward manufacturers.\")\n\nfor chunk in doc.noun_chunks:\n print(chunk.text+' - '+chunk.root.text+' - '+chunk.root.dep_+' - '+chunk.root.head.text)",
"Doc.noun_chunks is a generator function\nPreviously we mentioned that Doc objects do not retain a list of sentences, but they're available through the Doc.sents generator.<br>It's the same with Doc.noun_chunks - lists can be created if needed:",
"len(doc.noun_chunks)\n\nlen(list(doc.noun_chunks))",
"For more on noun_chunks visit https://spacy.io/usage/linguistic-features#noun-chunks\nGreat! Now you should be more familiar with both named entities and noun chunks. In the next section we revisit the NER visualizer.\nNext up: Visualizing NER"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
jmlon/PythonTutorials
|
pandas/Apache log analyzer with Pandas.ipynb
|
gpl-3.0
|
[
"Building an Apache log analyzer with Pandas\nApache access logs are text files that record the activity of a web site. The analysis of log files provides useful insights for web masters and site owners. This example illustrates how to use the data analysis functions of Pandas to analize log files.\nFor this exercise we will need to import the following libraries:",
"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom dateutil.parser import *",
"Apache log files\nLog files come in various formats which differ in the amount mof information registered in the log. The two most common formats are the 'common' and the 'combined'. For more details about apache log formats see <a href=\"https://httpd.apache.org/docs/2.2/en/logs.html\">Apache's Log Files</a>. Here are a couple of examples:\nCommon format:<BR>\n <PRE>local - - [30/Mar/1995:20:28:05 -0700] \"GET 6224.html HTTP/1.0\" 200 2644</PRE>\nCombined format:<BR>\n <PRE>192.168.0.1 - - [02/Jan/2018:07:20:02 -0500] \"GET /index.html HTTP/1.1\" 200 8813 \"-\" \"Mozilla/5.0 (Linux; Android 7.0; PRA-LX3 Build/HUAWEIPRA-LX3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36\"</PRE>\nThe first element of a log line is the address or hostname of the client.<BR>\nNext come the id and the user, usually not used and register as a '-'.<BR>\nThen, we have the date and time enclosed between '[' and ']'.<BR>\nThe next element is the request, which comes enclosed in quotes.<BR>\nThen we have a couple numbers, the http status code and the response size. In some cases, they may be registered as '-'.<BR>\nIn the combined format we have two additional elements, the referer and the user agent, both enclosed in quotes.\nReading the log file\nAt first, the log lines may seem difficult to parse. Pandas simplifies thet task with the <a href=\"https://pandas.pydata.org/pandas-docs/stable/io.html#io-read-csv-table\">read_csv function</a>, which supports many customization options. We are going to need the following:\n<UL>\n <li><em>delim_whitespace=True</em>. Use whitespaces instead of commas as field separators.</li>\n <li><em>header=None</em>. Log files do no include a headers line.</li>\n <li><em>parse_dates={ 'dt': [3,4] }</em>. We are going to use columns 3 and 4 to parse the date.</li>\n <li><em>date_parser=apacheDateParser</em>. Our custom function to parse dates in the log's format.</li>\n <li><em>index_col=0</em>. Use the date-time field as the dataframe index</li>\n <li><em>names=['client','id','user','datetime','tz','request','status','size','referer','agent']</em>. Name the columns to make it easier to access and remember their meaning.</li>\n <li><em>converters={ 'status':myIntParser, 'size': myIntParser }</em>. We want to handle the status code and the document size as integers, but we need a custon function to handle the cases where the field is '-'.</li>\n <li><em>encoding='iso-8859-1'</em>. What encoding uses the log file. Most cases are either 'iso-8859-1' or 'utf-8'.</li>\n <li><em>dtype={ 'referer': object, 'agent': object }.</em>Specify the data type of the last columns. Important in the case of the common format, which does not contain this information.</li>\n</UL>\n\nSo, lets define our custom functions for parsing integers and dates:",
"def apacheDateParser(x,y):\n return parse(x+' '+y, fuzzy=True) \n\n\ndef myIntParser(x):\n try:\n # Throws a ValueError exception if is not a valid integer\n return int(x)\n except ValueError:\n return np.nan",
"And now we can read the log file into a Pandas <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html\">Dataframe</a>.",
"data = pd.read_csv('<Path to your access_log file>', encoding='iso-8859-1',\n delim_whitespace=True, \n header=None, \n parse_dates={ 'dt': [3,4] },\n date_parser=apacheDateParser,\n index_col=0, \n names=['client','id','user','datetime','tz','request','status','size','referer','agent'],\n converters={ 'status':myIntParser, 'size': myIntParser },\n dtype={ 'referer': object, 'agent': object } )",
"We can check how many rows and columns in the data with",
"print(data.shape)",
"And take a look at the data with",
"data.head()",
"In this case the log file is in the common format and for this reason the referer and agent columns are empty.\nWe may also want to check that the type conversions work as expected",
"data.dtypes",
"We can check some basic statistics of the data, for example\nThe mean transfer size is",
"data['size'].mean()",
"and its standard deviation is",
"data['size'].std()",
"We can see that in some cases the size was not a valid value",
"data['size'][data['size'].isnull()].head()",
"When doing analysis on files with this kind of problems, be aware that there may be cases like this that introduce error in the results. For example if we count the number of size records we obtain",
"data['size'].count()",
"Much lower than the number of rows in the table.\nData analysis\nGrouping\nUsing a grouping criteria we can obtain statistics about groups of records that share certain characteristic. In this example, we are going to characterize the visits to the website by day of the week. So, we start by grouping the dataframe by weekday for counting the number is hits. In this case, any column will do for the counting.",
"grpHitsWDay = data[['id']].groupby(data.index.weekday, sort=False)",
"Observe that the groupby operation returns a DataFrameGroupBy object",
"grpHitsWDay",
"The indices attribute give us a good intuition of how groups are represented",
"grpHitsWDay.indices",
"each weekday (0,..,6) is an array that containts the rows of the dataframe that belong to the group. This is quite important because when computing any metric, we have to use functions that operate over the arrays of the corresponding rows.\nFor example, counting the number of elements in the array gives us the total hits of the respective day",
"grpHitsWDay.count()",
"Of course, it would be nicer if we give the days of the week the corresponding names and the column the name 'Hits'",
"hits = grpHitsWDay.count()\nhits.index = [ 'Mon','Tue','Wed','Thu','Fri','Sat','Sun' ]\nhits.columns = [ 'Hits' ]\nhits",
"The method describe gives a basic statistical description of the 'Hits' metric",
"hits.describe()",
"Sometimes a picture is work a thousand words",
"hits.plot(kind='bar', figsize=(8,6), colormap='summer', title='Hits per weekday', legend=False)\nplt.show()",
"One may want a characterize several of the metrics at the same time. Let us characterize the behavior of hits and transferred bytes per weekday",
"grpWDay = data[ ['id','size'] ].groupby(data.index.weekday)",
"In this case, we want to count the number of hits and sum the number of bytes. The aggregate method allows passing the fuctions to apply to each column",
"stats = grpWDay.aggregate({ 'id':lambda x: x.count(), 'size':np.sum })\nstats",
"A couple of notes:\n<ul>\n<li>The columns of a dataframe are NumPy arrays, therefore standard NumPy functions (such as np.sum) can be used.</li>\n<li>A did not find a function that takes an array as argument and count the number of elements, but no problem, I created a lambda expression that takes the array as input and returns the result of invoking its count() method.</li>\n</ul>\n\nOf course, everything looks better with nicer names, so let us rename the columns and the indices",
"stats = grpWDay.aggregate({ 'id':lambda x: x.count(), 'size':np.sum }).rename(columns={'size':'Bytes', 'id':'Hits'})\nstats.index=[ 'Mon','Tue','Wed','Thu','Fri','Sat','Sun' ]\nstats",
"Now let us plot both metrics",
"stats.plot(kind='bar', figsize=(8,6), colormap='summer', title='Hits & bytes per weekday', subplots=True)\nplt.show() ",
"Post-processing of the dataset\nSometimes, we can obtain additional information by doing some operations over the data. One good example is identifying the resources of the web site. Currently, the dataset containts a request column that gives the method, the resource and the protocol version",
"data['request'].head(10)",
"The HTTP protocol dictates that the three fields are separated by spaces and the request cannot contain any additional spaces. Thus a simple split would give us the three fields. Lets grab the resource and add an extra column to the dataframe",
"data['resource'] = data['request'].apply(lambda x: x.split()[1])\ndata['resource'].head(10)",
"Here we use the apply method, which invokes a function to each element of the array. We define a lambda function that takes the request string, makes a split and returns the element at position 1.\nWell then, let us find the number of hits and bytes for each resource",
"grpRsc = data[ ['id','size'] ].groupby(data['resource'])\nstats = grpRsc.aggregate({ 'id':lambda x: x.count(), 'size':np.sum }).rename(columns={'size':'XferBytes', 'id':'Hits'})\nstats",
"It is commonly the case that we are interested in the top hitters. So, let us sort the information and grab the top ten hitters in descending order",
"sortedh = stats.sort_values(by='Hits', ascending=False)\nsortedh.head(10)",
"Observe that the top hits are not responsible for the most transferred bytes. Let us see this from the perspective of transferred bytes",
"sortedb = stats.sort_values(by='XferBytes', ascending=False)\nsortedb.head(10)",
"Now we now what to optimize to improve the bandwidth utilization of the website. How about plotting some of this information",
"sortedb.head(10).plot(kind='bar', figsize=(8,5), colormap='summer', title='Xfer & Hits (sorted by Xfer)', subplots=True)\nplt.show()",
"To explore further\nPandas allows many different things with a few lines of code. Some interesting exercises could be the following:\n<ul>\n<li>Group the data using the status code. Determine what resources are causing the larger number of errors. These could reveal broken links or possible attacks on the web site.</li> \n<li>To keep log files not too large, web servers use some log rotation schemes. For analysis it may be necessary to have all the information in a single dataframe. This could be done using the <a href=\"https://pandas.pydata.org/pandas-docs/stable/merging.html\">concat</a> or the <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html#pandas.DataFrame.append\">append</a> functions.</li> \n</ul>\n\nSource code\n<a href=\"https://github.com/jmlon/PythonTutorials/blob/master/pandas/logAnalyzer.py\">logAnalyzer.py</a> in GitHub"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
clauwag/WikipediaGenderInequality
|
notebooks/Notability - 03 - Consolidate Person Data.ipynb
|
mit
|
[
"Consolidate DBpedia Person Data\nIn this notebook we consolidate person data from all editions into one file, by removing duplicates.\nBy Eduardo Graells-Garrido.",
"from __future__ import print_function, unicode_literals\n\nimport gzip\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport dbpedia_config\n\nsns.set_context('poster', font_scale=0.8)\n%matplotlib inline\n\ntarget_folder = dbpedia_config.TARGET_FOLDER\nlanguages = dbpedia_config.LANGUAGES\n\nfilenames = ['{1}/person_data_{0}.csv.gz'.format(lang, target_folder) for lang in languages]",
"Person DataFrame\nWe will create a single dataframe with all the editions.",
"all_bios = None\nfor lang, filename in zip(languages, filenames):\n this_edition = pd.read_csv(filename, encoding='utf-8')\n this_edition['language'] = lang\n \n if all_bios is None:\n all_bios = this_edition\n else:\n all_bios = pd.concat([all_bios, this_edition])\n \nall_bios.language.value_counts()\n\ndef w_fraction(arr):\n #print arr\n return np.sum(arr == 'female') / float(len(arr))\n\ncol_labels = all_bios.groupby('language').aggregate(\n {'edition_count': lambda x: len(x), 'gender': w_fraction, 'available_english': np.mean}\n ).sort('edition_count', ascending=False)\n\ncol_labels['female_median_count'] = [all_bios[(all_bios.language == idx) \n & (all_bios.gender == 'female')].edition_count.median()\n for idx in col_labels.index]\ncol_labels['male_median_count'] = [all_bios[(all_bios.language == idx) \n & (all_bios.gender == 'male')].edition_count.median()\n for idx in col_labels.index]\n\ncol_labels['female_mean_count'] = [all_bios[(all_bios.language == idx) \n & (all_bios.gender == 'female')].edition_count.mean()\n for idx in col_labels.index]\ncol_labels['male_mean_count'] = [all_bios[(all_bios.language == idx) \n & (all_bios.gender == 'male')].edition_count.mean()\n for idx in col_labels.index]\n\n\ncol_labels",
"Consolidations\nLet's remove duplicates and build a single dataset for all languages.",
"all_bios.drop_duplicates(subset=['same_as'], inplace=True)\nall_bios.drop_duplicates(subset=['wikidata_entity'], inplace=True)\nall_bios.drop_duplicates(subset=['label'], inplace=True)\n\nall_bios.gender.value_counts()\n\nall_bios = all_bios[all_bios.gender.isin(['male', 'female'])].copy()\n\nprint(all_bios.shape)\n\nall_bios.gender.value_counts()\n\nall_bios.sample(n=5)\n\nwith gzip.open('{0}/consolidated_person_data.csv.gz'.format(target_folder), 'wb') as f:\n all_bios.to_csv(f, encoding='utf-8')"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
bennyrowland/suspect
|
docs/notebooks/tut1_intro.ipynb
|
mit
|
[
"Introduction to MRS processing with Suspect\nWelcome to the first in our series of tutorials in how to use Suspect for working with MR spectroscopy data. In this introduction, we will present some of the basic features of Suspect while in subsequent tutorials we will explore various parts of the processing pipeline in more detail.\nThe first thing is to import the suspect package. We will also import the pyplot module from Matplotlib, which we will use for plotting our data, and we use some Jupyter \"magic\" to cause all plots to be rendered inline with the text in the notebook.",
"import suspect\nimport numpy as np\nfrom matplotlib import pyplot as plt\n%matplotlib inline",
"Let's get started by loading some MRS data. Suspect currently supports various different data formats including Siemens DICOM, RDA and TWIX and Philips SDAT. GE P files are not yet supported but should be soon. The Suspect repository on Github contains a number of example data files and we will be using those throughout this tutorial series, so you can follow along if you like. If you are using the OpenMRSLab Docker image (which we use to write all these tutorials) then you will find this sample data in the folder at /home/jovyan/suspect/tests/test_data/. We are going to start with an RDA file for a short echo time single voxel PRESS sequence.",
"data = suspect.io.load_rda(\"/home/jovyan/suspect/tests/test_data/siemens/SVS_30.rda\")\nprint(data)",
"When we print the data object we just loaded we see that it is an instance of the MRSData class, and we also get some other information about the acquisition sequence such as the field strength and echo time. The MRSData class stores time domain spectroscopy data and is at the core of the Suspect package. It is a subclass of numpy.ndarray which means it has all the standard properties, as well as additional MRS specific ones. To learn more about the MRSData class and all its functions and properties, check out the MRSData API Reference",
"print(data.shape)\nprint(data.f0)\nprint(data.dt)\nprint(data.sw)",
"Now that we have some data loaded, we want to plot it to see what it looks like. As an ndarray subclass, MRSData is fully compatible with the standard Matplotlib plotting library so displaying our FID is as simple as:",
"plt.plot(data.time_axis(), data.real)",
"Note that the MRSData object has a time_axis() method which gives us the time at which each FID point was acquired. There are similar methods in the frequency domain to give us the axis in Hz or PPM. To obtain the spectrum from the FID we can apply the Fourier transform directly, or just use the helper spectrum() method provided by MRSData.",
"plt.plot(data.frequency_axis_ppm(), data.spectrum().real)\n# reverse the limits on the x-axis so that ppm runs from right to left\nplt.xlim([10, -1])",
"Looking back at the time domain plot we can see that there is a spurious signal which appears at the end of the acquisition window. This kind of artefact can distort the spectrum and cause problems in subsequent processing. For example the end of the FID is often considered to be pure noise, which is used in assessing SNR and these false signals can affect this analysis.\nFortunately we can get rid of this artefact by apodising our data, that is applying a windowing function in the time domain. The scipy.signal package provides a huge array of different windowing functions, in our case we will be using the Tukey window as this allows us to leave the first half of the signal completely unaffected and only suppress the signal close to the artefact region.",
"import scipy.signal\n# scipy.signal produces symmetric windows so only take the second half\nwindow = scipy.signal.tukey(data.np * 2)[data.np:]\nplt.plot(data.time_axis(), window)",
"Applying the window to our FID data is as simple as multiplying the two objects together. NumPy will multiply the two arrays componentwise and return the result as a new MRSData object, copying all the parameters from the original data object, so that the new object keeps all the essential MRS parameters and methods.",
"windowed_data = window * data\nplt.plot(data.time_axis(), data.real)\nplt.plot(windowed_data.time_axis(), windowed_data.real)",
"So that concludes our first look at the Suspect library. We have learnt about the MRSData class, how to load MRS data from a file and plot it, in the time and frequency domains, and seen a simple example of removing an artefact through apodisation. In the following tutorials, we will learn how to use Suspect to do more advanced data processing, including working with raw data, channel combination, B0 drift correction and water suppression."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
GoogleCloudPlatform/tensorflow-recommendation-wals
|
notebooks/Part1.ipynb
|
apache-2.0
|
[
"Exploring the model code\nThe model code is contained in the wals_ml_engine directory. The code's \nhigh-level functionality is implemented by the following files:\nmltrain.sh\n * Launches various types of ML Engine jobs. This shell\n script accepts arguments for the location of the dataset file, the\n delimiter used to separate values in the file, and whether the data\n file has a header line. It's a best practice to create a script that\n automatically configures and executes ML Engine jobs.\ntask.py\n * Parses the arguments for the ML Engine job and executes\n training.\nmodel.py\n * Loads the dataset.\n * Creates two sparse matrices from the data, one for training and one for\n testing. Executes WALS on the training sparse matrix of ratings.\nwals.py\n * Creates the WALS model.\n * Executes the WALS algorithm.\n * Calculates the root-mean-square error RMSE for a set of row/column factors and a ratings matrix.\nLet's run some code\nNow we will run some of the code from model.py in this notebook, to help you understand it.\nExecute the following cell to import necessary python modules:",
"import datetime\nimport numpy as np\nimport pandas as pd\nfrom scipy.sparse import coo_matrix\nimport tensorflow as tf",
"The MovieLens data set\nExecute the following cell to download the MovieLens 100k data set:",
"!curl -O 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'\n!unzip ml-100k.zip\n!mkdir -p ../data\n!cp ml-100k/u.data ../data/",
"Let's take a look at the MovieLens data. It consists of rows of individual user ratings of movies. Each row consists of four elements: a unique user id, a unique 'item id' corresponding to a movie, a rating from 1-5, and a timestamp of when the rating was made. Each row of data maps to a single entry in the ratings matrix:\n\nLet's inspect the contents of the file:",
"!head ../data/u.data",
"This model ignores the timestamp. We will only make use of the user id, item (or movie) id, and rating.\nHow the model preprocesses data\nThe model code performs data preprocessing to create a sparse ratings matrix and prepare it for matrix factorization. \nThis involves the following steps:\n\nThe model code loads rows of data from a delimited text file, in this case the MovieLens data. \n\nExecute this cell to read the MovieLens data set into a Pandas dataframe:",
"input_file = '../data/u.data'\nheaders = ['user_id', 'item_id', 'rating', 'timestamp']\nheader_row = None\nratings_df = pd.read_csv(input_file,\n sep='\\t',\n names=headers,\n header=header_row,\n dtype={\n 'user_id': np.int32,\n 'item_id': np.int32,\n 'rating': np.float32,\n 'timestamp': np.int32,\n })",
"The code establishes a 0-indexed set of unique IDs for users and items. This guarantees that a unique ID corresponds to specific row and column indexes of the sparse ratings matrix.\n\nLet's find the number of unique users and movies:",
"np_users = ratings_df.user_id.as_matrix()\nnp_items = ratings_df.item_id.as_matrix()\nunique_users = np.unique(np_users)\nunique_items = np.unique(np_items)\n\nn_users = unique_users.shape[0]\nn_items = unique_items.shape[0]\n\nn_users\n\nn_items",
"The MovieLens 100k data uses 1-based IDs where the lowest index of the unique set is 1. But the TensorFlow code assumes a starting index of zero. The code handles this by converting the Pandas dataframe to a numpy array and subtracting one from each index:",
"ratings = ratings_df.as_matrix(['user_id', 'item_id', 'rating'])\nratings[:,0] -= 1\nratings[:,1] -= 1\n\nratings",
"The model code randomly selects a test set of ratings. By default, 10% of the ratings are chosen for the test set. These ratings are removed from the training set and will be used to evaluate the predictive accuracy of the user and item factors.",
"TEST_SET_RATIO = 10\n\ntest_set_size = len(ratings) / TEST_SET_RATIO\ntest_set_idx = np.random.choice(xrange(len(ratings)),\n size=test_set_size, replace=False)\ntest_set_idx = sorted(test_set_idx)\n\nts_ratings = ratings[test_set_idx]\ntr_ratings = np.delete(ratings, test_set_idx, axis=0)\n\ntest_set_idx\n\nts_ratings\n\ntr_ratings",
"Finally, the code creates a scipy sparse matrix in coordinate form (coo_matrix) that includes the user and item indexes and ratings. The coo_matrix object acts as a wrapper for a sparse matrix. It also performs validation of the user and ratings indexes, checking for errors in preprocessing:",
"u_tr, i_tr, r_tr = zip(*tr_ratings)\ntr_sparse = coo_matrix((r_tr, (u_tr, i_tr)), shape=(n_users, n_items))\n\nu_ts, i_ts, r_ts = zip(*ts_ratings)\ntest_sparse = coo_matrix((r_ts, (u_ts, i_ts)), shape=(n_users, n_items))\n\ntr_sparse\n\ntest_sparse",
"How the WALS Algorithm is implemented in TensorFlow\nYou can read the solution online to understand how the WALS algorithm is implemented in TensorFlow."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
hpparvi/PyTransit
|
notebooks/example_qpower2_model.ipynb
|
gpl-2.0
|
[
"QPower2 model\nThe qpower2 model, pytransit.QPower2Model, implements a transit over a stellar disk with the stellar limb darkening described using the qpower2 limb darkening model as described by Maxted & Gill (A&A 622, 2019). The model is parallelised using numba, and the number of threads can be set using the NUMBA_NUM_THREADS environment variable. An OpenCL version for GPU computation is implemented by pytransit.QPower2ModelCL.",
"%pylab inline \n\nsys.path.append('..')\n\nfrom pytransit import QPower2Model\n\nseed(0)\n\ntimes_sc = linspace(0.85, 1.15, 1000) # Short cadence time stamps\ntimes_lc = linspace(0.85, 1.15, 100) # Long cadence time stamps\n\nk, t0, p, a, i, e, w = 0.1, 1., 2.1, 3.2, 0.5*pi, 0.3, 0.4*pi\npvp = tile([k, t0, p, a, i, e, w], (50,1))\npvp[1:,0] += normal(0.0, 0.005, size=pvp.shape[0]-1)\npvp[1:,1] += normal(0.0, 0.02, size=pvp.shape[0]-1)\n\nldc = stack([normal(0.3, 0.05, pvp.shape[0]), normal(0.1, 0.02, pvp.shape[0])], 1)",
"Model initialization\nThe qpower2 model doesn't take any special initialization arguments, so the initialization is straightforward.",
"tm = QPower2Model()",
"Data setup\nHomogeneous time series\nThe model needs to be set up by calling set_data() before it can be used. At its simplest, set_data takes the mid-exposure times of the time series to be modelled.",
"tm.set_data(times_sc)",
"Model use\nEvaluation\nThe transit model can be evaluated using either a set of scalar parameters, a parameter vector (1D ndarray), or a parameter vector array (2D ndarray). The model flux is returned as a 1D ndarray in the first two cases, and a 2D ndarray in the last (one model per parameter vector).\n\ntm.evaluate_ps(k, ldc, t0, p, a, i, e=0, w=0) evaluates the model for a set of scalar parameters, where k is the radius ratio, ldc is the limb darkening coefficient vector, t0 the zero epoch, p the orbital period, a the semi-major axis divided by the stellar radius, i the inclination in radians, e the eccentricity, and w the argument of periastron. Eccentricity and argument of periastron are optional, and omitting them defaults to a circular orbit. \n\ntm.evaluate_pv(pv, ldc) evaluates the model for a 1D parameter vector, or 2D array of parameter vectors. In the first case, the parameter vector should be array-like with elements [k, t0, p, a, i, e, w]. In the second case, the parameter vectors should be stored in a 2d ndarray with shape (npv, 7) as \n[[k1, t01, p1, a1, i1, e1, w1],\n [k2, t02, p2, a2, i2, e2, w2],\n ...\n [kn, t0n, pn, an, in, en, wn]]\n\n\nThe reason for the different options is that the model implementations may have optimisations that make the model evaluation for a set of parameter vectors much faster than if computing them separately. This is especially the case for the OpenCL models.\nNote: PyTransit uses always a 2D parameter vector array under the hood, and the scalar evaluation method just packs the parameters into an array before model evaluation.\nLimb darkening\nThe quadratic limb darkening coefficients are given either as a 1D or 2D array, depending on whether the model is evaluated for a single set of parameters or an array of parameter vectors. In the first case, the coefficients can be given as [u, v], and in the second, as [[u1, v1], [u2, v2], ... [un, vn]]. \nIn the case of a heterogeneous time series with multiple passbands (more details below), the coefficients are given for a single parameter set as a 1D array with a length $2n_{pb}$ ([u1, v1, u2, v2, ... un, vn], where the index now marks the passband), and for a parameter vector array as a 2D array with a shape (npv, 2*npb), as\n[[u11, v11, u12, v12, ... u1n, v1n], \n [u21, v21, u22, v22, ... u2n, v2n], \n ...\n [un1, vn1, un2, vn2, ... unn, vnn]]",
"def plot_transits(tm, ldc, fmt='k'):\n fig, axs = subplots(1, 3, figsize = (13,3), constrained_layout=True, sharey=True)\n\n flux = tm.evaluate_ps(k, ldc[0], t0, p, a, i, e, w)\n axs[0].plot(tm.time, flux, fmt)\n axs[0].set_title('Individual parameters')\n\n flux = tm.evaluate_pv(pvp[0], ldc[0])\n axs[1].plot(tm.time, flux, fmt)\n axs[1].set_title('Parameter vector')\n\n flux = tm.evaluate_pv(pvp, ldc)\n axs[2].plot(tm.time, flux.T, 'k', alpha=0.2);\n axs[2].set_title('Parameter vector array')\n\n setp(axs[0], ylabel='Normalised flux')\n setp(axs, xlabel='Time [days]', xlim=tm.time[[0,-1]])\n\ntm.set_data(times_sc)\nplot_transits(tm, ldc)",
"Supersampling\nThe transit model can be supersampled by setting the nsamples and exptimes arguments in set_data.",
"tm.set_data(times_lc, nsamples=10, exptimes=0.01)\nplot_transits(tm, ldc)",
"Heterogeneous time series\nPyTransit allows for heterogeneous time series, that is, a single time series can contain several individual light curves (with, e.g., different time cadences and required supersampling rates) observed (possibly) in different passbands.\nIf a time series contains several light curves, it also needs the light curve indices for each exposure. These are given through lcids argument, which should be an array of integers. If the time series contains light curves observed in different passbands, the passband indices need to be given through pbids argument as an integer array, one per light curve. Supersampling can also be defined on per-light curve basis by giving the nsamplesand exptimes as arrays with one value per light curve. \nFor example, a set of three light curves, two observed in one passband and the third in another passband\ntimes_1 (lc = 0, pb = 0, sc) = [1, 2, 3, 4]\ntimes_2 (lc = 1, pb = 0, lc) = [3, 4]\ntimes_3 (lc = 2, pb = 1, sc) = [1, 5, 6]\n\nWould be set up as\ntm.set_data(time = [1, 2, 3, 4, 3, 4, 1, 5, 6], \n lcids = [0, 0, 0, 0, 1, 1, 2, 2, 2], \n pbids = [0, 0, 1],\n nsamples = [ 1, 10, 1],\n exptimes = [0.1, 1.0, 0.1])\n\nFurther, each passband requires two limb darkening coefficients, so the limb darkening coefficient array for a single parameter set should now be\nldc = [u1, v1, u2, v2]\n\nwhere u and v are the passband-specific qpower2 limb darkening model coefficients.\nExample: two light curves with different cadences and passbands",
"times_1 = linspace(0.85, 1.0, 500)\ntimes_2 = linspace(1.0, 1.15, 10)\ntimes = concatenate([times_1, times_2])\nlcids = concatenate([full(times_1.size, 0, 'int'), full(times_2.size, 1, 'int')])\npbids = [0, 1]\nnsamples = [1, 10]\nexptimes = [0, 0.0167]\n\nldc2 = tile(ldc, (1,2))\nldc2[:,2:] /= 2\n\ntm.set_data(times, lcids, pbids, nsamples=nsamples, exptimes=exptimes)\nplot_transits(tm, ldc2, 'k.-')",
"<center>© Hannu Parviainen 2010-2020</center>"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
HaoMood/cs231n
|
assignment1/assignment1sol/knn/knn_main.ipynb
|
gpl-3.0
|
[
"cs231n assignment1 sol.\nk-Nearest Neighbor (kNN) exercise\nThe kNN classifier consists of two stages:\n - During training, the classifier takes the training data and simply remembers it\n - During testing, kNN classifies every test image by comparing to all training images and transfering the labels of the k most similar training examples\nThe value of k is cross-validated\nIn this exercise you will implement these steps and understand the basic Image Classification pipeline, cross-validation, and gain proficiency in writing efficient, vectorized code.\nwriten by Hao Zhang: haomoodzhang@gmail.com",
"# Run some setup code\n% reset\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# This is a bit of magic to make matplotlib figures appear inline in the notebook\n# rather than in a new window.\n%matplotlib inline\nplt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots\nplt.rcParams['image.interpolation'] = 'nearest'\nplt.rcParams['image.cmap'] = 'gray'\n\n# Some more magic so that the notebook will reload external python modules;\n# see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython\n%load_ext autoreload\n%autoreload 2\n\n# bool var. to let program show debug info.\ndebug = True\nshow_img = True\n\nimport cifar10\n# Load the raw CIFAR-10 data\nX, y, X_test, y_test = cifar10.load('../cifar-10-batches-py', debug = debug)\n\n# Visualize some examples from the dataset.\n# We show a few examples of training images from each class.\nif show_img:\n cifar10.show(X, y)\n\n# Subsample the data for more efficient code execution in this exercise\nm = 5000\nm_test = 500\nX, y, X_test, y_test = cifar10.subsample_vec(X, y, X_test, y_test, m, m_test, debug = debug)\nn = X.shape[0]\n\nfrom KNNClassifier import KNN\n# Create a kNN classifier instance. \n# Remember that training a kNN classifier is a noop: \n# the Classifier simply remembers the data and does no further processing \nmodel = KNN()\nmodel.train(X, y)\n\n# We would now like to classify the test data with the kNN classifier\n# We use k = 1 (which is Nearest Neighbor).\ny_hat = model.predict(X_test, hpara = 1, show_img = show_img)\nnum_correct = np.sum(y_hat == y_test)\nacc = float(num_correct) / m_test\nprint 'Got %d / %d correct, acc: %f' % (num_correct, m_test, acc)",
"Inline Question #1: Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.)\n\n\nWhat in the data is the cause behind the distinctly bright rows?\n\n\nAnswer: Some testing points are far from almost every training points\n\n\nWhat causes the columns?\n\n\nAnswer: Some training points are far from almost every testing points",
"# You should expect to see approximately 27% accuracy. Now lets try out a larger k, say k = 5\ny_hat = model.predict(X_test, hpara = 5, show_img = show_img)\nnum_correct = np.sum(y_hat == y_test)\nacc = float(num_correct) / m_test\nprint 'Got %d / %d correct, acc: %f' % (num_correct, m_test, acc)",
"Cross-validation\nWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.",
"from cv import cv\nnum_folds = 5\nk_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n\n# A dictionary holding the accuracies for different values of k that we find\n# when running cross-validation. After running cross-validation,\n# k2acc[k] should be a list of length num_folds giving the different\n# accuracy values that we found when using that value of k.\nk2acc = {}\n\n# Perform k-fold cross validation to find the best value of k. For each\n# possible value of k, run the k-nearest-neighbor algorithm num_folds times, \n# where in each case you use all but one of the folds as training data and the \n# last fold as a validation set. Store the accuracies for all fold and all \n# values of k in the k_to_accuracies dictionary. \nfor k in k_choices:\n hpara = k\n k2acc[k] = cv(X, y, num_folds, KNN, hpara)\n # Print out the computed accuracies\n print 'k =', k, 'acc =', [round(elm, 5) for elm in k2acc[k]]\n\nk_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100]\n# plot the raw observation\nfor k in k_choices:\n acc = k2acc[k]\n plt.scatter([k] * len(acc), acc)\n \n# plot the trend line with error bars that correspond to std. dev.\nacc_mean = np.array([np.mean(v) for k, v in sorted(k2acc.items())])\nacc_std = np.array([np.std(v) for k, v in sorted(k2acc.items())])\nplt.errorbar(k_choices, acc_mean, yerr = acc_std)\nplt.title('CV on k')\nplt.xlabel('k')\nplt.ylabel('CV acc')\nplt.show()\n\n# Based on the cross-validation results above, choose the best value for k, \n# retrain the classifier using all the training data, and test it on the test\n# data. You should be able to get above 28% accuracy on the test data.\nk_star = 10\n\nmodel = KNN()\nmodel.train(X, y)\ny_hat = model.predict(X_test, k = k_star)\n\n# Compute and display the acc.\nnum_correct = np.sum(y_hat == y_test)\nacc = float(num_correct) / m_test\nprint 'Got %d / %d correct, acc = %f' % (num_correct, m_test, acc)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
yashdeeph709/Algorithms
|
PythonBootCamp/Complete-Python-Bootcamp-master/Advanced Functions Test Solutions.ipynb
|
apache-2.0
|
[
"Advanced Functions Test Solutions\nFor this test, you should use the built-in functions to be able to write the requested functions in one line.\nProblem 1\nUse map to create a function which finds the length of each word in the phrase\n(broken by spaces) and return the values in a list.\nThe function will have an input of a string, and output a list of integers.",
"def word_lengths(phrase):\n \n return list(map(len, phrase.split()))\n\nword_lengths('How long are the words in this phrase')",
"Problem 2\nUse reduce to take a list of digits and return the number that they\ncorrespond to. Do not convert the integers to strings!",
"def digits_to_num(digits):\n \n return reduce(lambda x,y: x*10 + y,digits)\n\ndigits_to_num([3,4,3,2,1])",
"Problem 3\nUse filter to return the words from a list of words which start with a target letter.",
"def filter_words(word_list, letter):\n \n return filter(lambda word: word[0]==letter,word_list)\n\nl = ['hello','are','cat','dog','ham','hi','go','to','heart']\nfilter_words(l,'h')",
"Problem 4\nUse zip and list comprehension to return a list of the same length where each value is the two strings from\nL1 and L2 concatenated together with connector between them. Look at the example output below:",
"def concatenate(L1, L2, connector):\n \n return [word1+connector+word2 for (word1,word2) in zip(L1,L2)]\n\nconcatenate(['A','B'],['a','b'],'-')",
"Problem 5\nUse enumerate and other skills to return a dictionary which has the values of the list as keys and the index as the value. You may assume that a value will only appear once in the given list.",
"def d_list(L):\n \n return {key:value for value,key in enumerate(L)}\n\nd_list(['a','b','c'])",
"Problem 6\nUse enumerate and other skills from above to return the count of the number of items in the list whose value equals its index.",
"def count_match_index(L):\n \n return len([num for count,num in enumerate(L) if num == count])\n\ncount_match_index([0,2,2,1,5,5,6,10])",
"Great Job!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
besser82/shogun
|
doc/ipython-notebooks/classification/Classification.ipynb
|
bsd-3-clause
|
[
"Visual Comparison Between Different Classification Methods in Shogun\nNotebook by Youssef Emad El-Din (Github ID: <a href=\"https://github.com/youssef-emad/\">youssef-emad</a>)\nThis notebook demonstrates different classification methods in Shogun. The point is to compare and visualize the decision boundaries of different classifiers on two different datasets, where one is linear seperable, and one is not.\n\n<a href =\"#section1\">Data Generation and Visualization</a>\n<a href =\"#section2\">Support Vector Machine</a>\n<a href =\"#section2a\">Linear SVM</a>\n<a href =\"#section2b\">Gaussian Kernel</a>\n<a href =\"#section2c\">Sigmoid Kernel</a>\n<a href =\"#section2d\">Polynomial Kernel</a>\n<a href =\"#section3\">Naive Bayes</a>\n<a href =\"#section4\">Nearest Neighbors</a>\n<a href =\"#section5\">Linear Discriminant Analysis</a>\n<a href =\"#section6\">Quadratic Discriminat Analysis</a>\n<a href =\"#section7\">Gaussian Process</a>\n<a href =\"#section7a\">Logit Likelihood model</a>\n<a href =\"#section7b\">Probit Likelihood model</a>\n<a href =\"#section8\">Putting It All Together</a>",
"%matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nSHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data')\nfrom shogun import *\nimport shogun as sg\n\n#Needed lists for the final plot\nclassifiers_linear = []*10\nclassifiers_non_linear = []*10\nclassifiers_names = []*10\nfadings = []*10",
"<a id = \"section1\">Data Generation and Visualization</a>\nTransformation of features to Shogun format using <a href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1DenseFeatures.html\">RealFeatures</a> and <a href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1BinaryLabels.html\">BinaryLables</a> classes.",
"shogun_feats_linear = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'toy/classifier_binary_2d_linear_features_train.dat')))\nshogun_labels_linear = BinaryLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'toy/classifier_binary_2d_linear_labels_train.dat')))\n\nshogun_feats_non_linear = features(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'toy/classifier_binary_2d_nonlinear_features_train.dat')))\nshogun_labels_non_linear = BinaryLabels(CSVFile(os.path.join(SHOGUN_DATA_DIR, 'toy/classifier_binary_2d_nonlinear_labels_train.dat')))\n\nfeats_linear = shogun_feats_linear.get('feature_matrix')\nlabels_linear = shogun_labels_linear.get('labels')\n\nfeats_non_linear = shogun_feats_non_linear.get('feature_matrix')\nlabels_non_linear = shogun_labels_non_linear.get('labels')",
"Data visualization methods.",
"def plot_binary_data(plot,X_train, y_train):\n \"\"\"\n This function plots 2D binary data with different colors for different labels.\n \"\"\"\n plot.xlabel(r\"$x$\")\n plot.ylabel(r\"$y$\")\n plot.plot(X_train[0, np.argwhere(y_train == 1)], X_train[1, np.argwhere(y_train == 1)], 'ro')\n plot.plot(X_train[0, np.argwhere(y_train == -1)], X_train[1, np.argwhere(y_train == -1)], 'bo')\n\ndef compute_plot_isolines(classifier,feats,size=200,fading=True):\n \"\"\"\n This function computes the classification of points on the grid\n to get the decision boundaries used in plotting\n \"\"\"\n x1 = np.linspace(1.2*min(feats[0]), 1.2*max(feats[0]), size)\n x2 = np.linspace(1.2*min(feats[1]), 1.2*max(feats[1]), size)\n\n x, y = np.meshgrid(x1, x2)\n\n plot_features=features(np.array((np.ravel(x), np.ravel(y))))\n \n if fading == True:\n plot_labels = classifier.apply(plot_features).get('current_values')\n else:\n plot_labels = classifier.apply(plot_features).get('labels')\n z = plot_labels.reshape((size, size))\n return x,y,z\n\ndef plot_model(plot,classifier,features,labels,fading=True):\n \"\"\"\n This function plots an input classification model\n \"\"\"\n x,y,z = compute_plot_isolines(classifier,features,fading=fading)\n plot.pcolor(x,y,z,cmap='RdBu_r')\n plot.contour(x, y, z, linewidths=1, colors='black')\n plot_binary_data(plot,features, labels)\n \n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"Linear Features\")\nplot_binary_data(plt,feats_linear, labels_linear)\nplt.subplot(122)\nplt.title(\"Non Linear Features\")\nplot_binary_data(plt,feats_non_linear, labels_non_linear)",
"<a id=\"section2\" href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1SVM.html\">Support Vector Machine</a>\n<a id=\"section2a\" href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LibLinear.html\">Linear SVM</a>\nShogun provide <a href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1LibLinear.html\">Liblinear</a> which is a library for large-scale linear learning focusing on SVM used for classification",
"plt.figure(figsize=(15,5))\nc = 0.5\nepsilon =1e-3\n\nsvm_linear = LibLinear(c,shogun_feats_linear,shogun_labels_linear)\nsvm_linear.put('liblinear_solver_type', L2R_L2LOSS_SVC) \nsvm_linear.put('epsilon', epsilon)\nsvm_linear.train()\nclassifiers_linear.append(svm_linear)\nclassifiers_names.append(\"SVM Linear\")\nfadings.append(True)\n\nplt.subplot(121)\nplt.title(\"Linear SVM - Linear Features\")\nplot_model(plt,svm_linear,feats_linear,labels_linear)\n\nsvm_non_linear = LibLinear(c,shogun_feats_non_linear,shogun_labels_non_linear)\nsvm_non_linear.put('liblinear_solver_type', L2R_L2LOSS_SVC) \nsvm_non_linear.put('epsilon', epsilon)\nsvm_non_linear.train()\nclassifiers_non_linear.append(svm_non_linear)\n\nplt.subplot(122)\nplt.title(\"Linear SVM - Non Linear Features\")\nplot_model(plt,svm_non_linear,feats_non_linear,labels_non_linear)",
"SVM - Kernels\nShogun provides many options for using kernel functions. Kernels in Shogun are based on two classes which are <a href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1Kernel.html\">Kernel</a> and <a href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1KernelMachine.html\">KernelMachine</a> base class.\n<a id =\"section2b\" href = \"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1GaussianKernel.html\">Gaussian Kernel</a>",
"gaussian_c=0.7\n\ngaussian_kernel_linear=sg.kernel(\"GaussianKernel\", log_width=np.log(100))\ngaussian_svm_linear=sg.machine('LibSVM', C1=gaussian_c, C2=gaussian_c, kernel=gaussian_kernel_linear, labels=shogun_labels_linear)\ngaussian_svm_linear.train(shogun_feats_linear)\nclassifiers_linear.append(gaussian_svm_linear)\nfadings.append(True)\n\ngaussian_kernel_non_linear=sg.kernel(\"GaussianKernel\", log_width=np.log(100))\ngaussian_svm_non_linear=sg.machine('LibSVM', C1=gaussian_c, C2=gaussian_c, kernel=gaussian_kernel_non_linear, labels=shogun_labels_non_linear)\ngaussian_svm_non_linear.train(shogun_feats_non_linear)\nclassifiers_non_linear.append(gaussian_svm_non_linear)\nclassifiers_names.append(\"SVM Gaussian Kernel\")\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"SVM Gaussian Kernel - Linear Features\")\nplot_model(plt,gaussian_svm_linear,feats_linear,labels_linear)\n\nplt.subplot(122)\nplt.title(\"SVM Gaussian Kernel - Non Linear Features\")\nplot_model(plt,gaussian_svm_non_linear,feats_non_linear,labels_non_linear)",
"<a id =\"section2c\" href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CSigmoidKernel.html\">Sigmoid Kernel</a>",
"sigmoid_c = 0.9\n\nsigmoid_kernel_linear = SigmoidKernel(shogun_feats_linear,shogun_feats_linear,200,1,0.5)\nsigmoid_svm_linear = sg.machine('LibSVM', C1=sigmoid_c, C2=sigmoid_c, kernel=sigmoid_kernel_linear, labels=shogun_labels_linear)\nsigmoid_svm_linear.train()\nclassifiers_linear.append(sigmoid_svm_linear)\nclassifiers_names.append(\"SVM Sigmoid Kernel\")\nfadings.append(True)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"SVM Sigmoid Kernel - Linear Features\")\nplot_model(plt,sigmoid_svm_linear,feats_linear,labels_linear)\n\nsigmoid_kernel_non_linear = SigmoidKernel(shogun_feats_non_linear,shogun_feats_non_linear,400,2.5,2)\nsigmoid_svm_non_linear = sg.machine('LibSVM', C1=sigmoid_c, C2=sigmoid_c, kernel=sigmoid_kernel_non_linear, labels=shogun_labels_non_linear)\nsigmoid_svm_non_linear.train()\nclassifiers_non_linear.append(sigmoid_svm_non_linear)\n\nplt.subplot(122)\nplt.title(\"SVM Sigmoid Kernel - Non Linear Features\")\nplot_model(plt,sigmoid_svm_non_linear,feats_non_linear,labels_non_linear)",
"<a id =\"section2d\" href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1CPolyKernel.html\">Polynomial Kernel</a>",
"poly_c = 0.5\ndegree = 4\n\npoly_kernel_linear = sg.kernel('PolyKernel', degree=degree, c=1.0)\npoly_kernel_linear.init(shogun_feats_linear, shogun_feats_linear)\npoly_svm_linear = sg.machine('LibSVM', C1=poly_c, C2=poly_c, kernel=poly_kernel_linear, labels=shogun_labels_linear)\npoly_svm_linear.train()\nclassifiers_linear.append(poly_svm_linear)\nclassifiers_names.append(\"SVM Polynomial kernel\")\nfadings.append(True)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"SVM Polynomial Kernel - Linear Features\")\nplot_model(plt,poly_svm_linear,feats_linear,labels_linear)\n\npoly_kernel_non_linear = sg.kernel('PolyKernel', degree=degree, c=1.0)\npoly_kernel_non_linear.init(shogun_feats_non_linear, shogun_feats_non_linear)\npoly_svm_non_linear = sg.machine('LibSVM', C1=poly_c, C2=poly_c, kernel=poly_kernel_non_linear, labels=shogun_labels_non_linear)\npoly_svm_non_linear.train()\nclassifiers_non_linear.append(poly_svm_non_linear)\n\nplt.subplot(122)\nplt.title(\"SVM Polynomial Kernel - Non Linear Features\")\nplot_model(plt,poly_svm_non_linear,feats_non_linear,labels_non_linear)",
"<a id =\"section3\" href=\"http://www.shogun-toolbox.org/doc/en/latest/classshogun_1_1GaussianNaiveBayes.html\">Naive Bayes</a>",
"multiclass_labels_linear = shogun_labels_linear.get('labels')\nfor i in range(0,len(multiclass_labels_linear)):\n if multiclass_labels_linear[i] == -1:\n multiclass_labels_linear[i] = 0\n\nmulticlass_labels_non_linear = shogun_labels_non_linear.get('labels')\nfor i in range(0,len(multiclass_labels_non_linear)):\n if multiclass_labels_non_linear[i] == -1:\n multiclass_labels_non_linear[i] = 0\n\n\nshogun_multiclass_labels_linear = MulticlassLabels(multiclass_labels_linear)\nshogun_multiclass_labels_non_linear = MulticlassLabels(multiclass_labels_non_linear)\n\nnaive_bayes_linear = GaussianNaiveBayes()\nnaive_bayes_linear.put('features', shogun_feats_linear)\nnaive_bayes_linear.put('labels', shogun_multiclass_labels_linear)\nnaive_bayes_linear.train()\nclassifiers_linear.append(naive_bayes_linear)\nclassifiers_names.append(\"Naive Bayes\")\nfadings.append(False)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"Naive Bayes - Linear Features\")\nplot_model(plt,naive_bayes_linear,feats_linear,labels_linear,fading=False)\n\nnaive_bayes_non_linear = GaussianNaiveBayes()\nnaive_bayes_non_linear.put('features', shogun_feats_non_linear)\nnaive_bayes_non_linear.put('labels', shogun_multiclass_labels_non_linear)\nnaive_bayes_non_linear.train()\nclassifiers_non_linear.append(naive_bayes_non_linear)\n\nplt.subplot(122)\nplt.title(\"Naive Bayes - Non Linear Features\")\nplot_model(plt,naive_bayes_non_linear,feats_non_linear,labels_non_linear,fading=False)",
"<a id =\"section4\" href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1KNN.html\">Nearest Neighbors</a>",
"number_of_neighbors = 10\n\ndistances_linear = sg.distance('EuclideanDistance')\ndistances_linear.init(shogun_feats_linear, shogun_feats_linear)\nknn_linear = KNN(number_of_neighbors,distances_linear,shogun_labels_linear)\nknn_linear.train()\nclassifiers_linear.append(knn_linear)\nclassifiers_names.append(\"Nearest Neighbors\")\nfadings.append(False)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"Nearest Neighbors - Linear Features\")\nplot_model(plt,knn_linear,feats_linear,labels_linear,fading=False)\n\ndistances_non_linear = sg.distance('EuclideanDistance')\ndistances_non_linear.init(shogun_feats_non_linear, shogun_feats_non_linear)\nknn_non_linear = KNN(number_of_neighbors,distances_non_linear,shogun_labels_non_linear)\nknn_non_linear.train()\nclassifiers_non_linear.append(knn_non_linear)\n\nplt.subplot(122)\nplt.title(\"Nearest Neighbors - Non Linear Features\")\nplot_model(plt,knn_non_linear,feats_non_linear,labels_non_linear,fading=False)",
"<a id =\"section5\" href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1CLDA.html\">Linear Discriminant Analysis</a>",
"gamma = 0.1\n\nlda_linear = sg.machine('LDA', gamma=gamma, labels=shogun_labels_linear)\nlda_linear.train(shogun_feats_linear)\nclassifiers_linear.append(lda_linear)\nclassifiers_names.append(\"LDA\")\nfadings.append(True)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"LDA - Linear Features\")\nplot_model(plt,lda_linear,feats_linear,labels_linear)\n\nlda_non_linear = sg.machine('LDA', gamma=gamma, labels=shogun_labels_non_linear)\nlda_non_linear.train(shogun_feats_non_linear)\nclassifiers_non_linear.append(lda_non_linear)\n\nplt.subplot(122)\nplt.title(\"LDA - Non Linear Features\")\nplot_model(plt,lda_non_linear,feats_non_linear,labels_non_linear)",
"<a id =\"section6\" href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1QDA.html\">Quadratic Discriminant Analysis</a>",
"qda_linear = QDA(shogun_feats_linear, shogun_multiclass_labels_linear)\nqda_linear.train()\nclassifiers_linear.append(qda_linear)\nclassifiers_names.append(\"QDA\")\nfadings.append(False)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"QDA - Linear Features\")\nplot_model(plt,qda_linear,feats_linear,labels_linear,fading=False)\n\nqda_non_linear = QDA(shogun_feats_non_linear, shogun_multiclass_labels_non_linear)\nqda_non_linear.train()\nclassifiers_non_linear.append(qda_non_linear)\n\nplt.subplot(122)\nplt.title(\"QDA - Non Linear Features\")\nplot_model(plt,qda_non_linear,feats_non_linear,labels_non_linear,fading=False)",
"<a id =\"section7\" href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1GaussianProcessBinaryClassification.html\">Gaussian Process</a>\n<a id =\"section7a\">Logit Likelihood model</a>\nShogun's <a href= \"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1LogitLikelihood.html\">LogitLikelihood</a> and <a href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1EPInferenceMethod.html\">EPInferenceMethod</a> classes are used.",
"# create Gaussian kernel with width = 2.0\nkernel = sg.kernel(\"GaussianKernel\", log_width=np.log(2))\n# create zero mean function\nzero_mean = ZeroMean()\n# create logit likelihood model\nlikelihood = LogitLikelihood()\n# specify EP approximation inference method\ninference_model_linear = EPInferenceMethod(kernel, shogun_feats_linear, zero_mean, shogun_labels_linear, likelihood)\n# create and train GP classifier, which uses Laplace approximation\ngaussian_logit_linear = GaussianProcessClassification(inference_model_linear)\ngaussian_logit_linear.train()\nclassifiers_linear.append(gaussian_logit_linear)\nclassifiers_names.append(\"Gaussian Process Logit\")\nfadings.append(True)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"Gaussian Process - Logit - Linear Features\")\nplot_model(plt,gaussian_logit_linear,feats_linear,labels_linear)\n\ninference_model_non_linear = EPInferenceMethod(kernel, shogun_feats_non_linear, zero_mean,\n shogun_labels_non_linear, likelihood)\ngaussian_logit_non_linear = GaussianProcessClassification(inference_model_non_linear)\ngaussian_logit_non_linear.train()\nclassifiers_non_linear.append(gaussian_logit_non_linear)\n\nplt.subplot(122)\nplt.title(\"Gaussian Process - Logit - Non Linear Features\")\nplot_model(plt,gaussian_logit_non_linear,feats_non_linear,labels_non_linear)",
"<a id =\"section7b\">Probit Likelihood model</a> \nShogun's <a href=\"http://www.shogun-toolbox.org/doc/en/current/classshogun_1_1ProbitLikelihood.html\">ProbitLikelihood</a> class is used.",
"likelihood = ProbitLikelihood()\n\ninference_model_linear = EPInferenceMethod(kernel, shogun_feats_linear, zero_mean, shogun_labels_linear, likelihood)\ngaussian_probit_linear = GaussianProcessClassification(inference_model_linear)\ngaussian_probit_linear.train()\nclassifiers_linear.append(gaussian_probit_linear)\nclassifiers_names.append(\"Gaussian Process Probit\")\nfadings.append(True)\n\nplt.figure(figsize=(15,5))\nplt.subplot(121)\nplt.title(\"Gaussian Process - Probit - Linear Features\")\nplot_model(plt,gaussian_probit_linear,feats_linear,labels_linear)\n\ninference_model_non_linear = EPInferenceMethod(kernel, shogun_feats_non_linear,\n zero_mean, shogun_labels_non_linear, likelihood)\ngaussian_probit_non_linear = GaussianProcessClassification(inference_model_non_linear)\ngaussian_probit_non_linear.train()\nclassifiers_non_linear.append(gaussian_probit_non_linear)\n\nplt.subplot(122)\nplt.title(\"Gaussian Process - Probit - Non Linear Features\")\nplot_model(plt,gaussian_probit_non_linear,feats_non_linear,labels_non_linear)",
"<a id=\"section8\">Putting It All Together</a>",
"figure = plt.figure(figsize=(30,9))\nplt.subplot(2,11,1)\nplot_binary_data(plt,feats_linear, labels_linear)\nfor i in range(0,10):\n plt.subplot(2,11,i+2)\n plt.title(classifiers_names[i])\n plot_model(plt,classifiers_linear[i],feats_linear,labels_linear,fading=fadings[i])\n\nplt.subplot(2,11,12)\nplot_binary_data(plt,feats_non_linear, labels_non_linear)\n\nfor i in range(0,10):\n plt.subplot(2,11,13+i)\n plot_model(plt,classifiers_non_linear[i],feats_non_linear,labels_non_linear,fading=fadings[i])"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
evanmiltenburg/python-for-text-analysis
|
Chapters-colab/Chapter_15_Off_to_analyzing_text.ipynb
|
apache-2.0
|
[
"<a href=\"https://colab.research.google.com/github/cltl/python-for-text-analysis/blob/colab/Chapters-colab/Chapter_15_Off_to_analyzing_text.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
"%%capture\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Data.zip\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/images.zip\n!wget https://github.com/cltl/python-for-text-analysis/raw/master/zips/Extra_Material.zip\n\n!unzip Data.zip -d ../\n!unzip images.zip -d ./\n!unzip Extra_Material.zip -d ../\n\n!rm Data.zip\n!rm Extra_Material.zip\n!rm images.zip",
"Chapter 15: Off to analyzing text\nWay to go! You have already learned a lot of essential components of the Python language. Being able to deal with data structures, import packages, build your own functions and operate with files is not only essential for most tasks in Python, but also a prerequisite for text analysis. We have applied some common preprocessing steps like casefolding/lowercasing, punctuation removal, and stemming/lemmatization. Did you know that there are some very useful NLP packages and modules that do some of these steps? One that is often used in text analysis is the Python package NLTK (the Natural Language Toolkit).\nAt the end of this chapter, you will be able to:\n\nhave an idea of the NLP tasks that constitute an NLP pipeline\nuse the functions of the NLTK module to manipulate the content of files for NLP purposes (e.g. sentence splitting, tokenization, POS-tagging, and lemmatization);\ndo nesting of multiple for-loops or files\n\nMore NLP software for Python:\n\nNLTK\nSpaCy\nStanford CoreNLP\nAbout Python NLP libraries\n\nIf you have questions about this chapter, please contact us (cltl.python.course@gmail.com).\n1 A short intro to text processing\nThere are many aspects of text we can (try to) analyze. Commonly used analyses conducted in Natural Language Processing (NLP) are for instance:\n\ndetermining the part of speech of words in a text (verb, noun, etc.)\nanalyzing the syntactic relations between words and phrases in a sentence (i.e., syntactic parsing)\nanalyzing which entities (people, organizations, locations) are mentioned in a text\n\n...and many more. Each of these aspects is addressed within its own NLP task. \nThe NLP pipeline\nUsually, these tasks are carried out sequentially because they depend on each other. For instance, we need to first tokenize the text (split it into words) in order to be able to assign part-of-speech tags to each word. This sequence is often called an NLP pipeline. For example, a general pipeline could consist of the components shown below (taken from here) You can see the NLP pipeline of the NewsReader project here. (you can ignore the middle part of the picture, and focus on the blue and green boxes in the outer row).\n<img src='images/nlp-pipeline.jpg'>\nIn this chapter we will look into four simple NLP modules that are nevertheless very common in NLP: tokenization, sentence splitting, lemmatization and POS tagging. \nThere are also more advanced processing modules out there - feel free to do some research yourself :-) \n2 The NLTK package\nNLTK (Natural Language Processing Toolkit) is a module we can use for most fundamental aspects of natural language processing. There are many more advanced approaches out there, but it is a good way of getting started. \nHere we will show you how to use it for tokenization, sentence splitting, POS tagging, and lemmatization. These steps are necessary processing steps for most NLP tasks. \nWe will first give you an overview of all tasks and then delve into each of them in more detail. \nBefore we can use NLTK for the first time, we have to make sure it is downloaded and installed on our computer (some of you may have already done this). \nTo install NLTK, please try to run the following two cells. If this does not work, please try and follow the documentation. If you don't manage to get this to work, please ask for help.",
"%%bash\npip install nltk",
"Once you have downloaded the NLTK book, you do not need to run the download again. If you are using the NLTK again, it is sufficient to import it.",
"# downloading nltk\n\nimport nltk\nnltk.download('book')",
"Now that we have installed and downloaded NLTK, let's look at an example of a simple NLP pipeline. In the following cell, you can observe how we tokenize raw text into tokens and setnences, perform part of speech tagging and lemmatize some of the tokens. Don't worry about the details just yet - we will go trhough them step by step.",
"text = \"This example sentence is used for illustrating some basic NLP tasks. Language is awesome!\"\n\n# Tokenization\ntokens = nltk.word_tokenize(text)\n\n# Sentence splitting\nsentences = nltk.sent_tokenize(text)\n\n# POS tagging\ntagged_tokens = nltk.pos_tag(tokens)\n\n# Lemmatization\nlmtzr = nltk.stem.wordnet.WordNetLemmatizer()\nlemma=lmtzr.lemmatize(tokens[4], 'v')\n\n# Printing all information\nprint(tokens)\nprint(sentences)\nprint(tagged_tokens)\nprint(lemma)",
"2.1 Tokenization and sentence splitting with NLTK\n2.1.1 word_tokenize()\nNow, let's try tokenizing our Charlie story! First, we will open and read the file again and assign the file contents to the variable content. Then, we can call the word_tokenize() function from the nltk module as follows:",
"with open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n\ntokens = nltk.word_tokenize(content)\nprint(type(tokens), len(tokens))\nprint(tokens)",
"As you can see, we now have a list of all words in the text. The punctuation marks are also in the list, but as separate tokens.\n2.1.2 sent_tokenize()\nAnother thing that NLTK can do for you is to split a text into sentences by using the sent_tokenize() function. We use it on the entire text (as a string):",
"with open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n\nsentences = nltk.sent_tokenize(content)\n\nprint(type(sentences), len(sentences))\nprint(sentences)",
"We can now do all sorts of cool things with these lists. For example, we can search for all words that have certain letters in them and add them to a list. Let's say we want to find all present participles in the text. We know that present participles end with -ing, so we can do something like this:",
"# Open and read in file as a string, assign it to the variable `content`\nwith open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n \n# Split up entire text into tokens using word_tokenize():\ntokens = nltk.word_tokenize(content)\n\n# create an empty list to collect all words having the present participle -ing:\npresent_participles = []\n\n# looking through all tokens\nfor token in tokens:\n # checking if a token ends with the present parciciple -ing\n if token.endswith(\"ing\"):\n # if the condition is met, add it to the list we created above (present_participles)\n present_participles.append(token)\n \n# Print the list to inspect it\nprint(present_participles)",
"This looks good! We now have a list of words like boiling, sizzling, etc. However, we can see that there is one word in the list that actually is not a present participle (ceiling). Of course, also other words can end with -ing. So if we want to find all present participles, we have to come up with a smarter solution.\n2.2. Part-of-speech (POS) tagging\nOnce again, NLTK comes to the rescue. Using the function pos_tag(), we can label each word in the text with its part of speech. \nTo do pos-tagging, you first need to tokenize the text. We have already done this above, but we will repeat the steps here, so you get a sense of what an NLP pipeline may look like.\n2.2.1 pos_tag()\nTo see how pos_tag() can be used, we can (as always) look at the documentation by using the help() function. As we can see, pos_tag() takes a tokenized text as input and returns a list of tuples in which the first element corresponds to the token and the second to the assigned pos-tag.",
"# As always, we can start by reading the documentation:\nhelp(nltk.pos_tag)\n\n# Open and read in file as a string, assign it to the variable `content`\nwith open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n \n# Split up entire text into tokens using word_tokenize():\ntokens = nltk.word_tokenize(content)\n\n# Apply pos tagging to the tokenized text\ntagged_tokens = nltk.pos_tag(tokens)\n\n# Inspect pos tags\nprint(tagged_tokens)",
"2.2.2 Working with POS tags\nAs we saw above, pos_tag() returns a list of tuples: The first element is the token, the second element indicates the part of speech (POS) of the token. \nThis POS tagger uses the POS tag set of the Penn Treebank Project, which can be found here. For example, all tags starting with a V are used for verbs. \nWe can now use this, for example, to identify all the verbs in a text:",
"# Open and read in file as a string, assign it to the variable `content`\nwith open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n \n# Apply tokenization and POS tagging\ntokens = nltk.word_tokenize(content)\ntagged_tokens = nltk.pos_tag(tokens)\n\n# List of verb tags (i.e. tags we are interested in)\nverb_tags = [\"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]\n\n# Create an empty list to collect all verbs:\nverbs = []\n\n# Iterating over all tagged tokens\nfor token, tag in tagged_tokens:\n \n # Checking if the tag is any of the verb tags\n if tag in verb_tags:\n # if the condition is met, add it to the list we created above \n verbs.append(token)\n \n# Print the list to inspect it\nprint(verbs)",
"2.3. Lemmatization\nWe can also use NLTK to lemmatize words.\nThe lemma of a word is the form of the word which is usually used in dictionary entries. This is useful for many NLP tasks, as it gives a better generalization than the strong a word appears in. To a computer, cat and cats are two completely different tokens, even though we know they are both forms of the same lemma. \n2.3.1 The WordNet lemmatizer\nWe will use the WordNetLemmatizer for this using the lemmatize() function. In the code below, we loop through the list of verbs, lemmatize each of the verbs, and add them to a new list called verb_lemmas. Again, we show all the processing steps (consider the comments in the code below):",
"#################################################################################\n#### Process text as explained above ###\n\nwith open(\"../Data/Charlie/charlie.txt\") as infile:\n content = infile.read()\n \ntokens = nltk.word_tokenize(content)\ntagged_tokens = nltk.pos_tag(tokens)\n\nverb_tags = [\"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]\nverbs = []\n\nfor token, tag in tagged_tokens:\n if tag in verb_tags:\n verbs.append(token)\n\nprint(verbs)\n\n#############################################################################\n#### Use the list of verbs collected above to lemmatize all the verbs ###\n\n \n# Instatiate a lemmatizer object\nlmtzr = nltk.stem.wordnet.WordNetLemmatizer()\n\n# Create list to collect all the verb lemmas:\nverb_lemmas = []\n \nfor participle in verbs:\n # For this lemmatizer, we need to indicate the POS of the word (in this case, v = verb)\n lemma = lmtzr.lemmatize(participle, \"v\") \n verb_lemmas.append(lemma)\nprint(verb_lemmas)",
"Note about the wordnet lemmatizer: \nWe need to specify a POS tag to the WordNet lemmatizer, in a WordNet format (\"n\" for noun, \"v\" for verb, \"a\" for adjective). If we do not indicate the Part-of-Speech tag, the WordNet lemmatizer thinks it is a noun (this is the default value for its part-of-speech). See the examples below:",
"test_nouns = ('building', 'applications', 'leafs')\nfor n in test_nouns:\n print(f\"Noun in conjugated form: {n}\")\n default_lemma=lmtzr.lemmatize(n) # default lemmatization, without specifying POS, n is interpretted as a noun!\n print(f\"Default lemmatization: {default_lemma}\")\n verb_lemma=lmtzr.lemmatize(n, 'v')\n print(f\"Lemmatization as a verb: {verb_lemma}\")\n noun_lemma=lmtzr.lemmatize(n, 'n')\n print(f\"Lemmatization as a noun: {noun_lemma}\")\n print()\n\ntest_verbs=('grew', 'standing', 'plays')\nfor v in test_verbs:\n print(f\"Verb in conjugated form: {v}\")\n default_lemma=lmtzr.lemmatize(v) # default lemmatization, without specifying POS, v is interpretted as a noun!\n print(f\"Default lemmatization: {default_lemma}\")\n verb_lemma=lmtzr.lemmatize(v, 'v')\n print(f\"Lemmatization as a verb: {verb_lemma}\")\n noun_lemma=lmtzr.lemmatize(v, 'n')\n print(f\"Lemmatization as a noun: {noun_lemma}\")\n print()",
"3 Nesting\nSo far, we typically used a single for-loop, or we were opening a single file at a time. In Python (and most programming languages), one can nest multiple loops or files in one another. For instance, we can use one (outer) for-loop to iterate through files, and then for each file iterate through all its sentences (internal for-loop). As we have learned above, glob is a convenient way of creating a list of files. \nYou might think: can we stretch this on more levels? Iterate through files, then iterate through the sentences in these files, then iterate through each word in these sentences, then iterate through each letter in these words, etc. This is possible. Python (and most programming languages) allow you to perform nesting with (in theory) as many loops as you want. Keep in mind that nesting too much will eventually cause computational problems, but this also depends on the size of your data. \nFor the tasks we are treating here, a a couple of levels of nesting are fine. \nIn the code below, we want get an idea of the number and length of the sentences in the texts stored in the ../Data/Dreams directory. We do this by creating two for loops: We iterate over all the files in the directory (loop 1), apply sentence tokenization and iterate over all the sentences in the file (loop 2).\nLook at the code and comments below to figure out what is going on:",
"import glob\n\n### Loop 1 ####\n# Loop1: iterate over all the files in the dreams directory\nfor filename in glob.glob(\"../Data/Dreams/*.txt\"): \n # read in the file and assign the content to a variable\n with open(filename, \"r\") as infile:\n content = infile.read()\n # split the content into sentences\n sentences = nltk.sent_tokenize(content) \n # Print the number of sentences in the file\n print(f\"INFO: File {filename} has {len(sentences)} sentences\") \n\n # For each file, assign a number to each sentence. Start with 0:\n counter=0\n\n #### Loop 2 ####\n # Loop 2: loop over all the sentences in a file:\n for sentence in sentences:\n # add 1 to the counter\n counter+=1 \n # tokenize the sentence\n tokens=nltk.word_tokenize(sentence) \n # print the number of tokens per sentence\n print(f\"Sentence {counter} has {len(tokens)} tokens\") \n \n # print an empty line after each file (this belongs to loop 1)\n print()",
"4 Putting it all together\nIn this section, we will use what we have learned above to write a small NLP program. We will go through all the steps and show how they can be put together. In the last chapters, we have already learned how to write functions. We will make use of this skill here. \nOur goal is to collect all the nouns from Vickie's dream reports. \nBefore we write actual code, it is always good to consider which steps we need to carry out to reach the goal. \nImportant steps to remember:\n\ncreate a list of all the files we want to process\nopen and read the files\ntokenize the texts\nperform pos-tagging\ncollect all the tokens analyzed as nouns\n\nRemember, we first needed to import nltk to use it. \n4.1 Writing a processing function for a single file\nSince we want to carry out the same task for each of the files, it is very useful (and good practice!) to write a single function which can do the processing. The following function reads the specified file and returns the tokens with their POS tags:",
"import nltk\n\ndef tag_tokens_file(filepath):\n \"\"\"Read the contents of the file found at the location specified in \n FILEPATH and return a list of its tokens with their POS tags.\"\"\"\n with open(filepath, \"r\") as infile:\n content = infile.read()\n tokens = nltk.word_tokenize(content)\n tagged_tokens = nltk.pos_tag(tokens)\n return tagged_tokens",
"Now, instead of having to open a file, read the contents and close the file, we can just call the function tag_tokens_file to do this. We can test it on a single file:",
"filename = \"../Data/Dreams/vickie1.txt\"\ntagged_tokens = tag_tokens_file(filename)\nprint(tagged_tokens)",
"4.2 Iterating over all the files and applying the processing function\nWe can also do this for each of the files in the ../Data/Dreams directory by using a for-loop:",
"import glob\n\n# Iterate over the `.txt` files in the directory and perform POS tagging on each of them\nfor filename in glob.glob(\"../Data/Dreams/*.txt\"): \n tagged_tokens = tag_tokens_file(filename)\n print(filename, \"\\n\", tagged_tokens, \"\\n\")",
"4.3 Collecting all the nouns\nNow, we extend this code a bit so that we don't print all POS-tagged tokens of each file, but we get all (proper) nouns from the texts and add them to a list called nouns_in_dreams. Then, we print the set of nouns:",
"# Create a list that will contain all nouns\nnouns_in_dreams = []\n\n# Iterate over the `.txt` files in the directory and perform POS tagging on each of them\nfor filename in glob.glob(\"../Data/Dreams/*.txt\"): \n tagged_tokens = tag_tokens_file(filename)\n \n # Get all (proper) nouns in the text (\"NN\" and \"NNP\") and add them to the list\n for token, pos in tagged_tokens:\n if pos in [\"NN\", \"NNP\"]:\n nouns_in_dreams.append(token)\n\n# Print the set of nouns in all dreams\nprint(set(nouns_in_dreams))\n",
"Now we have an idea what Vickie dreams about!\nExercises\nExercise 1: \nTry to collect all the present participles in the the text store in ../Data/Charlie/charlie.txt using the NLTK tokenizer and POS-tagger.",
"# you code here",
"You should get the following list: \n['boiling', 'bubbling', 'hissing', 'sizzling', 'clanking', 'running', 'hopping', 'knowing', 'rubbing', 'cackling', 'going']",
"# we can test our code using the assert statement (don't worry about this now, \n# but if you want to use it, you can probably figure out how it works yourself :-) \n# If our code is correct, we should get a compliment :-)\nassert len(present_participles) == 11 and type(present_participles[0]) == str\nprint(\"Well done!\")",
"Exercise 2: \nThe resulting list verb_lemmas above contains a lot of duplicates. Do you remember how you can get rid of these duplicates? Create a set in which each verb occurs only once and name it unique_verbs. Then print it.",
"## the list is stored under the variable 'verb_lemmas'\n\n# your code here\n\n# Test your code here! If your code is correct, you should get a compliment :-)\nassert len(unique_verbs) == 28 \nprint(\"Well done!\")",
"Exercise 3: \nNow use a for-loop to count the number of times that each of these verb lemmas occurs in the text! For each verb in the list you just created, get the count of this verb in charlie.txt using the count() method. Create a dictionary that contains the lemmas of the verbs as keys, and the counts of these verbs as values. Refer to the notebook about Topic 1 if you forgot how to use the count() method or how to create dictionary entries!\nTip: you don't need to read in the file again, you can just use the list called verb_lemmas.",
"verb_counts = {}\n\n# Finish this for-loop\nfor verb in unique_verbs:\n # your code here\n\nprint(verb_counts) \n\n# Test your code here! If your code is correct, you should get a compliment :-)\nassert len(verb_counts) == 28 and verb_counts[\"bubble\"] == 1 and verb_counts[\"be\"] == 9\nprint(\"Well done!\")",
"Exercise 4:\nWrite your counts to a file called charlie_verb_counts.txt and write it to ../Data/Charlie/charlie_verb_counts.txt in the following format:\nverb, count\nverb, count \n...\nDon't forget to use newline characters at the end of each line."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
statsmodels/statsmodels.github.io
|
v0.13.0/examples/notebooks/generated/mediation_survival.ipynb
|
bsd-3-clause
|
[
"Mediation analysis with duration data\nThis notebook demonstrates mediation analysis when the\nmediator and outcome are duration variables, modeled\nusing proportional hazards regression. These examples\nare based on simulated data.",
"import pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\nfrom statsmodels.stats.mediation import Mediation",
"Make the notebook reproducible.",
"np.random.seed(3424)",
"Specify a sample size.",
"n = 1000",
"Generate an exposure variable.",
"exp = np.random.normal(size=n)",
"Generate a mediator variable.",
"def gen_mediator():\n mn = np.exp(exp)\n mtime0 = -mn * np.log(np.random.uniform(size=n))\n ctime = -2 * mn * np.log(np.random.uniform(size=n))\n mstatus = (ctime >= mtime0).astype(int)\n mtime = np.where(mtime0 <= ctime, mtime0, ctime)\n return mtime0, mtime, mstatus",
"Generate an outcome variable.",
"def gen_outcome(otype, mtime0):\n if otype == \"full\":\n lp = 0.5 * mtime0\n elif otype == \"no\":\n lp = exp\n else:\n lp = exp + mtime0\n mn = np.exp(-lp)\n ytime0 = -mn * np.log(np.random.uniform(size=n))\n ctime = -2 * mn * np.log(np.random.uniform(size=n))\n ystatus = (ctime >= ytime0).astype(int)\n ytime = np.where(ytime0 <= ctime, ytime0, ctime)\n return ytime, ystatus",
"Build a dataframe containing all the relevant variables.",
"def build_df(ytime, ystatus, mtime0, mtime, mstatus):\n df = pd.DataFrame(\n {\n \"ytime\": ytime,\n \"ystatus\": ystatus,\n \"mtime\": mtime,\n \"mstatus\": mstatus,\n \"exp\": exp,\n }\n )\n return df",
"Run the full simulation and analysis, under a particular\npopulation structure of mediation.",
"def run(otype):\n\n mtime0, mtime, mstatus = gen_mediator()\n ytime, ystatus = gen_outcome(otype, mtime0)\n df = build_df(ytime, ystatus, mtime0, mtime, mstatus)\n\n outcome_model = sm.PHReg.from_formula(\n \"ytime ~ exp + mtime\", status=\"ystatus\", data=df\n )\n mediator_model = sm.PHReg.from_formula(\"mtime ~ exp\", status=\"mstatus\", data=df)\n\n med = Mediation(\n outcome_model,\n mediator_model,\n \"exp\",\n \"mtime\",\n outcome_predict_kwargs={\"pred_only\": True},\n )\n med_result = med.fit(n_rep=20)\n print(med_result.summary())",
"Run the example with full mediation",
"run(\"full\")",
"Run the example with partial mediation",
"run(\"partial\")",
"Run the example with no mediation",
"run(\"no\")"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
mwickert/scikit-dsp-comm
|
docs/source/nb_examples/Multirate_Processing.ipynb
|
bsd-2-clause
|
[
"%pylab inline\nimport sk_dsp_comm.sigsys as ss\nimport sk_dsp_comm.fir_design_helper as fir_d\nimport sk_dsp_comm.iir_design_helper as iir_d\nimport sk_dsp_comm.multirate_helper as mrh\nimport scipy.signal as signal\nfrom IPython.display import Audio, display\nfrom IPython.display import Image, SVG\n\n%config InlineBackend.figure_formats=['svg'] # SVG inline viewing",
"Multirate Signal Processing Using multirate_helper\nIn this section the classes multirate_FIR and multirate_IIR, found in the module sk_dsp_comm.multirate_helper, are discussed with the aim of seeing how they can be used to filter, interpolate (upsample and filter), and decimate (filter and downsample) discrete time signals. Fundamentally the processing consists of two elements: (1) and upsampler or downsampler and (2) a lowpass filter. \nFundamentally this modules provides classes to change the sampling rate by an integer factor, either up, interpolation or down, decimation, with integrated filtering to supress spectral images or aliases, respectively. The top level block diagram of the interpolator and decimator are given in the following two figures. The frequencies given in the figures assume that the interpolator is rate chainging from 8 ksps to 96 ksps ($L=12$) and the decimator is rate changing from 96 ksps to 8 ksps ($M=12$). This is for example purposes only. The FIR/IIR filter cutoff frequency will in general be $f_c = f_\\text{s,out}/(2L)$ for the decimator and $f_c = f_\\text{s,in}/(2M)$. The primitives to implement the classes are available in sk_dsp_comm.sigsys and scipy.signal.",
"Image('300ppi/Interpolator_Top_Level@300ppi.png',width='60%')\n\nImage('300ppi/Decimator_Top_Level@300ppi.png',width='60%')",
"The upsample block, shown above with arrow pointing up and integer $L=12$ next to the arrow, takes the input sequence and produces the output sequence by inserting $L-1$ (as shown here 11) zero samples between each input sample. The downsample block, shown above with arrow pointing down and integer $M=12$ next to the arrow, takes the input sequence and retains at the output sequence every $M$th (as shown here 12th) sample.\nThe impact of these blocks in the frequency domain is a little harder to explain. In words, the spectrum at the output of the upsampler is compressed by the factor $L$, such that it will contain $L$ spectral images, including the fundamental image centered at $f = 0$, evenly spaced up to the sampling $f_s$. Overall the spectrum of $x_\\text{up}[n]$ is of course periodic with respect to the sampling rate. The lowpass filter interpolates signal sample values from the non-zero samples where the zero samples reside. It is this interpolation that effectively removed or suppresses the spectral images outside the interval $|f| > f_s/(2L)$.\nFor the downsampler the input spectrum is stretched along the frequency axis by the factor $M$, with aliasing from frequency bands outside $|f| < f_s/(2M)$. To avoid aliasing the lowpass filter blocks input signals for $f > f_s/(2M)$.\nTo get started using the module you will need an import similar to:\npython\nimport sk_dsp_comm.multirate_helper as mrh\nThe rate_change Class\nWe start with the description of a third class, mrh.rate_change, which is simplistic, offering little user interaction, but automatically designs the required lowpass filter you see in the above block diagrams. Below is a table which describes this class:",
"Image('300ppi/Multirate_Table1@300ppi.png',width='85%')",
"This class is used in the analog modulation demos for the ECE 4625/5625 Chapter 3 Jupyter notebook. Using this class you can quickly create a interpolation or decimation block with the necessary lowpass filter automatically designed and implemented. Fine tuning of the filter is limited to choosing the filter order and the cutoff frequency as a fraction of the signal bandwidth given the rate change integer, $L$ or $M$. The filter type is also limited to Butterworth or Chebyshev type 1 having passband ripple of 0.05 dB.\nA Simple Example\nPass a sinusoidal signal through an $L=4$ interpolator. Verify that spectral images occur with the use of the interpolation lowpass filter.",
"fs_in = 8000\nM = 4\nfs_out = M*fs_in\nrc1 = mrh.rate_change(M) # Rate change by 4\nn = arange(0,1000)\nx = cos(2*pi*1000/fs_in*n)\nx_up = ss.upsample(x,4)\ny = rc1.up(x)",
"Time Domain",
"subplot(211)\nstem(n[500:550],x_up[500:550]);\nylabel(r'$x_{up}[n]$')\ntitle(r'Upsample by $L=4$ Output')\n#ylim(-100,-10)\nsubplot(212)\nstem(n[500:550],y[500:550]);\nylabel(r'$y[n]$')\nxlabel(r'')\ntitle(r'Interpolate by $L=4$ Output')\n#ylim(-100,-10)\ntight_layout()",
"Clearly the lowpass interpolation filter has done a good job of filling in values for the zero samples\n\nFrequency Domain",
"subplot(211)\npsd(x_up,2**10,fs_out);\nylabel(r'PSD (dB)')\ntitle(r'Upsample by $L=4$ Output')\nylim(-100,-10)\nsubplot(212)\npsd(y,2**10,fs_out);\nylabel(r'PSD (dB)')\ntitle(r'Interpolate by $L=4$ Output')\nylim(-100,-10)\ntight_layout()",
"The filtering action of the LPF does its best to suppress the images at 7000, 9000, and 15000 Hz.\n\nThe multirate_FIR Class\nWith this class you implement an object that can filter, interpolate, or decimate a signal. Additionally support methods drill into the characteristics of the lowpass filter at the heart of the processing block. To use this class the user must supply FIR filter coefficients that implement a lowpass filter with cutoff frequency appropriate for the desired interpolation of decimation factor. The module sk_dsp_com.FIR_design_helper is capable of delivering the need filter coefficients array. See FIR design helper notes for multirate filter design examples.\nWith FIR coefficients in hand it is an easy matter to create an multirate FIR object capable of filtering, interpolation, or decimation. The details of the class interface are given in Table 2 below.",
"Image('300ppi/Multirate_Table2@300ppi.png',width='85%')",
"Notice that the class also provides a means to obtain frequency response plots and pole-zero plots directly from the instantiated multirate objects.\nFIR Interpolator Design Example\nHere we take the earlier lowpass filter designed to interpolate a signal being upsampled from $f_{s1} = 8000$ kHz to $f_{s2} = 96$ kHz. The upsampling factor is $L = f_{s2}/f_{s1} = 12$. The ideal interpolation filter should cutoff at $f_{s1}/2 = f_{s2}/(2\\cdot 12) = 8000/2 = 4000$ Hz.\nRecall the upsampler (y = ss.upsampler(x, L)) inserts $L-1$ samples between each input sample. In the frequency domain the zero insertion replicates the input spectrum on $[0,f_{s1}/2]$ $L$ times over the interval $[0,f_{s2}]$ (equivalently $L/2$ times on the inteval $[0f_{s2}/2]$. The lowpass interpolation filter serves to removes the images above $f_{s2}/(2L)$ in the frequency domain and in so doing filling in the zeros samples with waveform interpolants in the time domain.",
"# Design the filter core for an interpolator used in changing the sampling rate from 8000 Hz\n# to 96000 Hz\nb_up = fir_d.fir_remez_lpf(3300,4300,0.5,60,96000)\n# Create the multirate object\nmrh_up = mrh.multirate_FIR(b_up)",
"As an input consider a sinusoid at 1 kHz and observe the interpolator output spectrum compared with the input spectrum.",
"# Sinusoidal test signal\nn = arange(10000)\nx = cos(2*pi*1000/8000*n)\n# Interpolate by 12 (upsample by 12 followed by lowpass filter)\ny = mrh_up.up(x,12)\n\n# Plot the results\nsubplot(211)\npsd(x,2**12,8000);\ntitle(r'1 KHz Sinusoid Input to $L=12$ Interpolator')\nylabel(r'PSD (dB)')\nylim([-100,0])\nsubplot(212)\npsd(y,2**12,12*8000)\ntitle(r'1 KHz Sinusoid Output from $L=12$ Interpolator')\nylabel(r'PSD (dB)')\nylim([-100,0])\ntight_layout()",
"In the above spectrum plots notice that images of the input 1 kHz sinusoid are down $\\simeq 60$ dB, which is precisely the stop band attenuation provided by the interpolation filter. The variation is due to the stopband ripple.\nThe multirate_IIR Class\nWith this class, as with multirate_FIR you implement an object that can filter, interpolate, or decimate a signal. The filter in this case is a user supplied IIR filter in second-order sections (sos) form. Additionally support methods drill into the characteristics of the lowpass filter at the heart of the procssing block. The module sk_dsp_com.IIR_design_helper is capable of delivering the need filter coefficients array. See IIR design helper notes for multirate filter design examples.\nWith IIR coefficients in hand it is an easy matter to create an multirate IIR object capable of filtering, interpolation, or decimation. The details of the class interface are given in Table 3 below.",
"Image('300ppi/Multirate_Table3@300ppi.png',width='85%')",
"IIR Decimator Design Example\nWhan a signal is decimated the signal is first lowpass filtered then downsampled. The lowpass filter serves to prevent aliasing as the sampling rate is reduced. Downsampling by $M$ (y = ss.downsample(x, M)) removes $M-1$ sampling for every $M$ sampling input or equivalently retains one sample out of $M$. The lowpass prefilter has cutoff frequency equal to the folding frequency of the output sampling rate, i.e., $f_c = f_{s2}/2$. Note avoid confusion with the project requirements, where the decimator is needed to take a rate $f_{s2}$ signal back to $f_{s1}$, let the input sampling rate be $f_{s2} = 96000$ HZ and the output sampling rate be $f_{s1} = 8000$ Hz. The input sampling rate is $M$ times the output rate, i.e., $f_{s2} = Mf_{s1}$, so you design the lowpass filter to have cutoff $f_c = f_{s2}/(2\\cdot L)$.\nECE 5625 Important Observation: In the coherent SSB demodulator of Project 1, the decimator can be conveniently integrated with the lowpass filter that serves to remove the double frequency term.\nIn the example that follows a Chebyshev type 1 lowpass filter is designed to have cutoff around 4000 Hz. A sinusoid is used as a test input signal at sampling rate 96000 Hz.",
"# Design the filter core for a decimator used in changing the \n# sampling rate from 96000 Hz to 8000 Hz\nb_dn, a_dn, sos_dn = iir_d.IIR_lpf(3300,4300,0.5,60,96000,'cheby1')\n# Create the multirate object\nmrh_dn = mrh.multirate_IIR(sos_dn)\nmrh_dn.freq_resp('dB',96000)\ntitle(r'Decimation Filter Frequency Response - Magnitude');",
"Note the Chebyshev lowpass filter design above is very efficient compared with the 196-tap FIR lowpass designed for use in the interpolator. It is perhaps a better overall choice. The FIR has linear phase and the IIR filter does not, but for the project this is not really an issue.\n\nAs an input consider a sinusoid at 1 kHz and observe the interpolator output spectrum compared with the input spectrum.",
"# Sinusoidal test signal\nn = arange(100000)\nx = cos(2*pi*1000/96000*n)\n# Decimate by 12 (lowpass filter followed by downsample by 12)\ny = mrh_dn.dn(x,12)\n\n# Plot the results\nsubplot(211)\npsd(x,2**12,96000);\ntitle(r'1 KHz Sinusoid Input to $M=12$ Decimator')\nylabel(r'PSD (dB)')\nylim([-100,0])\nsubplot(212)\npsd(y,2**12,8000)\ntitle(r'1 KHz Sinusoid Output from $M=12$ Decimator')\nylabel(r'PSD (dB)')\nylim([-100,0])\ntight_layout()"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
JohnPHogan/FantasyFootball
|
Variances.ipynb
|
bsd-2-clause
|
[
"| Stat Category | Point Value |\n|---------------------|---------------------------|\n|Passing Yards | 1 point for every 25 yards|\n|Rushing Yards | 1 point for every 10 yards|\n|Rushing TDs | 6 points |\n|Receiving Yards | 1 point for every 10 yards|\n|Receiving TDs | 6 points |\n|Interceptions | -2 points |\nSet environment",
"%matplotlib inline\n\nimport pandas as pd\nimport matplotlib as mp\nimport numpy as np\nimport seaborn as sns",
"Read in footballdb 2016 summary stats for QBs, RBs, and WRs",
"football_db = pd.read_csv('FootballDB2016YearlyStats.csv')\nfootball_db.columns.values\n",
"Get the Variances between the provided Fantasy Score and the Calculated score",
"football_db['FantasyVariance'] = (football_db.FantasyPts / football_db.CalcFantasyPoints)\n# Correct any divide by 0 errors\nfootball_db['FantasyVariance'].replace([np.inf, -np.inf], 0) \nprint('Done')\n\nfootball_db.to_csv('Checkdata.csv')",
"Calculate the mean, the median and the standard variation",
"fantasy_mean = football_db.FantasyVariance.mean()\nfantasy_median = football_db.FantasyVariance.median()\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\n\n\n\n\n# \n\nx = football_db['FantasyVariance']\nsns.set_context('poster')\nsns.set_style(\"ticks\")\n\ng=sns.distplot(x,\n kde_kws={\"color\":\"g\",\"lw\":4,\"label\":\"KDE Estim\",\"alpha\":0.5},\n hist_kws={\"color\":\"r\",\"alpha\":0.3,\"label\":\"Freq\"})\n\n\n# remove the top and right line in graph\nsns.despine()\n\n# Set the size of the graph from here\ng.figure.set_size_inches(12,7)\n# Set the Title of the graph from here\ng.axes.set_title('Provided and Calculated Fantasy Point Variance Distribution', fontsize=34,color=\"b\",alpha=0.3)\n# Set the xlabel of the graph from here\ng.set_xlabel(\"Variance\",size = 67,color=\"g\",alpha=0.5)\n# Set the ylabel of the graph from here\ng.set_ylabel(\"Density\",size = 67,color=\"r\",alpha=0.5)\n# Set the ticklabel size and color of the graph from here\ng.tick_params(labelsize=14,labelcolor=\"black\")\n\nqb = football_db.loc[football_db.Pos == 'QB']\nx = qb['FantasyVariance']\nfantasy_mean = x.mean()\nfantasy_median = x.median()\nfantasy_std = np.std(x)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\ng=sns.distplot(x)\n\n\nrb = football_db.loc[football_db.Pos == 'RB']\nprint(type(rb))\nx = rb['FantasyVariance']\nfantasy_mean = x.mean()\nfantasy_median = x.median()\n\nfantasy_std = np.std(x)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\ng=sns.distplot(x)\n\n\n\nwr = football_db.loc[football_db.Pos == 'WR']\nx = wr['FantasyVariance']\nfantasy_mean = x.mean()\nfantasy_median = x.median()\nfantasy_std = np.std(x)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\n\ng=sns.distplot(x,\n kde_kws={\"color\":\"g\",\"lw\":4,\"label\":\"KDE Estim\",\"alpha\":0.5},\n hist_kws={\"color\":\"r\",\"alpha\":0.3,\"label\":\"Freq\"})\n\n",
"Only has to be run once.\nIf 'Name' exists in Checkdata.csv, this step can be skipped. This will format the 'Player' data column scraped from the footballdb.com website, which has this format: \"Aaron Rodgers, GB\", and writes out a 'Name' data column that will match the game by game Name field and look like this: \"rodgers, aaron\"",
"name = []\nfor index, row in football_db.iterrows():\n full_name = row.Player\n split_name = full_name.split()\n first_name = split_name[0]\n last_name = split_name[1]\n name.append(last_name.lower() + ' ' + first_name.lower())\n \nfootball_db['Name'] = name\nfootball_db.to_csv('Checkdata.csv')\nprint('Done!')\n \n\nqb_games = pd.read_csv('qb_games.csv')\nqb_games['FantasyPoints'] = (qb_games['Pass Yds']/25) + (6 * qb_games['Pass TD']) - (2 * qb_games['Pass Int']) + (qb_games['Rush Yds'] /10) + (6 * qb_games['Rush TD'])\nqb_games.columns.values\n\nfootballdb_qb = football_db.loc[football_db.Pos == 'QB']\nfootballdb_qb.head(10)\n\nqb_games2016 = qb_games.loc[qb_games.Year == 2016]\n\nqb_games2016 = qb_games2016[['Name', 'FantasyPoints']]\nfootball_db_qb = footballdb_qb[['Name', 'CalcFantasyPoints']]\nqb_games2016_sum = qb_games2016.groupby(['Name'], as_index=False).sum()\n\nfootball_db_qb.head(10)\n\nqb_merged = qb_games2016_sum.merge(football_db_qb, on='Name')\nprint(len(qb_games2016_sum))\nprint(len(qb_merged))\n\nqb_var = qb_merged.FantasyPoints / qb_merged.CalcFantasyPoints\n\nfantasy_mean = qb_var.mean()\nfantasy_median = qb_var.median()\nfantasy_std = np.std(qb_var)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\n\ng=sns.distplot(qb_var,\n kde_kws={\"color\":\"g\",\"lw\":4,\"label\":\"KDE Estim\",\"alpha\":0.5},\n hist_kws={\"color\":\"r\",\"alpha\":0.3,\"label\":\"Freq\"})\n\n\n\n\n\nrb_games = pd.read_csv('rb_games.csv')\nrb_games['FantasyPoints'] = ((rb_games['Rush Yds'] + rb_games['Rec Yds']) / 10) + ((rb_games['Rush TD'] + rb_games['Rec TD']) *6)\n\nrb_games2016 = rb_games.loc[rb_games.Year == 2016]\n\nfootballdb_rb = football_db.loc[football_db.Pos == 'RB']\nprint(len(footballdb_rb))\n\nrb_games2016 = rb_games2016[['Name', 'FantasyPoints']]\nfootball_db_rb = footballdb_rb[['Name', 'CalcFantasyPoints']]\nrb_games2016_sum = rb_games2016.groupby(['Name'], as_index=False).sum()\nrb_games2016_sum.head(32)\n\nrb_merged = rb_games2016_sum.merge(football_db_rb, on='Name')\nprint(len(rb_games2016_sum))\nprint(len(rb_merged))\n\nrb_var = rb_merged.FantasyPoints / rb_merged.CalcFantasyPoints\n\nfantasy_mean = rb_var.mean()\nfantasy_median = rb_var.median()\nfantasy_std = np.std(rb_var)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\n\ng=sns.distplot(rb_var,\n kde_kws={\"color\":\"g\",\"lw\":4,\"label\":\"KDE Estim\",\"alpha\":0.5},\n hist_kws={\"color\":\"r\",\"alpha\":0.3,\"label\":\"Freq\"})\n\n\n\n\nwr_games = pd.read_csv('wr_games.csv')\nwr_games['FantasyPoints'] = ((wr_games['Rush Yds'] + wr_games['Rec Yds']) / 10) + ((wr_games['Rush TD'] + wr_games['Rec TD']) *6)\n\nwr_games2016 = wr_games.loc[wr_games.Year == 2016]\n\nfootballdb_wr = football_db.loc[football_db.Pos == 'WR']\nprint(len(footballdb_wr))\n\nwr_games2016 = wr_games2016[['Name', 'FantasyPoints']]\nfootballdb_wr = footballdb_wr[['Name', 'CalcFantasyPoints']]\nwr_games2016_sum = wr_games2016.groupby(['Name'], as_index=False).sum()\nprint(len(wr_games2016_sum))\nwr_games2016_sum.head(32)\n\nwr_merged = wr_games2016_sum.merge(footballdb_wr, on='Name')\nprint(len(wr_games2016_sum))\nprint(len(wr_merged))\n\nwr_var = wr_merged.FantasyPoints / wr_merged.CalcFantasyPoints\n\nfantasy_mean = wr_var.mean()\nfantasy_median = wr_var.median()\nfantasy_std = np.std(wr_var)\nprint('The mean for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_mean))\nprint('The median for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_median))\nprint('The standard deviation for the variance between provided score and the calculated score is: {0:.4f}.'.format(fantasy_std))\n\n\n\ng=sns.distplot(wr_var,\n kde_kws={\"color\":\"g\",\"lw\":4,\"label\":\"KDE Estim\",\"alpha\":0.5},\n hist_kws={\"color\":\"r\",\"alpha\":0.3,\"label\":\"Freq\"})\n\n\n\n\n\nqb_by_year = qb_games.groupby(['Name', 'Year', 'Career Year'], as_index=False)[['FantasyPoints']].sum()\nqb_by_year['FantasyMean'] = qb_by_year.FantasyPoints / 16\nqb2013 = qb_by_year.loc[qb_by_year.Year == 2013].sort_values(['FantasyPoints'], ascending=False)\nqb2013 = qb2013.head(20)\nqb2013_fp_mean = qb2013.FantasyPoints.mean()\nqb2013_fm_mean = qb2013.FantasyMean.mean()\nprint('The 2013 fantasy score mean is: %d' %(qb2013_fp_mean))\nprint('The 2013 fantasy mean is: %d' %(qb2013_fm_mean))\n\n\nqb2014 = qb_by_year.loc[qb_by_year.Year == 2014].sort_values(['FantasyPoints'], ascending=False)\nqb2014 = qb2014.head(20)\nqb2014_fp_mean = qb2014.FantasyPoints.mean()\nqb2014_fm_mean = qb2014.FantasyMean.mean()\nprint('The 2014 fantasy score mean is: %d' %(qb2014_fp_mean))\nprint('The 2014 fantasy mean is: %d' %(qb2014_fm_mean))\n\n\nqb2015 = qb_by_year.loc[qb_by_year.Year == 2015].sort_values(['FantasyPoints'], ascending=False)\nqb2015_fp_mean = qb2015.FantasyPoints.mean()\nqb2015_fm_mean = qb2015.FantasyMean.mean()\nprint('The 2015 fantasy score mean is: %d' %(qb2015_fp_mean))\nprint('The 2015 fantasy mean is: %d' %(qb2015_fm_mean))\nqb2015.head(20)\n\nqb2016 = qb_by_year.loc[qb_by_year.Year == 2016].sort_values(['FantasyPoints'], ascending=False)\nqb2016_fp_mean = qb2016.FantasyPoints.mean()\nqb2016_fm_mean = qb2016.FantasyMean.mean()\nprint('The 2016 fantasy score mean is: %d' %(qb2016_fp_mean))\nprint('The 2016 fantasy mean is: %d' %(qb2016_fm_mean))\nqb2016.head(20)\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='Pass Att', x='Career Year', data=qb_by_year)\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='Pass Rate', x='Career Year', data=qb_by_year)\n\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='FantasyPoints', x='Career Year', data=qb_by_year)\n\n\nqb_min_passes_by_year = qb_by_year.loc[qb_by_year['Pass Att'] > 20]\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='FantasyPoints', x='Career Year', data=qb_min_passes_by_year)\n\nqb_min_rate_by_year = qb_by_year.loc[qb_by_year['Pass Rate'] > 55]\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='FantasyPoints', x='Career Year', data=qb_min_passes_by_year)\n\nqb_min_comb_by_year = qb_by_year.loc[(qb_by_year['Pass Rate'] > 55) & (qb_by_year['Pass Att'] > 20) & (qb_by_year['FantasyPoints'] > 20)]\n\n\nqb_min_comb_by_year = qb_by_year.loc[(qb_by_year['Pass Rate'] > 55) & (qb_by_year['Pass Att'] > 20) & (qb_by_year['FantasyPoints'] > 20)]\n\nsns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='FantasyPoints', x='Career Year', data=qb_min_comb_by_year)",
"Find the lowest Fantasy Football Scores for a QB\nAnd assign the 20 worst scores to the qb_lowest dataframe",
"qb_Fantasy = qb_games.sort_values(['FantasyPoints'], ascending=True)\nqb_lowest = qb_Fantasy[['Name', 'Year', 'Career Year', 'Pass Att', 'Pass Yds', 'Pass TD', 'Pass Int', 'Rush Yds', 'Rush TD', 'FantasyPoints']].head(20)",
"Merge the names of the QB's with the lowest Fantasy Score of all time back into the larger dataframe to get their career stats",
"qb_lowest = qb_Fantasy.head(20)[['Name', 'Career Year']]\n# Merge on Name with the qb_games dataframe\nqb_low_career = qb_games.merge(qb_lowest, on='Name')\nprint('The number of quarterbacks who generated the 20 worst scores are: %d'%(len(qb_low_career.Name.unique())))\nqb_low_career.Name.unique()\n",
"Create a Scatter plot showing the career performances for the QB's who had the 20 worst Fantasy Football point games",
"sns.set_context(\"notebook\", font_scale=1.1)\nsns.set_style(\"ticks\")\n\n\nsns.lmplot(y='FantasyPoints', x='Career Year_x', data=qb_low_career)",
"Group these players by name and by career year and create a Scatter Plot",
"qb_career = qb_low_career.groupby(['Name', 'Career Year_x'], as_index=False).mean()\nprint(len(qb_career.Name.unique()))\nsns.lmplot(y='FantasyPoints', x='Career Year_x', data=qb_career)\n\nqb_Fantasy = qb_games.sort_values(['FantasyPoints'], ascending=False)\nqb_top_games = qb_Fantasy[['Name', 'Year', 'Career Year', 'Pass Att', 'Pass Yds', 'Pass TD', 'Pass Int', 'Rush Yds', 'Rush TD', 'FantasyPoints']].head(20)\n\nqb_pass_att = qb_games.loc[(qb_games['Pass Att'] > 20) & (qb_games['Pass Rate'] > 90) & (qb_games['FantasyPoints'] > 20)]\nprint(type(qb_pass_att))\nsns.lmplot(x='Career Year', y='FantasyPoints', data=qb_pass_att)\n\nsns.lmplot(x='Rush Att', y='FantasyPoints', data=rb_games)\n\nsns.lmplot(x='Career Year', y='FantasyPoints', data=wr_games)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
iAInNet/tensorflow_in_action
|
_pratice_cifar10.ipynb
|
gpl-3.0
|
[
"import cifar10_input\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport math",
"全局参数",
"max_steps = 3000\nbatch_size = 128\ndata_dir = 'data/cifar10/cifar-10-batches-bin/'\nmodel_dir = 'model/_cifar10_v2/'",
"初始化权重\n如果需要,会给权重加上L2 loss。为了在后面计算神经网络的总体loss的时候被用上,需要统一存到一个collection。\n加载数据\n使用cifa10_input来获取数据,这个文件来自tensorflow github,可以下载下来直接使用。如果使用distorted_input方法,那么得到的数据是经过增强处理的。会对图片随机做出切片、翻转、修改亮度、修改对比度等操作。这样就能多样化我们的训练数据。\n得到一个tensor,batch_size大小的batch。并且可以迭代的读取下一个batch。",
"X_train, y_train = cifar10_input.distorted_inputs(data_dir, batch_size)\n\nX_test, y_test = cifar10_input.inputs(eval_data=True, data_dir=data_dir, batch_size=batch_size)\n\nimage_holder = tf.placeholder(tf.float32, [batch_size, 24, 24, 3])\nlabel_holder = tf.placeholder(tf.int32, [batch_size])",
"第一个卷积层\n同样的,我们使用5x5卷积核,3个通道(input_channel),64个output_channel。不对第一层的参数做正则化,所以将lambda_value设定为0。其中涉及到一个小技巧,就是在pool层,使用了3x3大小的ksize,但是使用2x2的stride,这样增加数据的丰富性。最后使用LRN。LRN最早见于Alex参见ImageNet的竞赛的那篇CNN论文中,Alex在论文中解释了LRN层模仿了生物神经系统的“侧抑制”机制,对局部神经元的活动创建竞争环境,使得其中响应比较大的值变得相对更大,并抑制其他反馈较小的神经元,增加了模型的泛化能力。不过在之后的VGGNet论文中,对比了使用和不使用LRN两种模型,结果表明LRN并不能提高模型的性能。不过这里还是基于AlexNet的设计将其加上。",
"weight1 = variable_with_weight_loss([5, 5, 3, 64], stddev=0.05, lambda_value=0)\nkernel1 = tf.nn.conv2d(image_holder, weight1, [1, 1, 1, 1], padding='SAME')\nbias1 = tf.Variable(tf.constant(0.0, shape=[64]))\nconv1 = tf.nn.relu(tf.nn.bias_add(kernel1, bias1))\npool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')\nnorm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75)",
"第二个卷积层\n\n输入64个channel,输出依然是64个channel\n设定bias的大小为0.1\n调换最大池化层和LRN的顺序,先进行LRN然后再最大池化层\n\n但是为什么要这么做,完全不知道?\n多看论文。",
"weight2 = variable_with_weight_loss(shape=[5, 5, 64, 64], stddev=5e-2, lambda_value=0.0)\nkernel2 = tf.nn.conv2d(norm1, weight2, strides=[1, 1, 1, 1], padding='SAME')\nbias2 = tf.Variable(tf.constant(0.1, shape=[64]))\nconv2 = tf.nn.relu(tf.nn.bias_add(kernel2, bias2))\nnorm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001/9.0, beta=0.75)\npool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME')",
"第一个全连接层\n\n要将卷积层拉伸\n全连接到新的隐藏层,设定为384个节点\n正态分布设定为0.04,bias设定为0.1\n重点是,在这里我们还设定weight loss的lambda数值为0.04",
"flattern = tf.reshape(pool2, [batch_size, -1])\ndim = flattern.get_shape()[1].value\nweight3 = variable_with_weight_loss(shape=[dim, 384], stddev=0.04, lambda_value=0.04)\nbias3 = tf.Variable(tf.constant(0.1, shape=[384]))\nlocal3 = tf.nn.relu(tf.matmul(flattern, weight3) + bias3)",
"第二个全连接层\n\n下降为192个节点,减少了一半",
"weight4 = variable_with_weight_loss(shape=[384, 192], stddev=0.04, lambda_value=0.04)\nbias4 = tf.Variable(tf.constant(0.1, shape=[192]))\nlocal4 = tf.nn.relu(tf.matmul(local3, weight4) + bias4)",
"输出层\n\n最后有10个类别",
"weight5 = variable_with_weight_loss(shape=[192, 10], stddev=1/192.0, lambda_value=0.0)\nbias5 = tf.Variable(tf.constant(0.0, shape=[10]))\nlogits = tf.add(tf.matmul(local4, weight5), bias5)\n\ndef loss(logits, labels):\n labels = tf.cast(labels, tf.int64)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits, labels=labels,\n name = 'cross_entropy_per_example'\n )\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n tf.add_to_collection('losses', cross_entropy_mean)\n \n return tf.add_n(tf.get_collection('losses'), name='total_loss')\n\nloss = loss(logits, label_holder)\n\ntrain_op = tf.train.AdamOptimizer(1e-3).minimize(loss)",
"使用in_top_k来输出top k的准确率,默认使用top 1。常用的可以是top 5。",
"top_k_op = tf.nn.in_top_k(logits, label_holder, 1)\n\nsess = tf.InteractiveSession()\n\nsaver = tf.train.Saver()\n\ntf.global_variables_initializer().run()",
"启动caifar_input中需要用的线程队列。主要用途是图片数据增强。这里总共使用了16个线程来处理图片。",
"tf.train.start_queue_runners()",
"每次在计算之前,先执行image_train,label_train来获取一个batch_size大小的训练数据。然后,feed到train_op和loss中,训练样本。每10次迭代计算就会输出一些必要的信息。",
"for step in range(max_steps):\n start_time = time.time()\n image_batch, label_batch = sess.run([X_train, y_train])\n _, loss_value = sess.run([train_op, loss], \n feed_dict={image_holder: image_batch, label_holder: label_batch})\n duration = time.time() - start_time\n if step % 10 == 0:\n examples_per_sec = batch_size / duration\n sec_this_batch = float(duration)\n \n format_str = ('step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)')\n print(format_str % (step, loss_value, examples_per_sec, sec_this_batch))\n\nsaver.save(sess, save_path=os.path.join(model_dir, 'model.chpt'), global_step=max_steps)\n\nnum_examples = 10000\nnum_iter = int(math.ceil(num_examples / batch_size))\nture_count = 0\ntotal_sample_count = num_iter * batch_size\nstep = 0\nwhile step < num_iter:\n image_batch, label_batch = sess.run([X_test, y_test])\n predictions = sess.run([top_k_op], \n feed_dict={image_holder: image_batch, label_holder: label_batch})\n true_count += np.sum(predictions)\n step += 1\n\nprecision = ture_count / total_sample_count\nprint(\"Precision @ 1 = %.3f\" % precision)\n\nsess.close()"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
ClaudiaEsp/inet
|
Analysis/misc/How to use DataLoader.ipynb
|
gpl-2.0
|
[
"<H1>How to use DataLoader</H1>\n<P>This is an example on how to use a DataLoader object</P>",
"from __future__ import division\nfrom terminaltables import AsciiTable\n\nimport inet\ninet.__version__\n\nfrom inet import DataLoader",
"<H2>Object creation</H2>\nThe object loads the connectivity matrices in .syn format and reports the number of files loaded at construction.",
"mydataset = DataLoader('../../data/PV') # create an object with information of all connections",
"<H2>Object atttributes</H2>\nThe object contains a list with all experiments loaded",
"len(mydataset.experiment)\n\nmydataset.nIN, mydataset.nPC # number of PV cells and GC cells recorded\n\nmydataset.configuration # number of recording configurations\n\nprint(mydataset.motif) # number of connections tested and found for every type",
"Details of every experiments are given in a list",
"mydataset.experiment[0] # example of the data from the first experiment",
"and details fo the recording configurations are provided",
"mydataset.experiment[12]['fname'] # mydataset.filename(12)\n\nmydataset.filename(12)\n\nmydataset.experiment[12]['matrix'] \n\nmydataset.matrix(12)\n\nprint(mydataset.experiment[12]['motif'])\n\nmydataset.motifs(12)",
"or the type the number of configurations when two PV-positive cells were recorded",
"mydataset.IN[2]",
"<H2> Descriptive statistics </H2>\nThe stats attribute will return basis statistics of the whole dataset",
"y = mydataset.stats()\n\nprint AsciiTable(y).table \n\nmymotifs = mydataset.motif\ninfo = [\n ['Connection type', 'Value'],\n ['PV-PV chemical synapses', mymotifs.ii_chem_found],\n ['PV-PV electrical synapses', mymotifs.ii_elec_found],\n [' ',' '],\n ['PV-PV bidirectional chemical', mymotifs.ii_c2_found],\n ['PV-PV divergent chemical', mymotifs.ii_div_found],\n ['PV-PV convergent chemical', mymotifs.ii_con_found],\n ['PV-PV linear chemical', mymotifs.ii_lin_found],\n [''],\n ['PV-PV one chemical with electrical', mymotifs.ii_c1e_found],\n ['PV-PV bidirectional chemical with electrical', mymotifs.ii_c2e_found],\n [' ',' '],\n ['P(PV-PV) chemical synapse', mymotifs.ii_chem_found/mymotifs.ii_chem_tested],\n ['P(PV-PV) electrical synapse', mymotifs.ii_elec_found/mymotifs.ii_elec_tested],\n [''],\n ['P(PV-PV) bidirectional chemical synapse', mymotifs.ii_c2_found/mymotifs.ii_c2_tested],\n ['P(div) divergent chemical motifs', mymotifs.ii_div_found/mymotifs.ii_div_tested],\n ['P(div) convergent chemical motifs', mymotifs.ii_con_found/mymotifs.ii_con_tested], \n ['P(chain) linear chain motifs', mymotifs.ii_lin_found/mymotifs.ii_lin_tested],\n [' ',' '],\n ['P(PV-PV) one chemical with electrical', mymotifs.ii_c1e_found/mymotifs.ii_c1e_tested],\n ['P(PV-PV) bidirectional chemical with electrical', mymotifs.ii_c2e_found/mymotifs.ii_c2e_tested],\n [' ',' '],\n ['PV-GC chemical synapses', mymotifs.ie_found],\n ['GC-PC chemical synapses', mymotifs.ei_found],\n [' ',' '],\n ['P(PV-GC) chemical synapse',mymotifs.ie_found/mymotifs.ie_tested],\n ['P(GC-PC) chemical synapse', mymotifs.ei_found/mymotifs.ei_tested],\n [' ',' '],\n ]\n\n\ntable = AsciiTable(info)\nprint (table.table)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
steinam/teacher
|
jup_notebooks/data-science-ipython-notebooks-master/pandas/03.11-Working-with-Time-Series.ipynb
|
mit
|
[
"<!--BOOK_INFORMATION-->\n<img align=\"left\" style=\"padding-right:10px;\" src=\"figures/PDSH-cover-small.png\">\nThis notebook contains an excerpt from the Python Data Science Handbook by Jake VanderPlas; the content is available on GitHub.\nThe text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!\nNo changes were made to the contents of this notebook from the original.\n<!--NAVIGATION-->\n< Vectorized String Operations | Contents | High-Performance Pandas: eval() and query() >\nWorking with Time Series\nPandas was developed in the context of financial modeling, so as you might expect, it contains a fairly extensive set of tools for working with dates, times, and time-indexed data.\nDate and time data comes in a few flavors, which we will discuss here:\n\nTime stamps reference particular moments in time (e.g., July 4th, 2015 at 7:00am).\nTime intervals and periods reference a length of time between a particular beginning and end point; for example, the year 2015. Periods usually reference a special case of time intervals in which each interval is of uniform length and does not overlap (e.g., 24 hour-long periods comprising days).\nTime deltas or durations reference an exact length of time (e.g., a duration of 22.56 seconds).\n\nIn this section, we will introduce how to work with each of these types of date/time data in Pandas.\nThis short section is by no means a complete guide to the time series tools available in Python or Pandas, but instead is intended as a broad overview of how you as a user should approach working with time series.\nWe will start with a brief discussion of tools for dealing with dates and times in Python, before moving more specifically to a discussion of the tools provided by Pandas.\nAfter listing some resources that go into more depth, we will review some short examples of working with time series data in Pandas.\nDates and Times in Python\nThe Python world has a number of available representations of dates, times, deltas, and timespans.\nWhile the time series tools provided by Pandas tend to be the most useful for data science applications, it is helpful to see their relationship to other packages used in Python.\nNative Python dates and times: datetime and dateutil\nPython's basic objects for working with dates and times reside in the built-in datetime module.\nAlong with the third-party dateutil module, you can use it to quickly perform a host of useful functionalities on dates and times.\nFor example, you can manually build a date using the datetime type:",
"from datetime import datetime\ndatetime(year=2015, month=7, day=4)",
"Or, using the dateutil module, you can parse dates from a variety of string formats:",
"from dateutil import parser\ndate = parser.parse(\"4th of July, 2015\")\ndate",
"Once you have a datetime object, you can do things like printing the day of the week:",
"date.strftime('%A')",
"In the final line, we've used one of the standard string format codes for printing dates (\"%A\"), which you can read about in the strftime section of Python's datetime documentation.\nDocumentation of other useful date utilities can be found in dateutil's online documentation.\nA related package to be aware of is pytz, which contains tools for working with the most migrane-inducing piece of time series data: time zones.\nThe power of datetime and dateutil lie in their flexibility and easy syntax: you can use these objects and their built-in methods to easily perform nearly any operation you might be interested in.\nWhere they break down is when you wish to work with large arrays of dates and times:\njust as lists of Python numerical variables are suboptimal compared to NumPy-style typed numerical arrays, lists of Python datetime objects are suboptimal compared to typed arrays of encoded dates.\nTyped arrays of times: NumPy's datetime64\nThe weaknesses of Python's datetime format inspired the NumPy team to add a set of native time series data type to NumPy.\nThe datetime64 dtype encodes dates as 64-bit integers, and thus allows arrays of dates to be represented very compactly.\nThe datetime64 requires a very specific input format:",
"import numpy as np\ndate = np.array('2015-07-04', dtype=np.datetime64)\ndate",
"Once we have this date formatted, however, we can quickly do vectorized operations on it:",
"date + np.arange(12)",
"Because of the uniform type in NumPy datetime64 arrays, this type of operation can be accomplished much more quickly than if we were working directly with Python's datetime objects, especially as arrays get large\n(we introduced this type of vectorization in Computation on NumPy Arrays: Universal Functions).\nOne detail of the datetime64 and timedelta64 objects is that they are built on a fundamental time unit.\nBecause the datetime64 object is limited to 64-bit precision, the range of encodable times is $2^{64}$ times this fundamental unit.\nIn other words, datetime64 imposes a trade-off between time resolution and maximum time span.\nFor example, if you want a time resolution of one nanosecond, you only have enough information to encode a range of $2^{64}$ nanoseconds, or just under 600 years.\nNumPy will infer the desired unit from the input; for example, here is a day-based datetime:",
"np.datetime64('2015-07-04')",
"Here is a minute-based datetime:",
"np.datetime64('2015-07-04 12:00')",
"Notice that the time zone is automatically set to the local time on the computer executing the code.\nYou can force any desired fundamental unit using one of many format codes; for example, here we'll force a nanosecond-based time:",
"np.datetime64('2015-07-04 12:59:59.50', 'ns')",
"The following table, drawn from the NumPy datetime64 documentation, lists the available format codes along with the relative and absolute timespans that they can encode:\n|Code | Meaning | Time span (relative) | Time span (absolute) |\n|--------|-------------|----------------------|------------------------|\n| Y | Year | ± 9.2e18 years | [9.2e18 BC, 9.2e18 AD] |\n| M | Month | ± 7.6e17 years | [7.6e17 BC, 7.6e17 AD] |\n| W | Week | ± 1.7e17 years | [1.7e17 BC, 1.7e17 AD] |\n| D | Day | ± 2.5e16 years | [2.5e16 BC, 2.5e16 AD] |\n| h | Hour | ± 1.0e15 years | [1.0e15 BC, 1.0e15 AD] |\n| m | Minute | ± 1.7e13 years | [1.7e13 BC, 1.7e13 AD] |\n| s | Second | ± 2.9e12 years | [ 2.9e9 BC, 2.9e9 AD] |\n| ms | Millisecond | ± 2.9e9 years | [ 2.9e6 BC, 2.9e6 AD] |\n| us | Microsecond | ± 2.9e6 years | [290301 BC, 294241 AD] |\n| ns | Nanosecond | ± 292 years | [ 1678 AD, 2262 AD] |\n| ps | Picosecond | ± 106 days | [ 1969 AD, 1970 AD] |\n| fs | Femtosecond | ± 2.6 hours | [ 1969 AD, 1970 AD] |\n| as | Attosecond | ± 9.2 seconds | [ 1969 AD, 1970 AD] |\nFor the types of data we see in the real world, a useful default is datetime64[ns], as it can encode a useful range of modern dates with a suitably fine precision.\nFinally, we will note that while the datetime64 data type addresses some of the deficiencies of the built-in Python datetime type, it lacks many of the convenient methods and functions provided by datetime and especially dateutil.\nMore information can be found in NumPy's datetime64 documentation.\nDates and times in pandas: best of both worlds\nPandas builds upon all the tools just discussed to provide a Timestamp object, which combines the ease-of-use of datetime and dateutil with the efficient storage and vectorized interface of numpy.datetime64.\nFrom a group of these Timestamp objects, Pandas can construct a DatetimeIndex that can be used to index data in a Series or DataFrame; we'll see many examples of this below.\nFor example, we can use Pandas tools to repeat the demonstration from above.\nWe can parse a flexibly formatted string date, and use format codes to output the day of the week:",
"import pandas as pd\ndate = pd.to_datetime(\"4th of July, 2015\")\ndate\n\ndate.strftime('%A')",
"Additionally, we can do NumPy-style vectorized operations directly on this same object:",
"date + pd.to_timedelta(np.arange(12), 'D')",
"In the next section, we will take a closer look at manipulating time series data with the tools provided by Pandas.\nPandas Time Series: Indexing by Time\nWhere the Pandas time series tools really become useful is when you begin to index data by timestamps.\nFor example, we can construct a Series object that has time indexed data:",
"index = pd.DatetimeIndex(['2014-07-04', '2014-08-04',\n '2015-07-04', '2015-08-04'])\ndata = pd.Series([0, 1, 2, 3], index=index)\ndata",
"Now that we have this data in a Series, we can make use of any of the Series indexing patterns we discussed in previous sections, passing values that can be coerced into dates:",
"data['2014-07-04':'2015-07-04']",
"There are additional special date-only indexing operations, such as passing a year to obtain a slice of all data from that year:",
"data['2015']",
"Later, we will see additional examples of the convenience of dates-as-indices.\nBut first, a closer look at the available time series data structures.\nPandas Time Series Data Structures\nThis section will introduce the fundamental Pandas data structures for working with time series data:\n\nFor time stamps, Pandas provides the Timestamp type. As mentioned before, it is essentially a replacement for Python's native datetime, but is based on the more efficient numpy.datetime64 data type. The associated Index structure is DatetimeIndex.\nFor time Periods, Pandas provides the Period type. This encodes a fixed-frequency interval based on numpy.datetime64. The associated index structure is PeriodIndex.\nFor time deltas or durations, Pandas provides the Timedelta type. Timedelta is a more efficient replacement for Python's native datetime.timedelta type, and is based on numpy.timedelta64. The associated index structure is TimedeltaIndex.\n\nThe most fundamental of these date/time objects are the Timestamp and DatetimeIndex objects.\nWhile these class objects can be invoked directly, it is more common to use the pd.to_datetime() function, which can parse a wide variety of formats.\nPassing a single date to pd.to_datetime() yields a Timestamp; passing a series of dates by default yields a DatetimeIndex:",
"dates = pd.to_datetime([datetime(2015, 7, 3), '4th of July, 2015',\n '2015-Jul-6', '07-07-2015', '20150708'])\ndates",
"Any DatetimeIndex can be converted to a PeriodIndex with the to_period() function with the addition of a frequency code; here we'll use 'D' to indicate daily frequency:",
"dates.to_period('D')",
"A TimedeltaIndex is created, for example, when a date is subtracted from another:",
"dates - dates[0]",
"Regular sequences: pd.date_range()\nTo make the creation of regular date sequences more convenient, Pandas offers a few functions for this purpose: pd.date_range() for timestamps, pd.period_range() for periods, and pd.timedelta_range() for time deltas.\nWe've seen that Python's range() and NumPy's np.arange() turn a startpoint, endpoint, and optional stepsize into a sequence.\nSimilarly, pd.date_range() accepts a start date, an end date, and an optional frequency code to create a regular sequence of dates.\nBy default, the frequency is one day:",
"pd.date_range('2015-07-03', '2015-07-10')",
"Alternatively, the date range can be specified not with a start and endpoint, but with a startpoint and a number of periods:",
"pd.date_range('2015-07-03', periods=8)",
"The spacing can be modified by altering the freq argument, which defaults to D.\nFor example, here we will construct a range of hourly timestamps:",
"pd.date_range('2015-07-03', periods=8, freq='H')",
"To create regular sequences of Period or Timedelta values, the very similar pd.period_range() and pd.timedelta_range() functions are useful.\nHere are some monthly periods:",
"pd.period_range('2015-07', periods=8, freq='M')",
"And a sequence of durations increasing by an hour:",
"pd.timedelta_range(0, periods=10, freq='H')",
"All of these require an understanding of Pandas frequency codes, which we'll summarize in the next section.\nFrequencies and Offsets\nFundamental to these Pandas time series tools is the concept of a frequency or date offset.\nJust as we saw the D (day) and H (hour) codes above, we can use such codes to specify any desired frequency spacing.\nThe following table summarizes the main codes available:\n| Code | Description | Code | Description |\n|--------|---------------------|--------|----------------------|\n| D | Calendar day | B | Business day |\n| W | Weekly | | |\n| M | Month end | BM | Business month end |\n| Q | Quarter end | BQ | Business quarter end |\n| A | Year end | BA | Business year end |\n| H | Hours | BH | Business hours |\n| T | Minutes | | |\n| S | Seconds | | |\n| L | Milliseonds | | |\n| U | Microseconds | | |\n| N | nanoseconds | | |\nThe monthly, quarterly, and annual frequencies are all marked at the end of the specified period.\nBy adding an S suffix to any of these, they instead will be marked at the beginning:\n| Code | Description || Code | Description |\n|---------|------------------------||---------|------------------------|\n| MS | Month start ||BMS | Business month start |\n| QS | Quarter start ||BQS | Business quarter start |\n| AS | Year start ||BAS | Business year start |\nAdditionally, you can change the month used to mark any quarterly or annual code by adding a three-letter month code as a suffix:\n\nQ-JAN, BQ-FEB, QS-MAR, BQS-APR, etc.\nA-JAN, BA-FEB, AS-MAR, BAS-APR, etc.\n\nIn the same way, the split-point of the weekly frequency can be modified by adding a three-letter weekday code:\n\nW-SUN, W-MON, W-TUE, W-WED, etc.\n\nOn top of this, codes can be combined with numbers to specify other frequencies.\nFor example, for a frequency of 2 hours 30 minutes, we can combine the hour (H) and minute (T) codes as follows:",
"pd.timedelta_range(0, periods=9, freq=\"2H30T\")",
"All of these short codes refer to specific instances of Pandas time series offsets, which can be found in the pd.tseries.offsets module.\nFor example, we can create a business day offset directly as follows:",
"from pandas.tseries.offsets import BDay\npd.date_range('2015-07-01', periods=5, freq=BDay())",
"For more discussion of the use of frequencies and offsets, see the \"DateOffset\" section of the Pandas documentation.\nResampling, Shifting, and Windowing\nThe ability to use dates and times as indices to intuitively organize and access data is an important piece of the Pandas time series tools.\nThe benefits of indexed data in general (automatic alignment during operations, intuitive data slicing and access, etc.) still apply, and Pandas provides several additional time series-specific operations.\nWe will take a look at a few of those here, using some stock price data as an example.\nBecause Pandas was developed largely in a finance context, it includes some very specific tools for financial data.\nFor example, the accompanying pandas-datareader package (installable via conda install pandas-datareader), knows how to import financial data from a number of available sources, including Yahoo finance, Google Finance, and others.\nHere we will load Google's closing price history:",
"from pandas_datareader import data\n\ngoog = data.DataReader('GOOG', start='2004', end='2016',\n data_source='google')\ngoog.head()",
"For simplicity, we'll use just the closing price:",
"goog = goog['Close']",
"We can visualize this using the plot() method, after the normal Matplotlib setup boilerplate (see Chapter 4):",
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn; seaborn.set()\n\ngoog.plot();",
"Resampling and converting frequencies\nOne common need for time series data is resampling at a higher or lower frequency.\nThis can be done using the resample() method, or the much simpler asfreq() method.\nThe primary difference between the two is that resample() is fundamentally a data aggregation, while asfreq() is fundamentally a data selection.\nTaking a look at the Google closing price, let's compare what the two return when we down-sample the data.\nHere we will resample the data at the end of business year:",
"goog.plot(alpha=0.5, style='-')\ngoog.resample('BA').mean().plot(style=':')\ngoog.asfreq('BA').plot(style='--');\nplt.legend(['input', 'resample', 'asfreq'],\n loc='upper left');",
"Notice the difference: at each point, resample reports the average of the previous year, while asfreq reports the value at the end of the year.\nFor up-sampling, resample() and asfreq() are largely equivalent, though resample has many more options available.\nIn this case, the default for both methods is to leave the up-sampled points empty, that is, filled with NA values.\nJust as with the pd.fillna() function discussed previously, asfreq() accepts a method argument to specify how values are imputed.\nHere, we will resample the business day data at a daily frequency (i.e., including weekends):",
"fig, ax = plt.subplots(2, sharex=True)\ndata = goog.iloc[:10]\n\ndata.asfreq('D').plot(ax=ax[0], marker='o')\n\ndata.asfreq('D', method='bfill').plot(ax=ax[1], style='-o')\ndata.asfreq('D', method='ffill').plot(ax=ax[1], style='--o')\nax[1].legend([\"back-fill\", \"forward-fill\"]);",
"The top panel is the default: non-business days are left as NA values and do not appear on the plot.\nThe bottom panel shows the differences between two strategies for filling the gaps: forward-filling and backward-filling.\nTime-shifts\nAnother common time series-specific operation is shifting of data in time.\nPandas has two closely related methods for computing this: shift() and tshift()\nIn short, the difference between them is that shift() shifts the data, while tshift() shifts the index.\nIn both cases, the shift is specified in multiples of the frequency.\nHere we will both shift() and tshift() by 900 days;",
"fig, ax = plt.subplots(3, sharey=True)\n\n# apply a frequency to the data\ngoog = goog.asfreq('D', method='pad')\n\ngoog.plot(ax=ax[0])\ngoog.shift(900).plot(ax=ax[1])\ngoog.tshift(900).plot(ax=ax[2])\n\n# legends and annotations\nlocal_max = pd.to_datetime('2007-11-05')\noffset = pd.Timedelta(900, 'D')\n\nax[0].legend(['input'], loc=2)\nax[0].get_xticklabels()[2].set(weight='heavy', color='red')\nax[0].axvline(local_max, alpha=0.3, color='red')\n\nax[1].legend(['shift(900)'], loc=2)\nax[1].get_xticklabels()[2].set(weight='heavy', color='red')\nax[1].axvline(local_max + offset, alpha=0.3, color='red')\n\nax[2].legend(['tshift(900)'], loc=2)\nax[2].get_xticklabels()[1].set(weight='heavy', color='red')\nax[2].axvline(local_max + offset, alpha=0.3, color='red');",
"We see here that shift(900) shifts the data by 900 days, pushing some of it off the end of the graph (and leaving NA values at the other end), while tshift(900) shifts the index values by 900 days.\nA common context for this type of shift is in computing differences over time. For example, we use shifted values to compute the one-year return on investment for Google stock over the course of the dataset:",
"ROI = 100 * (goog.tshift(-365) / goog - 1)\nROI.plot()\nplt.ylabel('% Return on Investment');",
"This helps us to see the overall trend in Google stock: thus far, the most profitable times to invest in Google have been (unsurprisingly, in retrospect) shortly after its IPO, and in the middle of the 2009 recession.\nRolling windows\nRolling statistics are a third type of time series-specific operation implemented by Pandas.\nThese can be accomplished via the rolling() attribute of Series and DataFrame objects, which returns a view similar to what we saw with the groupby operation (see Aggregation and Grouping).\nThis rolling view makes available a number of aggregation operations by default.\nFor example, here is the one-year centered rolling mean and standard deviation of the Google stock prices:",
"rolling = goog.rolling(365, center=True)\n\ndata = pd.DataFrame({'input': goog,\n 'one-year rolling_mean': rolling.mean(),\n 'one-year rolling_std': rolling.std()})\nax = data.plot(style=['-', '--', ':'])\nax.lines[0].set_alpha(0.3)",
"As with group-by operations, the aggregate() and apply() methods can be used for custom rolling computations.\nWhere to Learn More\nThis section has provided only a brief summary of some of the most essential features of time series tools provided by Pandas; for a more complete discussion, you can refer to the \"Time Series/Date\" section of the Pandas online documentation.\nAnother excellent resource is the textbook Python for Data Analysis by Wes McKinney (OReilly, 2012).\nAlthough it is now a few years old, it is an invaluable resource on the use of Pandas.\nIn particular, this book emphasizes time series tools in the context of business and finance, and focuses much more on particular details of business calendars, time zones, and related topics.\nAs always, you can also use the IPython help functionality to explore and try further options available to the functions and methods discussed here. I find this often is the best way to learn a new Python tool.\nExample: Visualizing Seattle Bicycle Counts\nAs a more involved example of working with some time series data, let's take a look at bicycle counts on Seattle's Fremont Bridge.\nThis data comes from an automated bicycle counter, installed in late 2012, which has inductive sensors on the east and west sidewalks of the bridge.\nThe hourly bicycle counts can be downloaded from http://data.seattle.gov/; here is the direct link to the dataset.\nAs of summer 2016, the CSV can be downloaded as follows:",
"# !curl -o FremontBridge.csv https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD",
"Once this dataset is downloaded, we can use Pandas to read the CSV output into a DataFrame.\nWe will specify that we want the Date as an index, and we want these dates to be automatically parsed:",
"data = pd.read_csv('FremontBridge.csv', index_col='Date', parse_dates=True)\ndata.head()",
"For convenience, we'll further process this dataset by shortening the column names and adding a \"Total\" column:",
"data.columns = ['West', 'East']\ndata['Total'] = data.eval('West + East')",
"Now let's take a look at the summary statistics for this data:",
"data.dropna().describe()",
"Visualizing the data\nWe can gain some insight into the dataset by visualizing it.\nLet's start by plotting the raw data:",
"%matplotlib inline\nimport seaborn; seaborn.set()\n\ndata.plot()\nplt.ylabel('Hourly Bicycle Count');",
"The ~25,000 hourly samples are far too dense for us to make much sense of.\nWe can gain more insight by resampling the data to a coarser grid.\nLet's resample by week:",
"weekly = data.resample('W').sum()\nweekly.plot(style=[':', '--', '-'])\nplt.ylabel('Weekly bicycle count');",
"This shows us some interesting seasonal trends: as you might expect, people bicycle more in the summer than in the winter, and even within a particular season the bicycle use varies from week to week (likely dependent on weather; see In Depth: Linear Regression where we explore this further).\nAnother way that comes in handy for aggregating the data is to use a rolling mean, utilizing the pd.rolling_mean() function.\nHere we'll do a 30 day rolling mean of our data, making sure to center the window:",
"daily = data.resample('D').sum()\ndaily.rolling(30, center=True).sum().plot(style=[':', '--', '-'])\nplt.ylabel('mean hourly count');",
"The jaggedness of the result is due to the hard cutoff of the window.\nWe can get a smoother version of a rolling mean using a window function–for example, a Gaussian window.\nThe following code specifies both the width of the window (we chose 50 days) and the width of the Gaussian within the window (we chose 10 days):",
"daily.rolling(50, center=True,\n win_type='gaussian').sum(std=10).plot(style=[':', '--', '-']);",
"Digging into the data\nWhile these smoothed data views are useful to get an idea of the general trend in the data, they hide much of the interesting structure.\nFor example, we might want to look at the average traffic as a function of the time of day.\nWe can do this using the GroupBy functionality discussed in Aggregation and Grouping:",
"by_time = data.groupby(data.index.time).mean()\nhourly_ticks = 4 * 60 * 60 * np.arange(6)\nby_time.plot(xticks=hourly_ticks, style=[':', '--', '-']);",
"The hourly traffic is a strongly bimodal distribution, with peaks around 8:00 in the morning and 5:00 in the evening.\nThis is likely evidence of a strong component of commuter traffic crossing the bridge.\nThis is further evidenced by the differences between the western sidewalk (generally used going toward downtown Seattle), which peaks more strongly in the morning, and the eastern sidewalk (generally used going away from downtown Seattle), which peaks more strongly in the evening.\nWe also might be curious about how things change based on the day of the week. Again, we can do this with a simple groupby:",
"by_weekday = data.groupby(data.index.dayofweek).mean()\nby_weekday.index = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']\nby_weekday.plot(style=[':', '--', '-']);",
"This shows a strong distinction between weekday and weekend totals, with around twice as many average riders crossing the bridge on Monday through Friday than on Saturday and Sunday.\nWith this in mind, let's do a compound GroupBy and look at the hourly trend on weekdays versus weekends.\nWe'll start by grouping by both a flag marking the weekend, and the time of day:",
"weekend = np.where(data.index.weekday < 5, 'Weekday', 'Weekend')\nby_time = data.groupby([weekend, data.index.time]).mean()",
"Now we'll use some of the Matplotlib tools described in Multiple Subplots to plot two panels side by side:",
"import matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 2, figsize=(14, 5))\nby_time.ix['Weekday'].plot(ax=ax[0], title='Weekdays',\n xticks=hourly_ticks, style=[':', '--', '-'])\nby_time.ix['Weekend'].plot(ax=ax[1], title='Weekends',\n xticks=hourly_ticks, style=[':', '--', '-']);",
"The result is very interesting: we see a bimodal commute pattern during the work week, and a unimodal recreational pattern during the weekends.\nIt would be interesting to dig through this data in more detail, and examine the effect of weather, temperature, time of year, and other factors on people's commuting patterns; for further discussion, see my blog post \"Is Seattle Really Seeing an Uptick In Cycling?\", which uses a subset of this data.\nWe will also revisit this dataset in the context of modeling in In Depth: Linear Regression.\n<!--NAVIGATION-->\n< Vectorized String Operations | Contents | High-Performance Pandas: eval() and query() >"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
ScoffM/ITESO-Word2Vec
|
Doc2Vec_PopCorn.ipynb
|
gpl-3.0
|
[
"Doc2Vec",
"import re\nimport random\nimport nltk.data\nimport numpy as np\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom nltk.corpus import stopwords\nfrom gensim.models import Doc2Vec\nfrom gensim.models.doc2vec import LabeledSentence\nfrom sklearn.ensemble import RandomForestClassifier\n\n#Loading the differents sets of data.\ntrain = pd.read_csv( \"labeledTrainData.tsv\", header=0, \n delimiter=\"\\t\", quoting=3, encoding=\"utf-8\" )\ntest = pd.read_csv( \"testData.tsv\", header=0, delimiter=\"\\t\", quoting=3, encoding=\"utf-8\" )\nunlabeled_train = pd.read_csv( \"unlabeledTrainData.tsv\", header=0, \n delimiter=\"\\t\", quoting=3, encoding=\"utf-8\" )\n\n#Getting the reviews for each set of data.\nx_train = train['review']\nx_test = test['review']\nx_unlabeled = unlabeled_train['review']\n\n#Getting the sentiment just for train. In unlabeled_train we don't\n#have sentiment column as same in test.\ny_train = train['sentiment']",
"Function to clean the data.\nRemoves html, special characters like punctuation and put all the words in lower case",
"def review_to_wordlist( review, remove_stopwords=False ):\n # Function to convert a document to a sequence of words,\n # optionally removing stop words. Returns a list of words.\n #\n clean_reviews = []\n for i in range(len(review)):\n # 1. Remove HTML\n review_text = BeautifulSoup(review[i]).get_text()\n # \n # 2. Remove non-letters\n review_text = re.sub(\"[^a-zA-Z]\",\" \", review_text)\n #\n # 3. Convert words to lower case and split them\n words = review_text.lower().split()\n #\n # 4. Optionally remove stop words (false by default)\n if remove_stopwords:\n stops = set(stopwords.words(\"english\"))\n words = [w for w in words if not w in stops]\n #\n clean_reviews.append(words)\n # 5. Return a list of reviews\n return(clean_reviews)\n\n#Cleaning the data with the reviews in each set of data\nx_train = review_to_wordlist(x_train)\nx_test = review_to_wordlist(x_test)\nx_unlabeled = review_to_wordlist(x_unlabeled)",
"Function that labelize each review into 'TRAIN_i' , 'TEST_i' and 'UNSUP_i' where i is an index for each observation.\nThis procces is needed because in Doc2Vec it's necesary that each document, in this case\nreview, needs to have a label associated with it.",
"def labelizeReviews(reviews, label_type):\n labelized = []\n for i,v in enumerate(reviews):\n label = '%s_%s'%(label_type,i)\n labelized.append(LabeledSentence(v, [label]))\n return labelized\n\nx_concatenate = np.concatenate((x_train, x_unlabeled))\n\n#Doing labilize procces to each data set, specifying in the parameter \"label_type\"\n#what kind of data is the given data. \nx_train2 = labelizeReviews(x_concatenate, 'TRAIN')\nx_test2 = labelizeReviews(x_test, 'TEST')\n\nsize = 50\nmodel= Doc2Vec(min_count=1, window=5, size=size, sample=1e-4, negative=5, workers=8)\n\n#build vocab over all reviews\nmodel.build_vocab(x_train2)\n\nimport random as ra\n\nra.seed(12345)\nalpha = 0.025\nmin_alpha = 0.001\nnum_epochs = 5\nalpha_delta = (alpha - min_alpha) / num_epochs\n\nfor epoch in range(num_epochs):\n print(epoch)\n ra.shuffle(x_train2)\n model.alpha = alpha\n model.min_alpha = alpha\n model.train(x_train2)\n alpha -= alpha_delta\n\n#Infering over the test reviews in base the previous model built\ntest_vectors = np.zeros((len(x_test),size))\nfor i in range(len(x_test)):\n test_vectors[i] = model.infer_vector(x_test[i])\n\n#Getting the train vectors from the model with the function docvecs. \n#Remember that when we concatenate train and unlabeled sets, the first \n#25,000 rows are from train set. The rest 50,000 rows are from the unlabeled set.\ntrain_vectors = np.zeros((len(x_train), size))\nfor i in range(len(x_train)):\n train_vectors[i] = model.docvecs[i]\n\n#model.save('my_model.doc2vec')",
"Training and prediciting sentimient with Random Forest",
"# Fit a random forest and extract predictions \nforest = RandomForestClassifier(n_estimators = 100)\n# Fitting the forest may take a few minutes\nprint \"Fitting a random forest to labeled training data...\"\nforest = forest.fit(train_vectors,train[\"sentiment\"])\n\nresults = forest.predict(test_vectors)\n\noutput = pd.DataFrame(data={\"id\":test[\"id\"], \"sentiment\":results})\noutput.to_csv( \"Doc2Vec.csv\", index=False, quoting=3 )",
"Training and predicting sentiment with Logistic Regression",
"from sklearn.linear_model import LogisticRegression\n\nlgr = LogisticRegression()\nlgr = lgr.fit(train_vectors, train[\"sentiment\"])\n\nresults = lgr.predict(test_vectors)\n\noutput = pd.DataFrame(data={\"id\":test[\"id\"], \"sentiment\":results})\noutput.to_csv( \"Doc2Vec_lgr.csv\", index=False, quoting=3 )",
"Logistic Regression is slightly better than Random Forest"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
chetan51/nupic.research
|
projects/dynamic_sparse/notebooks/ExperimentAnalysis-Neurips1.ipynb
|
gpl-3.0
|
[
"%load_ext autoreload\n%autoreload 2\n\nimport sys\nsys.path.append(\"../../\")\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport glob\nimport tabulate\nimport pprint\nimport click\nimport numpy as np\nimport pandas as pd\nfrom ray.tune.commands import *\nfrom dynamic_sparse.common.browser import *",
"Load and check data",
"exps = ['neurips_1_eval1', ]\npaths = [os.path.expanduser(\"~/nta/results/{}\".format(e)) for e in exps]\ndf = load_many(paths)\n\ndf.head(5)\n\ndf.columns\n\ndf.shape\n\ndf.iloc[1]\n\ndf.groupby('model')['model'].count()",
"## Analysis\nExperiment Details",
"# Did any trials failed?\ndf[df[\"epochs\"]<30][\"epochs\"].count()\n\n# Removing failed trials\ndf_origin = df.copy()\ndf = df_origin[df_origin[\"epochs\"]>=30]\ndf.shape\n\n# which ones failed?\n# failed, or still ongoing?\ndf_origin['failed'] = df_origin[\"epochs\"]<100\ndf_origin[df_origin['failed']]['epochs']\n\n# helper functions\ndef mean_and_std(s):\n return \"{:.3f} ± {:.3f}\".format(s.mean(), s.std())\n\ndef round_mean(s):\n return \"{:.0f}\".format(round(s.mean()))\n\nstats = ['min', 'max', 'mean', 'std']\n\ndef agg(columns, filter=None, round=3):\n if filter is None:\n return (df.groupby(columns)\n .agg({'val_acc_max_epoch': round_mean,\n 'val_acc_max': stats, \n 'model': ['count']})).round(round)\n else:\n return (df[filter].groupby(columns)\n .agg({'val_acc_max_epoch': round_mean,\n 'val_acc_max': stats, \n 'model': ['count']})).round(round)\n",
"Did Hebbian perform better than SET?",
"agg(['model'])\n\nhigh_sparsity = (df['on_perc']==0.05)\navg_sparsity = (df['on_perc']==0.1)\nlow_sparsity = (df['on_perc']==0.2)\n\nagg(['kwinners'], low_sparsity)\n\nagg(['kwinners'], high_sparsity)",
"No evidence of significant difference. In networks with high sparsity, the impact of kWinners is worst, which is expected since kWinners (at 30%) will make the activations more sparse than ReLU (which is 50% sparse on average)\n\nWhat is the optimal level of weight sparsity?",
"agg(['on_perc'])",
"Sparsity at 80 and 90% levels seem more or less equivalent, difference is 1 point in accuracy. The jump from 90 to 95% shows a drastic increase in acc, of 6 points.\n\nHebbian grow helps learning?",
"agg(['hebbian_grow'])\n\nagg(['hebbian_grow'], low_sparsity)\n\nagg(['hebbian_grow'], high_sparsity)",
"No strong evidence it helps in low sparsity case. In high sparsity (95%), seems very harmful\n\nHebbian pruning helps learning?",
"agg(['hebbian_prune_perc'])\n\nagg(['hebbian_prune_perc'], low_sparsity)\n\nagg(['hebbian_prune_perc'], high_sparsity)",
"There is good evidence it helps. The trend is very clear in the low sparsity (80% sparse) cases.",
"no_magnitude = (df['weight_prune_perc'] == 0)\nagg(['hebbian_prune_perc'], no_magnitude)\n\nno_magnitude = (df['weight_prune_perc'] == 0)\nagg(['hebbian_prune_perc'], (no_magnitude & low_sparsity))",
"Results seem similar even when no magnitude pruning is involved, only hebbian pruning\n\nMagnitude pruning helps learning?",
"agg(['weight_prune_perc'])\n\nagg(['weight_prune_perc'], low_sparsity)\n\nagg(['weight_prune_perc'], high_sparsity)\n\nagg(['weight_prune_perc'], avg_sparsity)",
"In low sparsity cases, results are the same for any amount of pruning. In average and high sparsity, there is a gaussian like curve, with the peak at around 0.2 (maybe extending to 0.3). \nResults are consistent with what has been seen in previous experiments and in related papers.\nWorth note that although results are better at 0.2, it also takes slightly longer to achieve better results compared to m",
"no_hebbian = (df['hebbian_prune_perc'] == 0)\nagg(['weight_prune_perc'], no_hebbian)",
"Somewhat inconsistent result looking at cases where there is no hebbian learning, only pruning by magnitude. There is an anomaly at the last entry where 50% of the weights are pruned - results are similar to 20%.\nNumber of samples averaged from is a lot lower in this pivot\n\nWhat is the optimal combination of weight and magnitude pruning?",
"pd.pivot_table(df, \n index='hebbian_prune_perc',\n columns='weight_prune_perc',\n values='val_acc_max',\n aggfunc=mean_and_std)\n\npd.pivot_table(df[low_sparsity], \n index=['kwinners','hebbian_prune_perc'],\n columns='weight_prune_perc',\n values='val_acc_max',\n aggfunc=mean_and_std)\n\npd.pivot_table(df[avg_sparsity], \n index=['kwinners','hebbian_prune_perc'],\n columns='weight_prune_perc',\n values='val_acc_max',\n aggfunc=mean_and_std)",
"There is a more clear trend in the low sparsity case. Results from high sparsity are inconclusive, with several runs failing to \"converge\"\nWeight pruning alone improves the model by up to 0.7% from 10% pruning to 50% magnitude pruning\nHebbian pruning alone improves the model by 1.5%\nBoth combined can increase from 1.5% seem in hebbian only to 1.8% improvement. \nComparisons above are from 0.1 to 0.5 pruning. There is a question left of why no pruning at both sides - the (0,0) point - it is an anomaly to the trend shown in the pivot.",
"pd.pivot_table(df[avg_sparsity], \n index='hebbian_prune_perc',\n columns='weight_prune_perc',\n values='val_acc_max',\n aggfunc=mean_and_std)\n\npd.pivot_table(df[high_sparsity], \n index='hebbian_prune_perc',\n columns='weight_prune_perc',\n values='val_acc_max',\n aggfunc=mean_and_std)"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
armandosrz/UdacityNanoMachine
|
customer_segments/customer_segments.ipynb
|
apache-2.0
|
[
"Machine Learning Engineer Nanodegree\nUnsupervised Learning\nProject: Creating Customer Segments\nWelcome to the third project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and it will be your job to implement the additional functionality necessary to successfully complete this project. Sections that begin with 'Implementation' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide. \n\nNote: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.\n\nGetting Started\nIn this project, you will analyze a dataset containing data on various customers' annual spending amounts (reported in monetary units) of diverse product categories for internal structure. One goal of this project is to best describe the variation in the different types of customers that a wholesale distributor interacts with. Doing so would equip the distributor with insight into how to best structure their delivery service to meet the needs of each customer.\nThe dataset for this project can be found on the UCI Machine Learning Repository. For the purposes of this project, the features 'Channel' and 'Region' will be excluded in the analysis — with focus instead on the six product categories recorded for customers.\nRun the code block below to load the wholesale customers dataset, along with a few of the necessary Python libraries required for this project. You will know the dataset loaded successfully if the size of the dataset is reported.",
"# Import libraries necessary for this project\nimport numpy as np\nimport pandas as pd\nfrom IPython.display import display # Allows the use of display() for DataFrames\n\n# Import supplementary visualizations code visuals.py\nimport visuals as vs\n\n# Pretty display for notebooks\n%matplotlib inline\n\n# Load the wholesale customers dataset\ntry:\n data = pd.read_csv(\"customers.csv\")\n data.drop(['Region', 'Channel'], axis = 1, inplace = True)\n print \"Wholesale customers dataset has {} samples with {} features each.\".format(*data.shape)\nexcept:\n print \"Dataset could not be loaded. Is the dataset missing?\"",
"Data Exploration\nIn this section, you will begin exploring the data through visualizations and code to understand how each feature is related to the others. You will observe a statistical description of the dataset, consider the relevance of each feature, and select a few sample data points from the dataset which you will track through the course of this project.\nRun the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories: 'Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', and 'Delicatessen'. Consider what each category represents in terms of products you could purchase.",
"# Display a description of the dataset\ndisplay(data.describe())",
"Implementation: Selecting Samples\nTo get a better understanding of the customers and how their data will transform through the analysis, it would be best to select a few sample data points and explore them in more detail. In the code block below, add three indices of your choice to the indices list which will represent the customers to track. It is suggested to try different sets of samples until you obtain customers that vary significantly from one another.",
"# TODO: Select three indices of your choice you wish to sample from the dataset\nindices = [201,47,399]\n\n# Create a DataFrame of the chosen samples\nsamples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True)\nprint \"Chosen samples of wholesale customers dataset:\"\ndisplay(samples)\n\nprint \"Chosen samples offset from mean:\"\ndisplay(samples - np.around(data.mean().values))\n\nprint \"Chosen samples offset from median:\"\ndisplay(samples - np.around(data.median().values))\n",
"Question 1\nConsider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers.\nWhat kind of establishment (customer) could each of the three samples you've chosen represent?\nHint: Examples of establishments include places like markets, cafes, and retailers, among many others. Avoid using names for establishments, such as saying \"McDonalds\" when describing a sample customer as a restaurant.\nAnswer:\n1. Bakery and Pastries restaurant.- Due to the consumption of milk, grocery and delicatessen we can observe that this product are bought in order to build all the necessary elements of the pastries and baked goods. In terms of detergents and paper, their consumption is also fairly high due to the number of customers and the required elements to clean the kitchen.\n2. Market Place.- The high consumptions in all products, most of them above the mean, indicates that the customer buy all this products in order to re-sell them in their local market. \n3. Coffee place, the small number of offered products is reduced, however as a coffee place the demand for fresh, milk and frozen products is high. Also since most people order their product and leave afterwards, the consumptions in detergents and paper is low. \nImplementation: Feature Relevance\nOne interesting thought to consider is if one (or more) of the six product categories is actually relevant for understanding customer purchasing. That is to say, is it possible to determine whether customers purchasing some amount of one category of products will necessarily purchase some proportional amount of another category of products? We can make this determination quite easily by training a supervised regression learner on a subset of the data with one feature removed, and then score how well that model can predict the removed feature.\nIn the code block below, you will need to implement the following:\n - Assign new_data a copy of the data by removing a feature of your choice using the DataFrame.drop function.\n - Use sklearn.cross_validation.train_test_split to split the dataset into training and testing sets.\n - Use the removed feature as your target label. Set a test_size of 0.25 and set a random_state.\n - Import a decision tree regressor, set a random_state, and fit the learner to the training data.\n - Report the prediction score of the testing set using the regressor's score function.",
"# TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature\ncategories = ['Fresh', 'Milk', 'Grocery', 'Frozen', 'Detergents_Paper', 'Delicatessen']\nfor cat in categories:\n \n # TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature\n y = data[cat]\n new_data = data.drop([cat], axis = 1)\n\n # TODO: Split the data into training and testing sets using the given feature as the target\n from sklearn.cross_validation import train_test_split\n X_train, X_test, y_train, y_test = train_test_split(new_data, y, test_size = 0.25, random_state = 1)\n\n # TODO: Create a decision tree regressor and fit it to the training set\n from sklearn.tree import DecisionTreeRegressor\n regressor = DecisionTreeRegressor(random_state = 1)\n regressor.fit(X_train, y_train)\n\n\n # TODO: Report the score of the prediction using the testing set\n score = regressor.score(X_test, y_test)\n print 'Score of {} is {:.3f}'.format(cat, score)\n",
"Question 2\nWhich feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits?\nHint: The coefficient of determination, R^2, is scored between 0 and 1, with 1 being a perfect fit. A negative R^2 implies the model fails to fit the data.\nAnswer:\nWell, since I am curiuous I predicted all of them with the following results in descendent order. A high R^2 implies that a feature is contained at a certain degree in the other features, making it irrelevant. \n1. Not relevant:\n - Detergents_Paper\n - Grocery\n - Milk\n2. Relevant(all the elements fail to be predicted):\n - Delicatessen\n - Frozen\n - Fresh\nVisualize Feature Distributions\nTo get a better understanding of the dataset, we can construct a scatter matrix of each of the six product features present in the data. If you found that the feature you attempted to predict above is relevant for identifying a specific customer, then the scatter matrix below may not show any correlation between that feature and the others. Conversely, if you believe that feature is not relevant for identifying a specific customer, the scatter matrix might show a correlation between that feature and another feature in the data. Run the code block below to produce a scatter matrix.",
"# Produce a scatter matrix for each pair of features in the data\npd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');",
"Question 3\nAre there any pairs of features which exhibit some degree of correlation? Does this confirm or deny your suspicions about the relevance of the feature you attempted to predict? How is the data for those features distributed?\nHint: Is the data normally distributed? Where do most of the data points lie? \nAnswer:\nWe can see a correlation between all of the three categories previously stated: Milk, Grocery and Detergents. Confirming the assumptions stated above. \nThe data is all clearly skewed to the right, so the data is not normally distributed. \nData Preprocessing\nIn this section, you will preprocess the data to create a better representation of customers by performing a scaling on the data and detecting (and optionally removing) outliers. Preprocessing data is often times a critical step in assuring that results you obtain from your analysis are significant and meaningful.\nImplementation: Feature Scaling\nIf data is not normally distributed, especially if the mean and median vary significantly (indicating a large skew), it is most often appropriate to apply a non-linear scaling — particularly for financial data. One way to achieve this scaling is by using a Box-Cox test, which calculates the best power transformation of the data that reduces skewness. A simpler approach which can work in most cases would be applying the natural logarithm.\nIn the code block below, you will need to implement the following:\n - Assign a copy of the data to log_data after applying logarithmic scaling. Use the np.log function for this.\n - Assign a copy of the sample data to log_samples after applying logarithmic scaling. Again, use np.log.",
"# TODO: Scale the data using the natural logarithm\nlog_data = np.log(data)\n\n# TODO: Scale the sample data using the natural logarithm\nlog_samples = np.log(samples)\n\n# Produce a scatter matrix for each pair of newly-transformed features\npd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde');\n\ndisplay(log_data.describe())",
"Observation\nAfter applying a natural logarithm scaling to the data, the distribution of each feature should appear much more normal. For any pairs of features you may have identified earlier as being correlated, observe here whether that correlation is still present (and whether it is now stronger or weaker than before).\nRun the code below to see how the sample data has changed after having the natural logarithm applied to it.",
"# Display the log-transformed sample data\ndisplay(log_samples)",
"Implementation: Outlier Detection\nDetecting outliers in the data is extremely important in the data preprocessing step of any analysis. The presence of outliers can often skew results which take into consideration these data points. There are many \"rules of thumb\" for what constitutes an outlier in a dataset. Here, we will use Tukey's Method for identfying outliers: An outlier step is calculated as 1.5 times the interquartile range (IQR). A data point with a feature that is beyond an outlier step outside of the IQR for that feature is considered abnormal.\nIn the code block below, you will need to implement the following:\n - Assign the value of the 25th percentile for the given feature to Q1. Use np.percentile for this.\n - Assign the value of the 75th percentile for the given feature to Q3. Again, use np.percentile.\n - Assign the calculation of an outlier step for the given feature to step.\n - Optionally remove data points from the dataset by adding indices to the outliers list.\nNOTE: If you choose to remove any outliers, ensure that the sample data does not contain any of these points!\nOnce you have performed this implementation, the dataset will be stored in the variable good_data.",
"# For each feature find the data points with extreme high or low values\n\nrepeated_index = {}\n\nfor feature in log_data.keys():\n \n # TODO: Calculate Q1 (25th percentile of the data) for the given feature\n Q1 = np.percentile(log_data[feature], 25)\n \n # TODO: Calculate Q3 (75th percentile of the data) for the given feature\n Q3 = np.percentile(log_data[feature], 75)\n \n # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range)\n step = (Q3 - Q1) * 1.5\n \n # Display the outliers\n print \"Data points considered outliers for the feature '{}':\".format(feature)\n display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))])\n # Check the index that are repeated more than once\n for i in log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))].index:\n if i not in repeated_index:\n repeated_index[i] = 1\n else:\n repeated_index[i] += 1\n \n# OPTIONAL: Select the indices for data points you wish to remove\n\noutliers = []\nfor key in repeated_index.keys():\n if repeated_index[key] > 1:\n outliers.append(key)\nprint 'Outliners represented in 2 or more features: {}'.format(outliers)\n\noutliers += [154, 95, 328, 75, 420, 142, 187, 86, 183, 325]\n\n# Min 1.098612\t4.007333\t1.098612\t3.218876\t1.098612\t1.098612\n# Max 11.627601\t11.205013\t11.437986\t11.016479\t10.617099\t10.777768\n\n# Remove the outliers, if any were specified\nprint 'All Outliers: {}'.format(outliers)\ngood_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True)",
"Question 4\nAre there any data points considered outliers for more than one feature based on the definition above? Should these data points be removed from the dataset? If any data points were added to the outliers list to be removed, explain why. \nAnswer:\nThe data points _65, 66, 75, 128, 154_ are repeated more than once in the dataset, hence they should be removed from the dataset due to them affecting more than one entry point. It has a greater damage than those that only affect one.\nPoints being removed for being the min in their category:\n- _Data Point 161_.- Value of 1.098612. Feature Detergents_Paper.\n- _Data Point 95, 338.- Min element for Fresh (1.098612).\n- _Data Point 154_.- Min element for Milk (4.007333)\n- _Data Point 75_.- Grocery (1.098612)\n- _Data Point 420_.- Frozen (3.218876)\n- _Data Point 142, 187_.- Delicatessen (3.218876)\n\nPoints being removed for being the max in their category:\n- _Data Point 86_.- Min element for Milk (11.205013)\n- _Data Point 325_.- Frozen (11.016479)\n- _Data Point 183_.- Delicatessen (10.777768)\n\nA simple procedure for deleting outliers was placed, deleted the min and max elements in the dataset __that are considered outliers__ and delete those who are present in more than one category.\n\nFeature Transformation\nIn this section you will use principal component analysis (PCA) to draw conclusions about the underlying structure of the wholesale customer data. Since using PCA on a dataset calculates the dimensions which best maximize variance, we will find which compound combinations of features best describe customers.\nImplementation: PCA\nNow that the data has been scaled to a more normal distribution and has had any necessary outliers removed, we can now apply PCA to the good_data to discover which dimensions about the data best maximize the variance of features involved. In addition to finding these dimensions, PCA will also report the explained variance ratio of each dimension — how much variance within the data is explained by that dimension alone. Note that a component (dimension) from PCA can be considered a new \"feature\" of the space, however it is a composition of the original features present in the data.\nIn the code block below, you will need to implement the following:\n - Import sklearn.decomposition.PCA and assign the results of fitting PCA in six dimensions with good_data to pca.\n - Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.",
"# TODO: Apply PCA by fitting the good data with the same number of dimensions as features\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=6).fit(good_data)\n\n# TODO: Transform log_samples using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Generate PCA results plot\npca_results = vs.pca_results(good_data, pca)",
"Question 5\nHow much variance in the data is explained in total by the first and second principal component? What about the first four principal components? Using the visualization provided above, discuss what the first four dimensions best represent in terms of customer spending.\nHint: A positive increase in a specific dimension corresponds with an increase of the positive-weighted features and a decrease of the negative-weighted features. The rate of increase or decrease is based on the indivdual feature weights.",
"print pca_results['Explained Variance'].cumsum()",
"Answer:\nThe variance for the first two columns equals 71.80%. \nThe first four components equate for 93.35% of the variance.\nIn terms of each specific dimension:\n- First dimension is meaningful weighted towards Milk, Grocery and heavily weighted towards Detergents. This dimension is best categorized by retail goods customers.\n- Second dimension, we can observe how the components greatly switch, by now relying especially on Fresh, with also an emphasis in Delicatessen and Frozen. This dimension is best categorized by restaurant customers.\n- Third dimension Frozen and Delicatessen remain constant with respect to the second one. However, the component of Fresh has a heavily negative weight. Milk also has a positive weight. I believe this dimension is better represented by customers that sell coffee and icecream.\n- Fourth dimension the model is high on Delicatessen and a particular low weight in Frozen products. This dimension would be best represented by a candy shop or a bakery.\nObservation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it in six dimensions. Observe the numerical value for the first four dimensions of the sample points. Consider if this is consistent with your initial interpretation of the sample points.",
"# Display sample log-data after having a PCA transformation applied\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values))",
"Implementation: Dimensionality Reduction\nWhen using principal component analysis, one of the main goals is to reduce the dimensionality of the data — in effect, reducing the complexity of the problem. Dimensionality reduction comes at a cost: Fewer dimensions used implies less of the total variance in the data is being explained. Because of this, the cumulative explained variance ratio is extremely important for knowing how many dimensions are necessary for the problem. Additionally, if a signifiant amount of variance is explained by only two or three dimensions, the reduced data can be visualized afterwards.\nIn the code block below, you will need to implement the following:\n - Assign the results of fitting PCA in two dimensions with good_data to pca.\n - Apply a PCA transformation of good_data using pca.transform, and assign the results to reduced_data.\n - Apply a PCA transformation of log_samples using pca.transform, and assign the results to pca_samples.",
"# TODO: Apply PCA by fitting the good data with only two dimensions\npca = PCA(n_components=2).fit(good_data)\n\n# TODO: Transform the good data using the PCA fit above\nreduced_data = pca.transform(good_data)\n\n# TODO: Transform log_samples using the PCA fit above\npca_samples = pca.transform(log_samples)\n\n# Create a DataFrame for the reduced data\nreduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2'])\nprint 'done'",
"Observation\nRun the code below to see how the log-transformed sample data has changed after having a PCA transformation applied to it using only two dimensions. Observe how the values for the first two dimensions remains unchanged when compared to a PCA transformation in six dimensions.",
"# Display sample log-data after applying PCA transformation in two dimensions\ndisplay(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2']))",
"Visualizing a Biplot\nA biplot is a scatterplot where each data point is represented by its scores along the principal components. The axes are the principal components (in this case Dimension 1 and Dimension 2). In addition, the biplot shows the projection of the original features along the components. A biplot can help us interpret the reduced dimensions of the data, and discover relationships between the principal components and original features.\nRun the code cell below to produce a biplot of the reduced-dimension data.",
"# Create a biplot\nvs.biplot(good_data, reduced_data, pca)",
"Observation\nOnce we have the original feature projections (in red), it is easier to interpret the relative position of each data point in the scatterplot. For instance, a point the lower right corner of the figure will likely correspond to a customer that spends a lot on 'Milk', 'Grocery' and 'Detergents_Paper', but not so much on the other product categories. \nFrom the biplot, which of the original features are most strongly correlated with the first component? What about those that are associated with the second component? Do these observations agree with the pca_results plot you obtained earlier?\nClustering\nIn this section, you will choose to use either a K-Means clustering algorithm or a Gaussian Mixture Model clustering algorithm to identify the various customer segments hidden in the data. You will then recover specific data points from the clusters to understand their significance by transforming them back into their original dimension and scale. \nQuestion 6\nWhat are the advantages to using a K-Means clustering algorithm? What are the advantages to using a Gaussian Mixture Model clustering algorithm? Given your observations about the wholesale customer data so far, which of the two algorithms will you use and why?\nAnswer:\n- K-Means:\n - Fast and easy to implement.\n - Uses hard clustering to define the subgroups.\n - Warranty to find a local optimum.\n- Gaussian Mixture Model:\n - Adds more flexibility in the sense of defining the subgroups.\n - Uses a Gaussian model to predict the percentage a point has to belong to all clusters. Picks the higher one as the group where it belongs.\n - Helps uncovering some hidden variables on the data.\nI will use the Gaussian Mixture model, due to the uncovered relationships between certain features. Also, after applying a log function to normalize the data points might end up in clusters they do not belong due to the underlying proximity.\nImplementation: Creating Clusters\nDepending on the problem, the number of clusters that you expect to be in the data may already be known. When the number of clusters is not known a priori, there is no guarantee that a given number of clusters best segments the data, since it is unclear what structure exists in the data — if any. However, we can quantify the \"goodness\" of a clustering by calculating each data point's silhouette coefficient. The silhouette coefficient for a data point measures how similar it is to its assigned cluster from -1 (dissimilar) to 1 (similar). Calculating the mean silhouette coefficient provides for a simple scoring method of a given clustering.\nIn the code block below, you will need to implement the following:\n - Fit a clustering algorithm to the reduced_data and assign it to clusterer.\n - Predict the cluster for each data point in reduced_data using clusterer.predict and assign them to preds.\n - Find the cluster centers using the algorithm's respective attribute and assign them to centers.\n - Predict the cluster for each sample data point in pca_samples and assign them sample_preds.\n - Import sklearn.metrics.silhouette_score and calculate the silhouette score of reduced_data against preds.\n - Assign the silhouette score to score and print the result.",
"from sklearn import mixture\nfrom sklearn.metrics import silhouette_score\n\n\ndef get_gmm(n_comp):\n # TODO: Apply your clustering algorithm of choice to the reduced data \n clusterer = mixture.GMM(n_components = n_comp).fit(reduced_data)\n\n # TODO: Predict the cluster for each data point\n preds = clusterer.predict(reduced_data)\n\n # TODO: Find the cluster centers\n centers = clusterer.means_\n\n # TODO: Predict the cluster for each transformed sample data point\n sample_preds = clusterer.predict(pca_samples)\n\n # TODO: Calculate the mean silhouette coefficient for the number of clusters chosen\n score = silhouette_score(reduced_data, preds)\n print 'Silhouette score for {} components is {}'.format(n_comp, score)\n return preds, centers, sample_preds",
"Question 7\nReport the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score?",
"for x in range(2, 10):\n get_gmm(x)",
"Answer: \nThe scores an be seen above. The best obtained score was 2 components with a score of 0.419983017307\nCluster Visualization\nOnce you've chosen the optimal number of clusters for your clustering algorithm using the scoring metric above, you can now visualize the results by executing the code block below. Note that, for experimentation purposes, you are welcome to adjust the number of clusters for your clustering algorithm to see various visualizations. The final visualization provided should, however, correspond with the optimal number of clusters.",
"# Display the results of the clustering from implementation\npreds, centers, sample_preds = get_gmm(2)\nvs.cluster_results(reduced_data, preds, centers, pca_samples)",
"Implementation: Data Recovery\nEach cluster present in the visualization above has a central point. These centers (or means) are not specifically data points from the data, but rather the averages of all the data points predicted in the respective clusters. For the problem of creating customer segments, a cluster's center point corresponds to the average customer of that segment. Since the data is currently reduced in dimension and scaled by a logarithm, we can recover the representative customer spending from these data points by applying the inverse transformations.\nIn the code block below, you will need to implement the following:\n - Apply the inverse transform to centers using pca.inverse_transform and assign the new centers to log_centers.\n - Apply the inverse function of np.log to log_centers using np.exp and assign the true centers to true_centers.",
"# TODO: Inverse transform the centers\nlog_centers = pca.inverse_transform(centers)\n\n# TODO: Exponentiate the centers\ntrue_centers = np.exp(log_centers)\n\n# Display the true centers\nsegments = ['Segment {}'.format(i) for i in range(0,len(centers))]\ntrue_centers = pd.DataFrame(np.round(true_centers), columns = data.keys())\ntrue_centers.index = segments\n\nprint 'Centers information:'\ndisplay(true_centers)\n\nprint 'Orginal data description (without outliers):'\n\ndata_no_outliers = data.drop(data.index[outliers]).reset_index(drop = True)\n\ndisplay(data_no_outliers.describe())\n\nprint \"Centers offset from mean\"\ndisplay(true_centers - np.around(data_no_outliers.mean().values))\n\nprint \"Centers offset from median\"\ndisplay(true_centers - np.around(data_no_outliers.median().values))\n",
"Question 8\nConsider the total purchase cost of each product category for the representative data points above, and reference the statistical description of the dataset at the beginning of this project. What set of establishments could each of the customer segments represent?\nHint: A customer who is assigned to 'Cluster X' should best identify with the establishments represented by the feature set of 'Segment X'.\nAnswer:\n\nSegment 0.- The customers from this segment are primarily characterized by having an above the mean consumption of Milk, Grocery and Detergents. On the other side, it can also be observed a particularly low, close to a 30% segment, consumption of fresh and frozen products. Due to this characteristics, we can describe this segment as being a reseller like a market. \nSegment 1.- This particular segment has a below the mean consumption in all six different categories, which might indicate they belong to smaller establishments from the ones present in cluster 0. When comparing those values to their respective medians, we can observe two particular categories that are above the median values Fresh and Frozen products. Under this circumstances is fair to assume that those two products best represent this segment. So this customers need to restock their inventory promptly, indicating they belong to groups that produce food or fresh products like restaurants or coffee stores. \n\nIn other words, we can divide the groups into providers of goods (which buy fresh and frozen items that are placed in shelves) and those who use the supplies to create food.\nQuestion 9\nFor each sample point, which customer segment from Question 8 best represents it? Are the predictions for each sample point consistent with this?\nRun the code block below to find which cluster each sample point is predicted to be.",
"# Display the predictions\nfor i, pred in enumerate(sample_preds):\n print \"Sample point\", i, \"predicted to be in Cluster\", pred",
"Answer:\n1. Sample Point 0:\n - Predicted: Bakery and Pastries restaurant\n - Result: The prediction was not consisted with the customer segment. The unique characteristics of high detergent paper usage in combination with all the other products was assigned that prediction.\n2. Sample Point 1:\n - Predicted: Market Place\n - Result: Customer segment consistent with prediction.\n3. Sample Point 2:\n - Predicted: Coffee Place\n - Result: Customer segment consistent with prediction.\nConclusion\nIn this final section, you will investigate ways that you can make use of the clustered data. First, you will consider how the different groups of customers, the customer segments, may be affected differently by a specific delivery scheme. Next, you will consider how giving a label to each customer (which segment that customer belongs to) can provide for additional features about the customer data. Finally, you will compare the customer segments to a hidden variable present in the data, to see whether the clustering identified certain relationships.\nQuestion 10\nCompanies will often run A/B tests when making small changes to their products or services to determine whether making that change will affect its customers positively or negatively. The wholesale distributor is considering changing its delivery service from currently 5 days a week to 3 days a week. However, the distributor will only make this change in delivery service for customers that react positively. How can the wholesale distributor use the customer segments to determine which customers, if any, would react positively to the change in delivery service?\nHint: Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most?\nAnswer:\nWe can not assume the change will affect all customers equally. Based on the two segments we can make assumptions to be tested. Our assumption would be that the customers on segment 0, retail, will be benefited by a 3 days a week delivery based on the lack of need of daily fresh food and storage capacity to hold more product volume if needed. This will also improve their efficiency by having less product to manage and overall less work. However, segment 1 should remain with a 5 days a week model. \nHowever, we could not assume all the customers inside each cluster have the same needs. In order to test the selected assumptions, we will select a specific numbers of customers in each cluster and put all those customers in a 3-day delivery service and evaluate their reactions. Two different non-parallel A/B tests should be created under the following principles. \n- Randon Selection: The users to be involved in the testing are going to be randomly selected from the two clusters. They should represent 20% of the population of the cluster. \n- Partition Selection: For each cluster select: 5% of the users from below the 25% threshold in the cluster, 10% from the range of 25%-75% of the cluster and the final 5% from the higher 75% of the cluster. \nThis will give us a better representation of the customer reaction to the new delivery service by obtaining data points from all areas of the clusters. Based on the data, the above hypothesis can be tested.\nQuestion 11\nAdditional structure is derived from originally unlabeled data when using clustering techniques. Since each customer has a customer segment it best identifies with (depending on the clustering algorithm applied), we can consider 'customer segment' as an engineered feature for the data. Assume the wholesale distributor recently acquired ten new customers and each provided estimates for anticipated annual spending of each product category. Knowing these estimates, the wholesale distributor wants to classify each new customer to a customer segment to determine the most appropriate delivery service.\nHow can the wholesale distributor label the new customers using only their estimated product spending and the customer segment data?\nHint: A supervised learner could be used to train on the original customers. What would be the target variable?\nAnswer:\nSince we already defined two different clusters with their separate characteristics, we can convert this problem into a supervised classification problem, in which the segment number would be the feature. The new information would be used to predict the appropriate cluster.\nSince we have only two posible clusters this could be solve with a binary classifier.\nVisualizing Underlying Distributions\nAt the beginning of this project, it was discussed that the 'Channel' and 'Region' features would be excluded from the dataset so that the customer product categories were emphasized in the analysis. By reintroducing the 'Channel' feature to the dataset, an interesting structure emerges when considering the same PCA dimensionality reduction applied earlier to the original dataset.\nRun the code block below to see how each data point is labeled either 'HoReCa' (Hotel/Restaurant/Cafe) or 'Retail' the reduced space. In addition, you will find the sample points are circled in the plot, which will identify their labeling.",
"# Display the clustering results based on 'Channel' data\nvs.channel_results(reduced_data, outliers, pca_samples)",
"Question 12\nHow well does the clustering algorithm and number of clusters you've chosen compare to this underlying distribution of Hotel/Restaurant/Cafe customers to Retailer customers? Are there customer segments that would be classified as purely 'Retailers' or 'Hotels/Restaurants/Cafes' by this distribution? Would you consider these classifications as consistent with your previous definition of the customer segments?\nAnswer:\nThe number of clusters used on my algorithm is consistent with the above distribution. The algorithm also generalises well the overall distinction between the two clusters close to the 0.5 mark of the first dimension. We can also observe more overlapping HRC in the retailer side, possible due to the wide range this areas cover. \nFrom the [-2] mark to the left we could consider all the data points as purely HRC and from the other side we can consider the right side of the 3 mark on the first dimension as purely retail. \nI would consider this distributions as consistent with the ones obtained before due to the clear pattern that can be observed on both the previous definition and the new one. There are some overlaps, but overall we obtained a consistent pattern. \n\nNote: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to\nFile -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
NEONInc/NEON-Data-Skills
|
code/Python/hyperspectral-data/Calculate_NDVI_Extract_Spectra_Masks.ipynb
|
gpl-2.0
|
[
"Calculate NDVI\nThe Normalized Difference Vegetation Index (NDVI) is a standard band-ratio calculation frequently used to analyze ecological remote sensing data. NDVI indicates whether the remotely-sensed target contains live green vegetation. When sunlight strikes objects, certain wavelengths of this spectrum are absorbed and other wavelengths are reflected. The pigment chlorophyll in plant leaves strongly absorbs visible light (with wavelengths in the range of 400-700 nm) for use in photosynthesis. The cell structure of the leaves, however, strongly reflects near-infrared light (wavelengths ranging from 700 - 1100 nm). Plants reflect up to 60% more light in the near infrared portion of the spectrum than they do in the green portion of the spectrum. By comparing the ratio of Near Infrared (NIR) to Visible (VIS) bands in hyperspectral data, we can obtain a quick look at vegetation in the region of interest. NDVI is a normalized measure of the difference between reflectance at near infrared and visible bands of the electromagnetic spectrum. \nThe formula for NDVI is: $$NDVI = \\frac{(NIR - VIS)}{(NIR+ VIS)}$$\n<p>\n<img src=\"files/ndvi_tree.png\" style=\"width: 250px;\"/>\n<center><font size=\"2\">Figure: (Wu et al. 2014)</font></center>\n<center><font size=\"2\">https://www.researchgate.net/figure/266947355_fig1_Figure-1-Green-vegetation-left-absorbs-visible-light-and-reflects-near-infrared-light</font></center>\n</p>\n\nStart by setting plot preferences and loading the neon_aop_refl_hdf5_functions module:",
"%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\n\n%load neon_aop_refl_hdf5_functions.py",
"Read in SERC Flightline & Subset",
"#Define inputs\nfilename = '../data/SERC/hyperspectral/NEON_D02_SERC_DP1_20160807_160559_reflectance.h5'\nsercRefl, sercRefl_md, wavelengths = h5refl2array(filename)\n\nclipExtDict = {}\nclipExtDict['xMin'] = 367400.\nclipExtDict['xMax'] = 368100.\nclipExtDict['yMin'] = 4305750.\nclipExtDict['yMax'] = 4306350.\n\nclipExtent = (clipExtDict['xMin'],clipExtDict['xMax'],clipExtDict['yMin'],clipExtDict['yMax'])\nclipIndex = calc_clip_index(clipExtDict,sercRefl_md['ext_dict'])\nsercReflSubset = subset_clean_refl(sercRefl,sercRefl_md,clipIndex)",
"Stack NIR and VIS bands\nNow that we have uploaded all the required functions, we can calculate NDVI and plot it. \nWe will compute NDVI using bands 58 and 90. These correspond to wavelength ranges of:\n$$band 58: \\lambda_{VIS} = 666.6-671.6 nm$$ $$band 90: \\lambda_{NIR} = 826.8-831.9 nm$$.",
"#Select bands to be used in the NDVI calculation\nndvi_bands = (58,90) #NIR and VIS (Red) bands\n\n#Check the center wavelengths that these bands represent\nband_width = wavelengths.value[1]-wavelengths.value[0]\n\nprint('band 58 wavelength range: ' + str(round(wavelengths.value[57]-band_width/2,2)) \n + '-' + str(round(wavelengths.value[57]+band_width/2,2)) + ' nm')\nprint('band 90 wavelength range: ' + str(round(wavelengths.value[89]-band_width/2,2)) \n + '-' + str(round(wavelengths.value[89]+band_width/2,2)) + ' nm')\n\n#Use the stack_subset_bands function to create a stack of the subsetted red and NIR bands needed to calculate NDVI\n\nndvi_stack = stack_subset_bands(sercRefl,sercRefl_md,ndvi_bands,clipIndex)",
"Calculate NDVI & Plot",
"vis = ndvi_stack[:,:,0].astype(float)\nnir = ndvi_stack[:,:,1].astype(float)\n\nndvi = np.divide((nir-vis),(nir+vis))\n\nplot_band_array(ndvi,clipExtent,(0,np.max(ndvi)),\\\n title='SERC Subset NDVI \\n (VIS = Band 58, NIR = Band 90)',cmap_title='NDVI',colormap='seismic')",
"Extract Spectra Using Masks\nIn the second part of this tutorial, we will learn how to extract the average spectra of pixels whose NDVI exceeds a specified threshold value. There are several ways to do this using numpy, including the mask functions numpy.ma, as well as numpy.where and finally using boolean indexing. \nTo start, lets copy the NDVI calculated above and use booleans to create an array only containing NDVI > 0.6.",
"import copy\nndvi_gtpt6 = copy.copy(ndvi)\nndvi_gtpt6[ndvi<0.6] = np.nan #set all pixels with NDVI < 0.6 to nan, keeping only values > 0.6\nprint('Mean NDVI > 0.6:',round(np.nanmean(ndvi_gtpt6),2))\n\nplot_band_array(ndvi_gtpt6,clipExtent,(0.6,1),title='SERC Subset NDVI > 0.6 \\n (VIS = Band 58, NIR = Band 90)',\n cmap_title='NDVI',colormap='RdYlGn')",
"Function to calculate the mean spectra for reflectance values thresholed by NDVI using numpy.ma:",
"import numpy.ma as ma\ndef calculate_mean_masked_spectra(reflArray,ndvi,ndvi_threshold,ineq='>'):\n \n mean_masked_refl = np.zeros(reflArray.shape[2])\n \n for i in np.arange(reflArray.shape[2]):\n refl_band = reflArray[:,:,i]\n \n if ineq == '>':\n ndvi_mask = ma.masked_where((ndvi<=ndvi_threshold) | (np.isnan(ndvi)),ndvi)\n \n elif ineq == '<':\n ndvi_mask = ma.masked_where((ndvi>=ndvi_threshold) | (np.isnan(ndvi)),ndvi)\n \n else:\n print('ERROR: Invalid inequality. Enter < or >')\n \n masked_refl = ma.MaskedArray(refl_band,mask=ndvi_mask.mask)\n mean_masked_refl[i] = ma.mean(masked_refl)\n \n return mean_masked_refl",
"We can test out this function for various NDVI thresholds. We'll test two together, and you can try out different values on your own. Let's look at the average spectra for healthy vegetation (NDVI > 0.6), and for a lower threshold (NDVI < 0.3).",
"sercSpectra_ndvi_gtpt6 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.6)\nsercSpectra_ndvi_ltpt3 = calculate_mean_masked_spectra(sercReflSubset,ndvi,0.3,ineq='<') \n\nimport pandas\n\n#Remove water vapor band windows & last 10 bands \nw = copy.copy(wavelengths.value)\nw[((w >= 1340) & (w <= 1445)) | ((w >= 1790) & (w <= 1955))]=np.nan\nw[-10:]=np.nan; # the last 10 bands sometimes have noise - best to eliminate\n\nnan_ind = np.argwhere(np.isnan(w))\n\nsercSpectra_ndvi_gtpt6[nan_ind] = np.nan\nsercSpectra_ndvi_ltpt3[nan_ind] = np.nan\n\n#Create dataframe with masked NDVI mean spectra\nsercSpectra_ndvi_df = pandas.DataFrame()\nsercSpectra_ndvi_df['wavelength'] = w\nsercSpectra_ndvi_df['mean_refl_ndvi_gtpt6'] = sercSpectra_ndvi_gtpt6\nsercSpectra_ndvi_df['mean_refl_ndvi_ltpt3'] = sercSpectra_ndvi_ltpt3\n\nax = plt.gca();\nsercSpectra_ndvi_df.plot(ax=ax,x='wavelength',y='mean_refl_ndvi_gtpt6',color='green',\n edgecolor='none',kind='scatter',label='NDVI > 0.6',legend=True);\nsercSpectra_ndvi_df.plot(ax=ax,x='wavelength',y='mean_refl_ndvi_ltpt3',color='red',\n edgecolor='none',kind='scatter',label='NDVI < 0.3',legend=True);\nax.set_title('Mean Spectra of Reflectance Masked by NDVI')\nax.set_xlim([np.nanmin(w),np.nanmax(w)]); ax.set_ylim(0,0.45)\nax.set_xlabel(\"Wavelength, nm\"); ax.set_ylabel(\"Reflectance\")\nax.grid('on'); ",
"References\nWu C-D, McNeely E, Cedeño-Laurent JG, Pan W-C, Adamkiewicz G, Dominici F, et al. (2014) Linking Student Performance in Massachusetts Elementary Schools with the “Greenness” of School Surroundings Using Remote Sensing. PLoS ONE 9(10): e108548. doi:10.1371/journal.pone.0108548"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
bourneli/deep-learning-notes
|
DAT236x Deep Learning Explained/Lab5_RecurrentNetwork.ipynb
|
mit
|
[
"Lab 5 - Time series prediction with LSTM (IOT Data)\nThis lab corresponds to Module 5 of the \"Deep Learning Explained\" course.\nIn this lab we want to build a model using some real world internet-of-things (IOT) data. As an example we want to predict the daily output of a solar panel base on the initial readings of the day. \nSolar power forecasting is a challenging and important problem. The solar energy generation forecasting problem is closely linked to the problem of weather variables forecasting. Indeed, this problem is usually split into two parts, on one hand focusing on the forecasting of solar PV (solar panel system) or any other meteorological variable and on the other hand estimating the amount of energy that a concrete power plant will produce with the estimated meteorological resource. In general, the way to deal with this difficult problem is usually related to the spatial and temporal scales we are interested in. This lab focusses on a simplified forecasting model using previously generated data from solar panel to predict the future. \nGoal\nUsing historic daily production of a solar panel, we want to predict the total power production of the solar panel array for a future day. We will be using an LSTM based time series prediction model to predict the daily output of a solar panel based on the initial readings of a the day. \n\nWe train the model with historical data of the solar panel. In our example we want to predict the total power production of the solar panel array for the day starting with the initial readings of the day. We start predicting after the first 2 readings and adjust the prediction with each new reading.\nWe will use a recurrent model with the LSTM cell. This lab has the following sub-sections:\n- Setup\n- Data generation\n- LSTM network modeling\n- Training, test and prediction workflow\nFor more details on how LSTMs work, view the Module 5 videos or see this excellent post.\nSetup",
"from matplotlib import pyplot as plt\nimport math\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nimport time\n\nimport cntk as C\n\ntry:\n from urllib.request import urlretrieve\nexcept ImportError:\n from urllib import urlretrieve\n\n%matplotlib inline\n\n# to make things reproduceable, seed random\nnp.random.seed(0)\nC.cntk_py.set_fixed_random_seed(1)\nC.cntk_py.force_deterministic_algorithms()",
"In the block below, we check if we are running this notebook in the CNTK internal test machines by looking for environment variables defined there. We then select the right target device (GPU vs CPU) to test this notebook. In other cases, we use CNTK's default policy to use the best available device (GPU, if available, else CPU).",
"if 'TEST_DEVICE' in os.environ:\n if os.environ['TEST_DEVICE'] == 'cpu':\n C.device.try_set_default_device(C.device.cpu())\n else:\n C.device.try_set_default_device(C.device.gpu(0))\n\n# Test for CNTK version\nif not C.__version__ == \"2.0\":\n raise Exception(\"this notebook was designed to work with 2.0. Current Version: \" + C.__version__) ",
"There are two training modes that we can choose from for this lab:\n- Fast mode: isFast is set to True. This is the default mode for the notebooks, which means we train for fewer iterations or train / test on limited data. This ensures functional correctness of the notebook though the models produced are far from what a completed training would produce.\n\nSlow mode: We recommend the user to set this flag to False once the user has gained familiarity with the notebook content and wants to gain insight from running the notebooks for a longer period with different parameters for training. \n\nFor Fast mode we train the model for 100 epochs and results have low accuracy but is good enough for development. The model yields good accuracy after 1000-2000 epochs.",
"isFast = True\n\n# we need around 2000 epochs to see good accuracy. For testing 100 epochs will do.\nEPOCHS = 200 if isFast else 2000",
"Data generation\nOur solar panel emits two measures at 30 min interval:\n- solar.current is the current production in Watt\n- solar.total is the total produced for the day so far in Watt/hour\nOur prediction approach involves starting with the first 2 initial readings of the day. Based on these readings we start predicting and adjust the prediction with each new reading. The training data we are going to use comes as a CSV file and has the following format:\n\ntime,solar.current,solar.total\n7am,6.3,1.7\n7:30am,44.3,11.4\n...\n\nOur training dataset contains 3 years of captured data and can be found here. \nThe dataset is not pre-processed: it is raw data and contains smaller gaps and errors (like a panel failed to report).\nPre-processing\nMost of the code in this example is related to data preparation. Thankfully the pandas library make this easy.\nBelow, we define a generate_solar_data() function that performs the following tasks:\n- read raw data into a pandas dataframe\n- normalize the data\n- group the data by day\n- append the columns \"solar.current.max\" and \"solar.total.max\"\n- generate the sequences for each day\n Sequence Generation The measurements for a day are grouped into a set of sequences, corresponding to each measurement for the day. Each measurement sequence will contain all of the raw measurements (solar.current, solar.total) seen for the current day, up until and including the current measurement. \nHere is an example of some sequehnces for a day:\n1.7,11.4 -> 10300\n1.7,11.4,67.5 -> 10300\n1.7,11.4,67.5,250.5 ... -> 10300\n1.7,11.4,67.5,250.5,573.5 -> 10300\nAll sequences for all days are flattened into a single list of sequences. The day and timestamp information have been removed; only the sequences matter.\nNote if we have less than 8 datapoints for a day we skip over the day assuming something is missing in the raw data. If we get more than 14 data points in a day we truncate the readings.\nTraining / Testing / Validation data preparation\nWe start by reading the CSV file. The raw data is sorted by time. Normally, we would randomize the data before splitting into training, validation and test datasets, but this would make it impractical to visualize results. \nHence, we split the dataset in the following manner: pick the following (in sequence order): 8 values for training, 1 for validation and 1 for test until there is no more data. This will spread training, validation and test datasets across the full timeline while preserving time order.",
"def generate_solar_data(input_url, time_steps, normalize=1, val_size=0.1, test_size=0.1):\n \"\"\"\n generate sequences to feed to rnn based on data frame with solar panel data\n the csv has the format: time ,solar.current, solar.total\n (solar.current is the current output in Watt, solar.total is the total production\n for the day so far in Watt hours)\n \"\"\"\n # try to find the data file local. If it doesn't exists download it.\n cache_path = os.path.join(\"data\", \"iot\")\n cache_file = os.path.join(cache_path, \"solar.csv\")\n if not os.path.exists(cache_path):\n os.makedirs(cache_path)\n if not os.path.exists(cache_file):\n urlretrieve(input_url, cache_file)\n print(\"downloaded data successfully from \", input_url)\n else:\n print(\"using cache for \", input_url)\n \n df = pd.read_csv(cache_file, index_col=\"time\", parse_dates=['time'], dtype=np.float32)\n \n df[\"date\"] = df.index.date\n \n # normalize data\n df['solar.current'] /= normalize\n df['solar.total'] /= normalize\n \n # group by day, find the max for a day and add a new column .max\n grouped = df.groupby(df.index.date).max()\n grouped.columns = [\"solar.current.max\", \"solar.total.max\", \"date\"]\n\n # merge continuous readings and daily max values into a single frame\n df_merged = pd.merge(df, grouped, right_index=True, on=\"date\")\n df_merged = df_merged[[\"solar.current\", \"solar.total\",\n \"solar.current.max\", \"solar.total.max\"]]\n # we group by day so we can process a day at a time.\n grouped = df_merged.groupby(df_merged.index.date)\n per_day = []\n for _, group in grouped:\n per_day.append(group)\n\n # split the dataset into train, validatation and test sets on day boundaries\n val_size = int(len(per_day) * val_size)\n test_size = int(len(per_day) * test_size)\n next_val = 0\n next_test = 0\n\n result_x = {\"train\": [], \"val\": [], \"test\": []}\n result_y = {\"train\": [], \"val\": [], \"test\": []} \n\n # generate sequences a day at a time\n for i, day in enumerate(per_day):\n # if we have less than 8 datapoints for a day we skip over the\n # day assuming something is missing in the raw data\n total = day[\"solar.total\"].values\n if len(total) < 8:\n continue\n if i >= next_val:\n current_set = \"val\"\n next_val = i + int(len(per_day) / val_size)\n elif i >= next_test:\n current_set = \"test\"\n next_test = i + int(len(per_day) / test_size)\n else:\n current_set = \"train\"\n max_total_for_day = np.array(day[\"solar.total.max\"].values[0])\n for j in range(2, len(total)):\n result_x[current_set].append(total[0:j])\n result_y[current_set].append([max_total_for_day])\n if j >= time_steps:\n break\n # make result_y a numpy array\n for ds in [\"train\", \"val\", \"test\"]:\n result_y[ds] = np.array(result_y[ds])\n return result_x, result_y",
"Data caching\nFor routine testing we would like to cache the data locally when available. If it is not available from the cache locations we shall download.",
"# there are 14 lstm cells, 1 for each possible reading we get per day\nTIMESTEPS = 14\n\n# 20000 is the maximum total output in our dataset. We normalize all values with \n# this so our inputs are between 0.0 and 1.0 range.\nNORMALIZE = 20000\n\nX, Y = generate_solar_data(\"https://www.cntk.ai/jup/dat/solar.csv\", \n TIMESTEPS, normalize=NORMALIZE)",
"Utility for data fetching\nnext_batch() yields the next batch for training. We use variable size sequences supported by CNTK and batches are a list of numpy arrays where the numpy arrays have variable length. \nA standard practice is to shuffle batches with each epoch. We don't do this here because we want to be able to graph the data that is easily interpretable.",
"# process batches of 10 days\nBATCH_SIZE = TIMESTEPS * 10\n\ndef next_batch(x, y, ds):\n \"\"\"get the next batch for training\"\"\"\n\n def as_batch(data, start, count):\n return data[start:start + count]\n\n for i in range(0, len(x[ds]), BATCH_SIZE):\n yield as_batch(X[ds], i, BATCH_SIZE), as_batch(Y[ds], i, BATCH_SIZE)",
"Understand the data format\nYou can now see the sequence we are going to feed to the LSTM. Note if we have less than 8 datapoints for a day we skip over the day assuming something is missing in the raw data. If we get more than 14 data points in a day we truncate the readings.",
"X['train'][0:3]\n\nY['train'][0:3]",
"LSTM network setup\nLSTM will automatically adapt to the maximum sequence length of our data; we do not need to specify this maximum length as part of our model and we do not need to pad our variable length sequences in any way.\nWe model our network with H_DIMS = 14 LSTM cells, which we have found (by trying other values) produces good prediction results for our problem. \nThe output of the neural network is the total output for the day and each sequence for a given day has the same total output.\nFor example:\n1.7,11.4 -> 10300\n1.7,11.4,67.5 -> 10300\n1.7,11.4,67.5,250.5 ... -> 10300\n1.7,11.4,67.5,250.5,573.5 -> 10300\nThe outputs from the LSTMs are feed into a dense layer and we randomly dropout 20% of the values to not overfit the model to the training set. The output of the dense layer becomes the prediction our model generates.\nOur LSTM model has the following design:\n\nThe network model is an exact translation of the network diagram above.",
"#Define the size of the internal state\nH_DIMS = 14 # error 0.007\n# H_DIMS = 7 # error 0.008\n# H_DIMS = 28 # erro 0.00862598\n# dropout 0.2, test error: 0.007\n# dropout 0.5, test error: 0.0083\n# dropout 0.9, test error: 0.013\ndef create_model(x):\n \"\"\"Create the model for time series prediction\"\"\"\n with C.layers.default_options(initial_state = 0.1):\n m = C.layers.Recurrence(C.layers.LSTM(H_DIMS))(x)\n #m = C.layers.Recurrence(C.layers.RNNStep(H_DIMS))(x) # 0.028\n m = C.sequence.last(m)\n m = C.layers.Dropout(0.2)(m)\n# m = C.layers.Dropout(0.5)(m)\n# m = C.layers.Dropout(0.9)(m)\n m = C.layers.Dense(1)(m)\n return m",
"Training\nBefore we can start training we need to bind our input variables for the model and define which optimizer we want to use. For this example we choose the adam optimizer. We choose squared_error as our loss function.",
"# input sequences\nx = C.sequence.input_variable(1)\n\n# create the model\nz = create_model(x)\n\n# expected output (label), also the dynamic axes of the model output\n# is specified as the model of the label input\nl = C.input_variable(1, dynamic_axes=z.dynamic_axes, name=\"y\")\n\n# the learning rate\nlearning_rate = 0.005\nlr_schedule = C.learning_rate_schedule(learning_rate, C.UnitType.minibatch)\n\n# loss and error function\nloss = C.squared_error(z, l)\nerror = C.squared_error(z, l)\n# loss = C.abs(z-l)\n# error = C.abs(z-l)\n\n# use adam optimizer\nmomentum_time_constant = C.momentum_as_time_constant_schedule(BATCH_SIZE / -math.log(0.9)) \nlearner = C.fsadagrad(z.parameters, \n lr = lr_schedule, \n momentum = momentum_time_constant)\n\ntrainer = C.Trainer(z, (loss, error), [learner])",
"Time to start training.",
"# training\nloss_summary = []\n\nstart = time.time()\nfor epoch in range(0, EPOCHS):\n for x_batch, l_batch in next_batch(X, Y, \"train\"):\n trainer.train_minibatch({x: x_batch, l: l_batch})\n \n if epoch % (EPOCHS / 10) == 0:\n training_loss = trainer.previous_minibatch_loss_average\n loss_summary.append(training_loss)\n print(\"epoch: {}, loss: {:.4f}\".format(epoch, training_loss))\n\nprint(\"Training took {:.1f} sec\".format(time.time() - start))",
"A look how the loss function shows how the model is converging:",
"plt.plot(loss_summary, label='training loss');",
"Let us evaluate our performance for the training, validation, and test datasets. We use mean squared error as our metric which might be a little simplistic. A method that would define a ratio of how many predictions have been inside a given tolerance would make a better measure.\n Suggested Exploration: Try out absolute error (C.abs(z-l)) instead of a squared error.",
"# evaluate the specified X and Y data on our model\ndef get_error(X,Y,labeltxt):\n result = 0.0\n numbatches = 0\n for x1, y1 in next_batch(X, Y, labeltxt):\n eval_error = trainer.test_minibatch({x : x1, l : y1})\n result += eval_error\n numbatches += 1\n\n return float(result)/numbatches\n\n# Print the training and validation errors\nfor labeltxt in [\"train\", \"val\"]:\n print(\"Error for {}: {:.8f}\".format(labeltxt, get_error(X, Y, labeltxt)))\n\n# Print the test error\nlabeltxt = \"test\"\nprint(\"Error for {}: {:.8f}\".format(labeltxt, get_error(X, Y, labeltxt)))",
"Visualize the prediction\nOur model has been trained well, given that the training, validation and test errors are in the same ballpark. To better understand our predictions, let's visualize the results. We will take our newly created model, make predictions and plot them against the actual readings.",
"# predict\nf, a = plt.subplots(2, 1, figsize=(12, 8))\nfor j, ds in enumerate([\"val\", \"test\"]):\n results = []\n for x_batch, _ in next_batch(X, Y, ds):\n pred = z.eval({x: x_batch})\n results.extend(pred[:, 0])\n # because we normalized the input data we need to multiply the prediction\n # with SCALER to get the real values.\n a[j].plot((Y[ds] * NORMALIZE).flatten(), label=ds + ' raw');\n a[j].plot(np.array(results) * NORMALIZE, label=ds + ' pred');\n a[j].legend();",
"If we let the model train for 2000 epochs the predictions are close to the actual data and follow the right pattern.\n Suggested Exploration \nSo what we do with this model? A practical application would be to generate alerts if the actual output is not in line with the prediction, for example if one of the panels is failing. The solar array that goes with our dataset has 16 panels. If we'd want to detect failure without generating false alerts, the accuracy of our prediction would need to be at least 1 - 1/16, around 94%. Our model is close to this but would most likely generate occasional false alerts.\n\nImprove the model by training for more epochs.\nFurther preprocess the training set to smooth-out missing values\nTry out more complex networks.\n\nIn our experience with time series data, one can achieve significant accuracy improvement using higher resolution training data, for example, reading a data point every 5 minutes instead of every 30 minutes.\nWe hope this tutorial gets you started on time series prediction with neural networks."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
feststelltaste/software-analytics
|
notebooks/Word Cloud Computing.ipynb
|
gpl-3.0
|
[
"Introduction\nYou all know word clouds:\n \nThey give you a quick overview of the top topics of your blog, book, source code – or presentation. The latter was the one that got me thinking: How cool would it be if you start your presentation with a word cloud of the main topics of your talk? And: How easy is it to do that completely automated with Python?!\nSo let's go crazy this time with word cloud computing for different data sources like texts, web sites, source code and PowerPoint presentations!\nThe Idea\nThe main idea is to read any text in any format, preprocess it and throw it against a word cloud producing library. For this, we need some main libraries that do all the work for us:\n\n<tt>nltk</tt> for some big texts and for cleaning up our input texts\n<tt>beautifulsoup</tt> for getting raw texts from HTML websites\n<tt>pygments</tt> for retrieving identifiers from source code\n<tt>python-pptx</tt> for extracting texts from PowerPoint slides\n<tt>wordcloud</tt> for producing, well, a word cloud\n\nSo let's get started!\nBasic example\nIn this section, I demonstrate how easy it is to produce a word cloud from some given text with <tt>wordcloud</tt>. We import the <tt>WordCloud</tt> class and use it directly to generate a word cloud with two words.",
"from wordcloud import WordCloud\nWordCloud().generate(\"Hello reader!\").to_image()",
"We see that <tt>wordcloud</tt> just did some text preprocessing (like removing the \"!\") and rendered the texts.\nThat's it!\nAdvanced example\nThe example above wasn't very impressive and expressive. So we use <tt>nltk</tt> to retrieve some big texts from a corpus. In the following word cloud, we want to display the main topics of some movie reviews.",
"from nltk.corpus import movie_reviews\nmovie_reviews.words()[:10]",
"We also need some basic text preprocessing: removing the language's common words via a stop list for that language. The stop list is just a different kind of corpus – a list of text tokens.",
"from nltk.corpus import stopwords\nenglish_stopword_tokens = stopwords.words('english')\nenglish_stopword_tokens[:10]",
"Let's do some basic text preprocessing by only keeping alphabetic characters and removing the stop words.",
"movie_reviews_tokens = [s for s in movie_reviews.words() \n if s.isalpha() and \n not s in english_stopword_tokens]\nmovie_reviews_tokens[:5]",
"We join the text array together to get a long string and display it as word cloud.",
"movie_reviews_texts = \" \".join(movie_reviews_tokens)\nWordCloud().generate(movie_reviews_texts).to_image()",
"Let's move on to some more interesting visualizations.\nHTML webpage\nWe can read any website via Python's built-in <tt>request</tt> library. In this example, we read the aim42 (a guide for software architecture improvement; very valuable and interesting!) directly from the guide's website. We just need to get the response's text, that delivers the website as pure HTML.",
"import requests\nwebpage = requests.get(\"http://aim42.github.io/\")\nwebpage.text[:100]",
"We use <tt>beautifulsoup</tt> so get only the text from the HTML.",
"from bs4 import BeautifulSoup\nparsed_content = BeautifulSoup(webpage.text, 'html.parser')\ntext_content = parsed_content.body.get_text()\ntext_content[:100]",
"Again, we clean up the data by only processing any alphabetic text and keeping all the tokens that aren't in the stop word list.",
"content_tokens = []\nfor line in text_content.split(\"\\n\"):\n for token in line.split(\" \"):\n if token.isalpha() and not token in english_stopword_tokens:\n content_tokens.append(token.lower())\ncontent_tokens[0:5]",
"And again, we produce a word cloud. For a nicer styling, we set some arguments in the constructor.",
"text = \" \".join(content_tokens)\nWordCloud(max_font_size=40,\n scale=1.5,\n background_color=\"white\").generate(text).to_image()",
"Here we are! The aim42 guide is (amongst other things) about data, system and architecture :-).\nSource code\nNext, we move over to source code!\nIt's nice to get a quick overview of what your software is all about. Our study object, in this case, is the Spring PetClinic. For our nice word cloud, we need to read all the source code files, extract the identifiers, handle some programming language specific cases and remove common words via the stop list.\nAnd here comes some magic all in one dirty little code block (I promise to get through it step by step in another blog post/notebook):\n\nWe use <tt>glob</tt> to get a list of source code paths and read the content.\nWe use <tt>pygments</tt>'s <tt>JavaLexer</tt> to retrieve just the tokens we want.\nWe use some regex voodoo to break Java's CamelCase names into separate words.\nWe filter out common Java and English words via a stop list.\nWe set a minimal number of characters a word has to consist of.",
"import glob\nfrom pygments.token import Token\nfrom pygments.lexers.jvm import JavaLexer\nimport re\n\nLEXER = JavaLexer()\n\nCAMEL_CASE_1_PATTERN = re.compile(r'(.)([A-Z][a-z]+)')\nCAMEL_CASE_2_PATTERN = re.compile(r'([a-z0-9])([A-Z])')\nWORD_BOUNDARY_PATTERN = re.compile(r'[^a-zA-Z]')\n\nJAVA_STOP_WORDS = set([\"byte\", \"short\", \"int\", \"long\", \n \"float\", \"double\", \"char\", \"string\", \n \"object\", \"java\", \"get\", \"set\", \"is\"])\n\nSTOP_LIST = JAVA_STOP_WORDS | set(english_stopword_tokens)\nMIN_WORD_LENGTH = 3\n\n\ndef break_tokens(tokens):\n tokens = CAMEL_CASE_1_PATTERN.sub(r'\\1 \\2', tokens)\n tokens = CAMEL_CASE_2_PATTERN.sub(r'\\1 \\2', tokens)\n tokens = WORD_BOUNDARY_PATTERN.sub(' ', tokens)\n return tokens.split(' ')\n\n\ndef filter_token(tokens_of_name):\n filtered_tokens = []\n for token in tokens_of_name:\n if len(token) >= MIN_WORD_LENGTH and token.lower() not in STOP_LIST:\n filtered_tokens.append(token.lower())\n return filtered_tokens\n \n \ndef extract_names(file_path, token_types):\n\n extracted_names = []\n \n with open(file_path) as source_code_file:\n \n source_code_content = source_code_file.read()\n \n for token_type, tokens in LEXER.get_tokens(source_code_content):\n\n if token_type in token_types:\n tokens_of_name = break_tokens(tokens) \n extracted_names.extend(filter_token(tokens_of_name))\n\n return extracted_names\n\n\ndef extract_names_from_source_code(root_dir, glob_pattern, relevant_token_types):\n \n file_paths = glob.glob(root_dir + glob_pattern, recursive=True)\n \n filtered_names = []\n \n for file_path in file_paths:\n\n names = extract_names(file_path, relevant_token_types)\n\n if len(names) > 0:\n filtered_names.extend(names)\n\n return filtered_names\n\nrelevant_token_types = [Token.Name]\n\nnames = extract_names_from_source_code(\n r'../../spring-petclinic/src/main', \n '/**/*.java',\n relevant_token_types)\n\nnames[:5]",
"As above, we join the names and create a word cloud.",
"names_text = \" \".join(names)\nWordCloud(width=360, height=360).generate(names_text).to_image()",
"Well, I guess the PetClinic software is about \"pets\" ;-)\nPowerPoint Presentation\nLast but not least, to our original goal: creating a word cloud for my PowerPoint presentation (in German and English). \nWe use <tt>python-pptx</tt> to wind our way through the presentation.",
"from pptx import Presentation\nPPTX = r'data/talk.pptx'\nprs = Presentation(PPTX)\n\ntext_fragments = []\nfor slide in prs.slides:\n \n # store title for later replacement\n title = \"\"\n if slide.shapes.title and slide.shapes.title.text:\n title = slide.shapes.title.text\n \n # read the slide's notes\n if slide.has_notes_slide:\n notes = slide.notes_slide.notes_text_frame.text\n note_tokens = notes.split(\" \")\n text_fragments.extend(s for s in note_tokens if s.isalpha())\n \n # read the slide's text\n for shape in slide.shapes:\n if not shape.has_text_frame:\n continue\n \n text_frame_text = shape.text_frame.text.replace(title, \"\")\n text_frame_tokens = text_frame_text.split(\" \")\n text_fragments.extend(s for s in text_frame_tokens if s.isalpha())\n \ntext_fragments[:5]",
"Cleaning up the tokens is a little bit tricky because we have German as well as English words in it. We also need some additional stop words for words that aren't common but don't make sense in a word cloud.\nAnd we filter out the words that are contained in the stop list.",
"german_stopword_tokens = stopwords.words('german')\nstop_word_tokens = set(german_stopword_tokens) | set(english_stopword_tokens)\ncustom_stop_words = [\"Nichts\", \"unserer\", \"viele\", \"großen\", \"Du\", \"Deiner\"]\nstop_word_tokens = stop_word_tokens | set(custom_stop_words)\n\ntext_tokens = [token for token \n in text_fragments \n if token not in stop_word_tokens]\ntext_tokens[:5]",
"And now finally: The word cloud of my PowerPoint presentation! :-)",
"text = \" \".join(text_tokens)\nWordCloud(min_font_size=30, \n max_font_size=80, \n scale=0.5, \n width=960, \n height=720).generate(text).to_image()",
"Nice! For non-German-speakers: It's about reproducible, data-driven, automated software analysis.\nSummary\nIf you read this, you withstand this long article! I showed you how to extract texts from various formats. As you probably saw, the main work is cleaning up the texts before displaying it properly. It's said that in Data Science, 80% of the analytic's work is cleaning up the data. Well, we certainly saw that today!\nNonetheless, have fun creating your own word clouds!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
tensorflow/federated
|
docs/tutorials/custom_federated_algorithm_with_tff_optimizers.ipynb
|
apache-2.0
|
[
"Copyright 2021 The TensorFlow Authors.",
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/federated/tutorials/custom_federated_algorithm_with_tff_optimizers\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/federated/blob/v0.27.0/docs/tutorials/custom_federated_algorithm_with_tff_optimizers.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/federated/blob/v0.27.0/docs/tutorials/custom_federated_algorithm_with_tff_optimizers.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/federated/docs/tutorials/custom_federated_algorithm_with_tff_optimizers.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n\nUse TFF optimizers in custom iterative process\nThis is an alternative to the Build Your Own Federated Learning Algorithm tutorial and the simple_fedavg example to build a custom iterative process for the federated averaging algorithm. This tutorial will use TFF optimizers instead of Keras optimizers. \nThe TFF optimizer abstraction is desgined to be state-in-state-out to be easier to be incorporated in a TFF iterative process. The tff.learning APIs also accept TFF optimizers as input argument. \nBefore we start\nBefore we start, please run the following to make sure that your environment is\ncorrectly setup. If you don't see a greeting, please refer to the\nInstallation guide for instructions.",
"#@test {\"skip\": true}\n!pip install --quiet --upgrade tensorflow-federated\n!pip install --quiet --upgrade nest-asyncio\n\nimport nest_asyncio\nnest_asyncio.apply()\n\nimport functools\nimport attr\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_federated as tff",
"Preparing data and model\nThe EMNIST data processing and model are very similar to the simple_fedavg example.",
"only_digits=True\n\n# Load dataset.\nemnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(only_digits)\n\n# Define preprocessing functions.\ndef preprocess_fn(dataset, batch_size=16):\n\n def batch_format_fn(element):\n return (tf.expand_dims(element['pixels'], -1), element['label'])\n\n return dataset.batch(batch_size).map(batch_format_fn)\n\n# Preprocess and sample clients for prototyping.\ntrain_client_ids = sorted(emnist_train.client_ids)\ntrain_data = emnist_train.preprocess(preprocess_fn)\ncentral_test_data = preprocess_fn(\n emnist_train.create_tf_dataset_for_client(train_client_ids[0]))\n\n# Define model.\ndef create_keras_model():\n \"\"\"The CNN model used in https://arxiv.org/abs/1602.05629.\"\"\"\n data_format = 'channels_last'\n input_shape = [28, 28, 1]\n\n max_pool = functools.partial(\n tf.keras.layers.MaxPooling2D,\n pool_size=(2, 2),\n padding='same',\n data_format=data_format)\n conv2d = functools.partial(\n tf.keras.layers.Conv2D,\n kernel_size=5,\n padding='same',\n data_format=data_format,\n activation=tf.nn.relu)\n\n model = tf.keras.models.Sequential([\n conv2d(filters=32, input_shape=input_shape),\n max_pool(),\n conv2d(filters=64),\n max_pool(),\n tf.keras.layers.Flatten(),\n tf.keras.layers.Dense(512, activation=tf.nn.relu),\n tf.keras.layers.Dense(10 if only_digits else 62),\n ])\n\n return model\n\n# Wrap as `tff.learning.Model`.\ndef model_fn():\n keras_model = create_keras_model()\n return tff.learning.from_keras_model(\n keras_model,\n input_spec=central_test_data.element_spec,\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))",
"Custom iterative process\nIn many cases, federated algorithms have 4 main components:\n\nA server-to-client broadcast step.\nA local client update step.\nA client-to-server upload step.\nA server update step.\n\nIn TFF, we generally represent federated algorithms as a tff.templates.IterativeProcess (which we refer to as just an IterativeProcess throughout). This is a class that contains initialize and next functions. Here, initialize is used to initialize the server, and next will perform one communication round of the federated algorithm. \nWe will introduce different components to build the federated averaging (FedAvg) algorithm, which will use an optimizer in the client update step, and another optimizer in the server update step. The core logics of client and server updates can be expressed as pure TF blocks.\nTF blocks: client and server update\nOn each client, a local client_optimizer is initialized and used to update the client model weights. On the server, server_optimizer will use the state from the previous round, and update the state for the next round.",
"@tf.function\ndef client_update(model, dataset, server_weights, client_optimizer):\n \"\"\"Performs local training on the client's dataset.\"\"\"\n # Initialize the client model with the current server weights.\n client_weights = model.trainable_variables\n # Assign the server weights to the client model.\n tf.nest.map_structure(lambda x, y: x.assign(y),\n client_weights, server_weights)\n # Initialize the client optimizer.\n trainable_tensor_specs = tf.nest.map_structure(\n lambda v: tf.TensorSpec(v.shape, v.dtype), client_weights)\n optimizer_state = client_optimizer.initialize(trainable_tensor_specs)\n # Use the client_optimizer to update the local model.\n for batch in iter(dataset):\n with tf.GradientTape() as tape:\n # Compute a forward pass on the batch of data.\n outputs = model.forward_pass(batch)\n # Compute the corresponding gradient.\n grads = tape.gradient(outputs.loss, client_weights)\n # Apply the gradient using a client optimizer.\n optimizer_state, updated_weights = client_optimizer.next(\n optimizer_state, client_weights, grads)\n tf.nest.map_structure(lambda a, b: a.assign(b), \n client_weights, updated_weights)\n # Return model deltas.\n return tf.nest.map_structure(tf.subtract, client_weights, server_weights)\n\n@attr.s(eq=False, frozen=True, slots=True)\nclass ServerState(object):\n trainable_weights = attr.ib()\n optimizer_state = attr.ib()\n\n@tf.function\ndef server_update(server_state, mean_model_delta, server_optimizer):\n \"\"\"Updates the server model weights.\"\"\"\n # Use aggregated negative model delta as pseudo gradient. \n negative_weights_delta = tf.nest.map_structure(\n lambda w: -1.0 * w, mean_model_delta)\n new_optimizer_state, updated_weights = server_optimizer.next(\n server_state.optimizer_state, server_state.trainable_weights, \n negative_weights_delta)\n return tff.structure.update_struct(\n server_state,\n trainable_weights=updated_weights,\n optimizer_state=new_optimizer_state)",
"TFF blocks: tff.tf_computation and tff.federated_computation\nWe now use TFF for orchestration and build the iterative process for FedAvg. We have to wrap the TF blocks defined above with tff.tf_computation, and use TFF methods tff.federated_broadcast, tff.federated_map, tff.federated_mean in a tff.federated_computation function. It is easy to use the tff.learning.optimizers.Optimizer APIs with initialize and next functions when defining a custom iterative process.",
"# 1. Server and client optimizer to be used.\nserver_optimizer = tff.learning.optimizers.build_sgdm(\n learning_rate=0.05, momentum=0.9)\nclient_optimizer = tff.learning.optimizers.build_sgdm(\n learning_rate=0.01)\n\n# 2. Functions return initial state on server. \n@tff.tf_computation\ndef server_init():\n model = model_fn()\n trainable_tensor_specs = tf.nest.map_structure(\n lambda v: tf.TensorSpec(v.shape, v.dtype), model.trainable_variables)\n optimizer_state = server_optimizer.initialize(trainable_tensor_specs)\n return ServerState(\n trainable_weights=model.trainable_variables,\n optimizer_state=optimizer_state)\n\n@tff.federated_computation\ndef server_init_tff():\n return tff.federated_value(server_init(), tff.SERVER)\n\n# 3. One round of computation and communication.\nserver_state_type = server_init.type_signature.result\nprint('server_state_type:\\n', \n server_state_type.formatted_representation())\ntrainable_weights_type = server_state_type.trainable_weights\nprint('trainable_weights_type:\\n', \n trainable_weights_type.formatted_representation())\n\n# 3-1. Wrap server and client TF blocks with `tff.tf_computation`.\n@tff.tf_computation(server_state_type, trainable_weights_type)\ndef server_update_fn(server_state, model_delta):\n return server_update(server_state, model_delta, server_optimizer)\n\nwhimsy_model = model_fn()\ntf_dataset_type = tff.SequenceType(whimsy_model.input_spec)\nprint('tf_dataset_type:\\n', \n tf_dataset_type.formatted_representation())\n@tff.tf_computation(tf_dataset_type, trainable_weights_type)\ndef client_update_fn(dataset, server_weights):\n model = model_fn()\n return client_update(model, dataset, server_weights, client_optimizer)\n\n# 3-2. Orchestration with `tff.federated_computation`.\nfederated_server_type = tff.FederatedType(server_state_type, tff.SERVER)\nfederated_dataset_type = tff.FederatedType(tf_dataset_type, tff.CLIENTS)\n@tff.federated_computation(federated_server_type, federated_dataset_type)\ndef run_one_round(server_state, federated_dataset):\n # Server-to-client broadcast.\n server_weights_at_client = tff.federated_broadcast(\n server_state.trainable_weights)\n # Local client update.\n model_deltas = tff.federated_map(\n client_update_fn, (federated_dataset, server_weights_at_client))\n # Client-to-server upload and aggregation.\n mean_model_delta = tff.federated_mean(model_deltas)\n # Server update.\n server_state = tff.federated_map(\n server_update_fn, (server_state, mean_model_delta))\n return server_state\n\n# 4. Build the iterative process for FedAvg.\nfedavg_process = tff.templates.IterativeProcess(\n initialize_fn=server_init_tff, next_fn=run_one_round)\nprint('type signature of `initialize`:\\n', \n fedavg_process.initialize.type_signature.formatted_representation())\nprint('type signature of `next`:\\n', \n fedavg_process.next.type_signature.formatted_representation())",
"Evaluating the algorithm\nWe evaluate the performance on a centralized evaluation dataset.",
"def evaluate(server_state):\n keras_model = create_keras_model()\n tf.nest.map_structure(\n lambda var, t: var.assign(t),\n keras_model.trainable_weights, server_state.trainable_weights)\n metric = tf.keras.metrics.SparseCategoricalAccuracy()\n for batch in iter(central_test_data):\n preds = keras_model(batch[0], training=False)\n metric.update_state(y_true=batch[1], y_pred=preds)\n return metric.result().numpy()\n\nserver_state = fedavg_process.initialize()\nacc = evaluate(server_state)\nprint('Initial test accuracy', acc)\n\n# Evaluate after a few rounds\nCLIENTS_PER_ROUND=2\nsampled_clients = train_client_ids[:CLIENTS_PER_ROUND]\nsampled_train_data = [\n train_data.create_tf_dataset_for_client(client)\n for client in sampled_clients]\nfor round in range(20):\n server_state = fedavg_process.next(server_state, sampled_train_data)\nacc = evaluate(server_state)\nprint('Test accuracy', acc)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
charlesll/RamPy
|
examples/Smoothing.ipynb
|
gpl-2.0
|
[
"Quick example to smooth a signal",
"%pylab inline\n#import sys\nsys.path.append(\"../\")\nimport numpy as np\nimport scipy\nfrom matplotlib import pyplot as plt\n#import gcvspline\nimport rampy as rp\nimport gcvspline",
"Creating a fake, noisy signal",
"nb_points = 200\nx = np.linspace(50, 600, nb_points)\n\n# gaussian peaks\np1 = 20.0 * np.exp(-np.log(2) * ((x-150.0)/15.0)**2)\np2 = 100.0 * np.exp(-np.log(2) * ((x-250.0)/20.0)**2)\np3 = 50.0 * np.exp(-np.log(2) * ((x-450.0)/50.0)**2)\np4 = 20.0 * np.exp(-np.log(2) * ((x-350.0)/300)**2)\np5 = 30.0 * np.exp(-np.log(2) * ((x-460.0)/5.0)**2)\n\n# background: a large gaussian + linear \nbkg = 60.0 * np.exp(-np.log(2) * ((x-250.0)/200.0)**2) + 0.1*x\n\n#noise\nnoise = 2.0 * np.random.normal(size=nb_points)\n\n#observation\ny = p1 + p2 + p3 + p4 + p5 + noise +bkg\n",
"Smoothing the signal with the smooth() function\nThe smooth function has 10 different smnoothings algorithms.\nSpline, Savitsky-Golay and Whittaker smoothing are available as:\n - GCVSmoothedNSpline (Generalised Cross Validated Spline, see gcvspline doc)\n - DOFSmoothedNSpline (Degree of Freedom spline, see gcvspline doc)\n - MSESmoothedNSpline (Mean Square Error spline, see gcvspline doc)\n - savgol, the scipy Savitsky-Golay filter\n - whittaker, a Whittaker smoother (see also whittaker() function)\nMoving window smoothings are available by setting the method to:\n - flat, a flat window smoothing\n - hanning, a hanning window smoothing\n - hamming, a hamming window smoothing\n - bartlett, a bartlett window smoothing\n - blackman, a blackman window smoothing\nSee the smooth function help for more details on parameters",
"y_smo_1 = rp.smooth(x,y,method=\"GCVSmoothedNSpline\")\ny_smo_2 = rp.smooth(x,y,method=\"DOFSmoothedNSpline\")\ny_smo_3 = rp.smooth(x,y,method=\"MSESmoothedNSpline\")\ny_smo_4 = rp.smooth(x,y,method=\"savgol\",window_length=5,polyorder=2)\ny_smo_5 = rp.smooth(x,y,method=\"whittaker\",Lambda=10**0.5)\ny_smo_6 = rp.smooth(x,y,method=\"flat\",window_length=5)\ny_smo_7 = rp.smooth(x,y,method=\"hanning\",window_length=5)\ny_smo_8 = rp.smooth(x,y,method=\"hamming\",window_length=5)\ny_smo_9 = rp.smooth(x,y,method=\"bartlett\",window_length=5)\ny_smo_10 = rp.smooth(x,y,method=\"blackman\",window_length=5)",
"Figures",
"plt.figure(figsize=(8,8))\nplt.subplot(2,1,1)\nplt.plot(x,y,\"k.\",label=\"signal\")\nplt.plot(x,y_smo_1,label=\"GCVSmoothedNSpline\")\nplt.plot(x,y_smo_2,label=\"DOFSmoothedNSpline\")\nplt.plot(x,y_smo_3,label=\"MSESmoothedNSpline\")\nplt.plot(x,y_smo_4,label=\"savgol\")\nplt.plot(x,y_smo_5,label=\"whittaker\")\n\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.legend()\n\nplt.subplot(2,1,2)\nplt.plot(x,y,\"k.\",label=\"signal\")\nplt.plot(x,y_smo_6,label=\"flat\")\nplt.plot(x,y_smo_7,label=\"hanning\")\nplt.plot(x,y_smo_8,label=\"hamming\")\nplt.plot(x,y_smo_9,label=\"bartlett\")\nplt.plot(x,y_smo_10,label=\"blackman\")\n\nplt.xlabel(\"X\")\nplt.ylabel(\"Y\")\nplt.legend()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
y2ee201/Deep-Learning-Nanodegree
|
transfer-learning/Transfer_Learning.ipynb
|
mit
|
[
"Transfer Learning\nMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebook, you'll be using VGGNet trained on the ImageNet dataset as a feature extractor. Below is a diagram of the VGGNet architecture.\n<img src=\"assets/cnnarchitecture.jpg\" width=700px>\nVGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.\nYou can read more about transfer learning from the CS231n course notes.\nPretrained VGGNet\nWe'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. Make sure to clone this repository to the directory you're working from. You'll also want to rename it so it has an underscore instead of a dash.\ngit clone https://github.com/machrisaa/tensorflow-vgg.git tensorflow_vgg\nThis is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. You'll need to clone the repo into the folder containing this notebook. Then download the parameter file using the next cell.",
"from urllib.request import urlretrieve\nfrom os.path import isfile, isdir\nfrom tqdm import tqdm\n\nvgg_dir = 'tensorflow_vgg/'\n# Make sure vgg exists\nif not isdir(vgg_dir):\n raise Exception(\"VGG directory doesn't exist!\")\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile(vgg_dir + \"vgg16.npy\"):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:\n urlretrieve(\n 'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',\n vgg_dir + 'vgg16.npy',\n pbar.hook)\nelse:\n print(\"Parameter file already exists!\")",
"Flower power\nHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the TensorFlow inception tutorial.",
"import tarfile\n\ndataset_folder_path = 'flower_photos'\n\nclass DLProgress(tqdm):\n last_block = 0\n\n def hook(self, block_num=1, block_size=1, total_size=None):\n self.total = total_size\n self.update((block_num - self.last_block) * block_size)\n self.last_block = block_num\n\nif not isfile('flower_photos.tar.gz'):\n with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:\n urlretrieve(\n 'http://download.tensorflow.org/example_images/flower_photos.tgz',\n 'flower_photos.tar.gz',\n pbar.hook)\n\nif not isdir(dataset_folder_path):\n with tarfile.open('flower_photos.tar.gz') as tar:\n tar.extractall()\n tar.close()",
"ConvNet Codes\nBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.\nHere we're using the vgg16 module from tensorflow_vgg. The network takes images of size $224 \\times 224 \\times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from the source code):\n```\nself.conv1_1 = self.conv_layer(bgr, \"conv1_1\")\nself.conv1_2 = self.conv_layer(self.conv1_1, \"conv1_2\")\nself.pool1 = self.max_pool(self.conv1_2, 'pool1')\nself.conv2_1 = self.conv_layer(self.pool1, \"conv2_1\")\nself.conv2_2 = self.conv_layer(self.conv2_1, \"conv2_2\")\nself.pool2 = self.max_pool(self.conv2_2, 'pool2')\nself.conv3_1 = self.conv_layer(self.pool2, \"conv3_1\")\nself.conv3_2 = self.conv_layer(self.conv3_1, \"conv3_2\")\nself.conv3_3 = self.conv_layer(self.conv3_2, \"conv3_3\")\nself.pool3 = self.max_pool(self.conv3_3, 'pool3')\nself.conv4_1 = self.conv_layer(self.pool3, \"conv4_1\")\nself.conv4_2 = self.conv_layer(self.conv4_1, \"conv4_2\")\nself.conv4_3 = self.conv_layer(self.conv4_2, \"conv4_3\")\nself.pool4 = self.max_pool(self.conv4_3, 'pool4')\nself.conv5_1 = self.conv_layer(self.pool4, \"conv5_1\")\nself.conv5_2 = self.conv_layer(self.conv5_1, \"conv5_2\")\nself.conv5_3 = self.conv_layer(self.conv5_2, \"conv5_3\")\nself.pool5 = self.max_pool(self.conv5_3, 'pool5')\nself.fc6 = self.fc_layer(self.pool5, \"fc6\")\nself.relu6 = tf.nn.relu(self.fc6)\n```\nSo what we want are the values of the first fully connected layer, after being ReLUd (self.relu6). To build the network, we use\nwith tf.Session() as sess:\n vgg = vgg16.Vgg16()\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n with tf.name_scope(\"content_vgg\"):\n vgg.build(input_)\nThis creates the vgg object, then builds the graph with vgg.build(input_). Then to get the values from the layer,\nfeed_dict = {input_: images}\ncodes = sess.run(vgg.relu6, feed_dict=feed_dict)",
"import os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_vgg import vgg16\nfrom tensorflow_vgg import utils\n\ndata_dir = 'flower_photos/'\ncontents = os.listdir(data_dir)\nclasses = [each for each in contents if os.path.isdir(data_dir + each)]",
"Below I'm running images through the VGG network in batches.\n\nExercise: Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).",
"# Set the batch size higher if you can fit in in your GPU memory\nbatch_size = 10\ncodes_list = []\nlabels = []\nbatch = []\n\ncodes = None\n\nwith tf.Session() as sess:\n \n # TODO: Build the vgg network here\n vgg = vgg16.Vgg16()\n inputs_ = tf.placeholder(tf.float32, shape=[None, 224, 224, 3])\n with tf.name_scope('content_vgg'):\n vgg.build(inputs_)\n\n for each in classes:\n print(\"Starting {} images\".format(each))\n class_path = data_dir + each\n files = os.listdir(class_path)\n for ii, file in enumerate(files, 1):\n # Add images to the current batch\n # utils.load_image crops the input images for us, from the center\n img = utils.load_image(os.path.join(class_path, file))\n batch.append(img.reshape((1, 224, 224, 3)))\n labels.append(each)\n \n # Running the batch through the network to get the codes\n if ii % batch_size == 0 or ii == len(files):\n \n # Image batch to pass to VGG network\n images = np.concatenate(batch)\n \n # TODO: Get the values from the relu6 layer of the VGG network\n codes_batch = sess.run(vgg.relu6, feed_dict={inputs_: images})\n \n # Here I'm building an array of the codes\n if codes is None:\n codes = codes_batch\n else:\n codes = np.concatenate((codes, codes_batch))\n \n # Reset to start building the next batch\n batch = []\n print('{} images processed'.format(ii))\n\n# write codes to file\nwith open('codes', 'w') as f:\n codes.tofile(f)\n \n# write labels to file\nimport csv\nwith open('labels', 'w') as f:\n writer = csv.writer(f, delimiter='\\n')\n writer.writerow(labels)",
"Building the Classifier\nNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.",
"# read codes and labels from file\nimport csv\n\nwith open('labels') as f:\n reader = csv.reader(f, delimiter='\\n')\n labels = np.array([each for each in reader if len(each) > 0]).squeeze()\nwith open('codes') as f:\n codes = np.fromfile(f, dtype=np.float32)\n codes = codes.reshape((len(labels), -1))",
"Data prep\nAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!\n\nExercise: From scikit-learn, use LabelBinarizer to create one-hot encoded vectors from the labels.",
"from sklearn.preprocessing import LabelBinarizer\nlb = LabelBinarizer()\nlb.fit(labels)\n\nlabels_vecs = lb.transform(labels) # Your one-hot encoded labels array here\nprint(labels[1600:1604])\nprint(labels_vecs[1600:1604])",
"Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use StratifiedShuffleSplit from scikit-learn.\nYou can create the splitter like so:\nss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)\nThen split the data with \nsplitter = ss.split(x, y)\nss.split returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use next(splitter) to get the indices. Be sure to read the documentation and the user guide.\n\nExercise: Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets.",
"from sklearn.model_selection import StratifiedShuffleSplit\nss = StratifiedShuffleSplit(n_splits = 1, test_size = 0.2)\nsplitter = ss.split(codes, labels_vecs)\n\nfor train_index, test_index in splitter:\n train_x, train_y = codes[train_index], labels_vecs[train_index]\n val_x, val_y = codes[test_index], labels_vecs[test_index]\n\nss = StratifiedShuffleSplit(n_splits = 1, test_size = 0.5)\nsplitter = ss.split(val_x, val_y)\n\nfor val_index, test_index in splitter:\n test_x, test_y = val_x[test_index], val_y[test_index]\n val_x, val_y = val_x[val_index], val_y[val_index]\n\nprint(\"Train shapes (x, y):\", train_x.shape, train_y.shape)\nprint(\"Validation shapes (x, y):\", val_x.shape, val_y.shape)\nprint(\"Test shapes (x, y):\", test_x.shape, test_y.shape)",
"If you did it right, you should see these sizes for the training sets:\nTrain shapes (x, y): (2936, 4096) (2936, 5)\nValidation shapes (x, y): (367, 4096) (367, 5)\nTest shapes (x, y): (367, 4096) (367, 5)\nClassifier layers\nOnce you have the convolutional codes, you just need to build a classfier from some fully connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.\n\nExercise: With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost.",
"inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]])\nlabels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]])\n\nlearning_rate = 0.01\n\n# TODO: Classifier layers and operations\n# weights = tf.Variable(tf.truncated_normal(dtype=tf.float32, mean=0, stddev=0.1, shape=[codes.shape[1], 5]))\n# biases = tf.Variable(tf.truncated_normal(dtype=tf.float32, mean=0, stddev=0.1, shape=[5]))\n\nfc = tf.contrib.layers.fully_connected(inputs=inputs_, num_outputs=256)\n\nlogits = tf.contrib.layers.fully_connected(inputs=fc, num_outputs= labels_vecs.shape[1], activation_fn=None) # output layer logits\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels_, name=None)# cross entropy loss\ncost = tf.reduce_mean(cross_entropy)\n\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)# training optimizer\n\n# Operations for validation/test accuracy\npredicted = tf.nn.softmax(logits)\ncorrect_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))",
"Batches!\nHere is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.",
"def get_batches(x, y, n_batches=10):\n \"\"\" Return a generator that yields batches from arrays x and y. \"\"\"\n batch_size = len(x)//n_batches\n \n for ii in range(0, n_batches*batch_size, batch_size):\n # If we're not on the last batch, grab data with size batch_size\n if ii != (n_batches-1)*batch_size:\n X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size] \n # On the last batch, grab the rest of the data\n else:\n X, Y = x[ii:], y[ii:]\n # I love generators\n yield X, Y",
"Training\nHere, we'll train the network.\n\nExercise: So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the get_batches function I wrote before to get your batches like for x, y in get_batches(train_x, train_y). Or write your own!",
"epochs = 10\nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n \n # TODO: Your training code here\n for i in range(epochs):\n iteration = 0\n for x, y in get_batches(train_x, train_y):\n loss, _ = sess.run([cost, optimizer], feed_dict={inputs_: x, labels_: y})\n acc = accuracy.eval(feed_dict={inputs_: val_x, labels_: val_y})\n print('Epoch {}/Iteration {}: Loss = {:.4f}, Validation Accuracy = {:.2f}'.format(i + 1, iteration + 1, loss, acc)) \n iteration = iteration + 1\n saver.save(sess, \"checkpoints/flowers.ckpt\")",
"Testing\nBelow you see the test accuracy. You can also see the predictions returned for images.",
"with tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: test_x,\n labels_: test_y}\n test_acc = sess.run(accuracy, feed_dict=feed)\n print(\"Test accuracy: {:.4f}\".format(test_acc))\n\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage import imread",
"Below, feel free to choose images and see how the trained classifier predicts the flowers in them.",
"test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg'\ntest_img = imread(test_img_path)\nplt.imshow(test_img)\n\n# Run this cell if you don't have a vgg graph built\nif 'vgg' in globals():\n print('\"vgg\" object already exists. Will not create again.')\nelse:\n #create vgg\n with tf.Session() as sess:\n input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])\n vgg = vgg16.Vgg16()\n vgg.build(inputs_)\n\nwith tf.Session() as sess:\n img = utils.load_image(test_img_path)\n img = img.reshape((1, 224, 224, 3))\n\n feed_dict = {inputs_: img}\n code = sess.run(vgg.relu6, feed_dict=feed_dict)\n \nsaver = tf.train.Saver()\nwith tf.Session() as sess:\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\n \n feed = {inputs_: code}\n prediction = sess.run(predicted, feed_dict=feed).squeeze()\n\nplt.imshow(test_img)\n\nplt.barh(np.arange(5), prediction)\n_ = plt.yticks(np.arange(5), lb.classes_)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
bhermanmit/openmc
|
docs/source/examples/mg-mode-part-iii.ipynb
|
mit
|
[
"This Notebook illustrates the use of the the more advanced features of OpenMC's multi-group mode and the openmc.mgxs.Library class. During this process, this notebook will illustrate the following features:\n\nCalculation of multi-group cross sections for a simplified BWR 8x8 assembly with isotropic and angle-dependent MGXS.\nAutomated creation and storage of MGXS with openmc.mgxs.Library\nFission rate comparison between continuous-energy and the two multi-group OpenMC cases.\n\nTo avoid focusing on unimportant details, the BWR assembly in this notebook is greatly simplified. The descriptions which follow will point out some areas of simplification.\nGenerate Input Files",
"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport openmc\n\n%matplotlib inline",
"We will be running a rodded 8x8 assembly with Gadolinia fuel pins. Let's create all the elemental data we would need for this case.",
"# Instantiate some elements\nelements = {}\nfor elem in ['H', 'O', 'U', 'Zr', 'Gd', 'B', 'C', 'Fe']:\n elements[elem] = openmc.Element(elem)",
"With the elements we defined, we will now create the materials we will use later.\nMaterial Definition Simplifications:\n\nThis model will be run at room temperature so the NNDC ENDF-B/VII.1 data set can be used but the water density will be representative of a module with around 20% voiding. This water density will be non-physically used in all regions of the problem.\nSteel is composed of more than just iron, but we will only treat it as such here.",
"materials = {}\n\n# Fuel\nmaterials['Fuel'] = openmc.Material(name='Fuel')\nmaterials['Fuel'].set_density('g/cm3', 10.32)\nmaterials['Fuel'].add_element(elements['O'], 2)\nmaterials['Fuel'].add_element(elements['U'], 1, enrichment=3.)\n\n# Gadolinia bearing fuel\nmaterials['Gad'] = openmc.Material(name='Gad')\nmaterials['Gad'].set_density('g/cm3', 10.23)\nmaterials['Gad'].add_element(elements['O'], 2)\nmaterials['Gad'].add_element(elements['U'], 1, enrichment=3.)\nmaterials['Gad'].add_element(elements['Gd'], .02)\n\n# Zircaloy\nmaterials['Zirc2'] = openmc.Material(name='Zirc2')\nmaterials['Zirc2'].set_density('g/cm3', 6.55)\nmaterials['Zirc2'].add_element(elements['Zr'], 1)\n\n# Boiling Water\nmaterials['Water'] = openmc.Material(name='Water')\nmaterials['Water'].set_density('g/cm3', 0.6)\nmaterials['Water'].add_element(elements['H'], 2)\nmaterials['Water'].add_element(elements['O'], 1)\n\n# Boron Carbide for the Control Rods\nmaterials['B4C'] = openmc.Material(name='B4C')\nmaterials['B4C'].set_density('g/cm3', 0.7 * 2.52)\nmaterials['B4C'].add_element(elements['B'], 4)\nmaterials['B4C'].add_element(elements['C'], 1)\n\n# Steel \nmaterials['Steel'] = openmc.Material(name='Steel')\nmaterials['Steel'].set_density('g/cm3', 7.75)\nmaterials['Steel'].add_element(elements['Fe'], 1)",
"We can now create a Materials object that can be exported to an actual XML file.",
"# Instantiate a Materials object\nmaterials_file = openmc.Materials(materials.values())\n\n# Export to \"materials.xml\"\nmaterials_file.export_to_xml()",
"Now let's move on to the geometry. The first step is to define some constants which will be used to set our dimensions and then we can start creating the surfaces and regions for the problem, the 8x8 lattice, the rods and the control blade.\nBefore proceeding let's discuss some simplifications made to the problem geometry:\n- To enable the use of an equal-width mesh for running the multi-group calculations, the intra-assembly gap was increased to the same size as the pitch of the 8x8 fuel lattice\n- The can is neglected\n- The pin-in-water geometry for the control blade is ignored and instead the blade is a solid block of B4C\n- Rounded corners are ignored\n- There is no cladding for the water rod",
"# Set constants for the problem and assembly dimensions\nfuel_rad = 0.53213\nclad_rad = 0.61341\nNp = 8\npin_pitch = 1.6256\nlength = float(Np + 2) * pin_pitch\nassembly_width = length - 2. * pin_pitch\nrod_thick = 0.47752 / 2. + 0.14224\nrod_span = 7. * pin_pitch\n\nsurfaces = {}\n\n# Create boundary planes to surround the geometry\nsurfaces['Global x-'] = openmc.XPlane(x0=0., boundary_type='reflective')\nsurfaces['Global x+'] = openmc.XPlane(x0=length, boundary_type='reflective')\nsurfaces['Global y-'] = openmc.YPlane(y0=0., boundary_type='reflective')\nsurfaces['Global y+'] = openmc.YPlane(y0=length, boundary_type='reflective')\n\n# Create cylinders for the fuel and clad\nsurfaces['Fuel Radius'] = openmc.ZCylinder(R=fuel_rad)\nsurfaces['Clad Radius'] = openmc.ZCylinder(R=clad_rad)\n\nsurfaces['Assembly x-'] = openmc.XPlane(x0=pin_pitch)\nsurfaces['Assembly x+'] = openmc.XPlane(x0=length - pin_pitch)\nsurfaces['Assembly y-'] = openmc.YPlane(y0=pin_pitch)\nsurfaces['Assembly y+'] = openmc.YPlane(y0=length - pin_pitch)\n\n# Set surfaces for the control blades\nsurfaces['Top Blade y-'] = openmc.YPlane(y0=length - rod_thick)\nsurfaces['Top Blade x-'] = openmc.XPlane(x0=pin_pitch)\nsurfaces['Top Blade x+'] = openmc.XPlane(x0=rod_span)\nsurfaces['Left Blade x+'] = openmc.XPlane(x0=rod_thick)\nsurfaces['Left Blade y-'] = openmc.YPlane(y0=length - rod_span)\nsurfaces['Left Blade y+'] = openmc.YPlane(y0=9. * pin_pitch)",
"With the surfaces defined, we can now construct regions with these surfaces before we use those to create cells",
"# Set regions for geometry building\nregions = {}\nregions['Global'] = \\\n (+surfaces['Global x-'] & -surfaces['Global x+'] &\n +surfaces['Global y-'] & -surfaces['Global y+'])\nregions['Assembly'] = \\\n (+surfaces['Assembly x-'] & -surfaces['Assembly x+'] &\n +surfaces['Assembly y-'] & -surfaces['Assembly y+'])\nregions['Fuel'] = -surfaces['Fuel Radius']\nregions['Clad'] = +surfaces['Fuel Radius'] & -surfaces['Clad Radius']\nregions['Water'] = +surfaces['Clad Radius']\nregions['Top Blade'] = \\\n (+surfaces['Top Blade y-'] & -surfaces['Global y+']) & \\\n (+surfaces['Top Blade x-'] & -surfaces['Top Blade x+'])\nregions['Top Steel'] = \\\n (+surfaces['Global x-'] & -surfaces['Top Blade x-']) & \\\n (+surfaces['Top Blade y-'] & -surfaces['Global y+'])\nregions['Left Blade'] = \\\n (+surfaces['Left Blade y-'] & -surfaces['Left Blade y+']) & \\\n (+surfaces['Global x-'] & -surfaces['Left Blade x+'])\nregions['Left Steel'] = \\\n (+surfaces['Left Blade y+'] & -surfaces['Top Blade y-']) & \\\n (+surfaces['Global x-'] & -surfaces['Left Blade x+'])\nregions['Corner Blade'] = \\\n regions['Left Steel'] | regions['Top Steel']\nregions['Water Fill'] = \\\n regions['Global'] & ~regions['Assembly'] & \\\n ~regions['Top Blade'] & ~regions['Left Blade'] &\\\n ~regions['Corner Blade']",
"We will begin building the 8x8 assembly. To do that we will have to build the cells and universe for each pin type (fuel, gadolinia-fuel, and water).",
"universes = {}\ncells = {}\n\nfor name, mat, in zip(['Fuel Pin', 'Gd Pin'],\n [materials['Fuel'], materials['Gad']]):\n universes[name] = openmc.Universe(name=name)\n cells[name] = openmc.Cell(name=name)\n cells[name].fill = mat\n cells[name].region = regions['Fuel']\n universes[name].add_cell(cells[name])\n \n cells[name + ' Clad'] = openmc.Cell(name=name + ' Clad')\n cells[name + ' Clad'].fill = materials['Zirc2']\n cells[name + ' Clad'].region = regions['Clad']\n universes[name].add_cell(cells[name + ' Clad'])\n \n cells[name + ' Water'] = openmc.Cell(name=name + ' Water')\n cells[name + ' Water'].fill = materials['Water']\n cells[name + ' Water'].region = regions['Water']\n universes[name].add_cell(cells[name + ' Water'])\n\nuniverses['Hole'] = openmc.Universe(name='Hole')\ncells['Hole'] = openmc.Cell(name='Hole')\ncells['Hole'].fill = materials['Water']\nuniverses['Hole'].add_cell(cells['Hole'])",
"Let's use this pin information to create our 8x8 assembly.",
"# Create fuel assembly Lattice\nuniverses['Assembly'] = openmc.RectLattice(name='Assembly')\nuniverses['Assembly'].pitch = (pin_pitch, pin_pitch)\nuniverses['Assembly'].lower_left = [pin_pitch, pin_pitch]\n\nf = universes['Fuel Pin']\ng = universes['Gd Pin']\nh = universes['Hole']\n\nlattices = [[f, f, f, f, f, f, f, f],\n [f, f, f, f, f, f, f, f],\n [f, f, f, g, f, g, f, f],\n [f, f, g, h, h, f, g, f],\n [f, f, f, h, h, f, f, f],\n [f, f, g, f, f, f, g, f],\n [f, f, f, g, f, g, f, f],\n [f, f, f, f, f, f, f, f]]\n\n# Store the array of lattice universes\nuniverses['Assembly'].universes = lattices\n\ncells['Assembly'] = openmc.Cell(name='Assembly')\ncells['Assembly'].fill = universes['Assembly']\ncells['Assembly'].region = regions['Assembly']",
"So far we have the rods and water within the assembly , but we still need the control blade and the water which fills the rest of the space. We will create those cells now",
"# The top portion of the blade, poisoned with B4C\ncells['Top Blade'] = openmc.Cell(name='Top Blade')\ncells['Top Blade'].fill = materials['B4C']\ncells['Top Blade'].region = regions['Top Blade']\n\n# The left portion of the blade, poisoned with B4C\ncells['Left Blade'] = openmc.Cell(name='Left Blade')\ncells['Left Blade'].fill = materials['B4C']\ncells['Left Blade'].region = regions['Left Blade']\n\n# The top-left corner portion of the blade, with no poison\ncells['Corner Blade'] = openmc.Cell(name='Corner Blade')\ncells['Corner Blade'].fill = materials['Steel']\ncells['Corner Blade'].region = regions['Corner Blade']\n\n# Water surrounding all other cells and our assembly\ncells['Water Fill'] = openmc.Cell(name='Water Fill')\ncells['Water Fill'].fill = materials['Water']\ncells['Water Fill'].region = regions['Water Fill']",
"OpenMC requires that there is a \"root\" universe. Let us create our root universe and fill it with the cells just defined.",
"# Create root Universe\nuniverses['Root'] = openmc.Universe(name='root universe', universe_id=0)\nuniverses['Root'].add_cells([cells['Assembly'], cells['Top Blade'],\n cells['Corner Blade'], cells['Left Blade'],\n cells['Water Fill']])",
"What do you do after you create your model? Check it! We will use the plotting capabilities of the Python API to do this for us.\nWhen doing so, we will coloring by material with fuel being red, gadolinia-fuel as yellow, zirc cladding as a light grey, water as blue, B4C as black and steel as a darker gray.",
"universes['Root'].plot(center=(length / 2., length / 2., 0.),\n pixels=(500, 500), width=(length, length),\n color_by='material',\n colors={materials['Fuel']: (1., 0., 0.),\n materials['Gad']: (1., 1., 0.),\n materials['Zirc2']: (0.5, 0.5, 0.5),\n materials['Water']: (0.0, 0.0, 1.0),\n materials['B4C']: (0.0, 0.0, 0.0),\n materials['Steel']: (0.4, 0.4, 0.4)})",
"Looks pretty good to us!\nWe now must create a geometry that is assigned a root universe and export it to XML.",
"# Create Geometry and set root universe\ngeometry = openmc.Geometry(universes['Root'])\n\n# Export to \"geometry.xml\"\ngeometry.export_to_xml()",
"With the geometry and materials finished, we now just need to define simulation parameters, including how to run the model and what we want to learn from the model (i.e., define the tallies). We will start with our simulation parameters in the next block.\nThis will include setting the run strategy, telling OpenMC not to bother creating a tallies.out file, and limiting the verbosity of our output to just the header and results to not clog up our notebook with results from each batch.",
"# OpenMC simulation parameters\nbatches = 1000\ninactive = 20\nparticles = 1000\n\n# Instantiate a Settings object\nsettings_file = openmc.Settings()\nsettings_file.batches = batches\nsettings_file.inactive = inactive\nsettings_file.particles = particles\nsettings_file.output = {'tallies': False}\nsettings_file.verbosity = 4\n\n# Create an initial uniform spatial source distribution over fissionable zones\nbounds = [pin_pitch, pin_pitch, 10, length - pin_pitch, length - pin_pitch, 10]\nuniform_dist = openmc.stats.Box(bounds[:3], bounds[3:], only_fissionable=True)\nsettings_file.source = openmc.source.Source(space=uniform_dist)\n\n# Export to \"settings.xml\"\nsettings_file.export_to_xml()",
"Create an MGXS Library\nNow we are ready to generate multi-group cross sections! First, let's define a 2-group structure using the built-in EnergyGroups class.",
"# Instantiate a 2-group EnergyGroups object\ngroups = openmc.mgxs.EnergyGroups()\ngroups.group_edges = np.array([0., 0.625, 20.0e6])",
"Next, we will instantiate an openmc.mgxs.Library for the energy groups with our the problem geometry. This library will use the default setting of isotropically-weighting the multi-group cross sections.",
"# Initialize a 2-group Isotropic MGXS Library for OpenMC\niso_mgxs_lib = openmc.mgxs.Library(geometry)\niso_mgxs_lib.energy_groups = groups",
"Now, we must specify to the Library which types of cross sections to compute. OpenMC's multi-group mode can accept isotropic flux-weighted cross sections or angle-dependent cross sections, as well as supporting anisotropic scattering represented by either Legendre polynomials, histogram, or tabular angular distributions. \nJust like before, we will create the following multi-group cross sections needed to run an OpenMC simulation to verify the accuracy of our cross sections: \"total\", \"absorption\", \"nu-fission\", '\"fission\", \"nu-scatter matrix\", \"multiplicity matrix\", and \"chi\".\n\"multiplicity matrix\" is needed to provide OpenMC's multi-group mode with additional information needed to accurately treat scattering multiplication (i.e., (n,xn) reactions)) explicitly.",
"# Specify multi-group cross section types to compute\niso_mgxs_lib.mgxs_types = ['total', 'absorption', 'nu-fission', 'fission',\n 'nu-scatter matrix', 'multiplicity matrix', 'chi']",
"Now we must specify the type of domain over which we would like the Library to compute multi-group cross sections. The domain type corresponds to the type of tally filter to be used in the tallies created to compute multi-group cross sections. At the present time, the Library supports \"material\" \"cell\", \"universe\", and \"mesh\" domain types. \nFor the sake of example we will use a mesh to gather our cross sections. This mesh will be set up so there is one mesh bin for every pin cell.",
"# Instantiate a tally Mesh\nmesh = openmc.Mesh()\nmesh.type = 'regular'\nmesh.dimension = [10, 10]\nmesh.lower_left = [0., 0.]\nmesh.upper_right = [length, length]\n\n# Specify a \"mesh\" domain type for the cross section tally filters\niso_mgxs_lib.domain_type = \"mesh\"\n\n# Specify the mesh over which to compute multi-group cross sections\niso_mgxs_lib.domains = [mesh]",
"Now we will set the scattering treatment that we wish to use.\nIn the mg-mode-part-ii notebook, the cross sections were generated with a typical P3 scattering expansion in mind. Now, however, we will use a more advanced technique: OpenMC will directly provide us a histogram of the change-in-angle (i.e., $\\mu$) distribution.\nWhere as in the mg-mode-part-ii notebook, all that was required was to set the legendre_order attribute of mgxs_lib, here we have only slightly more work: we have to tell the Library that we want to use a histogram distribution (as it is not the default), and then tell it the number of bins.\nFor this problem we will use 11 bins.",
"# Set the scattering format to histogram and then define the number of bins\n\n# Avoid a warning that corrections don't make sense with histogram data\niso_mgxs_lib.correction = None\n# Set the histogram data\niso_mgxs_lib.scatter_format = 'histogram'\niso_mgxs_lib.histogram_bins = 11",
"Ok, we made our isotropic library with histogram-scattering!\nNow why don't we go ahead and create a library to do the same, but with angle-dependent MGXS. That is, we will avoid making the isotropic flux weighting approximation and instead just store a cross section for every polar and azimuthal angle pair.\nTo do this with the Python API and OpenMC, all we have to do is set the number of polar and azimuthal bins. Here we only need to set the number of bins, the API will convert all of angular space into equal-width bins for us.\nSince this problem is symmetric in the z-direction, we only need to concern ourselves with the azimuthal variation here. We will use eight angles.\nOk, we will repeat all the above steps for a new library object, but will also set the number of azimuthal bins at the end.",
"# Let's repeat all of the above for an angular MGXS library so we can gather\n# that in the same continuous-energy calculation\nangle_mgxs_lib = openmc.mgxs.Library(geometry)\nangle_mgxs_lib.energy_groups = groups\nangle_mgxs_lib.mgxs_types = ['total', 'absorption', 'nu-fission', 'fission',\n 'nu-scatter matrix', 'multiplicity matrix', 'chi']\n\nangle_mgxs_lib.domain_type = \"mesh\"\nangle_mgxs_lib.domains = [mesh]\nangle_mgxs_lib.correction = None\nangle_mgxs_lib.scatter_format = 'histogram'\nangle_mgxs_lib.histogram_bins = 11\n\n# Set the angular bins to 8\nangle_mgxs_lib.num_azimuthal = 8",
"Now that our libraries have been setup, let's make sure they contain the types of cross sections which meet the needs of OpenMC's multi-group solver. Note that this step is done automatically when writing the Multi-Group Library file later in the process (as part of the mgxs_lib.write_mg_library()), but it is a good practice to also run this before spending all the time running OpenMC to generate the cross sections.",
"# Check the libraries - if no errors are raised, then the library is satisfactory.\niso_mgxs_lib.check_library_for_openmc_mgxs()\nangle_mgxs_lib.check_library_for_openmc_mgxs()",
"Lastly, we use our two Library objects to construct the tallies needed to compute all of the requested multi-group cross sections in each domain.\nWe expect a warning here telling us that the default Legendre order is not meaningful since we are using histogram scattering.",
"# Construct all tallies needed for the multi-group cross section library\niso_mgxs_lib.build_library()\nangle_mgxs_lib.build_library()",
"The tallies within the libraries can now be exported to a \"tallies.xml\" input file for OpenMC.",
"# Create a \"tallies.xml\" file for the MGXS Library\ntallies_file = openmc.Tallies()\niso_mgxs_lib.add_to_tallies_file(tallies_file, merge=True)\nangle_mgxs_lib.add_to_tallies_file(tallies_file, merge=True)",
"In addition, we instantiate a fission rate mesh tally for eventual comparison of results.",
"# Instantiate tally Filter\nmesh_filter = openmc.MeshFilter(mesh)\n\n# Instantiate the Tally\ntally = openmc.Tally(name='mesh tally')\ntally.filters = [mesh_filter]\ntally.scores = ['fission']\n\n# Add tally to collection\ntallies_file.append(tally, merge=True)\n\n# Export all tallies to a \"tallies.xml\" file\ntallies_file.export_to_xml()",
"Time to run the calculation and get our results!",
"# Run OpenMC\nopenmc.run()",
"To make the files available and not be over-written when running the multi-group calculation, we will now rename the statepoint and summary files.",
"# Move the StatePoint File\nce_spfile = './statepoint_ce.h5'\nos.rename('statepoint.' + str(batches) + '.h5', ce_spfile)\n# Move the Summary file\nce_sumfile = './summary_ce.h5'\nos.rename('summary.h5', ce_sumfile)",
"Tally Data Processing\nOur simulation ran successfully and created statepoint and summary output files. Let's begin by loading the StatePoint file, but not automatically linking the summary file.",
"# Load the statepoint file, but not the summary file, as it is a different filename than expected.\nsp = openmc.StatePoint(ce_spfile, autolink=False)",
"In addition to the statepoint file, our simulation also created a summary file which encapsulates information about the materials and geometry. This is necessary for the openmc.Library to properly process the tally data. We first create a Summary object and link it with the statepoint. Normally this would not need to be performed, but since we have renamed our summary file to avoid conflicts with the Multi-Group calculation's summary file, we will load this in explicitly.",
"su = openmc.Summary(ce_sumfile)\nsp.link_with_summary(su)",
"The statepoint is now ready to be analyzed. To create our libraries we simply have to load the tallies from the statepoint into each Library and our MGXS objects will compute the cross sections for us under-the-hood.",
"# Initialize MGXS Library with OpenMC statepoint data\niso_mgxs_lib.load_from_statepoint(sp)\nangle_mgxs_lib.load_from_statepoint(sp)",
"The next step will be to prepare the input for OpenMC to use our newly created multi-group data.\nIsotropic Multi-Group OpenMC Calculation\nWe will now use the Library to produce the isotropic multi-group cross section data set for use by the OpenMC multi-group solver. \nIf the model to be run in multi-group mode is the same as the continuous-energy mode, the openmc.mgxs.Library class has the ability to directly create the multi-group geometry, materials, and multi-group library for us. \nNote that this feature is only useful if the MG model is intended to replicate the CE geometry - it is not useful if the CE library is not the same geometry (like it would be for generating MGXS from a generic spectral region).\nThis method creates and assigns the materials automatically, including creating a geometry which is equivalent to our mesh cells for which the cross sections were derived.",
"# Allow the API to create our Library, materials, and geometry file\niso_mgxs_file, materials_file, geometry_file = iso_mgxs_lib.create_mg_mode()\n\n# Tell the materials file what we want to call the multi-group library\nmaterials_file.cross_sections = 'mgxs.h5'\n\n# Write our newly-created files to disk\niso_mgxs_file.export_to_hdf5('mgxs.h5')\nmaterials_file.export_to_xml()\ngeometry_file.export_to_xml()",
"Next, we can make the changes we need to the settings file.\nThese changes are limited to telling OpenMC to run a multi-group calculation and provide the location of our multi-group cross section file.",
"# Set the energy mode\nsettings_file.energy_mode = 'multi-group'\n\n# Export to \"settings.xml\"\nsettings_file.export_to_xml()",
"Let's clear up the tallies file so it doesn't include all the extra tallies for re-generating a multi-group library",
"# Create a \"tallies.xml\" file for the MGXS Library\ntallies_file = openmc.Tallies()\n\n# Add our fission rate mesh tally\ntallies_file.add_tally(tally)\n\n# Export to \"tallies.xml\"\ntallies_file.export_to_xml()",
"Before running the calculation let's look at our meshed model. It might not be interesting, but let's take a look anyways.",
"geometry_file.root_universe.plot(center=(length / 2., length / 2., 0.),\n pixels=(300, 300), width=(length, length),\n color_by='material')",
"So, we see a 10x10 grid with a different color for every material, sounds good!\nAt this point, the problem is set up and we can run the multi-group calculation.",
"# Execute the Isotropic MG OpenMC Run\nopenmc.run()",
"Before we go the angle-dependent case, let's save the StatePoint and Summary files so they don't get over-written",
"# Move the StatePoint File\niso_mg_spfile = './statepoint_mg_iso.h5'\nos.rename('statepoint.' + str(batches) + '.h5', iso_mg_spfile)\n# Move the Summary file\niso_mg_sumfile = './summary_mg_iso.h5'\nos.rename('summary.h5', iso_mg_sumfile)",
"Angle-Dependent Multi-Group OpenMC Calculation\nLet's now run the calculation with the angle-dependent multi-group cross sections. This process will be the exact same as above, except this time we will use the angle-dependent Library as our starting point.\nWe do not need to re-write the materials, geometry, or tallies file to disk since they are the same as for the isotropic case.",
"# Let's repeat for the angle-dependent case\nangle_mgxs_lib.load_from_statepoint(sp)\nangle_mgxs_file, materials_file, geometry_file = angle_mgxs_lib.create_mg_mode()\nangle_mgxs_file.export_to_hdf5()",
"At this point, the problem is set up and we can run the multi-group calculation.",
"# Execute the angle-dependent OpenMC Run\nopenmc.run()",
"Results Comparison\nIn this section we will compare the eigenvalues and fission rate distributions of the continuous-energy, isotropic multi-group and angle-dependent multi-group cases.\nWe will begin by loading the multi-group statepoint files, first the isotropic, then angle-dependent. The angle-dependent was not renamed, so we can autolink its summary.",
"# Load the isotropic statepoint file\niso_mgsp = openmc.StatePoint(iso_mg_spfile, autolink=False)\niso_mgsum = openmc.Summary(iso_mg_sumfile)\niso_mgsp.link_with_summary(iso_mgsum)\n\n# Load the angle-dependent statepoint file\nangle_mgsp = openmc.StatePoint('statepoint.' + str(batches) + '.h5')",
"Eigenvalue Comparison\nNext, we can load the eigenvalues for comparison and do that comparison",
"ce_keff = sp.k_combined\niso_mg_keff = iso_mgsp.k_combined\nangle_mg_keff = angle_mgsp.k_combined\n\n# Find eigenvalue bias\niso_bias = 1.0E5 * (ce_keff[0] - iso_mg_keff[0])\nangle_bias = 1.0E5 * (ce_keff[0] - angle_mg_keff[0])",
"Let's compare the eigenvalues in units of pcm",
"print('Isotropic to CE Bias [pcm]: {0:1.1f}'.format(iso_bias))\nprint('Angle to CE Bias [pcm]: {0:1.1f}'.format(angle_bias))",
"We see a large reduction in error by switching to the usage of angle-dependent multi-group cross sections! \nOf course, this rodded and partially voided BWR problem was chosen specifically to exacerbate the angular variation of the reaction rates (and thus cross sections). Such improvements should not be expected in every case, especially if localized absorbers are not present.\nIt is important to note that both eigenvalues can be improved by the application of finer geometric or energetic discretizations, but this shows that the angle discretization may be a factor for consideration.\nFission Rate Distribution Comparison\nNext we will visualize the mesh tally results obtained from our three cases.\nThis will be performed by first obtaining the one-group fission rate tally information from our state point files. After we have this information we will re-shape the data to match the original mesh laydown. We will then normalize, and finally create side-by-side plots of all.",
"sp_files = [sp, iso_mgsp, angle_mgsp]\ntitles = ['Continuous-Energy', 'Isotropic Multi-Group',\n 'Angle-Dependent Multi-Group']\nfiss_rates = []\nfig = plt.figure(figsize=(12, 6))\nfor i, (case, title) in enumerate(zip(sp_files, titles)):\n # Get our mesh tally information\n mesh_tally = case.get_tally(name='mesh tally')\n fiss_rates.append(mesh_tally.get_values(scores=['fission']))\n \n # Reshape the array\n fiss_rates[-1].shape = mesh.dimension\n \n # Normalize the fission rates\n fiss_rates[-1] /= np.mean(fiss_rates[-1])\n \n # Set 0s to NaNs so they show as white\n fiss_rates[-1][fiss_rates[-1] == 0.] = np.nan\n\n fig = plt.subplot(1, len(titles), i + 1)\n # Plot only the fueled regions\n plt.imshow(fiss_rates[-1][1:-1, 1:-1], cmap='jet', origin='lower',\n vmin=0.4, vmax=4.)\n plt.title(title + '\\nFission Rates')",
"With this colormap, dark blue is the lowest power and dark red is the highest power.\nWe see general agreement between the fission rate distributions, but it looks like there may be less of a gradient near the rods in the continuous-energy and angle-dependent MGXS cases than in the isotropic MGXS case. \nTo better see the differences, let's plot ratios of the fission powers for our two multi-group cases compared to the continuous-energy case t",
"# Calculate and plot the ratios of MG to CE for each of the 2 MG cases\nratios = []\nfig, axes = plt.subplots(figsize=(12, 6), nrows=1, ncols=2)\nfor i, (case, title, axis) in enumerate(zip(sp_files[1:], titles[1:], axes.flat)):\n # Get our ratio relative to the CE (in fiss_ratios[0])\n ratios.append(np.divide(fiss_rates[i + 1], fiss_rates[0]))\n \n # Plot only the fueled regions\n im = axis.imshow(ratios[-1][1:-1, 1:-1], cmap='bwr', origin='lower',\n vmin = 0.9, vmax = 1.1)\n axis.set_title(title + '\\nFission Rates Relative\\nto Continuous-Energy')\n \n# Add a color bar\nfig.subplots_adjust(right=0.8)\ncbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])\nfig.colorbar(im, cax=cbar_ax)",
"With this ratio its clear that the errors are significantly worse in the isotropic case. These errors are conveniently located right where the most anisotropy is espected: by the control blades and by the Gd-bearing pins!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
NYUDataBootcamp/Projects
|
MBA_S17/Pittman-Renewable+Energy (2).ipynb
|
mit
|
[
"Where Should Renewable Energy Go Next?\nMay 5, 2017\nWritten by Katharine Pittman\nContact: klp398@nyu.edu\nOverview\nSince 2011, the advocation and utilization of renewable energy has gained exponential momentum as the effect of climate change and global warming has become increasingly acknowledged. However, state legislation is the primary factor as to where renewable energy is implemented. Large energy companies that provide renewable energy options, such as SunPower and NRG, only provide these services in certain states. At the moment these states include: CA, CO, GA, MA, MD, MN, NJ, NM, PA, RI, and VT. These states will be referred to as the \"Key 11 States\" throughout this project.\nThe object of this project is to investigate which states should be targeted next based on various avenues.",
"import sys # system module \nimport pandas as pd # data package\nimport matplotlib.pyplot as plt # graphics module \nimport datetime as dt # date and time module\nimport numpy as np # foundation for Pandas \n\n%matplotlib inline\n\n# check versions\nprint('Python version:', sys.version)\nprint('Pandas version: ', pd.__version__)\nprint('Today: ', dt.date.today())",
"Selecting and Accessing Data Set #1\nOne of my main priorities for selecting a data set was that it contained all of the information I needed for that particular part of my project, and I wouldn't have to \"piece together\" different files to create a graph.\nThe U.S. Energy Information Administration (https://www.eia.gov/) has an innumerable amount of data, some files more detailed, while others are more holistic in nature. \nFor the first part of my project, I am looking at the electricity prices for each state in 2015 for the Residential sector. From this I will identify the Top 5 Most Expensive States in terms of electricity prices that are NOT part of the Key 11 States, and then look at the average price of electricity per state from 2000 to 2015 for these Top 5 States.",
"url = 'https://www.eia.gov/electricity/data/state/avgprice_annual.xlsx' # importing the data\nprice = pd.read_excel(url) \nprice.head() # looking at the beginning of the data\n\nprice.tail() # looking at the end of the data",
"Cleaning Up Data Set #1\nAfter looking at the head of the data, I don't need the first row and I only need the first four columns, since I am only interested in prices for Residential. After looking at the tail of the data, I don't need any of the data prior to 2000, since I am focusing on 2000-2015.\nAfter looking at the data from the url in full, I also am only interested in the Full-Service Provider prices for each state, so I will pull only this data from the dataset.",
"url = 'https://www.eia.gov/electricity/data/state/avgprice_annual.xlsx' # importing our data\nprice = pd.read_excel(url, \n skiprows=1, # skipping the first row\n usecols=range(4), # only interested in the first four columns\n skipfooter=1126) # skipping data for years 1990-1999\n\nsector = ['Full-Service Providers'] # specifying what sector I want\nprice.isin(sector)\ncleaned_price = price[price['Industry Sector Category'].isin(sector)]\nprint(cleaned_price)\n\n# Inspecting the cleaned up data\n\nprint('Dimensions: ', cleaned_price.shape, '\\n') \nprint('Column labels: ', cleaned_price.columns, '\\n')\nprint('Row labels: ', cleaned_price.index, '\\n')\nprint('Type: ', cleaned_price.dtypes, '\\n') # '\\n' adds a blank line and makes the output easier to read",
"Price of Electricity for Each State in 2015\nThe five states with the highest electricity prices as of 2015 - that are not part of the Key 11 States - are HI, CT, AK, NH, and NY.",
"year = [2015] # specifying the year I want\ncleaned_price.isin(year)\nprice2015 = cleaned_price[cleaned_price['Year'].isin(year)]\nprice2015_sorted = price2015.sort_values('Residential') # sorts the prices in ascending order\nprint(price2015_sorted)",
"Price of Electricity from 2000-2015 for HI, CT, AK, NH, and NY",
"# Showing the prices of electricity from 2000-2015 for just one state as a reference\n\nstate = ['HI'] # specifying what state I want\ncleaned_price.isin(state)\nHI_price = cleaned_price[cleaned_price['State'].isin(state)].iloc[::-1] # reverses the order \n # of the rows\nprint(HI_price) # showing how the data looks\n\n# Showing a graph for just one state as a reference\n\nplt.figure(figsize = (16,7))\nplt.plot(HI_price['Year'], HI_price['Residential'], color = 'red')\nplt.suptitle('Price of Electricity in HI by Year', fontsize=18)\nplt.xlabel('Year', fontsize=12)\nplt.ylabel('Residential', fontsize=12)\n\n\n# Pulling the price by year data for the additional four states I'm interested in \n\nstate = ['CT'] # specifying what state I want\ncleaned_price.isin(state)\nCT_price = cleaned_price[cleaned_price['State'].isin(state)].iloc[::-1] # reverses the order\n\nstate = ['AK'] # specifying what state I want\ncleaned_price.isin(state)\nAK_price = cleaned_price[cleaned_price['State'].isin(state)].iloc[::-1] # reverses the order\n\nstate = ['NH'] # specifying what state I want\ncleaned_price.isin(state)\nNH_price = cleaned_price[cleaned_price['State'].isin(state)].iloc[::-1] # reverses the order\n\nstate = ['NY'] # specifying what state I want\ncleaned_price.isin(state)\nNY_price = cleaned_price[cleaned_price['State'].isin(state)].iloc[::-1] # reverses the order\n\n# Plotting a line graph with data from all five states I'm interested in\n\nplt.figure(figsize = (17,10))\n\nplt.plot(HI_price['Year'], HI_price['Residential'], color = 'red', label = \"Hawaii\")\nplt.plot(CT_price['Year'], CT_price['Residential'], color = 'blue', label = \"Connecticut\")\nplt.plot(AK_price['Year'], AK_price['Residential'], color = 'green', label = \"Arkansas\")\nplt.plot(NH_price['Year'], NH_price['Residential'], color = 'purple', label = \"New Hampshire\")\nplt.plot(NY_price['Year'], NY_price['Residential'], color = 'cyan', label = \"New York\")\n\nplt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)\n\nplt.suptitle('Price of Electricity in HI, CT, AK, NH, & NY by Year', fontsize=18)\nplt.xlabel('Year', fontsize=12)\nplt.ylabel('Residential', fontsize=12)\n\nplt.show()",
"Selecting and Accessing Data Set #2\nBesides cost, another avenue to investigate which states should consider adopting renewable energy is coal consumption. Data Set #2 will be looking at the Consumption of Coal for Electricity Generation by State in 2014 and 2015 for All Sectors. The Top 5 Coal Consuming states will be identified and graphically represented.",
"url2 = 'https://www.eia.gov/electricity/annual/xls/epa_05_09.xlsx' # importing our data\ncoal_consumption = pd.read_excel(url2) \ncoal_consumption.head() # looking at the beginning of the data\n\ncoal_consumption.tail() # looking at the end of the data",
"Cleaning Up Data Set #2\nData Set #2 lists the amount of coal consumed (in thousand tons) for electricity generation for each state, however it also divides the states into regions and provides the region total of coal consumed. As I am only focusing on the indvidiual states (and D.C.), I will have to specify that I just want the data for these rows.",
"url2 = 'https://www.eia.gov/electricity/annual/xls/epa_05_09.xlsx' # importing our data\ncoal_consumption = pd.read_excel(url2, \n skiprows=4,\n usecols=range(3),\n skipfooter=2)\n\ncoal_consumption.columns = ['State', '2015', '2014'] \nprint(coal_consumption)\n\n# Inspecting the cleaned up data\n\nprint('Dimensions: ', coal_consumption.shape, '\\n') \nprint('Column labels: ', coal_consumption.columns, '\\n')\nprint('Row labels: ', coal_consumption.index, '\\n')\nprint('Type: ', coal_consumption.dtypes, '\\n') # '\\n' adds a blank line and makes the output easier to read",
"Coal Consumption\nThe five states with the highest coal comsumtipn in 2015 - that are not part of the Key 11 States - are TX, IL, IN, MO, and KY.",
"# I don't want data for the different regions, so I'm specifying what rows I do want data for\n\nstate_list = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', \n 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', \n 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', \n 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', \n 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', \n 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', \n 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', \n 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming', \n 'District of Columbia']\n\ncoal_consumption.isin(state_list)\nstate_coal_consumption = coal_consumption[coal_consumption['State'].isin(state_list)].sort_values('2015')\n# sorts the values in ascending order, so I can pick out which states have the highest consumption \n\nprint(state_coal_consumption)\n\n# Here I can use nlargest to graph the top 5 states, but this is only because one of the Key 11 States \n# is not included in the Top 5.\n\nmy_plot = state_coal_consumption.nlargest(5, '2015').plot(x = 'State', kind='bar')",
"Selecting and Accessing Data Set #3\nThe final avenue I will take into addressing which states renewable energy should take over next may actually be the most important - emissions. This data set specifies the Carbon Dioxide, Sulfur Dioxide, and Nitrogen Oxides emitted from energy consumption at conventional power plants and combined-heat-and-power plants for 2014 and 2015. One must keep in mind that identified states from this section are likely similiar to states that consumed a vast amount of coal.",
"url3 = 'https://www.eia.gov/electricity/annual/xls/epa_09_05.xlsx' # importing our data\nemissions = pd.read_excel(url3) \nemissions.head() # looking at the beginning of the data\n\nemissions.tail() # looking at the end of the data",
"Cleaning Up Data Set #3\nFor Data Set #3 I will be looking at the 5 Highest Emitting States for each of the three categories (CO2, SO2, NOx) for Total emissions between 2014 and 2015.",
"url3 = 'https://www.eia.gov/electricity/annual/xls/epa_09_05.xlsx' # importing our data\n\nemissions = pd.read_excel(url3,\n skiprows=4,\n skipfooter=2)\n\nemissions.columns = ['State', 'CO2 2015', 'CO2 2014', 'SO2 2015', 'SO2 2014', 'NOx 2015', 'NOx 2014'] \n # renaming the columns\n\nemissions['CO2 Total'] = emissions['CO2 2015'] + emissions['CO2 2014'] # adding CO2 emissions for 2014 + 2015\nemissions['SO2 Total'] = emissions['SO2 2015'] + emissions['SO2 2014'] # adding SO2 emissions for 2014 + 2015\nemissions['NOx Total'] = emissions['NOx 2015'] + emissions['NOx 2014'] # adding NOx emissions for 2014 + 2015\n\ntotals = ['State','CO2 Total', 'SO2 Total', 'NOx Total']\nsmall_emissions = state_emissions[totals] # creating a new dataframe with just the total emissions\n\nsmall_emissions = small_emissions.set_index(['State']) # setting the index to the State name\nprint(small_emissions) # checking to make sure it looks good\n\n# Inspecting the cleaned up data\n\nprint('Dimensions: ', small_emissions.shape, '\\n') \nprint('Column labels: ', small_emissions.columns, '\\n')\nprint('Row labels: ', small_emissions.index, '\\n')\nprint('Type: ', small_emissions.dtypes, '\\n') # '\\n' adds a blank line and makes the output easier to read",
"CO2 Emissions\nBelow are the sorted values for CO2 Emissions. You can see that the 5 Highest Emitting States - not including any of the Key 11 States - are TX, FL, IN, OH, and IL.",
"print(small_emissions.sort_values('CO2 Total'))",
"SO2 Emissions\nBelow are the sorted values for SO2 Emissions. You can see that the 5 Highest Emitting States - not including any of the Key 11 States - are TX, OH, IN, IL, and KY.",
"print(small_emissions.sort_values('SO2 Total'))",
"NOx Emissions\nBelow are the sorted values for NOx Emissions. You can see that the 5 Highest Emitting States - not including any of the Key 11 States - are TX, IN, OH, FL, and KY.",
"print(small_emissions.sort_values('NOx Total'))",
"Emission Graphs\nBecause CO2 emission levels are tremednenously larger than SO2 or NOx levels it does not make sense to plot the three different emissions all on the same graph. Therefore, I will plot CO2 levels separately and then on a different graph plot SO2 and NOx together.\nCO2 Graph",
"CO2_states = ['Texas', 'Florida','Indiana','Ohio','Illinois']\nCO2_small = small_emissions.T[CO2_states] # creating a new dataframe with just the total emissions and\n # translating the dataframe so the State names will be in the Index\n \nprint(CO2_small.T['CO2 Total']) # only want to show the CO2 Totals because the SO2 and NOx are below\n\nCO2_plot = CO2_small.T['CO2 Total'].plot(kind='bar') # translating it again so I can specify \n # that I only want 'CO2 Total' in the plot",
"SO2 & NOx Graph\nThe 5 Highest Emitting States for SO2 and NOx have 4 overlapping states, so I will be plotting the combined highest 5 states, which makes a total of 6 states.",
"SO2_NOx_states = ['Texas','Indiana','Ohio','Florida','Kentucky','Illinois']\nintermediate = small_emissions.T[SO2_NOx_states] # creating a new dataframe with just the total emissions and\n # translating the dataframe so the State names will be in the Index\n\nSO2_NOx = ['SO2 Total', 'NOx Total'] # specifying that I just want these two columns for my new df, not CO2\nfinal_SO2_NOx = intermediate.T[SO2_NOx] #creating a new dataframe with just the SO2 Total and NOx Total and\n # translating again so the SO2 Total and NOx Total will be in the Index\nprint(final_SO2_NOx)\n\nfinal_SO2_NOx.plot(kind='bar')",
"Conculsions\nThe three avenues I investigated to see which states renewable energy should expand to next included 1) Electricity Cost, 2) Coal Consumption, and 3) CO2, SO2, and NOx Emissions.\nNot including the 11 Key States....\n* The 5 Most Expensive States for Electricity are: HI, CT, AK, NH, and NY.\n* The 5 Highest Coal Consuming States for Electricity are: TX, IN, MO, KY, and IL.\n* The 5 Highest CO2 Emitting States are: TX, IN, OH, FL, and IL.\n* The 5 Highest SO2 Emitting States are: TX, IN, OH, KY, and IL.\n* The 5 Highest NOx Emitting States are: TX, IN, OH, KY, and FL.\nUnfortunately, there was not a single state that appeared in all 5 categories. It seems the states with the highest consumptions and emissions have lower electricity prices.\nBased on this data, the next states that I believe would have the most profound effect and should consider implementing renewable energy projects are Texas and Indiana."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
CI-WATER/gsshapy
|
notebooks/Create GSSHA Model.ipynb
|
bsd-3-clause
|
[
"Installation Instructions\nDownload and install miniconda: https://conda.io/miniconda.html\nMake sure you are using the conda-forge channel:\nbash\n$ conda config --add channels conda-forge\n$ conda update --yes conda python\nInstall gsshapy:\nbash\n$ conda create -n gssha python=2\n$ source activate gssha\n(gssha)$ conda install --yes gsshapy jupyter",
"from datetime import datetime, timedelta\nimport os\ntry:\n from urllib import urlretrieve\nexcept ImportError:\n from urllib.request import urlretrieve\n\nfrom gsshapy.modeling import GSSHAModel",
"Parameters to change for the run:",
"base_dir = os.getcwd()\ngssha_model_name = 'philippines_example'\nland_use_grid_id = 'glcf'\ngssha_model_directory = os.path.join(base_dir, gssha_model_name)\n# make the directory for the output\ntry:\n os.mkdir(gssha_model_directory)\nexcept OSError:\n pass",
"Download files:",
"base_boundary_url = ('https://github.com/CI-WATER/gsshapy/'\n 'raw/master/tests/grid_standard/'\n 'philippines/')\nbase_shape_filename = 'philippines_5070115700'\n\n\n# retrieve the shapefile\nshapefile_name = base_shape_filename+'.shp'\nboundary_shapefile = urlretrieve(base_boundary_url+shapefile_name,\n filename=os.path.join(gssha_model_directory, shapefile_name))[0]\nfor file_extension in ['.shx', '.prj', '.dbf']:\n file_name = base_shape_filename+file_extension\n urlretrieve(base_boundary_url+file_name, \n filename=os.path.join(gssha_model_directory, file_name))\n \n# retrieve the DEM\nelevation_file_path = urlretrieve(base_boundary_url + 'gmted_elevation.tif', \n filename=os.path.join(gssha_model_directory, 'gmted_elevation.tif'))[0]\n# retrieve the land use grid\nland_cover_url = ('https://github.com/CI-WATER/gsshapy/'\n 'raw/master/tests/grid_standard/'\n 'land_cover/LC_hd_global_2012.tif')\nland_use_file_path = urlretrieve(land_cover_url, \n filename=os.path.join(gssha_model_directory, 'LC_hd_global_2012.tif'))[0]",
"Use the data to generate a GSSHA model:",
"# generate GSSHA model files\nmodel = GSSHAModel(project_name=gssha_model_name,\n project_directory=gssha_model_directory,\n mask_shapefile=boundary_shapefile,\n elevation_grid_path=elevation_file_path,\n land_use_grid=land_use_file_path,\n land_use_grid_id=land_use_grid_id,\n out_hydrograph_write_frequency=1,\n load_rasters_to_db=False)\n\n# add card for max depth\nmodel.project_manager.setCard('FLOOD_GRID',\n '{0}.fgd'.format(gssha_model_name),\n add_quotes=True)\n# TODO: Add depth grids to simulation\n# MAP_FREQ, DEPTH\n\n# add event for simulation\nmodel.set_event(simulation_start=datetime.utcnow(),\n simulation_duration=timedelta(seconds=2*60),\n rain_intensity=24,\n rain_duration=timedelta(seconds=1*60),\n )\nmodel.write()",
"More information about options can be found here: http://gsshapy.readthedocs.io/en/latest/api/modeling/modeling.html"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
yl565/statsmodels
|
examples/notebooks/discrete_choice_example.ipynb
|
bsd-3-clause
|
[
"Discrete Choice Models\nFair's Affair data\nA survey of women only was conducted in 1974 by Redbook asking about extramarital affairs.",
"%matplotlib inline\n\nfrom __future__ import print_function\nimport numpy as np\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom statsmodels.formula.api import logit, probit, poisson, ols\n\nprint(sm.datasets.fair.SOURCE)\n\nprint( sm.datasets.fair.NOTE)\n\ndta = sm.datasets.fair.load_pandas().data\n\ndta['affair'] = (dta['affairs'] > 0).astype(float)\nprint(dta.head(10))\n\nprint(dta.describe())\n\naffair_mod = logit(\"affair ~ occupation + educ + occupation_husb\" \n \"+ rate_marriage + age + yrs_married + children\"\n \" + religious\", dta).fit()\n\nprint(affair_mod.summary())",
"How well are we predicting?",
"affair_mod.pred_table()",
"The coefficients of the discrete choice model do not tell us much. What we're after is marginal effects.",
"mfx = affair_mod.get_margeff()\nprint(mfx.summary())\n\nrespondent1000 = dta.ix[1000]\nprint(respondent1000)\n\nresp = dict(zip(range(1,9), respondent1000[[\"occupation\", \"educ\", \n \"occupation_husb\", \"rate_marriage\", \n \"age\", \"yrs_married\", \"children\", \n \"religious\"]].tolist()))\nresp.update({0 : 1})\nprint(resp)\n\nmfx = affair_mod.get_margeff(atexog=resp)\nprint(mfx.summary())\n\naffair_mod.predict(respondent1000)\n\naffair_mod.fittedvalues[1000]\n\naffair_mod.model.cdf(affair_mod.fittedvalues[1000])",
"The \"correct\" model here is likely the Tobit model. We have an work in progress branch \"tobit-model\" on github, if anyone is interested in censored regression models.\nExercise: Logit vs Probit",
"fig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111)\nsupport = np.linspace(-6, 6, 1000)\nax.plot(support, stats.logistic.cdf(support), 'r-', label='Logistic')\nax.plot(support, stats.norm.cdf(support), label='Probit')\nax.legend();\n\nfig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111)\nsupport = np.linspace(-6, 6, 1000)\nax.plot(support, stats.logistic.pdf(support), 'r-', label='Logistic')\nax.plot(support, stats.norm.pdf(support), label='Probit')\nax.legend();",
"Compare the estimates of the Logit Fair model above to a Probit model. Does the prediction table look better? Much difference in marginal effects?\nGenarlized Linear Model Example",
"print(sm.datasets.star98.SOURCE)\n\nprint(sm.datasets.star98.DESCRLONG)\n\nprint(sm.datasets.star98.NOTE)\n\ndta = sm.datasets.star98.load_pandas().data\nprint(dta.columns)\n\nprint(dta[['NABOVE', 'NBELOW', 'LOWINC', 'PERASIAN', 'PERBLACK', 'PERHISP', 'PERMINTE']].head(10))\n\nprint(dta[['AVYRSEXP', 'AVSALK', 'PERSPENK', 'PTRATIO', 'PCTAF', 'PCTCHRT', 'PCTYRRND']].head(10))\n\nformula = 'NABOVE + NBELOW ~ LOWINC + PERASIAN + PERBLACK + PERHISP + PCTCHRT '\nformula += '+ PCTYRRND + PERMINTE*AVYRSEXP*AVSALK + PERSPENK*PTRATIO*PCTAF'",
"Aside: Binomial distribution\nToss a six-sided die 5 times, what's the probability of exactly 2 fours?",
"stats.binom(5, 1./6).pmf(2)\n\nfrom scipy.misc import comb\ncomb(5,2) * (1/6.)**2 * (5/6.)**3\n\nfrom statsmodels.formula.api import glm\nglm_mod = glm(formula, dta, family=sm.families.Binomial()).fit()\n\nprint(glm_mod.summary())",
"The number of trials",
"glm_mod.model.data.orig_endog.sum(1)\n\nglm_mod.fittedvalues * glm_mod.model.data.orig_endog.sum(1)",
"First differences: We hold all explanatory variables constant at their means and manipulate the percentage of low income households to assess its impact\non the response variables:",
"exog = glm_mod.model.data.orig_exog # get the dataframe\n\nmeans25 = exog.mean()\nprint(means25)\n\nmeans25['LOWINC'] = exog['LOWINC'].quantile(.25)\nprint(means25)\n\nmeans75 = exog.mean()\nmeans75['LOWINC'] = exog['LOWINC'].quantile(.75)\nprint(means75)\n\nresp25 = glm_mod.predict(means25)\nresp75 = glm_mod.predict(means75)\ndiff = resp75 - resp25",
"The interquartile first difference for the percentage of low income households in a school district is:",
"print(\"%2.4f%%\" % (diff[0]*100))\n\nnobs = glm_mod.nobs\ny = glm_mod.model.endog\nyhat = glm_mod.mu\n\nfrom statsmodels.graphics.api import abline_plot\nfig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111, ylabel='Observed Values', xlabel='Fitted Values')\nax.scatter(yhat, y)\ny_vs_yhat = sm.OLS(y, sm.add_constant(yhat, prepend=True)).fit()\nfig = abline_plot(model_results=y_vs_yhat, ax=ax)",
"Plot fitted values vs Pearson residuals\nPearson residuals are defined to be \n$$\\frac{(y - \\mu)}{\\sqrt{(var(\\mu))}}$$\nwhere var is typically determined by the family. E.g., binomial variance is $np(1 - p)$",
"fig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111, title='Residual Dependence Plot', xlabel='Fitted Values',\n ylabel='Pearson Residuals')\nax.scatter(yhat, stats.zscore(glm_mod.resid_pearson))\nax.axis('tight')\nax.plot([0.0, 1.0],[0.0, 0.0], 'k-');",
"Histogram of standardized deviance residuals with Kernel Density Estimate overlayed\nThe definition of the deviance residuals depends on the family. For the Binomial distribution this is \n$$r_{dev} = sign\\left(Y-\\mu\\right)*\\sqrt{2n(Y\\log\\frac{Y}{\\mu}+(1-Y)\\log\\frac{(1-Y)}{(1-\\mu)}}$$\nThey can be used to detect ill-fitting covariates",
"resid = glm_mod.resid_deviance\nresid_std = stats.zscore(resid) \nkde_resid = sm.nonparametric.KDEUnivariate(resid_std)\nkde_resid.fit()\n\nfig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111, title=\"Standardized Deviance Residuals\")\nax.hist(resid_std, bins=25, normed=True);\nax.plot(kde_resid.support, kde_resid.density, 'r');",
"QQ-plot of deviance residuals",
"fig = plt.figure(figsize=(12,8))\nax = fig.add_subplot(111)\nfig = sm.graphics.qqplot(resid, line='r', ax=ax)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
bdestombe/flopy-1
|
examples/Notebooks/flopy3_LoadSWRBinaryData.ipynb
|
bsd-3-clause
|
[
"FloPy\nPlotting SWR Process Results\nThis notebook demonstrates the use of the SwrObs and SwrStage, SwrBudget, SwrFlow, and SwrExchange, SwrStructure, classes to read binary SWR Process observation, stage, budget, reach to reach flows, reach-aquifer exchange, and structure files. It demonstrates these capabilities by loading these binary file types and showing examples of plotting SWR Process data. An example showing how the simulated water surface profile at a selected time along a selection of reaches can be plotted is also presented.",
"%matplotlib inline\nfrom IPython.display import Image\nimport os\nimport sys\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport flopy\n\nprint(sys.version)\nprint('numpy version: {}'.format(np.__version__))\nprint('matplotlib version: {}'.format(mpl.__version__))\nprint('flopy version: {}'.format(flopy.__version__))\n\n#Set the paths\ndatapth = os.path.join('..', 'data', 'swr_test')\n\n# SWR Process binary files \nfiles = ('SWR004.obs', 'SWR004.vel', 'SWR004.str', 'SWR004.stg', 'SWR004.flow')",
"Load SWR Process observations\nCreate an instance of the SwrObs class and load the observation data.",
"sobj = flopy.utils.SwrObs(os.path.join(datapth, files[0]))\n\nts = sobj.get_data()",
"Plot the data from the binary SWR Process observation file",
"fig = plt.figure(figsize=(6, 12))\nax1 = fig.add_subplot(3, 1, 1)\nax1.semilogx(ts['totim']/3600., -ts['OBS1'], label='OBS1')\nax1.semilogx(ts['totim']/3600., -ts['OBS2'], label='OBS2')\nax1.semilogx(ts['totim']/3600., -ts['OBS9'], label='OBS3')\nax1.set_ylabel('Flow, in cubic meters per second')\nax1.legend()\n\nax = fig.add_subplot(3, 1, 2, sharex=ax1)\nax.semilogx(ts['totim']/3600., -ts['OBS4'], label='OBS4')\nax.semilogx(ts['totim']/3600., -ts['OBS5'], label='OBS5')\nax.set_ylabel('Flow, in cubic meters per second')\nax.legend()\n\nax = fig.add_subplot(3, 1, 3, sharex=ax1)\nax.semilogx(ts['totim']/3600., ts['OBS6'], label='OBS6')\nax.semilogx(ts['totim']/3600., ts['OBS7'], label='OBS7')\nax.set_xlim(1, 100)\nax.set_ylabel('Stage, in meters')\nax.set_xlabel('Time, in hours')\nax.legend();",
"Load the same data from the individual binary SWR Process files\nLoad discharge data from the flow file. The flow file contains the simulated flow between connected reaches for each connection in the model.",
"sobj = flopy.utils.SwrFlow(os.path.join(datapth, files[1]))\ntimes = np.array(sobj.get_times())/3600.\nobs1 = sobj.get_ts(irec=1, iconn=0)\nobs2 = sobj.get_ts(irec=14, iconn=13)\nobs4 = sobj.get_ts(irec=4, iconn=3)\nobs5 = sobj.get_ts(irec=5, iconn=4)",
"Load discharge data from the structure file. The structure file contains the simulated structure flow for each reach with a structure.",
"sobj = flopy.utils.SwrStructure(os.path.join(datapth, files[2]))\nobs3 = sobj.get_ts(irec=17, istr=0)",
"Load stage data from the stage file. The flow file contains the simulated stage for each reach in the model.",
"sobj = flopy.utils.SwrStage(os.path.join(datapth, files[3]))\nobs6 = sobj.get_ts(irec=13)",
"Load budget data from the budget file. The budget file contains the simulated budget for each reach group in the model. The budget file also contains the stage data for each reach group. In this case the number of reach groups equals the number of reaches in the model.",
"sobj = flopy.utils.SwrBudget(os.path.join(datapth, files[4]))\nobs7 = sobj.get_ts(irec=17)",
"Plot the data loaded from the individual binary SWR Process files.\nNote that the plots are identical to the plots generated from the binary SWR observation data.",
"fig = plt.figure(figsize=(6, 12))\nax1 = fig.add_subplot(3, 1, 1)\nax1.semilogx(times, obs1['flow'], label='OBS1')\nax1.semilogx(times, obs2['flow'], label='OBS2')\nax1.semilogx(times, -obs3['strflow'], label='OBS3')\nax1.set_ylabel('Flow, in cubic meters per second')\nax1.legend()\n\nax = fig.add_subplot(3, 1, 2, sharex=ax1)\nax.semilogx(times, obs4['flow'], label='OBS4')\nax.semilogx(times, obs5['flow'], label='OBS5')\nax.set_ylabel('Flow, in cubic meters per second')\nax.legend()\n\nax = fig.add_subplot(3, 1, 3, sharex=ax1)\nax.semilogx(times, obs6['stage'], label='OBS6')\nax.semilogx(times, obs7['stage'], label='OBS7')\nax.set_xlim(1, 100)\nax.set_ylabel('Stage, in meters')\nax.set_xlabel('Time, in hours')\nax.legend();",
"Plot simulated water surface profiles\nSimulated water surface profiles can be created using the ModelCrossSection class. \nSeveral things that we need in addition to the stage data include reach lengths and bottom elevations. We load these data from an existing file.",
"sd = np.genfromtxt(os.path.join(datapth, 'SWR004.dis.ref'), names=True)",
"The contents of the file are shown in the cell below.",
"fc = open(os.path.join(datapth, 'SWR004.dis.ref')).readlines()\nfc",
"Create an instance of the SwrStage class for SWR Process stage data.",
"sobj = flopy.utils.SwrStage(os.path.join(datapth, files[3]))",
"Create a selection condition (iprof) that can be used to extract data for the reaches of interest (reaches 0, 1, and 8 through 17). Use this selection condition to extract reach lengths (from sd['RLEN']) and the bottom elevation (from sd['BELEV']) for the reaches of interest. The selection condition will also be used to extract the stage data for reaches of interest.",
"iprof = sd['IRCH'] > 0\niprof[2:8] = False\ndx = np.extract(iprof, sd['RLEN'])\nbelev = np.extract(iprof, sd['BELEV'])",
"Create a fake model instance so that the ModelCrossSection class can be used.",
"ml = flopy.modflow.Modflow()\ndis = flopy.modflow.ModflowDis(ml, nrow=1, ncol=dx.shape[0], delr=dx, top=4.5, botm=belev.reshape(1,1,12))",
"Create an array with the x position at the downstream end of each reach, which will be used to color the plots below each reach.",
"x = np.cumsum(dx)",
"Plot simulated water surface profiles for 8 times.",
"fig = plt.figure(figsize=(12, 12))\nfor idx, v in enumerate([19, 29, 34, 39, 44, 49, 54, 59]):\n ax = fig.add_subplot(4, 2, idx+1)\n s = sobj.get_data(idx=v)\n stage = np.extract(iprof, s['stage'])\n xs = flopy.plot.ModelCrossSection(model=ml, line={'Row': 0})\n xs.plot_fill_between(stage.reshape(1,1,12), colors=['none', 'blue'], ax=ax, edgecolors='none')\n linecollection = xs.plot_grid(ax=ax, zorder=10)\n ax.fill_between(np.append(0., x), y1=np.append(belev[0], belev), y2=-0.5, \n facecolor='0.5', edgecolor='none', step='pre')\n ax.set_title('{} hours'.format(times[v]))\n ax.set_ylim(-0.5, 4.5)",
"Summary\nThis notebook demonstrates flopy functionality for reading binary output generated by the SWR Process. Binary files that can be read include observations, stages, budgets, flow, reach-aquifer exchanges, and structure data. The binary stage data can also be used to create water-surface profiles. \nHope this gets you started!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
tclaudioe/Scientific-Computing
|
SC1/Bonus_Finding_2_Chebyshev_Points_Graphically.ipynb
|
bsd-3-clause
|
[
"<center>\n <h1> ILI285 - Computación Científica I / INF285 - Computación Científica </h1>\n <h2> Finding 2 Chebyshev points graphycally </h2>\n <h2> <a href=\"#acknowledgements\"> [S]cientific [C]omputing [T]eam </a> </h2>\n <h2> Version: 1.02</h2>\n</center>\nTable of Contents\n\nFinding 2 Chebyshev points\nPython Modules and Functions\nAcknowledgements",
"import numpy as np\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interact\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\nimport matplotlib as mpl\nmpl.rcParams['font.size'] = 14\nmpl.rcParams['axes.labelsize'] = 20\nmpl.rcParams['xtick.labelsize'] = 14\nmpl.rcParams['ytick.labelsize'] = 14\n%matplotlib inline",
"<div id='cheb' />\n\nFinding 2 Chebyshev points\nWe compute them so we can compare them later.",
"n=2\ni=1\ntheta1=(2*i-1)*np.pi/(2*n)\ni=2\ntheta2=(2*i-1)*np.pi/(2*n)\nc1=np.cos(theta1)\nc2=np.cos(theta2)",
"Recall that the Chebyshev points are points that minimize the following expression:\n$$\n\\displaystyle{\\omega(x_1,x_2,\\dots,x_n)=\\max_{x} |(x-x_1)\\,(x-x_2)\\,\\cdots\\,(x-x_n)|}.\n$$\nThis comes from the Interpolation Error Formula (I hope you remember it, otherwise see the textbook or the classnotes!). \nIn this notebook, we will find the $\\min$ for 2 points, \nthis means:\n$$\n[x_1,x_2]= \\displaystyle{\\mathop{\\mathrm{argmin}}{x_1,x_2\\in [-1,1]}} \\,\\omega(x_1,x_2)=\\displaystyle{\\mathop{\\mathrm{argmin}}{x_1,x_2\\in [-1,1]}}\\,\n\\max_{x\\in [-1,1]} |(x-x_1)\\,(x-x_2)|.\n$$\nFor doing this, we first need to build $\\omega(x_1,x_2)$,",
"N=50\nx=np.linspace(-1,1,N)\nw = lambda x1,x2: np.max(np.abs((x-x1)*(x-x2)))\nwv=np.vectorize(w)",
"Now we need to evaluate $\\omega(x_1,x_2)$ over the domain $\\Omega=[0,1]^2$.",
"[X,Y]=np.meshgrid(x,x)\nW=wv(X,Y)",
"With this data, we can now plot the function $\\omega(x_1,x_2)$ on $\\Omega$. \nThe minimun value of is shown by the color at the bottom of the colorbar.\nBy visual inspection, we see that we have two mins. \nThey are located at the bottom right and top left.",
"plt.figure(figsize=(8,8))\n#plt.contourf(X, Y, W,100, cmap=cm.hsv, antialiased=False)\nplt.contourf(X, Y, W,100, cmap=cm.nipy_spectral, antialiased=False)\nplt.xlabel(r'$x_1$')\nplt.ylabel(r'$x_2$')\nplt.colorbar()\nplt.show()",
"Finally, we have included the min in the plot and we see the agreement between the min of $\\omega(x_1,x_2)$ and the Chebyshev points found.",
"plt.figure(figsize=(8,8))\nplt.contourf(X, Y, W,100, cmap=cm.nipy_spectral, antialiased=False)\nplt.plot(c1,c2,'k.',markersize=16)\nplt.plot(c2,c1,'k.',markersize=16)\nplt.colorbar()\nplt.xlabel(r'$x_1$') \nplt.ylabel(r'$x_2$')\nplt.show()",
"<div id='py' />\n\nPython Modules and Functions\nAn interesting module:\nhttps://docs.scipy.org/doc/numpy-1.13.0/reference/routines.polynomials.chebyshev.html\n<div id='acknowledgements' />\n\nAcknowledgements\n\nMaterial created by professor Claudio Torres (ctorres@inf.utfsm.cl). DI UTFSM. May 2018.\nUpdate June 2020 - v1.02 - C.Torres : Fixing formatting issues."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
sdpython/ensae_teaching_cs
|
_doc/notebooks/td1a/td1a_correction_session5.ipynb
|
mit
|
[
"1A.2 - Classes, méthodes, attributs, opérateurs et carré magique (correction)\nCorrection.",
"from jyquickhelper import add_notebook_menu\nadd_notebook_menu()",
"Exercice 1 : carré magique",
"class CarreMagique :\n def __init__(self, coef) :\n self.mat = [ [ coef[i+j*3] for i in range(3) ] for j in range(3) ]\n def __str__(self) :\n return \"\\n\".join ( [ \",\".join( [ str(n) for n in row ] ) for row in self.mat ] )\n def __add__ (self, carre) :\n coef = []\n for i in range(3) :\n for j in range(3) :\n coef.append ( self.mat[i][j] + carre.mat[i][j])\n return CarreMagique(coef)\n\nc = CarreMagique ( [ 1,3,4, 2,6,9, 8,7,5 ] )\nprint (c)\nprint(\"--\")\nprint (c + c)",
"Exercice 2 : à faire à trois, carré magique (suite)",
"class CarreMagique :\n def __init__(self, coef) :\n self.mat = [ [ coef[i+j*3] for i in range(3) ] for j in range(3) ]\n def __str__(self) :\n return \"\\n\".join ( [ \",\".join( str(n) for n in row ) for row in self.mat ] )\n def __add__ (self, carre) :\n coef = []\n for i in range(3) :\n for j in range(3) :\n coef.append ( self.mat[i][j] + carre.mat[i][j])\n return CarreMagique(coef)\n\n def somme_ligne_colonne_diagonale(self):\n tout = [ sum ( ligne ) for ligne in self.mat ] + \\\n [ sum ( self.mat[i][j] for i in range(3) ) for j in range(3) ] + \\\n [ sum ( self.mat[i][i] for i in range(3) ) ] + \\\n [ sum ( self.mat[2-i][i] for i in range(3) ) ] \n return tout\n \n def coefficient_unique(self): \n d = { }\n for ligne in self.mat :\n for c in ligne :\n d [c] = d.get(c,0) + 1\n return len(d) == 9\n \n def est_magique(self):\n unique = self.coefficient_unique()\n if not unique : return False\n somme = self.somme_ligne_colonne_diagonale()\n return min(somme) == max(somme) \n \nc = CarreMagique ( [ 1,1,1, 1,1,1, 1,1,1 ] )\nprint (c.est_magique())\nc = CarreMagique ( [ 1,4,8, 5,2,6, 7,9,3 ] )\nprint (c.est_magique())\nc = CarreMagique ( [ 1,6,8, 7,5,3, 2,4,9 ] )\nprint (c.est_magique())\nc = CarreMagique ( [ 2,7,6, 9,5,1, 4,3,8 ] )\nprint (c.est_magique())",
"Exercice 3 : trouver tous les carrés magiques\nLa première version est fastidieuse à écrire mais simple à comprendre.",
"def tous_les_carre_naif() :\n res = []\n for a1 in range(9) :\n for a2 in range(9) :\n for a3 in range(9) :\n for b1 in range(9) :\n for b2 in range(9) :\n for b3 in range(9) :\n for c1 in range(9) :\n for c2 in range(9) :\n for c3 in range(9) :\n carre = CarreMagique( [a1,a2,a3, b1,b2,b3, c1,c2,c3 ])\n if carre.est_magique() :\n res.append (carre)\n print (carre)\n return res\n\n# tous_les_carre_naif() (c'est très long)",
"La seconde version n'est pas plus rapide mais elle contient moins de boucles.",
"def tous_les_carre_naif2() :\n # on choisit l'ensemble de tous les tableaux de 9 chiffres compris entre 1 et 9\n coef = [ 1 ] * 9\n res = [ ]\n while coef [0] < 10 :\n carre = CarreMagique(coef)\n if carre.est_magique() :\n res.append (carre)\n print (carre)\n coef[-1] += 1\n if coef[-1] >= 10 :\n i = len(coef)-1\n while coef[i] >= 10 and i > 0 :\n coef[i] = 1\n coef[i-1] += 1\n i -= 1\n \n# tous_les_carre_naif2() (c'est très long) ",
"La troisième version utilise le fait que les chiffres d'un carré magique sont tous différents. Il suffit de regarder seulement tous les permutations. La variable stop_after permet de se limiter seulement aux premiers.",
"def tous_les_carres_permutation( permut = None, pos = 0, stop_after = 3):\n if pos == 9 :\n carre = CarreMagique (permut) \n if carre.est_magique() :\n print (carre)\n print ()\n return [ carre ]\n else :\n return []\n else :\n res = [ ]\n if permut == None :\n permut = [ i+1 for i in range(9) ]\n for i in range (pos,9) :\n # on permute les éléments i et pos\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n\n res += tous_les_carres_permutation(permut, pos+1)\n \n if stop_after > 0 and len(res) >= stop_after :\n return res\n \n # on effectue la permutation inverse\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n return res\n \nres = tous_les_carres_permutation()\nprint (\"nombre de carrés\", len(res))",
"Le langage Python propose une fonction qui parcourt toutes les permutations d'un ensemble : itertools.permutation. Cela réduit de beaucoup la longueur du programme.",
"import itertools\ndef tous_les_carres_permutation( stop_after = 3):\n res = [ ]\n firstn = list(range(1,10))\n for permut in itertools.permutations(firstn) :\n carre = CarreMagique (permut) \n if carre.est_magique() :\n res.append( carre )\n if stop_after >= 0 :\n print (carre)\n print ()\n if len(res) >= stop_after :\n return res\n return res\n \nres = tous_les_carres_permutation()\nprint (\"nombre de carrés\", len(res))",
"Exercice 4 : faire plus rapide\nEst-il possible d'aller plus vite que de parcourir l'ensemble des permutations ? La réponse est oui. En parcourant les permutations, la fonction qui teste si les chiffres sont uniques est devenue inutile. Pour vérifier qu'on va plus vite, on peut mesurer le temps que met la fonction pour trouver tous les carrés :",
"import time\nd = time.perf_counter()\nres = tous_les_carres_permutation(-1)\nd = time.perf_counter() - d\nprint (\"nombre de carrés\", len(res), \" en \", d, \"seconds\")",
"Pour aller plus vite, il faut utiliser la contrainte des sommes. Comment ? Lorsqu'on permute les nombres, on peut simplement vérifier que les deux premières lignes ont la même somme. L'utilisation de cette contrainte nous permet de d'aller 10 fois plus vite et d'obtenir le résultat en moins d'une seconde. L'inconvénient est que l'optimisation fonctionne parce qu'on ne parcourt pas toutes les permutations. On ne peut plus utiliser la fonction itertools.permutation.",
"def tous_les_carres_permutation_ligne12_meme_somme( permut = None, pos = 0):\n if pos == 9 :\n carre = CarreMagique (permut) \n if carre.est_magique() :\n #print (carre)\n #print ()\n return [ carre ]\n else :\n return []\n else :\n if pos >= 6 : # ajout\n if sum ( permut[:3]) != sum(permut[3:6]) : # ajout\n return [ ] # ajout\n \n res = [ ]\n if permut == None :\n permut = [ i+1 for i in range(9) ]\n for i in range (pos,9) :\n # on permute les éléments i et pos\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n\n res += tous_les_carres_permutation_ligne12_meme_somme(permut, pos+1) # changé\n \n # on effectue la permutation inverse\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n return res\n \nimport time\nd = time.perf_counter()\nres = tous_les_carres_permutation_ligne12_meme_somme()\nd = time.perf_counter() - d\nprint (\"nombre de carrés\", len(res), \" en \", d) ",
"Programme complet",
"class CarreMagique :\n def __init__(self, coef) :\n self.mat = [ [ coef[i+j*3] for i in range(3) ] for j in range(3) ]\n def __str__(self) :\n return \"\\n\".join ( [ \",\".join( [ str(n) for n in row ] ) for row in self.mat ] )\n def __add__ (self, carre) :\n coef = []\n for i in range(3) :\n for j in range(3) :\n coef.append ( self.mat[i][j] + carre.mat[i][j])\n return CarreMagique(coef)\n \n def somme_ligne_colonne_diagonale(self):\n tout = [ sum ( ligne ) for ligne in self.mat ] + \\\n [ sum ( self.mat[i][j] for i in range(3) ) for j in range(3) ] + \\\n [ sum ( self.mat[i][i] for i in range(3) ) ] + \\\n [ sum ( self.mat[2-i][i] for i in range(3) ) ] \n return tout\n \n def coefficient_unique(self): \n d = { }\n for ligne in self.mat :\n for c in ligne :\n d [c] = d.get(c,0) + 1\n return len(d) == 9\n \n def est_magique(self):\n unique = self.coefficient_unique()\n if not unique : return False\n somme = self.somme_ligne_colonne_diagonale()\n return min(somme) == max(somme) \n \ndef tous_les_carres_permutation_ligne12_meme_somme( permut = None, pos = 0):\n if pos == 9 :\n carre = CarreMagique (permut) \n if carre.est_magique() :\n #print (carre)\n #print ()\n return [ carre ]\n else :\n return []\n else :\n if pos >= 6 : # ajout\n if sum ( permut[:3]) != sum(permut[3:6]) : # ajout\n return [ ] # ajout\n \n res = [ ]\n if permut == None :\n permut = [ i+1 for i in range(9) ]\n for i in range (pos,9) :\n # on permute les éléments i et pos\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n\n res += tous_les_carres_permutation_ligne12_meme_somme(permut, pos+1) # changé\n \n # on effectue la permutation inverse\n a = permut[i]\n permut[i] = permut[pos]\n permut[pos] = a\n return res\n \nimport time\nd = time.perf_counter()\nres = tous_les_carres_permutation_ligne12_meme_somme()\nd = time.perf_counter() - d\nprint (\"nombre de carrés\", len(res), \" en \", d)",
"On peut faire encore plus rapide en utilisant les contraintes pour inférer les autres coefficients (solution venant d'un élève) :",
"def tous_les_carres():\n for a1 in range(1,10):\n for a2 in range(1,10):\n for a3 in range(1,10):\n for b1 in range(1,10):\n somme = a1 + a2 + a3\n c1 = somme - a1 - b1\n b2 = somme - a3 - c1\n b3 = somme - b1 - b2\n c2 = somme - a2 - b2\n c3 = somme - c1 - c2\n M = CarreMagique([a1,a2,a3,b1,b2,b3,c1,c2,c3])\n if M.est_magique() and 0 < b2 < 10 and 0 < b3 < 10 and 0 < c1 < 10 and 0 < c2 < 10 and 0 < c3 < 10 :\n #print(M)\n #print(\"---------------\") \n pass\n%timeit tous_les_carres()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
dpiparo/swanExamples
|
notebooks/LHCb_OpenData_Spark.ipynb
|
lgpl-2.1
|
[
"Apache Spark and High Energy Physics Data Analysis\nAn example using LHCb open data\nThis notebook is an example of how to use Spark to perform a simple analysis using high energy physics data from a LHC experiment.\nThe exercises, figures and data are from original work developed and published by the LHCb collaboration as part of the opendata and outreach efforts (see credits below).\nPrerequisites - This work is intended to be accessible to an audience with some familiarity with data analysis in Python and an interest in particle Physics at undergraduate level.\nTechnology - The focus of this notebook is as much on tools and techniques as it is on physics: Apache Spark is used for reading and analyzing high energy physics (HEP) data using Python with Pandas and Jupyter notebooks.\nCredits:\n * The original text of this notebook, including all exercises, analysis, explanations and data have been developed by the LHCb collaboration and are authored and shared by the LHCb collaboration in their opendata project at:\n * https://github.com/lhcb/opendata-project\n * http://www.hep.manchester.ac.uk/u/parkes/LHCbAntimatterProjectWeb/LHCb_Matter_Antimatter_Asymmetries/Homepage.html \n * https://cds.cern.ch/record/1994172?ln=en \n\n\nThe library for reading physics data stored using the popular ROOT format has been developed by DIANA-HEP and CMS Big Data project. See also the code repository at: \n\nhttps://github.com/diana-hep/spark-root\n\n\n\nThe Spark code in this notebook has been developed in the context of the CERN Hadoop and Spark service. \nContact email: Luca.Canali@cern.ch\n\n\nIntroduction and setup of the lab environemnt\nThere are a few different ways that you can to run Python and Spark in a notebook environment.\nThe following are instructions to set up a lab environemnt on a low-end system (small VM or laptop).\nIf you have already set up Spark on a local machine or a cluster, you can just start the Jupyter notebook. \nNote for CERN users: if you are using CERN SWAN service (hosted Jupyter notebooks) to run this, you can move on to the next cell.\nInstructions to get started with Jupyter notebooks and PySpark on a standalone system:\n\nSetup the Python environment, for example download and install Anaconda https://www.continuum.io/downloads\n\nversion used/tested for this notebook: Anaconda 4.4.0 for Python 2.7\n\n\nSet up Spark\n\nsimply run pip install pyspark \nas an alternative download Spark from http://spark.apache.org/downloads.html\n\nnote: Spark version used for testing this notebook: Spark 2.2.0 and 2.1.1\n\n\nStart the Jupyter notebook\npython\njupyter-notebook --ip=`hostname` --no-browser\n\n\nPoint your browser to the URL as prompted \n\nOpen this notebook",
"# This starts the Spark Session\n# Note: Shift-Enter can be used to run Jupyter cells\n# These instructions rely on internet access to download the spark-root package from Maven Central\n\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName(\"LHCb Open Data with Spark\") \\\n .config(\"spark.jars.packages\", \"org.diana-hep:spark-root_2.11:0.1.11\") \\\n .getOrCreate()\n\n# Test that Spark SQL works\n\nsql = spark.sql\nsql(\"select 'Hello World!'\").show()",
"Get the data: download from CERN open data portal\nDownload the data for the exercises from the CERN opendata portal:\nMore info on the CERN opedata initiative at http://opendata.cern.ch/about \nNote for CERN users using CERN SWAN (hosted notbooks): you don't need to download data (see next cell)\nSimulation data (~2 MB) - you need this file only for the first part of the notebook: working on simulation data \nhttp://opendata.cern.ch/eos/opendata/lhcb/AntimatterMatters2017/data/PhaseSpaceSimulation.root \nMeasurement data (~1 GB) - you will need these files for the second part of the notebook: working on real data \nhttp://opendata.cern.ch/eos/opendata/lhcb/AntimatterMatters2017/data/B2HHH_MagnetDown.root \nhttp://opendata.cern.ch/eos/opendata/lhcb/AntimatterMatters2017/data/B2HHH_MagnetUp.root \nNotes: \nOn Linux you can use wget to download the files\nIf you run Spark on a standalone system or VM, simply put the data in the local filesystem.\nIf you are using Spark on a cluster, you should put the data in a cluster filesystem, for example HDFS.",
"# Edit this with the path to the data, with a trainling \"/\" \n# see above at \"get the data\" for details on how to download\n\n# CERN SWAN users can find data already in EOS\ndata_directory = \"/eos/opendata/lhcb/AntimatterMatters2017/data/\"\n\n# Uncomment and edit the path for locally downloaded data\n# data_directory = \"/home/luca/misc/opendata-project/data/\"\n",
"Measuring Matter Antimatter Asymmetries at the Large Hadron Collider\n\nGetting Started\nNote: the original text of this exercise in the form relased by LHCb can be found at https://github.com/lhcb/opendata-project\n\n<b> Welcome to the first guided LHCb Open Data Portal project! </b>\n<div align=\"justify\">Here you will be able to analyse data taken by the Large Hadron Collider (LHC) at CERN. The aim of this study is for you to be able to search for differences in the behaviour of matter and [antimatter](https://en.wikipedia.org/wiki/Antimatter). This project will enable you to carry out your own data analysis at a level similar to that of CERN research. This project does not require a detailed knowledge of particle physics. It is most suitable for people with a scientific and mathematical background equivalent to that required for applying for university entrance in a science, technology engineering or mathematics discipline. Some previous familiarity with computer programming would also be advantageous. Additional theoretical information or programming knowledge you might need is provided as the project progresses.</div>\n\nBefore you start, you might find it helpful to find out more about matter antimatter asymmetries, what we hope to learn by studying them, and how we can detect them with experiments such as the LHCb experiment at CERN.\nHere are some details that relate directly to this project:\n - What is the particle physics focus of this experiment? and what will I study in this project?\n - How does the LHCb detector record the data?\nReading simulation data\nIn order to get started and check the first code that you will be writing works correctly it is best to start by analysing simulated data rather than real data from the LHC. The real data contains not only the type of events that you wish to analyse, known as the 'signal', but also events that can fake these, known as 'background'. The real data measurements are also limited by the resolution of the detector. The simplified simulation data provided here contains only the signal events and provides the results that would be obtained for a perfect detector.\nIMPORTANT: For every code box with code already in it, like the one below you must click in and press shift+enter to run the code.\nIf the In [x]: to the left of a codebox changes to In [*]: that means the code in that box is currently running",
"# Boilerplate\nfrom __future__ import print_function\nfrom __future__ import division\n\n%pylab inline\npylab.rcParams['figure.figsize'] = (12.0, 8.0)",
"If you want help with coding there is in addition to the example code, some hints within each section and a function reference list \nThis is a reference to Spark DataFrames and SQL",
"# Let us now load the simulated data\n# as detailed above you should have downloaded locally the simulation data from \n# http://opendata.cern.ch/eos/opendata/lhcb/upload/AntimatterMatters2017/data/PhaseSpaceSimulation.root\n\n# This reads the data into a Spark DataFrame using the spark-root connector\nsim_data_df = spark.read.format(\"org.dianahep.sparkroot\").load(data_directory + \"PhaseSpaceSimulation.root\")\n\n# This registers the Spark DataFrame as a temporary view and will allow the use of SQL, used later in the notebook\nsim_data_df.createOrReplaceTempView(\"sim_data\") \n\nsim_data_df.cache() # it is a small dataset (~2 MB) so we can afford to cache it\nsim_data_df.count()",
"<div align=\"justify\">Now that you can access the data, you can use a number of functions which can help you analyse it. You can find these functions in the libraries at the top of the page. Try to make a table of some of the information within your data file so that you can get a feel of the typical values for data in the set. Understanding the range of values for different variables will help with plotting graphs.</div>\n\nThe data contains information about 'events' that were observed in the detector. An event refers to the particles produced when an interaction took place when two proton are collided at the LHC. The data you have includes information about particles observed in the detector after each collision. If you think of the data as a table, each row of the table is the results from a different collision. The columns of the table are different quantities measured about the particles produced in the collision. \nWe are interested in analysing the decays of particles called B<sup>+</sup> or B<sup>-</sup> mesons decaying into three other mesons called kaons (K<sup>+</sup> or K<sup>-</sup>). The events you have been given are those in which this process may have occurred. The detector has been used to reconstruct tracks that may have come from the kaons. You are given the measured momenta, charge, and likelihood of the tracks being kaons. You are given information for three tracks in each event, the ones that could be the three kaons that a B<sup>+</sup> or B<sup>-</sup> meson has decayed into. The following information is available about each event: information list",
"# Display the first 10 rows in the sim_data_df Spark DataFrame\n\nsim_data_df.limit(10).toPandas() # use pandas only for visualization\n\n# Print the schema of the simulation data\n\nsim_data_df.printSchema() # the schema of the root file",
"Invariant mass reconstruction\nAims:\n\nPlot a histogram of the momentum of one of the kaon candidates\nCalculate the energy of each of the kaon candidates\nPlot the invariant masses of the B<sup>+</sup> or B<sup>-</sup> mesons___\n\nPlotting a feature:\nYou can plot any feature of the data in a histogram. Choose any suitable binning that allows you to observed the distribution of the variable clearly. Try making a histogram for the first kaon candidate's momentum x-component (H1_PX):",
"# Plot a histogram of the distribution of the H1_PX variable, using Pandas\n\n# This is a basic solution that moves all the data from the Spark DataFrame \n# into a Python Pandas DataFrame. It's OK for small sata sets, but it has scalability issues\n\nh1px_data = sim_data_df.select(\"H1_PX\").toPandas() # select H1_PX data and moves it to Pandas\nh1px_data.plot.hist(bins=31, range=[-150000, 150000], title=\"Histogram - distribution of H1_PX, simulation data\")\nxlabel('H1_PX (MeV/c)')\nylabel('Count');\n\n# This example computes and plots a histogram of the H1_PX data, similarly to the previous cell\n# The notable difference is that Spark SQL is used to compute the aggregations and only the final result\n# is returned and transformed into a Pandas DataFrame, just for plotting. \n# This vesion can scale on a cluster for large datasets, while the previous version requires to fetch all data into Pandas\n\nhistogram_h1px_df = sql(\"\"\"\n select round(H1_PX/10000,0) * 10000 as bin, count(1) as count\n from sim_data \n group by round(H1_PX/10000,0) order by 1\n \"\"\")\nhistogram_h1px_pandas = histogram_h1px_df.toPandas()\nhistogram_h1px_pandas.plot.bar(x='bin', y='count', title=\"Histogram - distribution of H1_PX, simulation data,\")\nxlabel('H1_PX (MeV/c)')\nylabel('Count');\n\n# This is the same query used for the histogram displayed above. \n# It is here just to show the numeric values of each of the bins\n\nsql(\"\"\"\n select round(H1_PX/10000,0) * 10000 as bin, count(1) as count\n from sim_data \n group by round(H1_PX/10000,0) order by 1\n \"\"\").show(50)\n",
"Momentum is a vector quantity, it has x,y, and z components. Try calculating the magnitude of the momentum of the first kaon candidate and plotting a histogram of this, you'll need the H1_PX, H1_PY and H1_PZ variables.",
"# Selects the vector components of the momentum of H1 and computes the magnitude of the vector\n# Only consider data where H1_PROBK = 1.0 (note,this could be relaxed to H1_PROBK >= <some threshold value>)\n\np_tot = sql(\"\"\"\n select H1_PX, H1_PY, H1_PZ, round(sqrt(H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ),2) H1_PTOT \n from sim_data \n where H1_PROBK = 1.0\"\"\")\n\np_tot.show(5) # displays the first 5 rows of the result\n\n# calculate a variable for the magnitude of the momentum of the first kaon \n# plot a histogram of this variable\n\nh1ptot_data_plot = p_tot.select(\"H1_PTOT\").toPandas().plot.hist(bins=31, range=[0, 550000]) \nxlabel('H1_PTOT (MeV/c)')\nylabel('Count');",
"Hints\nHistogram plotting - You can use the hist() function. The parameters bins(n) and range(x,y) allow youto plot n bins over the range x to y.\nVector Magnitude The square magnitude of a magnitude of a vector is given by the sum of the square of its of its components in the x,y and z directions: $p^2 = p_x^2+p_y^2+p_z^2$, where $p$ is the magnitude of the momentum, and $p_x,p_y,p_z$ are the components of the momentum in the X,Y, and Z directions.\nEnergy and mass\nEinstein's theory of special relativity relates Energy, mass and momentum. We have measured the momentum of the kaon candidates in the detector, and have just plotted one of the components of the momentum of the kaon, and the magnitude of the momentum. The invariant mass of the kaon is well known and you can look this up. We wish to determine the energy of the kaons. \nHere is a brief guide to the energy-momentum relation of special relativity. Further information can be found on wikipedia pages on Invariant Mass and the Energy-momentum relation.\nNow, calculate the energy of the first kaon candidate using:\n<center> $E^2 = p^2 + m^2$ </center>",
"# Computes the Energy of the kaon candidates using the formula of special relativity\n# that is including the magnitude of the momentum and invariant mass\n\nkcharged_mass = 493.677\n\nEnergy_H1 = spark.sql(\"\"\"\n select round(sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ),2) H1_Energy\n from sim_data \n where H1_PROBK = 1.0\n \"\"\".format(kcharged_mass*kcharged_mass))\n\nEnergy_H1.show(5)\n\n# Plots a histogram of the energy of the first kaon candidate\n\nEnergy_H1_data_plot = Energy_H1.toPandas().plot.hist(bins=31, range=[0, 550000]) \nxlabel('H1_Energy (MeV)')\nylabel('Count');",
"Hints\nEnergy calculation - Use the magnitude of momentum variable you calculated above and the known invariant mass of the kaon to work out the energy of the first hadron. Calculate the energy squared, and then the energy and plot this.\nKaon mass - you can find the kaon mass on wikipedia or in physics textbooks. There is also a reference used by particle physicists: all our knowledge of the properties of the particles are collected together by the particle data group here.\nCalculate the momenta and energies of the second and third kaon candidates also.",
"# calculate variables for the energy of the other two kaons\n\nkcharged_mass = 493.677\n\nEnergy_H2 = spark.sql(\"\"\"\n select sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) H2_Energy\n from sim_data \n where H2_PROBK = 1.0\n \"\"\".format(kcharged_mass*kcharged_mass))\n\nEnergy_H3 = spark.sql(\"\"\"\n select sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) H3_Energy\n from sim_data \n where H3_PROBK = 1.0\n \"\"\".format(kcharged_mass*kcharged_mass))\n\nEnergy_H2_data_plot = Energy_H2.toPandas().plot.hist(bins=31, range=[0, 550000]) \nxlabel('H2_Energy (MeV)')\nylabel('Count')\nEnergy_H3_data_plot = Energy_H3.toPandas().plot.hist(bins=31, range=[0, 550000]) \nxlabel('H3_Energy (MeV)')\nylabel('Count');",
"Adding features of the $B$ meson\nIn this analysis we are looking for B<sup>+</sup> or B<sup>-</sup> mesons (see B meson) that have decayed into the three charged kaons.\nEnergy is a conserved quantities. This means that you can use the energy of the three 'daughter' kaons, which you have calculated above, to calculate the energy that the B meson that decayed into them must have.\nMomentum is also a conserved quantity. Hence you can also use the momenta of the 'daughter' kaons to calculate the momentum of the B meson. But be careful - momentum is a vector quantity. \nUsing the Energy of the B meson and the magnitude of the momentum of the B meson you can use the energy-momentum relationship again. This time you are applying it to the B meson. This will allow you to calculate the invariant mass of the B meson.",
"# calculate the energy of the B meson from the sum of the energies of the kaons\n\nsum_kaons_energy = sql(\"\"\"\n select \n sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ) +\n sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) +\n sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) as Tot_Energy \n from sim_data\n where H1_ProbK = 1.0 and H2_ProbK = 1.0 and H3_ProbK = 1.0\"\"\".format(kcharged_mass*kcharged_mass))\n\nsum_kaons_energy.show(10)\n\n# Calculate the momentum components of the B meson \n# This is a vector sum (i.e. we sum each vector component of the kaons)\n\nsum_kaons_momentum = sql(\"\"\"\n select \n H1_PX + H2_PX + H3_PX as PX_Tot,\n H1_PY + H2_PY + H3_PY as PY_Tot,\n H1_PZ + H2_PZ + H3_PZ as PZ_Tot\n from sim_data\n where H1_ProbK = 1.0 and H2_ProbK = 1.0 and H3_ProbK = 1.0\"\"\")\n\nsum_kaons_momentum.show(10)\n\n# Calculate the momentum components of the B meson \n# This computes the vector magnitude of the vector computed above\n# we use the spark sql declarative interface as opposed to writing an SQL statement for this\n# the two approaches are equivalent in Spark\n\nsum_kaons_momentum_magnitude = sum_kaons_momentum.selectExpr(\"sqrt(PX_Tot*PX_Tot + PY_Tot*PY_Tot + PZ_Tot*PZ_Tot) as P_Tot\")\n\nsum_kaons_momentum_magnitude.show(10)\n\n# calculate the B meson invariant mass\n# plot the B meson invariant mass in a histogram\n\nb_meson_4momentum = sum_kaons_energy = sql(\"\"\"\n select \n sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ) +\n sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) +\n sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) as Tot_Energy,\n H1_PX + H2_PX + H3_PX as PX_Tot,\n H1_PY + H2_PY + H3_PY as PY_Tot,\n H1_PZ + H2_PZ + H3_PZ as PZ_Tot\n from sim_data\n where H1_ProbK = 1.0 and H2_ProbK = 1.0 and H3_ProbK = 1.0\"\"\".format(kcharged_mass*kcharged_mass))\n\nb_meson_4momentum.show(5)\n\nb_meson_invariant_mass = b_meson_4momentum.selectExpr(\"\"\"\n sqrt(Tot_Energy* Tot_Energy - (PX_Tot*PX_Tot + PY_Tot*PY_Tot + PZ_Tot*PZ_Tot) ) as invariant_mass\"\"\")\n \nb_meson_invariant_mass.show(5)\n\nb_meson_invariant_mass.toPandas().plot.hist(bins=101, range=[4000, 6000],\ntitle=\"Histogram - distribution of B meson invariant mass, simulation data\") \nxlabel('b_meson_invariant_mass (MeV)')\nylabel('Count');\n\n# Note the mass of the charged B meson is expected to be 5279.29±0.15 and this is consistenet with the \n# the peak in found in the data plotted here",
"You should have a graph that sharply peaks at the mass of the B<sup>+</sup> meson. The mass of the B<sup>+</sup> and B<sup>-</sup> meson are the same. Check that the peak of your graph is at the known mass of the B meson. Congratulations!\nRecall that you have made this plot for simulated data. How might you expect the plots for real data to look different ? In the next section you will start to work with the real LHC data.\nHint\nB Meson Energy - From energy conservation, the energy of the B meson will be the sum of the energies of the three kaons: $E_B=E_{K1}+E_{K2}+E_{K3}$, where $E_B$ is the energy of the B meson, $E_{K1}, E_{K2}, E_{K3}$ are the energies of each of the kaons. \nB meson momentum - From momentum conservation, the X component of the momentum of the B meson will be the sum of the X momentum components of the three Kaons : $px_B=px_{K1}+px_{K2}+px_{K3}$, where $px$ is the X direction component of the momentum of the B meson, $px_{K1},px_{K2},px_{K3}$ are the X direction components of the momenta of the three kaons. You can then do the same with the Y and Z components. Having obtained the X,Y, and z components of the B momentum you can find the magnitude of the momentum of the B meson.\n B meson invariant mass* - Rearrange the equation $E^2=p^2+m^2$ to find $m^2$. Using the values of the magnitude of the momentum of the B meson and the B meson Energy, find the mass of the B meson.\nHistogram plotting - Take care that the range of your mass plot is set suitably that you can see the mass peak. Once you have found the peak you can set the range appropriately. You do not have to start your graph at a mass of 0.\nUnits - The data you are provided has energies in 'MeV' (10<sup>6</sup> electron volts). The mass of the B meson is often quoted in 'GeV/c<sup>2</sup>' (10<sup>9</sup> electron volts).\nWorking with real data and applying cuts\nAims:\n\n\nFilter out data that is not from the B<sup>+</sup> → K<sup>+</sup>K<sup>+</sup>K<sup>−</sup> channel, or the antiparticle equivalent B<sup>-</sup> → K<sup>+</sup>K<sup>-</sup>K<sup>−</sup>\n\n\nPlot a histogram of B-meson mass for the real data and observe how different cuts affect the data\n\n\nIn the section above you have analysed the simulation data to determine the invariant mass of the B meson. Now, you can start applying the methods you have used to the real LHCb data. This data was collected by the LHCb detector at CERN during 2011, the first major year of LHC operations.\nThe data you are given has been filtered to select only events that are likely to have come from B<sup>+</sup> or B<sup>-</sup> mesons decaying into three final state charged particles. You are interested in the case where these three final state paticles are charged kaons K<sup>+</sup> or K<sup>-</sup>.\nAn introduction has been provided on the detector and data sample. As background information we also provide further information on the selection that has been applied to select this data sample.\nPreselection\nYou want to apply a preselection to the three final state tracks that\n* Ensures that they are not muons (i.e. !H1_isMuon where ! means not, and similarly for H2 and H3)\n* Requires that they each have a low probability of being pions (e.g. H1_ProbPi < 0.5)\n* Requires that they each have a high probability of being a kaon (e.g. H1_ProbK > 0.5)\nYou need to find a balance between making cuts that are too loose and include too many background events and too tight and reject many of your signal events.\nIn order to now find the most suitable further selection cuts, make yourself familiar with how cuts can affect the significance of the final result. Feel free to come back to this stage later and adjust your cuts to see the impact. \nThe pre selection you create will be applied for you if give it the name 'preselection'.\nWe have provided an example preselection in the hints, so feel free to use that to get started if you wish. start with a loose preselection and then refine it after you have studied the plots.",
"# Create the DataFrames with ROOT data using the spark-root data format\n# Only metadata is read at this stage (reading into Spark DatFrames is lazily executed)\n\nB2HHH_MagnetDown_df = spark.read.format(\"org.dianahep.sparkroot\").load(data_directory + \"B2HHH_MagnetDown.root\")\nB2HHH_MagnetUp_df = spark.read.format(\"org.dianahep.sparkroot\").load(data_directory + \"B2HHH_MagnetUp.root\")\n\n\n# Put all the data together\nB2HHH_AllData_df = B2HHH_MagnetDown_df.union(B2HHH_MagnetUp_df)\n\n# This defines the cut criteria\n# You can experiment with different criteria\n\npreselection = \"\"\"H1_ProbPi < 0.5 and H2_ProbPi < 0.5 and H3_ProbPi < 0.5 \n and H1_ProbK > 0.5 and H2_ProbK > 0.5 and H3_ProbK > 0.5 \n and H1_isMuon = 0 and H2_isMuon = 0 and H3_isMuon = 0\"\"\"\n\n# Apply cuts to the data as a filter \nB2HHH_AllData_WithCuts_df = B2HHH_AllData_df.filter(preselection)\n\n# This *may take a few minutes* as data will be read at this stage\n\nB2HHH_AllData_WithCuts_df.cache() # flags the DataFrame for caching, this is useful for performance\nB2HHH_AllData_WithCuts_df.count() # triggers an action, data will be read at this stage\n\n# This registers the dataframe with cuts (filters) as a view for later use with SQL\nB2HHH_AllData_WithCuts_df.createOrReplaceTempView(\"B2HHH_AllData_WithCuts\")\n\n# Displays a sample of the data\nB2HHH_AllData_WithCuts_df.limit(10).toPandas()",
"Make histograms of the probability of a final state particle being a kaon or a pion.\nThese will help guide you on suitable probability values at which to cut.\nYou can also consider more sophisticated options like 2-D plots of kaon and pion probabilities or different values of the cuts for the different final state particles.",
"# plot the probability that a final state particle is a kaon\n\nB2HHH_AllData_WithCuts_df.select(\"H1_ProbK\", \"H2_ProbK\", \"H3_ProbK\").toPandas().plot.hist(bins=101, range=[0.0, 1.0])\nxlabel('Probability value that the particle is a kaon')\nylabel('Count');\n\n# plot the probability that a final state particle is a pion\nB2HHH_AllData_WithCuts_df.select(\"H1_ProbPi\", \"H2_ProbPi\", \"H3_ProbPi\").toPandas().plot.hist(bins=101, range=[0.0, 1.0])\nxlabel('Probability value that the particle is a pion')\nylabel('Count');",
"Now calculate the invariant mass of the B meson for the real data and plot a histogram of this. \nCompare it with the one you drew for the simulation data. \nCan you explain the differences you observe?",
"# calculate the B meson invariant mass\n# plot the B meson invariant mass in a histogram\nb_meson_4momentum_withcuts = sql(\"\"\"\n select \n sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ) +\n sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) +\n sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) as Tot_Energy,\n H1_PX + H2_PX + H3_PX as PX_Tot,\n H1_PY + H2_PY + H3_PY as PY_Tot,\n H1_PZ + H2_PZ + H3_PZ as PZ_Tot\n from B2HHH_AllData_WithCuts\"\"\".format(kcharged_mass*kcharged_mass))\n\nb_meson_4momentum_withcuts.createOrReplaceTempView(\"b_meson_4momentum_mycuts_read_data\")\nb_meson_4momentum_withcuts.show(5)\n\nb_meson_invariant_mass_withcuts = b_meson_4momentum_withcuts.selectExpr(\"\"\"\n sqrt(Tot_Energy* Tot_Energy - (PX_Tot*PX_Tot + PY_Tot*PY_Tot + PZ_Tot*PZ_Tot) ) as invariant_mass\"\"\")\n \nb_meson_invariant_mass_withcuts.show(5)\n\n# draw a histogram for the B meson mass in the real data\n\nb_meson_invariant_mass_withcuts.toPandas().plot.hist(bins=101, range=[4000, 6000],\ntitle=\"Histogram - distribution of B meson invariant mass, real data\") \nxlabel('b_meson_invariant_mass (MeV)')\nylabel('Count');\n",
"Additional exercise: Experiment with the cuts and see the impact of harsher or more lenient cuts on the invariant mass plot.\nYou should select a set of cuts which makes the signal most prominent with respect to the background.\nOnce you have finalised the selection on particle identification also make cuts on the reconstructed particle mass to select the events in the B meson mass peak, removing the background events which lie at lower and higher invariant masses. \nSearching for global matter anti-matter differences\nIn this section you will start to study matter antimatter differences (CP Violation). Here 'global' means that you are looking for differences across all ranges of energy and momentum (the kinematics) of the kaons into which the charge B mesons have decayed. Later we look at 'local' differences in different regions of the kinematics. \nAims:\n\nCalculate the global CP asymmetry \nWork out the statistical uncertainty\nDetermine if there is evidence for CP violation in this decay\n\nIn order to quantify the matter antimatter asymmetry in this process we wish to compare the B<sup>+</sup> and the B<sup>-</sup> particles. The B<sup>-</sup> is the anti-particle of the B<sup>+</sup>.\nHow can you distinguish between events that contain B<sup>+</sup> and B<sup>-</sup> particles using H1_Charge, H2_Charge and H3_Charge?",
"# make a variable for the charge of the B mesons\n\nB_charge_df = B2HHH_AllData_WithCuts_df.selectExpr(\"H1_charge + H2_charge + H3_charge as B_Charge\")",
"Now count the numbers of events of each of the two types (N<sup>+</sup> and N<sup>-</sup>). Also calculate the difference between these two numbers.",
"# make variables for the numbers of positive and negative B mesons\n\n# I am using the declarative API of Spark SQl for this. If you want to use SQL you can do the following:\n# B_charge_df.createOrReplaceTempView(\"B_charge_table\")\n# sql(\"select B_Charge, count(*) from B_charge_table group by B_Charge\").show(5)\n\nB_charge_df.groupBy(\"B_Charge\").count().show()\n",
"In order to calculate the Asymmetry, you can make use of the formula:\n(note you may need to run this box in order to see the image)\n<img src=\"https://github.com/lhcb/opendata-project/raw/master/Images/AsymmetryEq.png\" width=\"200\" />",
"# calculate the value of the asymmetry, by using the formula above, and then print it\n\nN_plus = 12390.0\nN_minus = 11505.0\nA = (N_minus - N_plus) / (N_minus + N_plus)\nA",
"Hint\nDifferentiating between N+ and N-\n\nCharge is a conserved quantity. The charge of the $B$ meson is equal to the sum of the charges of the particles into which it decays.\nYou can use len(real_data.query('B_Charge == charge')) to count the number of mesons, where B_Charge is the variable you created and charge is 1 or -1.\nYou can find an example of this at the end of the example notebook.\n\nEstimating the significance of the deviation\nYou will now need to calculate the statistical uncertainty of the asymmetry. You can do so using the formula: <img src=\"https://github.com/lhcb/opendata-project/raw/master/Images/AsymmetryErrorEq.png\" width=\"200\" />\nThe significance of the result, sigma, is found by dividing the value for asymmetry by its uncertainty. A value exceeding three sigma is considered \"evidence\" by particle physicists while a value of five sigma or more can be called an \"observation\" or \"discovery\".",
"# calculate the statistical significance of your result and print it\n\nsqrt((1 - A*A)/(N_minus + N_plus))",
"Congratulations! You have performed your first search for a matter anti-matter difference.\nHere you have only considered the statistical uncertainty. Your measurement will also have other sources of uncertainty known as systematic uncertainties which you have not considered at this stage.\nDalitz plots and two body resonances\nAims:\n\nProduce Dalitz plots of the simulation and real data sample\nCreate ordered and binned dalitz plots.\nIdentify two body resonances in the Dalitz plots\n\nIn this stage we introduce you to an important technique for analysing decays of one particle (your charged B meson) into three bodies (the three kaons). This is known as a Dalitz plot. \nThe decay of the B meson can proceed either directly to the three-body final state or via an intermediate particle. For example, B<sup>+</sup> → K<sup>+</sup>K<sup>+</sup>K<sup>−</sup>, could proceed through the decay B<sup>+</sup> → K<sup>+</sup>R<sup>0</sup>, where R<sup>0</sup> is a neutral particle resonance which can decay R<sup>0</sup> → K<sup>+</sup>K<sup>-</sup>. Dalitz plots can be used to identify these resonances which are visible as bands on the Dalitz plot.\nMore information about these plots and why these are used in particle physics research can be found in Dalitz Plot Introduction.\nThe kinematics of a three-body decay can be fully described using only two variables. The energies and momenta of the three kaons are not independent of each other as they all come from the decay of a B meson and energy and momentum are conserved. The axes of the plots conventionally are the squared invariant masses of two pairs of the decay products. It is a 2D plot, the x and y axes are both squared masses and the density of points in the plot shows the structure.\nConsider our decay B<sup>+</sup> → K<sup>+</sup><sub>1</sub>K<sup>+</sup><sub>2</sub>K<sup>−</sup><sub>3</sub>, where we have numbered the kaons 1,2,3 to distinguish them. We can calculate the invariant mass of three possible combinations that could correspond to intermediate resonances R<sup>++</sup><sub>1</sub> → K<sup>+</sup><sub>1</sub>K<sup>+</sup><sub>2</sub>, R<sup>0</sup><sub>2</sub> → K<sup>+</sup><sub>1</sub>K<sup>-</sup><sub>3</sub>, and R<sup>0</sup><sub>3</sub> → K<sup>+</sup><sub>2</sub>K<sup>-</sup><sub>3</sub>. \nThe potential R<sup>++</sup><sub>1</sub> would be a doubly charged resonance. We would not expect to see any resonances corresponding to this as mesons are composed of one quark and one anti-quark and their charges cannot add up to two units.\nThe potential R<sup>0</sup><sub>2</sub> and R<sup>0</sup><sub>3</sub> correspond to configurations in which we could see resonances. Hence you should compute the invariant mass combinations for these. The square of these masses should be used as the Dalitz variables. \nWe suggest you make these plots first for the simulation data. In the simulation there are no intermediate resonances and your plot should be of uniform density inside the range physically allowed by energy and momentum conservation.",
"# calculate the invariant masses for each possible hadron pair combination\n\ntwo_body_resonances_df = sql(\"\"\"\n select \n sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ) +\n sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) as Energy_K1_K2,\n sqrt((H1_PX + H2_PX)*(H1_PX + H2_PX) + (H1_PY + H2_PY)*(H1_PY + H2_PY) \n + (H1_PZ + H2_PZ)*(H1_PZ + H2_PZ)) as P_K1_K2,\n sqrt({0} + H1_PX*H1_PX + H1_PY*H1_PY + H1_PZ*H1_PZ) +\n sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) as Energy_K1_K3,\n sqrt((H1_PX + H3_PX)*(H1_PX + H3_PX) + (H1_PY + H3_PY)*(H1_PY + H3_PY) \n + (H1_PZ + H3_PZ)*(H1_PZ + H3_PZ)) as P_K1_K3,\n sqrt({0} + H2_PX*H2_PX + H2_PY*H2_PY + H2_PZ*H2_PZ) +\n sqrt({0} + H3_PX*H3_PX + H3_PY*H3_PY + H3_PZ*H3_PZ) as Energy_K2_K3,\n sqrt((H2_PX + H3_PX)*(H2_PX + H3_PX) + (H2_PY + H3_PY)*(H2_PY + H3_PY) \n + (H2_PZ + H3_PZ)*(H2_PZ + H3_PZ)) as P_K2_K3,\n H1_Charge, H2_Charge, H3_Charge\n from B2HHH_AllData_WithCuts\"\"\".format(kcharged_mass*kcharged_mass))\n\ntwo_body_resonances_df.limit(5).toPandas()\n\n# Computes 2-body resonance invariant mass from two_body_resonances_df\n\ntwo_body_resonances_invariant_mass_GeV_df = two_body_resonances_df.selectExpr( \n \"sqrt(Energy_K1_K2*Energy_K1_K2 - P_K1_K2*P_K1_K2) / 1000.0 as Mass_K1_K2\", \n \"sqrt(Energy_K1_K3*Energy_K1_K3 - P_K1_K3*P_K1_K3) / 1000.0 as Mass_K1_K3\",\n \"sqrt(Energy_K2_K3*Energy_K2_K3 - P_K2_K3*P_K2_K3) / 1000.0 as Mass_K2_K3\",\n \"H1_Charge\", \"H2_Charge\", \"H3_Charge\") \n\ntwo_body_resonances_invariant_mass_GeV_df.show(5)\n\n\n# Two_body_resonances_invariant_mass_GeV_df.filter(\"H1_Charge * H2_Charge = -1\").show()\n\ntwo_body_resonances_invariant_mass_GeV_df.createOrReplaceTempView(\"t1\")\nsql(\"select H2_Charge * H3_Charge, count(*) from t1 group by H2_Charge * H3_Charge\").show()\n\n# plot the invariant mass for one of these combinations\n\ntwo_body_resonances_invariant_mass_GeV_df.filter(\"H1_Charge + H2_Charge = 0\").select(\"Mass_K1_K2\") \\\n .toPandas().plot.hist(bins=101, range=[0, 10],\ntitle=\"Histogram - distribution of K1_K2 resonance invariant mass, simulation data\") \nxlabel('b_meson_invariant_mass (GeV)')\nylabel('Count');\n\n\ntwo_body_resonances_invariant_mass_GeV_df.filter(\"H1_Charge * H3_Charge = -1\").count()\n\n# Make a Dalitz plot with labelled axes for the simulation data\n\n# This is achieved by plotting a scatter graph from Mass_12 squared vs. Mass_13 squared\n# As in the text of the exercise, add a filter on data that the possible resonance has charge 0\n\ndalitz_plot_df = two_body_resonances_invariant_mass_GeV_df \\\n .filter(\"H1_Charge + H2_Charge = 0\").filter(\"H1_Charge + H3_Charge = 0\") \\\n .selectExpr(\"Mass_K1_K2*Mass_K1_K2 as M12_squared\", \"Mass_K1_K3*Mass_K1_K3 as M13_squared\")\n\ndalitz_plot_df.toPandas().plot.scatter(x='M12_squared', y='M13_squared',\ntitle=\"Dalitz plot, B+/- meson decay into thre kaons, simulation data\")\nxlabel('Mass_K1_K2 squared (GeV^2)')\nylabel('Mass_K1_K3 squared (GeV^2)');\n",
"Hints\nCalculating invariant mass - Use the same technique as you did above for the B meson, but now applying it to two-body invariant masses rather than three.\nPlotting the Dalitz plot - You can use a scatter plot from matplotlib to plot a Dalitz plot, see the example analysis. Remember to use the square of each two-body mass.\nAdding Dalitz plot for real data\nNow draw a Dalitz plot for the real data. Check that the signs of the charge of the hadrons are correct to correspond to your potential neutral resonances R<sup>0</sup><sub>2</sub> and R<sup>0</sup><sub>3</sub>.",
"# calculate the invariant masses for each possible hadron pair combination in the real data\n\n# make a Dalitz plot for the real data (with your preselection cuts applied)",
"<div align=\"justify\">While drawing the Dalitz plot for the real data, label the axes accordingly. Compare the Dalitz plots of the real data with the one for the simulation. \nWhat are the most striking differences? \n</div>\n\nOrdering Dalitz variables\nYou can make a further improvement to allow you to observe the resonances easier. Your resonances R<sup>0</sup><sub>2</sub> and R<sup>0</sup><sub>3</sub> are both composed of the same particle types, K<sup>+</sup>K<sup>-</sup>, and hence have the same distributions. It is useful to impose an ordering which distinguishes the resonances. We can call the resonances R<sup>0</sup><sub>Low</sub> and R<sup>0</sup><sub>High</sub>. In each event R<sup>0</sup><sub>Low</sub> is the resonance with the lower mass and the other corresponds to the higher mass combination of kaons. You can now use the mass of these ordered resonances as your Dalitz plot variables, thus effectively \"folding\" your Dalitz plot so that one axis always has a higher value than the other.",
"# make a new Dalitz plot with a mass ordering of the axes",
"Hint\nOrdered Dalitz plot - You can find the maximum of the mass of R<sup>0</sup><sub>Low</sub> vs R<sup>0</sup><sub>High</sub> elementwise on one axis, and the minimum of on the other. You can use numpy.min(a,b) and numpy.max(a,b) to perform elementwise comparisons between two arrays a and b and return one array filled by either the individual min/max element from the elementwise comparisons.\nBinned Dalitz plot\nYou can improve the representation of your Dalitz plot by binning the data. The hist2d function can be used to make a 2D histogram. The number of bins specification in the hist2d function is the number of bins in one axis.",
"# plot a binned Dalitz Plot\n# use colorbar() to make a legend for your plot at the side",
"Two body resonances\nYou can now use your Dalitz plot to identify the intermediate resonances that you see in your plots. The resonances will have shown up as bands of higher density of points on the plots. You can use the particle data group tables of mesons to identify which particles these correspond to. The tables give the masses and widths of the particles and their decay modes. You are looking for mesons with the masses corresponding to where you see the bands and that decay into K<sup>+</sup>K<sup>-</sup>.\nCongratulations! You have succesfully made a Dalitz plot and used it to observe the presence of intermediate particles in the decay of your charged B meson into three charged kaons. \nSearching for local matter anti-matter differences\nAims:\n\nObserve matter antimatter differences (CP violation) in regions of the Dalitz plots of the B<sup>+</sup> and B<sup>-</sup> mesons.\nFor the data in these regions produce plots to best display the CP violation.\n\nIn a section above you searched for global CP violation. You probably did not find a result with very high significance. \nCP violation may arise from interference between decays through different resonances, and hence the magnitude and sign of the CP violation may vary across the Dalitz plot. We can apply the same equation as in the global CP violation study \n<img src=\"https://github.com/lhcb/opendata-project/raw/master/Images/AsymmetryEq.png\" width=\"200\" />\nbut apply this only to events in particular regions of the Dalitz plot.\nRemoving charm resonances\nThe analysis performed here is to study the CP violation in the charmless B meson decays to kaons. \"charmless\" means that the decay does not proceed through a charm quark. However, the most frequent decay of the B mesons occur through the b quark decaying into a c quark. The majority of these events can be removed by rejecting the events that are proceeding through a D<sup>0</sup> meson (which contains the charm quark).\nIn the section above you plotted a histogram of the invariant mass of the intermediate resonances and will have observed the D<sup>0</sup> meson in this and in the Dalitz plot. You should now reject events that are around the mass range of the D<sup>0</sup> meson to suppress this contribution. You can do this in your pre-selection on the data that you set-up earlier in the project.\nThis was also a simplification that we did not consider when we were calculating the global asymmetry. After you have applied this pre-selection your code will now recompute the global asymmetry with the D<sup>0</sup> meson contribution rejected. We have not yet observed CP violation in charm mesons and searching for this is another active area of current research.\nComparing Dalitz plots\nMake separate Dalitz plots for the B<sup>+</sup> and the B<sup>-</sup> decays.\nLocal CP Violation will show up as an asymmetry between the B<sup>+</sup> and the B<sup>-</sup> plots. \nIn order that the statistical error on the asymmetry in each bin is not over large the bins need to contain a reasonable number of entries. Hence you will probably need larger bins than when you were looking for resonances in the section above. A suitable initial bin size might be $2.5~\\text{GeV}^2/\\text{c}^4 \\times 2.5~\\text{GeV}^2/\\text{c}^4$.",
"# make a Dalitz plot for the B+ events\n\n# make a Dalitz plot for the B- events\n\n# Make a plot showing the asymmetry between these two Daltz plots\n# i.e. calculate the asymmetry between each bin of the B+ and B- Dalitz plots and show the result in another 2D plot",
"Observing a large asymmetry in some regions of the plot does not necessarily mean you have observed CP violation. If there are very few events in that region of the plot the uncertainty on that large asymmetry may be large. Hence, the value may still be compatible with zero.\nYou can calculate the statistical uncertainty on the asymmetry, for each bin of the plot, using the same formulas as you used in the global asymmetry section. You can then make a plot showing the uncertainty on the asymmetry.\nDividing the plot showing the asymmetry by the plot showing the statistical uncertainty you can then obtain the significance of the asymmetry in each bin. You can then plot the significance of the asymmetry to see if there is any evidence for CP violation.",
"# Make a plot showing the uncertainty on the asymmetry \n\n# Make a plot showing the statistical significance of the asymmetry",
"Observing CP violation\nFrom your studies of the asymmetry plot, and the plot of its significance, you will be able to identify regions in the Dalitz plots that show indications of sizeable and significant CP Violation. You may find you have several consecutive bins with significant positive, or negative, asymmetries. You may wish to try alternative binnings of the Dalitz plots to best isolate the regions in which the significant asymmetries occur.\nYou can select events that are in these regions of the Dalitz plots where you observe signs of CP Violation. You can then plot a simple 1D histogram of the invariant mass distribution of the B<sup>+</sup> and the B<sup>-</sup> events, just as you did at the start of the project, but only for events that lie in the region of the Dalitz plot that you are interested in. Make the plots of the B<sup>+</sup> and the B<sup>-</sup> events with the same scale, or superimpose the two plots, so that you can observe if the particle and anti-particle decay processes are occurring at the same rate.",
"# Make a plot showing the invariant mass of the B+ meson particles\n# using events from a region of the Dalitz plot showing sizeable CP asymmetries\n\n# Make a plot showing the invariant mass of the B- meson particles using events from the same region",
"Congratulations! You should now have succesfully observed significant evidence for CP Violation. You should have plots that clearly show that particle and anti-particle decay processes occur at different rates in local regions of the Dalitz plot. You may wish to comapre your results with those published by the LHCb collaboration in this paper.\nWell Done you have succesfully completed your first particle physics analysis project. There are many more analyses that can be conducted witht the data set that you have been provided and the skills that you have gained. Ideas for some of these are explored in the section below. Maybe you can discover something new!\nNow you've finished the analysis please provide feedback to help us improve this project using this brief survey.\nFurther analyses\nThe data set you have been provided is the full set of data recorded by LHCb preselected for decays of charged B mesons into three final state tracks. This data set has been used for two important publications, here and here.\nWe discuss here: \n<ul>\n<li>Additional elements that you could add to your analysis of B<sup>+</sup> → K<sup>+</sup>K<sup>+</sup>K<sup>−</sup> </li>\n<li>Further analyses that you could perform with this data set</li>\n</ul>\n\nAdding extra sophistication\nSystematic Uncertainties\nIn this analysis you considered the statistical uncertainty on the result. This occurs as a result of having only a limited number of events. In addition there are systematic uncertainties, these arise from biases in your measurement. Here we discuss three sources of these for this analysis.\n<ul>\n<li> Production asymmetry. The LHC is a proton-proton collider and hence the initial state of the collision is not matter antimatter symmetric. Consequently B<sup>+</sup> and B<sup>-</sup> mesons may not be produced at exactly the same rates. This small production asymmetry it is estimated could be approximately 1%. It can also be measured from the data, as discussed in the LHCb paper.</li>\n<li> Detection asymmetry. The LHCb detector could be more efficient for detecting either the B<sup>+</sup> or the B<sup>-</sup> final states. This is because the positive and negative kaons will be bent by the magnet indifferent directions in the detector. If the efficiency of the detector is higher in one region than another this will lead to higher efficiencies for K<sup>+</sup> or K<sup>-</sup> and hence for B<sup>+</sup> or B<sup>-</sup>. For this reason the magnetic field of the LHCb detector is regularly reversed. You used data in this analysis in which the magnetic field was both up and down and hence the effect will (partially) cancel. By comparing results for the two magnet polarities separately you can check the size of this effect. When loading the data above both polarities were combined, you can instead load them independently to measure the difference between the two datasets.</li>\n<li> Analysis technique. The analysis technique you have used may bias the result. A major simplification we made in the analysis above was to neglect 'background' events. We imposed a selection to select a sample of predominantly signal events but have not accounted for the effect of the residual background events.</li>\n</ul>\n\nUsing mass sidebands\nOne source of 'background' events arises from random combinations of tracks in events that happen to fake the 'signal' characteristics. These events will not peak in the mass distribution at the mass of the B meson but rtaher will have a smoothly varying distribution. Looking at the number and distribution of of events away from the mass peak can allow you to estimate the number of background events under the mass peak.\nFitting distributions\nThe next level of sophistication in the analysis requires fitting the distributions of events that are observed in the B mass distribution in order to estimate the yield of signal events and background events. You can see how this is done in the LHCb paper on the analysis. Fitting can be performed using the CERN root framework.\nFurther analyses\nThe LHCb papers using this data set that you are using analysed four decay channels of the charged B mesons. You can perform any of these analyses.\n<ul>\n<li>B<sup>+</sup> → K<sup>+</sup>K<sup>+</sup>K<sup>−</sup> (and anti-particle equivalent). This is the analysis you have performed here. It has the lowest background of the four channels and hence the approximation we made of neglecting the background events will give the least bias to this channel.</li>\n<li>B<sup>+</sup> → π<sup>+</sup>π<sup>+</sup>π<sup>−</sup> (and anti-particle equivalent). In this analysis the final state is three charged pions. The level of background events compared to the signal is significantly higher as pions are the most commonly produced particle at the LHC. Hence, a method of estimating the background level should be added to complete this analysis.</li>\n<li>B<sup>+</sup> → K<sup>+</sup>π<sup>+</sup>π<sup>−</sup> (and anti-particle equivalent). In this analysis the final state is a mixture of one kaon and two pions. This means that the analysis needs to determine in each event which track is the best candidate kaon and apply selection cuts appropriately to select out the events.</li>\n<li>B<sup>+</sup> → π<sup>+</sup>K<sup>+</sup>K<sup>−</sup> (and anti-particle equivalent). This channel has a higher level of background compared to the signal.</li>\n</ul>"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
bwbadger/mifid2-rts
|
rts/RTS2_Worked_Examples.ipynb
|
bsd-3-clause
|
[
"Read me\nThe objective of this project is to show that it is better to express regulatory requirements using executable expressions which all interested parties can share and run and test, rather than to express regulatory requirements as text documents which everyone has to interpret for themselves.\nThis page is a Jupyter notebook. It is a combination of a document and some live software which you can execute if you are running your own jupyter-notebook server. If you are not running a Jupyter server you can still read the document and see the code examples - you just can't run them.\nIf you see something wrong on this page or in the code, please create an issue in the GitHub project.\nMiFID II classification of trades using the RTS 2 Annex 3 taxonomy.\nGovernments would prefer to avoid another financial crisis like the one in 2008 and believe that making the big players operate in a more open and transparent way will help avoid another crash.\nMarkets in Financial Instruments Directive II (MiFID II) is an EU law which has market transparency as its key objective. The predecessor law, MiFID I, only looked at a part of what banking firms do. MiFID II aims to cover most mainstream activity.\nGovernments rely on regulators to make sure that their laws are being followed. For MiFID II the primary regulator is ESMA. ESMA have produced a number of Regulatory Technical Standard (RTS) documents which aim to explain what banking firms must do to comply with the MiFID II law.\nOne of the RTS documents, RTS 2, explains how different kinds of trading activity can be identified. Having a clear way to say what has been traded is an important part of making the markets more transparent.\nSome kinds of trading activity are already pretty transparent, for example buying and selling shares in a public company. Trades of this kind are mostly done using a public exchange, such as the New York or London stock exchanges. The 'price' for a given stock is simply the amount of money paid in the most recent trade and this price is made public by the exchange so everyone can see what the latest price is. It is pretty easy to identify what has been traded because each stock has a identifier, e.g. 'AAPL' identifies Apple Inc. shares.\nNot all trades happen on public exchanges. Many trades happen directly between two parties and these are known as over the counter (OTC) trades. Each OTC trade can be fine-tuned, for example setting payment dates and interest rates. The fine tuning of OTC trades makes it hard to give an identity to what has been traded, but this is where RTS 2 comes in. \nThe easiest way to understand what RTS 2 is all about is to use it to classify some trades, and you can do just that below.\nA Python Implementation of RTS 2 Annex 3\nIt would be nice if ESMA published a working software implememtation of the RTS rules along with some test data so people can see exactly how the rules are supposed to work, and how reports are supposed to look. But ESMA don't do that. Each participant must somehow get an implementation of the RTS rules, either by writing it themselves or buying an implementation.\nOne market participant implemented the RTS rules themselves and have now released part of that implementation under an open source license, the BSD license, so anyone can see the implementaion and use it. This document forms a part of that release.\nHopefully this software will encourage ESMA to produce reference implementaions of their rules in future. They could even take this software as a starting point.\nThe software here is written in the Python programming language. Python was chosen because the language is ubiquitous, that is it can be used easily and immediately on most modern computers; everything from a Raspberry Pi to the largest of big data clusters.\nRunning a really simple initial classification\nThe box below contains python code which runs the classification software. If you are just viewing this page then you won't be able to run the code, but if you start the page using your own local Jupyter notebook server then the code will really run if you select the box below and press control+enter. If you can run the code you might like to try changing the values of the attributes below (e.g. to_date) to see what happens.",
"# Import the RTS 2 module and the Python date & time tools module\nimport rts2_annex3\nimport datetime\n\n# Create a simple Python object to represent a trade.\nclass SampleTrade(object):\n pass\nsample_trade = SampleTrade()\nsample_trade.asset_class_name = 'Foreign Exchange Derivatives'\nsample_trade.sub_asset_class_name= 'Deliverable FX options (DO)'\nsample_trade.underlying_currency_pair = ('GBP~USD')\nsample_trade.from_date = datetime.date(2017, 9, 13)\nsample_trade.to_date = datetime.date(2017, 10, 12)\n\n# Now classify the trade\nsample_classification = rts2_annex3.class_root.classification_for(sample_trade)\n\n# Lastly, display the classificaton\nsample_classification.classification_dict()",
"Understanding a classification\nThe classification is shown here as a Python dictionary, but one could imagine presenting this classification in many ways ... and this is a problem. What is the official accepted literal form of an RTS 2 classification? Nobody seems to know. So let's go with this dictionary for now.\nAnother point about the above representation is that it is very big, and the example is not one of the biggest! The reason for the size is that the text which appears is exactly as it appears in RTS 2. There is no obvious way to shorten the classification without inventing something, and that would open the door to arguments about what is right. This way, the classification links back to the RTS document in an extremely obvious, if verbose, way. No arguments.\nTo a large degree, the classification is simply repeating the information we gave our sample_trade object in the code above, but information has been checked and other information added.\nThis classification first confirms the identity of the RTS document the classification is based upon. The RTS rules may change over time, so it is important to know which version of the RTS a particular classification is based upon.\nNext we see the Asset class and Sub-asset class, which is repeating just what we said above. When classifying a trade there are some things you just have to know. There will be some help on how to choose Asset classes and Sub-asset classes below.\nThen we see something we didn't include in our trade object. The RTS 2 Annex 3 document defines a number of criteria for each kind of Sub-asset class. The Sub-asset class in this case has two criteria, and the classification included the description, the exact text, from the RTS document to explain what the criteria mean.\nThe values for the criteria do come from the values on our object, but some involve calculation. The currency pair criterion, criterion 1, is simply the name of underlying_currency_pair value we provided. Criterion 2 gets its value from date calculations which use the from and to dates we gave; the resulting value is a date bucket, bucket 2 in this case.\nWould Json be a better format for classifications?\nBecause the classification is just a Python object we can change its implementation to render the classification in any way we please, or we can take the dictionary it currently produces and convert it to something else. Here, the classification above is shown as json:",
"print(sample_classification.as_json(indent=4))",
"RTS 2 Annex 3 defines a taxonomy. A Tree.¶\nTo understand how the classification process works we need to look at what the RTS says.\nThe RTS 2 Annex 3 taxonomy is made up of Asset classes which get broken down into Sub-asset classes which are further broken down by combinations of criteria values.\nHere is some code to list the names of elements of the taxonomy:",
"# The root of the taxonomy is rts2_annex3.class_root. Here we ask the\n# root for the asset classes, and then ask each asset class for its name.\n# The names are exactly the names of the Asset classes you'll see in the RTS document.\n[asset_class.name for asset_class in rts2_annex3.class_root.asset_classes]\n\n# Each asset class is broken down into Sub-asset classes. \n# So now we take the FX Derivatives asset class and display the names of \n# its children, the sub-asset classes.\nfx_asset_class = rts2_annex3.class_root.asset_class_by_name('Foreign Exchange Derivatives')\n[sub_asset_class.name for sub_asset_class in fx_asset_class.children]\n\n# Each sub-asset class has a number of criteria.\n# Here we ask the Deliverable FX Options sub-asset class to list its\n# criteria:\nfx_do_sub_asset_class = fx_asset_class.sub_asset_class_by_name('Deliverable FX options (DO)')\n[criterion.description for criterion in fx_do_sub_asset_class.criteria]",
"Viewing the RTS 2 taxonomy using ipywidgets\nIf you are running this notebook on a live Jupyter server then you can run the code below to display widgets which let you navigate the RTS 2 taxonomy.\nYou can select an asset class in a drop-down widget. This then populates the sub-asset classes drop-down widget for the selected asset class. Selecting a sub-asset class causes the criteria for that sub-asset class to be displayed.\nHere is a screen shot of how the widgets look in action. In this example I have selected Energy Commodity Swaps which has seven criteria:",
"import rts2_annex3\nimport collections\nimport ipywidgets as widgets\nfrom IPython.display import display\n\nasset_classes = rts2_annex3.class_root.asset_classes\nasset_class_dict = collections.OrderedDict([\n (an_asset_class.name, an_asset_class) \n for an_asset_class \n in asset_classes])\n\nasset_class_widget = widgets.Dropdown(\n options=asset_class_dict,\n description='Asset Classes:',\n disabled=False,\n)\n\ndef sub_asset_class_dict(asset_class):\n return collections.OrderedDict([\n (sub_asset_class.name, sub_asset_class) \n for sub_asset_class \n in asset_class.sub_asset_classes])\n\nsub_asset_class_widget = widgets.Dropdown(\n options=sub_asset_class_dict(asset_class_widget.value),\n description='Sub-asset Classes:',\n disabled=False,\n)\n\ncriteria_vbox = widgets.VBox([])\n\ndef criteria_widgets(sub_asset_class):\n # OK, in here I need to look up the criteria for the\n # sub-asset class and build the widgets in rows of HBox es\n return [widgets.Label(criterion.display(prefix=\"\"))\n for criterion\n in sub_asset_class.criteria]\n \ndef asset_class_changed(change):\n if change['type'] == 'change' and change['name'] == 'value':\n selected_asset_class = change['new']\n sub_asset_class_widget.options = sub_asset_class_dict(selected_asset_class)\n \ndef sub_asset_class_changed(change):\n if change['type'] == 'change' and change['name'] == 'value':\n selected_sub_asset_class = change['new']\n criteria_vbox.children = criteria_widgets(selected_sub_asset_class)\n\nasset_class_widget.observe(asset_class_changed)\nsub_asset_class_widget.observe(sub_asset_class_changed)\ndisplay(asset_class_widget)\ndisplay(sub_asset_class_widget)\ncriteria_vbox.children = criteria_widgets(sub_asset_class_widget.value)\ndisplay(criteria_vbox)\n",
"Viewing the RTS 2 Annex 3 taxonomy as a tree\nThe following code walks the RTS 2 Annex 3 taxonomy building up a string which presents the taxonomy as a tree, in the same kind of way that nested file folders on a computer could be shown as a tree.\nThe names are all trimmed to 50 characters just to force each item onto a single line.",
"import rts2_annex3\nfrom IPython.display import display\n\nmax_name_length = 50\ntarget_string = ''\nroot = rts2_annex3.class_root\ntarget_string += 'Root\\n'\nfor asset_class in root.asset_classes:\n target_string += ' Asset class: \"' + asset_class.name + '\"\\n'\n for sub_asset_class in asset_class.children:\n target_string += ' Sub-asset class: \"' \\\n + sub_asset_class.name[:max_name_length] \\\n + '\"\\n'\n for criterion in sub_asset_class.criteria:\n target_string += ' Critrion: ' \\\n + str(criterion.criterion_number) \\\n + ' \"' \\\n + criterion.description[:max_name_length] \\\n + '\"\\n'\n\nprint(\"\\nDon't forget, all strings have been trimmed to {limit} characters! ... \\n\".format(\n limit=max_name_length))\nprint(target_string)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
GoogleCloudPlatform/training-data-analyst
|
courses/ai-for-time-series/notebooks/02-model.ipynb
|
apache-2.0
|
[
"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"Overview\nThis notebook demonstrates how to sequence data for a time-series problem, and then how to build deep learning and statistical models.\nDataset\nCTA - Ridership - Daily Boarding Totals: This dataset shows systemwide boardings for both bus and rail services provided by Chicago Transit Authority, dating back to 2001.\nObjective\nThe goal is to forecast future transit ridership in the City of Chicago, based on previous ridership.\nInstall packages and dependencies\nRestarting the kernel may be required to use new packages.",
"%pip install -U statsmodels scikit-learn --user",
"Note: To restart the Kernel, navigate to Kernel > Restart Kernel... on the Jupyter menu.\nImport libraries and define constants",
"import os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport warnings\n\nfrom google.cloud import storage\nfrom pandas.plotting import register_matplotlib_converters\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_absolute_percentage_error, mean_squared_error\nfrom sklearn.preprocessing import StandardScaler\nfrom statsmodels.tsa.holtwinters import ExponentialSmoothing\nfrom statsmodels.tools.sm_exceptions import ConvergenceWarning\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.layers import Conv1D, Dense, Dropout, Flatten, LSTM, MaxPooling1D\n\nregister_matplotlib_converters() # Address warning\n\n# Enter your project, region, and a bucket name. Then run the cell to make sure the\n# Cloud SDK uses the right project for all the commands in this notebook.\n\nPROJECT = 'your-project-name' # REPLACE WITH YOUR PROJECT ID\nBUCKET = 'your-bucket-name' # REPLACE WITH A UNIQUE BUCKET NAME e.g. your PROJECT NAME\nREGION = 'us-central1' # REPLACE WITH YOUR BUCKET REGION e.g. us-central1\nBUCKET_URI = 'gs://' + BUCKET\n\n#Don't change the following command - this is to check if you have changed the project name above.\nassert PROJECT != 'your-project-name', 'Don''t forget to change the project variables!'\n\n# Dataset parameters\n\ntarget_col = 'total_rides' # The variable you are predicting\nts_col = 'service_date' # The name of the column with the date field\n\n# Model parameters\n\nfreq = 'D' # Daily frequency\nn_input_steps = 30 # Lookback window\nn_output_steps = 7 # How many steps to predict forward\nn_seasons = 7 # Monthly periodicity\n\ntrain_split = 0.8 # % Split between train/test data\nepochs = 1000 # How many passes through the data (early-stopping will cause training to stop before this)\npatience = 5 # Terminate training after the validation loss does not decrease after this many epochs",
"Create a Cloud Storage bucket\nThe following steps are required, regardless of your notebook environment.\nWhen you submit a training job using the Cloud SDK, you upload a Python package\ncontaining your training code to a Cloud Storage bucket. AI Platform runs\nthe code from this package. In this tutorial, AI Platform also saves the\ntrained model that results from your job in the same bucket. You can then\ncreate an AI Platform model version based on this output in order to serve\nonline predictions.",
"storage_client = storage.Client()\ntry:\n bucket = storage_client.get_bucket(BUCKET)\n print('Bucket exists, let''s not recreate it.')\nexcept:\n bucket = storage_client.create_bucket(BUCKET)\n print('Created bucket: ' + BUCKET)",
"Load data",
"processed_file = 'cta_ridership.csv' # Which file to save the results to\n\nif os.path.exists(processed_file):\n input_file = processed_file # File created in previous lab\nelse:\n input_file = f'data/{processed_file}'\n\n# Read data\n\ndf = pd.read_csv(input_file, index_col=ts_col, parse_dates=True)\ndf.index.freq = freq\n\ndf.head()\n\n# Define some characteristics of the data that will be used later\nn_features = len(df.columns)\n\n# Index of target column. Used later when creating dataframes.\ntarget_col_num = df.columns.get_loc(target_col)\n\n# Split data\nsize = int(len(df) * train_split)\ndf_train, df_test = df[0:size].copy(deep=True), df[size:len(df)].copy(deep=True)\n\ndf_train.head()",
"TODO 1: Remove outliers\n\nSometimes, you can improve the accuracy of the model by removing outliers.\nIn this lab, you'll simply remove some extremely high values.\nYou can also apply techniques such as smoothing or resampling the frequency to reduce the impact of outliers.",
"df_train\n\n# Look at the highest peak. What level could you set a threshold that would clip this off?\n\n_=sns.lineplot(data=df_train[target_col]) \n\n# Hint: here are the top 5 values\n\ndf[target_col].sort_values(ascending=False).head()\n\n# TODO: Update the threshold below to remove the outliers\n\nthreshold = -1 # Set this just below the level you are seeing peaks. It will flag any values above it.\nassert threshold != -1, 'Set the threshold to the minimum that will eliminate outlier(s)'\n\n# Set any values above the threshold to NaN (not a number)\ndf_train.loc[df_train[target_col] > threshold, target_col] = np.nan\n\n# Interpolate the missing values (e.g. [3, NaN, 5] becomes [3, 4, 5])\ndf_train = df_train.interpolate()\n\n# Review the updated chart to see if outliers still exist\n# NOTE: If you set the threshold too low, rerun starting from the \n\n_=sns.lineplot(data=df_train[target_col])",
"Utility functions\nThe Utility functions section does not need thorough review.\nFunctions such as scaling variables, creating a time-series sequence, etc. are provided here.\nScale the inputs and outputs",
"# For neural networks to converge quicker, it is helpful to scale the values.\n# For example, each feature might be transformed to have a mean of 0 and std. dev. of 1.\n#\n# You are working with a mix of features, input timesteps, output horizon, etc.\n# which don't work out-of-the-box with common scaling utilities.\n# So, here are a couple wrappers to handle scaling and inverting the scaling.\n\nfeature_scaler = StandardScaler()\ntarget_scaler = StandardScaler()\n\ndef scale(df, \n fit=True, \n target_col=target_col,\n feature_scaler=feature_scaler,\n target_scaler=target_scaler):\n \"\"\"\n Scale the input features, using a separate scaler for the target.\n \n Parameters: \n df (pd.DataFrame): Input dataframe\n fit (bool): Whether to fit the scaler to the data (only apply to training data)\n target_col (pd.Series): The column that is being predicted\n feature_scaler (StandardScaler): Scaler used for features\n target_scaler (StandardScaler): Scaler used for target\n \n Returns: \n df_scaled (pd.DataFrame): Scaled dataframe \n \"\"\" \n \n target = df[target_col].values.reshape(-1, 1)\n if fit:\n target_scaler.fit(target)\n target_scaled = target_scaler.transform(target)\n \n # Select all columns other than target to be features\n features = df.loc[:, df.columns != target_col].values\n \n if features.shape[1]: # If there are any features\n if fit:\n feature_scaler.fit(features)\n features_scaled = feature_scaler.transform(features)\n \n # Combine target and features into one data frame\n df_scaled = pd.DataFrame(features_scaled)\n target_col_num = df.columns.get_loc(target_col)\n df_scaled.insert(target_col_num, target_col, target_scaled)\n df_scaled.columns = df.columns \n \n else: # If only target column (no additional features)\n df_scaled = pd.DataFrame(target_scaled, columns=df.columns)\n \n return df_scaled\n\ndef inverse_scale(data, target_scaler=target_scaler):\n \"\"\"\n Transform the scaled values of the target back into their original form.\n The features are left alone, as we're assuming that the output of the model only includes the target.\n \n Parameters: \n data (np.array): Input array\n target_scaler (StandardScaler): Scaler used for target\n \n Returns: \n data_scaled (np.array): Scaled array \n \"\"\" \n \n df = pd.DataFrame()\n data_scaled = np.empty([data.shape[1], data.shape[0]])\n for i in range(data.shape[1]):\n data_scaled[i] = target_scaler.inverse_transform([data[:,i]])\n return data_scaled.transpose()\n\ndf_train_scaled=scale(df_train)\ndf_test_scaled=scale(df_test, False)",
"Create sequences of time-series data",
"def reframe(data, n_input_steps = n_input_steps, n_output_steps = n_output_steps, target_col = target_col):\n\n target_col_num = data.columns.get_loc(target_col) \n \n # Iterate through data and create sequences of features and outputs\n df = pd.DataFrame(data)\n cols=list()\n for i in range(n_input_steps, 0, -1):\n cols.append(df.shift(i))\n for i in range(0, n_output_steps):\n cols.append(df.shift(-i))\n \n # Concatenate values and remove any missing values\n df = pd.concat(cols, axis=1)\n df.dropna(inplace=True)\n \n # Split the data into feature and target variables\n n_feature_cols = n_input_steps * n_features\n features = df.iloc[:,0:n_feature_cols]\n target_cols = [i for i in range(n_feature_cols + target_col_num, n_feature_cols + n_output_steps * n_features, n_features)]\n targets = df.iloc[:,target_cols]\n\n return (features, targets)\n\nX_train_reframed, y_train_reframed = reframe(df_train_scaled)\nX_test_reframed, y_test_reframed = reframe(df_test_scaled)",
"Evaluate results",
"def print_stats(timestep, y_true, y_pred, target_col, chart=True, table=False, dec=3):\n '''\n Helper function to print overall summary statistics and stats for each time step\n '''\n \n # Print summary statistics\n print('=== t+' + str(timestep) + ' ===')\n print('R^2: ' + str(np.round(r2_score(y_true, y_pred), dec)))\n print('MAPE: ' + str(np.round(mean_absolute_percentage_error(y_true, y_pred), dec)))\n print('MAE: ' + str(np.round(mean_absolute_error(y_true, y_pred), dec)))\n print('')\n\n df_y_true = pd.DataFrame(y_true)\n df_y_true[target_col + '_pred'] = np.round(y_pred, dec)\n \n # Show plot of actuals vs predictions and a sample of values\n if table:\n print(str(df_y_true.head(5)) + '\\n')\n print(str(df_y_true.tail(5)) + '\\n')\n if chart:\n sns.lineplot(data=df_y_true[[target_col, target_col+'_pred']])\n plt.show()\n \ndef evaluate(y_pred,\n exclude_timesteps=n_input_steps,\n y_true=df_test,\n target_col=target_col):\n '''\n Helper function to transform predictions to match size and indices of actuals.\n \n For example, n_timesteps from the test data will be required to make a prediction,\n so the number of predictions will be fewer than the number of test samples.\n \n Parameters:\n y_pred (np.array): Predictions\n exclude_timesteps (int): Number of leading timesteps to trim from the dataset\n y_true (pd.DataFrame): Actuals\n '''\n \n # Number of outputs (future timesteps)\n outputs = y_pred.shape[1]\n \n target_col_num = df.columns.get_loc(target_col)\n \n # Lists of actual and predicted values for each time step\n # For example, y_true_eval[2] will contain actual values 3 time steps out\n # These specific lists enable computing the accuracy for specific time steps\n y_true_eval, y_pred_eval = list(), list()\n\n # Actual and predicted values combined across all time steps (to compute overall accuracy metrics)\n y_true_all, y_pred_all = np.array([]), np.array([])\n \n # Append entries to lists for each output timestep\n for t in range(outputs):\n if exclude_timesteps:\n y_true_eval.append(y_true[exclude_timesteps+t:len(y_true)-outputs+t+1].copy())\n y_pred_eval.append(y_pred[:,t]) \n else:\n y_true_eval.append(y_true[t:].copy())\n y_pred_eval.append(y_pred[:-1*t-1,t])\n # Append the output values to the combined lists\n y_true_all = np.concatenate([y_true_all, y_true_eval[t].values[:,target_col_num]], axis=0)\n y_pred_all = np.concatenate([y_pred_all, y_pred_eval[t]], axis=0)\n\n # Print aggregate statistics across all time steps (only if predicting multiple time steps)\n if outputs > 1:\n print_stats('(1-' + str(outputs) + ')', y_true_all, y_pred_all, target_col, False)\n\n # Print stats for each future time step\n for t in range(outputs): \n print_stats(t+1, y_true_eval[t][target_col], y_pred_eval[t], target_col, True)",
"ML Models\nIn this section, you will build models using popular neural network architectures for time-series data.\nLong Short Term Memory (LSTM)",
"# Reshape test data to match model inputs and outputs\n\nX_train = X_train_reframed.values.reshape(-1, n_input_steps, n_features)\nX_test = X_test_reframed.values.reshape(-1, n_input_steps, n_features)\ny_train = y_train_reframed.values.reshape(-1, n_output_steps, 1)\ny_test = y_test_reframed.values.reshape(-1, n_output_steps, 1)",
"TODO 2: Update the LSTM architecture\nTry increasing and decreasing the number of LSTM units and see if you notice any accuracy improvements.\nYou can use hyper-parameter tuning to search for optimal values, but that's outside the scope of this lab.",
"# Try increasing and decreasing the number of LSTM units and see if you notice any accuracy improvements.\n# Run the next cell to evaluate the results in more detail.\n\nmodel = Sequential([\n LSTM(64, input_shape=[n_input_steps, n_features]),\n Dense(n_output_steps)])\n\nmodel.compile(optimizer='adam', loss='mae')\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=patience)\n_ = model.fit(x=X_train, y=y_train, validation_data=(X_test, y_test), epochs=epochs, callbacks=[early_stopping])\n\nmodel.save('./lstm_export/')\n\n# Predict the results, and then reverse the transformation that scaled all values to a mean of 0 and std. dev. of 1\npreds = model.predict(X_test)\ny_pred_lstm = inverse_scale(preds)\n\n# Evaluate the overall results and for each time step\nevaluate(y_pred_lstm)\n\n# The plot will show the R^2 value (0 lowest -> 1 highest) and the MAE (mean absolute error) for the entire prediction window.\n# It will also show individual plots for 1 day out, 2 days out, etc. comparing the actual vs the predicted value.",
"Convolutional Neural Network (CNN)\nTODO 3: Update the CNN architecture\nTry adjusting the # of filters (pattern types) and kernel size (size of the sliding window)",
"from tensorflow.keras.layers import AveragePooling1D\n\n# TODO: Try adjusting the # of filters (pattern types) and kernel size (size of the sliding window)\nmodel = Sequential([\n Conv1D(filters=32, kernel_size=3, input_shape=[n_input_steps, n_features]),\n Flatten(),\n Dense(n_output_steps)])\n\nmodel.compile(optimizer='adam', loss='mae')\n\nearly_stopping = EarlyStopping(monitor='val_loss', patience=5)\n_ = model.fit(x=X_train, y=y_train, validation_data=(X_test, y_test), epochs=epochs, callbacks=[early_stopping])\n\nmodel.save('./cnn_export/')\n\npreds = model.predict(X_test)\ny_pred_cnn = inverse_scale(preds)\n\nevaluate(y_pred_cnn)",
"Naïve Models\nSo-called \"naïve models\" can be surprisingly hard to beat. These can serve as a useful benchmark for your model's performance.\nRandom Walk\nAssume that future value(s) will be the same as the most recent value.",
"from statsmodels.tsa.arima.model import ARIMA\n\nhist = df_train[target_col].copy() # Predict based on historical data. Start with the training data\nhist.index.freq = pd.infer_freq(hist.index) # To avoid warnings, explicitly specify the dataframe frequency\nn_pred = len(df_test) + 1 # Number of predictions: 1 on the training set; and then 1 for each additional \ny_pred_rw = np.empty([n_pred,n_output_steps]) # Create an array to hold predictions, with a number of predictions equal to the test set size, each containing the # of time steps you are predicting forward.\n\nfor t in range(n_pred):\n mod = ARIMA(hist, order=(0, 1, 0))\n res = mod.fit()\n pred = res.forecast(n_output_steps)\n y_pred_rw[t] = pred.values\n if t < n_pred - 1:\n hist.loc[df_test.iloc[t].name] = df_test[target_col][t] # Append the latest test data row to the history, for fitting the next model\n hist.index.freq = pd.infer_freq(hist.index)\n\nevaluate(y_pred_rw, 0)",
"Seasonal Naïve\nSimilar to random walk, but instead of using the previous value, you'll use the value from the previous seasonal period. For example, if you're predicting July's forecast, you'll use last July's value, rather than June's value.",
"# You will use a walk-forward approach, in which a model is fit on all historical data available.\n# As you progress through the test set to evaluate the model, you will be creating new models for each row in the test set.\n# Each new model will be fit on not only the training data, but on prior test data.\n\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\n\nhist = df_train[target_col].copy() # Predict based on historical data. Start with the training data\nhist.index.freq = pd.infer_freq(hist.index) # To avoid warnings, explicitly specify the dataframe frequency\nn_pred = len(df_test) + 1 # Number of predictions: 1 on the training set; and then 1 for each additional \ny_pred_sn = np.empty([n_pred,n_output_steps]) # Create an array to hold predictions, with a number of predictions equal to the test set size, each containing the # of time steps you are predicting forward.\n\nfor t in range(n_pred):\n mod = SARIMAX(hist, order=(0, 0, 0), seasonal_order=(0, 1, 0, n_seasons))\n res = mod.fit(disp=False)\n pred = res.forecast(n_output_steps)\n y_pred_sn[t] = pred.values\n if t < n_pred - 1:\n hist.loc[df_test.iloc[t].name] = df_test[target_col][t] # Append the latest test data row to the history, for fitting the next model\n hist.index.freq = pd.infer_freq(hist.index)\n\nevaluate(y_pred_sn, 0)",
"Statistical Models\nYou will next implement a popular statistical method for time-series analysis, exponential smoothing. Exponential smoothing estimates future data by weighting recent observations more heavily. The Holt-Winters exponential smoothing method used here uses a \"triple\" exponential smoothing approach that also considers trend and seasonality.\nYou can also ensemble classical and machine learning methods for a potentially even more accurate result.\nExponential Smoothing",
"with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=ConvergenceWarning)\n\n# You will use a walk-forward approach, in which a model is fit on all historical data available.\n# As you progress through the test set to evaluate the model, you will be creating new models for each row in the test set.\n# Each new model will be fit on not only the training data, but on prior test data.\n\nhist = df_train[target_col].copy() # Predict based on historical data. Start with the training data\nhist.index.freq = pd.infer_freq(hist.index) # To avoid warnings, explicitly specify the dataframe frequency\nn_pred = len(df_test) + 1 # Number of predictions: 1 on the training set; and then 1 for each additional \ny_pred_es = np.empty([n_pred,n_output_steps]) # Create an array to hold predictions, with a number of predictions equal to the test set size, each containing the # of time steps you are predicting forward.\n\nfor t in range(n_pred):\n mod = ExponentialSmoothing(hist, seasonal_periods=n_seasons, trend='add', seasonal='add', damped_trend=True, use_boxcox=False, initialization_method='heuristic')\n res = mod.fit(method='L-BFGS-B') # Use a different minimizer to avoid convergence warnings\n pred = res.forecast(n_output_steps)\n y_pred_es[t] = pred.values\n if t < n_pred - 1:\n hist.loc[df_test.iloc[t].name] = df_test[target_col][t] # Append the latest test data row to the history, for fitting the next model\n hist.index.freq = pd.infer_freq(hist.index)\n\nevaluate(y_pred_es, 0)",
"Ensemble ML and Statistical Models\nIf the performance of the ML and statistical models are similar, ensembling them can be helpful, because their approaches are quite different.",
"# Start by adjusting the sizes of the prediction arrays to match.\n# Some methods predict the initial timesteps of the test set.\n# Others start after the first sequence length.\n# So, you will remove the test data that doesn't exist in both sets.\n\ndef trunc(df, test_set=df_test, n_input_steps = n_input_steps, n_output_steps = n_output_steps):\n return df[n_input_steps: -n_output_steps]\n\ny_pred_es_trunc = trunc(y_pred_es)\ny_true_trunc = trunc(df_test)\n\nmodels = [y_pred_lstm, y_pred_cnn, y_pred_es_trunc]\nweights = [2, 1, 1]\n\ny_pred_ensemble = np.average( np.array(models), axis=0, weights=weights)\n\nevaluate(y_pred_ensemble, 0, y_true_trunc)",
"Conclusion\nGreat job! You've now completed the modeling portion of this workshop. You've covered:\n* Removing outliers from the data\n* Multi-step forecasting\n* Neural network architectures for time-series forecasting: LSTM and CNN\n* Statistical models, including Holt-Winters Exponential Smoothing \n* Ensembling models"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
probml/pyprobml
|
notebooks/misc/logreg_tpu_pytorch_lightning_bolts.ipynb
|
mit
|
[
"<a href=\"https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/logreg_tpu_pytorch_lightning_bolts.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\nLogistic regression on MNIST using TPUs and PyTorch Lightning\nCode is from \nhttps://lightning-bolts.readthedocs.io/en/latest/introduction_guide.html#logistic-regression\nSetup TPU\nBe sure to select Runtime=TPU in the drop-down menu!\nSee\nhttps://colab.sandbox.google.com/github/pytorch/xla/blob/master/contrib/colab/getting-started.ipynb#scrollTo=3P6b3uqfzpDI\nSee also \nhttps://pytorch-lightning.readthedocs.io/en/latest/notebooks/lightning_examples/cifar10-baseline.html#",
"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport os\n\nassert os.environ[\"COLAB_TPU_ADDR\"], \"Make sure to select TPU from Edit > Notebook settings > Hardware accelerator\"\n\n\n#!pip install -q cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.8-cp37-cp37m-linux_x86_64.whl\n\n!pip install -q cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.9-cp37-cp37m-linux_x86_64.whl",
"Setup lightning",
"#!pip install -q lightning-bolts\n!pip install --quiet torchmetrics lightning-bolts torchvision torch pytorch-lightning\n\nfrom pl_bolts.models.regression import LogisticRegression\nimport pytorch_lightning as pl\n\nfrom pl_bolts.datamodules import MNISTDataModule, FashionMNISTDataModule, CIFAR10DataModule, ImagenetDataModule",
"Iris",
"from sklearn.datasets import load_iris\nfrom pl_bolts.datamodules import SklearnDataModule\nimport pytorch_lightning as pl\n\n# use any numpy or sklearn dataset\nX, y = load_iris(return_X_y=True)\ndm = SklearnDataModule(X, y, batch_size=12)\n\n# build model\nmodel = LogisticRegression(input_dim=4, num_classes=3)\n\n# fit\ntrainer = pl.Trainer(tpu_cores=8)\ntrainer.fit(model, train_dataloader=dm.train_dataloader(), val_dataloaders=dm.val_dataloader())\n\ntrainer.test(test_dataloaders=dm.test_dataloader())",
"CIFAR",
"# create dataset\n# dm = MNISTDataModule(num_workers=0, data_dir='data')\ndm = CIFAR10DataModule(num_workers=0, data_dir=\"data\")\ndm.prepare_data() # force download now\n\nprint(dm.size())\nprint(dm.num_classes)\nndims = np.prod(dm.size())\nnclasses = dm.num_classes\nprint([ndims, nclasses, ndims * nclasses])\n\nmodel = LogisticRegression(input_dim=ndims, num_classes=nclasses, learning_rate=0.001)\nprint(model)\n\ntrainer = pl.Trainer(tpu_cores=8, max_epochs=2)\n# trainer = pl.Trainer(max_epochs=2)\ntrainer.fit(model, datamodule=dm)\n\ntrainer.test(model, test_dataloaders=dm.val_dataloader())"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
KasperPRasmussen/bokeh
|
examples/howto/charts/deep_dive.ipynb
|
bsd-3-clause
|
[
"Bokeh Charts Deep Dive\nCharts Purpose\nCharts provides a few things, but the core purpose is to help you understand your data by separating it into unique visual groups before you know what those groups are.\nWhat Charts ultimately does is build Glyph Renderers to represent the groups of data and add them to a Chart.\nIt does this by adapting data into a consistent format, understanding metadata about the specific chart, deriving the unique groups of data based on the chart configuration, then assigning attributes to each group.\nOutline\nThe topics covered in this deep dive are:\n\nData - a consistent chart metadata-aware data structure for charts\nAttributes - fault resistant assignment of chart attributes to distinct groups of data\nBuilders - glyph renderer factories (data driven glyphs)\nNew Charts - how to build custom charts\n\n\nData\nThe Charts interface is built around the use of a table data structure, pandas. There are a few primary reasons for doing this.\n\nOther smart people have already considered how a graphics system would work on this type of data (Grammar of Graphics)\nA typical analyst will likely encounter data that is in this format, or can easily be transformed into it.\nThe table data structure can provide useful information about the data, which aids in building the chart\nInteractive app generation can be greatly simplified",
"import pandas as pd\nfrom bokeh.charts import Scatter, show, output_notebook\noutput_notebook()",
"What is table-like data?\nData that contains like data grouped and labeled by a column and new records listed as rows, or data that can be inferred into this format. This format is pretty flexible and an analyst will commonly encounter this format in databases, so we will go further into certain styles of structuring the data and the reasoning behind them.\nWhen encountering databases, you will likely be accessing one to many tables, joining them, then performing some exploratory analysis. This joined dataset will likely contain columns with dates and strings that describe the values in the record. These columns which uniquely identify the columns that contain numerical measurements are often called dimensions, and the numerical measurements are called values.\nFormats Transformed",
"from bokeh.charts.data_source import ChartDataSource",
"Array (list/pd.series/np.array)\nArrays are assumed to be like values that would be assigned to a column. Passing in Chart([1, 2], [3, 4]) would be creating the following data source internally for the chart to use:",
"ds = ChartDataSource.from_data([1, 2], [3, 4])\nds.df.head()",
"In cases where there isn't enough metadata, column names will be automatically assigned to the array-like data in order received.\nRecord Data\nThis data would be encountered more when dealing with json data, or serialized objects.",
"records = [\n {'name': 'bob', 'age': 25},\n {'name': 'susan', 'age': 22}\n]\n\nds = ChartDataSource.from_data(records)\nds.df.head()",
"Structuring Data\nExample:\nImagine we had some sample data. The data is sampled over time at two different weather stations, each with a status raining. The sampled values are temperature. Dimensions are in italics and values are bolded. We will look at two different approaches to storing this data.\nFor the example we will assume the two weather stations each record a temperature on three different days, where it is raining on the first day for station a, and the second day for station b.\nTall Data\n(preferred format for Charts)\nTable-like data can be thought of as observations about the world or some process or system. As new observations are added, you will want to add new rows, and avoid having to add new columns, because you must carefully consider all other rows when that occurs.\nFor the example, a tall data source will minimize the number of columns that contain like information. For Tall data, the format will be the following:",
"data = dict(sample_time=['2015-12-01', '2015-12-02', '2015-12-03', '2015-12-01', '2015-12-02', '2015-12-03'],\n temperature=[68, 67, 77, 45, 50, 43],\n location=['station a', 'station a', 'station a', 'station b', 'station b', 'station b'],\n raining=[True, False, False, False, True, False]\n )\ntall = pd.DataFrame(data)\ntall.head()",
"Wide Data\n(supported for some Charts, or with transformations)\nIt is often in scientific use cases or in pivoted data that you will find where multiple columns contain the same class of measurement. For instance, when sampling temperature for two weather stations, wide data would contain the weather_station dimension encoded into the column names. This is simple if we only have temperature data.",
"data = dict(sample_time=['2015-12-01', '2015-12-02', '2015-12-03'],\n station_a_temp=[68, 67, 77],\n station_b_temp=[45, 50, 43]\n )\nwide = pd.DataFrame(data)\nwide.head()\n",
"However, if we need to add the raining flag, we must add two new columns, because the flag can be different between the two stations, and the columns are containing the station dimension.",
"data['station_a_raining'] = [True, False, False]\ndata['station_b_raining'] = [False, False, False]\n\nwide = pd.DataFrame(data)\nwide.head()",
"Why is Tall Data Preferred?\nTall data is better suited towards interactive analysis. While wide data is fine for simple data that can only be viewed against one or two dimensions, highly dimensional data will be much easier to use to reconfigure charts and/or adding new values.",
"tall_line1 = Scatter(tall, x='sample_time', y='temperature', color='location', legend=True)\ntall_line2 = Scatter(tall, x='sample_time', y='temperature', color='raining', legend=True)\n\nshow(tall_line1)\nshow(tall_line2)",
"Imagine if a new station was added. There are two problems with the wide data:\n\n\nMore modifications required to the data structure and function call.\n\nA value must be listed for all stations, no matter if there exists a sample for the date\nAny reference on the function to each station would require adding the new station name. This list of names could grow quite large and you may have columns that aren't stations, and aren't temperature measurements.\n\n\n\nDifficult to build interactive applications when required to reference multiple series. Must handle multiple selections for some of the fields, which adds complexity.\n\n\n\nTransforming Data\nThe ChartDataSource can process any Charts data transformations that are added when creating the chart.",
"from bokeh.charts import bins, blend\n\ndata = {\n 'temperature_a': [32, 23, 95, 90, 23, 58, 90],\n 'temperature_b': [45, 34, 23, 88, 67, 34, 23]\n}\n\nds = ChartDataSource.from_data(data, x=blend('temperature_a', 'temperature_b')) \n\nds.df.head()\n\nds = ChartDataSource.from_data(data, x=bins('temperature_a'))\n\nds.df.head()\n\nds = ChartDataSource.from_data(data, x=bins('temperature_a'), y=bins('temperature_b'))\n\nds.df.head()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
pagutierrez/tutorial-sklearn
|
notebooks-spanish/21-reduccion_dimensionalidad_no_lineal.ipynb
|
cc0-1.0
|
[
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np",
"Aprendizaje de variedades\nUna de las debilidades del PCA es que no puede detectar características no lineales. Un conjunto de algoritmos que evitan este problema son los algoritmos de aprendizaje de variedades (manifold learning). Un conjunto de datos que se suele emplear a menudo en este contexto es el S-curve:",
"from sklearn.datasets import make_s_curve\nX, y = make_s_curve(n_samples=1000)\n\nfrom mpl_toolkits.mplot3d import Axes3D\nax = plt.axes(projection='3d')\n\nax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y)\nax.view_init(10, -60);",
"Este es en realidad un conjunto de datos 2D (que sería la S desenrollada), pero se ha embebido en un espacio 3D, de tal forma que un PCA no es capaz de descubrir el conjunto de datos original",
"from sklearn.decomposition import PCA\nX_pca = PCA(n_components=2).fit_transform(X)\nplt.scatter(X_pca[:, 0], X_pca[:, 1], c=y);",
"Como puedes observar, al ser un método lineal, el PCA ha obtenido dos direcciones máxima variabilidad, pero ha perdido muchísima varianza en los datos, al proyectar la S directamente en un hiperplano. Los algoritmos de aprendizaje de variedades, disponibles en el paquete sklearn.manifold, pretenden descubrir el manifold que contiene a los datos (en este caso, es un manifold de dos dimensiones). Apliquemos, por ejemplo, el método Isomap:",
"from sklearn.manifold import Isomap\n\niso = Isomap(n_neighbors=15, n_components=2)\nX_iso = iso.fit_transform(X)\nplt.scatter(X_iso[:, 0], X_iso[:, 1], c=y);",
"Aprendizaje de variedades para la base de datos de dígitos\nPodemos aplicar este tipo de algoritmos para bases de datos de alta dimensionalidad, como la base de datos de dígitos manuscritos:",
"from sklearn.datasets import load_digits\ndigits = load_digits()\n\nfig, axes = plt.subplots(2, 5, figsize=(10, 5),\n subplot_kw={'xticks':(), 'yticks': ()})\nfor ax, img in zip(axes.ravel(), digits.images):\n ax.imshow(img, interpolation=\"none\", cmap=\"gray\")",
"Si visualizamos el dataset utilizando una técnica lineal como PCA, ya pudimos comprobar como conseguíamos algo de información sobre la estructura de los datos:",
"# Construir un modelo PCA\npca = PCA(n_components=2)\npca.fit(digits.data)\n# Transformar los dígitos según las dos primeras componentes principales\ndigits_pca = pca.transform(digits.data)\ncolors = [\"#476A2A\", \"#7851B8\", \"#BD3430\", \"#4A2D4E\", \"#875525\",\n \"#A83683\", \"#4E655E\", \"#853541\", \"#3A3120\",\"#535D8E\"]\nplt.figure(figsize=(10, 10))\nplt.xlim(digits_pca[:, 0].min(), digits_pca[:, 0].max() + 1)\nplt.ylim(digits_pca[:, 1].min(), digits_pca[:, 1].max() + 1)\nfor i in range(len(digits.data)):\n # Representar los dígitos usando texto\n plt.text(digits_pca[i, 0], digits_pca[i, 1], str(digits.target[i]),\n color = colors[digits.target[i]],\n fontdict={'weight': 'bold', 'size': 9})\nplt.xlabel(\"primera componente principal\")\nplt.ylabel(\"segunda componente principal\");",
"Sin embargo, podemos usar técnicas no lineales, que nos llevarán, en este caso, a una mejor visualización. Vamos a aplicar el método t-SNE de manifold learning:",
"from sklearn.manifold import TSNE\ntsne = TSNE(random_state=42)\n# utilizamos fit_transform en lugar de fit:\ndigits_tsne = tsne.fit_transform(digits.data)\n\nplt.figure(figsize=(10, 10))\nplt.xlim(digits_tsne[:, 0].min(), digits_tsne[:, 0].max() + 1)\nplt.ylim(digits_tsne[:, 1].min(), digits_tsne[:, 1].max() + 1)\nfor i in range(len(digits.data)):\n # actually plot the digits as text instead of using scatter\n plt.text(digits_tsne[i, 0], digits_tsne[i, 1], str(digits.target[i]),\n color = colors[digits.target[i]],\n fontdict={'weight': 'bold', 'size': 9})",
"t-SNE suele tardar más en ejecutarse que otros algoritmos de aprendizaje de variedades, pero el resultado suele ser muy bueno. Ten en cuenta que este algoritmo es no supervisado y no sabe nada sobre las etiquetas de los dígitos. Aún así, es capaz de separar muy bien las clases (aunque los dígitos 4, 1 y 9 se han subdividido en varios grupos).\n<div class=\"alert alert-success\">\n <b>EJERCICIO</b>:\n <ul>\n <li>\n Compara los resultados que se obtienen al aplicar Isomap, PCA y t-SNE a los dígitos manuscritos. ¿Qué algoritmo crees que lo hace mejor?\n </li>\n <li>\n Dado que t-SNE separa muy bien las clases, uno puede pensar en aplicarlo como preprocesamiento antes de un algoritmo de clasificación. Entrena un Knn en el dataset de los dígitos preprocesado con t-SNE y compara la precisión cuando lo hacemos sin preprocesamiento. Sin embargo, ten en cuenta que t-SNE no tiene método tranform y por tanto no se podría utilizar en producción.\n </li>\n </ul>\n</div>"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
mastertrojan/Udacity
|
language-translation/dlnd_language_translation.ipynb
|
mit
|
[
"Language Translation\nIn this project, you’re going to take a peek into the realm of neural network machine translation. You’ll be training a sequence to sequence model on a dataset of English and French sentences that can translate new sentences from English to French.\nGet the Data\nSince translating the whole language of English to French will take lots of time to train, we have provided you with a small portion of the English corpus.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport helper\nimport problem_unittests as tests\n\nsource_path = 'data/small_vocab_en'\ntarget_path = 'data/small_vocab_fr'\nsource_text = helper.load_data(source_path)\ntarget_text = helper.load_data(target_path)",
"Explore the Data\nPlay around with view_sentence_range to view different parts of the data.",
"view_sentence_range = (0, 10)\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\n\nprint('Dataset Stats')\nprint('Roughly the number of unique words: {}'.format(len({word: None for word in source_text.split()})))\n\nsentences = source_text.split('\\n')\nword_counts = [len(sentence.split()) for sentence in sentences]\nprint('Number of sentences: {}'.format(len(sentences)))\nprint('Average number of words in a sentence: {}'.format(np.average(word_counts)))\n\nprint()\nprint('English sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(source_text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))\nprint()\nprint('French sentences {} to {}:'.format(*view_sentence_range))\nprint('\\n'.join(target_text.split('\\n')[view_sentence_range[0]:view_sentence_range[1]]))",
"Implement Preprocessing Function\nText to Word Ids\nAs you did with other RNNs, you must turn the text into a number so the computer can understand it. In the function text_to_ids(), you'll turn source_text and target_text from words to ids. However, you need to add the <EOS> word id at the end of each sentence from target_text. This will help the neural network predict when the sentence should end.\nYou can get the <EOS> word id by doing:\npython\ntarget_vocab_to_int['<EOS>']\nYou can get other word ids using source_vocab_to_int and target_vocab_to_int.",
"def text_to_sentence_list(text): \n text_word = text.split('\\n')\n #print(text_word)\n return text_word\n\ndef words_to_ints(word_list, reference, source):\n int_list = []\n for sentence in word_list:\n temp = sentence.split()\n temp = ([word.replace(word, str(reference[word])) for word in temp])\n if source:\n temp.append(reference['<EOS>'])\n int_list.append(list(map(int, temp))) \n return int_list\n\ndef text_to_ids(source_text, target_text, source_vocab_to_int, target_vocab_to_int):\n \"\"\"\n Convert source and target text to proper word ids\n :param source_text: String that contains all the source text.\n :param target_text: String that contains all the target text.\n :param source_vocab_to_int: Dictionary to go from the source words to an id\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :return: A tuple of lists (source_id_text, target_id_text)\n \"\"\"\n source_id_text = text_to_sentence_list(source_text)\n #print(source_text)\n source_id_text = words_to_ints(source_id_text, source_vocab_to_int, False)\n #print(source_id_text)\n \n target_id_text = text_to_sentence_list(target_text)\n target_id_text = words_to_ints(target_id_text, target_vocab_to_int, True)\n\n # TODO: Implement Function\n return source_id_text, target_id_text\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_text_to_ids(text_to_ids)",
"Preprocess all the data and save it\nRunning the code cell below will preprocess all the data and save it to file.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nhelper.preprocess_and_save_data(source_path, target_path, text_to_ids)",
"Check Point\nThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport numpy as np\nimport helper\n\n(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()",
"Check the Version of TensorFlow and Access to GPU\nThis will check to make sure you have the correct version of TensorFlow and access to a GPU",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nfrom distutils.version import LooseVersion\nimport warnings\nimport tensorflow as tf\n\n# Check TensorFlow Version\nassert LooseVersion(tf.__version__) in [LooseVersion('1.0.0'), LooseVersion('1.0.1')], 'This project requires TensorFlow version 1.0 You are using {}'.format(tf.__version__)\nprint('TensorFlow Version: {}'.format(tf.__version__))\n\n# Check for a GPU\nif not tf.test.gpu_device_name():\n warnings.warn('No GPU found. Please use a GPU to train your neural network.')\nelse:\n print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))",
"Build the Neural Network\nYou'll build the components necessary to build a Sequence-to-Sequence model by implementing the following functions below:\n- model_inputs\n- process_decoding_input\n- encoding_layer\n- decoding_layer_train\n- decoding_layer_infer\n- decoding_layer\n- seq2seq_model\nInput\nImplement the model_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders:\n\nInput text placeholder named \"input\" using the TF Placeholder name parameter with rank 2.\nTargets placeholder with rank 2.\nLearning rate placeholder with rank 0.\nKeep probability placeholder named \"keep_prob\" using the TF Placeholder name parameter with rank 0.\n\nReturn the placeholders in the following the tuple (Input, Targets, Learing Rate, Keep Probability)",
"def model_inputs():\n \"\"\"\n Create TF Placeholders for input, targets, and learning rate.\n :return: Tuple (input, targets, learning rate, keep probability)\n \"\"\"\n # TODO: Implement Function\n input = tf.placeholder(tf.int32, [None, None], name=\"input\")\n targets = tf.placeholder(tf.int32, [None, None])\n learning_rate = tf.placeholder(tf.float32)\n keep_prob = tf.placeholder(tf.float32, name=\"keep_prob\")\n return input, targets, learning_rate, keep_prob\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_model_inputs(model_inputs)",
"Process Decoding Input\nImplement process_decoding_input using TensorFlow to remove the last word id from each batch in target_data and concat the GO ID to the beginning of each batch.",
"def process_decoding_input(target_data, target_vocab_to_int, batch_size):\n \"\"\"\n Preprocess target data for decoding\n :param target_data: Target Placeholder\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :param batch_size: Batch Size\n :return: Preprocessed target data\n \"\"\"\n ending = tf.strided_slice(target_data, [0, 0], [batch_size, -1], [1, 1])\n dec_input = tf.concat([tf.fill([batch_size, 1], target_vocab_to_int['<GO>']), ending], 1)\n \n # print(target_data, target_vocab_to_int, batch_size)\n # TODO: Implement Function\n return dec_input\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_process_decoding_input(process_decoding_input)",
"Encoding\nImplement encoding_layer() to create a Encoder RNN layer using tf.nn.dynamic_rnn().",
"def encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob):\n \"\"\"\n Create encoding layer\n :param rnn_inputs: Inputs for the RNN\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param keep_prob: Dropout keep probability\n :return: RNN state\n \"\"\" \n # Encoder embedding\n #print(rnn_inputs, rnn_size, num_layers)\n #enc_embed_input = tf.contrib.layers.embed_sequence(rnn_inputs, rnn_size, num_layers)\n # Encoder\n \n enc_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)\n _, enc_state = tf.nn.dynamic_rnn(enc_cell, rnn_inputs, dtype=tf.float32)\n # TODO: Implement Function\n return enc_state\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_encoding_layer(encoding_layer)",
"Decoding - Training\nCreate training logits using tf.contrib.seq2seq.simple_decoder_fn_train() and tf.contrib.seq2seq.dynamic_rnn_decoder(). Apply the output_fn to the tf.contrib.seq2seq.dynamic_rnn_decoder() outputs.",
"def decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope,\n output_fn, keep_prob):\n \"\"\"\n Create a decoding layer for training\n :param encoder_state: Encoder State\n :param dec_cell: Decoder RNN Cell\n :param dec_embed_input: Decoder embedded input\n :param sequence_length: Sequence Length\n :param decoding_scope: TenorFlow Variable Scope for decoding\n :param output_fn: Function to apply the output layer\n :param keep_prob: Dropout keep probability\n :return: Train Logits\n \"\"\"\n \n# train_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_train(enc_state)\n# train_pred, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(\n# dec_cell, train_decoder_fn, dec_embed_input, sequence_length, scope=decoding_scope)\n \n# # Apply output function\n# train_logits = output_fn(train_pred)\n \n train_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_train(encoder_state)\n train_pred, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, train_decoder_fn, dec_embed_input, \n sequence_length, scope=decoding_scope)\n \n #apply output_fn to tf.contrib.seq2seq.dynamic_rnn_decoder()\n # TODO: Implement Function\n return output_fn(train_pred)\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer_train(decoding_layer_train)",
"Decoding - Inference\nCreate inference logits using tf.contrib.seq2seq.simple_decoder_fn_inference() and tf.contrib.seq2seq.dynamic_rnn_decoder().",
"def decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id,\n maximum_length, vocab_size, decoding_scope, output_fn, keep_prob):\n \"\"\"\n Create a decoding layer for inference\n :param encoder_state: Encoder state\n :param dec_cell: Decoder RNN Cell\n :param dec_embeddings: Decoder embeddings\n :param start_of_sequence_id: GO ID\n :param end_of_sequence_id: EOS Id\n :param maximum_length: The maximum allowed time steps to decode\n :param vocab_size: Size of vocabulary\n :param decoding_scope: TensorFlow Variable Scope for decoding\n :param output_fn: Function to apply the output layer\n :param keep_prob: Dropout keep probability\n :return: Inference Logits\n \"\"\"\n \n infer_decoder_fn = tf.contrib.seq2seq.simple_decoder_fn_inference(\n output_fn, encoder_state, dec_embeddings, start_of_sequence_id, end_of_sequence_id, \n maximum_length, vocab_size)\n inference_logits, _, _ = tf.contrib.seq2seq.dynamic_rnn_decoder(dec_cell, infer_decoder_fn, scope=decoding_scope)\n # TODO: Implement Function\n return inference_logits\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer_infer(decoding_layer_infer)",
"Build the Decoding Layer\nImplement decoding_layer() to create a Decoder RNN layer.\n\nCreate RNN cell for decoding using rnn_size and num_layers.\nCreate the output fuction using lambda to transform it's input, logits, to class logits.\nUse the your decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, decoding_scope, output_fn, keep_prob) function to get the training logits.\nUse your decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, start_of_sequence_id, end_of_sequence_id, maximum_length, vocab_size, decoding_scope, output_fn, keep_prob) function to get the inference logits.\n\nNote: You'll need to use tf.variable_scope to share variables between training and inference.",
"def decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size,\n num_layers, target_vocab_to_int, keep_prob):\n \"\"\"\n Create decoding layer\n :param dec_embed_input: Decoder embedded input\n :param dec_embeddings: Decoder embeddings\n :param encoder_state: The encoded state\n :param vocab_size: Size of vocabulary\n :param sequence_length: Sequence Length\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :param keep_prob: Dropout keep probability\n :return: Tuple of (Training Logits, Inference Logits)\n \"\"\"\n\n #1 Decoder RNNs\n dec_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.BasicLSTMCell(rnn_size)] * num_layers)\n \n #2 lambda to transfrom input, logits, to class logits\n with tf.variable_scope('decoding') as decoding_scope:\n output_fn = lambda x: tf.contrib.layers.fully_connected(x, vocab_size, None, scope=decoding_scope)\n #3 create traning logits:\n training_logits = decoding_layer_train(encoder_state, dec_cell, dec_embed_input, sequence_length, \n decoding_scope, output_fn, keep_prob)\n \n #4 Use decoding_layer_infer to get inference logits\n with tf.variable_scope('decoding', reuse=True) as decoding_scope:\n infer_layer = decoding_layer_infer(encoder_state, dec_cell, dec_embeddings, target_vocab_to_int['<GO>'], target_vocab_to_int['<EOS>'], \n sequence_length, vocab_size, decoding_scope, output_fn, keep_prob)\n \n \n \n return training_logits, infer_layer\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_decoding_layer(decoding_layer)",
"Build the Neural Network\nApply the functions you implemented above to:\n\nApply embedding to the input data for the encoder.\nEncode the input using your encoding_layer(rnn_inputs, rnn_size, num_layers, keep_prob).\nProcess target data using your process_decoding_input(target_data, target_vocab_to_int, batch_size) function.\nApply embedding to the target data for the decoder.\nDecode the encoded input using your decoding_layer(dec_embed_input, dec_embeddings, encoder_state, vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob).",
"def seq2seq_model(input_data, target_data, keep_prob, batch_size, sequence_length, source_vocab_size, target_vocab_size,\n enc_embedding_size, dec_embedding_size, rnn_size, num_layers, target_vocab_to_int):\n \"\"\"\n Build the Sequence-to-Sequence part of the neural network\n :param input_data: Input placeholder\n :param target_data: Target placeholder\n :param keep_prob: Dropout keep probability placeholder\n :param batch_size: Batch Size\n :param sequence_length: Sequence Length\n :param source_vocab_size: Source vocabulary size\n :param target_vocab_size: Target vocabulary size\n :param enc_embedding_size: Decoder embedding size\n :param dec_embedding_size: Encoder embedding size\n :param rnn_size: RNN Size\n :param num_layers: Number of layers\n :param target_vocab_to_int: Dictionary to go from the target words to an id\n :return: Tuple of (Training Logits, Inference Logits)\n \"\"\"\n # TODO: Implement Function\n \n #1 Apply embedding to input data for encoder\n enc_embed_input = tf.contrib.layers.embed_sequence(input_data, source_vocab_size, enc_embedding_size)\n \n #2 Encode the input using encodig_layer\n enc_state = encoding_layer(enc_embed_input, rnn_size, num_layers, keep_prob)\n \n #3 Process target data using process_decoding_input\n dec_input = process_decoding_input(target_data, target_vocab_to_int, batch_size)\n \n #4 Apply embedding to target decoder\n dec_embeddings = tf.Variable(tf.random_uniform([target_vocab_size, dec_embedding_size]))\n dec_embed_input = tf.nn.embedding_lookup(dec_embeddings, dec_input)\n #5 Decode the encoded input using decoding_layer\n \n training_logits, inference_logits = decoding_layer(dec_embed_input, dec_embeddings, enc_state, \n target_vocab_size, sequence_length, rnn_size, num_layers, target_vocab_to_int, keep_prob)\n \n \n return training_logits, inference_logits\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_seq2seq_model(seq2seq_model)",
"Neural Network Training\nHyperparameters\nTune the following parameters:\n\nSet epochs to the number of epochs.\nSet batch_size to the batch size.\nSet rnn_size to the size of the RNNs.\nSet num_layers to the number of layers.\nSet encoding_embedding_size to the size of the embedding for the encoder.\nSet decoding_embedding_size to the size of the embedding for the decoder.\nSet learning_rate to the learning rate.\nSet keep_probability to the Dropout keep probability",
"# Number of Epochs\nepochs = 5\n# Batch Size\nbatch_size = 128\nrnn_size = 128\n# Number of Layers\nnum_layers = 2\n# Embedding Size\nencoding_embedding_size = 32\ndecoding_embedding_size = 32\n# Learning Rate\nlearning_rate = 0.005\n# Dropout Keep Probability\nkeep_probability = 0.9",
"Build the Graph\nBuild the graph using the neural network you implemented.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nsave_path = 'checkpoints/dev'\n(source_int_text, target_int_text), (source_vocab_to_int, target_vocab_to_int), _ = helper.load_preprocess()\nmax_source_sentence_length = max([len(sentence) for sentence in source_int_text])\n\ntrain_graph = tf.Graph()\nwith train_graph.as_default():\n input_data, targets, lr, keep_prob = model_inputs()\n sequence_length = tf.placeholder_with_default(max_source_sentence_length, None, name='sequence_length')\n input_shape = tf.shape(input_data)\n \n train_logits, inference_logits = seq2seq_model(\n tf.reverse(input_data, [-1]), targets, keep_prob, batch_size, sequence_length, len(source_vocab_to_int), len(target_vocab_to_int),\n encoding_embedding_size, decoding_embedding_size, rnn_size, num_layers, target_vocab_to_int)\n\n tf.identity(inference_logits, 'logits')\n with tf.name_scope(\"optimization\"):\n # Loss function\n cost = tf.contrib.seq2seq.sequence_loss(\n train_logits,\n targets,\n tf.ones([input_shape[0], sequence_length]))\n\n # Optimizer\n optimizer = tf.train.AdamOptimizer(lr)\n\n # Gradient Clipping\n gradients = optimizer.compute_gradients(cost)\n capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]\n train_op = optimizer.apply_gradients(capped_gradients)",
"Train\nTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forums to see if anyone is having the same problem.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport time\n\ndef get_accuracy(target, logits):\n \"\"\"\n Calculate accuracy\n \"\"\"\n max_seq = max(target.shape[1], logits.shape[1])\n if max_seq - target.shape[1]:\n target = np.pad(\n target,\n [(0,0),(0,max_seq - target.shape[1])],\n 'constant')\n if max_seq - logits.shape[1]:\n logits = np.pad(\n logits,\n [(0,0),(0,max_seq - logits.shape[1]), (0,0)],\n 'constant')\n\n return np.mean(np.equal(target, np.argmax(logits, 2)))\n\ntrain_source = source_int_text[batch_size:]\ntrain_target = target_int_text[batch_size:]\n\nvalid_source = helper.pad_sentence_batch(source_int_text[:batch_size])\nvalid_target = helper.pad_sentence_batch(target_int_text[:batch_size])\n\nwith tf.Session(graph=train_graph) as sess:\n sess.run(tf.global_variables_initializer())\n\n for epoch_i in range(epochs):\n for batch_i, (source_batch, target_batch) in enumerate(\n helper.batch_data(train_source, train_target, batch_size)):\n start_time = time.time()\n \n _, loss = sess.run(\n [train_op, cost],\n {input_data: source_batch,\n targets: target_batch,\n lr: learning_rate,\n sequence_length: target_batch.shape[1],\n keep_prob: keep_probability})\n \n batch_train_logits = sess.run(\n inference_logits,\n {input_data: source_batch, keep_prob: 1.0})\n batch_valid_logits = sess.run(\n inference_logits,\n {input_data: valid_source, keep_prob: 1.0})\n \n train_acc = get_accuracy(target_batch, batch_train_logits)\n valid_acc = get_accuracy(np.array(valid_target), batch_valid_logits)\n end_time = time.time()\n print('Epoch {:>3} Batch {:>4}/{} - Train Accuracy: {:>6.3f}, Validation Accuracy: {:>6.3f}, Loss: {:>6.3f}'\n .format(epoch_i, batch_i, len(source_int_text) // batch_size, train_acc, valid_acc, loss))\n\n # Save Model\n saver = tf.train.Saver()\n saver.save(sess, save_path)\n print('Model Trained and Saved')",
"Save Parameters\nSave the batch_size and save_path parameters for inference.",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\n# Save parameters for checkpoint\nhelper.save_params(save_path)",
"Checkpoint",
"\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport helper\nimport problem_unittests as tests\n\n_, (source_vocab_to_int, target_vocab_to_int), (source_int_to_vocab, target_int_to_vocab) = helper.load_preprocess()\nload_path = helper.load_params()",
"Sentence to Sequence\nTo feed a sentence into the model for translation, you first need to preprocess it. Implement the function sentence_to_seq() to preprocess new sentences.\n\nConvert the sentence to lowercase\nConvert words into ids using vocab_to_int\nConvert words not in the vocabulary, to the <UNK> word id.",
"def words_to_ints(word_list, reference):\n int_list = []\n for sentence in word_list:\n temp = sentence.split()\n temp = ([word.replace(word, str(reference.get(word, reference['<UNK>']))) for word in temp]) \n return temp\n\ndef sentence_to_seq(sentence, vocab_to_int):\n \"\"\"\n Convert a sentence to a sequence of ids\n :param sentence: String\n :param vocab_to_int: Dictionary to go from the words to an id\n :return: List of word ids\n \"\"\"\n \n\n # TODO: Implement Function\n text_list = text_to_sentence_list(sentence.lower())\n \n return list(map(int, words_to_ints(text_list, vocab_to_int)))\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE\n\"\"\"\ntests.test_sentence_to_seq(sentence_to_seq)",
"Translate\nThis will translate translate_sentence from English to French.",
"translate_sentence = 'he saw a old yellow truck .'\n\n\n\"\"\"\nDON'T MODIFY ANYTHING IN THIS CELL\n\"\"\"\ntranslate_sentence = sentence_to_seq(translate_sentence, source_vocab_to_int)\n\nloaded_graph = tf.Graph()\nwith tf.Session(graph=loaded_graph) as sess:\n # Load saved model\n loader = tf.train.import_meta_graph(load_path + '.meta')\n loader.restore(sess, load_path)\n\n input_data = loaded_graph.get_tensor_by_name('input:0')\n logits = loaded_graph.get_tensor_by_name('logits:0')\n keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0')\n\n translate_logits = sess.run(logits, {input_data: [translate_sentence], keep_prob: 1.0})[0]\n\nprint('Input')\nprint(' Word Ids: {}'.format([i for i in translate_sentence]))\nprint(' English Words: {}'.format([source_int_to_vocab[i] for i in translate_sentence]))\n\nprint('\\nPrediction')\nprint(' Word Ids: {}'.format([i for i in np.argmax(translate_logits, 1)]))\nprint(' French Words: {}'.format([target_int_to_vocab[i] for i in np.argmax(translate_logits, 1)]))",
"Imperfect Translation\nYou might notice that some sentences translate better than others. Since the dataset you're using only has a vocabulary of 227 English words of the thousands that you use, you're only going to see good results using these words. Additionally, the translations in this data set were made by Google translate, so the translations themselves aren't particularly good. (We apologize to the French speakers out there!) Thankfully, for this project, you don't need a perfect translation. However, if you want to create a better translation model, you'll need better data.\nYou can train on the WMT10 French-English corpus. This dataset has more vocabulary and richer in topics discussed. However, this will take you days to train, so make sure you've a GPU and the neural network is performing well on dataset we provided. Just make sure you play with the WMT10 corpus after you've submitted this project.\nSubmitting This Project\nWhen submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as \"dlnd_language_translation.ipynb\" and save it as a HTML file under \"File\" -> \"Download as\". Include the \"helper.py\" and \"problem_unittests.py\" files in your submission."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
epequeno/coursera
|
crypto-014/crib-drag.ipynb
|
unlicense
|
[
"Crib dragging\nfollowing http://travisdazell.blogspot.com/2012/11/many-time-pad-attack-crib-drag.html",
"m1 = \"hello world!!\".encode('hex')\nm2 = \"other message\".encode('hex')\nkey = \"secretkey123!\".encode('hex')\nprint 'm1: {}\\nm2: {}\\nkey: {}'.format(m1, m2, key)\nprint len(m1), len(m2), len(key)\n\nct1 = hex(int(m1, 16) ^ int(key, 16))[2:-1]\nct2 = hex(int(m2, 16) ^ int(key, 16))[2:-1]\nprint 'ct1: {}\\nct2: {}'.format(ct1, ct2)\n\nctx = hex(int(ct1, 16) ^ int(ct2, 16))[2:-1]\nprint 'ctx: {}'.format(ctx)",
"To demonstrate the OTP, we can decrypt the CTs by XOR'ing with the key (k): $ c_{n} \\oplus k = m_{n} $",
"print hex(int(ct1, 16) ^ int(key, 16))[2:-1].decode('hex')\nprint hex(int(ct2, 16) ^ int(key, 16))[2:-1].decode('hex')\n\nimport string\nspace = ' '.encode('hex')\n\ndef attack(crib, ctx):\n width = len(crib)\n print 'crib in hex: {}\\ncrib width: {}\\n------------'.format(crib, width)\n for i in range(0, len(ctx)):\n decoded = hex(int(crib, 16) ^ int(ctx[i:i+width], 16))[2:].decode('hex')\n if decoded.isalpha():\n print \"{}:{}\\t\".format(i, i+width), '{} XOR {}'.format(crib, ctx[i:i+width]), decoded\n \nattack(space, ctx)",
"The assignment asks us to examine what happens when we a space character ' ' with uppercase or lowercase letters:",
"for i in string.uppercase[:10]:\n print hex(int(' '.encode('hex'), 16) ^ int(i.encode('hex'), 16))[2:].decode('hex')",
"So, if we XOR a space with a letter we'll get it's opposite case. Thus far we have several candidates, if we didn't know anything about the PTs we'd have to expand our search with each candidate. For brevity's sake I'll expand the search with knowledge of the PT.\nWe know that all the letters in the PTs are lowercase so and that there are no 'q', 't', or 'f' characters so that narrows it down to 20 XOR 64 which produces 'D'",
"crib = ' '.encode('hex')\nattack(crib, ctx)",
"In this demonstration I'll proceed with knowledge of the PT to expand the crib. Note that by XOR'ing with the crib we get the plaintext of the second message:",
"crib = 'World!!'.encode('hex')\nattack(crib, ctx)\n\nct1 = 0x315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e\nct2 = 0x234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f\nct3 = 0x32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb\nct4 = 0x32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa\nct5 = 0x3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070\nct6 = 0x32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4\nct7 = 0x32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce\nct8 = 0x315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3\nct9 = 0x271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027\nct10 = 0x466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83\ntarget = 0x32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
tpin3694/tpin3694.github.io
|
regex/match_any_of_series_of_words.ipynb
|
mit
|
[
"Title: Match Any Of A Series Of Words\nSlug: match_any_of_series_of_words\nSummary: Match Any Of A Series Of Words\nDate: 2016-05-01 12:00\nCategory: Regex\nTags: Basics\nAuthors: Chris Albon \nBased on: Regular Expressions Cookbook\nPreliminaries",
"# Load regex package\nimport re",
"Create some text",
"# Create a variable containing a text string\ntext = 'The quick brown fox jumped over the lazy brown bear.'",
"Apply regex",
"# Find any of fox, snake, or bear\nre.findall(r'\\b(fox|snake|bear)\\b', text)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
theandygross/HIV_Methylation
|
Figure3.ipynb
|
mit
|
[
"Figure 4",
"import NotebookImport\nfrom Setup.Imports import *\n\nfrom Setup.Read_HIV_Data import *\n\nimport Setup.DX_Imports as dx",
"Set of patients used in analysis of age advancement",
"import Parallel.Age_HIV_Features as fx\n\nsns.set_context(\"paper\", rc={\"lines.linewidth\": 2.5, \n \"font_size\":14})\nsns.set_style(\"white\")",
"Compile HIV and age associated markers\nHere I'm splitting them by direction as well, either up-regulated, down-regulated or neutral. Up-regulated means that a marker increases in methylation with the presence of HIV or increasing age.",
"direction = fx.r4.multi_variate.HIV > 0\ndirection.name = 'up'\nh = fx.g_hiv\nh.name = 'HIV'\nhiv_d = combine(h, direction)\nhiv_d = hiv_d.replace({'both':'HIV-up', \n 'up': 'neutral',\n 'neither': 'neutral',\n 'HIV': 'HIV-down'})\nhiv_d.value_counts()\n\ndirection = fx.res.in_set_s1.multi_variate.age > 0\ndirection.name = 'up'\nh = fx.g_age\nh.name = 'age'\nage_d = combine(h, direction)\nage_d = age_d.replace({'both':'age-up', \n 'up': 'neutral',\n 'neither': 'neutral',\n 'age': 'age-down'})\nage_d.value_counts()",
"Looking at the assocation of age and HIV associated probes with genetic features",
"features = {'HIV-up': (hiv_d=='HIV-up') & (age_d != 'age-up'), \n 'HIV-down': (hiv_d=='HIV-down') & (age_d != 'age-down'),\n 'age-up': (age_d=='age-up') & (hiv_d != 'HIV-up'), \n 'age-down': (age_d=='age-down') & (hiv_d != 'HIV-down'),\n 'both-up': (hiv_d=='HIV-up') & (age_d=='age-up'),\n 'both-down': (hiv_d=='HIV-down') & (age_d=='age-down')}\n\nprobes_sets = {'PRC2': dx.prc2_probes, 'CpG island': dx.cpg_island,\n 'DHS': dx.dhs_site, 'Enhancer': dx.enhancer,\n 'Gene body': dx.gene_body, 'TSS': dx.gene_tss,\n 'Promoter': dx.promoter}\n\nc1 = pd.DataFrame({i:v.value_counts() for i,v in features.iteritems()}).T\nc1\n\nc2 = pd.DataFrame({i:v.value_counts() for i,v in probes_sets.iteritems()}).T\nc2",
"Looking at the overlap of age and HIV associated probes",
"def odds_ratio(a,b):\n ct = pd.crosstab(a,b).astype(float)\n r = (ct.ix[0,0] * ct.ix[1,1]) / (ct.ix[0,1] * ct.ix[1,0])\n return r\n\nct = pd.crosstab(hiv_d, age_d).ix[['HIV-down','neutral','HIV-up'],\n ['age-down','neutral','age-up']]\n\nor_ct = pd.DataFrame({a:{b:odds_ratio(hiv_d==a, age_d==b) for b in age_d.unique()}\n for a in hiv_d.unique()}).T.ix[ct.index, ct.columns]\nor_ct.columns.name = None\nor_ct.index.name = None\n\nor_ct\n\ndef overlap_plot(fig, ax):\n\n sns.heatmap(np.log2(or_ct).ix[::-1], linewidths=4, cbar=False, ax=ax, square=True,\n center=0)\n ax.set_xticklabels([c.get_text().split('-')[-1]\n for c in ax.get_xticklabels()], size=14)\n ax.set_yticklabels([c.get_text().split('-')[-1]\n for c in ax.get_yticklabels()], size=14)\n ax.set_xlabel('Validated age markers', size=14, ha='center')\n ax.set_ylabel('HIV-associated markers\\n', size=14, va='center')\n\n\n cbar = fig.colorbar(ax.get_children()[2], ticks=[-1.58,-1,0,1,1.58],\n ax=ax, use_gridspec=True, pad=.05, aspect=10, shrink=.85)\n cbar.ax.set_yticklabels(['1/3','1/2',1,2,3], size=14)\n cbar.ax.set_ylabel('Odds Ratio', rotation=270, size=14)\n for i,(a,v) in enumerate(ct.iterrows()):\n for j,(b,c) in enumerate(v.iteritems()): \n if np.log2(or_ct).abs().ix[a,b] > 1:\n color = 'white'\n else:\n color = 'black'\n ax.annotate(c, (j+.5, i+.5), ha='center', va='center', fontsize=12,\n color=color)\n \nfig, ax = subplots(figsize=(5.5,3))\noverlap_plot(fig, ax)",
"Overlap of different combinations of age and HIV assoicated probes with genetic features",
"associations = {}\nfor i,a in features.iteritems():\n for j,b in probes_sets.iteritems():\n associations[(i,j)] = odds_ratio(a,b.ix[fx.probe_idx])\nassociations = pd.Series(associations)\n\nassociations.unstack()\n\no = ['DHS','PRC2','CpG island','Enhancer', 'TSS','Gene body','Promoter']\np = ['HIV-up','both-up', 'age-up']\ndf1 = associations.unstack().T.ix[o[::-1],p]\n\no = ['DHS','PRC2','CpG island','Enhancer', 'TSS','Gene body','Promoter']\np = ['HIV-down','both-down', 'age-down']\ndf2 = associations.unstack().T.ix[o[::-1],p]\n\ncc = sns.color_palette()\ndef enrichment_plot(df, ax):\n np.log2(df).plot(kind='barh', ax=ax, alpha=.9, width=.8, \n color=[cc[1], cc[2], cc[3]])\n ax.set_xticks([-3, -2,-1,0,1,2,3,4])\n ax.set_xticklabels([.125, .25,.5,1,2,4,8,16], size=14)\n ax.set_ylim(-.75, 6.72)\n ax.set_xlabel('Odds ratio', size=14)\n ax.legend().set_visible(False)\n ax.spines['left'].set_visible(False)\n ax.set_yticklabels([c.get_text().replace('-','\\n')\n for c in ax.get_yticklabels()], size=14)\n for i in range(len(o)):\n ax.axhline(i+.5, color='grey', ls='--', lw=1)\n ax.legend()\n prettify_ax(ax, top=False)\n\nfig, axs = subplots(1,2, figsize=(10,5))\nenrichment_plot(df2, axs[0])\naxs[0].set_xbound(-2, 3.)\nenrichment_plot(df1, axs[1])\naxs[1].set_xbound(-2.8, 4.)\nfig.tight_layout()",
"Distrubution of CpG methylation levels among age and HIV associated probes",
"cc = sns.color_palette()[1:]\nmm = fx.mm #mean methylation for control patients\ndef dist_plot_split(splits, ax):\n for i,split in enumerate(splits):\n draw_dist(mm.ix[ti(split)], ax=ax, colors=cc[i])\n\n d = smooth_dist(mm)\n ax.fill_between(d.index, 0, d, color='grey', alpha=.2)\n ax.plot(d.index, d, color='grey', lw=2, zorder=-1)\n ax.set_ylabel('Density of CpG markers', size=14)\n ax.set_yticks([])\n ax.set_xlabel('Methylation state (%)', size=14)\n ax.set_xticks([0, .2, .4, .6, .8, 1.])\n ax.set_xticklabels(['0', '20', '40', '60', '80', '100'],\n size=14)\n #ax.set_ybound(0,7.2)\n ax.set_xbound(0,1)\n prettify_ax(ax)\n\nfig, axs = subplots(1,2, figsize=(12,4))\ndist_plot_split([features['HIV-down'],features['both-down'],features['age-down']],\n axs[0])\ndist_plot_split([features['HIV-up'],features['both-up'],features['age-up']],\n axs[1])\nfig.tight_layout()",
"Compiling the final figure",
"import matplotlib.gridspec as gridspec\n\nrcParams['font.sans-serif'] = 'Arial'\n\nplt.figure(figsize=(4.5,14))\ngs1 = gridspec.GridSpec(3, 1, height_ratios=[2,3,2], hspace=.3)\n\n#gs1.update(left=0.05, right=0.48, wspace=0.05)\n\nax1 = plt.subplot(gs1[0])\nax2 = plt.subplot(gs1[1])\nax3 = plt.subplot(gs1[2])\naxs = [ax1, ax2, ax3]\n\noverlap_plot(fig, ax1)\nenrichment_plot(df1, axs[1])\naxs[1].set_xbound(-2.8, 4.)\naxs[1].legend(loc='lower right')\n\ndist_plot_split([features['HIV-up'],features['both-up'],features['age-up']],\n axs[2])\n\nplt.savefig(FIGDIR + 'fig3_ab_c.pdf')"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
gsentveld/lunch_and_learn
|
notebooks/Data_Exploration_Sample_Child.ipynb
|
mit
|
[
"Exploring the files with Pandas\nMany statistical Python packages can deal with numpy Arrays.\nNumpy Arrays however are not always easy to use. \nPandas is a package that provides a dataframe interface, similar to what R uses as the main data structure.\nSince Pandas has become so popular, many packages accept both pd.DataFrames and numpy Arrays.",
"import os\nfrom dotenv import load_dotenv, find_dotenv\n\n# find .env automagically by walking up directories until it's found\ndotenv_path = find_dotenv()\n\n# load up the entries as environment variables\nload_dotenv(dotenv_path)",
"First some environment variables\nWe now use the files that are stored in the RAW directory.\nIf we decide to change the data format by changing names, adding features, created summary data frames etc., we will save those files in the INTERIM directory.",
"PROJECT_DIR = os.path.dirname(dotenv_path)\nRAW_DATA_DIR = PROJECT_DIR + os.environ.get(\"RAW_DATA_DIR\")\nINTERIM_DATA_DIR = PROJECT_DIR + os.environ.get(\"INTERIM_DATA_DIR\")\nfiles=os.environ.get(\"FILES\").split()\n\nprint(\"Project directory is : {0}\".format(PROJECT_DIR))\nprint(\"Raw data directory is : {0}\".format(RAW_DATA_DIR))\nprint(\"Interim directory is : {0}\".format(INTERIM_DATA_DIR))",
"Importing pandas and matplotlib.pyplot",
"# The following jupyter notebook magic makes the plots appear in the notebook. \n# If you run in batch mode, you have to save your plots as images.\n%matplotlib notebook\n\n# matplotlib.pyplot is traditionally imported as plt\nimport matplotlib.pyplot as plt\n\n# Pandas is traditionaly imported as pd.\nimport pandas as pd\nfrom pylab import rcParams\n\n# some display options to size the figures. feel free to experiment\npd.set_option('display.max_columns', 25)\nrcParams['figure.figsize'] = (17, 7)",
"Reading a file in Pandas\nReading a CSV file is really easy in Pandas. There are several formats that Pandas can deal with.\n|Format Type|Data Description|Reader|Writer|\n|---|---|---|---|\n|text|CSV|read_csv|to_csv|\n|text|JSON|read_json|to_json|\n|text|HTML|read_html|to_html|\n|text|Local clipboard|read_clipboard|to_clipboard|\n|binary|MS Excel|read_excel|to_excel|\n|binary|HDF5 Format|read_hdf|to_hdf|\n|binary|Feather Format|read_feather|to_feather|\n|binary|Msgpack|read_msgpack|to_msgpack|\n|binary|Stata|read_stata|to_stata|\n|binary|SAS|read_sas ||\n|binary|Python Pickle Format|read_pickle|to_pickle|\n|SQL|SQL|read_sql|to_sql|\n|SQL|Google Big Query|read_gbq|to_gbq|\nWe will use <code>pd.read_csv()</code>.\nAs you will see, the Jupyter notebook prints out a very nice rendition of the DataFrame object that is the result",
"\nsamchild=pd.read_csv(RAW_DATA_DIR+'/samchild.csv')\n\n\nsamchild.columns.values.tolist()\n\nfeatures=[x for x in samadult.columns.values.tolist() if x.startswith('ALDURA')]\n\nimport numpy as np\n\nnp.sum(samadult.WKDAYR.notnull() & (samadult['WKDAYR']<900))\n\nfeatures=[\n 'ALDURA3',\n 'ALDURA4',\n 'ALDURA6',\n 'ALDURA7',\n 'ALDURA8',\n 'ALDURA11',\n 'ALDURA17',\n 'ALDURA20',\n 'ALDURA21',\n 'ALDURA22',\n 'ALDURA23',\n 'ALDURA24',\n 'ALDURA27',\n 'ALDURA28',\n 'ALDURA29',\n 'ALDURA33']\n\ntarget='WKDAYR'\n\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\n\nreg=LinearRegression()\n\ndata=samadult[samadult.WKDAYR.notnull() & (samadult.WKDAYR<900)]\n\nX=data[features]\nX.shape\n\nX=X+1\nX.shape\n\nX=X.fillna(0)\nX.shape\n\n#X=np.log1p(X)\n#X.shape\n\ny=np.log1p(data[target])\n\nindicator_names=[x+\"_I\" for x in features]\n\nindicators=pd.DataFrame()\nfor feature in features:\n indicators[feature+\"_I\"]=data[feature].notnull().astype(int)\n \n\n\nindicators\n\nX=pd.concat([X, indicators], axis=1, join_axes=[X.index])\n\nX\n\nreg.fit(X,y)\n\ny_pred=reg.predict(X)\n\nscore=r2_score(y, y_pred)\n\nimport matplotlib.pyplot as plt\nplt.plot(y,y_pred,marker='.', linestyle='None', alpha=0.5 )\nplt.xlabel('Y Train')\nplt.ylabel('Y Predict')\nplt.show()\n\nscore\n\nfrom sklearn.linear_model import Ridge\n\nridge=Ridge(alpha=0.07, normalize=True)\nridge.fit(X,y)\n\ny_pred=ridge.predict(X)\n\ndef display_plot(cv_scores, cv_scores_std):\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n ax.plot(alpha_space, cv_scores)\n\n std_error = cv_scores_std / np.sqrt(10)\n\n ax.fill_between(alpha_space, cv_scores + std_error, cv_scores - std_error, alpha=0.2)\n ax.set_ylabel('CV Score +/- Std Error')\n ax.set_xlabel('Alpha')\n ax.axhline(np.max(cv_scores), linestyle='--', color='.5')\n ax.set_xlim([alpha_space[0], alpha_space[-1]])\n ax.set_xscale('log')\n plt.show()\n\n# Import necessary modules\nimport numpy as np\n\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import cross_val_score\n\n# Setup the array of alphas and lists to store scores\nalpha_space = np.logspace(-4, 0, 50)\nridge_scores = []\nridge_scores_std = []\n\n# Create a ridge regressor: ridge\nridge = Ridge(normalize=True)\n\n# Compute scores over range of alphas\nfor alpha in alpha_space:\n\n # Specify the alpha value to use: ridge.alpha\n ridge.alpha = alpha\n \n # Perform 10-fold CV: ridge_cv_scores\n ridge_cv_scores = cross_val_score(ridge, X, y, cv=10)\n \n # Append the mean of ridge_cv_scores to ridge_scores\n ridge_scores.append(np.mean(ridge_cv_scores))\n \n # Append the std of ridge_cv_scores to ridge_scores_std\n ridge_scores_std.append(np.std(ridge_cv_scores))\n\n# Display the plot\ndisplay_plot(ridge_scores, ridge_scores_std)\n\n\nfrom sklearn.decomposition import PCA\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import KMeans\n\n\nfig = plt.figure(1, figsize=(8, 6))\nplt.clf()\nax = Axes3D(fig, rect=[0, 0, .95, 1], elev=40, azim=20)\n\nplt.cla()\npca = PCA(n_components=3)\npca.fit(X)\nX_pca = pca.transform(X)\n\nkmean=KMeans(n_clusters=8)\nkmean.fit(X_pca)\ny_lab=kmean.labels_\n\n\n# Reorder the labels to have colors matching the cluster results\nax.scatter(X_pca[:, 0], X_pca[:, 1], X_pca[:, 2], label=y_lab,c=y_lab, cmap=plt.cm.spectral)\n\nax.w_xaxis.set_ticklabels([])\nax.w_yaxis.set_ticklabels([])\nax.w_zaxis.set_ticklabels([])\nplt.legend(bbox_to_anchor=(0, 1), loc='upper right', ncol=7)\n\nplt.show()\n\ny_lab",
"Back to Agenda"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
johnpfay/environ859
|
07_DataWrangling/Geopandas/3-SummarizeTidyTables.ipynb
|
gpl-3.0
|
[
"Summarize tidy tables\nThis script summarizes the water use and water suppy tidy tables generated by the CreateUsageTable and CreateSupplyTable scripts, respectively. Each table is then merged into a single dataframe to create a table listing water use and supply for each year/state combination. \n\nWorkflow\n\nImport and summarize use table on state, listing usage amounts by use class and source class (surface/groundwater)\nImport and summarize supply table, first on county so that amounts can be converted from mm to MGal/year.\nSummarize the county supply table to the state level, listing the total MGal/year of supply in each state",
"#Import libraries\nimport sys, os\nimport pandas as pd\nimport numpy as np\n\n#Get file names; these files are created by the CreateUsageTable.py and CreateSupplyTable.py respectively\ndataDir = '../../Data'\ntidyuseFN = dataDir + os.sep + \"UsageDataTidy.csv\"\ntidysupplyFN = dataDir + os.sep + \"SupplyTableTidy.csv\"\noutCountyFN = dataDir + os.sep + \"WaterByCounty.csv\"\noutStateFN = dataDir + os.sep + \"WaterByState.csv\"\noutNationFN = dataDir + os.sep + \"WaterBalanceData.csv\"",
"Summarize USE table by county\nComputes water usage for each county broken into each sector and source category.",
"#Read in the usage table from the csv file\ndfUse = pd.read_csv(tidyuseFN,dtype={'FIPS':np.str})\n\n#Remove rows with irrigation and thermoelectric sub-classes\n#dropValues = ['Irrigation_Crop', 'Irrigation_Golf','ThermoElec_OnceThru', 'ThermoElec_Recirc']\ndropValues = ['Irrigation','ThermoElec']\ndfUse = dfUse[~dfUse['UseClass'].isin(dropValues)]\n\n#Convert amounts from MGal/day to MGal/year\ndfUse['Amount'] = dfUse['Amount'] * 365\n\n#Add STATEFIPS column to dfUse (as left most 2 characters of FIPS values)\ndfUse['STATEFIPS'] = dfUse['FIPS'].str[:2]\n\n#Pivot on YEAR and FIPS listing usage in sector/source categories\ndfUseFIPS = dfUse.pivot_table(index=['YEAR','STATE','FIPS'],\n values='Amount',\n aggfunc='sum',\n columns=['UseClass','SrcClass'])\n\n#Flatten hierarchical column names\ndfUseFIPS.columns = ['_'.join(col).strip() for col in dfUseFIPS.columns.values]\n\n#Remove indices so values are available as columns\ndfUseFIPS.reset_index(inplace=True)\n\ndfUseFIPS.head(2)",
"Import and summarize supply table by county",
"#Read in the supply table from the csv file\ndfSupply = pd.read_csv(tidysupplyFN,dtype={'FIPS':np.str,'STATEFIPS':np.str}) \n\n#Compute supply as precipitation - evapotranspiration \n#(See https://www.fs.fed.us/rm/value/docs/spatial_distribution_water_supply.pdf)\n# * Could also use total_runoff\n# * Values are in mm/year and need to be adjusted to MGal/year by mulitplying by weighted area\ndfSupply['Supply'] = dfSupply['pr'] - dfSupply['et']\n\n#Summarize supply on YEAR and FIPS\n'''We take the mean mm/year across points in a county and then \n mulitply by county area to get volume (mm * m3). These values\n then need to by converted to MGal to give MGal/year\n'''\n\n#Compute mean runoff and supply on year and county\ndfSupplyFIPS = dfSupply.groupby(('YEAR','STATEFIPS','FIPS','Area'))['total_runoff','Supply'].mean()\n\n#Reset the index so Year, StateFIPS, FIPS, and AREA become columns again\ndfSupplyFIPS.reset_index(inplace=True)\n\n#Convert mm/Year * county area (m2) into MGal/year - to match use values\n''' m = [mm] / 1000; \n m * [m2] = m3;\n [m3] / 3785.41178 = 1 MGal'''\nfor param in ('total_runoff','Supply'):\n dfSupplyFIPS[param] = (dfSupplyFIPS[param] / 1000.0) * dfSupplyFIPS.Area / 3785.41178\n\ndfSupplyFIPS.head(2)",
"Join Use and Supply Tables on Year and FIPS",
"dfSupplyFIPS.columns.values\n\n#Merge the two tables on YEAR and FIPS columns\ndfAll = pd.merge(dfUseFIPS,dfSupplyFIPS, how='outer',on=['YEAR','FIPS'],left_index=True,right_index=True)\n\ndfAll.head(2)\n\n#Export to csv\ndfAll.to_csv(outCountyFN, index=False, encoding='utf8')",
"Summarize for entire US",
"#Group by YEAR\ndfUS = dfAll.groupby('YEAR').sum()\ndfUS.head()\n\ndfUS.reset_index(inplace=True)\n\ndfUSm = pd.melt(dfUS,id_vars='YEAR',var_name='Group',value_name='MGal')\n\ndfUSm.to_csv(outNationFN,index=False)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
ES-DOC/esdoc-jupyterhub
|
notebooks/test-institute-2/cmip6/models/sandbox-3/atmoschem.ipynb
|
gpl-3.0
|
[
"ES-DOC CMIP6 Model Properties - Atmoschem\nMIP Era: CMIP6\nInstitute: TEST-INSTITUTE-2\nSource ID: SANDBOX-3\nTopic: Atmoschem\nSub-Topics: Transport, Emissions Concentrations, Gas Phase Chemistry, Stratospheric Heterogeneous Chemistry, Tropospheric Heterogeneous Chemistry, Photo Chemistry. \nProperties: 84 (39 required)\nModel descriptions: Model description details\nInitialized From: -- \nNotebook Help: Goto notebook help page\nNotebook Initialised: 2018-02-15 16:54:45\nDocument Setup\nIMPORTANT: to be executed each time you run the notebook",
"# DO NOT EDIT ! \nfrom pyesdoc.ipython.model_topic import NotebookOutput \n\n# DO NOT EDIT ! \nDOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-3', 'atmoschem')",
"Document Authors\nSet document authors",
"# Set as follows: DOC.set_author(\"name\", \"email\") \n# TODO - please enter value(s)",
"Document Contributors\nSpecify document contributors",
"# Set as follows: DOC.set_contributor(\"name\", \"email\") \n# TODO - please enter value(s)",
"Document Publication\nSpecify document publication status",
"# Set publication status: \n# 0=do not publish, 1=publish. \nDOC.set_publication_status(0)",
"Document Table of Contents\n1. Key Properties\n2. Key Properties --> Software Properties\n3. Key Properties --> Timestep Framework\n4. Key Properties --> Timestep Framework --> Split Operator Order\n5. Key Properties --> Tuning Applied\n6. Grid\n7. Grid --> Resolution\n8. Transport\n9. Emissions Concentrations\n10. Emissions Concentrations --> Surface Emissions\n11. Emissions Concentrations --> Atmospheric Emissions\n12. Emissions Concentrations --> Concentrations\n13. Gas Phase Chemistry\n14. Stratospheric Heterogeneous Chemistry\n15. Tropospheric Heterogeneous Chemistry\n16. Photo Chemistry\n17. Photo Chemistry --> Photolysis \n1. Key Properties\nKey properties of the atmospheric chemistry\n1.1. Model Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview of atmospheric chemistry model.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.model_overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.2. Model Name\nIs Required: TRUE Type: STRING Cardinality: 1.1\nName of atmospheric chemistry model code.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.model_name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.3. Chemistry Scheme Scope\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nAtmospheric domains covered by the atmospheric chemistry model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.chemistry_scheme_scope') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"troposhere\" \n# \"stratosphere\" \n# \"mesosphere\" \n# \"mesosphere\" \n# \"whole atmosphere\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"1.4. Basic Approximations\nIs Required: TRUE Type: STRING Cardinality: 1.1\nBasic approximations made in the atmospheric chemistry model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.basic_approximations') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"1.5. Prognostic Variables Form\nIs Required: TRUE Type: ENUM Cardinality: 1.N\nForm of prognostic variables in the atmospheric chemistry component.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.prognostic_variables_form') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"3D mass/mixing ratio for gas\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"1.6. Number Of Tracers\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nNumber of advected tracers in the atmospheric chemistry model",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.number_of_tracers') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"1.7. Family Approach\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nAtmospheric chemistry calculations (not advection) generalized into families of species?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.family_approach') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"1.8. Coupling With Chemical Reactivity\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nAtmospheric chemistry transport scheme turbulence is couple with chemical reactivity?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.coupling_with_chemical_reactivity') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"2. Key Properties --> Software Properties\nSoftware properties of aerosol code\n2.1. Repository\nIs Required: FALSE Type: STRING Cardinality: 0.1\nLocation of code for this component.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.software_properties.repository') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"2.2. Code Version\nIs Required: FALSE Type: STRING Cardinality: 0.1\nCode version identifier.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_version') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"2.3. Code Languages\nIs Required: FALSE Type: STRING Cardinality: 0.N\nCode language(s).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.software_properties.code_languages') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"3. Key Properties --> Timestep Framework\nTimestepping in the atmospheric chemistry model\n3.1. Method\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nMathematical method deployed to solve the evolution of a given variable",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Operator splitting\" \n# \"Integrated\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"3.2. Split Operator Advection Timestep\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nTimestep for chemical species advection (in seconds)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_advection_timestep') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"3.3. Split Operator Physical Timestep\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nTimestep for physics (in seconds).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_physical_timestep') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"3.4. Split Operator Chemistry Timestep\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nTimestep for chemistry (in seconds).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_chemistry_timestep') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"3.5. Split Operator Alternate Order\nIs Required: FALSE Type: BOOLEAN Cardinality: 0.1\n?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_alternate_order') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"3.6. Integrated Timestep\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nTimestep for the atmospheric chemistry model (in seconds)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_timestep') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"3.7. Integrated Scheme Type\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nSpecify the type of timestep scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.integrated_scheme_type') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Explicit\" \n# \"Implicit\" \n# \"Semi-implicit\" \n# \"Semi-analytic\" \n# \"Impact solver\" \n# \"Back Euler\" \n# \"Newton Raphson\" \n# \"Rosenbrock\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"4. Key Properties --> Timestep Framework --> Split Operator Order\n**\n4.1. Turbulence\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for turbulence scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.turbulence') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.2. Convection\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for convection scheme This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.convection') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.3. Precipitation\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for precipitation scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.precipitation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.4. Emissions\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for emissions scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.emissions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.5. Deposition\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for deposition scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.deposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.6. Gas Phase Chemistry\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for gas phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.gas_phase_chemistry') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.7. Tropospheric Heterogeneous Phase Chemistry\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for tropospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.tropospheric_heterogeneous_phase_chemistry') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.8. Stratospheric Heterogeneous Phase Chemistry\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for stratospheric heterogeneous phase chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.stratospheric_heterogeneous_phase_chemistry') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.9. Photo Chemistry\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for photo chemistry scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.photo_chemistry') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"4.10. Aerosols\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nCall order for aerosols scheme. This should be an integer greater than zero, and may be the same value as for another process if they are calculated at the same time.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.timestep_framework.split_operator_order.aerosols') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"5. Key Properties --> Tuning Applied\nTuning methodology for atmospheric chemistry component\n5.1. Description\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral overview description of tuning: explain and motivate the main targets and metrics retained. &Document the relative weight given to climate performance metrics versus process oriented metrics, &and on the possible conflicts with parameterization level tuning. In particular describe any struggle &with a parameter value that required pushing it to its limits to solve a particular model deficiency.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.description') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"5.2. Global Mean Metrics Used\nIs Required: FALSE Type: STRING Cardinality: 0.N\nList set of metrics of the global mean state used in tuning model/component",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.global_mean_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"5.3. Regional Metrics Used\nIs Required: FALSE Type: STRING Cardinality: 0.N\nList of regional metrics of mean state used in tuning model/component",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.regional_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"5.4. Trend Metrics Used\nIs Required: FALSE Type: STRING Cardinality: 0.N\nList observed trend metrics used in tuning model/component",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.key_properties.tuning_applied.trend_metrics_used') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"6. Grid\nAtmospheric chemistry grid\n6.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nDescribe the general structure of the atmopsheric chemistry grid",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"6.2. Matches Atmosphere Grid\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\n* Does the atmospheric chemistry grid match the atmosphere grid?*",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.matches_atmosphere_grid') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"7. Grid --> Resolution\nResolution in the atmospheric chemistry grid\n7.1. Name\nIs Required: TRUE Type: STRING Cardinality: 1.1\nThis is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.resolution.name') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"7.2. Canonical Horizontal Resolution\nIs Required: FALSE Type: STRING Cardinality: 0.1\nExpression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.resolution.canonical_horizontal_resolution') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"7.3. Number Of Horizontal Gridpoints\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nTotal number of horizontal (XY) points (or degrees of freedom) on computational grid.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.resolution.number_of_horizontal_gridpoints') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"7.4. Number Of Vertical Levels\nIs Required: FALSE Type: INTEGER Cardinality: 0.1\nNumber of vertical levels resolved on computational grid.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.resolution.number_of_vertical_levels') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"7.5. Is Adaptive Grid\nIs Required: FALSE Type: BOOLEAN Cardinality: 0.1\nDefault is False. Set true if grid resolution changes during execution.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.grid.resolution.is_adaptive_grid') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"8. Transport\nAtmospheric chemistry transport\n8.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nGeneral overview of transport implementation",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.transport.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"8.2. Use Atmospheric Transport\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs transport handled by the atmosphere, rather than within atmospheric cehmistry?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.transport.use_atmospheric_transport') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"8.3. Transport Details\nIs Required: FALSE Type: STRING Cardinality: 0.1\nIf transport is handled within the atmospheric chemistry scheme, describe it.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.transport.transport_details') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"9. Emissions Concentrations\nAtmospheric chemistry emissions\n9.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview atmospheric chemistry emissions",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"10. Emissions Concentrations --> Surface Emissions\n**\n10.1. Sources\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nSources of the chemical species emitted at the surface that are taken into account in the emissions scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.sources') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Vegetation\" \n# \"Soil\" \n# \"Sea surface\" \n# \"Anthropogenic\" \n# \"Biomass burning\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"10.2. Method\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nMethods used to define chemical species emitted directly into model layers above the surface (several methods allowed because the different species may not use the same method).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.method') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Climatology\" \n# \"Spatially uniform mixing ratio\" \n# \"Spatially uniform concentration\" \n# \"Interactive\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"10.3. Prescribed Climatology Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted at the surface and prescribed via a climatology, and the nature of the climatology (E.g. CO (monthly), C2H6 (constant))",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_climatology_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"10.4. Prescribed Spatially Uniform Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted at the surface and prescribed as spatially uniform",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.prescribed_spatially_uniform_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"10.5. Interactive Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted at the surface and specified via an interactive method",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.interactive_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"10.6. Other Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted at the surface and specified via any other method",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.surface_emissions.other_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11. Emissions Concentrations --> Atmospheric Emissions\nTO DO\n11.1. Sources\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nSources of chemical species emitted in the atmosphere that are taken into account in the emissions scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.sources') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Aircraft\" \n# \"Biomass burning\" \n# \"Lightning\" \n# \"Volcanos\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"11.2. Method\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nMethods used to define the chemical species emitted in the atmosphere (several methods allowed because the different species may not use the same method).",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.method') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Climatology\" \n# \"Spatially uniform mixing ratio\" \n# \"Spatially uniform concentration\" \n# \"Interactive\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"11.3. Prescribed Climatology Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted in the atmosphere and prescribed via a climatology (E.g. CO (monthly), C2H6 (constant))",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_climatology_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.4. Prescribed Spatially Uniform Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted in the atmosphere and prescribed as spatially uniform",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.prescribed_spatially_uniform_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.5. Interactive Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted in the atmosphere and specified via an interactive method",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.interactive_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"11.6. Other Emitted Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of chemical species emitted in the atmosphere and specified via an "other method"",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.atmospheric_emissions.other_emitted_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"12. Emissions Concentrations --> Concentrations\nTO DO\n12.1. Prescribed Lower Boundary\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of species prescribed at the lower boundary.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_lower_boundary') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"12.2. Prescribed Upper Boundary\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of species prescribed at the upper boundary.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.emissions_concentrations.concentrations.prescribed_upper_boundary') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"13. Gas Phase Chemistry\nAtmospheric chemistry transport\n13.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview gas phase atmospheric chemistry",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"13.2. Species\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nSpecies included in the gas phase chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.species') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"HOx\" \n# \"NOy\" \n# \"Ox\" \n# \"Cly\" \n# \"HSOx\" \n# \"Bry\" \n# \"VOCs\" \n# \"isoprene\" \n# \"H2O\" \n# \"Other: [Please specify]\" \n# TODO - please enter value(s)\n",
"13.3. Number Of Bimolecular Reactions\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of bi-molecular reactions in the gas phase chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_bimolecular_reactions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.4. Number Of Termolecular Reactions\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of ter-molecular reactions in the gas phase chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_termolecular_reactions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.5. Number Of Tropospheric Heterogenous Reactions\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of reactions in the tropospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_tropospheric_heterogenous_reactions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.6. Number Of Stratospheric Heterogenous Reactions\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of reactions in the stratospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_stratospheric_heterogenous_reactions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.7. Number Of Advected Species\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of advected species in the gas phase chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_advected_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.8. Number Of Steady State Species\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of gas phase species for which the concentration is updated in the chemical solver assuming photochemical steady state",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.number_of_steady_state_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"13.9. Interactive Dry Deposition\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.interactive_dry_deposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"13.10. Wet Deposition\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs wet deposition included? Wet deposition describes the moist processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_deposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"13.11. Wet Oxidation\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs wet oxidation included? Oxidation describes the loss of electrons or an increase in oxidation state by a molecule",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.gas_phase_chemistry.wet_oxidation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"14. Stratospheric Heterogeneous Chemistry\nAtmospheric chemistry startospheric heterogeneous chemistry\n14.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview stratospheric heterogenous atmospheric chemistry",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"14.2. Gas Phase Species\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nGas phase species included in the stratospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.gas_phase_species') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Cly\" \n# \"Bry\" \n# \"NOy\" \n# TODO - please enter value(s)\n",
"14.3. Aerosol Species\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nAerosol species included in the stratospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.aerosol_species') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Sulphate\" \n# \"Polar stratospheric ice\" \n# \"NAT (Nitric acid trihydrate)\" \n# \"NAD (Nitric acid dihydrate)\" \n# \"STS (supercooled ternary solution aerosol particule))\" \n# TODO - please enter value(s)\n",
"14.4. Number Of Steady State Species\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of steady state species in the stratospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.number_of_steady_state_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"14.5. Sedimentation\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs sedimentation is included in the stratospheric heterogeneous chemistry scheme or not?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.sedimentation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"14.6. Coagulation\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs coagulation is included in the stratospheric heterogeneous chemistry scheme or not?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.stratospheric_heterogeneous_chemistry.coagulation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"15. Tropospheric Heterogeneous Chemistry\nAtmospheric chemistry tropospheric heterogeneous chemistry\n15.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview tropospheric heterogenous atmospheric chemistry",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"15.2. Gas Phase Species\nIs Required: FALSE Type: STRING Cardinality: 0.1\nList of gas phase species included in the tropospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.gas_phase_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"15.3. Aerosol Species\nIs Required: FALSE Type: ENUM Cardinality: 0.N\nAerosol species included in the tropospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.aerosol_species') \n\n# PROPERTY VALUE(S): \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Sulphate\" \n# \"Nitrate\" \n# \"Sea salt\" \n# \"Dust\" \n# \"Ice\" \n# \"Organic\" \n# \"Black carbon/soot\" \n# \"Polar stratospheric ice\" \n# \"Secondary organic aerosols\" \n# \"Particulate organic matter\" \n# TODO - please enter value(s)\n",
"15.4. Number Of Steady State Species\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of steady state species in the tropospheric heterogeneous chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.number_of_steady_state_species') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"15.5. Interactive Dry Deposition\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs dry deposition interactive (as opposed to prescribed)? Dry deposition describes the dry processes by which gaseous species deposit themselves on solid surfaces thus decreasing their concentration in the air.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.interactive_dry_deposition') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"15.6. Coagulation\nIs Required: TRUE Type: BOOLEAN Cardinality: 1.1\nIs coagulation is included in the tropospheric heterogeneous chemistry scheme or not?",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.tropospheric_heterogeneous_chemistry.coagulation') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# Valid Choices: \n# True \n# False \n# TODO - please enter value(s)\n",
"16. Photo Chemistry\nAtmospheric chemistry photo chemistry\n16.1. Overview\nIs Required: TRUE Type: STRING Cardinality: 1.1\nOverview atmospheric photo chemistry",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.photo_chemistry.overview') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"16.2. Number Of Reactions\nIs Required: TRUE Type: INTEGER Cardinality: 1.1\nThe number of reactions in the photo-chemistry scheme.",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.photo_chemistry.number_of_reactions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(value) \n# TODO - please enter value(s)\n",
"17. Photo Chemistry --> Photolysis\nPhotolysis scheme\n17.1. Method\nIs Required: TRUE Type: ENUM Cardinality: 1.1\nPhotolysis scheme",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.method') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# Valid Choices: \n# \"Offline (clear sky)\" \n# \"Offline (with clouds)\" \n# \"Online\" \n# TODO - please enter value(s)\n",
"17.2. Environmental Conditions\nIs Required: FALSE Type: STRING Cardinality: 0.1\nDescribe any environmental conditions taken into account by the photolysis scheme (e.g. whether pressure- and temperature-sensitive cross-sections and quantum yields in the photolysis calculations are modified to reflect the modelled conditions.)",
"# PROPERTY ID - DO NOT EDIT ! \nDOC.set_id('cmip6.atmoschem.photo_chemistry.photolysis.environmental_conditions') \n\n# PROPERTY VALUE: \n# Set as follows: DOC.set_value(\"value\") \n# TODO - please enter value(s)\n",
"©2017 ES-DOC"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
jni/numpy-skimage-tutorial
|
notebooks/00_images_are_arrays.ipynb
|
bsd-3-clause
|
[
"Images are numpy arrays\nWe represent images in scikit-image using standard numpy arrays. This allows maximum inter-operability with other libraries in the scientific Python ecosystem, such as matplotlib and scipy.\nLet's see how to build a grayscale image as a 2D array:",
"%matplotlib inline\nimport numpy as np\nfrom matplotlib import pyplot as plt, cm\n\nrandom_image = np.random.rand(500, 500)\nplt.imshow(random_image, cmap=cm.gray, interpolation='nearest');",
"The same holds for \"real-world\" images:",
"from skimage import data\n\ncoins = data.coins()\n\nprint(type(coins), coins.dtype, coins.shape)\nplt.imshow(coins, cmap=cm.gray, interpolation='nearest');",
"A color image is a 3D array, where the last dimension has size 3 and represents the red, green, and blue channels:",
"cat = data.chelsea()\nprint(cat.shape)\n\nplt.imshow(cat, interpolation='nearest');",
"These are just numpy arrays. Making a red square is easy using just array slicing and manipulation:",
"cat[10:110, 10:110, :] = [255, 0, 0] # [red, green, blue]\nplt.imshow(cat);",
"Images can also include transparent regions by adding a 4th dimension, called an alpha layer.\nData types and image values\nIn literature, one finds different conventions for representing image values:\n0 - 255 where 0 is black, 255 is white\n 0 - 1 where 0 is black, 1 is white\nscikit-image supports both conventions--the choice is determined by the\ndata-type of the array.\nE.g., here, I generate two valid images:",
"linear0 = np.linspace(0, 1, 2500).reshape((50, 50))\nlinear1 = np.linspace(0, 255, 2500).reshape((50, 50)).astype(np.uint8)\n\nprint \"Linear0:\", linear0.dtype, linear0.min(), linear0.max()\nprint \"Linear1:\", linear1.dtype, linear1.min(), linear1.max()\n\nfig, (ax0, ax1) = plt.subplots(1, 2)\nax0.imshow(linear0, cmap='gray')\nax1.imshow(linear1, cmap='gray');",
"The library is designed in such a way that any data-type is allowed as input,\nas long as the range is correct (0-1 for floating point images, 0-255 for unsigned bytes,\n0-65535 for unsigned 16-bit integers).\nThis is achieved through the use of a few utility functions, such as img_as_float and img_as_ubyte:",
"from skimage import img_as_float, img_as_ubyte\n\nimage = data.chelsea()\n\nimage_float = img_as_float(image)\nprint(image_float.dtype, image_float.min(), image_float.max())\n\nimage_ubyte = img_as_ubyte(image)\nprint(image_ubyte.dtype, image_ubyte.min(), image_ubyte.max())\n\nprint 231/255.",
"Your code would then typically look like this:\npython\ndef my_function(any_image):\n float_image = img_as_float(any_image)\n # Proceed, knowing image is in [0, 1]\nWe recommend using the floating point representation, given that\nscikit-image mostly uses that format internally.\n<span class=\"exercize\">Exercise: draw the letter H</span>\nDefine a function that takes as input an RGB image and a pair of coordinates (row, column), and returns the image (optionally a copy) with green letter H overlaid at those coordinates. The coordinates should point to the top-left corner of the H.\nThe arms and strut of the H should have a width of 3 pixels, and the H itself should have a height of 24 pixels and width of 20 pixels.",
"def draw_H(image, coords, color=(0.8, 0.8, 0.8), in_place=True):\n out = image\n # your code goes here\n return out",
"Test your function like so:",
"cat = data.chelsea()\ncat_H = draw_H(cat, (50, -50))\nplt.imshow(cat_H);",
"<span class=\"exercize\">Bonus points: RGB intensity plot</span>\nPlot the intensity of each channel of the image along a given row.",
"def plot_intensity(image, row):\n pass # code goes here",
"Test your function here:",
"plot_intensity(coins, 50)\nplot_intensity(cat, 250)",
"<div style=\"height: 400px;\"></div>",
"%reload_ext load_style\n%load_style ../themes/tutorial.css"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
statsmodels/statsmodels.github.io
|
v0.13.2/examples/notebooks/generated/kernel_density.ipynb
|
bsd-3-clause
|
[
"Kernel Density Estimation\nKernel density estimation is the process of estimating an unknown probability density function using a kernel function $K(u)$. While a histogram counts the number of data points in somewhat arbitrary regions, a kernel density estimate is a function defined as the sum of a kernel function on every data point. The kernel function typically exhibits the following properties:\n\nSymmetry such that $K(u) = K(-u)$.\nNormalization such that $\\int_{-\\infty}^{\\infty} K(u) \\ du = 1$ .\nMonotonically decreasing such that $K'(u) < 0$ when $u > 0$.\nExpected value equal to zero such that $\\mathrm{E}[K] = 0$.\n\nFor more information about kernel density estimation, see for instance Wikipedia - Kernel density estimation.\nA univariate kernel density estimator is implemented in sm.nonparametric.KDEUnivariate.\nIn this example we will show the following:\n\nBasic usage, how to fit the estimator.\nThe effect of varying the bandwidth of the kernel using the bw argument.\nThe various kernel functions available using the kernel argument.",
"%matplotlib inline\nimport numpy as np\nfrom scipy import stats\nimport statsmodels.api as sm\nimport matplotlib.pyplot as plt\nfrom statsmodels.distributions.mixture_rvs import mixture_rvs",
"A univariate example",
"np.random.seed(12345) # Seed the random number generator for reproducible results",
"We create a bimodal distribution: a mixture of two normal distributions with locations at -1 and 1.",
"# Location, scale and weight for the two distributions\ndist1_loc, dist1_scale, weight1 = -1, 0.5, 0.25\ndist2_loc, dist2_scale, weight2 = 1, 0.5, 0.75\n\n# Sample from a mixture of distributions\nobs_dist = mixture_rvs(\n prob=[weight1, weight2],\n size=250,\n dist=[stats.norm, stats.norm],\n kwargs=(\n dict(loc=dist1_loc, scale=dist1_scale),\n dict(loc=dist2_loc, scale=dist2_scale),\n ),\n)",
"The simplest non-parametric technique for density estimation is the histogram.",
"fig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\n\n# Scatter plot of data samples and histogram\nax.scatter(\n obs_dist,\n np.abs(np.random.randn(obs_dist.size)),\n zorder=15,\n color=\"red\",\n marker=\"x\",\n alpha=0.5,\n label=\"Samples\",\n)\nlines = ax.hist(obs_dist, bins=20, edgecolor=\"k\", label=\"Histogram\")\n\nax.legend(loc=\"best\")\nax.grid(True, zorder=-5)",
"Fitting with the default arguments\nThe histogram above is discontinuous. To compute a continuous probability density function,\nwe can use kernel density estimation.\nWe initialize a univariate kernel density estimator using KDEUnivariate.",
"kde = sm.nonparametric.KDEUnivariate(obs_dist)\nkde.fit() # Estimate the densities",
"We present a figure of the fit, as well as the true distribution.",
"fig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\n\n# Plot the histrogram\nax.hist(\n obs_dist,\n bins=20,\n density=True,\n label=\"Histogram from samples\",\n zorder=5,\n edgecolor=\"k\",\n alpha=0.5,\n)\n\n# Plot the KDE as fitted using the default arguments\nax.plot(kde.support, kde.density, lw=3, label=\"KDE from samples\", zorder=10)\n\n# Plot the true distribution\ntrue_values = (\n stats.norm.pdf(loc=dist1_loc, scale=dist1_scale, x=kde.support) * weight1\n + stats.norm.pdf(loc=dist2_loc, scale=dist2_scale, x=kde.support) * weight2\n)\nax.plot(kde.support, true_values, lw=3, label=\"True distribution\", zorder=15)\n\n# Plot the samples\nax.scatter(\n obs_dist,\n np.abs(np.random.randn(obs_dist.size)) / 40,\n marker=\"x\",\n color=\"red\",\n zorder=20,\n label=\"Samples\",\n alpha=0.5,\n)\n\nax.legend(loc=\"best\")\nax.grid(True, zorder=-5)",
"In the code above, default arguments were used. We can also vary the bandwidth of the kernel, as we will now see.\nVarying the bandwidth using the bw argument\nThe bandwidth of the kernel can be adjusted using the bw argument.\nIn the following example, a bandwidth of bw=0.2 seems to fit the data well.",
"fig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\n\n# Plot the histrogram\nax.hist(\n obs_dist,\n bins=25,\n label=\"Histogram from samples\",\n zorder=5,\n edgecolor=\"k\",\n density=True,\n alpha=0.5,\n)\n\n# Plot the KDE for various bandwidths\nfor bandwidth in [0.1, 0.2, 0.4]:\n kde.fit(bw=bandwidth) # Estimate the densities\n ax.plot(\n kde.support,\n kde.density,\n \"--\",\n lw=2,\n color=\"k\",\n zorder=10,\n label=\"KDE from samples, bw = {}\".format(round(bandwidth, 2)),\n )\n\n# Plot the true distribution\nax.plot(kde.support, true_values, lw=3, label=\"True distribution\", zorder=15)\n\n# Plot the samples\nax.scatter(\n obs_dist,\n np.abs(np.random.randn(obs_dist.size)) / 50,\n marker=\"x\",\n color=\"red\",\n zorder=20,\n label=\"Data samples\",\n alpha=0.5,\n)\n\nax.legend(loc=\"best\")\nax.set_xlim([-3, 3])\nax.grid(True, zorder=-5)",
"Comparing kernel functions\nIn the example above, a Gaussian kernel was used. Several other kernels are also available.",
"from statsmodels.nonparametric.kde import kernel_switch\n\nlist(kernel_switch.keys())",
"The available kernel functions",
"# Create a figure\nfig = plt.figure(figsize=(12, 5))\n\n# Enumerate every option for the kernel\nfor i, (ker_name, ker_class) in enumerate(kernel_switch.items()):\n\n # Initialize the kernel object\n kernel = ker_class()\n\n # Sample from the domain\n domain = kernel.domain or [-3, 3]\n x_vals = np.linspace(*domain, num=2 ** 10)\n y_vals = kernel(x_vals)\n\n # Create a subplot, set the title\n ax = fig.add_subplot(3, 3, i + 1)\n ax.set_title('Kernel function \"{}\"'.format(ker_name))\n ax.plot(x_vals, y_vals, lw=3, label=\"{}\".format(ker_name))\n ax.scatter([0], [0], marker=\"x\", color=\"red\")\n plt.grid(True, zorder=-5)\n ax.set_xlim(domain)\n\nplt.tight_layout()",
"The available kernel functions on three data points\nWe now examine how the kernel density estimate will fit to three equally spaced data points.",
"# Create three equidistant points\ndata = np.linspace(-1, 1, 3)\nkde = sm.nonparametric.KDEUnivariate(data)\n\n# Create a figure\nfig = plt.figure(figsize=(12, 5))\n\n# Enumerate every option for the kernel\nfor i, kernel in enumerate(kernel_switch.keys()):\n\n # Create a subplot, set the title\n ax = fig.add_subplot(3, 3, i + 1)\n ax.set_title('Kernel function \"{}\"'.format(kernel))\n\n # Fit the model (estimate densities)\n kde.fit(kernel=kernel, fft=False, gridsize=2 ** 10)\n\n # Create the plot\n ax.plot(kde.support, kde.density, lw=3, label=\"KDE from samples\", zorder=10)\n ax.scatter(data, np.zeros_like(data), marker=\"x\", color=\"red\")\n plt.grid(True, zorder=-5)\n ax.set_xlim([-3, 3])\n\nplt.tight_layout()",
"A more difficult case\nThe fit is not always perfect. See the example below for a harder case.",
"obs_dist = mixture_rvs(\n [0.25, 0.75],\n size=250,\n dist=[stats.norm, stats.beta],\n kwargs=(dict(loc=-1, scale=0.5), dict(loc=1, scale=1, args=(1, 0.5))),\n)\n\nkde = sm.nonparametric.KDEUnivariate(obs_dist)\nkde.fit()\n\nfig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\nax.hist(obs_dist, bins=20, density=True, edgecolor=\"k\", zorder=4, alpha=0.5)\nax.plot(kde.support, kde.density, lw=3, zorder=7)\n# Plot the samples\nax.scatter(\n obs_dist,\n np.abs(np.random.randn(obs_dist.size)) / 50,\n marker=\"x\",\n color=\"red\",\n zorder=20,\n label=\"Data samples\",\n alpha=0.5,\n)\nax.grid(True, zorder=-5)",
"The KDE is a distribution\nSince the KDE is a distribution, we can access attributes and methods such as:\n\nentropy\nevaluate\ncdf\nicdf\nsf\ncumhazard",
"obs_dist = mixture_rvs(\n [0.25, 0.75],\n size=1000,\n dist=[stats.norm, stats.norm],\n kwargs=(dict(loc=-1, scale=0.5), dict(loc=1, scale=0.5)),\n)\nkde = sm.nonparametric.KDEUnivariate(obs_dist)\nkde.fit(gridsize=2 ** 10)\n\nkde.entropy\n\nkde.evaluate(-1)",
"Cumulative distribution, it's inverse, and the survival function",
"fig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\n\nax.plot(kde.support, kde.cdf, lw=3, label=\"CDF\")\nax.plot(np.linspace(0, 1, num=kde.icdf.size), kde.icdf, lw=3, label=\"Inverse CDF\")\nax.plot(kde.support, kde.sf, lw=3, label=\"Survival function\")\nax.legend(loc=\"best\")\nax.grid(True, zorder=-5)",
"The Cumulative Hazard Function",
"fig = plt.figure(figsize=(12, 5))\nax = fig.add_subplot(111)\nax.plot(kde.support, kde.cumhazard, lw=3, label=\"Cumulative Hazard Function\")\nax.legend(loc=\"best\")\nax.grid(True, zorder=-5)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
rvuduc/cse6040-ipynbs
|
21--lsq-linreg-1-errs.ipynb
|
bsd-3-clause
|
[
"CSE 6040, Fall 2015 [21]: Linear regression via least squares, Part 1 -- Error analysis\nYay! Time for a new topic: linear regression by the method of least squares.\nWe will do this topic in two parts: one which is generically about the errors that can arise in carrying out a numerical computation, and the other which is specifically about the linear regression problem.\n\nThis lab kicks off the last part of our course, which is a survey of data analysis and mining methods. We will assume you will learn the theory behind these methods in more detail in other classes; our focus will be on algorithmic and implementation concepts.\n\nFor today's topic, let's use the following dataset, which is a crimes dataset from 1960: http://cse6040.gatech.edu/fa15/uscrime.csv\nThis dataset comes from: http://www.statsci.org/data/general/uscrime.html\nOther useful references and downloads for today's class:\n\nPlease get the latest version of cse6040utils.py\nPython's documentation on its float type: https://docs.python.org/2/tutorial/floatingpoint.html\nSolvers, including linear systems solvers, in SciPy: http://docs.scipy.org/doc/scipy/reference/linalg.html\n\nAlso, much of the discussion of round-off error is taken from an excellent book on numerical linear algebra.\n\nYou may be able to use the Georgia Tech library's web proxy service to download electronic chapters of this book. Also, this book was written by Rich's former PhD advisor, so a referral thereto is probably not completely objective. :)\n\nMotivation\nLet's start by loading a dataset and motivating the problem of modeling it using linear regression.",
"import numpy as np\nimport pandas as pd\nfrom IPython.display import display\nimport cse6040utils as cse6040\n\ndf = pd.read_csv ('uscrime.csv', skiprows=1)\ndisplay (df.head ())",
"Each row of this dataset is a US State. The columns are described here: http://www.statsci.org/data/general/uscrime.html\nLet's take a quick peek at the dataset.",
"df.describe ()\n\nimport seaborn as sns\n%matplotlib inline\n\n# Look at a few relationships\nsns.pairplot (df[['Crime', 'Wealth', 'Ed', 'U1']])",
"Suppose we wish to build a model of some quantity, called the response variable, given some set of predictors. In the US crimes dataset, the response might be the crime rate (Crime), which we wish to predict from the predictors of income (Wealth), education (Ed), and the unemployment rate of young males (U1).\nIn a linear regression model, we posit that the response is a linear function of the predictors. That is, suppose there are $m$ observations in total and consider the $i$-th observation. Let $b_i$ be the response of that observation. Then denote the $n$ predictors for observation $i$ as ${a_{i,1}, a_{i,2}, \\ldots, a_{i,n}}$. From this starting point, we might then posit a linear model of $b$ having the form,\n$b_i = x_0 + a_{i,1} x_1 + a_{i,2} x_2 + \\cdots + a_{i,n} x_n$,\nwhere we wish to compute the \"best\" set of coefficients, ${x_0, x_1, \\ldots, x_n}$. Note that this model includes a constant offset term, $x_0$. Since we want this model to hold for observations, then we effectively want to solve the system of $m$ equations in $n+1$ unknowns,\n$\\left(\n \\begin{array}{c}\n b_1 \\\n b_2 \\\n \\vdots \\\n b_m\n \\end{array}\n \\right)\n$\n=\n$\\left(\n \\begin{array}{ccccc}\n 1. & a_{1,1} & a_{1,2} & \\ldots & a_{1,n} \\\n 1. & a_{2,1} & a_{2,2} & \\ldots & a_{2,n} \\\n & & \\cdots & & \\\n 1. & a_{m,1} & a_{m,2} & \\ldots & a_{m,n}\n \\end{array}\n \\right)\n \\left(\\begin{array}{c}\n x_0 \\\n x_1 \\\n \\vdots \\\n x_n\n \\end{array}\\right),\n$\nor just $Ax=b$. Typically, there are many more observations than parameters ($m \\gg n$), in which case we say this linear system is overdetermined.\nSo how do we compute $x$? Most statistical software and libraries hide the details of computing $x$ from you. However, it's important to understand at least a little bit about what happens under the hood, which is today's topic.\nAside: Models, Errors, and Algorithms -- Oh my!\nThe main task of data analysis is to help explain and understand some phenomenon by building a mathematical model from data, and analyzing the model or using it to make predictions. During this process, there are several potential sources of error, including:\n\nmeasurement errors in the data, due to limitations in our observational equipment or methodology;\nmodeling error, due to our mathematical model having simplifying assumptions;\ntruncation error, due to limitations in our computer algorithms; and\nrounding error, due to the fact that we must represent all values on the computer in finite precision.\n\nIn this course, we will mostly leave measurement and modeling errors as a topics for other courses. Instead, we will focus on truncation and rounding errors, and to a lesser extent, assessing the potential impact of measurement error.\nExercise. Are there other kinds of errors not captured in the list above?\nExercise. Give examples of the kinds of errors that might arise in our motivating problem (i.e., building a linear regression model of crime rates).\n@YOUSE: Enter your discussion / solutions here\nFloating-point arithmetic\nReal values are typically stored in IEEE floating-point format. If you have programmed in other languages, you may have seen scalar data types for single-precision and double-precision formats (e.g., float and double in C/C++/Java). A \"floating-point\" encoding is basically a normalized scientific notation consisting of a base, a sign, a fractional mantissa, and an integer exponent. Let's look at an example to see how this might work.\nConsider the value 0.125. In a normalized scientific notation, we would write this number as $+1.25 \\times 10^{-1}$, where the base is 10, the mantissa is 1.25, and the exponent is -1. Conceptually, if we always used base 10 for all our floating-point values, then our floating-point encoding of this value would, conceptually, be a tuple $(+, 1.25, -1)$. \nHowever, we cannot store an infinite number of digits for the mantissa and exponent values. Thus, we would normally also limit the number of digits that may appear in either. We might use, say, 6 digits for the mantissa and 2 digits (ignoring the sign) for the exponent, i.e., a tuple of the form $(\\pm, m.mmmmm, \\pm xx)$.\nExercise. What is the largest value we could represent in this format? What is the smallest value? What is the smallest positive value we could represent? How would we encode these values?\n@YOUSE: Enter your solutions here\nExercise. Encode the following values as tuples:\n\n$1.0$\n$-10^{-6}$\n$1.0 - 10^{-6}$\n$1.0 + 10^{-6}$\n\n@YOUSE: Enter your solutions here\n\n(+, 1.00000, +00)\n(-, 1.00000, -06)\n(+, 9.99999, -01)\n(+, 1.00000, +00)\n 0.000001 == 10^(-6)\n\nA small surprise? The consequences of finite-precision\nLet $a=1.0$ and $b=10^{-6}$. Now consider two programs.\nProgram 1:\ns = a - b\nt = s + b\n\nProgram 2:\ns = a + b\nt = s - b\n\nIf the precision, or number of digits in the encoding, were infinite, then both programs would produce t == a == 1.0.\nExercise. Suppose we instead use a finite-precision floating-point encoding, using base 10 digits with 6 digits of precision for the mantissa and 2 digits for the exponent, plus separate sign \"digits\" for each. What is the final value of t in each of these two programs?\n@YOUSE: Enter your solutions here\nThe preceding examples assume the digits are represented in base 10. However, computers encode all values using bits, which are base 2 digits. All the same ideas as above apply, but on base 2 values rather than base 10 values.\nOne consequence of this difference is that certain finite-precision decimal fractions cannot be represented exactly!\n\nCan you see why? Consider the decimal value 0.1 represented in a binary format.\n\nIn addition, the IEEE floating-point standard defines the encoding a little differently than we've used it. First, if the value is not 0, then the mantissa always has an implicit \"1\" as the leading digit; therefore, it needn't be stored explicitly, thereby saving a bit and effectively increasing the precision a little. Secondly, the range of the exponent is not symmetric. In our hypothetical base-10 \"6 + 2\" encoding, we assumed the exponent would range from -99 to 99, which is a symmetric interval; in IEEE floating-point, there will be a slight asymmetry in this range. Part of the reason is that the IEEE floating-point encoding can also represent several kinds of special values, such as infinities and an odd bird called \"not-a-number\" or NaN. This latter value, which you may have seen if you have used any standard statistical packages, can be used to encode certain kinds of floating-point exceptions that result when, for instance, you try to divide by zero.\nIn IEEE floating-point, there are two main encodings, known as single-precision (float in C/C++/Java) and double-precision (double in C/C++/Java). In brief, these differ as follows:\n\n\nSingle-precision: 32 bits total, with 24 bits for the mantissa and an exponent range of [-126, 127].\n\n\nDouble-precision: 64 bits total, with 53 bits for the mantissa and an exponent range of [-1022, 1023].\n\n\nExercise. What is the smallest positive value that can be represented in IEEE single-precision? What about in double-precision?\n@YOUSE: Enter your solutions here\nExercise. Consider the smallest possible value greater than 1.0 that can be represented in floating-point. Let's call this value, $1.0 + \\epsilon$.\nDetermine $\\epsilon_s$ and $\\epsilon_d$, the corresponding values of $\\epsilon$ in single-precision and double-precision, respectively.\n@YOUSE: Enter your solutions here\nAnother important consequence of the binary format is that when you print things in base ten, what you see may not be what you get! For instance, try running the code below.",
"from decimal import Decimal\n\nx = 1.0 + 2.0**(-52)\n\nprint x\nprint Decimal (x) # What does this do?",
"Aside: If you ever need true decimal storage with no loss of precision, turn to the Decimal package. Just be warned it will come at a price:",
"a_native = 1.0\nb_native = 2.0\n\na_decimal = Decimal ('1.0')\nb_decimal = Decimal ('2.0')\n\n%timeit a_native + b_native\n%timeit a_decimal + b_decimal",
"For today's lesson, it will be helpful to occasionally peek at floating-point values \"in the raw.\" For this purpose, we've provided you with a handy routine called float_to_bin(x), which given a floating-point value x will return its IEEE representation as a binary string. (It is defined in the cse6040utils module.)\nThe following code uses float_to_bin() to define another function that dumps a floating-point number's complete Decimal form along with its binary form.",
"def print_float_bin (x, prefix=\"\"):\n print (\"%s: %s\\n%s %s\" % (prefix,\n Decimal (x),\n ' ' * len (prefix),\n cse6040.float_to_bin (x))) \n\na = -1.0\nb = 2.**(-52) # Recall: \\epsilon_d\nc = b / 2.\n\nprint_float_bin (a, prefix=\"a\")\nprint_float_bin (b, prefix=\"b\")\nprint_float_bin (c, prefix=\"c\")",
"Exercise. Recall the two program fragments from above:\nProgram 1:\ns = a - b\nt = s + b\n\nProgram 2:\ns = a + b\nt = s - b\n\nLet $a=1.0$ and $b=\\epsilon_d / 2 \\approx 1.11 \\times 10^{-16}$. Write some Python code to evaluate these two programs and compare their outputs. (To look closely at their outputs, use the print_float_bin() function from above.)",
"a = 1.0\nb = 2.**(-53) # What value goes here?\n\ns1 = a - b\nt1 = s1 + b\n\ns2 = a + b\nt2 = s2 - b\n\nprint_float_bin (s1, prefix=\"s1\")\nprint_float_bin (t1, prefix=\"t1\")\nprint (\"\\n\")\nprint_float_bin (s2, prefix=\"s2\")\nprint_float_bin (t2, prefix=\"t2\")\n\nprint \"\\n\", t1, t2\nprint (\"\\n(t1 == t2) == %s\" % (t1 == t2))",
"By the way, in Numpy you can determine machine epsilon in a more portable way:",
"EPS_S = np.finfo (np.float32).eps\nEPS_D = np.finfo (float).eps\n\nprint_float_bin (float (EPS_S), prefix=\"eps_s\")\nprint_float_bin (float (EPS_D), prefix=\"eps_d\")",
"Perturbation theory and condition numbers\nGiven the various sources of error, how do we know whether a given algorithm is \"good\" for computing the solution to a given problem? An important tool in the area of numerical analysis is perturbation theory.\nTo see perturbation theory in action, suppose we wish to determine by how much a \"small\" measurement error, $\\Delta x$, affects the output of some function, $f(x)$. Barring any other information and assuming $f(x)$ is continuous and differentiable, we could try to estimate the error of evaluating $f(x + \\Delta x)$ compared to $f(x)$ by the following linear approximation, which comes from a Taylor series expansion:\n$$f(x + \\Delta x) \\approx f(x) + \\Delta x \\cdot f'(x),$$\nwhere $f'(x)$ is the first derivative of $f(x)$ at the point $x$.\nAbsolute condition numbers. From this relation, we can compute an upper-bound on the absolute value of the error:\n$$\\left|f(x + \\Delta x) - f(x)\\right| \\approx \\left|\\Delta x\\right| \\cdot \\left|f'(x)\\right|.$$\nThis calculation says that the error depends not only on the measurement error, $\\Delta x$, but also the nature of the function itself at $x$ through the factor, $\\left|f'(x)\\right|$. Indeed, we will give this factor a special name of absolute condition number of evaluating $f$ at $x$. For any given computational problem, we will try to find condition numbers to help us quantify the \"hardness\" of the problem.\nThat is, for the problem of evaluating $f(x)$, the preceding analysis says that if this factor is not too large, then small measurement errors will lead to only small errors in the output. In this case, we say the problem is well-conditioned. If instead this factor is very large, then even very small errors will lead to large errors in the output. In this case, we say the problem is ill-conditioned.\nPut differently, the problem of evaluating $f(x)$ when the condition number is large is inherently more difficult than doing so when the condition number is small.\nRelative condition numbers. The error considered above is the absolute error, in contrast to the relative error,\n$$\\left|f(x + \\Delta x) - f(x)\\right| / \\left|f(x)\\right|.$$\nFor this case and problem of evaluating $f(x)$, let's rewrite this slightly as,\n$$\\frac{\\left|f(x + \\Delta x) - f(x)\\right|}\n {\\left|f(x)\\right|}\n\\approx\n \\frac{|\\Delta x|}\n {|x|}\n \\cdot\n\\underbrace{\n \\frac{\\left|f'(x)\\right| \\cdot |x|}\n {\\left|f(x)\\right|}\n}_{\\equiv\\ \\kappa_r(x)}\n,$$\nwhere $\\kappa_r(x)$ is the relative condition number of evaluating $f(x)$ at $x$.\nObserve that this relation expresses the relative change in the output as a function of some relative change in the input ($|\\Delta x| / |x|$).\nBackward stability. Let's say someone devises an algorithm to compute $f(x)$. For a given value $x$, let's suppose this algorithm produces the value $\\mathrm{alg}(x)$. One important question might be, is that output \"good\" or \"bad?\"\nOne property to measure \"goodness\" will be backward stability. In particular, we will say that $\\mathrm{alg}(x)$ is a backward stable algorithm to compute $f(x)$ if, for all $x$, there exists a \"small\" $\\Delta x$ such that\n$$\\mathrm{alg}(x) = f(x + \\Delta x).$$\nThat should look familiar! It means we can estimate the (absolute) backward error using our perturbation analysis from before, i.e.,\n$$\\left|\\mathrm{alg}(x) - f(x)\\right| \\approx \\left|f'(x)\\right| \\cdot \\left|\\Delta x\\right|.$$\nRound-off errors. We already know that numerical values can only be represented finitely, which introduces round-off error. Thus, at the very least we should hope that a scheme to compute $f(x)$ is as insensitive to round-off errors as possible.\nTo quantify sensitivity, the standard technique is to assume that every scalar floating-point operation incurs some bounded error. Let $a \\odot b$ be the exact result of some mathematical operation on $a$ and $b$, and let $\\mathrm{fl}(a \\odot b)$ be the computed value, after rounding in finite-precision. We will model the difference by,\n$$\\mathrm{fl}(a \\odot b) \\equiv (a \\odot b) (1 + \\delta),$$\nwhere $|\\delta| \\leq \\epsilon$, machine epsilon.\n(Left off here)\nIn class, we left off at this point. Indeed, there were some errors in the text that had appeared below, so they have been removed. We will pick up here (with the correct text!) in the next class."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
herruzojm/udacity-deep-learning
|
intro-to-tensorflow/intro_to_tensorflow.ipynb
|
mit
|
[
"<h1 align=\"center\">TensorFlow Neural Network Lab</h1>\n\n<img src=\"image/notmnist.png\">\nIn this lab, you'll use all the tools you learned from Introduction to TensorFlow to label images of English letters! The data you are using, <a href=\"http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html\">notMNIST</a>, consists of images of a letter from A to J in different fonts.\nThe above images are a few examples of the data you'll be training on. After training the network, you will compare your prediction model against test data. Your goal, by the end of this lab, is to make predictions against that test set with at least an 80% accuracy. Let's jump in!\nTo start this lab, you first need to import all the necessary modules. Run the code below. If it runs successfully, it will print \"All modules imported\".",
"import hashlib\nimport os\nimport pickle\nfrom urllib.request import urlretrieve\n\nimport numpy as np\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.utils import resample\nfrom tqdm import tqdm\nfrom zipfile import ZipFile\n\nprint('All modules imported.')",
"The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J).",
"def download(url, file):\n \"\"\"\n Download file from <url>\n :param url: URL to file\n :param file: Local file path\n \"\"\"\n if not os.path.isfile(file):\n print('Downloading ' + file + '...')\n urlretrieve(url, file)\n print('Download Finished')\n\n# Download the training and test dataset.\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_train.zip', 'notMNIST_train.zip')\ndownload('https://s3.amazonaws.com/udacity-sdc/notMNIST_test.zip', 'notMNIST_test.zip')\n\n# Make sure the files aren't corrupted\nassert hashlib.md5(open('notMNIST_train.zip', 'rb').read()).hexdigest() == 'c8673b3f28f489e9cdf3a3d74e2ac8fa',\\\n 'notMNIST_train.zip file is corrupted. Remove the file and try again.'\nassert hashlib.md5(open('notMNIST_test.zip', 'rb').read()).hexdigest() == '5d3c7e653e63471c88df796156a9dfa9',\\\n 'notMNIST_test.zip file is corrupted. Remove the file and try again.'\n\n# Wait until you see that all files have been downloaded.\nprint('All files downloaded.')\n\ndef uncompress_features_labels(file):\n \"\"\"\n Uncompress features and labels from a zip file\n :param file: The zip file to extract the data from\n \"\"\"\n features = []\n labels = []\n\n with ZipFile(file) as zipf:\n # Progress Bar\n filenames_pbar = tqdm(zipf.namelist(), unit='files')\n \n # Get features and labels from all files\n for filename in filenames_pbar:\n # Check if the file is a directory\n if not filename.endswith('/'):\n with zipf.open(filename) as image_file:\n image = Image.open(image_file)\n image.load()\n # Load image data as 1 dimensional array\n # We're using float32 to save on memory space\n feature = np.array(image, dtype=np.float32).flatten()\n\n # Get the the letter from the filename. This is the letter of the image.\n label = os.path.split(filename)[1][0]\n\n features.append(feature)\n labels.append(label)\n return np.array(features), np.array(labels)\n\n# Get the features and labels from the zip files\ntrain_features, train_labels = uncompress_features_labels('notMNIST_train.zip')\ntest_features, test_labels = uncompress_features_labels('notMNIST_test.zip')\n\n# Limit the amount of data to work with a docker container\ndocker_size_limit = 150000\ntrain_features, train_labels = resample(train_features, train_labels, n_samples=docker_size_limit)\n\n# Set flags for feature engineering. This will prevent you from skipping an important step.\nis_features_normal = False\nis_labels_encod = False\n\n# Wait until you see that all features and labels have been uncompressed.\nprint('All features and labels uncompressed.')",
"<img src=\"image/Mean_Variance_Image.png\" style=\"height: 75%;width: 75%; position: relative; right: 5%\">\nProblem 1\nThe first problem involves normalizing the features for your training and test data.\nImplement Min-Max scaling in the normalize_grayscale() function to a range of a=0.1 and b=0.9. After scaling, the values of the pixels in the input data should range from 0.1 to 0.9.\nSince the raw notMNIST image data is in grayscale, the current values range from a min of 0 to a max of 255.\nMin-Max Scaling:\n$\nX'=a+{\\frac {\\left(X-X_{\\min }\\right)\\left(b-a\\right)}{X_{\\max }-X_{\\min }}}\n$\nIf you're having trouble solving problem 1, you can view the solution here.",
"# Problem 1 - Implement Min-Max scaling for grayscale image data\ndef normalize_grayscale(image_data):\n \"\"\"\n Normalize the image data with Min-Max scaling to a range of [0.1, 0.9]\n :param image_data: The image data to be normalized\n :return: Normalized image data\n \"\"\"\n # Implement Min-Max scaling for grayscale image data\n x_max = 255\n x_min = 0\n a = 0.1\n b = 0.9\n return a + ( ((image_data - x_min)*(0.9-0.1))/(x_max - x_min) )\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Test Cases\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 255])),\n [0.1, 0.103137254902, 0.106274509804, 0.109411764706, 0.112549019608, 0.11568627451, 0.118823529412, 0.121960784314,\n 0.125098039216, 0.128235294118, 0.13137254902, 0.9],\n decimal=3)\nnp.testing.assert_array_almost_equal(\n normalize_grayscale(np.array([0, 1, 10, 20, 30, 40, 233, 244, 254,255])),\n [0.1, 0.103137254902, 0.13137254902, 0.162745098039, 0.194117647059, 0.225490196078, 0.830980392157, 0.865490196078,\n 0.896862745098, 0.9])\n\nif not is_features_normal:\n train_features = normalize_grayscale(train_features)\n test_features = normalize_grayscale(test_features)\n is_features_normal = True\n\nprint('Tests Passed!')\n\nif not is_labels_encod:\n # Turn labels into numbers and apply One-Hot Encoding\n encoder = LabelBinarizer()\n encoder.fit(train_labels)\n train_labels = encoder.transform(train_labels)\n test_labels = encoder.transform(test_labels)\n\n # Change to float32, so it can be multiplied against the features in TensorFlow, which are float32\n train_labels = train_labels.astype(np.float32)\n test_labels = test_labels.astype(np.float32)\n is_labels_encod = True\n\nprint('Labels One-Hot Encoded')\n\nassert is_features_normal, 'You skipped the step to normalize the features'\nassert is_labels_encod, 'You skipped the step to One-Hot Encode the labels'\n\n# Get randomized datasets for training and validation\ntrain_features, valid_features, train_labels, valid_labels = train_test_split(\n train_features,\n train_labels,\n test_size=0.05,\n random_state=832289)\n\nprint('Training features and labels randomized and split.')\n\n# Save the data for easy access\npickle_file = 'notMNIST.pickle'\nif not os.path.isfile(pickle_file):\n print('Saving data to pickle file...')\n try:\n with open('notMNIST.pickle', 'wb') as pfile:\n pickle.dump(\n {\n 'train_dataset': train_features,\n 'train_labels': train_labels,\n 'valid_dataset': valid_features,\n 'valid_labels': valid_labels,\n 'test_dataset': test_features,\n 'test_labels': test_labels,\n },\n pfile, pickle.HIGHEST_PROTOCOL)\n except Exception as e:\n print('Unable to save data to', pickle_file, ':', e)\n raise\n\nprint('Data cached in pickle file.')",
"Checkpoint\nAll your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed.",
"%matplotlib inline\n\n# Load the modules\nimport pickle\nimport math\n\nimport numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\n# Reload the data\npickle_file = 'notMNIST.pickle'\nwith open(pickle_file, 'rb') as f:\n pickle_data = pickle.load(f)\n train_features = pickle_data['train_dataset']\n train_labels = pickle_data['train_labels']\n valid_features = pickle_data['valid_dataset']\n valid_labels = pickle_data['valid_labels']\n test_features = pickle_data['test_dataset']\n test_labels = pickle_data['test_labels']\n del pickle_data # Free up memory\n\nprint('Data and modules loaded.')",
"Problem 2\nNow it's time to build a simple neural network using TensorFlow. Here, your network will be just an input layer and an output layer.\n<img src=\"image/network_diagram.png\" style=\"height: 40%;width: 40%; position: relative; right: 10%\">\nFor the input here the images have been flattened into a vector of $28 \\times 28 = 784$ features. Then, we're trying to predict the image digit so there are 10 output units, one for each label. Of course, feel free to add hidden layers if you want, but this notebook is built to guide you through a single layer network. \nFor the neural network to train on your data, you need the following <a href=\"https://www.tensorflow.org/resources/dims_types.html#data-types\">float32</a> tensors:\n - features\n - Placeholder tensor for feature data (train_features/valid_features/test_features)\n - labels\n - Placeholder tensor for label data (train_labels/valid_labels/test_labels)\n - weights\n - Variable Tensor with random numbers from a truncated normal distribution.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/constant_op.html#truncated_normal\">tf.truncated_normal() documentation</a> for help.\n - biases\n - Variable Tensor with all zeros.\n - See <a href=\"https://www.tensorflow.org/api_docs/python/constant_op.html#zeros\"> tf.zeros() documentation</a> for help.\nIf you're having trouble solving problem 2, review \"TensorFlow Linear Function\" section of the class. If that doesn't help, the solution for this problem is available here.",
"# All the pixels in the image (28 * 28 = 784)\nfeatures_count = 784\n# All the labels\nlabels_count = 10\n\n# Set the features and labels tensors\nfeatures = tf.placeholder(tf.float32)\nlabels = tf.placeholder(tf.float32)\n\n# Set the weights and biases tensors\nweights = tf.Variable(tf.truncated_normal((features_count, labels_count)))\nbiases = tf.Variable(tf.zeros(labels_count))\n\n### DON'T MODIFY ANYTHING BELOW ###\n\n#Test Cases\nfrom tensorflow.python.ops.variables import Variable\n\nassert features._op.name.startswith('Placeholder'), 'features must be a placeholder'\nassert labels._op.name.startswith('Placeholder'), 'labels must be a placeholder'\nassert isinstance(weights, Variable), 'weights must be a TensorFlow variable'\nassert isinstance(biases, Variable), 'biases must be a TensorFlow variable'\n\nassert features._shape == None or (\\\n features._shape.dims[0].value is None and\\\n features._shape.dims[1].value in [None, 784]), 'The shape of features is incorrect'\nassert labels._shape == None or (\\\n labels._shape.dims[0].value is None and\\\n labels._shape.dims[1].value in [None, 10]), 'The shape of labels is incorrect'\nassert weights._variable._shape == (784, 10), 'The shape of weights is incorrect'\nassert biases._variable._shape == (10), 'The shape of biases is incorrect'\n\nassert features._dtype == tf.float32, 'features must be type float32'\nassert labels._dtype == tf.float32, 'labels must be type float32'\n\n# Feed dicts for training, validation, and test session\ntrain_feed_dict = {features: train_features, labels: train_labels}\nvalid_feed_dict = {features: valid_features, labels: valid_labels}\ntest_feed_dict = {features: test_features, labels: test_labels}\n\n# Linear Function WX + b\nlogits = tf.matmul(features, weights) + biases\n\nprediction = tf.nn.softmax(logits)\n\n# Cross entropy\ncross_entropy = -tf.reduce_sum(labels * tf.log(prediction), reduction_indices=1)\n\n# Training loss\nloss = tf.reduce_mean(cross_entropy)\n\n# Create an operation that initializes all variables\ninit = tf.global_variables_initializer()\n\n# Test Cases\nwith tf.Session() as session:\n session.run(init)\n session.run(loss, feed_dict=train_feed_dict)\n session.run(loss, feed_dict=valid_feed_dict)\n session.run(loss, feed_dict=test_feed_dict)\n biases_data = session.run(biases)\n\nassert not np.count_nonzero(biases_data), 'biases must be zeros'\n\nprint('Tests Passed!')\n\n# Determine if the predictions are correct\nis_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels, 1))\n# Calculate the accuracy of the predictions\naccuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))\n\nprint('Accuracy function created.')",
"<img src=\"image/Learn_Rate_Tune_Image.png\" style=\"height: 70%;width: 70%\">\nProblem 3\nBelow are 2 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy.\nParameter configurations:\nConfiguration 1\n* Epochs: 1\n* Learning Rate:\n * 0.8\n * 0.5\n * 0.1\n * 0.05\n * 0.01\nConfiguration 2\n* Epochs:\n * 1\n * 2\n * 3\n * 4\n * 5\n* Learning Rate: 0.2\nThe code will print out a Loss and Accuracy graph, so you can see how well the neural network performed.\nIf you're having trouble solving problem 3, you can view the solution here.",
"# Change if you have memory restrictions\nbatch_size = 128\n\n# Find the best parameters for each configuration\nepochs = 5\nlearning_rate = 0.2\n\n\n\n### DON'T MODIFY ANYTHING BELOW ###\n# Gradient Descent\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) \n\n# The accuracy measured against the validation set\nvalidation_accuracy = 0.0\n\n# Measurements use for graphing loss and accuracy\nlog_batch_step = 50\nbatches = []\nloss_batch = []\ntrain_acc_batch = []\nvalid_acc_batch = []\n\nwith tf.Session() as session:\n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer and get loss\n _, l = session.run(\n [optimizer, loss],\n feed_dict={features: batch_features, labels: batch_labels})\n\n # Log every 50 batches\n if not batch_i % log_batch_step:\n # Calculate Training and Validation accuracy\n training_accuracy = session.run(accuracy, feed_dict=train_feed_dict)\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\n # Log batches\n previous_batch = batches[-1] if batches else 0\n batches.append(log_batch_step + previous_batch)\n loss_batch.append(l)\n train_acc_batch.append(training_accuracy)\n valid_acc_batch.append(validation_accuracy)\n\n # Check accuracy against Validation data\n validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)\n\nloss_plot = plt.subplot(211)\nloss_plot.set_title('Loss')\nloss_plot.plot(batches, loss_batch, 'g')\nloss_plot.set_xlim([batches[0], batches[-1]])\nacc_plot = plt.subplot(212)\nacc_plot.set_title('Accuracy')\nacc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')\nacc_plot.plot(batches, valid_acc_batch, 'x', label='Validation Accuracy')\nacc_plot.set_ylim([0, 1.0])\nacc_plot.set_xlim([batches[0], batches[-1]])\nacc_plot.legend(loc=4)\nplt.tight_layout()\nplt.show()\n\nprint('Validation accuracy at {}'.format(validation_accuracy))",
"Test\nYou're going to test your model against your hold out dataset/testing data. This will give you a good indicator of how well the model will do in the real world. You should have a test accuracy of at least 80%.",
"### DON'T MODIFY ANYTHING BELOW ###\n# The accuracy measured against the test set\ntest_accuracy = 0.0\n\nwith tf.Session() as session:\n \n session.run(init)\n batch_count = int(math.ceil(len(train_features)/batch_size))\n\n for epoch_i in range(epochs):\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n batch_features = train_features[batch_start:batch_start + batch_size]\n batch_labels = train_labels[batch_start:batch_start + batch_size]\n\n # Run optimizer\n _ = session.run(optimizer, feed_dict={features: batch_features, labels: batch_labels})\n\n # Check accuracy against Test data\n test_accuracy = session.run(accuracy, feed_dict=test_feed_dict)\n\n\nassert test_accuracy >= 0.80, 'Test accuracy at {}, should be equal to or greater than 0.80'.format(test_accuracy)\nprint('Nice Job! Test Accuracy is {}'.format(test_accuracy))",
"Multiple layers\nGood job! You built a one layer TensorFlow network! However, you might want to build more than one layer. This is deep learning after all! In the next section, you will start to satisfy your need for more layers."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
opencb/opencga
|
opencga-client/src/main/python/notebooks/general-notebooks/pyopencga_basic_notebook_001.ipynb
|
apache-2.0
|
[
"pyopencga Basic User Usage\n\n[NOTE] The server methods used by pyopencga client are defined in the following swagger URL:\n- http://bioinfo.hpc.cam.ac.uk/opencga-demo/webservices\nFor tutorials and more info about accessing the OpenCGA REST please read the documentation at http://docs.opencb.org/display/opencga/Python\nLoading pyOpenCGA\nYou have two main options\na) From source code: If you need to import from the source code remember that Python3 does not accept relative importing, so you need to append the module path to sys.path \nb) Installed pyopencga (recommended): You can import pyopencga directly (skip next section) if you have installed pyopencga with pip install pyopencga\nPreparing environment for importing from source",
"# Initialize PYTHONPATH for pyopencga\nimport sys\nimport os\nfrom pprint import pprint\n\ncwd = os.getcwd()\nprint(\"current_dir: ....\"+cwd[-10:])\n\nbase_modules_dir = os.path.dirname(cwd)\nprint(\"base_modules_dir: ....\"+base_modules_dir[-10:])\n\nsys.path.append(base_modules_dir)\n",
"Importing pyopencga Library\nThis is the recommended way of using pyopencga",
"from pyopencga.opencga_config import ClientConfiguration\nfrom pyopencga.opencga_client import OpencgaClient\nfrom pprint import pprint\nimport json\n",
"Setup client and login\nConfiguration and Credentials \nYou need to provide a server URL in the standard configuration format for OpenCGA as a dict or in a json file\nRegarding credentials, if you don't pass the password, it would be asked interactively without echo.",
"# server host\nhost = 'http://bioinfo.hpc.cam.ac.uk/opencga-prod'\n\n# user credentials\nuser = \"demouser\"\npasswd = \"demouser\" ## you can skip this, see below.\n\n# the user demo access projects from user opencga\nprj_owner = \"demo\"\n",
"Creating ConfigClient for server connection configuration",
"# Creating ClientConfiguration dict\nhost = 'http://bioinfo.hpc.cam.ac.uk/opencga-prod'\n\nconfig_dict = {\"rest\": {\n \"host\": host \n }\n }\n\nprint(\"Config information:\\n\",config_dict)\n",
"Initialize the client configuration\nYou can pass a dictionary to the ClientConfiguration",
"config = ClientConfiguration(config_dict)\noc = OpencgaClient(config)\n",
"Make the login",
"# here we put only the user in order to be asked for the password interactively\n# oc.login(user)\n\n# or you can pass the user and passwd\noc.login(user, passwd)",
"You are now connected to OpenCGA\nWorking with RestResponse results\nAll OpenCGA client libraris including pyopencga implement a RestReponse wrapper object to make even easier to work with REST web services responses. REST responsess include metadata and OpenCGA 2.0.0 has been designed to work in a federation mode, all these can make a bit difficult to start working with the responses. Please read this brief documentation http://docs.opencb.org/display/opencga/RESTful+Web+Services#RESTfulWebServices-OpenCGA2.x\nLet's see a quick example of how to use RESTResponse wrapper in pyopencga. You can get some extra inforamtion here http://docs.opencb.org/display/opencga/Python#Python-WorkingwiththeRestResponse. Let's execute a first simple query to fetch all projects for the user demouser (already logged in):",
"## Let's fecth the available projects.\n## First let's get the project client and execute search() funciton\nproject_client = oc.projects\nprojects = project_client.search()\n\n## Uncomment this line to view the JSON response.\n## NOTE: it incudes study information so this can be big\n##pprint(projects.get_responses())",
"Although you can iterate through all diferent projects by executing this, this is not recommended way.",
"## Loop through all diferent projects \nfor project in projects.responses[0]['results']:\n print(project['id'], project['name'])",
"Using RestResponse object makes things much easier!\nYou can use get_results function to iterate over all results, in this case the projects:",
"## Loop through all diferent projects \nfor project in projects.get_results():\n print(project['id'], project['name'])",
"You can also iterate results, this is specially interesting when fetching many results from the server:",
"## Iterate through all diferent projects \nfor project in projects.result_iterator():\n print(project['id'], project['name'])",
"IMPORTANT: RestResponse obejct implements a very powerful custom function to print results :-)",
"## This function iterates over all the results, it can be configured to exclude metadata, change separator or even select the fields!\nprojects.print_results()",
"With print_results you can even print nested fields in an array:",
"## Lets exclude metadata and print only few fields, use dot notation for ensted fields\nprojects.print_results(fields='id,name,organism.scientificName,organism.assembly',metadata=False)\n\n## You can change separator\nprint()\nprint('With a different separator:\\n')\nprojects.print_results(fields='id,name,organism.scientificName,organism.assembly', separator=',', metadata=False)\n",
"Working with Users",
"# Listing available methods for the user client object\nuser_client = oc.users\n\n\n## getting user information\n## [NOTE] User needs the quey_id string directly --> (user)\nuser_info = user_client.info(user).get_result(0)\n\nprint(\"user info:\")\nprint(\"name: {}\\towned_projects: {}\".format(user_info[\"name\"], len(user_info[\"projects\"])))\n",
"The demouser has not projects from its own, but has been granted access to some projects from demo user. Let's see how to find it out.\nWe need to list user's projects using project client search() function.",
"## Getting user projects\n## [NOTE] Client specific methods have the query_id as a key:value (i.e (user=user_id)) \nproject_client = oc.projects\nprojects_info = project_client.search()\n\nprojects_info.print_results(fields='id,name,organism.scientificName,organism.assembly', metadata=False)\n",
"User demo has access to one project called demo@family\nWorking with Projects\nAs seen above you can fetch projects and studies for the logged user executing this:\nNOTE: in opencga the projects and studies have a full qualified name (fqn) with the format [owner]@[project]:[study]",
"## Getting all projects from logged in user\nproject_client = oc.projects\nprojects = project_client.search()\n\nfor project in projects.get_results():\n print(\"Name: {}\\tFQN: {}\".format(project[\"name\"], project[\"fqn\"]))",
"All OpenCGA REST web services accept many parameters to filter results:",
"## Getting information from a specific project\nproject_id = 'family'\n\n## you can also use the following command:\n## projects = project_client.search(id=project_id)\n\nprojects = project_client.info(project_id)\nproject = projects.get_result(0)\n\n# Print the studies in the project\nfor study in project['studies']:\n print(\"project:{}\\t study:{}\".format(project_id, study['id']))",
"Fetch studies for a given project:",
"## Fetching the studies from a project using the studies method\n# studies = project_client.studies(project_id)\n# for study in studies.get_results():\n# pprint(study)",
"Working with Samples\nTo fetch samples you need to use the sample client built in pyopencga:",
"## Let's print samples from platinum usinf project:study notation\nstudy_id = 'family:platinum'\nsamples = oc.samples.search(study=study_id, count=True, limit = 2) ## other params@ , count=True, id='NA12880,NA12881'\nsamples.print_results()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
tritemio/pybroom
|
doc/notebooks/pybroom-example-multi-datasets-scipy-robust-fit.ipynb
|
mit
|
[
"PyBroom Example - Multiple Datasets - Scipy Robust Fit\nThis notebook is part of pybroom.\n\nThis notebook demonstrate using pybroom when fitting a set of curves (curve fitting) using robust fitting and scipy.\nWe will show that pybroom greatly simplifies comparing, filtering and plotting fit results \nfrom multiple datasets.\nSee\npybroom-example-multi-datasets\nfor an example using lmfit.Model instead of directly scipy.",
"%matplotlib inline\n%config InlineBackend.figure_format='retina' # for hi-dpi displays\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.pylab import normpdf\nimport seaborn as sns\nfrom lmfit import Model\nimport lmfit\nprint('lmfit: %s' % lmfit.__version__)\n\nsns.set_style('whitegrid')\n\nimport pybroom as br",
"Create Noisy Data\nWe start simulating N datasets which are identical except for the additive noise.",
"N = 200\n\nx = np.linspace(-10, 10, 101)\n\npeak1 = lmfit.models.GaussianModel(prefix='p1_')\npeak2 = lmfit.models.GaussianModel(prefix='p2_')\nmodel = peak1 + peak2\n\n#params = model.make_params(p1_amplitude=1.5, p2_amplitude=1, \n# p1_sigma=1, p2_sigma=1)\n\nY_data = np.zeros((N, x.size))\nY_data.shape, x.shape\n\nfor i in range(Y_data.shape[0]):\n Y_data[i] = model.eval(x=x, p1_center=-1, p2_center=2, \n p1_sigma=0.5, p2_sigma=1, \n p1_height=1, p2_height=0.5)\nY_data += np.random.randn(*Y_data.shape)/10",
"Add some outliers:",
"num_outliers = int(Y_data.size * 0.05)\nidx_ol = np.random.randint(low=0, high=Y_data.size, size=num_outliers)\nY_data.reshape(-1)[idx_ol] = (np.random.rand(num_outliers) - 0.5)*4\n\nplt.plot(x, Y_data.T, 'ok', alpha=0.1);\nplt.title('%d simulated datasets, with outliers' % N);",
"Model Fitting\ncurve_fit()",
"import scipy.optimize as so\n\nfrom collections import namedtuple\n\n# Model PDF to be maximized\ndef model_pdf(x, a1, a2, mu1, mu2, sig1, sig2):\n return (a1 * normpdf(x, mu1, sig1) + \n a2 * normpdf(x, mu2, sig2))\n\nresult = so.curve_fit(model_pdf, x, Y_data[0])\n\ntype(result), type(result[0]), type(result[1])\n\nresult[0]",
"Using a namedtuple is a clean way to assign names to an array of paramenters:",
"Params = namedtuple('Params', 'a1 a2 mu1 mu2 sig1 sig2')\n\np = Params(*result[0])\np",
"Unfortunately, not much data is returned by curve_fit, a 2-element tuple with:\n\narray of best-fit parameters\narray of jacobian\n\nTherefore curve_fit is not very useful for detailed comparison of fit results. \nA better interface for curve fitting would be lmfit.Model (see \nthis other notebook).\nIn the current notebook we keep exploring further options offered by scipy.optimize.\nleast_squares()\nAs an example, we use the least_squares function which supports robust loss functions and constraints.\nWe need to define the residuals:",
"def residuals(p, x, y):\n return y - model_pdf(x, *p)",
"Then, we fit the N datasets with different loss functions storing result in a dict containing lists:",
"losses = ('linear', 'huber', 'cauchy')\nResults = {}\nfor loss in losses:\n Results[loss] = [so.least_squares(residuals, (1,1,0,1,1,1), args=(x, y), loss=loss, f_scale=0.5)\n for y in Y_data]",
"<div class=\"alert alert-info\">\n\n**NOTE**: For more details on robust fitting and on the different loss functions see\n[Robust nonlinear regression in scipy](http://scipy-cookbook.readthedocs.io/items/robust_regression.html).\n\n</div>",
"# result = Results['cauchy'][0]\n# for k in result.keys():\n# print(k, type(result[k]))",
"Tidying the results\nNow we tidy the results, combining the results for the different loss functions\nin a single DataFrames.\nWe start with the glance function, which returns one row per fit result:",
"dg_tot = br.glance(Results, var_names=['loss', 'dataset'])\ndg_tot.head()\n\ndg_tot.success.all()",
"Then we apply tidy, which returns one row per parameter.\nSince the object OptimzeResult returned by scipy.optimize does \nonly contains an array of parameters, we need to pass the names as\nas additional argument:",
"pnames = 'a1 a2 mu1 mu2 sig1 sig2'\ndt_tot = br.tidy(Results, var_names=['loss', 'dataset'], param_names=pnames)\ndt_tot.head()",
"Finally, we cannot apply the\naugment function, since the OptimizeResult object\ndoes not include much per-data-point information \n(it may contain the array of residuals).\nPlots\nFirst we plot the peak position and sigmas distributions:",
"kws = dict(bins = np.arange(-2, 4, 0.1), histtype='step', lw=2)\nfor loss in losses:\n dt_tot.query('(name == \"mu1\" or name == \"mu2\") and loss == \"%s\"' % loss)['value'].hist(label=loss, **kws)\n kws['ax'] = plt.gca()\nplt.title(' Distribution of peaks centers')\nplt.legend();\n\nkws = dict(bins = np.arange(0, 4, 0.1), histtype='step', lw=2)\nfor loss in losses:\n dt_tot.query('(name == \"sig1\" or name == \"sig2\") and loss == \"%s\"' % loss)['value'].hist(label=loss, **kws)\n kws['ax'] = plt.gca()\nplt.title(' Distribution of peaks sigmas')\nplt.legend();",
"A more complete overview for all the fit paramenters can be obtained with a factorplot:",
"sns.factorplot(x='loss', y='value', data=dt_tot, col='name', hue='loss',\n col_wrap=4, kind='box', sharey=False);",
"From all the previous plots we see that, as espected, using robust fitting \nwith higher damping of outlier (i.e. cauchy vs huber or linear) \nresults in more accurate fit results.\nFinally, we can have a peek at the comparison of raw data and fitted models\nfor a few datatsets.\nSince OptimizeResults does not include \"augmented\" data we need to \ngenerate these data by evaluating the model with the best-fit parameters.\nWe use seaborn's FacetGrid, passing a custom function _plot\nfor model evaluation:",
"def _plot(names, values, x, label=None, color=None):\n df = pd.concat([names, values], axis=1)\n kw_pars = br.tidy_to_dict(df)\n y = model_pdf(x, **kw_pars)\n plt.plot(x, y, lw=2, color=color, label=label) \n\ngrid = sns.FacetGrid(dt_tot.query('dataset < 9'), col='dataset', hue='loss', col_wrap=3)\ngrid.map(_plot, 'name', 'value', x=x)\ngrid.add_legend()\nfor i, ax in enumerate(grid.axes):\n ax.plot(x, Y_data[i], 'o', ms=3, color='k')\nplt.ylim(-1, 1.5)",
"For comparison, the ModelResult object returned by lmfit,\ncontains not only the evaluated model but also the evaluation\nof the single components (each single peak in this case).\nTherefore the above plot can be generated more straighforwardly\nusing the \"augmented\" data.\nSee the notebook pybroom-example-multi-datasets\nfor an example."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
llulai/deep-learning
|
autoencoder/Simple_Autoencoder.ipynb
|
mit
|
[
"A Simple Autoencoder\nWe'll start off by building a simple autoencoder to compress the MNIST dataset. With autoencoders, we pass input data through an encoder that makes a compressed representation of the input. Then, this representation is passed through a decoder to reconstruct the input data. Generally the encoder and decoder will be built with neural networks, then trained on example data.\n\nIn this notebook, we'll be build a simple network architecture for the encoder and decoder. Let's get started by importing our libraries and getting the dataset.",
"%matplotlib inline\n\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data', validation_size=0)",
"Below I'm plotting an example image from the MNIST dataset. These are 28x28 grayscale images of handwritten digits.",
"img = mnist.train.images[2]\nplt.imshow(img.reshape((28, 28)), cmap='Greys_r')",
"We'll train an autoencoder with these images by flattening them into 784 length vectors. The images from this dataset are already normalized such that the values are between 0 and 1. Let's start by building basically the simplest autoencoder with a single ReLU hidden layer. This layer will be used as the compressed representation. Then, the encoder is the input layer and the hidden layer. The decoder is the hidden layer and the output layer. Since the images are normalized between 0 and 1, we need to use a sigmoid activation on the output layer to get values matching the input.\n\n\nExercise: Build the graph for the autoencoder in the cell below. The input images will be flattened into 784 length vectors. The targets are the same as the inputs. And there should be one hidden layer with a ReLU activation and an output layer with a sigmoid activation. The loss should be calculated with the cross-entropy loss, there is a convenient TensorFlow function for this tf.nn.sigmoid_cross_entropy_with_logits (documentation). You should note that tf.nn.sigmoid_cross_entropy_with_logits takes the logits, but to get the reconstructed images you'll need to pass the logits through the sigmoid function.",
"# Size of the encoding layer (the hidden layer)\nencoding_dim = 32 # feel free to change this value\n\ninputs_ = tf.placeholder(tf.float32, shape=(None, 784))\ntargets_ = tf.placeholder(tf.float32, shape=(None, 784))\n\n# Output of hidden layer\nencoded = tf.layers.dense(inputs_, encoding_dim)\n\n# Output layer logits\nlogits = tf.layers.dense(encoded, targets_.shape[1], activation=tf.nn.relu)\n# Sigmoid output from logits\ndecoded = tf.nn.sigmoid(logits, activation=None)\n\n# Sigmoid cross-entropy loss\nloss = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=targets_)\n# Mean of the loss\ncost = tf.reduce_mean(loss)\n\n# Adam optimizer\nopt = tf.train.AdamOptimizer().minimize(cost)",
"Training",
"# Create the session\nsess = tf.Session()",
"Here I'll write a bit of code to train the network. I'm not too interested in validation here, so I'll just monitor the training loss. \nCalling mnist.train.next_batch(batch_size) will return a tuple of (images, labels). We're not concerned with the labels here, we just need the images. Otherwise this is pretty straightfoward training with TensorFlow. We initialize the variables with sess.run(tf.global_variables_initializer()). Then, run the optimizer and get the loss with batch_cost, _ = sess.run([cost, opt], feed_dict=feed).",
"epochs = 20\nbatch_size = 200\nsess.run(tf.global_variables_initializer())\nfor e in range(epochs):\n for ii in range(mnist.train.num_examples//batch_size):\n batch = mnist.train.next_batch(batch_size)\n feed = {inputs_: batch[0], targets_: batch[0]}\n batch_cost, _ = sess.run([cost, opt], feed_dict=feed)\n\n print(\"Epoch: {}/{}...\".format(e+1, epochs),\n \"Training loss: {:.4f}\".format(batch_cost))",
"Checking out the results\nBelow I've plotted some of the test images along with their reconstructions. For the most part these look pretty good except for some blurriness in some parts.",
"fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4))\nin_imgs = mnist.test.images[:10]\nreconstructed, compressed = sess.run([decoded, encoded], feed_dict={inputs_: in_imgs})\n\nfor images, row in zip([in_imgs, reconstructed], axes):\n for img, ax in zip(images, row):\n ax.imshow(img.reshape((28, 28)), cmap='Greys_r')\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\nfig.tight_layout(pad=0.1)\n\nsess.close()",
"Up Next\nWe're dealing with images here, so we can (usually) get better performance using convolution layers. So, next we'll build a better autoencoder with convolutional layers.\nIn practice, autoencoders aren't actually better at compression compared to typical methods like JPEGs and MP3s. But, they are being used for noise reduction, which you'll also build."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
CORE-GATECH-GROUP/serpent-tools
|
examples/Settings.ipynb
|
mit
|
[
"Copyright (c) 2017-2020 Serpent-Tools developer team, GTRC\nTHE 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.\nThe serpentTools package is designed to, without intervention, be able to store all the data contained in each of the various output files. However, the serpentTools.settings module grants great flexibility to the user over what data is obtained through the rc class. This notebook will provide as an intro into using this class.\nAll the settings are given in Default Settings, showing their default values and possible options.\nBasic Usage",
"import serpentTools\nfrom serpentTools.settings import rc",
"The rc object can be used like a dictionary, polling all possible settings with the keys method.",
"rc.keys()",
"Settings such as depletion.materialVariables are specific for the DepletionReader, while settings that are led with xs are sent to the ResultsReader and BranchingReader, as well as their specific settings. The rc class acts as a dictionary, and updating a value is as simple as",
"rc['verbosity'] = 'debug'",
"The rc object automatically checks to make sure the value is of the correct type, and is an allowable option, if given.",
"try:\n rc['depletion.metadataKeys'] = False\nexcept TypeError as te:\n print(te)\n\ntry:\n rc['serpentVersion'] = '1.2.3'\nexcept KeyError as ke:\n print(ke)",
"The rc module can also be used inside a context manager to revert changes.",
"with rc:\n rc['depletion.metadataKeys'] = ['ZAI', 'BU']\n \nrc['depletion.metadataKeys']\nrc['verbosity'] = 'info'",
"Group Constant Variables\nTwo settings control what group constant data and what variables are extracted from the results and coefficient files.\n\nxs.variableExtras: Full SERPENT_STYLE variable names, i.e. INF_TOT, FISSION_PRODUCT_DECAY_HEAT\nxs.variableGroups: Select keywords that represent blocks of common variables\n\nThese variable groups are described in Variable Groups and rely upon the SERPENT version to properly expand the groups.",
"rc['serpentVersion']\n\nrc['xs.variableGroups'] = ['kinetics', 'xs', 'diffusion']\nrc['xs.variableExtras'] = ['XS_DATA_FILE_PATH']\nvarSet = rc.expandVariables()\nprint(sorted(varSet))",
"However, one might see that the full group constant cross sections are not present in this set",
"assert 'INF_SCATT3' not in varSet",
"This is because two additional settings instruct the BranchingReader and ResultsReader to obtain infinite medium and leakage-corrected cross sections: xs.getInfXS and xs.getB1XS, respectively. By default, xs.getInfXS and xs.getB1XS default to True. This, in conjunction with leaving the xs.variableGroups and xs.variableExtras settings to empty lists, instructs these readers to obtain all the data present in their respective files.\nSee the BrancingReader or ResultsReader examples for more information on using these settings to control scraped data.\nConfiguration files\nThe rc object allows for settings to be updated from a yaml configuration file using the loadYaml method. The file contains setting names as keys with the desired variables as values, as\nverbosity: warning\nxs.getInfXS: False\nHowever, the loader can also expand a nested dictionary structure, as\nbranching:\n floatVariables: [Fhi, Blo]\ndepletion:\n materials: [fuel*]\n materialVariables:\n [ADENS, MDENS, VOLUME]",
"%cat myConfig.yaml\n\nmyConf = 'myConfig.yaml'\nrc.loadYaml(myConf)\nrc['xs.getInfXS']"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
Upward-Spiral-Science/spect-team
|
Code/Assignment-10/GenderDistinguished_ADHD_Bipolar_Fix&Tune_YatingJing.ipynb
|
apache-2.0
|
[
"Gender Distinguished Analysis and Parameter Tuning - by Yating Jing\n\nBuild models for female patients and male patients separately.\nFix earlier pipeline mistake (dimensionality reduction prior to classification).\n\nIn previous analysis, I made a mistakes with the dimensionality reduction - classification pipeline. Specifically, I reduced the dimension using PCA/LLE on the entire data before the training and testing procedure. This part is fixed in this notebook. \nAdditionally, I tried SVM with RBF kernel and tuned some parameters.",
"import pandas as pd\nimport numpy as np\n\ndf_adhd = pd.read_csv('ADHD_Gender_rCBF.csv')\ndf_bipolar = pd.read_csv('Bipolar_Gender_rCBF.csv')\n\nn1, n2 = df_adhd.shape[0], df_bipolar.shape[0]\n\nprint 'Number of ADHD patients (without Bipolar) is', n1\nprint 'Number of Bipolar patients (without ADHD) is', n2\nprint 'Chance before gender separation is', float(n1) / (n1 + n2)\n\n# Separate the genders\nadhd1_id, adhd2_id = list(), list()\nbipolar1_id, bipolar2_id = list(), list()\n\nfor i, g in df_adhd[['Patient_ID', 'Gender_id']].values:\n if g == 1:\n adhd1_id.append(i)\n elif g == 2:\n adhd2_id.append(i)\n \nfor i, g in df_bipolar[['Patient_ID', 'Gender_id']].values:\n if g == 1:\n bipolar1_id.append(i)\n elif g == 2:\n bipolar2_id.append(i)\n \nprint 'Number of Gender 1 ADHD patients (without Bipolar) is', len(adhd1_id)\nprint 'Number of Gender 2 ADHD patients (without Bipolar) is', len(adhd2_id)\nprint 'Number of Gender 1 Bipolar patients (without ADHD) is', len(bipolar1_id)\nprint 'Number of Gender 2 Bipolar patients (without ADHD) is', len(bipolar2_id)\n\n# Separate ADHD data gender-wise\ndf_adhd1 = df_adhd.loc[df_adhd['Patient_ID'].isin(adhd1_id)].drop(['Patient_ID', 'Gender_id'], axis=1)\ndf_adhd2 = df_adhd.loc[df_adhd['Patient_ID'].isin(adhd2_id)].drop(['Patient_ID', 'Gender_id'], axis=1)\n# Separate Bipolar data gender-wise\ndf_bipolar1 = df_bipolar.loc[df_bipolar['Patient_ID'].isin(bipolar1_id)].drop(['Patient_ID', 'Gender_id'], axis=1)\ndf_bipolar2 = df_bipolar.loc[df_bipolar['Patient_ID'].isin(bipolar2_id)].drop(['Patient_ID', 'Gender_id'], axis=1)\n\n# Create disorder labels for classification\n# ADHD: 0, Bipolar: 1\nn1_adhd, n1_bipolar = len(adhd1_id), len(bipolar1_id)\nn2_adhd, n2_bipolar = len(adhd2_id), len(bipolar2_id)\n# Labels for gender 1\ny1 = [0] * n1_adhd + [1] * n1_bipolar \n# Labels for gender 2\ny2 = [0] * n2_adhd + [1] * n2_bipolar \n\nprint 'Shape check:'\nprint 'ADHD:', df_adhd1.shape, df_adhd2.shape\nprint 'Bipolar:', df_bipolar1.shape, df_bipolar2.shape\n\n# Gender1 data\ndf1_all = pd.concat([df_adhd1, df_bipolar1], axis=0)\n# Gender2 data\ndf2_all = pd.concat([df_adhd2, df_bipolar2], axis=0)\n\nprint '\\nDouble shape check:'\nprint 'Gender 1:', df1_all.shape, len(y1)\nprint 'Gender 2:', df2_all.shape, len(y2)\n\n# Compute chances \nchance1 = float(n1_adhd)/(n1_adhd + n1_bipolar)\nchance2 = float(n2_adhd)/(n2_adhd + n2_bipolar)\nprint 'Chance for gender 1 is', chance1\nprint 'Chance for gender 2 is', chance2",
"Machine Learning Utilities\nPrincipal Component Analysis",
"from sklearn import preprocessing\nfrom sklearn.decomposition import PCA\n\n# Plot explained variance ratio\ndef plot_evr(ex_var_ratio):\n fig = plt.figure()\n plt.title('Explained Variance Ratios by PCA')\n plt.plot(ex_var_ratio)\n plt.ylabel('Explained Variance Ratio')\n plt.xlabel('Principal Component')\n\ndef pca_fit(X, n=10):\n # PCA \n pca = PCA(n_components=n)\n \n # Scale\n X_scaled = preprocessing.scale(X)\n \n # Fit \n pc = pca.fit_transform(X_scaled)\n \n # print '\\nExplained Variance Ratios:'\n # print pca.explained_variance_ratio_\n \n # print 'Sum of Explained Variance Ratios of the first', n, 'components is', \n # print np.sum(pca.explained_variance_ratio_)\n\n # plot_evr(pca.explained_variance_ratio_)\n\n return pca, pc\n\ndef pca_transform(pca, X, n=10):\n X_scaled = preprocessing.scale(X)\n pc = pca.transform(X_scaled)\n return pc",
"Locally Linear Embedding",
"from sklearn import preprocessing\nfrom sklearn.manifold import LocallyLinearEmbedding\n\n# Compute explained variance ratio of transformed data\ndef compute_explained_variance_ratio(transformed_data):\n explained_variance = np.var(transformed_data, axis=0)\n explained_variance_ratio = explained_variance / np.sum(explained_variance)\n explained_variance_ratio = np.sort(explained_variance_ratio)[::-1]\n return explained_variance_ratio\n\ndef lle_fit(X, n=10):\n # LLE\n lle = LocallyLinearEmbedding(n_neighbors=25, n_components=n, method='ltsa')\n # Scale\n X_scaled = preprocessing.scale(X)\n \n pc = lle.fit_transform(X_scaled)\n ex_var_ratio = compute_explained_variance_ratio(pc) \n \n # print 'Explained Variance Ratios:'\n # print ex_var_ratio\n \n return lle, pc\n\ndef lle_transform(lle, X, n=10):\n X_scaled = preprocessing.scale(X)\n pc = lle.transform(X_scaled)\n return pc",
"Classification",
"from sklearn.cross_validation import KFold\n\ndef train_test_clf(clf, clf_name, X, y, dr_method, k=10, n_comps=10):\n '''\n Train and test a classifier using K-fold cross validation\n Args:\n clf: sklearn classifier\n clf_name: classifier name (for printing)\n X: training data (2D numpy matrix)\n y: labels (1D vector)\n dr_method: dimensionality reduction method used to construct the features\n k: number of folds (default=10)\n n_comps: number of principal components to keep (default=10)\n '''\n X, y = np.array(X), np.array(y)\n kf = KFold(len(X), n_folds=k)\n scores = list()\n \n for i, (train_index, test_index) in enumerate(kf):\n # print 'Fold', i, '(10-fold CV)'\n # Train test split\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n \n X_train_redu, X_test_redu = [], []\n \n # Dimensionality Reduction\n if dr_method == 'PCA':\n # PCA fit\n pca, X_train_redu = pca_fit(X_train, n_comps)\n # PCA transform\n X_test_redu = pca_transform(pca, X_test, n_comps)\n elif dr_method == 'LLE':\n # LLE fit\n lle, X_train_redu = lle_fit(X_train, n_comps)\n # LLE transform\n X_test_redu = lle_transform(lle, X_test, n_comps)\n \n # Classification\n clf.fit(X_train_redu, y_train)\n score = clf.score(X_test_redu, y_test)\n scores.append(score)\n \n scores = np.array(scores)\n acc, acc_std = scores.mean(), scores.std()\n \n print clf_name + ' accuracy is %0.4f (+/- %0.3f)' % (acc, acc_std)\n return acc, acc_std\n\n%matplotlib inline\nimport matplotlib.pyplot as plt\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import LinearSVC, SVC\nfrom sklearn.lda import LDA\nfrom sklearn.qda import QDA\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom sklearn.ensemble import AdaBoostClassifier\n\ndef classify(X, y, gender, dr_method, n_feats):\n '''\n Train and test a classifier \n Args:\n X: training data (2D numpy matrix)\n y: labels (1D vector)\n gender: current gender genre (for plotting)\n dr_method: dimensionality reduction method used to construct the features\n n_feats: number of features used in classification\n '''\n lg = LogisticRegression(penalty='l2')\n lsvc = LinearSVC()\n svc = SVC(kernel='rbf')\n qda = QDA()\n rf = RandomForestClassifier(n_estimators=10, max_depth=5) \n gb = GradientBoostingClassifier(n_estimators=20, max_depth=6)\n et = ExtraTreesClassifier(n_estimators=20, max_depth=6)\n ada = AdaBoostClassifier()\n\n classifiers = [lg, lsvc, svc, qda, rf, gb, et, ada]\n clf_names = ['Logistic Regression', 'Linear SVM', 'SVM (RBF)', 'QDA', \\\n 'Random Forest', 'Gradient Boosting', 'Extra Trees', 'AdaBoost']\n accuracies = list()\n \n for clf, name in zip(classifiers, clf_names):\n # print '\\n*********************************************************'\n acc, acc_std = train_test_clf(clf, name, X, y, dr_method, 10, n_feats)\n accuracies.append(acc)\n \n # Visualize classifier performance\n x = range(len(accuracies))\n width = 0.6/1.5\n plt.bar(x, accuracies, width)\n \n # Compute chance\n n0, n1 = y.count(0), y.count(1)\n chance = max(n0, n1) / float(n0 + n1)\n \n fig_title = gender + ' Classifier Performance on ' + dr_method + ' features'\n plt.title(fig_title, y=1.08)\n plt.xticks(x, clf_names, rotation=50)\n plt.xlabel('Classifier')\n plt.gca().xaxis.set_label_coords(1.1, -0.025)\n plt.ylabel('Accuracy')\n plt.axhline(chance, color='red', linestyle='--', label='chance') # plot chance\n plt.legend(loc='center left', bbox_to_anchor=(1, 0.85))",
"Gender 1 ADHD v.s. Bipolar Analysis",
"# Classification using PCA features\nprint 'Using PCA features:\\n'\nX1 = df1_all.values\nclassify(X1, y1, 'Gender 1', 'PCA', 10)\n\n# Classification using LLE features\nprint 'Using LLE features:\\n'\nX1 = df1_all.values\nclassify(X1, y1, 'Gender 1', 'LLE', 15)",
"Gender 2 ADHD v.s. Bipolar Analysis",
"# Classification using PCA features\nprint 'Using PCA features:\\n'\nX2 = df2_all.values\nclassify(X2, y2, 'Gender 2', 'PCA', 10)\n\n# Classification using LLE features\nprint 'Using LLE features:\\n'\nX2 = df2_all.values\nclassify(X2, y2, 'Gender 2', 'LLE', 15)",
"Conclusion\nFeatures extracted using PCA method does not give better result than chance. The highest ADHD against Bipolar prediction accuracy is yielded by LLE pipelines with QDA classification method. \nHowever, when using only 15 neighbors for LLE and extracting only 10 components, QDA gave the worst prediction result ever. For some reason, LLE with 25 neighbors for 15 components works great with QDA on this task"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
opesci/devito
|
examples/cfd/07_cavity_flow.ipynb
|
mit
|
[
"Cavity flow with Navier-Stokes\nThe final two steps will both solve the Navier–Stokes equations in two dimensions, but with different boundary conditions.\nThe momentum equation in vector form for a velocity field v⃗ \nis:\n$$ \\frac{\\partial \\overrightarrow{v}}{\\partial t} + (\\overrightarrow{v} \\cdot \\nabla ) \\overrightarrow{v} = -\\frac{1}{\\rho}\\nabla p + \\nu \\nabla^2 \\overrightarrow{v}$$\nThis represents three scalar equations, one for each velocity component (u,v,w). But we will solve it in two dimensions, so there will be two scalar equations.\nRemember the continuity equation? This is where the Poisson equation for pressure comes in!\nHere is the system of differential equations: two equations for the velocity components u,v and one equation for pressure:\n$$ \\frac{\\partial u}{\\partial t} + u \\frac{\\partial u}{\\partial x} + v \\frac{\\partial u}{\\partial y}= -\\frac{1}{\\rho}\\frac{\\partial p}{\\partial x} + \\nu \\left[ \\frac{\\partial^2 u}{\\partial x^2} +\\frac{\\partial^2 u}{\\partial y^2} \\right] $$\n$$ \\frac{\\partial v}{\\partial t} + u \\frac{\\partial v}{\\partial x} + v \\frac{\\partial v}{\\partial y}= -\\frac{1}{\\rho}\\frac{\\partial p}{\\partial y} + \\nu \\left[ \\frac{\\partial^2 v}{\\partial x^2} +\\frac{\\partial^2 v}{\\partial y^2} \\right] $$\n$$\n\\frac{\\partial^2 p}{\\partial x^2} +\\frac{\\partial^2 p}{\\partial y^2} =\n\\rho \\left[\\frac{\\partial}{\\partial t} \\left(\\frac{\\partial u}{\\partial x} + \\frac{\\partial v}{\\partial y} \\right) - \\left(\\frac{\\partial u}{\\partial x}\\frac{\\partial u}{\\partial x}+2\\frac{\\partial u}{\\partial y}\\frac{\\partial v}{\\partial x}+\\frac{\\partial v}{\\partial y}\\frac{\\partial v}{\\partial y} \\right) \\right]\n$$\nFrom the previous steps, we already know how to discretize all these terms. Only the last equation is a little unfamiliar. But with a little patience, it will not be hard!\nOur stencils look like this:\nFirst the momentum equation in the u direction\n$$\n\\begin{split}\nu_{i,j}^{n+1} = u_{i,j}^{n} & - u_{i,j}^{n} \\frac{\\Delta t}{\\Delta x} \\left(u_{i,j}^{n}-u_{i-1,j}^{n}\\right) - v_{i,j}^{n} \\frac{\\Delta t}{\\Delta y} \\left(u_{i,j}^{n}-u_{i,j-1}^{n}\\right) \\\n& - \\frac{\\Delta t}{\\rho 2\\Delta x} \\left(p_{i+1,j}^{n}-p_{i-1,j}^{n}\\right) \\\n& + \\nu \\left(\\frac{\\Delta t}{\\Delta x^2} \\left(u_{i+1,j}^{n}-2u_{i,j}^{n}+u_{i-1,j}^{n}\\right) + \\frac{\\Delta t}{\\Delta y^2} \\left(u_{i,j+1}^{n}-2u_{i,j}^{n}+u_{i,j-1}^{n}\\right)\\right)\n\\end{split}\n$$\nSecond the momentum equation in the v direction\n$$\n\\begin{split}\nv_{i,j}^{n+1} = v_{i,j}^{n} & - u_{i,j}^{n} \\frac{\\Delta t}{\\Delta x} \\left(v_{i,j}^{n}-v_{i-1,j}^{n}\\right) - v_{i,j}^{n} \\frac{\\Delta t}{\\Delta y} \\left(v_{i,j}^{n}-v_{i,j-1}^{n})\\right) \\\n& - \\frac{\\Delta t}{\\rho 2\\Delta y} \\left(p_{i,j+1}^{n}-p_{i,j-1}^{n}\\right) \\\n& + \\nu \\left(\\frac{\\Delta t}{\\Delta x^2} \\left(v_{i+1,j}^{n}-2v_{i,j}^{n}+v_{i-1,j}^{n}\\right) + \\frac{\\Delta t}{\\Delta y^2} \\left(v_{i,j+1}^{n}-2v_{i,j}^{n}+v_{i,j-1}^{n}\\right)\\right)\n\\end{split}\n$$\nFinally the pressure-Poisson equation\n$$\\begin{split}\np_{i,j}^{n} = & \\frac{\\left(p_{i+1,j}^{n}+p_{i-1,j}^{n}\\right) \\Delta y^2 + \\left(p_{i,j+1}^{n}+p_{i,j-1}^{n}\\right) \\Delta x^2}{2\\left(\\Delta x^2+\\Delta y^2\\right)} \\\n& -\\frac{\\rho\\Delta x^2\\Delta y^2}{2\\left(\\Delta x^2+\\Delta y^2\\right)} \\\n& \\times \\left[\\frac{1}{\\Delta t}\\left(\\frac{u_{i+1,j}-u_{i-1,j}}{2\\Delta x}+\\frac{v_{i,j+1}-v_{i,j-1}}{2\\Delta y}\\right)-\\frac{u_{i+1,j}-u_{i-1,j}}{2\\Delta x}\\frac{u_{i+1,j}-u_{i-1,j}}{2\\Delta x}\\right. \\ \n& \\left. -2\\frac{u_{i,j+1}-u_{i,j-1}}{2\\Delta y}\\frac{v_{i+1,j}-v_{i-1,j}}{2\\Delta x}-\\frac{v_{i,j+1}-v_{i,j-1}}{2\\Delta y}\\frac{v_{i,j+1}-v_{i,j-1}}{2\\Delta y} \\right] \n\\end{split}\n$$\nThe initial condition is $u,v,p=0$\neverywhere, and the boundary conditions are:\n$u=1$ at $y=1$ (the \"lid\");\n$u,v=0$ on the other boundaries;\n$\\frac{\\partial p}{\\partial y}=0$ at $y=0,1$;\n$\\frac{\\partial p}{\\partial x}=0$ at $x=0,1$\n$p=0$ at $(0,0)$\nInterestingly these boundary conditions describe a well known problem in the Computational Fluid Dynamics realm, where it is known as the lid driven square cavity flow problem.\nNumpy Implementation",
"import numpy as np\nfrom matplotlib import pyplot, cm\n%matplotlib inline\n\nnx = 41\nny = 41\nnt = 1000\nnit = 50\nc = 1\ndx = 1. / (nx - 1)\ndy = 1. / (ny - 1)\nx = np.linspace(0, 1, nx)\ny = np.linspace(0, 1, ny)\nY, X = np.meshgrid(x, y)\n\nrho = 1\nnu = .1\ndt = .001\n\nu = np.zeros((nx, ny))\nv = np.zeros((nx, ny))\np = np.zeros((nx, ny)) ",
"The pressure Poisson equation that's written above can be hard to write out without typos. The function build_up_b below represents the contents of the square brackets, so that the entirety of the Poisson pressure equation is slightly more manageable.",
"def build_up_b(b, rho, dt, u, v, dx, dy):\n \n b[1:-1, 1:-1] = (rho * (1 / dt * \n ((u[2:, 1:-1] - u[0:-2, 1:-1]) / \n (2 * dx) + (v[1:-1, 2:] - v[1:-1, 0:-2]) / (2 * dy)) -\n ((u[2:, 1:-1] - u[0:-2, 1:-1]) / (2 * dx))**2 -\n 2 * ((u[1:-1, 2:] - u[1:-1, 0:-2]) / (2 * dy) *\n (v[2:, 1:-1] - v[0:-2, 1:-1]) / (2 * dx))-\n ((v[1:-1, 2:] - v[1:-1, 0:-2]) / (2 * dy))**2))\n\n return b",
"The function pressure_poisson is also defined to help segregate the different rounds of calculations. Note the presence of the pseudo-time variable nit. This sub-iteration in the Poisson calculation helps ensure a divergence-free field.",
"def pressure_poisson(p, dx, dy, b):\n pn = np.empty_like(p)\n pn = p.copy()\n \n for q in range(nit):\n pn = p.copy()\n p[1:-1, 1:-1] = (((pn[2:, 1:-1] + pn[0:-2, 1:-1]) * dy**2 + \n (pn[1:-1, 2:] + pn[1:-1, 0:-2]) * dx**2) /\n (2 * (dx**2 + dy**2)) -\n dx**2 * dy**2 / (2 * (dx**2 + dy**2)) * \n b[1:-1,1:-1])\n \n p[-1, :] = p[-2, :] # dp/dx = 0 at x = 2\n p[:, 0] = p[:, 1] # dp/dy = 0 at y = 0\n p[0, :] = p[1, :] # dp/dx = 0 at x = 0\n p[:, -1] = p[:, -2] # p = 0 at y = 2\n p[0, 0] = 0 \n \n return p, pn",
"Finally, the rest of the cavity flow equations are wrapped inside the function cavity_flow, allowing us to easily plot the results of the cavity flow solver for different lengths of time.",
"def cavity_flow(nt, u, v, dt, dx, dy, p, rho, nu):\n un = np.empty_like(u)\n vn = np.empty_like(v)\n b = np.zeros((nx, ny))\n \n for n in range(0,nt):\n un = u.copy()\n vn = v.copy()\n \n b = build_up_b(b, rho, dt, u, v, dx, dy)\n p = pressure_poisson(p, dx, dy, b)[0]\n pn = pressure_poisson(p, dx, dy, b)[1]\n \n u[1:-1, 1:-1] = (un[1:-1, 1:-1]-\n un[1:-1, 1:-1] * dt / dx *\n (un[1:-1, 1:-1] - un[0:-2, 1:-1]) -\n vn[1:-1, 1:-1] * dt / dy *\n (un[1:-1, 1:-1] - un[1:-1, 0:-2]) -\n dt / (2 * rho * dx) * (p[2:, 1:-1] - p[0:-2, 1:-1]) +\n nu * (dt / dx**2 *\n (un[2:, 1:-1] - 2 * un[1:-1, 1:-1] + un[0:-2, 1:-1]) +\n dt / dy**2 *\n (un[1:-1, 2:] - 2 * un[1:-1, 1:-1] + un[1:-1, 0:-2])))\n\n v[1:-1,1:-1] = (vn[1:-1, 1:-1] -\n un[1:-1, 1:-1] * dt / dx *\n (vn[1:-1, 1:-1] - vn[0:-2, 1:-1]) -\n vn[1:-1, 1:-1] * dt / dy *\n (vn[1:-1, 1:-1] - vn[1:-1, 0:-2]) -\n dt / (2 * rho * dy) * (p[1:-1, 2:] - p[1:-1, 0:-2]) +\n nu * (dt / dx**2 *\n (vn[2:, 1:-1] - 2 * vn[1:-1, 1:-1] + vn[0:-2, 1:-1]) +\n dt / dy**2 *\n (vn[1:-1, 2:] - 2 * vn[1:-1, 1:-1] + vn[1:-1, 0:-2])))\n\n u[:, 0] = 0\n u[0, :] = 0\n u[-1, :] = 0\n u[:, -1] = 1 # Set velocity on cavity lid equal to 1\n \n v[:, 0] = 0\n v[:, -1] = 0\n v[0, :] = 0\n v[-1, :] = 0\n \n return u, v, p, pn\n\n#NBVAL_IGNORE_OUTPUT\nu = np.zeros((nx, ny))\nv = np.zeros((nx, ny))\np = np.zeros((nx, ny))\nb = np.zeros((nx, ny))\nnt = 1000\n# Store the output velocity and pressure fields in the variables a, b and c.\n# This is so they do not clash with the devito outputs below.\na, b, c, d = cavity_flow(nt, u, v, dt, dx, dy, p, rho, nu)\n\nfig = pyplot.figure(figsize=(11, 7), dpi=100)\npyplot.contourf(X, Y, c, alpha=0.5, cmap=cm.viridis)\npyplot.colorbar()\npyplot.contour(X, Y, c, cmap=cm.viridis)\npyplot.quiver(X[::2, ::2], Y[::2, ::2], a[::2, ::2], b[::2, ::2])\npyplot.xlabel('X')\npyplot.ylabel('Y');",
"Validation\nMarchi et al (2009)$^1$ compared numerical implementations of the lid driven cavity problem with their solution on a 1024 x 1024 nodes grid. We will compare a solution using both NumPy and Devito with the results of their paper below.\n\nhttps://www.scielo.br/scielo.php?pid=S1678-58782009000300004&script=sci_arttext",
"# Import u values at x=L/2 (table 6, column 2 rows 12-26) in Marchi et al.\nMarchi_Re10_u = np.array([[0.0625, -3.85425800e-2],\n [0.125, -6.96238561e-2],\n [0.1875, -9.6983962e-2],\n [0.25, -1.22721979e-1],\n [0.3125, -1.47636199e-1],\n [0.375, -1.71260757e-1],\n [0.4375, -1.91677043e-1],\n [0.5, -2.05164738e-1],\n [0.5625, -2.05770198e-1],\n [0.625, -1.84928116e-1],\n [0.6875, -1.313892353e-1],\n [0.75, -3.1879308e-2],\n [0.8125, 1.26912095e-1],\n [0.875, 3.54430364e-1],\n [0.9375, 6.50529292e-1]])\n# Import v values at y=L/2 (table 6, column 2 rows 27-41) in Marchi et al.\nMarchi_Re10_v = np.array([[0.0625, 9.2970121e-2],\n [0.125, 1.52547843e-1],\n [0.1875, 1.78781456e-1],\n [0.25, 1.76415100e-1],\n [0.3125, 1.52055820e-1],\n [0.375, 1.121477612e-1],\n [0.4375, 6.21048147e-2],\n [0.5, 6.3603620e-3],\n [0.5625,-5.10417285e-2],\n [0.625, -1.056157259e-1],\n [0.6875,-1.51622101e-1],\n [0.75, -1.81633561e-1],\n [0.8125,-1.87021651e-1],\n [0.875, -1.59898186e-1],\n [0.9375,-9.6409942e-2]])\n\n#NBVAL_IGNORE_OUTPUT\n# Check results with Marchi et al 2009.\nnpgrid=[nx,ny]\n\nx_coord = np.linspace(0, 1, npgrid[0])\ny_coord = np.linspace(0, 1, npgrid[1])\n\nfig = pyplot.figure(figsize=(12, 6))\nax1 = fig.add_subplot(121)\nax1.plot(a[int(npgrid[0]/2),:],y_coord[:])\nax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')\nax1.set_xlabel('$u$')\nax1.set_ylabel('$y$')\nax1 = fig.add_subplot(122)\nax1.plot(x_coord[:],b[:,int(npgrid[1]/2)])\nax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')\nax1.set_xlabel('$x$')\nax1.set_ylabel('$v$')\n\npyplot.show()",
"Devito Implementation",
"from devito import Grid\n\ngrid = Grid(shape=(nx, ny), extent=(1., 1.))\nx, y = grid.dimensions\nt = grid.stepping_dim",
"Reminder: here are our equations\n$$ \\frac{\\partial u}{\\partial t} + u \\frac{\\partial u}{\\partial x} + v \\frac{\\partial u}{\\partial y}= -\\frac{1}{\\rho}\\frac{\\partial p}{\\partial x} + \\nu \\left[ \\frac{\\partial^2 u}{\\partial x^2} +\\frac{\\partial^2 u}{\\partial y^2} \\right] $$\n$$ \\frac{\\partial v}{\\partial t} + u \\frac{\\partial v}{\\partial x} + v \\frac{\\partial v}{\\partial y}= -\\frac{1}{\\rho}\\frac{\\partial p}{\\partial y} + \\nu \\left[ \\frac{\\partial^2 v}{\\partial x^2} +\\frac{\\partial^2 v}{\\partial y^2} \\right] $$\n$$\n\\frac{\\partial^2 p}{\\partial x^2} +\\frac{\\partial^2 p}{\\partial y^2} =\n\\rho \\left[\\frac{\\partial}{\\partial t} \\left(\\frac{\\partial u}{\\partial x} + \\frac{\\partial v}{\\partial y} \\right) - \\left(\\frac{\\partial u}{\\partial x}\\frac{\\partial u}{\\partial x}+2\\frac{\\partial u}{\\partial y}\\frac{\\partial v}{\\partial x}+\\frac{\\partial v}{\\partial y}\\frac{\\partial v}{\\partial y} \\right) \\right]\n$$\nNote that p has no time dependence, so we are going to solve for p in pseudotime then move to the next time step and solve for u and v. This will require two operators, one for p (using p and pn) in pseudotime and one for u and v in time.\nAs shown in the Poisson equation tutorial, a TimeFunction can be used despite the lack of a time-dependence. This will cause Devito to allocate two grid buffers, which we can addressed directly via the terms pn and pn.forward. The internal time loop can be controlled by supplying the number of pseudotime steps (iterations) as a time argument to the operator.\nThe time steps are advanced through a Python loop where a separator operator calculates u and v.\nAlso note that we need to use first order spatial derivatives for the velocites and these derivatives are not the maximum spatial derivative order (2nd order) in these equations. This is the first time we have seen this in this tutorial series (previously we have only used a single spatial derivate order). \nTo use a first order derivative of a devito function, we use the syntax function.dxc or function.dyc for the x and y derivatives respectively.",
"from devito import TimeFunction, Function, \\\nEq, solve, Operator, configuration\n\n# Build Required Functions and derivatives:\n# --------------------------------------\n# |Variable | Required Derivatives |\n# --------------------------------------\n# | u | dt, dx, dy, dx**2, dy**2 |\n# | v | dt, dx, dy, dx**2, dy**2 |\n# | p | dx, dy, dx**2, dy**2 |\n# | pn | dx, dy, dx**2, dy**2 |\n# --------------------------------------\nu = TimeFunction(name='u', grid=grid, space_order=2)\nv = TimeFunction(name='v', grid=grid, space_order=2)\np = TimeFunction(name='p', grid=grid, space_order=2)\n#Variables are automatically initalized at 0.\n\n# First order derivatives will be handled with p.dxc\neq_u =Eq(u.dt + u*u.dx + v*u.dy, -1./rho * p.dxc + nu*(u.laplace), subdomain=grid.interior)\neq_v =Eq(v.dt + u*v.dx + v*v.dy, -1./rho * p.dyc + nu*(v.laplace), subdomain=grid.interior)\neq_p =Eq(p.laplace,rho*(1./dt*(u.dxc+v.dyc)-(u.dxc*u.dxc)+2*(u.dyc*v.dxc)+(v.dyc*v.dyc)), subdomain=grid.interior)\n\n# NOTE: Pressure has no time dependence so we solve for the other pressure buffer.\nstencil_u =solve(eq_u , u.forward)\nstencil_v =solve(eq_v , v.forward)\nstencil_p=solve(eq_p, p)\n \nupdate_u =Eq(u.forward, stencil_u)\nupdate_v =Eq(v.forward, stencil_v)\nupdate_p =Eq(p.forward, stencil_p) \n\n# Boundary Conds. u=v=0 for all sides\nbc_u = [Eq(u[t+1, 0, y], 0)] \nbc_u += [Eq(u[t+1, nx-1, y], 0)] \nbc_u += [Eq(u[t+1, x, 0], 0)] \nbc_u += [Eq(u[t+1, x, ny-1], 1)] # except u=1 for y=2\nbc_v = [Eq(v[t+1, 0, y], 0)] \nbc_v += [Eq(v[t+1, nx-1, y], 0)] \nbc_v += [Eq(v[t+1, x, ny-1], 0)] \nbc_v += [Eq(v[t+1, x, 0], 0)] \n\nbc_p = [Eq(p[t+1, 0, y],p[t+1, 1,y])] # dpn/dx = 0 for x=0.\nbc_p += [Eq(p[t+1,nx-1, y],p[t+1,nx-2, y])] # dpn/dx = 0 for x=2.\nbc_p += [Eq(p[t+1, x, 0],p[t+1,x ,1])] # dpn/dy = 0 at y=0\nbc_p += [Eq(p[t+1, x, ny-1],p[t+1, x, ny-2])] # pn=0 for y=2\nbc_p += [Eq(p[t+1, 0, 0], 0)]\nbc=bc_u+bc_v\n\noptime=Operator([update_u, update_v]+bc_u+bc_v)\noppres=Operator([update_p]+bc_p)\n\n# Silence non-essential outputs from the solver.\nconfiguration['log-level'] = 'ERROR'\n\n\n# This is the time loop.\nfor step in range(0,nt):\n if step>0:\n oppres(time_M = nit)\n optime(time_m=step, time_M=step, dt=dt)\n\n#NBVAL_IGNORE_OUTPUT\nfig = pyplot.figure(figsize=(11,7), dpi=100)\n# Plotting the pressure field as a contour.\npyplot.contourf(X, Y, p.data[0], alpha=0.5, cmap=cm.viridis) \npyplot.colorbar()\n# Plotting the pressure field outlines.\npyplot.contour(X, Y, p.data[0], cmap=cm.viridis) \n# Plotting velocity field.\npyplot.quiver(X[::2,::2], Y[::2,::2], u.data[0,::2,::2], v.data[0,::2,::2]) \npyplot.xlabel('X')\npyplot.ylabel('Y');\n",
"Validation",
"#NBVAL_IGNORE_OUTPUT\n# Again, check results with Marchi et al 2009.\nfig = pyplot.figure(figsize=(12, 6))\nax1 = fig.add_subplot(121)\nax1.plot(u.data[0,int(grid.shape[0]/2),:],y_coord[:])\nax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')\nax1.set_xlabel('$u$')\nax1.set_ylabel('$y$')\nax1 = fig.add_subplot(122)\nax1.plot(x_coord[:],v.data[0,:,int(grid.shape[0]/2)])\nax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')\nax1.set_xlabel('$x$')\nax1.set_ylabel('$v$')\n\npyplot.show()",
"The Devito implementation produces results consistent with the benchmark solution. There is a small disparity in a few of the velocity values, but this is expected as the Devito 41 x 41 node grid is much coarser than the benchmark on a 1024 x 1024 node grid.\nComparison",
"#NBVAL_IGNORE_OUTPUT\nfig = pyplot.figure(figsize=(12, 6))\nax1 = fig.add_subplot(121)\nax1.plot(a[int(npgrid[0]/2),:],y_coord[:])\nax1.plot(u.data[0,int(grid.shape[0]/2),:],y_coord[:],'--')\nax1.plot(Marchi_Re10_u[:,1],Marchi_Re10_u[:,0],'ro')\nax1.set_xlabel('$u$')\nax1.set_ylabel('$y$')\nax1 = fig.add_subplot(122)\nax1.plot(x_coord[:],b[:,int(npgrid[1]/2)])\nax1.plot(x_coord[:],v.data[0,:,int(grid.shape[0]/2)],'--')\nax1.plot(Marchi_Re10_v[:,0],Marchi_Re10_v[:,1],'ro')\nax1.set_xlabel('$x$')\nax1.set_ylabel('$v$')\nax1.legend(['numpy','devito','Marchi (2009)'])\n\npyplot.show()\n\n#Pressure norm check\ntol = 1e-3\nassert np.sum((c[:,:]-d[:,:])**2/ np.maximum(d[:,:]**2,1e-10)) < tol\nassert np.sum((p.data[0]-p.data[1])**2/np.maximum(p.data[0]**2,1e-10)) < tol",
"Overlaying all the graphs together shows how the Devito, NumPy and Marchi et al (2009)$^1$ \n solutions compare with each other. A final accuracy check is done which is to test whether the pressure norm has exceeded a specified tolerance."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
aeantipov/fk_mc
|
examples/graph_lattice_test.ipynb
|
gpl-2.0
|
[
"FK Weyl - tight binding model\nThe idea is to combine the FK interaction (annealed disorder) with some weird dispersion, in this case Weyl semimetal. The generic Hamiltonian is \n$$\nH = \\sum_{i,j,\\alpha,\\beta} c^\\dagger_{i,\\alpha} \\hat t c_{j,\\beta} + \\sum_{i, \\alpha} U_{i} n_{i, \\alpha} w_i \n- \\sum_i \\mu_f w_i - \\sum_{i,\\alpha} \\mu_c n_{i\\alpha}\n$$",
"import importlib\nimport os\nimport sys\ndef is_interactive():\n import __main__ as main\n return not hasattr(main, '__file__')\n# defaults\nshell_mode = not is_interactive() \nplot_graphs = importlib.util.find_spec(\"matplotlib\") is not None and not shell_mode\n\n# Matplotlib\nif (plot_graphs):\n import matplotlib\n import matplotlib.pyplot as plt\n from matplotlib.ticker import AutoMinorLocator\n from matplotlib import gridspec\n import subprocess\n \n def plt_show():\n plt.show() if not shell_mode else None\n\n if not shell_mode:\n # Matplotlib defaults\n %matplotlib inline\n %config InlineBackend.figure_format = 'retina'\n %load_ext autoreload\n %autoreload 2\n\n font = {'family' : 'sans-serif', 'weight' : 'normal', 'size' : 16}\n font2 = {'family' : 'helvetica', 'weight' : 'bold', 'size' : 24}\n lines = {'markersize' : 0.5}\n matplotlib.rc('font', **font)\n matplotlib.rc('lines')\n matplotlib.rc('text', usetex=True)\n \n # Plot styles\n mycolors=[\"#083E76\",\"#0B4D92\",\"#2165AC\",\"#407BB8\",\"#368B6B\",\"#58A588\",\"#f4a582\",\"#d6604d\",\"#b2182b\",\"#393B3D\",\"#D13648\"]\n mypts=[\"o\",\"^\",\"v\",\"s\",\"p\",\"h\",\"d\",\"8\",\"4\"]\n mylines=[\"-\",\"--\",\":\",\"-.\",\"-\",\"--\",\":\",\"-.\",\"-\"]\n myformats = [x + y for (x,y) in zip(mypts,mylines)]\n stylepick = lambda x,l : int(round((len(mycolors)-2) / float(l)*x + 1,0))\n \n\n# Parameters from command line parser\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n pass\n \n try:\n import unicodedata\n unicodedata.numeric(s)\n return True\n except (TypeError, ValueError):\n pass\n \n return False\n \ndef args_to_params(args_in, mp):\n import argparse\n parser = argparse.ArgumentParser(description='m_proximity',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n [parser.add_argument('--'+n, default = v) for n,v in mp.items()]\n args = parser.parse_args(args_in)\n p1 = vars(args)\n p = dict((k, type(mp[k])(v)) for k, v in p1.items() if v!=None)\n return p\n\n# Output data\ndata_out = dict()",
"TB Hamiltonian\nThe Weyl Hamiltonian is \n$$\n\\hat t = \\frac{k_z^2}{2m} \\sigma_z + k_x \\sigma_x + k_y \\sigma_y.\n$$\nA bit more involved version reads\n$$\n\\hat t = v (\\sin k_x \\sigma_x + \\sin k_y \\sigma_y) + (M - t (\\cos k_x + \\cos k_y + \\cos k_z))\\sigma_z\n$$\nwhich low-k expansion is in fact \n$$\nH = v (k_x \\sigma_x + k_y \\sigma_y ) + (M - t + t \\frac{k_x^2 + k_y^2 + k_z^2}{2}) \\sigma_z\n$$",
"p = {\n \"t\" : 1, \n \"N_x\" : 1024,\n \"save_hdf5\" : 1,\n \"h5path\" : \"\",\n \"h5section\" : \"\",\n \"h5file\" : \"graph_lattice_test.h5\",\n }\n\nimport itertools\nns_in = [x for x in itertools.chain.from_iterable([\"--\"+n, str(v)] for n,v in {**p}.items())]\np=args_to_params(ns_in if not shell_mode else sys.argv[1:len(sys.argv)], p)\n\nprint(\"Params:\\n\",p)\n\np_names = {\n \"t\" : \"t\",\n}\nfname_text = \"\".join([\"{}{:1.3f}\".format(x.replace(\"_\",\"\"),p[x]) for x in sorted(p_names.keys())])\nprint(fname_text)",
"Kwant routines",
"import kwant\nimport sympy\nimport sympy.functions\nimport sympy.functions.elementary\nimport sympy.functions.elementary.trigonometric\nimport numpy as np\nimport tinyarray\nfrom types import SimpleNamespace\n\nsympy.init_printing(use_latex='mathjax')\n\nimport discretizer as dr\n\nk_x, k_y, k_z = dr.momentum_operators\nk = sympy.sqrt(k_x**2+k_y**2 +k_z**2)\nx, y, z = dr.coordinates\nsigma_x = sympy.physics.matrices.msigma(1)\nsigma_y = sympy.physics.matrices.msigma(2)\nsigma_z = sympy.physics.matrices.msigma(3)\nsigma_0 = sigma_z * sigma_z\nM,t,mu,v = sympy.symbols('M t mu v', commutative=True)\n\n# H1 = k_x * sigma_x + k_y * sigma_y + k_z*k_z / 2 * sigma_z - mu * sigma_z\n# H2 = v * (k_x * sigma_x + k_y * sigma_y) + (M - t + t/2*k**2)*sigma_z\nH2 = -t/2 * k_x * k_x * sigma_0\n\nHs = H2\n#print(sympy.latex(H1))\n#print(sympy.latex(H2))\nHs\n\ntb = dr.Discretizer(Hs, discrete_coordinates={'x', 'y', 'z'}, lattice_constant=1.0, verbose=False)\n\ntb.symbolic_hamiltonian\n\ndims = np.array([p[\"N_x\"], 1, 1])\ndims_mult = np.array([dims[1]*dims[2], dims[1], 1])\n\ndef shape(pos):\n return (0 <= pos[0] < dims[0]) and (0 <= pos[1] < dims[1]) and (0<=pos[2] < dims[2])\ndef lead_shape_z(pos):\n return (0 <= pos[1] < dims[1]) and (0 <= pos[0] < dims[0])\ndef lead_shape_x(pos):\n return (0 <= pos[1] < dims[1]) and (0 <= pos[2] < dims[2])\ndef lead_shape_y(pos):\n return (0 <= pos[0] < dims[0]) and (0 <= pos[2] < dims[2])\n\n\nsyst_in = tb.build(shape, (0, 0, 0))\nlead_x = tb.build(lead_shape_x, (0, 0, 0), symmetry=(-1, 0, 0))\nlead_y = tb.build(lead_shape_y, (0, 0, 0), symmetry=(0, -1, 0))\nlead_z = tb.build(lead_shape_z, (0, 0, 0), symmetry=(0, 0, -1))\nsyst_in.attach_lead(lead_x)\nsyst_in.attach_lead(lead_x.reversed())\nsyst_in.attach_lead(lead_y)\nsyst_in.attach_lead(lead_y.reversed())\nsyst_in.attach_lead(lead_z)\nsyst_in.attach_lead(lead_z.reversed())\n\n\nsyst = syst_in.finalized()\n\nif plot_graphs:\n kwant.plot(syst)",
"Apply parameters and extract the Hamiltonian",
"args = SimpleNamespace()\nvars(args).update(p)\nprint(args)\n\nH_Weyl = syst.hamiltonian_submatrix(args=[args], sparse=True)\n\nif plot_graphs:\n fig = plt.figure()\n ax = fig.add_subplot(1,1,1)\n kwant.plotter.bands(syst.leads[0], args=[args], momenta=np.linspace(-np.pi, np.pi, 21, endpoint=True), show=False, ax = ax);\n ax.set_xlabel(r\"$k_x$\")\n ax.set_ylabel(r\"$E$\")\n plt.show()\n#plt.ylim(-0.5, 0.5)",
"Dump Hamiltonian ordered along the position on the lattice and the list of sites\nC++ ordering is $z-y-x$, while kwant orders as $x-y-z$\nSo we need to rearrange the terms in the Hamiltonian such as to get the FK-order.",
"# Order sites\nprint(syst.hamiltonian(0,0, args))\norb_size = syst.hamiltonian(0,0, args).shape[0]\nprint(\"orb_size =\", orb_size)\n\n# The order of sites in kwant is not guaranteed to follow the lattice\npos_array = np.array([np.array(s.pos).astype(np.int_) for s in syst.sites])\npos_flat = np.sum(pos_array * dims_mult[::-1], axis = 1)\npos_order = np.argsort(pos_flat)\nNsites = len(pos_order)\nprint(\"Nsites =\", Nsites)\n\n#print(pos_array[pos_order])\n\n# Convert pos_order to order of hamiltonian matrix elements\nmat_order = np.column_stack(tuple([pos_order * orb_size + o for o in range(orb_size)])).flatten()\n\n# Extract finite size Hamiltonian\nH1 = H_Weyl.tolil()\nrows,cols = H1.nonzero()\n \nexport_hopping = np.array([\n [row,col, H1[row,col]] for row,col in zip(rows[mat_order],cols[mat_order])\n])\nexport_coords = pos_array[pos_order]\n\ndata_out[\"hopping\"] = export_hopping\ndata_out[\"coordinates\"] = export_coords\ndata_out[\"dims\"] = dims\ndata_out[\"norbitals\"] = orb_size\n\n\n# HDF5\nimport h5py\n\ndef save_hdf5(h5file, h5section, name, data_out):\n write_on_top = h5section == \"\" or h5section == \"/\" or h5section == \"''\"\n h5mode = \"a\" if os.path.exists(h5file) else \"w\" # and not write_on_top\n #h5mode=\"w\"\n hdf5_out = h5py.File(h5file, h5mode)\n\n if not write_on_top:\n if h5section in hdf5_out:\n del hdf5_out[h5section]\n h5top = hdf5_out.create_group(h5section)\n else:\n h5top = hdf5_out\n print(\"Saving to\", h5file, \"/\" + h5section + \"/\" + name,end=\": \")\n \n sg = h5top.create_group(name) \n for h,v in data_out.items():\n print(h,end=\"; \")\n v1 = v\n is_complex = False\n if isinstance(v, (list, tuple, np.ndarray)):\n is_complex = (v.dtype == np.complex)\n if is_complex:\n v1 = v.astype(np.complex).view(np.float).reshape(np.append(v.shape,[2]))\n dset = sg.create_dataset(h, data = v1)\n if is_complex: \n dset.attrs[\"__complex__\"] = 1\n hdf5_out.close()\n print(\"\\nDone.\\n\")\n \n \ndef read_hdf5(h5file, h5section, name):\n read_on_top = h5section == \"\" or h5section == \"/\" or h5section == \"''\"\n h5mode = \"r\" \n success = os.path.exists(h5file)\n dummy_out = (False,None)\n if not success:\n return dummy_out\n\n hdf5_out = h5py.File(h5file, h5mode)\n \n success = h5section in hdf5_out or read_on_top\n if not success:\n return dummy_out\n\n print (h5file, h5section, name, read_on_top)\n if not read_on_top:\n h5top = hdf5_out[h5section]\n else:\n h5top = hdf5_out\n print(\"Reading from\", h5file, \"/\", h5section)\n\n success = name in h5top\n if not success:\n return dummy_out\n\n \n sg = h5top[name]\n vnames = sg.keys()\n data_in1 = dict()\n for h in vnames:\n data_in1[h] = sg.get(h).value \n hdf5_out.close()\n return (success, data_in1)\n\nh5path = os.getcwd() if p[\"h5path\"] == \"\" else p[\"h5path\"]\nh5file = p[\"h5file\"]\np[\"h5file\"] = h5file\nh5file = h5path + os.path.sep + p[\"h5file\"]\nif p[\"save_hdf5\"]:\n os.remove(h5file) if os.path.exists(h5file) else None\n save_hdf5(h5file,p[\"h5section\"],\"parameters\",p) \n save_hdf5(h5file,p[\"h5section\"],\"lattice\",data_out)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
Mashimo/datascience
|
01-Regression/Regularisation.ipynb
|
apache-2.0
|
[
"Regularisation\nThe basic idea of regularisation is to penalise or shrink the large coefficients of a regression model.\nThis can help with the bias / variance trade-off and can help with model selection by automatically removing irrelevant features.\nThe shrinkage models that we will see here are the Ridge regression and Lasso.\nAn example: predict credit balance\nThe Credit data set records Balance (average credit card debt for a number of individuals) as well as several quantitative predictors: age, cards (number of credit cards), education (years of education), income (in thousands of dollars), limit (credit limit), and rating (credit rating). In addition to these quantitative variables, we also have four qualitative variables: gender, student (student status), status (marital status), and ethnicity (Caucasian, African American or Asian).",
"import pandas as pd\n\n# load up the Credit dataset \n#\ndata = pd.read_csv(\"../datasets/credit.csv\", index_col=0) \n\ndata.shape\n\ndata.columns\n\ndata.head()\n\ndata.describe()\n\ndata.info()",
"Prepare training data: features and target",
"y = data['Balance'].copy() # our target\nX = data.copy()\nX.drop(['Balance'], axis=1, inplace=True)",
"Predict balance from gender (variable with two levels)\nSuppose that we wish to investigate differences in credit card balance between males and females, ignoring the other variables for the moment.\nIf a qualitative predictor has only two levels then we can simply create an indicator or dummy variable that takes on two possible numerical values. \nWe can use the Python map primitive to map Female to 1 and Male to 0.\nBe careful that the labels need to be mapped correctly, eventual spaces included.",
"X.loc[1, 'Gender']\n\nX.Gender = X.Gender.map({'Female':1, ' Male':0})\nX.Gender.head()",
"The decision to use 0 or 1 is arbitrary and has no effect on the regression fit but different values could result in different coefficients.\nWe now use the new dummy variable as a predictor in a regression model.",
"from sklearn import linear_model\n\n#\n# : Create the linear regression model \n#\nmodel = linear_model.LinearRegression()\n\nmodel.fit(X[['Gender']], y)\nmodel.intercept_\n\nmodel.coef_",
"This results in the model:\nBalance = 509.7 if male\nBalance = 509.7 + 19.7 if female\nAnd 19.7 can be interpreted as the average difference in credit card balance between females and males (females are estimated to carry $19.7 in additional debt for a total of 509.7+19.7 = $529.4).\nHowever without checking its p-value or confidence intervals (outside the scope of this) we cannot say anything about the statistical evidence of this difference.\nPredict balance from ethnicity (variable with 3 levels)\nWhen a qualitative predictor has more than two levels, a single dummy variable cannot represent all possible values. In this situation, we can split a categorical variable into additional different binary variables, one for each level.\nFor example, for the ethnicity variable we create three dummy variables, using the pandas get_dummies() function.",
"etno = pd.get_dummies(X['Ethnicity']) # creates extra columns\nX = X.join(etno)\nX.head()",
"Since the dummies variable are additional - not new values mapped to the existing variable like for the gender - we can now drop the Ethnicity variable:",
"X.drop(['Ethnicity'], axis=1, inplace=True)\n\nfeatures = X[['Asian', 'Caucasian', 'African American']]\n\nmodel.fit(features, y)\nmodel.intercept_\n\nmodel.coef_",
"We see that the estimated balance for the African American is $531.00 = $520.60 + 10.40; it is estimated that the Asian category will have 18.7 dollars less debt than the African American category, and that the Caucasian category will have $12.50 less debt than the African American category. \nAgain, no statistical evidence.\nPredict from all variables\nFirst we convert the other two categorical variables:",
"X.Student = X.Student.map({'Yes':1, 'No':0})\nX.Married = X.Married.map({'Yes':1, 'No':0})\nX.head()",
"Now we implement a naive version of the Forward Stepwise Selection:\nstart from a null model and add the next feature with the best score (in terms of square error).",
"def find_best_feature(X):\n n_features = X.shape[1]\n max_score = 0\n for i in range(n_features):\n feature = X.columns[i]\n X_subset = X[[feature]]\n model.fit(X_subset, y)\n score = model.score(X_subset, y) # R^2 metric\n if score > max_score:\n max_score = score\n max_feature = feature\n\n return (max_score, max_feature)\n\nfind_best_feature(X)\n\nn_features = X.shape[1]\nscores = [0]\nX_selection = X.copy()\nX_subsets = pd.DataFrame(index=X.index)\n\nfor i in range(n_features):\n (_, next_best_feature) = find_best_feature(X_selection)\n print('Next best feature = {}'.format(next_best_feature))\n X_subset = X_selection[[next_best_feature]]\n X_subsets[next_best_feature] = X_subset\n\n model.fit(X_subsets, y)\n scores.append(model.score(X_subsets, y))\n \n X_selection.drop([next_best_feature], axis=1, inplace=True)\n\nprint(scores)",
"The first features are Rating, Limit, Income and Student.\nJust with these 4 features, the R2 score is already at 0.95",
"import matplotlib.pyplot as plt\n\nplt.title(\"Score versus features\")\nplt.xlabel('Number of features') \nplt.ylabel('R squared')\nplt.plot(scores)",
"The first 4 features are the best predictors, the others do not add too much value.\nAs we add more and more parameters to our model its complexity increases, which results in increasing variance and decreasing bias, i.e. overfitting. \nBasically there are two methods to overcome overfitting,\n\nReduce the model complexity (less features! Use a selection algorithm as the one above and extract a subset of features).\nRegularisation (what we are going to see)\n\nRegularisation\nThe subset selection methods use least squares to fit a linear model that contains a subset of the predictors.\nAs an alternative, we can fit a model containing all p predictors using a technique that constrains or regularises the coefficient estimates.",
"predictors = X.columns\ncoef = pd.Series(model.coef_,predictors).sort_values()\ncoef\n\ncoef.plot(kind='bar', title=\"Modal coefficients\")",
"We can see that the coefficient of Card is much higher as compared to rest of the coefficients. Therefore the credit balance of a person would be more driven by this feature.\nRidge Regression\nthe ridge regression coefficient estimates ˆR\nare the values that minimize ..\nAs with least squares, ridge regression seeks coe cient estimates that fit the data wePll, by making the RSS small.\n• However, the second term, j j2, called a shrinkage penalty, is small when 1, . . . , p are close to zero, and so it has the e↵ect of shrinking the estimates of j towards zero.\n• The tuning parameter serves to control the relative impact of these two terms on the regression coe cient estimates.\n• Selecting a good value for is critical; cross-validation is used for this.\nSKlearn has a module Ridge to apply a Ridge regression model.\nLet's see an example using lambda = 0.05 (called alpha in SciKitLearn)",
"from sklearn.linear_model import Ridge\n\n## training the model\nridgeReg = Ridge(alpha=0.05)\n\nridgeReg.fit(X, y)\n\nridgeReg.score(X, y)\n\nridgeReg.coef_",
"As you can see, the coefficients have been shrinked, and Cards is not sticking out anymore.\nStandardise\nThe standard least squares coefficient estimates are scale equivariant: multiplying Xj by a constant c simply leads to a scaling of the least squares coefficient estimates by a factor of 1/c.\nIn other words, regardless of how the jth predictor is scaled, Xj ˆj will remain the same.\nIn contrast, the ridge regression coefficient estimates can change substantially when multiplying a given predictor by a constant, due to the sum of squared coefficients term in the penalty part of the ridge regression objective function.\nTherefore, it is best to apply ridge regression after standardizing the predictors.",
"from sklearn import preprocessing\n\nscaler = preprocessing.StandardScaler()\nX = scaler.fit_transform(X)",
"how lambda affects the coefficients\nLet's plot the coefficients values based on the lambda parameter.",
"import numpy as np\n\nlambdas = [0.01, 1, 100, 10000]\ncoefficients = np.zeros(shape=(12, len(lambdas)))\ni=0\nfor l in lambdas:\n ridgeReg = Ridge(alpha=l)\n ridgeReg.fit(X, y)\n coefficients[:,i] = ridgeReg.coef_\n i += 1\n\nfig, ax = plt.subplots()\n\nplt.title(\"Ridge regularisation\")\nplt.xlabel(\"lambda\")\nplt.ylabel(\"standardised coefficients\")\nstyles=['-','--','-.',':']\n\nlabels = ['0.01','','1','', '100','', '1e4','']\nax.set_xticklabels(labels) # custom x labels\n\nfor i in range(0,12):\n s = styles[i % len(styles)]\n if i<3 or i==7:\n plt.plot(coefficients[i], label=predictors[i], linestyle=s)\n else:\n plt.plot(coefficients[i])\n\nplt.legend(loc='best')",
"Each curve corresponds to the ridge regression coefficient estimate for one of the variables, plotted as a function of λ.\nAt the left side of the plot, λ is essentially zero, and so the corresponding ridge coefficient estimates are the same as the usual least squares estimates. But as λ increases, the ridge coefficient estimates shrink towards zero. When λ is extremely large, then all of the ridge coefficient estimates are basically zero; this corresponds to the null model that contains no predictors.\nIn this plot, the income, limit, rating, and student variables are displayed in distinct colours, since these variables are the ones to have the largest coefficient estimates. \nRidge regression does have one obvious disadvantage.\nUnlike best subset, forward stepwise, and backward stepwise selection, which will generally select models that involve just a subset of the variables, ridge regression will include all p predictors in the final model.\nThe penalty λ will shrink all of the coefficients towards zero, but it will not set any of them exactly to zero.\nThis may not be a problem for prediction accuracy, but it can create a challenge in model interpretation in settings in which the number of variables p is quite large.\nFor example, in the Credit data set, it appears that the most important variables are income, limit, rating, and student. So we might wish to build a model including just these predictors. However, ridge regression will always generate a model involving all ten predictors.\nIncreasing the value of λ will tend to reduce the magnitudes of the coefficients, but will not result in exclusion of any of the variables.\nThe lasso is a relatively recent alternative to ridge regression that over-comes this disadvantage. \nThe lasso",
"from sklearn.linear_model import Lasso\n\nlassoReg = Lasso(alpha=0.3)\n\nlassoReg.fit(X, y)\n\nlassoReg.score(X, y)",
"In statistical parlance, the lasso uses an L1 penalty instead of an L2 penalty. \nThe L1 penalty has the effect of forcing some of the coefficient estimates to be exactly equal to zero when the tuning parameter λ is sufficiently large. Hence, much like best subset selection, the lasso performs variable selection.\nAs a result, models generated from the lasso are generally much easier to interpret than those produced by ridge regression. The lasso yields sparse models — that is, models that involve only a subset of the variables.",
"lambdas = [0.01, 1, 10, 50, 100, 200, 500, 1000]\ncoefficients = np.zeros(shape=(12, len(lambdas)))\ni=0\nfor l in lambdas:\n lassoReg = Lasso(alpha=l)\n lassoReg.fit(X, y)\n coefficients[:,i] = lassoReg.coef_\n i += 1\n\nfig, ax = plt.subplots()\n\nplt.title(\"Lasso Regularisation\")\nplt.xlabel(\"lambda\")\nplt.ylabel(\"standardised coefficients\")\nstyles=['-','--','-.',':']\n\nlabels = ['0.01','1','10','50', '100', '200','500','1000']\n\nax.set_xticklabels(labels) # custom x labels\n\nfor i in range(0,12):\n s = styles[i % len(styles)]\n if i<3 or i==7:\n plt.plot(coefficients[i], label=predictors[i], linestyle=s)\n else:\n plt.plot(coefficients[i])\n\nplt.legend(loc='best')",
"When λ = 0, the lasso simply gives the least squares fit and when λ becomes sufficiently large, the lasso gives the null model in which all coefficient estimates equal zero.\nHowever, in between these two extremes, the ridge regression and lasso models are quite different from each other, as you can see from the two plots.\nBoth in ridge regression and lasso, the tuning parameter serves to control the relative impact of the shrinking terms on the regression coeffcient estimates.\nSelecting a good value for λ is critical; cross-validation is used for this.\nSelecting the Tuning Parameter lambda\nCross-validation provides a simple way to tackle this problem. We choose a grid of λ values, and compute the cross-validation error for each value of λ\nWe then select the tuning parameter value for which the cross-validation error is smallest. Finally, the model is re-fit using all of the available observations and the selected value of the tuning parameter.",
"from sklearn.model_selection import cross_val_score, KFold\n\nlambdas = np.linspace(500,0.01,num=50)\nscoresCV = []\nfor l in lambdas:\n lassoReg = Lasso(alpha=l)\n lassoReg.fit(X, y) \n \n scoreCV = cross_val_score(lassoReg, X, y, scoring='neg_mean_squared_error', \n cv=KFold(n_splits=10, shuffle=True,\n random_state=1))\n scoresCV.append(np.mean(scoreCV))\n \n\nplt.title(\"Lambda tuning for Lasso Regularisation\")\nplt.xlabel(\"lambda\")\nplt.ylabel(\"Cross-Validation error (MSE)\")\n\nplt.plot(lambdas,scoresCV)",
"The plot displays how the cross-validation error changes with different values of lambda.\nThe point at which the cross-validation error is smallest is for very small values of lambda, close to zero.\nThanks to the sklearn function LassoCV, that applies cross-validation to the Lasso, we can calculate the exact value of lambda that minimise the error:",
"from sklearn.linear_model import LassoCV\n\nlassoCV = LassoCV()\nlassoCV.fit(X,y)\n\nlassoCV.alpha_"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
tensorflow/tensorrt
|
tftrt/examples/presentations/GTC-April2021-Dynamic-shape-ResNetV2.ipynb
|
apache-2.0
|
[
"# Copyright 2021 NVIDIA Corporation. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"TF-TRT Dynamic shapes example: ResNetV2\nThis notebook demonstrates how to use TF-TRT dynamic shape feature to generate a single engine with multiple optimization profiles, each optimized for a different batch size.\nRequirements\nThis notebook requires at least TF 2.5 and TRT 7.1.3.",
"# Verbose output\n# import os\n# os.environ[\"TF_CPP_VMODULE\"]=\"trt_engine_utils=2,trt_engine_op=2,convert_nodes=2,convert_graph=2,segment=2,trt_shape_optimization_profiles=2,trt_engine_resource_ops=2\"\n\n!pip install pillow matplotlib\n\nimport tensorflow as tf\nfrom tensorflow.python.compiler.tensorrt import trt_convert as trt\nimport numpy as np\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.framework import convert_to_constants\nfrom tensorflow.keras.applications.resnet_v2 import ResNet50V2\nfrom timeit import default_timer as timer",
"Load and save the TF model",
"model = ResNet50V2(weights='imagenet') \ntf.saved_model.save(model, 'resnet_v2_50_saved_model')",
"Helper functions",
"def get_func_from_saved_model(saved_model_dir):\n saved_model_loaded = tf.saved_model.load(\n saved_model_dir, tags=[tag_constants.SERVING])\n graph_func = saved_model_loaded.signatures[\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY]\n return graph_func, saved_model_loaded\n\ndef predict_and_benchmark_throughput(batched_input, model, N_warmup_run=50, N_run=500,\n result_key='predictions', batch_size=None):\n elapsed_time = []\n all_preds = []\n \n if batch_size is None or batch_size > batched_input.shape[0]:\n batch_size = batched_input.shape[0]\n print('Benchmarking with batch size', batch_size)\n \n elapsed_time = np.zeros(N_run)\n for i in range(N_warmup_run): \n preds = model(batched_input)\n \n # Force device synchronization\n tmp = preds[result_key][0,0].numpy() \n \n for i in range(N_run):\n start_time = timer()\n preds = model(batched_input)\n # Synchronize\n tmp += preds[result_key][0,0].numpy() \n end_time = timer()\n elapsed_time[i] = end_time - start_time\n all_preds.append(preds)\n\n if i>=50 and i % 50 == 0:\n print('Steps {}-{} average: {:4.1f}ms'.format(i-50, i, (elapsed_time[i-50:i].mean()) * 1000))\n\n print('Latency: {:5.2f}+/-{:4.2f}ms'.format(elapsed_time.mean()* 1000, elapsed_time.std()* 1000))\n print('Throughput: {:.0f} images/s'.format(N_run * batch_size / elapsed_time.sum()))\n return all_preds\n\ndef get_dummy_images(batch_size = 32, img_shape = [224, 224, 3]):\n img=tf.random.uniform(shape=[batch_size] + img_shape, dtype=tf.float32)\n print(\"Generated input random images with shape (N, H, W, C) =\", img.shape)\n return img",
"Input data\nGet some images from the web that will be used for testing the model",
"!mkdir data\n!wget -O ./data/img0.JPG \"https://d17fnq9dkz9hgj.cloudfront.net/breed-uploads/2018/08/siberian-husky-detail.jpg?bust=1535566590&width=630\"\n!wget -O ./data/img1.JPG \"https://www.hakaimagazine.com/wp-content/uploads/header-gulf-birds.jpg\"\n!wget -O ./data/img2.JPG \"https://www.artis.nl/media/filer_public_thumbnails/filer_public/00/f1/00f1b6db-fbed-4fef-9ab0-84e944ff11f8/chimpansee_amber_r_1920x1080.jpg__1920x1080_q85_subject_location-923%2C365_subsampling-2.jpg\"\n!wget -O ./data/img3.JPG \"https://www.familyhandyman.com/wp-content/uploads/2018/09/How-to-Avoid-Snakes-Slithering-Up-Your-Toilet-shutterstock_780480850.jpg\"",
"We will also use a batch of random pixels",
"input = get_dummy_images(128)",
"Run inference with TF",
"func, _ = get_func_from_saved_model('resnet_v2_50_saved_model')\n\noutput = func(input)\n\nprint('output shape',output['predictions'].shape)\n\nres = predict_and_benchmark_throughput(input, func, N_run=100)",
"Test the model on real data",
"import matplotlib.pyplot as plt\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications.resnet_v2 import preprocess_input, decode_predictions\n\ndef infer_real_images(func, img_shape=(224,224)):\n for i in range(4):\n img_path = './data/img%d.JPG'%i\n img = image.load_img(img_path, target_size=img_shape)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n \n preds = func(tf.convert_to_tensor(x))['predictions'].numpy()\n # decode the results into a list of tuples (class, description, probability)\n # (one such list for each sample in the batch)\n print('{} - Predicted: {}'.format(img_path, decode_predictions(preds, top=3)[0]))\n\n plt.subplot(2,2,i+1)\n plt.imshow(img);\n plt.axis('off');\n plt.title(decode_predictions(preds, top=3)[0][0][1])\n\ninfer_real_images(func)",
"Convert the model with TF-TRT",
"def trt_convert(input_path, output_path, input_shapes, explicit_batch=False):\n conv_params=trt.TrtConversionParams(\n precision_mode='FP16', minimum_segment_size=3,\n max_workspace_size_bytes=1<<30, maximum_cached_engines=1)\n converter = trt.TrtGraphConverterV2(\n input_saved_model_dir=input_path, conversion_params=conv_params,\n use_dynamic_shape=explicit_batch, dynamic_shape_profile_strategy='Optimal')\n\n converter.convert()\n def input_fn():\n for shapes in input_shapes:\n # return a list of input tensors\n yield [np.ones(shape=x).astype(np.float32) for x in shapes]\n\n converter.build(input_fn)\n converter.save(output_path)",
"Convert using implicit batch mode",
"trt_convert(input_path=\"resnet_v2_50_saved_model\", output_path=\"resnet_v2_50_trt\",\n input_shapes=[[input.shape]], \n explicit_batch=False)",
"Load converted model and check difference",
"trt_func, _ = get_func_from_saved_model('resnet_v2_50_trt')\n\ntrt_output = trt_func(input)\n\ndiff = output['predictions'] - trt_output['predictions']\nnp.max(np.abs(diff.numpy()))",
"Test the the converted model on real images",
"infer_real_images(trt_func)",
"Benchmark converted model",
"res = predict_and_benchmark_throughput(input, trt_func)",
"Check with different batch sizes",
"input1 = get_dummy_images(1)\nres = predict_and_benchmark_throughput(input1, trt_func)\n\ninput8 = get_dummy_images(8)\nres = predict_and_benchmark_throughput(input8, trt_func)\n\ninput32 = get_dummy_images(32)\nres = predict_and_benchmark_throughput(input32, trt_func)\n\ninput64 = get_dummy_images(64)\nres = predict_and_benchmark_throughput(input64, trt_func)",
"Convert in dynamic mode\nWe convert for a single input shape first, just to test whether we get the same perf as in implicit batch mode.",
"trt_convert(input_path=\"resnet_v2_50_saved_model\", output_path=\"resnet_v2_50_trt_ds\",\n input_shapes=[[input.shape]], \n explicit_batch=True)\n\ntrt_func_ds, _ = get_func_from_saved_model('resnet_v2_50_trt_ds')\ntrt_output = trt_func_ds(input)\n\ndiff = output['predictions'] - trt_output['predictions']\nnp.max(np.abs(diff.numpy()))\n\ninfer_real_images(trt_func_ds)\n\nres = predict_and_benchmark_throughput(input, trt_func_ds)",
"Convert with multiple profiles and benchmark\nHere we show that we can have a single engine that is optimized to infer with various batch sizes: 1, 8, 32",
"img_shape = [224, 224, 3]\ntrt_convert(input_path=\"resnet_v2_50_saved_model\", output_path=\"resnet_v2_50_trt_ds2\",\n input_shapes=[[[1] + img_shape,], \n [[8] + img_shape,], \n [[32] + img_shape,],\n [[64] + img_shape,],\n [[128] + img_shape,]], \n explicit_batch=True)\n\ntrt_func_ds2, _ = get_func_from_saved_model('resnet_v2_50_trt_ds2')",
"Batch size 128\nSame results as before.",
"res = predict_and_benchmark_throughput(input, trt_func_ds2)",
"Batch size 1\nWe compare the implicit batch engine to the dynamic shape engine. Note, that the implicit batch engine handles batch sizes 1..32, and it was optimized for N=32. The dynamic shape engine has a profile optimized for N=1, therefore it is faster (1.5 ms vs 2.2ms in implicit batch mode, measured on a V100 16GB card).",
"res = predict_and_benchmark_throughput(input1, trt_func_ds2)",
"Batch size 8\nThis is also faster with the dynamic shape engine 2.7 ms vs 3.1 in implicit batch mode.",
"res = predict_and_benchmark_throughput(input8, trt_func_ds2)\n\nres = predict_and_benchmark_throughput(input32, trt_func_ds2)\n\nres = predict_and_benchmark_throughput(input64, trt_func_ds2)\n",
"Plots",
"import matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnvgreen = np.array((118, 185, 0)) / 255\nmedium_gray = np.array([140, 140, 140])/255\n\nlabels = ['1', '8', '32', '64', '128']\n\n# Latency time for dynamic shae and implicit batch benchmarks\nds_time = [1.6, 2.9, 7.5, 13.3, 24.0]\nimpl_time = [2.99, 3.9, 7.96, 13.5, 23.98]\n\nx = np.arange(len(labels)) # the label locations\nwidth = 0.35 # the width of the bars\n\nfig, ax = plt.subplots()\nrects1 = ax.bar(x - width/2, ds_time, width, color=nvgreen, label='Dynamic shape')\nrects2 = ax.bar(x + width/2, impl_time, width, color=medium_gray, label='implicit batch')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\nax.set_ylabel('time (ms)')\nax.set_title('Inference latency (single TRT engine)')\nax.set_xticks(x)\nax.set_xlabel('batch size')\nax.set_xticklabels(labels)\nax.legend()"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
datascience-practice/data-quest
|
python_introduction/intermediate/.ipynb_checkpoints/indexing-and-more-functions-checkpoint.ipynb
|
mit
|
[
"2: Writing a while loop\nInstructions\nCreate a while loop that tests if b is greater than 5. If it is, the loop body should print b out, then subtract one from it.",
"x = 3\n# The loop body will execute three times. Once when x == 3, once when x == 4, and once when x == 5.\n# Then x < 6 will evaluate to False, and it will stop.\n# 3, 4, and 5 will be printed out.\nwhile x < 6:\n print(x)\n # Using += is a shorter way of saying x = x + 1. It will add one to x.\n x += 1\n\nb = 10",
"Answer",
"while b > 5:\n print(b)\n b -= 1",
"3: Using the break keyword\nInstructions\nLet's say we want two \"Bengal\" tigers from available_tigers for our nature reserve.\nWrite a for loop that increments tiger_count when it finds one, and breaks after finding two.",
"available_count = 0\ndesired_dog = \"Great Dane\"\navailable_dogs = [\"Labrador\", \"Poodle\", \"Sheepdog\", \"Great Dane\", \"Pomeranian\", \"Great Dane\", \"Collie\"]\n\n# Let's say we are searching for two dogs of the same breed to adopt.\n# We'll loop through the dogs.\nfor dog in available_dogs:\n # If our desired dog is found.\n if dog == desired_dog:\n # Increment the counter.\n available_count += 1\n # We only want two dogs, so we can stop searching after we find them.\n if available_count == 2:\n break\n\ntiger_count = 0\ndesired_tiger = \"Bengal\"\navailable_tigers = [\"Bengal\", \"Dressed up poodle\", \"Siberian\", \"Sumatran\", \"Bengal\", \"Housecat\", \"Hobbes\"]",
"Answer",
"for t in available_tigers:\n if t == \"Bengal\":\n tiger_count += 1\n if tiger_count == 2:\n break",
"4: Finding a column number from a name\nInstructions\nWrite a function that will get the column number from the column name.\nUse it to get the column number for the \"arr_delay\" column and assign it to the arr_delay variable.\nUse it to get the column number for the \"weather_delay\" column and assign it to the weather_delay variable.",
"column_names = ['year',\n 'month',\n 'carrier',\n 'carrier_name',\n 'airport',\n 'airport_name',\n 'arr_flights',\n 'arr_del15',\n 'carrier_ct',\n 'weather_ct',\n 'nas_ct',\n 'security_ct',\n 'late_aircraft_ct',\n 'arr_cancelled',\n 'arr_diverted',\n 'arr_delay',\n 'carrier_delay',\n 'weather_delay',\n 'nas_delay',\n 'security_delay',\n 'late_aircraft_delay']\n\n# It's pretty easy to get a column name from a column number.\n# The third column contains the carrier (same as the airline).\nprint(column_names[2])",
"Answer",
"def number_by_name(name):\n found = None\n for i, nm in enumerate(column_names):\n if nm == name:\n found = i\n break\n return found\n \n\narr_delay = number_by_name(\"arr_delay\")\nweather_delay = number_by_name(\"weather_delay\")\nprint(arr_delay, weather_delay)",
"5: Using negative indexing\nInstructions\nUse negative indexing to assign the third to last row in flight_delays to third_to_last.\nUse negative slicing to assign the fourth, third, and second to last rows in flight_delays to end_slice",
"from flight_delays import flight_delays\n# Prints the last row in flight_delays\nprint(flight_delays[-1])\n\n# Prints the second to last row in flight_delays\nprint(flight_delays[-2])\n\n# Prints the third to last and second to last rows in flight_delays (remember that slicing only goes up to but not including the second number)\n# This will get the rows at index -3 and -2\nprint(flight_delays[-3:-1])",
"Answer",
"third_to_last = flight_delays[-3]\nend_slice = flight_delays[-4:-1]\n\nprint(third_to_last, end_slice)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
patrickmineault/xcorr-notebooks
|
notebooks/Multi-armed bandit as a Markov decision process.ipynb
|
mit
|
[
"# Standard plotting setup\n%matplotlib inline\nimport matplotlib.pyplot as plt\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 10, 5\nplt.style.use('ggplot')",
"Multi-armed bandit as a Markov decision process\nLet's model the Bernouilli multi-armed bandit. The Bernoulli MBA is an $N$-armed bandit where each arm gives binary rewards according to some probability:\n$r_i \\sim Bernouilli(\\mu_i)$ \nHere $i$ is the index of the arm. Let's model this as a Markov decision process. The state is going to be defined as:\n$s(t) = (\\alpha_1, \\beta_1, \\ldots, \\alpha_N, \\beta_N, r_t)$\n$\\alpha_i$ is the number of successes encountered so far when pulling arm $i$. $\\beta_i$ is, similarly, the number of failures encountered when pulling that arm. $r_t$ is the reward, either 0 or 1, from the last trial. \nAssuming a uniform prior on $\\mu_i$, the posterior distribution of the $\\mu_i$ in a given state are:\n$p(\\mu_i|s(t)) = Beta(\\alpha_i+1,\\beta_i+1)$\nWhen we're in a given state, we have the choice of performing one of $N$ actions, corresponding to pulling each of the arms. Let's call pulling the $i$'th arm $a_i$. This will put us in a new state, with a certain probability. The new state will be same for arms not equal to i. For the $i$'th arm, we have:\n$s(t+1) = (\\ldots \\alpha_i + 1, \\beta_i \\ldots 1)$ with probability $(\\alpha_i+1)/(\\alpha_i+\\beta_i+2)$\n$s(t+1) = (\\ldots \\alpha_i, \\beta_i + 1 \\ldots 0)$ with probability $(\\beta_i+1)/(\\alpha_i+\\beta_i+2)$\nWe can solve this MDP exactly, e.g. using value iteration, for a small enough state space. For $M$ trials, the state space has cardinality $M^{2N}$ - it's possible to solve the 2-armed bandit for 10-20 trials this way, but it grows exponentially fast. \nNevertheless, we can use this optimal solution to compare it with commonly used heuristics like $\\epsilon$-greedy and UCB and determine how often these pick the optimal moves. Then we'll get some intuitions about what $\\epsilon$-greedy and UCB get right and wrong. Let's do it!",
"import itertools\nimport numpy as np\nfrom pprint import pprint\n\ndef sorted_values(dict_):\n return [dict_[x] for x in sorted(dict_)]\n\ndef solve_bmab_value_iteration(N_arms, M_trials, gamma=1,\n max_iter=10, conv_crit = .01):\n util = {}\n \n # Initialize every state to utility 0.\n state_ranges = [range(M_trials+1) for x in range(N_arms*2)]\n # The reward state\n state_ranges.append(range(2))\n for state in itertools.product(*state_ranges):\n # Some states are impossible to reach.\n if sum(state[:-1]) > M_trials:\n # A state with the total of alphas and betas greater than \n # the number of trials.\n continue\n \n if sum(state[:-1:2]) == 0 and state[-1] == 1:\n # A state with a reward but alphas all equal to 0.\n continue\n \n if sum(state[:-1:2]) == M_trials and state[-1] == 0:\n # A state with no reward but alphas adding up to M_trials.\n continue\n \n if sum(state[:-1]) == 1 and sum(state[:-1:2]) == 1 and state[-1] == 0:\n # A state with an initial reward according to alphas but not according\n # the reward index\n continue\n \n util[state] = 0\n \n # Main loop.\n converged = False\n new_util = util.copy()\n opt_actions = {}\n for j in range(max_iter):\n # Line 5 of value iteration\n for state in util.keys():\n reward = state[-1]\n \n # Terminal state.\n if sum(state[:-1]) == M_trials:\n new_util[state] = reward\n continue\n \n values = np.zeros(N_arms)\n \n # Consider every action\n for i in range(N_arms):\n # Successes and failure for this state.\n alpha = state[i*2]\n beta = state[i*2+1]\n \n # Two possible outcomes: either that arm gets rewarded,\n # or not.\n # Transition to unrewarded state:\n state0 = list(state)\n state0[-1] = 0\n state0[2*i+1] += 1\n state0 = tuple(state0)\n \n # The probability that we'll transition to this unrewarded state.\n p_state0 = (beta + 1) / float(alpha + beta + 2)\n \n # Rewarded state.\n state1 = list(state)\n state1[-1] = 1\n state1[2*i] += 1\n state1 = tuple(state1)\n \n p_state1 = 1 - p_state0\n try:\n value = gamma*(util[state0]*p_state0 + \n util[state1]*p_state1)\n except KeyError,e:\n print state\n print state0\n print state1\n raise e\n \n #print state0, util[state0], p_state0\n #print state1, util[state1], p_state1\n values[i] = value\n \n #print state, values, reward\n new_util[state] = reward + np.max(values)\n opt_actions[state] = np.argmax(values)\n \n # Consider the difference between the new util\n # and the old util.\n max_diff = np.max(abs(np.array(sorted_values(util)) - np.array(sorted_values(new_util))))\n util = new_util.copy()\n \n print \"Iteration %d, max diff = %.5f\" % (j, max_diff)\n if max_diff < conv_crit:\n converged = True\n break\n \n #pprint(util)\n \n if converged:\n print \"Converged after %d iterations\" % j\n else:\n print \"Not converged after %d iterations\" % max_iter\n \n return util, opt_actions\n\nutil, opt_actions = solve_bmab_value_iteration(2, 2, max_iter=5)\n\nopt_actions",
"For the 2-armed, 2-trial Bernoulli bandit, the strategy is simple: pick the first arm. If it rewards, then pick it again. If not, pick the other. Note that this is the same as most sensible strategies, for instance $\\epsilon$- greedy or UCB.",
"util",
"Note that the utility of the root node is 1.08 - what does that mean? If we get rewarded in the initial trial, that means that the posterior for the mean of that arm is .67. OTOH, when we fail on the first trial, we can still pick the other arm, which still has a posterior mean of .5. Thus, we have rewards:\n\n+2 with probability .5*2/3\n+1 with prob .5*1/3\n+1 with prob .5*.5\n+0 with prob .5*.5\n\nThat means the expected total reward is:",
"2*.5*2.0/3.0 + .5/3.0 + .5*.5",
"And that's what utility means in this context.\nLet's see about the 3-trial 2-armed bandit:",
"util, opt_actions = solve_bmab_value_iteration(2, 3, max_iter=5)\nopt_actions",
"The optimal strategy goes: pick arm 0. If it rewards, pick it again for the next 2 trials.\nIf it doesn't reward, then pick arm 1. If that rewards, keep that one. If it doesn't, pick 0 again.\nLet's see with 4:",
"util, opt_actions = solve_bmab_value_iteration(2, 4, max_iter=6)",
"What's interesting here is that value iteration always converges in M_trials + 1 iterations - information only travels backwards through time - much as in Viterbi in the context of HMMs. If we're only interested in the next best action given the current state, it might be possible to iterate backwards through time, starting from the terminal states, throwing away the latest data as we go along -- but let's not get into this premature optimization just yet. Let's see how for how many trials we can solve this without crashing my 5 year-old laptop.",
"M_trials = 16\n%time util, opt_actions = solve_bmab_value_iteration(2, M_trials, max_iter=M_trials+2)",
"It seems like my laptop can look ahead at least sixteen steps into the future without dying - pretty good!\nOptimal versus UCB\nLet's try and figure out how the optimal strategy relates to the upper confidence bound (UCB) heuristic. Let's train a logistic regression model with the same inputs as a UCB strategy - mean, standard deviation, time - and see how well it can approximate the optimal strategy.",
"# Create a design matrix related to the optimal strategies.\nX = []\ny = []\nseen_keys = {}\nfor key, val in opt_actions.iteritems():\n if key[:-1] in seen_keys:\n # We've already seen this, continue.\n continue\n \n alpha0 = float(key[0] + 1)\n beta0 = float(key[1] + 1)\n alpha1 = float(key[2] + 1)\n beta1 = float(key[3] + 1)\n \n if alpha0 == alpha1 and beta0 == beta1:\n # We're in a perfectly symmetric situtation, skip this then.\n continue\n \n seen_keys = key[:-1]\n \n # Standard results for the Beta distribution.\n # https://en.wikipedia.org/wiki/Beta_distribution\n mean0 = alpha0/(alpha0 + beta0)\n mean1 = alpha1/(alpha1 + beta1)\n \n std0 = np.sqrt(alpha0*beta0 / (alpha0 + beta0 + 1)) / (alpha0 + beta0)\n std1 = np.sqrt(alpha1*beta1 / (alpha1 + beta1 + 1)) / (alpha1 + beta1)\n \n t = alpha0 + beta0 + alpha1 + beta1\n X.append([mean0,mean1,std0,std1,t,1,alpha0 - 1,beta0 - 1,alpha1 - 1,beta1 - 1])\n y.append(val)\n \nX = np.array(X)\ny = np.array(y)",
"Let's train three supervised networks:\n\na purely myopic, greedy strategy\none which uses the uncertainty in the estimates\none which uses both uncertainty and number of trials left to hedge its bets",
"from sklearn.linear_model import LogisticRegression\n\nthe_model = LogisticRegression(C=100.0)\nX_ = X[:,:2]\nthe_model.fit(X_,y)\ny_pred = the_model.predict(X_)\n\nprint (\"Greedy: %.4f%% of moves are incorrect\" % ((np.mean(abs(y_pred-y)))*100))\nprint the_model.coef_\n\nthe_model = LogisticRegression(C=100.0)\nX_ = X[:,:4]\nthe_model.fit(X_,y)\ny_pred = the_model.predict(X_)\n\nprint (\"UCB: %.4f%% of moves are incorrect\" % ((np.mean(abs(y_pred-y)))*100))\nprint the_model.coef_\n\nthe_model = LogisticRegression(C=100000.0)\nX_ = X[:,:4]\nX_ = np.hstack((X_,(X[:,4]).reshape((-1,1))*X[:,2:4]))\nthe_model.fit(X_,y)\ny_pred = the_model.predict(X_)\n\nprint (\"UCB X time: %.4f%% of moves are incorrect\" % ((np.mean(abs(y_pred-y)))*100))\nprint the_model.coef_",
"We see that the greedy strategy misses the right move 3% of the time, while UCB shaves that down to 1.8%. Pretty significant. The UCB parameter - a parameter which determines how much \"bonus\" should be given to uncertainty - is suspiciously low at (29.49 / 57.7 ~= .5). In the literature, people use something around 2-3. \nAdding a parameter which is the cross of time and the standard deviation of the estimate reveals the source of this discrepancy: at the initial time point, the UCB parameter is high (496.7 / 201 ~ 2.5) and it ramps down linearly as a function of time to (496 - 26.26*16) / 200 ~= 0.4. Thus, the optimal strategy is similar to a UCB strategy, with a twist: the exploration bonus should ramp down as a function of time. This makes sense: new information is more valuable in the initial trials. \nThis UCB X time strategy misses only .5% of moves, which is quite good, all things considered."
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
volodymyrss/3ML
|
examples/Photometry_demo.ipynb
|
bsd-3-clause
|
[
"import numpy as np\nimport matplotlib.pyplot as plt\n\n%matplotlib inline\n%matplotlib notebook\n\nfrom threeML import *\nfrom astromodels.xspec import *\n\n# The filter library takes a while to load so you must import it explicitly..\n\nfrom threeML.plugins.photometry.filter_library import threeML_filter_library\n\nget_available_plugins()",
"Setup\nWe use speclite to handle optical filters: http://speclite.readthedocs.io/en/latest/ .\nTherefore, you can easily build your own custom filters, use the built in speclite filters, or use the 3ML filter library that we have built thanks to Spanish Virtual Observatory (http://svo.cab.inta-csic.es/main/index.php). \nIf you use these filters, please be sure to cite the proper sources!\nSimple example of building a filter\nLet's say we have our own 1-m telescope with a Johnson filter and we happen to record the data. We also have simultaneous data at other wavelengths and we want to compare. Let's setup the optical plugin (we'll ignore the other data for now).",
"import speclite.filters as spec_filters\n\nmy_backyard_telescope_filter = spec_filters.load_filter('bessell-r')\n\n# NOTE:\nmy_backyard_telescope_filter.name",
"NOTE: the filter name is 'bessell-R'. The plugin will look for the name after the '-' i.e 'R'\nNow let's build a 3ML plugin via PhotometryLike. \nOur data are entered as keywords with the name of the filter as the keyword and the data in an magnitude,error tuple, i.e. R=(mag,mag_err):",
"my_backyard_telescope = PhotometryLike('backyard_astronomy',\n filters=my_backyard_telescope_filter,\n R=(20,.1) )\n\nmy_backyard_telescope.display_filters()",
"3ML filter library\nExplore the filter library. If you cannot find what you need, it is simple to add your own",
"threeML_filter_library.SLOAN\n\nspec_filters.plot_filters(threeML_filter_library.SLOAN.SDSS)\n\nspec_filters.plot_filters(threeML_filter_library.Herschel.SPIRE)\n\nspec_filters.plot_filters(threeML_filter_library.Keck.NIRC2)",
"Build your own filters\nFollowing the example from speclite, we can build our own filters and add them:",
"fangs_g = spec_filters.FilterResponse(\n wavelength = [3800, 4500, 5200] * u.Angstrom,\n response = [0, 0.5, 0], meta=dict(group_name='fangs', band_name='g'))\nfangs_r = spec_filters.FilterResponse(\n wavelength = [4800, 5500, 6200] * u.Angstrom,\n response = [0, 0.5, 0], meta=dict(group_name='fangs', band_name='r'))\n\nfangs = spec_filters.load_filters('fangs-g', 'fangs-r')\n\nfangslike = PhotometryLike('fangs',filters=fangs,g=(20,.1),r=(18,.1))\n\n\nfangslike.display_filters()",
"GROND Example\nNow we will look at GROND. We get the filter from the 3ML filter library.\n(Just play with tab completion to see what is available!)",
"grond = PhotometryLike('GROND',\n filters=threeML_filter_library.ESO.GROND,\n #g=(21.5.93,.23),\n #r=(22.,0.12),\n i=(21.8,.01),\n z=(21.2,.01),\n J=(19.6,.01),\n H=(18.6,.01),\n K=(18.,.01))\n\ngrond.display_filters()",
"Model specification\nHere we use XSPEC's dust extinction models for the milky way and the host",
"spec = Powerlaw() * XS_zdust() * XS_zdust()\n\ndata_list = DataList(grond)\n\nmodel = Model(PointSource('grb',0,0,spectral_shape=spec))\n\nspec.piv_1 = 1E-2\nspec.index_1.fix=False\nspec.redshift_2 = 0.347\nspec.redshift_2.fix = True\n\nspec.e_bmv_2 = 5./2.93\nspec.e_bmv_2.fix = True\nspec.rv_2 = 2.93\nspec.rv_2.fix = True\n\n\nspec.method_2 = 3\nspec.method_2.fix=True\n\n\n\nspec.e_bmv_3 = .002/3.08\nspec.e_bmv_3.fix = True\nspec.rv_3= 3.08\nspec.rv_3.fix=True\nspec.redshift_3 = 0\nspec.redshift_3.fix=True\nspec.method_3 = 1\nspec.method_3.fix=True\n\njl = JointLikelihood(model,data_list)\n",
"We compute $m_{\\rm AB}$ from astromodels photon fluxes. This is done by convolving the differential flux over the filter response:\n$ F[R,f_\\lambda] \\equiv \\int_0^\\infty \\frac{dg}{d\\lambda}(\\lambda)R(\\lambda) \\omega(\\lambda) d\\lambda$\nwhere we have converted the astromodels functions to wavelength properly.",
"jl.set_minimizer('ROOT')\n_ = jl.fit()\n",
"Examine the fit",
"_=display_photometry_model_magnitudes(jl)\n\nnew_grond = grond.get_simulated_dataset()\n\n_ = plot_point_source_spectra(jl.results,flux_unit='erg/(cm2 s keV)',\n xscale='linear',\n energy_unit='nm',ene_min=1E3, ene_max=1E5 )"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
kimkipyo/dss_git_kkp
|
통계, 머신러닝 복습/160525수_8일차_다변수 분포, 기초 확률론 4 - 상관 관계 Correlation/5.결합, 주변, 조건부 확률 밀도 함수.ipynb
|
mit
|
[
"결합, 주변, 조건부 확률 밀도 함수\n\n결합누적확률분포는 이제 변수가 2개니까 다변수로 붙어서 나온 개념이다.\n\n두 개 이상의 확률 변수가 서로 관계를 가지며 존재하는 경우를 생각해 보자. 예를 들어 학교에 있는 학생의 키와 몸무게를 측정하는 경우 한 명의 학생 $\\omega$에 대해 두 개의 자료 ($x$, $y$)가 한 쌍으로 나오게 된다. 이렇게 취득한 자료를 확률 변수 $X$와 $Y$로 볼 때, 이들의 확률 분포를 한번에 묘사하기 위한 확률 분포를 결합 확률 분포(join probability distribution)라고 한다. \n결합 확률 분포도 단일 연속 확률 변수의 경우와 마찬가지로 누적 확률 분포 함수(cumulative probability function)와 확률 밀도 함수(probability density function)를 통해 서술된다.\n연속 확률 변수의 결합 누적 확률 분포 함수\n두 확률 변수 $X$, $Y$에 대한 누적 확률 분포 함수 $F_{XY}(x, y) $는 다음과 같이 정의한다.\n$$ F_{XY}(x, y) = P({ X < x } \\cap { Y < y }) = P(X < x, Y < y) $$\n만약 구간의 끝을 나타내는 두 독립 변수 $x$, $y$중 하나가 무한대 값을 가지는 경우에는 해당 변수의 값은 어떤 값을 가져도 상관없으므로 남은 하나의 변수에 대한 누적 확률 분포 함수로 줄어든다. 이를 주변 확률 분포(marginal probability distribution)이라고 한다.\n$$ F_X(x)=F_{XY}(x, \\infty) $$\n$$ F_Y(x)=F_{XY}(\\infty, y) $$\n누적 확률 분포 함수 $F_{XY}(x, y) $는 다음과 같은 특성을 가진다.\n$$ F_{XY}(\\infty, \\infty)=1 $$\n$$ F_{XY}(-\\infty, y)=F_{XY}(x,-\\infty)=0 $$\n연속 확률 변수의 결합 확률 밀도 함수\n단일 확률 변수의 경우처럼 누적 결합 확률 분포 함수를 미분하여 결합 확률 밀도 함수를 정의할 수 있다. 다만 이 경우에는 독립 변수가 2개이므로 각각에 대해 모두 편미분(partial differentication)해야 한다.\n$$ f_{XY} = \\dfrac{\\partial^2 F_{XY}(x, y)}{\\partial x \\partial y} $$\n결합 확률 밀도 함수를 특정 구간에 대해 적분하면 해당 구간에 대한 확률이 된다.\n$$ \\int_{x_1}^{x_2} \\int_{y_1}^{y_2} f_{XY}(x,y)dxdy = P\\big({ x_1 \\leq X \\leq x_2, \\; y_1 \\leq Y \\leq y_2 }\\big) $$\n따라서 결합 확률 밀도 함수를 모든 변수에 대해 $-\\infty$에서 $\\infty$ 까지 적분하면 값이 1이 된다.\n$$ \\int_{-\\infty}^{\\infty} \\int_{-\\infty}^{\\infty} f_{XY}(x,y)dxdy=1 $$\n연속 확률 변수의 결합 확률 밀도 함수는 2차원 함수가 된다. 아래는 다변수 정규 분포의 결합 확률 밀도의 예를 그린 것이다.",
"mu = [2, 3]\ncov = [[2, -1],[2, 4]]\nrv = sp.stats.multivariate_normal(mu, cov)\nxx = np.linspace(-1, 5, 150)\nyy = np.linspace(0, 6, 120)\nXX, YY = np.meshgrid(xx, yy)\nZZ = rv.pdf(np.dstack([XX, YY]))\nplt.contour(XX, YY, ZZ)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Joint Probability Density\")\nplt.axis(\"equal\")\nplt.show()",
"동일한 결합 확률 밀도 함수를 3차원으로 그리면 아래와 같다.",
"from mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\nax.contour(XX, YY, ZZ, levels=np.linspace(0, 0.1, 20))\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_title(\"Joint Probability Density\")\nplt.show()",
"이산 확률 변수의 결합 확률 질량 함수\n\n이젠 사건이 아니라 숫자다. x, y가 숫자로 들어간다.\n여기서는 확률로 나타낼 수 있다. 누적의 의미가 없어진다. 그 값 자체가 확률\n\n다변수 이산 확률 변수에 대해서는 결합 확률 질량 함수를 구할 수 있다. 결합 확률 질량 함수는 모든 확률 변수의 값이 특정 숫자가 될 확률을 뜻한다. \n$$ f_{XY}(x,y) = P(X=x,Y=y) $$\n결합 확률 질량 함수는 댜음과 같이 2차원 표의 형태가 된다.",
"pmf = np.array([[0, 0, 0, 0, 1, 1],\n [0, 0, 1, 2, 1, 0],\n [0, 1, 3, 3, 1, 0],\n [0, 1, 2, 1, 0, 0],\n [1, 1, 0, 0, 0, 0]])\npmf = pmf / pmf.sum()\npmf\n\nsns.heatmap(pmf)\nplt.xlabel(\"x\")\nplt.ylabel(\"y\")\nplt.title(\"Joint Probability Mass Function\")\nplt.show()",
"주변 확률 밀도 함수\n주변 확률 밀도 함수(marginal probability density function)는 다변수 확률 변수에서 특정한 하나의 변수에 대한 기대값을 말한다. 따라서 결합 확률 밀도 함수를 특정 변수에 대해서만 적분하여 구한다. \n기댓값 계산(적분)으로 인해 차원이 한 개 줄어들기 때문에 2차원 확률 변수의 주변 확률 밀도 함수는 1차원 함수가 된다.\n$$ \n\\begin{align}%\\label{}\n\\nonumber f_X(x) = \\text{E}{Y}[f{XY}(x,y)] = \\int_{-\\infty}^{\\infty} f_{XY}(x,y)dy \\\n\\nonumber f_Y(y) = \\text{E}{X}[f{XY}(x,y)] = \\int_{-\\infty}^{\\infty} f_{XY}(x,y)dx\n\\end{align} \n$$\n이산 확률 변수의 경우에는 주변 확률 질량 함수(marginal probability mass function) 다음과 같이 정의한다\n$$ \n\\begin{align}%\\label{}\n\\nonumber f_X(x) = \\text{E}{Y}[f{XY}(x,y)] = \\sum_{y_j} f_{XY}(x,y_j) \\\n\\nonumber f_Y(y) = \\text{E}{X}[f{XY}(x,y)] = \\sum_{x_i} f_{XY}(x_i,y) \\\n\\end{align} \n$$\n위에서 예로 든 이산 확률 변수의 경우에 주변 확률 질량 함수를 계산하면 다음과 같다.",
"pmf\n\npmf_marginal_x = pmf.sum(axis=0)\npmf_marginal_x\n\npmf_marginal_y = pmf.sum(axis=1)\npmf_marginal_y[:, np.newaxis]",
"위에서 예로 든 연속 확률 변수의 경우에 주변 확률 밀도 함수를 계산하면 다음과 같다.",
"fig = plt.figure()\nax = fig.gca(projection='3d')\nax.contour(XX, YY, 0.4*ZZ, levels=np.linspace(0, 0.04, 30), alpha=0.3)\nax.plot(yy, ZZ.mean(axis=1), zdir='x', lw=3)\nax.plot(xx, ZZ.mean(axis=0), zdir='y', lw=3)\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_title(\"Marginal Probability Density\")\nax.view_init(55, -40)\nplt.show()",
"다변수 가우시안 정규분포의 첫 번째 꼭지점이 높은 이유는? 맨처음 올라가는 것의 미분 기울기가 급격하게 올라가기 때문\n아까 달팽이그림에서는 미분만 나타난 것이다. 그걸 적분한 것만이 값을 가질 수 있다. 0부터 1사이의 값\n조인트와 마지날은 상대적인 개념이다. 즉, 관계적인 개념.\n독립은 pdf의 모양과만 관계가 있다.\n\n조건부 확률 밀도 함수\n\n오로지 y값 말고 x값에만 관심 있으면 y를 다 없애면 된다.\n조건부도 마찬가지로 차원이 줄어든다. 2차원이 1차원으로\n조건부는 특정한 값을 하나 찝어. 값이 하나 박히다. 단면만 보는 것. 마지날은 눌러 찍은 것이고.\n그런데 여기서 마지날은 다 똑같아진다. 어디서든 곡선들의 합이 다 같아지기 때문이다.\n정규화 하기 이전의 컨디셔널\n\n조건부 확률 밀도 함수(conditional probability density function)는 다변수 확률 변수 중 하나의 값이 특정 값으로 고정되어 상수가 되어 버린 경우이다. \n$$ f_{X \\mid Y}(x \\mid y_0) = \\dfrac{f_{XY}(x, y=y_0)}{f_{Y}(y_0)} $$\n$$ f_{Y \\mid X}(y \\mid x_0) = \\dfrac{f_{XY}(x, y=y_0)}{f_{X}(x_0)} $$\n주변 확률 밀도 함수와 마찬가지로 차원이 감소하지만 기댓값(적분) 연산으로 변수가 없어진 주변 확률 밀도 함수와는 다른 값이다.\n위에서 예로 든 연속 확률 변수의 조건부 확률 밀도 함수를 그림으로 나타내면 다음과 같다. (이 그림은 사실 normailization이 되지 않았다.)",
"fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(8, 12), subplot_kw={'projection': '3d'})\nax1.plot_wireframe(XX, YY, ZZ, rstride=30, cstride=0, lw=3)\nax1.set_xlabel(\"x\")\nax1.set_ylabel(\"y\")\nax1.set_title(\"Conditional Probability Density $f(x \\mid y)$\")\nax2.plot_wireframe(XX, YY, ZZ, rstride=0, cstride=30, lw=3)\nax2.set_xlabel(\"x\")\nax2.set_ylabel(\"y\")\nax2.set_title(\"Conditional Probability Density $f(y \\mid x)$\")\nplt.tight_layout()\nplt.show()",
"위에서 예로 든 이산 확률 변수의 경우에 조건부 확률 질량 함수를 계산하면 다음과 같다.",
"pmf\n\nconf_y0 = pmf[0, :] / pmf_marginal_y[0]\nconf_y0\n\ncond_y1 = pmf[1, :] / pmf_marginal_y[1]\ncond_y1"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
justacec/bokeh
|
examples/howto/charts/deep_dive-composite_glyphs.ipynb
|
bsd-3-clause
|
[
"from bokeh.charts import output_notebook, show\nfrom bokeh.charts.glyphs import BarGlyph\n\noutput_notebook()",
"Composite Glyph\nOne or more actual glyphs that have been grouped together to represent some set of data, which respond to some standardized set of graphics operations.\nIn a chart, a composite glyph is generated for each group of data. For example, a box glyph will produce one box for a box plot. This is composed of multiple glyphs, but represents a single group of data.\nThis guide walks through the creation and use of composite glyphs.\nBarGlyph\nA simple bar has two components. It has some location along an axis, then it has some height from that axis. A bar can be created from a single value, or it can be created through aggregation. For example:\nBar from single value",
"bar = BarGlyph(label='a', values=[1])\nbar.data",
"Bar from multiple values\nNotice the difference in height.",
"bar = BarGlyph(label='a', values=[1, 2, 3, 4])\nbar.data",
"Simplified input using same order",
"bar = BarGlyph('a', 1)\nbar.data",
"Operations on Composite Glyphs\nGrammar of Graphics describes some common graphical operations that each glyph type would respond differently to. A common operation for bars would be stacking\nUn-Stacked",
"bar1 = BarGlyph('foo', 1)\nbar2 = BarGlyph('foo', 2)\n\nprint('No stacking')\nprint('bar1 y: %s, bar2 y: %s' % (bar1.data['y'], bar2.data['y']) )",
"Stacked",
"from bokeh.charts.operations import stack\n\nbar1, bar2 = stack(bar1, bar2)\n\nprint('With Stacking')\nprint('bar1 y: %s, bar2 y: %s' % (bar1.data['y'], bar2.data['y']) )",
"Producing Combined Data Source",
"from bokeh.charts.utils import comp_glyphs_to_df\n\n# utility that uses pandas.concat to concatenate each CompositeGlyph.df\ncomp_glyphs_to_df(bar1, bar2)",
"Standalone Use of Composite Glyphs\nSetup",
"from bokeh.charts.chart import Chart\nfrom bokeh.models.ranges import DataRange1d, FactorRange\nfrom bokeh.io import curdoc, curstate\n\ndef add_chart_to_doc(chart):\n \"Handle adding chart to doc.\"\n curdoc()._current_plot = chart\n if curstate().autoadd:\n curdoc().add_root(chart)",
"Build Bars and Add Them Manually to Chart\nIn the chart below, the bars corresponding to foo overlap.",
"\n# two bars overlap on the same label/index\nbar1 = BarGlyph(label='foo', values=[1])\nbar2 = BarGlyph('foo', 2)\n\n# only the third bar doesn't overlap\nbar3 = BarGlyph('bar', 3)\n\n# composite glyphs can have multiple renderers, so we get them all\nrenderers = []\nfor bar in [bar1, bar2, bar3]:\n renderers += bar.renderers\n\n# create a chart and directly add the renderers\nc = Chart(renderers=renderers)\n\n# add ranges/scales (typically handled by builder)\nc.add_ranges('x', FactorRange(factors=['foo', 'bar']))\nc.add_ranges('y', DataRange1d(start=0, end=4))\n\nc.add_scales('x', 'auto')\nc.add_scales('y', 'auto')\n\n# build the chart (typically called by create_and_build)\nc.start_plot()\n\n# add chart to doc (typically handled by create_and_build)\nadd_chart_to_doc(c)\n\nshow(c)",
"Stack the Bars, then Show Chart\nOne potential way to handle overlapping bars is to stack them. See below that stacking the bars results in a stacked bar chart.",
"stack(bar1, bar2, bar3)\n\nshow(c)"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
Almaz-KG/MachineLearning
|
ml-for-finance/python-for-financial-analysis-and-algorithmic-trading/02-NumPy/1-NumPy-Arrays.ipynb
|
apache-2.0
|
[
"<a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a>\n\n<center>Copyright Pierian Data 2017</center>\n<center>For more information, visit us at www.pieriandata.com</center>\nNumPy\nNumPy (or Numpy) is a Linear Algebra Library for Python, the reason it is so important for Finance with Python is that almost all of the libraries in the PyData Ecosystem rely on NumPy as one of their main building blocks. Plus we will use it to generate data for our analysis examples later on!\nNumpy is also incredibly fast, as it has bindings to C libraries. For more info on why you would want to use Arrays instead of lists, check out this great StackOverflow post.\nWe will only learn the basics of NumPy, to get started we need to install it!\nInstallation Instructions\nNumPy is already included in your environment! You are good to go if you are using pyfinance env!\n\nFor those not using the provided environment:\nIt is highly recommended you install Python using the Anaconda distribution to make sure all underlying dependencies (such as Linear Algebra libraries) all sync up with the use of a conda install. If you have Anaconda, install NumPy by going to your terminal or command prompt and typing:\nconda install numpy\n\nIf you do not have Anaconda and can not install it, please refer to Numpy's official documentation on various installation instructions.\n\nUsing NumPy\nOnce you've installed NumPy you can import it as a library:",
"import numpy as np",
"Numpy has many built-in functions and capabilities. We won't cover them all but instead we will focus on some of the most important aspects of Numpy: vectors,arrays,matrices, and number generation. Let's start by discussing arrays.\nNumpy Arrays\nNumPy arrays are the main way we will use Numpy throughout the course. Numpy arrays essentially come in two flavors: vectors and matrices. Vectors are strictly 1-d arrays and matrices are 2-d (but you should note a matrix can still have only one row or one column).\nLet's begin our introduction by exploring how to create NumPy arrays.\nCreating NumPy Arrays\nFrom a Python List\nWe can create an array by directly converting a list or list of lists:",
"my_list = [1,2,3]\nmy_list\n\nnp.array(my_list)\n\nmy_matrix = [[1,2,3],[4,5,6],[7,8,9]]\nmy_matrix\n\nnp.array(my_matrix)",
"Built-in Methods\nThere are lots of built-in ways to generate Arrays\narange\nReturn evenly spaced values within a given interval.",
"np.arange(0,10)\n\nnp.arange(0,11,2)",
"zeros and ones\nGenerate arrays of zeros or ones",
"np.zeros(3)\n\nnp.zeros((5,5,5))\n\nnp.ones(3)\n\nnp.ones((3,3))",
"linspace\nReturn evenly spaced numbers over a specified interval.",
"np.linspace(0,10,10)\n\nnp.linspace(0,10,50)",
"eye\nCreates an identity matrix",
"np.eye(8)",
"Random\nNumpy also has lots of ways to create random number arrays:\nrand\nCreate an array of the given shape and populate it with\nrandom samples from a uniform distribution\nover [0, 1).",
"np.random.rand(2)\n\nnp.random.rand(5,5)",
"randn\nReturn a sample (or samples) from the \"standard normal\" distribution. Unlike rand which is uniform:",
"np.random.randn(2)\n\nnp.random.randn(5,5)",
"randint\nReturn random integers from low (inclusive) to high (exclusive).",
"np.random.randint(1,100)\n\nnp.random.randint(1,100,3)",
"Array Attributes and Methods\nLet's discuss some useful attributes and methods or an array:",
"arr = np.arange(30)\nranarr = np.random.randint(0,50,10)\n\narr\n\nranarr",
"Reshape\nReturns an array containing the same data with a new shape.",
"arr.reshape(3,10)",
"max,min,argmax,argmin\nThese are useful methods for finding max or min values. Or to find their index locations using argmin or argmax",
"ranarr\n\nranarr.max()\n\nranarr.argmax()\n\nranarr.min()\n\nranarr.argmin()",
"Shape\nShape is an attribute that arrays have (not a method):",
"# Vector\narr.shape\n\n# Notice the two sets of brackets\narr.reshape(1,30)\n\narr.reshape(1,30).shape\n\narr.reshape(30,1)\n\narr.reshape(30,1).shape",
"dtype\nYou can also grab the data type of the object in the array:",
"arr.dtype",
"Great Job!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
AllenDowney/ModSim
|
soln/chap23.ipynb
|
gpl-2.0
|
[
"Chapter 23\nModeling and Simulation in Python\nCopyright 2021 Allen Downey\nLicense: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",
"# install Pint if necessary\n\ntry:\n import pint\nexcept ImportError:\n !pip install pint\n\n# download modsim.py if necessary\n\nfrom os.path import exists\n\nfilename = 'modsim.py'\nif not exists(filename):\n from urllib.request import urlretrieve\n url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/main/'\n local, _ = urlretrieve(url+filename, filename)\n print('Downloaded ' + local)\n\n# import functions from modsim\n\nfrom modsim import *",
"Code from the previous chapter",
"from modsim import Params\n\nparams = Params(\n x = 0, # m\n y = 1, # m\n angle = 45, # degree\n velocity = 40, # m / s\n\n mass = 145e-3, # kg \n diameter = 73e-3, # m \n C_d = 0.33, # dimensionless\n\n rho = 1.2, # kg/m**3\n g = 9.8, # m/s**2\n)\n\nfrom modsim import State, System, pol2cart\nfrom numpy import pi, deg2rad\n\ndef make_system(params):\n \n # convert angle to degrees\n theta = deg2rad(params.angle)\n \n # compute x and y components of velocity\n vx, vy = pol2cart(theta, params.velocity)\n \n # make the initial state\n init = State(x=params.x, y=params.y, vx=vx, vy=vy)\n \n # compute the frontal area\n area = pi * (params.diameter/2)**2\n\n return System(init = init,\n mass = params.mass,\n area = area,\n C_d = params.C_d,\n rho = params.rho,\n g = params.g,\n t_end=10)\n\nfrom modsim import vector_mag, vector_hat\n\ndef drag_force(V, system):\n rho, C_d, area = system.rho, system.C_d, system.area\n \n mag = rho * vector_mag(V)**2 * C_d * area / 2\n direction = -vector_hat(V)\n f_drag = mag * direction\n return f_drag\n\nfrom modsim import Vector\n\ndef slope_func(t, state, system):\n x, y, vx, vy = state\n mass, g = system.mass, system.g\n \n V = Vector(vx, vy)\n a_drag = drag_force(V, system) / mass\n a_grav = Vector(0, -g)\n \n A = a_grav + a_drag\n \n return V.x, V.y, A.x, A.y\n\ndef event_func(t, state, system):\n x, y, vx, vy = state\n return y",
"In the previous chapter we developed a model of the flight of a\nbaseball, including gravity and a simple version of drag, but neglecting spin, Magnus force, and the dependence of the coefficient of drag on velocity.\nIn this chapter we apply that model to an optimization problem.\nThe Manny Ramirez problem\nManny Ramirez is a former member of the Boston Red Sox (an American\nbaseball team) who was notorious for his relaxed attitude and taste for practical jokes. Our objective in this chapter is to solve the following Manny-inspired problem:\n\nWhat is the minimum effort required to hit a home run in Fenway Park?\n\nFenway Park is a baseball stadium in Boston, Massachusetts. One of its\nmost famous features is the \"Green Monster\", which is a wall in left\nfield that is unusually close to home plate, only 310 feet away. To\ncompensate for the short distance, the wall is unusually high, at 37\nfeet (see http://modsimpy.com/wally).\nWe want to find the minimum velocity at which a ball can leave home\nplate and still go over the Green Monster. We'll proceed in the\nfollowing steps:\n\n\nFor a given velocity, we'll find the optimal launch angle, that is, the angle the ball should leave home plate to maximize its height when it reaches the wall.\n\n\nThen we'll find the minimal velocity that clears the wall, given\n that it has the optimal launch angle.\n\n\nFinding the range\nSuppose we want to find the launch angle that maximizes range, that is, the distance the ball travels in the air before landing. We'll use a function in the ModSim library, maximize, which takes a function and finds its maximum.\nThe function we pass to maximize should take launch angle in degrees, simulate the flight of a ball launched at that angle, and return the distance the ball travels along the $x$ axis.",
"from modsim import run_solve_ivp\n\ndef range_func(angle, params):\n params = params.set(angle=angle)\n system = make_system(params)\n results, details = run_solve_ivp(system, slope_func,\n events=event_func)\n x_dist = results.iloc[-1].x\n print(angle, x_dist)\n return x_dist",
"range_func makes a new System object with the given value of\nangle. Then it calls run_solve_ivp and\nreturns the final value of x from the results.\nWe can call range_func directly like this:",
"range_func(45, params)",
"And we can sweep a sequence of angles like this:",
"from modsim import linspace, SweepSeries\n\nangles = linspace(20, 80, 21)\nsweep = SweepSeries()\n\nfor angle in angles:\n x_dist = range_func(angle, params)\n sweep[angle] = x_dist",
"Here's what the results look like.",
"from modsim import decorate\n\nsweep.plot()\n\ndecorate(xlabel='Launch angle (degree)',\n ylabel='Range (meter)')",
"It looks like the optimal angle is near 40°.\nWe can find the optimal angle more precisely and more efficiently using maximize_scalar, like this:",
"from modsim import maximize_scalar\n\nres = maximize_scalar(range_func, [0, 90], params)\nres.message",
"The first parameter is the function we want to maximize. The second is\nthe range of values we want to search; in this case, it's the range of\nangles from 0° to 90°. \nThe return value from maximize is an object that contains the\nresults, including x, which is the angle that yielded the highest\nrange, and fun, which is the value of range_func when it's evaluated at x, that is, range when the baseball is launched at the optimal angle.",
"res.x, res.fun",
"For these parameters, the optimal angle is about 41°, which yields a\nrange of 100 m.\nSummary\nIf you enjoy this exercise, you might be interested in this paper: \"How to hit home runs: Optimum baseball bat swing parameters for maximum range trajectories\", by Sawicki, Hubbard, and Stronge, at\nhttp://modsimpy.com/runs.\nExercise\nExercise: Let's finish off the Manny Ramirez problem:\n\nWhat is the minimum effort required to hit a home run in Fenway Park?\n\nAlthough the problem asks for a minimum, it is not an optimization problem. Rather, we want to solve for the initial velocity that just barely gets the ball to the top of the wall, given that it is launched at the optimal angle.\nAnd we have to be careful about what we mean by \"optimal\". For this problem, we don't want the longest range, we want the maximum height at the point where it reaches the wall.\nIf you are ready to solve the problem on your own, go ahead. Otherwise I will walk you through the process with an outline and some starter code.\nAs a first step, write an event_func that stops the simulation when the ball reaches the wall at 310 feet (94.5 m).\nTest your function with the initial conditions.",
"# Solution\n\ndef event_func(t, state, system):\n x, y, vx, vy = state\n return x - 94.5\n\n# Solution\n\nsystem = make_system(params)\nevent_func(0, system.init, system)",
"Next, write a function called height_func that takes a launch angle, simulates the flight of a baseball, and returns the height of the baseball when it reaches the wall.\nTest your function with the initial conditions.",
"# Solution\n\ndef height_func(angle, params):\n params = params.set(angle=angle)\n system = make_system(params)\n\n results, details = run_solve_ivp(system, slope_func, \n events=event_func)\n height = results.iloc[-1].y\n return height\n\n# Solution\n\nheight_func(40, params)",
"Now use maximize_scalar to find the optimal angle. Is it higher or lower than the angle that maximizes range?",
"# Solution\n\nbounds = [0, 90]\nres = maximize_scalar(height_func, bounds, params)\nres.message\n\n# Solution\n\nres.x, res.fun",
"Even though we are finding the \"minimum\" velocity, we are not really solving a minimization problem. Rather, we want to find the velocity that makes the height at the wall exactly 37 feet (11.3 m), given that it's launched at the optimal angle. And that's a job for root_scalar.\nWrite an error function that takes a velocity and a System object as parameters. It should use maximize_scalar to find the highest possible height of the ball at the wall, for the given velocity. Then it should return the difference between that optimal height and 11.3 meters.",
"# Solution\n\ndef error_func(velocity, params):\n print(velocity)\n params = params.set(velocity=velocity)\n bounds = [0, 90]\n res = maximize_scalar(height_func, bounds, params)\n return res.fun - 11.3",
"Test your error function before you call root_scalar.",
"# Solution\n\nerror_func(40, params)",
"Then use root_scalar to find the answer to the problem, the minimum velocity that gets the ball out of the park.",
"# Solution\n\nfrom scipy.optimize import root_scalar\n\nbracket = [30, 50]\nres = root_scalar(error_func, params, bracket=bracket)\n\n# Solution\n\nres\n\n# Solution\n\nmin_velocity = res.root\nmin_velocity",
"And just to check, run error_func with the value you found.",
"# Solution\n\nerror_func(min_velocity, params)",
"Under the Hood\nmaximize_scalar uses a golden section search, which you can read about at http://modsimpy.com/minimize)."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
Kaggle/learntools
|
notebooks/game_ai/raw/tut4.ipynb
|
apache-2.0
|
[
"Introduction\nSo far, our agents have relied on detailed information about how to play the game. The heuristic really provides a lot of guidance about how to select moves!\nIn this tutorial, you'll learn how to use reinforcement learning to build an intelligent agent without the use of a heuristic. Instead, we will gradually refine the agent's strategy over time, simply by playing the game and trying to maximize the winning rate.\nIn this notebook, we won't be able to explore this complex field in detail, but you'll learn about the big picture and explore code that you can use to train your own agent.\nNeural Networks\nIt's difficult to come up with a perfect heuristic. Improving the heuristic generally entails playing the game many times, to determine specific cases where the agent could have made better choices. And, it can prove challenging to interpret what exactly is going wrong, and ultimately to fix old mistakes without accidentally introducing new ones.\nWouldn't it be much easier if we had a more systematic way of improving the agent with gameplay experience? \nIn this tutorial, towards this goal, we'll replace the heuristic with a neural network.\nThe network accepts the current board as input. And, it outputs a probability for each possible move.\n<center>\n<img src=\"https://i.imgur.com/KgAliYQ.png\" width=90%><br/>\n</center>\nThen, the agent selects a move by sampling from these probabilities. For instance, for the game board in the image above, the agent selects column 4 with 50% probability.\nThis way, to encode a good gameplay strategy, we need only amend the weights of the network so that for every possible game board, it assigns higher probabilities to better moves.\nAt least in theory, that's our goal. In practice, we won't actually check if that's the case -- since remember that Connect Four has over 4 trillion possible game boards!\nSetup\nHow can we approach the task of amending the weights of the network, in practice? Here's the approach we'll take in this lesson:\n- After each move, we give the agent a reward that tells it how well it did:\n - If the agent wins the game in that move, we give it a reward of +1.\n - Else if the agent plays an invalid move (which ends the game), we give it a reward of -10.\n - Else if the opponent wins the game in its next move (i.e., the agent failed to prevent its opponent from winning), we give the agent a reward of -1.\n - Else, the agent gets a reward of 1/42.\n\nAt the end of each game, the agent adds up its reward. We refer to the sum of rewards as the agent's cumulative reward. \nFor instance, if the game lasted 8 moves (each player played four times), and the agent ultimately won, then its cumulative reward is 3*(1/42) + 1.\nIf the game lasted 11 moves (and the opponent went first, so the agent played five times), and the opponent won in its final move, then the agent's cumulative reward is 4*(1/42) - 1.\nIf the game ends in a draw, then the agent played exactly 21 moves, and it gets a cumulative reward of 21*(1/42).\nIf the game lasted 7 moves and ended with the agent selecting an invalid move, the agent gets a cumulative reward of 3*(1/42) - 10.\n\nOur goal is to find the weights of the neural network that (on average) maximize the agent's cumulative reward. \nThis idea of using reward to track the performance of an agent is a core idea in the field of reinforcement learning. Once we define the problem in this way, we can use any of a variety of reinforcement learning algorithms to produce an agent.\nReinforcement Learning\nThere are many different reinforcement learning algorithms, such as DQN, A2C, and PPO, among others. All of these algorithms use a similar process to produce an agent:\n\n\nInitially, the weights are set to random values.\n\n\nAs the agent plays the game, the algorithm continually tries out new values for the weights, to see how the cumulative reward is affected, on average. Over time, after playing many games, we get a good idea of how the weights affect cumulative reward, and the algorithm settles towards weights that performed better. \n\nOf course, we have glossed over the details here, and there's a lot of complexity involved in this process. For now, we focus on the big picture!\n\n\n\nThis way, we'll end up with an agent that tries to win the game (so it gets the final reward of +1, and avoids the -1 and -10) and tries to make the game last as long as possible (so that it collects the 1/42 bonus as many times as it can).\n\nYou might argue that it doesn't really make sense to want the game to last as long as possible -- this might result in a very inefficient agent that doesn't play obvious winning moves early in gameplay. And, your intuition would be correct -- this will make the agent take longer to play a winning move! The reason we include the 1/42 bonus is to help the algorithms we'll use to converge better. Further discussion is outside of the scope of this course, but you can learn more by reading about the \"temporal credit assignment problem\" and \"reward shaping\".\n\n\n\nIn the next section, we'll use the Proximal Policy Optimization (PPO) algorithm to create an agent.\nCode\nThere are a lot of great implementations of reinforcement learning algorithms online. In this course, we'll use Stable Baselines.\nCurrently, Stable Baselines is not yet compatible with TensorFlow 2.0. So, we begin by downgrading to TensorFlow 1.0.",
"#$HIDE$\nimport random\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\n#$HIDE$\n!pip install 'tensorflow==1.15.0'\n!pip install 'gym==0.21.0'\n\n# Check version of tensorflow\nimport tensorflow as tf\ntf.__version__",
"There's a bit of extra work that we need to do to make the environment compatible with Stable Baselines. For this, we define the ConnectFourGym class below. This class implements ConnectX as an OpenAI Gym environment and uses several methods:\n- reset() will be called at the beginning of every game. It returns the starting game board as a 2D numpy array with 6 rows and 7 columns.\n- change_reward() customizes the rewards that the agent receives. (The competition already has its own system for rewards that are used to rank the agents, and this method changes the values to match the rewards system we designed.) \n- step() is used to play the agent's choice of action (supplied as action), along with the opponent's response. It returns:\n - the resulting game board (as a numpy array), \n - the agent's reward (from the most recent move only: one of +1, -10, -1, or 1/42), and\n - whether or not the game has ended (if the game has ended, done=True; otherwise, done=False).\nTo learn more about how to define environments, check out the documentation here.",
"from kaggle_environments import make, evaluate\nfrom gym import spaces\n\nclass ConnectFourGym:\n def __init__(self, agent2=\"random\"):\n ks_env = make(\"connectx\", debug=True)\n self.env = ks_env.train([None, agent2])\n self.rows = ks_env.configuration.rows\n self.columns = ks_env.configuration.columns\n # Learn about spaces here: http://gym.openai.com/docs/#spaces\n self.action_space = spaces.Discrete(self.columns)\n self.observation_space = spaces.Box(low=0, high=2, \n shape=(self.rows,self.columns,1), dtype=int)\n # Tuple corresponding to the min and max possible rewards\n self.reward_range = (-10, 1)\n # StableBaselines throws error if these are not defined\n self.spec = None\n self.metadata = None\n def reset(self):\n self.obs = self.env.reset()\n return np.array(self.obs['board']).reshape(self.rows,self.columns,1)\n def change_reward(self, old_reward, done):\n if old_reward == 1: # The agent won the game\n return 1\n elif done: # The opponent won the game\n return -1\n else: # Reward 1/42\n return 1/(self.rows*self.columns)\n def step(self, action):\n # Check if agent's move is valid\n is_valid = (self.obs['board'][int(action)] == 0)\n if is_valid: # Play the move\n self.obs, old_reward, done, _ = self.env.step(int(action))\n reward = self.change_reward(old_reward, done)\n else: # End the game and penalize agent\n reward, done, _ = -10, True, {}\n return np.array(self.obs['board']).reshape(self.rows,self.columns,1), reward, done, _",
"In this notebook, we'll train an agent to beat the random agent. We specify this opponent in the agent2 argument below.",
"# Create ConnectFour environment\nenv = ConnectFourGym(agent2=\"random\")",
"Stable Baselines requires us to work with \"vectorized\" environments. For this, we can use the DummyVecEnv class. \nThe Monitor class lets us watch how the agent's performance gradually improves, as it plays more and more games.",
"#$HIDE$\n!apt-get update\n!apt-get install -y cmake libopenmpi-dev python3-dev zlib1g-dev\n!pip install \"stable-baselines[mpi]==2.10.2\"\n\nimport os\nfrom stable_baselines.bench import Monitor \nfrom stable_baselines.common.vec_env import DummyVecEnv\n\n# Create directory for logging training information\nlog_dir = \"ppo/\"\nos.makedirs(log_dir, exist_ok=True)\n\n# Logging progress\nmonitor_env = Monitor(env, log_dir, allow_early_resets=True)\n\n# Create a vectorized environment\nvec_env = DummyVecEnv([lambda: monitor_env])",
"The next step is to specify the architecture of the neural network. In this case, we use a convolutional neural network. To learn more about how to specify architectures with Stable Baselines, check out the documentation here.\nNote that this is the neural network that outputs the probabilities of selecting each column. Since we use the PPO algorithm (PPO1 in the code cell below), our network will also output some additional information (called the \"value\" of the input). This is outside the scope of this course, but you can learn more by reading about \"actor-critic networks\".",
"from stable_baselines import PPO1 \nfrom stable_baselines.common.tf_layers import conv, linear, conv_to_fc\nfrom stable_baselines.common.policies import CnnPolicy\n\n# Neural network for predicting action values\ndef modified_cnn(scaled_images, **kwargs):\n activ = tf.nn.relu\n layer_1 = activ(conv(scaled_images, 'c1', n_filters=32, filter_size=3, stride=1, \n init_scale=np.sqrt(2), **kwargs))\n layer_2 = activ(conv(layer_1, 'c2', n_filters=64, filter_size=3, stride=1, \n init_scale=np.sqrt(2), **kwargs))\n layer_2 = conv_to_fc(layer_2)\n return activ(linear(layer_2, 'fc1', n_hidden=512, init_scale=np.sqrt(2))) \n\nclass CustomCnnPolicy(CnnPolicy):\n def __init__(self, *args, **kwargs):\n super(CustomCnnPolicy, self).__init__(*args, **kwargs, cnn_extractor=modified_cnn)\n \n# Initialize agent\nmodel = PPO1(CustomCnnPolicy, vec_env, verbose=0)",
"In the code cell above, the weights of the neural network are initially set to random values.\nIn the next code cell, we \"train the agent\", which is just another way of saying that we find weights of the neural network that are likely to result in the agent selecting good moves.\nWe plot a rolling average of the cumulative reward that the agent received during training. As evidenced by the increasing function, the agent gradually learned to perform better by playing the game.",
"# Train agent\nmodel.learn(total_timesteps=60000)\n\n# Plot cumulative reward\nwith open(os.path.join(log_dir, \"monitor.csv\"), 'rt') as fh: \n firstline = fh.readline()\n assert firstline[0] == '#'\n df = pd.read_csv(fh, index_col=None)['r']\ndf.rolling(window=1000).mean().plot()\nplt.show()",
"Finally, we specify the trained agent in the format required for the competition.",
"def agent1(obs, config):\n # Use the best model to select a column\n col, _ = model.predict(np.array(obs['board']).reshape(6,7,1))\n # Check if selected column is valid\n is_valid = (obs['board'][int(col)] == 0)\n # If not valid, select random move. \n if is_valid:\n return int(col)\n else:\n return random.choice([col for col in range(config.columns) if obs.board[int(col)] == 0])",
"In the next code cell, we see the outcome of one game round against a random agent.",
"# Create the game environment\nenv = make(\"connectx\")\n\n# Two random agents play one game round\nenv.run([agent1, \"random\"])\n\n# Show the game\nenv.render(mode=\"ipython\")",
"And, we calculate how it performs on average, against the random agent.",
"#$HIDE_INPUT$\ndef get_win_percentages(agent1, agent2, n_rounds=100):\n # Use default Connect Four setup\n config = {'rows': 6, 'columns': 7, 'inarow': 4}\n # Agent 1 goes first (roughly) half the time \n outcomes = evaluate(\"connectx\", [agent1, agent2], config, [], n_rounds//2)\n # Agent 2 goes first (roughly) half the time \n outcomes += [[b,a] for [a,b] in evaluate(\"connectx\", [agent2, agent1], config, [], n_rounds-n_rounds//2)]\n print(\"Agent 1 Win Percentage:\", np.round(outcomes.count([1,-1])/len(outcomes), 2))\n print(\"Agent 2 Win Percentage:\", np.round(outcomes.count([-1,1])/len(outcomes), 2))\n print(\"Number of Invalid Plays by Agent 1:\", outcomes.count([None, 0]))\n print(\"Number of Invalid Plays by Agent 2:\", outcomes.count([0, None]))\n\nget_win_percentages(agent1=agent1, agent2=\"random\")",
"It's important to note that the agent that we've created here was only trained to beat the random agent, because all of its gameplay experience has been with the random agent as opponent. \nIf we want to produce an agent that reliably performs better than many other agents, we have to expose our agent to these other agents during training. To learn more about how to do this, you can read about self-play.\nLearn more\nThis was a very quick and high-level introduction to reinforcement learning. If you'd like to dig more deeply into this topic, we recommend checking out the following (free!) resources:\n- David Silver's videos - here\n- Richard Sutton's and Andrew Barto's textbook - here\n- Denny Britz's GitHub repository - here\n- The Deep RL Bootcamp - here\nYour turn\nContinue to check your understanding and run the code yourself!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
gcgruen/homework
|
data-databases-homework/Homework_3_Gruen_graded.ipynb
|
mit
|
[
"graded = 9/9\nHomework assignment #3\nThese problem sets focus on using the Beautiful Soup library to scrape web pages.\nProblem Set #1: Basic scraping\nI've made a web page for you to scrape. It's available here. The page concerns the catalog of a famous widget company. You'll be answering several questions about this web page. In the cell below, I've written some code so that you end up with a variable called html_str that contains the HTML source code of the page, and a variable document that stores a Beautiful Soup object.",
"from bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nhtml_str = urlopen(\"http://static.decontextualize.com/widgets2016.html\").read()\ndocument = BeautifulSoup(html_str, \"html.parser\")",
"Now, in the cell below, use Beautiful Soup to write an expression that evaluates to the number of <h3> tags contained in widgets2016.html.",
"h3_tags = document.find_all('h3')\n\nh3_tags_count = 0\nfor tag in h3_tags:\n h3_tags_count = h3_tags_count + 1\nprint(h3_tags_count)",
"Now, in the cell below, write an expression or series of statements that displays the telephone number beneath the \"Widget Catalog\" header.",
"#inspecting webpace with help of developer tools -- shows infomation is stored in an a tag that has the class 'tel'\na_tags = document.find_all('a', {'class':'tel'})\n\nfor tag in a_tags:\n print(tag.string)\n\n#Does not return the same: [tag.string for tag in a_tags]",
"In the cell below, use Beautiful Soup to write some code that prints the names of all the widgets on the page. After your code has executed, widget_names should evaluate to a list that looks like this (though not necessarily in this order):\nSkinner Widget\nWidget For Furtiveness\nWidget For Strawman\nJittery Widget\nSilver Widget\nDivided Widget\nManicurist Widget\nInfinite Widget\nYellow-Tipped Widget\nUnshakable Widget\nSelf-Knowledge Widget\nWidget For Cinema",
"search_table = document.find_all('table',{'class': 'widgetlist'})\n#print(search_table)\n\ntables_content = [table('td', {'class':'wname'}) for table in search_table]\n#print(tables_content)\n\nfor table in tables_content:\n for single_table in table:\n print(single_table.string)",
"Problem set #2: Widget dictionaries\nFor this problem set, we'll continue to use the HTML page from the previous problem set. In the cell below, I've made an empty list and assigned it to a variable called widgets. Write code that populates this list with dictionaries, one dictionary per widget in the source file. The keys of each dictionary should be partno, wname, price, and quantity, and the value for each of the keys should be the value for the corresponding column for each row. After executing the cell, your list should look something like this:\n[{'partno': 'C1-9476',\n 'price': '$2.70',\n 'quantity': u'512',\n 'wname': 'Skinner Widget'},\n {'partno': 'JDJ-32/V',\n 'price': '$9.36',\n 'quantity': '967',\n 'wname': u'Widget For Furtiveness'},\n ...several items omitted...\n {'partno': '5B-941/F',\n 'price': '$13.26',\n 'quantity': '919',\n 'wname': 'Widget For Cinema'}]\nAnd this expression:\nwidgets[5]['partno']\n\n... should evaluate to:\nLH-74/O",
"widgets = []\n\n#STEP 1: Find all tr tags, because that's what tds are grouped by\nfor tr_tags in document.find_all('tr', {'class': 'winfo'}):\n#STEP 2: For each tr_tag in tr_tags, make a dict of its td\n tr_dict ={}\n for td_tags in tr_tags.find_all('td'):\n td_tags_class = td_tags['class']\n for tag in td_tags_class:\n tr_dict[tag] = td_tags.string\n#STEP3: add dicts to list\n widgets.append(tr_dict)\nwidgets\n#widgets[5]['partno']",
"In the cell below, duplicate your code from the previous question. Modify the code to ensure that the values for price and quantity in each dictionary are floating-point numbers and integers, respectively. I.e., after executing the cell, your code should display something like this:\n[{'partno': 'C1-9476',\n 'price': 2.7,\n 'quantity': 512,\n 'widgetname': 'Skinner Widget'},\n {'partno': 'JDJ-32/V',\n 'price': 9.36,\n 'quantity': 967,\n 'widgetname': 'Widget For Furtiveness'},\n ... some items omitted ...\n {'partno': '5B-941/F',\n 'price': 13.26,\n 'quantity': 919,\n 'widgetname': 'Widget For Cinema'}]\n\n(Hint: Use the float() and int() functions. You may need to use string slices to convert the price field to a floating-point number.)",
"#had to rename variables as it kept printing the ones from the cell above...\nwidgetsN = []\nfor trN_tags in document.find_all('tr', {'class': 'winfo'}):\n trN_dict ={}\n for tdN_tags in trN_tags.find_all('td'):\n tdN_tags_class = tdN_tags['class']\n for tagN in tdN_tags_class:\n if tagN == 'price':\n sliced_tag_string = tdN_tags.string[1:]\n trN_dict[tagN] = float(sliced_tag_string)\n elif tagN == 'quantity':\n trN_dict[tagN] = int(tdN_tags.string)\n else:\n trN_dict[tagN] = tdN_tags.string\n widgetsN.append(trN_dict)\nwidgetsN",
"Great! I hope you're having fun. In the cell below, write an expression or series of statements that uses the widgets list created in the cell above to calculate the total number of widgets that the factory has in its warehouse.\nExpected output: 7928",
"widget_quantity_list = [element['quantity'] for element in widgetsN]\nsum(widget_quantity_list)",
"In the cell below, write some Python code that prints the names of widgets whose price is above $9.30.\nExpected output:\nWidget For Furtiveness\nJittery Widget\nSilver Widget\nInfinite Widget\nWidget For Cinema",
"for widget in widgetsN:\n if widget['price'] > 9.30:\n print(widget['wname'])",
"Problem set #3: Sibling rivalries\nIn the following problem set, you will yet again be working with the data in widgets2016.html. In order to accomplish the tasks in this problem set, you'll need to learn about Beautiful Soup's .find_next_sibling() method. Here's some information about that method, cribbed from the notes:\nOften, the tags we're looking for don't have a distinguishing characteristic, like a class attribute, that allows us to find them using .find() and .find_all(), and the tags also aren't in a parent-child relationship. This can be tricky! For example, take the following HTML snippet, (which I've assigned to a string called example_html):",
"example_html = \"\"\"\n<h2>Camembert</h2>\n<p>A soft cheese made in the Camembert region of France.</p>\n\n<h2>Cheddar</h2>\n<p>A yellow cheese made in the Cheddar region of... France, probably, idk whatevs.</p>\n\"\"\"",
"If our task was to create a dictionary that maps the name of the cheese to the description that follows in the <p> tag directly afterward, we'd be out of luck. Fortunately, Beautiful Soup has a .find_next_sibling() method, which allows us to search for the next tag that is a sibling of the tag you're calling it on (i.e., the two tags share a parent), that also matches particular criteria. So, for example, to accomplish the task outlined above:",
"example_doc = BeautifulSoup(example_html, \"html.parser\")\ncheese_dict = {}\nfor h2_tag in example_doc.find_all('h2'):\n cheese_name = h2_tag.string\n cheese_desc_tag = h2_tag.find_next_sibling('p')\n cheese_dict[cheese_name] = cheese_desc_tag.string\n\ncheese_dict",
"With that knowledge in mind, let's go back to our widgets. In the cell below, write code that uses Beautiful Soup, and in particular the .find_next_sibling() method, to print the part numbers of the widgets that are in the table just beneath the header \"Hallowed Widgets.\"\nExpected output:\nMZ-556/B\nQV-730\nT1-9731\n5B-941/F",
"for h3_tags in document.find_all('h3'):\n if h3_tags.string == 'Hallowed widgets':\n hallowed_table = h3_tags.find_next_sibling('table')\n for element in hallowed_table.find_all('td', {'class':'partno'}):\n print(element.string)",
"Okay, now, the final task. If you can accomplish this, you are truly an expert web scraper. I'll have little web scraper certificates made up and I'll give you one, if you manage to do this thing. And I know you can do it!\nIn the cell below, I've created a variable category_counts and assigned to it an empty dictionary. Write code to populate this dictionary so that its keys are \"categories\" of widgets (e.g., the contents of the <h3> tags on the page: \"Forensic Widgets\", \"Mood widgets\", \"Hallowed Widgets\") and the value for each key is the number of widgets that occur in that category. I.e., after your code has been executed, the dictionary category_counts should look like this:\n{'Forensic Widgets': 3,\n 'Hallowed widgets': 4,\n 'Mood widgets': 2,\n 'Wondrous widgets': 3}",
"category_counts = {}\n\nfor x_tags in document.find_all('h3'):\n x_table = x_tags.find_next_sibling('table')\n tr_info_tags = x_table.find_all('tr', {'class':'winfo'})\n category_counts[x_tags.string] = len(tr_info_tags)\n \ncategory_counts",
"Congratulations! You're done."
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
maxis42/ML-DA-Coursera-Yandex-MIPT
|
4 Stats for data analysis/Lectures notebooks/5 binomial test for proportion/stat.binomial_test_with_plots.ipynb
|
mit
|
[
"Биномиальный критерий для доли",
"import numpy as np\nfrom scipy import stats\n\n%pylab inline",
"Shaken, not stirred\nДжеймс Бонд говорит, что предпочитает мартини взболтанным, но не смешанным. Проведём слепой тест (blind test): $n$ раз предложим ему пару напитков и выясним, какой из двух он предпочитает. Получаем: \n* выборка: бинарный вектор длины $n$, где 1 — Джеймс Бонд предпочел взболтанный напиток, 0 — смешанный;\n* гипотеза $H_0$: Джеймс Бонд не различает 2 вида напитков и выбирает наугад;\n* статистика $T$: количество единиц в выборке.\nЕсли нулевая гипотеза справедлива и Джеймс Бонд действительно выбирает наугад, то мы можем с одинаковой вероятностью получить любой из $2^n$ бинарных векторов длины $n$. \nМы могли бы перебрать все такие векторы, посчитать на каждом значение статистики $T$ и получить таким образом её нулевое распределение. Но в данном случае этот этап можно пропустить: мы имеем дело с выборкой, состоящей из 0 и 1, то есть, из распределения Бернулли $Ber(p)$. Нулевая гипотеза выбора наугад соответствует значению $p=\\frac1{2}$, то есть, в каждом эксперименте вероятность выбора взболтанного мартини равна $\\frac1{2}$. Сумма $n$ одинаково распределённых бернуллиевских случайных величин с параметром $p$ имеет биномиальное распределение $Bin(n, p)$. Следовательно, нулевое распределение статистики $T$ — $Bin\\left(n, \\frac1{2}\\right)$.\nПусть $n=16.$",
"n = 16\nF_H0 = stats.binom(n, 0.5)\n\nx = np.linspace(0,16,17)\n\npylab.bar(x, F_H0.pmf(x), align = 'center')\nxlim(-0.5, 16.5) \npylab.show()",
"Односторонняя альтернатива\nгипотеза $H_1$: Джеймс Бонд предпочитает взболтанный мартини.\nПри такой альтернативе более вероятны большие значения статистики; при расчёте достигаемого уровня значимости будем суммировать высоту столбиков в правом хвосте распределения.",
"pylab.bar(x, F_H0.pmf(x), align = 'center')\npylab.bar(np.linspace(12,16,5), F_H0.pmf(np.linspace(12,16,5)), align = 'center', color='red')\nxlim(-0.5, 16.5) \npylab.show()\n\nstats.binom_test(12, 16, 0.5, alternative = 'greater')\n\npylab.bar(x, F_H0.pmf(x), align = 'center')\npylab.bar(np.linspace(11,16,6), F_H0.pmf(np.linspace(11,16,6)), align = 'center', color='red')\nxlim(-0.5, 16.5) \npylab.show()\n\nstats.binom_test(11, 16, 0.5, alternative = 'greater')",
"Двусторонняя альтернатива\nгипотеза $H_1$: Джеймс Бонд предпочитает какой-то определённый вид мартини.\nПри такой альтернативе более вероятны очень большие и очень маленькие значения статистики; при расчёте достигаемого уровня значимости будем суммировать высоту столбиков в правом и левом хвостах распределения.",
"pylab.bar(x, F_H0.pmf(x), align = 'center')\npylab.bar(np.linspace(12,16,5), F_H0.pmf(np.linspace(12,16,5)), align = 'center', color='red')\npylab.bar(np.linspace(0,4,5), F_H0.pmf(np.linspace(0,4,5)), align = 'center', color='red')\nxlim(-0.5, 16.5) \npylab.show()\n\nstats.binom_test(12, 16, 0.5, alternative = 'two-sided')\n\npylab.bar(x, F_H0.pmf(x), align = 'center')\npylab.bar(np.linspace(13,16,4), F_H0.pmf(np.linspace(13,16,4)), align = 'center', color='red')\npylab.bar(np.linspace(0,3,4), F_H0.pmf(np.linspace(0,3,4)), align = 'center', color='red')\nxlim(-0.5, 16.5) \npylab.show()\n\nstats.binom_test(13, 16, 0.5, alternative = 'two-sided')"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
foreignOwl/data-analysis-notebooks
|
jeopardyQuestionAnalysis.ipynb
|
mit
|
[
"How the Length of a Jeopardy Question Relates to its Value?\nThe American television game show Jeopardy is probably one of the most famous shows ever aired on TV. Few years ago IBM's Watson conquered the show, and now, it's time the conquer the dataset of all the questions that were asked in years and see if any interesting relations lie behind them.\n\nThanks to Reddit user trexmatt for providing CSV data of the questions which can be found here.\n\nStructure of the Dataset\nAs explained on the Reddit post given above, each row of the dataset contains information on a particular question:\n* Category\n* Value\n* Question text\n* Answer text\n* Round of the game the question was asked\n* Show number\n* Date\nHypothesis\nBefore diving into analysis of the data let's come up with a relation between different columns:\n\nValue of the question is related to its length.\n\nSetting up Data",
"# this line is required to see visualizations inline for Jupyter notebook\n%matplotlib inline\n\n# importing modules that we need for analysis\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport re\n\n# read the data from file and print out first few rows\njeopardy = pd.read_csv(\"jeopardy.csv\")\nprint(jeopardy.head(3))\n\nprint(jeopardy.columns)",
"Apparently columns have a blank space in the beginning. Let's get rid of them:",
"jeopardy.rename(columns = lambda x: x[1:] if x[0] == \" \" else x, inplace=True)\njeopardy.columns",
"Hypothesis - \"Value of the question is related to its length.\"\nLet's have a copy of dataframe so that changes we make doesn't disturb further analysis.",
"data1 = jeopardy\n\ndata1[\"Question\"].value_counts()[:10]",
"There are some media-based questions, and also some questions with hyper-links. These can disturb our analysis so we should get rid of them.",
"# regex pattern used to remove hyper-links\npattern = re.compile(\"^<a href\")\n\n# remove media clue questions\ndata1 = data1[data1[\"Question\"].str.contains(pattern) == False]\ndata1 = data1[data1[\"Question\"] != \"[audio clue]\"]\ndata1 = data1[data1[\"Question\"] != \"(audio clue)\"]\ndata1 = data1[data1[\"Question\"] != \"[video clue]\"]\ndata1 = data1[data1[\"Question\"] != \"[filler]\"]\n\ndata1[\"Question\"].value_counts()[:10]",
"We can add a column to dataframe for lenght of questions.",
"data1[\"Question Length\"] = data1[\"Question\"].apply(lambda x: len(x))\ndata1[\"Question Length\"][:12]",
"When we look at the \"Value\" column, we see they are not integers but strings, also there are some \"None\" values. We should clean those values.",
"data1[\"Value\"].value_counts()[:15]\n\n# get rid of None values\ndata1 = data1[data1[\"Value\"] != \"None\"]\n\n# parse integers from strings\npattern = \"[0-9]\"\ndata1[\"Value\"] = data1[\"Value\"].apply(lambda x: \"\".join(re.findall(pattern,x)))\ndata1[\"Value\"] = data1[\"Value\"].astype(int)\n\nprint(data1[\"Value\"].value_counts()[:10])\nprint(\"Number of distinct values:\" + str(len(data1[\"Value\"].value_counts())))",
"The \"Value\" column has 145 different values. For the sake of simplicity, let's keep the ones that are multiples of 100 and between 200 and 2500 (first round questions has range of 200-1000, second round questions has range of 500-2500).",
"data1 = data1[(data1[\"Value\"]%100 == 0) & (data1[\"Value\"]<= 2500)]\nprint(data1[\"Value\"].value_counts())\nprint(\"Number of distinct values: \" + str(len(data1[\"Value\"].value_counts())))\n\n# set up the figure and plot length vs value on ax1\nfig = plt.figure(figsize=(10,5))\n\nax1 = fig.add_subplot(1,1,1)\nax1.scatter(data1[\"Question Length\"], data1[\"Value\"])\nax1.set_xlim(0, 800)\nax1.set_ylim(0, 2700)\nax1.set_title(\"The Relation between Question Length and Value\")\nax1.set_xlabel(\"Lenght of the Question\")\nax1.set_ylabel(\"Value of the Question\")\nplt.show()",
"It looks like there isn't a correlation, but this graph isn't structured well enough to draw conclusions. Instead, let's calculate average question length for each value and plot average length vs value.",
"#find the average length for each value\naverage_lengths = []\nvalues = data1[\"Value\"].unique()\nfor value in values:\n rows = data1[data1[\"Value\"] == value]\n average = rows[\"Question Length\"].mean()\n average_lengths.append(average)\nprint(average_lengths)\nprint(values)\n\n# set up the figure and plot average length vs value on ax1\nfig = plt.figure(figsize=(10,5))\n\nax1 = fig.add_subplot(1,1,1)\nax1.scatter(average_lengths, values)\nax1.set_title(\"The Relation between Average Question Length and Value\")\nax1.set_xlabel(\"Average Question Length\")\nax1.set_ylabel(\"Value\")\nax1.set_xlim(70, 105)\nax1.set_ylim(0, 3000)\nplt.show()\n\nprint(\"Correlation coefficient: \" + str(np.corrcoef(average_lengths, values)[0,1]))",
"Here we go! Even though it's not a strong correlation, we've found a moderate correlation (with coefficient 0.53) between length of the question and it's value!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
bjackman/lisa
|
ipynb/examples/trappy/trappy_example.ipynb
|
apache-2.0
|
[
"TRAPpy\nTRAPpy (Trace Analysis and Plotting in Python) is a visualization tool to help analyze data generated on a device. It parses ftrace-like logs and creates in-memory data structures to be used for plotting and data analysis.\nMore information can be found at https://github.com/ARM-software/trappy and https://pythonhosted.org/TRAPpy/.\nA big part of the notebook below is target and test environment confituration as well as workload configuration, detailed in examples/utils/ and examples/wlgen/. For this reason those cells won't be documented in detail here in order to focus more on TRAPpy.",
"import logging\nfrom conf import LisaLogging\nLisaLogging.setup()\n\n# Generate plots inline\n%pylab inline\n\nimport json\nimport os\n\n# Support to initialise and configure your test environment\nimport devlib\nfrom env import TestEnv\n\n# Support to configure and run RTApp based workloads\nfrom wlgen import RTA, Periodic, Ramp, Step, Pulse\n\n# Suport for FTrace events parsing and visualization\nimport trappy\nfrom trappy.ftrace import FTrace\nfrom trace import Trace",
"Test environment setup\nFor more details on this please check out examples/utils/testenv_example.ipynb.",
"# Setup a target configuration\nmy_target_conf = {\n \n \"platform\" : 'linux',\n \"board\" : 'juno',\n\n \"modules\" : [\n 'bl',\n 'cpufreq'\n ],\n\n \"host\" : '192.168.0.1',\n \"username\" : 'root',\n \"password\" : 'juno',\n## Workload execution\n \"rtapp-calib\" : {\n '0': 361, '1': 138, '2': 138, '3': 352, '4': 360, '5': 353\n }\n\n}\n\nmy_tests_conf = {\n\n \"tools\" : ['rt-app', 'taskset', 'trace-cmd'],\n\n \"ftrace\" : {\n \"events\" : [\n 'sched_migrate_task',\n 'sched_process_exec',\n 'sched_process_fork',\n 'sched_stat_iowait',\n 'sched_switch',\n 'sched_wakeup',\n 'sched_wakeup_new',\n 'sched_overutilized',\n 'cpu_capacity',\n 'sched_load_avg_cpu',\n 'sched_load_avg_task',\n 'sched_boost_cpu',\n 'sched_boost_task',\n 'sched_energy_diff',\n 'cpu_frequency',\n 'cpu_idle',\n 'sched_tune_config',\n ],\n \"buffsize\" : 10240\n },\n\n}\n\nte = TestEnv(target_conf=my_target_conf, test_conf=my_tests_conf)\ntarget = te.target",
"Workload configuration and execution\nFor more details on this please check out examples/wlgen/rtapp_example.ipynb.",
"# Create a new RTApp workload generator using the calibration values\nrtapp = RTA(target, 'trappy', calibration=te.calibration())\n\n# Configure this RTApp instance to:\nrtapp.conf(\n kind='profile',\n \n params={\n 'task_per20': Periodic(\n period_ms=100,\n duty_cycle_pct=20,\n duration_s=5,\n cpus=None,\n sched={\n \"policy\": \"FIFO\",\n },\n delay_s=0\n ).get(),\n\n 'task_rmp20_5-60': Ramp(\n period_ms=100,\n start_pct=5,\n end_pct=65,\n delta_pct=20,\n time_s=1,\n cpus=\"0\"\n ).get(),\n\n 'task_stp10-50': Step(\n period_ms=100,\n start_pct=0,\n end_pct=50,\n time_s=1,\n delay_s=0.5\n ).get(),\n\n 'task_pls5-80': Pulse(\n period_ms=100,\n start_pct=65,\n end_pct=5,\n time_s=1,\n delay_s=0.5\n ).get(),\n },\n\n run_dir=target.working_directory\n \n);\n\nlogging.info('#### Setup FTrace')\nte.ftrace.start()\n\nlogging.info('#### Start energy sampling')\nte.emeter.reset()\n\nlogging.info('#### Start RTApp execution')\nrtapp.run(out_dir=te.res_dir, cgroup=\"\")\n\nlogging.info('#### Read energy consumption: %s/energy.json', te.res_dir)\nnrg_report = te.emeter.report(out_dir=te.res_dir)\n\nlogging.info('#### Stop FTrace')\nte.ftrace.stop()\n\ntrace_file = os.path.join(te.res_dir, 'trace.dat')\nlogging.info('#### Save FTrace: %s', trace_file)\nte.ftrace.get_trace(trace_file)\n\nlogging.info('#### Save platform description: %s/platform.json', te.res_dir)\n(plt, plt_file) = te.platform_dump(te.res_dir)",
"Trace inspection",
"# NOTE: The interactive trace visualization is available only if you run\n# the workload to generate a new trace-file\ntrappy.plotter.plot_trace(te.res_dir)"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
kaslusimoes/MurphyProbabilisticML
|
chapters/Chapter 1.ipynb
|
mit
|
[
"%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt",
"Chapter 1 - Introduction to Machine Learning\nThis chapter introduces some common concepts about learning (such as supervised and unsupervised learning) and some simples applications.\nSupervised Learning\n\nClassification (labels)\nRegression (real)\n\nLearn when we have a dataset with points and true responses variables. If we use a probabilistic approach to this kind of inference, we want to find the probability distribution of the response $y$ given the training dataset $\\mathcal{D}$ and a new point $x$ outside of it.\n$$p(y\\ |\\ x, \\mathcal{D})$$\nA good guess $\\hat{y}$ for $y$ is the Maximum a Posteriori estimator:\n$$ŷ = \\underset{c}{\\mathrm{argmax}}\\ p(y = c|x, \\mathcal{D})$$\nUnsupervised Learning\n\nClustering\nDimensionality Reduction / Latent variables\nDiscovering graph structure\nMatrix completions\n\nParametric models\nThese models have a finite (and fixed) number of parameters.\nExamples:\n* Linear regression:\n$$y(\\mathbf{x}) = \\mathbf{w}^\\intercal\\mathbf{x} + \\epsilon$$\nWhich can be written as\n\n$$p(y\\ |\\ x, \\theta) = \\mathcal{N}(y\\ |\\ \\mu(x), \\sigma^2) = \\mathcal{N}(y\\ |\\ w^\\intercal x, \\sigma^2)$$",
"%run ../src/LinearRegression.py\n%run ../src/PolynomialFeatures.py\n\n# LINEAR REGRESSION\n\n# Generate random data\nX = np.linspace(0,20,10)[:,np.newaxis]\ny = 0.1*(X**2) + np.random.normal(0,2,10)[:,np.newaxis] + 20\n\n# Fit model to data\nlr = LinearRegression()\nlr.fit(X,y)\n\n# Predict new data\nx_test = np.array([0,20])[:,np.newaxis]\ny_predict = lr.predict(x_test)\n\n\n# POLYNOMIAL REGRESSION\n\n# Fit model to data\npoly = PolynomialFeatures(2)\nlr = LinearRegression()\nlr.fit(poly.fit_transform(X),y)\n\n# Predict new data\nx_pol = np.linspace(0, 20, 100)[:, np.newaxis]\ny_pol = lr.predict(poly.fit_transform(x_pol))\n\n# Plot data\n\nfig = plt.figure(figsize=(14, 6))\n\n# Plot linear regression\nax1 = fig.add_subplot(1, 2, 1)\nplt.scatter(X,y)\nplt.plot(x_test, y_predict, \"r\")\nplt.xlim(0, 20)\nplt.ylim(0, 50)\n\n# Plot polynomial regression\nax2 = fig.add_subplot(1, 2, 2)\nplt.scatter(X,y)\nplt.plot(x_pol, y_pol, \"r\")\nplt.xlim(0, 20)\nplt.ylim(0, 50);",
"Logistic regression:\n Despite the name, this is a classification model\n\n$$p(y\\ |\\ x, w) = \\mathrm{Ber}(y\\ |\\ \\mu(x)) = \\mathrm{Ber}(y\\ |\\ \\mathrm{sigm}(w^\\intercal x))$$\nwhere\n\n$$\\displaystyle \\mathrm{sigm}(x) = \\frac{e^x}{1+e^x}$$",
"%run ../src/LogisticRegression.py\n\nX = np.hstack((np.random.normal(90, 2, 100), np.random.normal(110, 2, 100)))[:, np.newaxis]\ny = np.array([0]*100 + [1]*100)[:, np.newaxis]\n\nlogr = LogisticRegression(learnrate=0.002, eps = 0.001)\n\nlogr.fit(X, y)\n\nx_test = np.array([-logr.w[0]/logr.w[1]]).reshape(1,1) #np.linspace(-10, 10, 30)[:, np.newaxis]\ny_probs = logr.predict_proba(x_test)[:, 0:1]\nprint(\"Probability:\" + str(y_probs))\n\n# Plot data\n\nfig = plt.figure(figsize=(14, 6))\n\n# Plot sigmoid function\nax1 = fig.add_subplot(1, 2, 1)\nt = np.linspace(-15,15,100)\nplt.plot(t, logr._sigmoid(t))\n\n# Plot logistic regression\nax2 = fig.add_subplot(1, 2, 2)\nplt.scatter(X, y)\nplt.scatter(x_test, y_probs, c='r')",
"Non-parametric models\nThese models don't have a finite number of parameters. For example the number of parameters increase with the amount of training data, as in KNN:\n$$p(y=c\\ |\\ x, \\mathcal{D}, K) = \\frac{1}{K} \\sum_{i \\in N_K(x, \\mathcal{D})} \\mathbb{I}(y_i = c)$$",
"%run ../src/KNearestNeighbors.py\n\n# Generate data from 3 gaussians\ngaussian_1 = np.random.multivariate_normal(np.array([1, 0.0]), np.eye(2)*0.01, size=100)\ngaussian_2 = np.random.multivariate_normal(np.array([0.0, 1.0]), np.eye(2)*0.01, size=100)\ngaussian_3 = np.random.multivariate_normal(np.array([0.1, 0.1]), np.eye(2)*0.001, size=100)\nX = np.vstack((gaussian_1, gaussian_2, gaussian_3))\ny = np.array([1]*100 + [2]*100 + [3]*100)\n\n# Fit the model\nknn = KNearestNeighbors(5)\nknn.fit(X, y)\n\n# Predict various points in space\nXX, YY = np.mgrid[-5:5:.2, -5:5:.2]\nX_test = np.hstack((XX.ravel()[:, np.newaxis], YY.ravel()[:, np.newaxis]))\ny_test = knn.predict(X_test)\n\nfig = plt.figure(figsize=(14, 6))\n\n# Plot original data\nax1 = fig.add_subplot(1, 2, 1)\nax1.plot(X[y == 1,0], X[y == 1,1], 'bo')\nax1.plot(X[y == 2,0], X[y == 2,1], 'go')\nax1.plot(X[y == 3,0], X[y == 3,1], 'ro')\n\n# Plot predicted data\nax2 = fig.add_subplot(1, 2, 2)\nax2.contourf(XX, YY, y_test.reshape(50,50));",
"Curse of dimensionality\nThe curse of dimensionality refers to a series of problems that arise only when dealing with high dimensional data sets. For example, in the KNN model, if we assume the data is uniformly distributed over a $N$-dimensional cube (with high $N$), then most of the points are near its faces. Therefore, KNN loses its locality property."
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
ve-interactive/Pynexus
|
examples/API.ipynb
|
apache-2.0
|
[
"Summary\nRequirements:\n\npython 3 \n\nThis notebook show how to make call to the AppNexus API.\nImplemented functions:\n```python\n def get_campaign(self, ids=None, one_id=None, advertiser_id=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Campaign+Service\"\"\"\ndef get_pixel(self, ids=None, one_id=None, advertiser_id=None,\n advertiser_code=None, pixel_code=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Conversion+Pixel+Service \"\"\"\n\ndef get_device(self, one_id=None, device_type=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Device+Model+Service \"\"\"\n\ndef get_advertiser(self, ids=None, one_id=None, search_term=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Advertiser+Service\"\"\"\n\ndef get_line_item(self, ids=None, one_id=None, advertiser_id=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Line+Item+Service\"\"\"\n\ndef get_insertion_order(self, ids=None, one_id=None, advertiser_id=None, search_term=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Insertion+Order+Service\"\"\"\n\ndef get_segment(self, ids=None, one_id=None, search_term=None, only_names=True):\n \"\"\" cf https://wiki.appnexus.com/display/api/Segment+Service\"\"\"\n\n```",
"from pynexus import AppNexusAPI\n\nAPPNEXUS_ACCOUNT = {\n \"username\": \"\",\n \"password\": \"\"\n}\napi = AppNexusAPI(**APPNEXUS_ACCOUNT)",
"1. Make a request\nOnly the mapping *id -> name *",
"api.get_device(one_id=80)",
"Full response",
"api.get_device(one_id=80, only_names=False)",
"2. Bulk request\nIf you need to retrieve more than 100 mappings, you will need to make several call.\nThe bulk_requests function can to that for you",
"pixels = AppNexusAPI.bulk_requests(api.get_pixel, range(0, 300))",
"You may also want to retrieve all the elements, without specifying an id.\nbase the default get function will only return up to 100 elements, you can use the bulk_request_get_all\nto avoid hitting the limit.",
"# We limit here the number of calls to 10\nnames = AppNexusAPI.bulk_request_get_all(api.get_pixel, limit=10, only_names=True)\n\nprint('%d elements downloaded' % len(names))"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
mne-tools/mne-tools.github.io
|
stable/_downloads/e1c3654f77f904db443b548e9d93b8f9/50_decoding.ipynb
|
bsd-3-clause
|
[
"%matplotlib inline",
"Decoding (MVPA)\n.. include:: ../../links.inc\nDesign philosophy\nDecoding (a.k.a. MVPA) in MNE largely follows the machine\nlearning API of the scikit-learn package.\nEach estimator implements fit, transform, fit_transform, and\n(optionally) inverse_transform methods. For more details on this design,\nvisit scikit-learn_. For additional theoretical insights into the decoding\nframework in MNE :footcite:KingEtAl2018.\nFor ease of comprehension, we will denote instantiations of the class using\nthe same name as the class but in small caps instead of camel cases.\nLet's start by loading data for a simple two-class problem:\nsphinx_gallery_thumbnail_number = 6",
"import numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\n\nimport mne\nfrom mne.datasets import sample\nfrom mne.decoding import (SlidingEstimator, GeneralizingEstimator, Scaler,\n cross_val_multiscore, LinearModel, get_coef,\n Vectorizer, CSP)\n\ndata_path = sample.data_path()\n\nsubjects_dir = data_path / 'subjects'\nmeg_path = data_path / 'MEG' / 'sample'\nraw_fname = meg_path / 'sample_audvis_filt-0-40_raw.fif'\ntmin, tmax = -0.200, 0.500\nevent_id = {'Auditory/Left': 1, 'Visual/Left': 3} # just use two\nraw = mne.io.read_raw_fif(raw_fname)\nraw.pick_types(meg='grad', stim=True, eog=True, exclude=())\n\n# The subsequent decoding analyses only capture evoked responses, so we can\n# low-pass the MEG data. Usually a value more like 40 Hz would be used,\n# but here low-pass at 20 so we can more heavily decimate, and allow\n# the example to run faster. The 2 Hz high-pass helps improve CSP.\nraw.load_data().filter(2, 20)\nevents = mne.find_events(raw, 'STI 014')\n\n# Set up bad channels (modify to your needs)\nraw.info['bads'] += ['MEG 2443'] # bads + 2 more\n\n# Read epochs\nepochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,\n picks=('grad', 'eog'), baseline=(None, 0.), preload=True,\n reject=dict(grad=4000e-13, eog=150e-6), decim=3,\n verbose='error')\nepochs.pick_types(meg=True, exclude='bads') # remove stim and EOG\ndel raw\n\nX = epochs.get_data() # MEG signals: n_epochs, n_meg_channels, n_times\ny = epochs.events[:, 2] # target: auditory left vs visual left",
"Transformation classes\nScaler\nThe :class:mne.decoding.Scaler will standardize the data based on channel\nscales. In the simplest modes scalings=None or scalings=dict(...),\neach data channel type (e.g., mag, grad, eeg) is treated separately and\nscaled by a constant. This is the approach used by e.g.,\n:func:mne.compute_covariance to standardize channel scales.\nIf scalings='mean' or scalings='median', each channel is scaled using\nempirical measures. Each channel is scaled independently by the mean and\nstandand deviation, or median and interquartile range, respectively, across\nall epochs and time points during :class:~mne.decoding.Scaler.fit\n(during training). The :meth:~mne.decoding.Scaler.transform method is\ncalled to transform data (training or test set) by scaling all time points\nand epochs on a channel-by-channel basis. To perform both the fit and\ntransform operations in a single call, the\n:meth:~mne.decoding.Scaler.fit_transform method may be used. To invert the\ntransform, :meth:~mne.decoding.Scaler.inverse_transform can be used. For\nscalings='median', scikit-learn_ version 0.17+ is required.\n<div class=\"alert alert-info\"><h4>Note</h4><p>Using this class is different from directly applying\n :class:`sklearn.preprocessing.StandardScaler` or\n :class:`sklearn.preprocessing.RobustScaler` offered by\n scikit-learn_. These scale each *classification feature*, e.g.\n each time point for each channel, with mean and standard\n deviation computed across epochs, whereas\n :class:`mne.decoding.Scaler` scales each *channel* using mean and\n standard deviation computed across all of its time points\n and epochs.</p></div>\n\nVectorizer\nScikit-learn API provides functionality to chain transformers and estimators\nby using :class:sklearn.pipeline.Pipeline. We can construct decoding\npipelines and perform cross-validation and grid-search. However scikit-learn\ntransformers and estimators generally expect 2D data\n(n_samples * n_features), whereas MNE transformers typically output data\nwith a higher dimensionality\n(e.g. n_samples * n_channels * n_frequencies * n_times). A Vectorizer\ntherefore needs to be applied between the MNE and the scikit-learn steps\nlike:",
"# Uses all MEG sensors and time points as separate classification\n# features, so the resulting filters used are spatio-temporal\nclf = make_pipeline(\n Scaler(epochs.info),\n Vectorizer(),\n LogisticRegression(solver='liblinear') # liblinear is faster than lbfgs\n)\n\nscores = cross_val_multiscore(clf, X, y, cv=5, n_jobs=1)\n\n# Mean scores across cross-validation splits\nscore = np.mean(scores, axis=0)\nprint('Spatio-temporal: %0.1f%%' % (100 * score,))",
"PSDEstimator\nThe :class:mne.decoding.PSDEstimator\ncomputes the power spectral density (PSD) using the multitaper\nmethod. It takes a 3D array as input, converts it into 2D and computes the\nPSD.\nFilterEstimator\nThe :class:mne.decoding.FilterEstimator filters the 3D epochs data.\nSpatial filters\nJust like temporal filters, spatial filters provide weights to modify the\ndata along the sensor dimension. They are popular in the BCI community\nbecause of their simplicity and ability to distinguish spatially-separated\nneural activity.\nCommon spatial pattern\n:class:mne.decoding.CSP is a technique to analyze multichannel data based\non recordings from two classes :footcite:Koles1991 (see also\nhttps://en.wikipedia.org/wiki/Common_spatial_pattern).\nLet $X \\in R^{C\\times T}$ be a segment of data with\n$C$ channels and $T$ time points. The data at a single time point\nis denoted by $x(t)$ such that $X=[x(t), x(t+1), ..., x(t+T-1)]$.\nCommon spatial pattern (CSP) finds a decomposition that projects the signal\nin the original sensor space to CSP space using the following transformation:\n\\begin{align}x_{CSP}(t) = W^{T}x(t)\n :label: csp\\end{align}\nwhere each column of $W \\in R^{C\\times C}$ is a spatial filter and each\nrow of $x_{CSP}$ is a CSP component. The matrix $W$ is also\ncalled the de-mixing matrix in other contexts. Let\n$\\Sigma^{+} \\in R^{C\\times C}$ and $\\Sigma^{-} \\in R^{C\\times C}$\nbe the estimates of the covariance matrices of the two conditions.\nCSP analysis is given by the simultaneous diagonalization of the two\ncovariance matrices\n\\begin{align}W^{T}\\Sigma^{+}W = \\lambda^{+}\n :label: diagonalize_p\\end{align}\n\\begin{align}W^{T}\\Sigma^{-}W = \\lambda^{-}\n :label: diagonalize_n\\end{align}\nwhere $\\lambda^{C}$ is a diagonal matrix whose entries are the\neigenvalues of the following generalized eigenvalue problem\n\\begin{align}\\Sigma^{+}w = \\lambda \\Sigma^{-}w\n :label: eigen_problem\\end{align}\nLarge entries in the diagonal matrix corresponds to a spatial filter which\ngives high variance in one class but low variance in the other. Thus, the\nfilter facilitates discrimination between the two classes.\n.. topic:: Examples\n* `ex-decoding-csp-eeg`\n* `ex-decoding-csp-eeg-timefreq`\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>The winning entry of the Grasp-and-lift EEG competition in Kaggle used\n the :class:`~mne.decoding.CSP` implementation in MNE and was featured as\n a [script of the week](sotw_).</p></div>\n\nWe can use CSP with these data with:",
"csp = CSP(n_components=3, norm_trace=False)\nclf_csp = make_pipeline(\n csp,\n LinearModel(LogisticRegression(solver='liblinear'))\n)\nscores = cross_val_multiscore(clf_csp, X, y, cv=5, n_jobs=1)\nprint('CSP: %0.1f%%' % (100 * scores.mean(),))",
"Source power comodulation (SPoC)\nSource Power Comodulation (:class:mne.decoding.SPoC)\n:footcite:DahneEtAl2014 identifies the composition of\northogonal spatial filters that maximally correlate with a continuous target.\nSPoC can be seen as an extension of the CSP where the target is driven by a\ncontinuous variable rather than a discrete variable. Typical applications\ninclude extraction of motor patterns using EMG power or audio patterns using\nsound envelope.\n.. topic:: Examples\n* `ex-spoc-cmc`\n\nxDAWN\n:class:mne.preprocessing.Xdawn is a spatial filtering method designed to\nimprove the signal to signal + noise ratio (SSNR) of the ERP responses\n:footcite:RivetEtAl2009. Xdawn was originally\ndesigned for P300 evoked potential by enhancing the target response with\nrespect to the non-target response. The implementation in MNE-Python is a\ngeneralization to any type of ERP.\n.. topic:: Examples\n* `ex-xdawn-denoising`\n* `ex-xdawn-decoding`\n\nEffect-matched spatial filtering\nThe result of :class:mne.decoding.EMS is a spatial filter at each time\npoint and a corresponding time course :footcite:SchurgerEtAl2013.\nIntuitively, the result gives the similarity between the filter at\neach time point and the data vector (sensors) at that time point.\n.. topic:: Examples\n* `ex-ems-filtering`\n\nPatterns vs. filters\nWhen interpreting the components of the CSP (or spatial filters in general),\nit is often more intuitive to think about how $x(t)$ is composed of\nthe different CSP components $x_{CSP}(t)$. In other words, we can\nrewrite Equation :eq:csp as follows:\n\\begin{align}x(t) = (W^{-1})^{T}x_{CSP}(t)\n :label: patterns\\end{align}\nThe columns of the matrix $(W^{-1})^T$ are called spatial patterns.\nThis is also called the mixing matrix. The example ex-linear-patterns\ndiscusses the difference between patterns and filters.\nThese can be plotted with:",
"# Fit CSP on full data and plot\ncsp.fit(X, y)\ncsp.plot_patterns(epochs.info)\ncsp.plot_filters(epochs.info, scalings=1e-9)",
"Decoding over time\nThis strategy consists in fitting a multivariate predictive model on each\ntime instant and evaluating its performance at the same instant on new\nepochs. The :class:mne.decoding.SlidingEstimator will take as input a\npair of features $X$ and targets $y$, where $X$ has\nmore than 2 dimensions. For decoding over time the data $X$\nis the epochs data of shape n_epochs × n_channels × n_times. As the\nlast dimension of $X$ is the time, an estimator will be fit\non every time instant.\nThis approach is analogous to SlidingEstimator-based approaches in fMRI,\nwhere here we are interested in when one can discriminate experimental\nconditions and therefore figure out when the effect of interest happens.\nWhen working with linear models as estimators, this approach boils\ndown to estimating a discriminative spatial filter for each time instant.\nTemporal decoding\nWe'll use a Logistic Regression for a binary classification as machine\nlearning model.",
"# We will train the classifier on all left visual vs auditory trials on MEG\n\nclf = make_pipeline(\n StandardScaler(),\n LogisticRegression(solver='liblinear')\n)\n\ntime_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_auc', verbose=True)\n# here we use cv=3 just for speed\nscores = cross_val_multiscore(time_decod, X, y, cv=3, n_jobs=1)\n\n# Mean scores across cross-validation splits\nscores = np.mean(scores, axis=0)\n\n# Plot\nfig, ax = plt.subplots()\nax.plot(epochs.times, scores, label='score')\nax.axhline(.5, color='k', linestyle='--', label='chance')\nax.set_xlabel('Times')\nax.set_ylabel('AUC') # Area Under the Curve\nax.legend()\nax.axvline(.0, color='k', linestyle='-')\nax.set_title('Sensor space decoding')",
"You can retrieve the spatial filters and spatial patterns if you explicitly\nuse a LinearModel",
"clf = make_pipeline(\n StandardScaler(),\n LinearModel(LogisticRegression(solver='liblinear'))\n)\ntime_decod = SlidingEstimator(clf, n_jobs=1, scoring='roc_auc', verbose=True)\ntime_decod.fit(X, y)\n\ncoef = get_coef(time_decod, 'patterns_', inverse_transform=True)\nevoked_time_gen = mne.EvokedArray(coef, epochs.info, tmin=epochs.times[0])\njoint_kwargs = dict(ts_args=dict(time_unit='s'),\n topomap_args=dict(time_unit='s'))\nevoked_time_gen.plot_joint(times=np.arange(0., .500, .100), title='patterns',\n **joint_kwargs)",
"Temporal generalization\nTemporal generalization is an extension of the decoding over time approach.\nIt consists in evaluating whether the model estimated at a particular\ntime instant accurately predicts any other time instant. It is analogous to\ntransferring a trained model to a distinct learning problem, where the\nproblems correspond to decoding the patterns of brain activity recorded at\ndistinct time instants.\nThe object to for Temporal generalization is\n:class:mne.decoding.GeneralizingEstimator. It expects as input $X$\nand $y$ (similarly to :class:~mne.decoding.SlidingEstimator) but\ngenerates predictions from each model for all time instants. The class\n:class:~mne.decoding.GeneralizingEstimator is generic and will treat the\nlast dimension as the one to be used for generalization testing. For\nconvenience, here, we refer to it as different tasks. If $X$\ncorresponds to epochs data then the last dimension is time.\nThis runs the analysis used in :footcite:KingEtAl2014 and further detailed\nin :footcite:KingDehaene2014:",
"# define the Temporal generalization object\ntime_gen = GeneralizingEstimator(clf, n_jobs=1, scoring='roc_auc',\n verbose=True)\n\n# again, cv=3 just for speed\nscores = cross_val_multiscore(time_gen, X, y, cv=3, n_jobs=1)\n\n# Mean scores across cross-validation splits\nscores = np.mean(scores, axis=0)\n\n# Plot the diagonal (it's exactly the same as the time-by-time decoding above)\nfig, ax = plt.subplots()\nax.plot(epochs.times, np.diag(scores), label='score')\nax.axhline(.5, color='k', linestyle='--', label='chance')\nax.set_xlabel('Times')\nax.set_ylabel('AUC')\nax.legend()\nax.axvline(.0, color='k', linestyle='-')\nax.set_title('Decoding MEG sensors over time')",
"Plot the full (generalization) matrix:",
"fig, ax = plt.subplots(1, 1)\nim = ax.imshow(scores, interpolation='lanczos', origin='lower', cmap='RdBu_r',\n extent=epochs.times[[0, -1, 0, -1]], vmin=0., vmax=1.)\nax.set_xlabel('Testing Time (s)')\nax.set_ylabel('Training Time (s)')\nax.set_title('Temporal generalization')\nax.axvline(0, color='k')\nax.axhline(0, color='k')\ncbar = plt.colorbar(im, ax=ax)\ncbar.set_label('AUC')",
"Projecting sensor-space patterns to source space\nIf you use a linear classifier (or regressor) for your data, you can also\nproject these to source space. For example, using our evoked_time_gen\nfrom before:",
"cov = mne.compute_covariance(epochs, tmax=0.)\ndel epochs\nfwd = mne.read_forward_solution(\n meg_path / 'sample_audvis-meg-eeg-oct-6-fwd.fif')\ninv = mne.minimum_norm.make_inverse_operator(\n evoked_time_gen.info, fwd, cov, loose=0.)\nstc = mne.minimum_norm.apply_inverse(evoked_time_gen, inv, 1. / 9., 'dSPM')\ndel fwd, inv",
"And this can be visualized using :meth:stc.plot <mne.SourceEstimate.plot>:",
"brain = stc.plot(hemi='split', views=('lat', 'med'), initial_time=0.1,\n subjects_dir=subjects_dir)",
"Source-space decoding\nSource space decoding is also possible, but because the number of features\ncan be much larger than in the sensor space, univariate feature selection\nusing ANOVA f-test (or some other metric) can be done to reduce the feature\ndimension. Interpreting decoding results might be easier in source space as\ncompared to sensor space.\n.. topic:: Examples\n* `ex-dec-st-source`\n\nExercise\n\nExplore other datasets from MNE (e.g. Face dataset from SPM to predict\n Face vs. Scrambled)\n\nReferences\n.. footbibliography::"
] |
[
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
anshbansal/anshbansal.github.io
|
udacity_data_science_notes/Data_Wrangling_with_MongoDB/lesson_04/lesson_04.ipynb
|
mit
|
[
"Intro to MongoDB\n\nMakes sense for data science applications\nwidely used in big data\ndocument database or associative array\npython dictionary\n\n\n\nResources\n\nMongoDB is a NoSQL database.\nSee this official site for JSON data format.\nPython dictionaries documentation.\n\nWhy MongoDB\n\nflexible schema\noriented towards programmers\ndata stored mapped directly to data formats in popular programming languages\ndrivers for most popular programming languages\n\n\nflexible deployments\nsingle\ncluster\nmany choices in between these 2\n\n\ndesigned for big data\nhorizontally scalable\non commodity hardware\nnative support for map reduce\nhas aggregation framework\n\n\n\nYou can download MongoDB for your platform from the official MongoDB page. You can also read specific MongoDB installation instructions.\nYou do not need to install MongoDB on your machine for most of the exercises in this course, however for best learning outcome we recommend that you do it. It's fast and easy!\nMongoDB has a lot of drivers and client libraries. The one we will be using in this course is PyMongo. See the official documentation for PyMongo installation instructions.",
"import pprint\n\ndef get_client():\n from pymongo import MongoClient\n return MongoClient('mongodb://localhost:27017/')\n \ndef get_db(): \n # 'examples' here is the database name. It will be created if it does not exist.\n db = get_client().examples\n return db\n\ndef add_city(db):\n db.cities.insert_one({\"name\" : \"Chicago\"})\n \ndef get_city(db):\n return db.cities.find_one()\n\ndb = get_db()\n#add_city(db)\n\nfor city in db.cities.find():\n pprint.pprint(city)",
"Flexible Schema\n\nusually\nsome documents or entries will have fields that others do not\nschema evolves with time\n\n\nMongoDB's indexing system and query execution system take this into account - missing fields, arrays vs values\n\nPyMongo\n\ndriver/client library for python\nbasic job is to maintain a connection to db and allow you to work with your data in a very natural way\n\n\n- We will start mongoDB and process is mongod\n- we will have a python app with pymongo module\n- pymongo talks with mongodb using a wire protocol in BSON format\n- MongoDB ensures that each entry will have an _id field. If we don't specify one it will insert one for us\nMultiple queries",
"#db.cities.insert_one({\"name\": \"London\", \"isOld\": True})\n\n#db.cities.insert_one({\"name\": \"New York\", \"isNew\": True})\n\ndef find_in_cities(query):\n for city in db.cities.find(query):\n pprint.pprint(city)\n\nfind_in_cities({\"name\": \"London\", \"isOld\": False})\n\nfind_in_cities({\"name\": \"London\", \"isOld\": True})",
"projections",
"query = {\"name\": \"London\", \"isOld\": True}\nprojection = {\"_id\": 0, \"name\": 1}\nfor city in db.cities.find(query, projection):\n pprint.pprint(city)\n\ndb.cities.count()\n\nlist(city for city in db.cities.find())",
"Getting Data into MongoDB",
"from pymongo import MongoClient\nimport csv\nimport json\nimport io\nimport re\nimport pprint\n\n\nfield_map = {\n \"name\" : \"name\",\n \"bodyStyle_label\" : \"bodyStyle\",\n \"assembly_label\" : \"assembly\",\n \"class_label\" : \"class\",\n \"designer_label\" : \"designer\",\n \"engine_label\" : \"engine\",\n \"length\" : \"length\",\n \"height\" : \"height\",\n \"width\" : \"width\",\n \"weight\" : \"weight\",\n \"wheelbase\" : \"wheelbase\",\n \"layout_label\" : \"layout\",\n \"manufacturer_label\" : \"manufacturer\",\n \"modelEndYear\" : \"modelEndYear\",\n \"modelStartYear\" : \"modelStartYear\",\n \"predecessorLabel\" : \"predecessorLabel\",\n \"productionStartYear\" : \"productionStartYear\",\n \"productionEndYear\" : \"productionEndYear\",\n \"transmission\" : \"transmission\"\n}\nfields = field_map.keys()\n\n\ndef skip_lines(input_file, skip):\n for i in range(0, skip):\n next(input_file)\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef strip_automobile(v):\n return re.sub(r\"\\s*\\(automobile\\)\\s*\", \" \", v)\n\ndef strip_city(v):\n return re.sub(r\"\\s*\\(city\\)\\s*\", \" \", v)\n\ndef parse_array(v):\n if (v[0] == \"{\") and (v[-1] == \"}\"):\n v = v.lstrip(\"{\")\n v = v.rstrip(\"}\")\n v_array = v.split(\"|\")\n v_array = [i.strip() for i in v_array]\n return v_array\n return v\n\ndef mm_to_meters(v):\n if v < 0.01:\n return v * 1000\n return v\n\ndef clean_dimension(d, field, v):\n if is_number(v):\n if field == \"weight\":\n d[field] = float(v) / 1000.0\n else:\n d[field] = mm_to_meters(float(v))\n \ndef clean_year(d, field, v):\n d[field] = v[0:4]\n\ndef parse_array2(v):\n if (v[0] == \"{\") and (v[-1] == \"}\"):\n v = v.lstrip(\"{\")\n v = v.rstrip(\"}\")\n v_array = v.split(\"|\")\n v_array = [i.strip() for i in v_array]\n return (True, v_array)\n return (False, v)\n\ndef ensure_not_array(v):\n (is_array, v) = parse_array(v)\n if is_array:\n return v[0]\n return v\n\ndef ensure_array(v):\n (is_array, v) = parse_array2(v)\n if is_array:\n return v\n return [v]\n\ndef ensure_float(v):\n if is_number(v):\n return float(v)\n\ndef ensure_int(v):\n if is_number(v):\n return int(v)\n\ndef ensure_year_array(val):\n #print \"val:\", val\n vals = ensure_array(val)\n year_vals = []\n for v in vals:\n v = v[0:4]\n v = int(v)\n if v:\n year_vals.append(v)\n return year_vals\n\ndef empty_val(val):\n val = val.strip()\n return (val == \"NULL\") or (val == \"\")\n\ndef years(row, start_field, end_field):\n start_val = row[start_field]\n end_val = row[end_field]\n\n if empty_val(start_val) or empty_val(end_val):\n return []\n\n start_years = ensure_year_array(start_val)\n if start_years:\n start_years = sorted(start_years)\n end_years = ensure_year_array(end_val)\n if end_years:\n end_years = sorted(end_years)\n all_years = []\n if start_years and end_years:\n #print start_years\n #print end_years\n for i in range(0, min(len(start_years), len(end_years))):\n for y in range(start_years[i], end_years[i]+1):\n all_years.append(y)\n return all_years\n\n\ndef process_file_autos(input_file):\n input_data = csv.DictReader(open(input_file))\n autos = []\n skip_lines(input_data, 3)\n for row in input_data:\n auto = {}\n model_years = {}\n production_years = {}\n dimensions = {}\n for field, val in row.iteritems():\n if field not in fields or empty_val(val):\n continue\n if field in [\"bodyStyle_label\", \"class_label\", \"layout_label\"]:\n val = val.lower()\n val = strip_automobile(val)\n val = strip_city(val)\n val = val.strip()\n val = parse_array(val)\n if field in [\"length\", \"width\", \"height\", \"weight\", \"wheelbase\"]:\n clean_dimension(dimensions, field_map[field], val)\n elif field in [\"modelStartYear\", \"modelEndYear\"]:\n clean_year(model_years, field_map[field], val)\n elif field in [\"productionStartYear\", \"productionEndYear\"]:\n clean_year(production_years, field_map[field], val)\n else:\n auto[field_map[field]] = val\n if dimensions:\n auto['dimensions'] = dimensions\n auto['modelYears'] = years(row, 'modelStartYear', 'modelEndYear')\n auto['productionYears'] = years(row, 'productionStartYear', 'productionEndYear')\n autos.append(auto)\n return autos\n\ndef insert_autos(infile, db):\n data = process_file_autos(infile)\n # Add your code here. Insert the data in one command.\n db.autos.insert_many(data)\n\ndb = get_db()\n#insert_autos('../autos.csv', db)\ndb.autos.find_one()\n\ndb.autos.count()",
"Using mongoimport\nDocumentation for mongoimport can be found here.\nThe following command is used \nmongoimport -db dbname -c collectionname --file input-file.json\nmongoimport --help\nIf no hostname and credentials are supplied, mongoimport will try to connect to the default localhost:27017\nOperators\n\nsame idea as in programming languages\nsame syntax as field names\ndistinguish operators from fields using $\n\nRange Queries\n\nInequality operators\n$gt\n$lt\n$gte\n$lte\n$ne\n\n\n\nUsing dot in the names we can query nested documents",
"list(city for city in db.autos.find())\n\nquery = {'dimensions.weight': {\"$gt\": 2000}}\ndb.autos.count(query)\n\n#using ASCII to query for string types\nquery = {'name': {\"$gte\": \"H\", \"$lte\": \"Z\"}}\nprint db.autos.count(query)\nprint db.autos.find_one(query)",
"These operators can also be used with datetime objects\n$exists\nAllows us to query and find the structure of the documents",
"def printCountAndOne(collection, query):\n print \"***\"\n print collection.count(query)\n pprint.pprint(collection.find_one(query))\n\nprint db.autos.count()\n\nprintCountAndOne(db.autos, {'assembly': {\"$exists\": 1}})\n\nprintCountAndOne(db.autos, {'assembly': {\"$exists\": 0}})",
"$regex\nMongoDB $regex Manual\nOfficial Python Regular Expression HOWTO.",
"printCountAndOne(db.autos, {\"assembly\": {\"$regex\": \"Japan\"}})",
"Querying Arrays Using Scalars\nMongoDB queries inside arrays using scalars\n$in\nContaining at least one of the array values",
"printCountAndOne(db.autos, {\"productionYears\": {\"$in\": [1986,1987,1988, 1992]}})",
"$all\nContaining all of the values",
"printCountAndOne(db.autos, {\"productionYears\": {\"$all\": [1986,1987,1988, 1992]}})",
"updates",
"from random import randint\nnew_name = \"test {}\".format(randint(0,999))\nprint \"new name is {}\".format(new_name)\n\nauto = db.autos.find_one({\"productionYears\": {\"$in\": [1986,1987,1988, 1992]}})\nauto['name'] = new_name\ndb.autos.save(auto)\n\ndb.autos.find_one({\"name\": {\"$eq\": new_name}})",
"set unset",
"#if exists then update else insert\ndb.autos.update_one({\"assembly\": {\"$regex\": \"Japan\"}}, {\"$set\": {\"test\": \"japanese\"}})\n\nprint db.autos.count({\"test\": \"japanese\"})\n\n#if exists then remove field else ignore\ndb.autos.update_one({\"test\": \"japanese\"}, {\"$unset\": {\"test\": \"\"}})\n\nprint db.autos.count({\"test\": \"japanese\"})",
"NOTE Need to remember that the second argument must have operator $set or $unset. If that is not there then the entire document found by the first one would be replace by what is passed as the second argument.",
"db.autos.update_many({\"assembly\": {\"$regex\": \"Japan\"}}, {\"$set\": {\"test\": \"japanese\"}})\n\nprint db.autos.count({\"test\": \"japanese\"})\n\n#db.autos.drop()\nquery = {\"test\": \"japanese\"}\n#print db.autos.delete_many(query)\n\nprint db.autos.count()",
"PROBLEM SET STARTS HERE\nIn this problem set you work with another type of infobox data, audit it,\nclean it, come up with a data model, insert it into MongoDB and then run some\nqueries against your database. The set contains data about Arachnid class\nanimals.\nYour task in this exercise is to parse the file, process only the fields that\nare listed in the FIELDS dictionary as keys, and return a list of dictionaries\nof cleaned values. \nThe following things should be done:\n- keys of the dictionary changed according to the mapping in FIELDS dictionary\n- trim out redundant description in parenthesis from the 'rdf-schema#label'\n field, like \"(spider)\"\n- if 'name' is \"NULL\" or contains non-alphanumeric characters, set it to the\n same value as 'label'.\n- if a value of a field is \"NULL\", convert it to None\n- if there is a value in 'synonym', it should be converted to an array (list)\n by stripping the \"{}\" characters and splitting the string on \"|\". Rest of the\n cleanup is up to you, e.g. removing \"*\" prefixes etc. If there is a singular\n synonym, the value should still be formatted in a list.\n- strip leading and ending whitespace from all fields, if there is any\n- the output structure should be as follows:\n[ { 'label': 'Argiope',\n 'uri': 'http://dbpedia.org/resource/Argiope_(spider)',\n 'description': 'The genus Argiope includes rather large and spectacular spiders that often ...',\n 'name': 'Argiope',\n 'synonym': [\"One\", \"Two\"],\n 'classification': {\n 'family': 'Orb-weaver spider',\n 'class': 'Arachnid',\n 'phylum': 'Arthropod',\n 'order': 'Spider',\n 'kingdom': 'Animal',\n 'genus': None\n }\n },\n { 'label': ... , }, ...\n]",
"import codecs\nimport csv\nimport json\nimport pprint\nimport re\n\nDATAFILE = 'arachnid.csv'\nFIELDS ={'rdf-schema#label': 'label',\n 'URI': 'uri',\n 'rdf-schema#comment': 'description',\n 'synonym': 'synonym',\n 'name': 'name',\n 'family_label': 'family',\n 'class_label': 'class',\n 'phylum_label': 'phylum',\n 'order_label': 'order',\n 'kingdom_label': 'kingdom',\n 'genus_label': 'genus'}\n \n \ndef remove_brackets_part(string):\n pattern = re.compile(r\"\\([^)]*?\\)\")\n return pattern.sub(\"\", string).strip()\n\n\ndef process_file(filename, fields):\n\n process_fields = fields.values()\n data = []\n with open(filename, \"r\") as f:\n reader = csv.DictReader(f)\n for i in range(3):\n l = reader.next()\n\n for line in reader:\n for key, value in fields.iteritems():\n if key != value:\n line[value] = line[key]\n\n if value in line:\n line[value] = line[value].strip()\n\n line['label'] = remove_brackets_part(line['label'])\n\n if ('name' not in line) or (line['name'] is None) or line['name'].isalnum():\n line['name'] = line['label']\n\n if 'synonym' in line:\n if line['synonym'] == 'NULL':\n line['synonym'] = None\n else:\n line['synonym'] = parse_array(line['synonym'])\n\n for key in line.keys():\n if (key not in line) or (line[key] == 'NULL'):\n line[key] = None\n\n data.append({'label': line['label'],\n 'uri': line['uri'],\n 'description': line['description'],\n 'name': line['name'],\n 'synonym': line['synonym'],\n 'classification': {\n 'family': line['family'],\n 'class': line['class'],\n 'phylum': line['phylum'],\n 'order': line['order'],\n 'kingdom': line['kingdom'],\n 'genus': line['genus']\n }\n })\n return data\n\n\ndef parse_array(v):\n if (v[0] == \"{\") and (v[-1] == \"}\"):\n v = v.lstrip(\"{\")\n v = v.rstrip(\"}\")\n v_array = v.split(\"|\")\n v_array = [i.strip() for i in v_array]\n return v_array\n return [v]\n\ndef test():\n data = process_file(DATAFILE, FIELDS)\n print \"Your first entry:\"\n pprint.pprint(data[0])\n first_entry = {\n \"synonym\": None, \n \"name\": \"Argiope\", \n \"classification\": {\n \"kingdom\": \"Animal\", \n \"family\": \"Orb-weaver spider\", \n \"order\": \"Spider\", \n \"phylum\": \"Arthropod\", \n \"genus\": None, \n \"class\": \"Arachnid\"\n }, \n \"uri\": \"http://dbpedia.org/resource/Argiope_(spider)\", \n \"label\": \"Argiope\", \n \"description\": \"The genus Argiope includes rather large and spectacular spiders that often have a strikingly coloured abdomen. These spiders are distributed throughout the world. Most countries in tropical or temperate climates host one or more species that are similar in appearance. The etymology of the name is from a Greek name meaning silver-faced.\"\n }\n\n assert len(data) == 76\n assert data[0] == first_entry\n assert data[17][\"name\"] == \"Ogdenia\"\n assert data[48][\"label\"] == \"Hydrachnidiae\"\n assert data[14][\"synonym\"] == [\"Cyrene Peckham & Peckham\"]\n\ntest()\n\ndb = get_db()\n\nwith open('arachnid.json') as f:\n data = json.loads(f.read())\n db.arachnid.insert(data, db)",
"For this exercise, the arachnid data is already in the database. You have been\ngiven the task of including 'binomialAuthority' information in the records.\nYou will do this by processing the arachnid.csv to extract binomial authority\ndata and then using this data to update the corresponding data base records.\nThe following things should be done in the function add_field:\n- process the csv file and extract 2 fields - 'rdf-schema#label' and\n 'binomialAuthority_label'\n- clean up the 'rdf-schema#label' the same way as in the first exercise,\n removing redundant \"(spider)\" suffixes\n- return a dictionary with the cleaned 'rdf-schema#label' field values as keys, \n and 'binomialAuthority_label' field values as values\n- if 'binomialAuthority_label' is \"NULL\" for a row in the csv, skip the item\nThe following should be done in the function update_db:\n- query the 'label' field in the database using rdf-schema#label keys from the\n data dictionary\n- update the documents by adding a new item under 'classification' with the key\n 'binomialAuthority' and the binomialAuthority_label value from the data\n dictionary as the value\nFor item {'Argiope': 'Jill Ward'} in the data dictionary, the resulting document structure \nshould look like this:\n{ 'label': 'Argiope',\n 'uri': 'http://dbpedia.org/resource/Argiope_(spider)',\n 'description': 'The genus Argiope includes rather large and spectacular spiders that often ...',\n 'name': 'Argiope',\n 'synonym': [\"One\", \"Two\"],\n 'classification': {\n 'binomialAuthority' : 'Jill Ward'\n 'family': 'Orb-weaver spider',\n 'class': 'Arachnid',\n 'phylum': 'Arthropod',\n 'order': 'Spider',\n 'kingdom': 'Animal',\n 'genus': None\n }\n}",
"DATAFILE = 'arachnid.csv'\nFIELDS ={'rdf-schema#label': 'label',\n 'binomialAuthority_label': 'binomialAuthority'}\n\ndef add_field(filename, fields):\n \"\"\"\n Complete this function to set up a dictionary for adding binomialAuthority\n information to the database.\n \"\"\"\n process_fields = fields.keys()\n data = {}\n with open(filename, \"r\") as f:\n reader = csv.DictReader(f)\n for i in range(3):\n l = reader.next()\n \n for line in reader:\n \n \n binomialAuthority_label = line['binomialAuthority_label']\n \n if binomialAuthority_label == 'NULL':\n continue\n \n label = remove_brackets_part(line['rdf-schema#label'])\n data[label] = binomialAuthority_label\n\n\n return data\n\n\ndef update_db(data, db):\n \"\"\"\n Use the dictionary you generated from add_field to update the database.\n \"\"\"\n for key, value in data.iteritems():\n pprint.pprint(\"{}:{}\".format(key, value))\n db.arachnid.update_many({\"label\": {\"$eq\": key}}, {\"$set\": {\"classification.binomialAuthority\": value}})\n \n\ndef testFinal():\n # Please change only the add_field and update_db functions!\n # Changes done to this function will not be taken into account\n # when doing a Test Run or Submit, they are just for your own reference\n # and as an example for running this code locally!\n \n data = add_field(DATAFILE, FIELDS)\n \n from pymongo import MongoClient\n client = MongoClient(\"mongodb://localhost:27017\")\n db = client.examples\n\n update_db(data, db)\n\n updated = db.arachnid.find_one({'label': 'Opisthoncana'})\n assert updated['classification']['binomialAuthority'] == 'Embrik Strand'\n pprint.pprint(data)\n\ntestFinal()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
milancurcic/lunch-bytes
|
Fall_2018/LB22/NeuralNetDemo.ipynb
|
cc0-1.0
|
[
"Create and test a simple neural network\n Lunch Bytes (LB22) • October 26, 2018 • Matt Grossi (matthew.grossi at rsmas.miami.edu) \nThis document provides a practical follow-up to my talk, Peeking under the hood of an artificial neural network.\n\nLet's set up a simple neural network!\nFirst we define functions for the routines we'll be using frequently. The workflow for [most of] these come from the presentation slides.\nDisclaimer: There are undoubtedly far more efficient ways to carry out these operations. I've chosen overly descriptive variables names to be as descriptive (and hopefully as helpful) as possible. I have not thoroughly checked this over for correct performance, typos, etc.",
"import numpy as np\nimport pandas as pd\nfrom sklearn import model_selection\n\ndef xfer(wsum):\n out = 1.0 / (1.0 + np.exp(-wsum))\n return out\n\ndef ErrHid(output, weights, outerr):\n dt = np.dot(weights, outerr)\n ErrorHid = output * (1.0 - output) * dt\n return ErrorHid\n\ndef ErrOut(output, targets):\n ErrorOut = output * (1.0 - output) * (targets - output)\n return ErrorOut\n\ndef WgtAdj(weights, responsibities, values, learnrate):\n weights += (learnrate * np.outer(values, responsibilities))\n return weights\n\ndef BiasAdj(bias, responsibilities, learnrate):\n bias += (learn * responsibilities)\n return bias\n\ndef run(examples, targets, weightsI2H, weightsH2O, biasHID, biasOUT):\n HiddenLayerInput = np.dot(examples, weightsI2H) + biasHID\n HiddenLayerOutput = xfer(wsum=HiddenLayerInput)\n OutputLayerInput = np.dot(HiddenLayerOutput, weightsH2O) + biasOUT\n Output = xfer(wsum=OutputLayerInput)\n return Output\n\ndef nnet(examples, targets, hidden, learn):\n \n # Set number of attributes passed: number of columns in 'examples'\n NumAtt = examples.shape[1]\n \n # Set number of output neurons: number of columns in 'targets'\n NumOut = train_targets.shape[1]\n \n # Randomly initialize weight matrices (replace any zeros with 0.1)\n weightsI2H = np.random.uniform(-1,1, size=(NumAtt,hidden))\n weightsI2H[weightsI2H==0] = 0.1\n weightsH2O = np.random.uniform(-1,1,size=(hidden,NumOut))\n weightsH2O[weightsH2O==0] = 0.1\n \n # Randomly initialize biases for hidden and output layer neurons\n biasHID = np.random.uniform(-1,1,size=hidden)\n biasOUT = np.random.uniform(-1,1,size=NumOut)\n \n # Loop to pass each training example\n for ex in range(len(examples)):\n \n # Forward propagate examples\n HiddenLayerInput = np.dot(examples[ex,:], weightsI2H) + biasHID\n HiddenLayerOutput = xfer(wsum=HiddenLayerInput)\n\n OutputLayerInput = np.dot(HiddenLayerOutput, weightsH2O) + biasOUT\n Output = xfer(wsum=OutputLayerInput)\n\n # Back-proagate error: calculaterror responsibilities for output and hidden layer neurons\n OutputErr = ErrOut(output=Output, targets=targets[ex,:])\n HiddenErr = ErrHid(output=HiddenLayerOutput, weights=weightsH2O, outerr=OutputErr)\n\n # Adjust weights\n weightsI2H += learn * np.outer(examples[ex,:], HiddenErr)\n weightsH2O += learn * np.outer(HiddenLayerOutput, OutputErr)\n \n biasHID += learn * HiddenErr\n biasOUT += learn * OutputErr\n \n # Correctly classified?\n if (train_targets[ex,0] < train_targets[ex,1]) == (Output[0] < Output[1]):\n print('Correct')\n else:\n print('Incorrect')\n \n return weightsI2H, weightsH2O, biasHID, biasOUT",
"Let's test this on a data set from the UC Irving Machine Learning Respository (https://archive.ics.uci.edu/ml/index.php). This handy respository contains hundreds of pre-classified data sets that are ideal for testing machine learning algorithms.\nConsider the banknote authentication data set. The documentation states that it contains 1372 examples of banknote-like specimens that are classified as either authentic (class 1) or not authentic (class 0) based on four attributes: variance, skewness, curtosis, and entropy of the image.",
"data = pd.read_csv(\"~/Documents/Classes/RSMAS/MachLearn/Project1/banknote.csv\",\n names=['var', 'skew', 'curt', 'ent', 'class-yes'])\n\ndata.head(3)\n\ndata.tail(3)",
"Before feeding a neural net, we need to set up our data. First, we note that these data are sorted by class (the last column, 0s and 1s), as is often the case with pre-classified data. It is good practice to shuffle the data to help ensure that the distribution of classes is roughly the same in both the training and testing subsets.",
"data = data.sample(frac=1).reset_index(drop=True)",
"We can think of these data as having two classes: authentic and not authentic. Our data set already contains a column that contains 1s whenever the example is in the authentic class. Now let's add a column that has a 1 when the example is in the not authentic class. Then print the first few lines to make sure we have what we think we have.",
"data['class-no'] = np.where(data['class-yes']==0, 1, 0)\n\ndata.head()",
"Next we need to normalize our data such that all columns are between 0 and 1:",
"data_norm = (data - data.min(axis=0)) / (data.max(axis=0) - data.min(axis=0))",
"Now, split the data into training and testing subsets. Here we choose to use 80% of the examples for training and 20% for testing. Finally, separate into examples, which will contain the attributes, and the targets, which will contain the class flag.",
"train, test = model_selection.train_test_split(data_norm, test_size = 0.2)\n\ntrain_examples = np.array(train.iloc[:,0:4], dtype=np.float64)\ntrain_targets = np.array(train[['class-yes', 'class-no']], dtype=np.float64)\n\ntest_examples = np.array(test.iloc[:,0:4], dtype=np.float64)\ntest_targets = np.array(test[['class-yes', 'class-no']], dtype=np.float64)",
"Finally, replace targets 1 and 0 with 0.8 and 0.2. (Why?)",
"#train_targets[np.where(train_targets==1)] = 0.8\n#train_targets[np.where(train_targets==0)] = 0.2\n\n#test_targets[np.where(test_targets==1)] = 0.8\n#test_targets[np.where(test_targets==0)] = 0.2",
"Now train the neural net!",
"I2H, H2O, bHID, bOUT = nnet(examples=train_examples, targets=train_targets,\n hidden=5, learn=0.05)",
"For instructive purposes, the function prints whether each example is correctly classified or not. One can see the variation in performance from example to example. Keep in mind that after each incorrect classification, slight adjustments are made to the internal weights.\nThe function 'nnet' loops through every training example once, representing one training epoch. In practice, the network would be trained over many (sometimes hundreds) of epochs, depending on the number of examples and the complexity of the data. At the end of each epoch, the model is run on the testing data and the mean squared error (MSE) is calculated over all of these training examples to assess the model performance. As the model learns, the MSE should decrease.\nJust for fun, let's run our neural net on the test examples. Notice that 'nnet' outputs a weight matrix and bias vector for each layer. All we need to do to run the model is forward-propagate the testing examples using these final weights and biases. No weight adjustments will be made, because we are running a trained model. See the 'run' function above.",
"out = run(examples=test_examples, targets=test_targets,\n weightsI2H=I2H, weightsH2O=H2O, biasHID=bHID, biasOUT=bOUT)\n\nout[0:5,]",
"What do these numbers mean? Remember that our target matrix consists of 0.8s and 0.2s (originally 1s and 0s) and correspond to whether the example was in the class authentic or not authentic. Our neural network had 2 output neurons, one for each class. The columns of 'out' therefore represent these two classes, in the same order as in the 'data'.\nBecause this is a simple classification problem, we can choose for each example the class (i.e., column) with the higher number:",
"# Predicted classes\npredicted_classes = np.array(pd.DataFrame(out).idxmax(axis=1))\nprint(predicted_classes)\n\n# Target classes\ntarget_classes = np.array(pd.DataFrame(test_targets).idxmax(axis=1))\nprint(target_classes)",
"Remember that python uses zero-based indexing. Thus, a 0 here means the first column contains the highest number, meaning the example is authentic. This is admittedly a little confusing. How does this compare to the actual testing data? The neural net is correct if the predicted class agrees with the actual class:",
"sum(target_classes == predicted_classes)/len(test_targets) * 100",
"Not well! In one epoch, the network is still pretty random. If the two classes are equally represented, then the network will achive 50% accuracy by predicting the same class every time, which is hardly impressive. Here it correctly classified 54% of the examples. But remember, this is only one epoch, and often many are needed to properly train a neural net.\nThis data set is particularly clean and linearly separable, so it should be predicted with relative ease. Indeed, after 200 or so epochs, this simple neural net is able to achieve >99% accuracy on testing data.\nThat's all there is to it!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
santoshphilip/eppy
|
docs/HVAC_Tutorial.ipynb
|
mit
|
[
"HVAC Loops\nConceptual Introduction to HVAC Loops\nEppy builds threee kinds of loops for the energyplus idf file:\n\nPlant Loops\nCondensor Loops\nAir Loops\n\nAll loops have two halves:\n\nSupply side\nDemand Side\n\nThe supply side provides the energy to the demand side that needs the energy. So the end-nodes on the supply side connect to the end-nodes on the demand side. \nThe loop is made up of branches connected to each other. A single branch can lead to multiple branches through a splitter component. Multiple branches can lead to a single branch through a mixer component. \nEach branch is made up of components connected in series (in a line)\nEppy starts off by building the shape or topology of the loop by connecting the branches in the right order. The braches themselves have a single component in them, that is just a place holder. Usually it is a pipe component. In an air loop it would be a duct component.\nThe shape of the loop for the supply or demand side is quite simple. \nIt can be described in the following manner for the supply side\n\nThe supply side starts single branch leads to a splitter\nThe splitter leads to multiple branches\nthese multiple branches come back and join in a mixer\nthe mixer leads to a single branch that becomes end of the suppply side\n\nFor the demand side we have:\n\nThe demand side starts single branch leads to a splitter\nThe splitter leads to multiple branches\nthese multiple branches come back and join in a mixer\nthe mixer leads to a single branch that becomes end of the demand side\n\nThe two ends of the supply side connect to the two ends of the demand side.\nDiagramtically the the two sides of the loop will look like this::\nIn eppy you could embody this is a list",
"supplyside = ['start_brandh', [ 'branch1', 'branch2', 'branch3'], 'end_branch']\ndemandside = ['d_start_brandh', ['d_branch1', 'd_branch2', 'd_branch3'], 'd_end_branch']\n",
"Eppy will build the build the shape/topology of the loop using the two lists above. Each branch will have a placeholder component, like a pipe or a duct::\nNow we will have to replace the placeholder with the real components that make up the loop. For instance, branch1 should really have a pre-heat coil leading to a supply fan leading to a cooling coil leading to a heating coil::\nEppy lets you build a new branch and you can replace branch1 with new_branch\nIn this manner we can build up the entire loop with the right components, once the initial toplogy is right\nBuilding a Plant loops\nEppy can build up the topology of a plant loop using single pipes in a branch. Once we do that the simple branch in the loop we have built can be replaced with a more complex branch.\nLet us try this out ans see how it works.\nBuilding the topology of the loop",
"# you would normaly install eppy by doing\n# python setup.py install\n# or\n# pip install eppy\n# or\n# easy_install eppy\n\n# if you have not done so, uncomment the following three lines\nimport sys\n# pathnameto_eppy = 'c:/eppy'\npathnameto_eppy = '../'\nsys.path.append(pathnameto_eppy) \n\n\nfrom eppy.modeleditor import IDF\nfrom eppy import hvacbuilder\n\nfrom io import StringIO\niddfile = \"../eppy/resources/iddfiles/Energy+V7_0_0_036.idd\"\nIDF.setiddname(iddfile)\n\n\n# make the topology of the loop\nidf = IDF(StringIO('')) # makes an empty idf file in memory with no file name\nloopname = \"p_loop\"\nsloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4'] # supply side of the loop\ndloop = ['db0', ['db1', 'db2', 'db3'], 'db4'] # demand side of the loop\nhvacbuilder.makeplantloop(idf, loopname, sloop, dloop)\nidf.saveas(\"hhh1.idf\")\n",
"We have made plant loop and saved it as hhh1.idf.\nNow let us look at what the loop looks like. \nDiagram of the loop\nLet us use the script \"eppy/useful_scripts/loopdiagrams.py\" to draw this diagram\nSee Generating a Loop Diagram page for details on how to do this\nBelow is the diagram for this simple loop\nNote: the supply and demnd sides are not connected in the diagram, but shown seperately for clarity",
"import ex_inits #no need to know this code, it just shows the image below\nfor_images = ex_inits\nfor_images.display_png(for_images.plantloop1) # display the image below\n",
"Modifying the topology of the loop\nLet us make a new branch and replace the exisiting branch \nThe existing branch name is \"sb0\" and it contains a single pipe component sb0_pipe.\nLet us replace it with a branch that has a chiller that is connected to a pipe which is turn connected to another pipe. So the connections in the new branch would look like \"chiller-> pipe1->pipe2\"",
"# make a new branch chiller->pipe1-> pipe2\n\n# make a new pipe component\npipe1 = idf.newidfobject(\"PIPE:ADIABATIC\", 'np1')\n\n# make a new chiller\nchiller = idf.newidfobject(\"Chiller:Electric\".upper(), 'Central_Chiller')\n\n# make another pipe component\npipe2 = idf.newidfobject(\"PIPE:ADIABATIC\", 'np2')\n\n# get the loop we are trying to modify\nloop = idf.getobject('PLANTLOOP', 'p_loop') # args are (key, name)\n# get the branch we are trying to modify\nbranch = idf.getobject('BRANCH', 'sb0') # args are (key, name)\nlistofcomponents = [chiller, pipe1, pipe2] # the new components are connected in this order\n",
"Now we are going to try to replace branch with the a branch made up of listofcomponents\n\nWe will do this by calling the function replacebranch\nCalling replacebranch can throw an exception WhichLoopError\nIn a moment, you will see why this exception is important",
"try:\n newbr = hvacbuilder.replacebranch(idf, loop, branch, listofcomponents, fluid='Water')\nexcept hvacbuilder.WhichLoopError as e:\n print(e)\n",
"The above code throws the exception. It says that the idfobject CHILLER:ELECTRIC - Central_Chiller has three possible connections. The chiller has inlet outlet nodes for the following\n\nChilled water\nCondenser\nHeat Recovery\n\neppy does not know which one to connect to, and it needs your help. We know that the chiller needs to be connected to the chilled water inlet and outlet. Simply copy Chilled_Water_ from the text in the exception and paste as shown in the code below. (make sure you copy it exactly. eppy is a little nerdy about that)",
"# instead of passing chiller to the function, we pass a tuple (chiller, 'Chilled_Water_').\n# This lets eppy know where the connection should be made.\n# The idfobject pipe does not have this ambiguity. So pipes do not need this extra information\nlistofcomponents = [(chiller, 'Chilled_Water_'), pipe1, pipe2]\n\ntry:\n newbr = hvacbuilder.replacebranch(idf, loop, branch, listofcomponents, fluid='Water')\nexcept Exception as e:\n print(e)\nelse: # else will run only if the try suceeds\n print(\"no exception was thrown\")\n\nidf.saveas(\"hhh_new.idf\")\n",
"Tagential note: The \"try .. except .. else\" statement is useful here. If you have not run across it before, take a look at these two links\n\nhttp://shahriar.svbtle.com/the-possibly-forgotten-optional-else-in-python-try-statement\nhttps://docs.python.org/2/tutorial/errors.html\n\nWe have saved this as file \"hhh_new.idf\".\nLet us draw the diagram of this file. (run this from eppy/eppy folder)",
"import ex_inits #no need to know this code, it just shows the image below\nfor_images = ex_inits\nfor_images.display_png(for_images.plantloop2) # display the image below\n",
"This diagram shows the new components in the branch\nWork flow with WhichLoopError\nWhen you are writing scripts don't bother to use try .. except for WhichLoopError. \n\nSimply allow the exception to be raised. \nUse the information in the exception to update your code\nYou may have to do this a couple of times in your script.\nIn a sense you are letting eppy tell you how to update the script.\n\nQuestion: I am writing an application using eppy, not just a script. The above workflow does not work for me\nResponse: Aha ! If that is the case, open an issue in github/eppy. We are lazy people. We don't write code unless it is needed :-)\nTraversing the loop\nIt would be nice to move through the loop using functions \"nextnode()\" and \"prevnode()\"\nEppy indeed has such functions\nLet us try to traverse the loop above.",
"# to traverse the loop we are going to call some functions ex_loopdiagrams.py, \n# the program that draws the loop diagrams.\nfrom eppy.useful_scripts import loopdiagram\nfname = 'hhh_new.idf'\niddfile = '../eppy/resources/iddfiles/Energy+V8_0_0.idd'\nedges = loopdiagram.getedges(fname, iddfile)\n# edges are the lines that draw the nodes in the loop. \n# The term comes from graph theory in mathematics\n",
"The above code gets us the edges of the loop diagram. Once we have the edges, we can traverse through the diagram. Let us start with the \"Central_Chiller\" and work our way down.",
"from eppy import walk_hvac\nfirstnode = \"Central_Chiller\"\nnextnodes = walk_hvac.nextnode(edges, firstnode)\nprint(nextnodes)\n\n\nnextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n\n\nnextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n\n\nnextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n",
"This leads us to three components -> ['sb1_pipe', 'sb2_pipe', 'sb3_pipe']. Let us follow one of them",
"nextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n\n\nnextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n\n\nnextnodes = walk_hvac.nextnode(edges, nextnodes[0])\nprint(nextnodes)\n",
"We have reached the end of this branch. There are no more components. \nWe can follow this in reverse using the function prevnode()",
"lastnode = 'sb4_pipe'\nprevnodes = walk_hvac.prevnode(edges, lastnode)\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n\n\nprevnodes = walk_hvac.prevnode(edges, prevnodes[0])\nprint(prevnodes)\n",
"All the way to where the loop ends\nBuilding a Condensor loop\nWe build the condensor loop the same way we built the plant loop. Pipes are put as place holders for the components. Let us build a new idf file with just a condensor loop in it.",
"condensorloop_idf = IDF(StringIO('')) \nloopname = \"c_loop\"\nsloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4'] # supply side\ndloop = ['db0', ['db1', 'db2', 'db3'], 'db4'] # demand side\ntheloop = hvacbuilder.makecondenserloop(condensorloop_idf, loopname, sloop, dloop)\ncondensorloop_idf.saveas(\"c_loop.idf\")\n",
"Again, just as we did in the plant loop, we can change the components of the loop, by replacing the branchs and traverse the loop using the functions nextnode() and prevnode()\nBuilding an Air Loop\nBuilding an air loop is similar to the plant and condensor loop. The difference is that instead of pipes , we have ducts as placeholder components. The other difference is that we have zones on the demand side.",
"airloop_idf = IDF(StringIO('')) \nloopname = \"a_loop\"\nsloop = ['sb0', ['sb1', 'sb2', 'sb3'], 'sb4'] # supply side of the loop\ndloop = ['zone1', 'zone2', 'zone3'] # zones on the demand side\nhvacbuilder.makeairloop(airloop_idf, loopname, sloop, dloop)\nairloop_idf.saveas(\"a_loop.idf\")\n",
"Again, just as we did in the plant and condensor loop, we can change the components of the loop, by replacing the branchs and traverse the loop using the functions nextnode() and prevnode()"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
tensorflow/probability
|
tensorflow_probability/examples/jupyter_notebooks/JointDistributionAutoBatched_A_Gentle_Tutorial.ipynb
|
apache-2.0
|
[
"Auto-Batched Joint Distributions: A Gentle Tutorial\nCopyright 2020 The TensorFlow Authors.\nLicensed under the Apache License, Version 2.0 (the \"License\");",
"#@title Licensed under the Apache License, Version 2.0 (the \"License\"); { display-mode: \"form\" }\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.",
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n <td>\n <a target=\"_blank\" href=\"https://www.tensorflow.org/probability/examples/Modeling_with_JointDistribution\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Modeling_with_JointDistribution.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n </td>\n <td>\n <a target=\"_blank\" href=\"https://github.com/tensorflow/probability/blob/main/tensorflow_probability/examples/jupyter_notebooks/Modeling_with_JointDistribution.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n </td>\n <td>\n <a href=\"https://storage.googleapis.com/tensorflow_docs/probability/tensorflow_probability/examples/jupyter_notebooks/Modeling_with_JointDistribution.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n </td>\n</table>\n\nIntroduction\nTensorFlow Probability (TFP) offers a number of JointDistribution abstractions that make probabilistic inference easier by allowing a user to easily express a probabilistic graphical model in a near-mathematical form; the abstraction generates methods for sampling from the model and evaluating the log probability of samples from the model. In this tutorial, we review \"autobatched\" variants, which were developed after the original JointDistribution abstractions. Relative to the original, non-autobatched abstractions, the autobatched versions are simpler to use and more ergonomic, allowing many models to be expressed with less boilerplate. In this colab, we explore a simple model in (perhaps tedious) detail, making clear the problems autobatching solves, and (hopefully) teaching the reader more about TFP shape concepts along the way.\nPrior to the introduction of autobatching, there were a few different variants of JointDistribution, corresponding to different syntactic styles for expressing probabilistic models: JointDistributionSequential, JointDistributionNamed, andJointDistributionCoroutine. Auobatching exists as a mixin, so we now have AutoBatched variants of all of these. In this tutorial, we explore the differences between JointDistributionSequential and JointDistributionSequentialAutoBatched; however, everything we do here is applicable to the other variants with essentially no changes.\nDependencies & Prerequisites",
"#@title Import and set ups{ display-mode: \"form\" }\n\nimport functools\nimport numpy as np\n\nimport tensorflow.compat.v2 as tf\ntf.enable_v2_behavior()\n\nimport tensorflow_probability as tfp\n\ntfd = tfp.distributions",
"Prerequisite: A Bayesian Regression Problem\nWe'll consider a very simple Bayesian regression scenario:\n$$\n\\begin{align}\nm & \\sim \\text{Normal}(0, 1) \\\nb & \\sim \\text{Normal}(0, 1) \\\nY & \\sim \\text{Normal}(mX + b, 1)\n\\end{align}\n$$\nIn this model, m and b are drawn from standard normals, and the observations Y are drawn from a normal distribution whose mean depends on the random variables m and b, and some (nonrandom, known) covariates X. (For simplicity, in this example, we assume the scale of all random variables is known.)\nTo perform inference in this model, we'd need to know both the covariates X and the observations Y, but for the purposes of this tutorial, we'll only need X, so we define a simple dummy X:",
"X = np.arange(7)\nX",
"Desiderata\nIn probabilistic inference, we often want to perform two basic operations:\n- sample: Drawing samples from the model.\n- log_prob: Computing the log probability of a sample from the model.\nThe key contribution of TFP's JointDistribution abstractions (as well as of many other approaches to probabilistic programming) is to allow users to write a model once and have access to both sample and log_prob computations.\nNoting that we have 7 points in our data set (X.shape = (7,)), we can now state the desiderata for an excellent JointDistribution:\n\nsample() should produce a list of Tensors having shape [(), (), (7,)], corresponding to the scalar slope, scalar bias, and vector observations, respectively.\nlog_prob(sample()) should produce a scalar: the log probability of a particular slope, bias, and observations.\nsample([5, 3]) should produce a list of Tensors having shape [(5, 3), (5, 3), (5, 3, 7)], representing a (5, 3)-batch of samples from the model.\nlog_prob(sample([5, 3])) should produce a Tensor with shape (5, 3).\n\nWe'll now look at a succession of JointDistribution models, see how to achieve the above desiderata, and hopefully learn a little more about TFP shapes along the way. \nSpoiler alert: The approach that satisfies the above desiderata without added boilerplate is autobatching. \nFirst Attempt; JointDistributionSequential",
"jds = tfd.JointDistributionSequential([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y\n])",
"This is more or less a direct translation of the model into code. The slope m and bias b are straightforward. Y is defined using a lambda-function: the general pattern is that a lambda-function of $k$ arguments in a JointDistributionSequential (JDS) uses the previous $k$ distributions in the model. Note the \"reverse\" order.\nWe'll call sample_distributions, which returns both a sample and the underlying \"sub-distributions\" that were used to generate the sample. (We could have produced just the sample by calling sample; later in the tutorial it will be convenient to have the distributions as well.) The sample we produce is fine:",
"dists, sample = jds.sample_distributions()\nsample",
"But log_prob produces a result with an undesired shape:",
"jds.log_prob(sample)",
"And multiple sampling doesn't work:",
"try:\n jds.sample([5, 3])\nexcept tf.errors.InvalidArgumentError as e:\n print(e)",
"Let's try to understand what's going wrong.\nA Brief Review: Batch and Event Shape\nIn TFP, an ordinary (not a JointDistribution) probability distribution has an event shape and a batch shape, and understanding the difference is crucial to effective use of TFP:\n\nEvent shape describes the shape of a single draw from the distribution; the draw may be dependent across dimensions. For scalar distributions, the event shape is []. For a 5-dimensional MultivariateNormal, the event shape is [5].\nBatch shape describes independent, not identically distributed draws, aka a \"batch\" of distributions. Representing a batch of distributions in a single Python object is one of the key ways TFP achieves efficiency at scale.\n\nFor our purposes, a critical fact to keep in mind is that if we call log_prob on a single sample from a distribution, the result will always have a shape that matches (i.e., has as rightmost dimensions) the batch shape.\nFor a more in-depth discussion of shapes, see the \"Understanding TensorFlow Distributions Shapes\" tutorial.\nWhy Doesn't log_prob(sample()) Produce a Scalar?\nLet's use our knowledge of batch and event shape to explore what's happening with log_prob(sample()). Here's our sample again:",
"sample",
"And here are our distributions:",
"dists",
"The log probability is computed by summing the log probabilities of the sub-distributions at the (matched) elements of the parts:",
"log_prob_parts = [dist.log_prob(s) for (dist, s) in zip(dists, sample)]\nlog_prob_parts\n\nnp.sum(log_prob_parts) - jds.log_prob(sample)",
"So, one level of explanation is that the log probability calculation is returning a 7-Tensor because the third subcomponent of log_prob_parts is a 7-Tensor. But why?\nWell, we see that the last element of dists, which corresponds to our distribution over Y in the mathematial formulation, has a batch_shape of [7]. In other words, our distribution over Y is a batch of 7 independent normals (with different means and, in this case, the same scale).\nWe now understand what's wrong: in JDS, the distribution over Y has batch_shape=[7], a sample from the JDS represents scalars for m and b and a \"batch\" of 7 independent normals. and log_prob computes 7 separate log-probabilities, each of which represents the log probability of drawing m and b and a single observation Y[i] at some X[i].\nFixing log_prob(sample()) with Independent\nRecall that dists[2] has event_shape=[] and batch_shape=[7]:",
"dists[2]",
"By using TFP's Independent metadistribution, which converts batch dimensions to event dimensions, we can convert this into a distribution with event_shape=[7] and batch_shape=[] (we'll rename it y_dist_i because it's a distribution on Y, with the _i standing in for our Independent wrapping):",
"y_dist_i = tfd.Independent(dists[2], reinterpreted_batch_ndims=1)\ny_dist_i",
"Now, the log_prob of a 7-vector is a scalar:",
"y_dist_i.log_prob(sample[2])",
"Under the covers, Independent sums over the batch:",
"y_dist_i.log_prob(sample[2]) - tf.reduce_sum(dists[2].log_prob(sample[2]))",
"And indeed, we can use this to construct a new jds_i (the i again stands for Independent) where log_prob returns a scalar:",
"jds_i = tfd.JointDistributionSequential([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Independent( # Y\n tfd.Normal(loc=m*X + b, scale=1.),\n reinterpreted_batch_ndims=1)\n])\n\njds_i.log_prob(sample)",
"A couple notes:\n- jds_i.log_prob(s) is not the same as tf.reduce_sum(jds.log_prob(s)). The former produces the \"correct\" log probability of the joint distribution. The latter sums over a 7-Tensor, each element of which is the sum of the log probability of m, b, and a single element of the log probability of Y, so it overcounts m and b. (log_prob(m) + log_prob(b) + log_prob(Y) returns a result rather than throwing an exception because TFP follows TF and NumPy's broadcasting rules; adding a scalar to a vector produces a vector-sized result.)\n- In this particular case, we could have solved the problem and achieved the same result using MultivariateNormalDiag instead of Independent(Normal(...)). MultivariateNormalDiag is a vector-valued distribution (i.e., it already has vector event-shape). Indeeed MultivariateNormalDiag could be (but isn't) implemented as a composition of Independent and Normal. It's worthwhile to remember that given a vector V, samples from n1 = Normal(loc=V), and n2 = MultivariateNormalDiag(loc=V) are indistinguishable; the difference beween these distributions is that n1.log_prob(n1.sample()) is a vector and n2.log_prob(n2.sample()) is a scalar.\nMultiple Samples?\nDrawing multiple samples still doesn't work:",
"try:\n jds_i.sample([5, 3])\nexcept tf.errors.InvalidArgumentError as e:\n print(e)",
"Let's think about why. When we call jds_i.sample([5, 3]), we'll first draw samples for m and b, each with shape (5, 3). Next, we're going to try to construct a Normal distribution via:\ntfd.Normal(loc=m*X + b, scale=1.)\nBut if m has shape (5, 3) and X has shape 7, we can't multiply them together, and indeed this is the error we're hitting:",
"m = tfd.Normal(0., 1.).sample([5, 3])\ntry:\n m * X\nexcept tf.errors.InvalidArgumentError as e:\n print(e)",
"To resolve this issue, let's think about what properties the distribution over Y has to have. If we've called jds_i.sample([5, 3]), then we know m and b will both have shape (5, 3). What shape should a call to sample on the Y distribution produce? The obvious answer is (5, 3, 7): for each batch point, we want a sample with the same size as X. We can achieve this by using TensorFlow's broadcasting capabilities, adding extra dimensions:",
"m[..., tf.newaxis].shape\n\n(m[..., tf.newaxis] * X).shape",
"Adding an axis to both m and b, we can define a new JDS that supports multiple samples:",
"jds_ia = tfd.JointDistributionSequential([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Independent( # Y\n tfd.Normal(loc=m[..., tf.newaxis]*X + b[..., tf.newaxis], scale=1.),\n reinterpreted_batch_ndims=1)\n])\n\nshaped_sample = jds_ia.sample([5, 3])\nshaped_sample\n\njds_ia.log_prob(shaped_sample)",
"As an extra check, we'll verify that the log probability for a single batch point matches what we had before:",
"(jds_ia.log_prob(shaped_sample)[3, 1] -\n jds_i.log_prob([shaped_sample[0][3, 1],\n shaped_sample[1][3, 1],\n shaped_sample[2][3, 1, :]]))",
"<a id='AutoBatching-For-The-Win'></a>\nAutoBatching For The Win\nExcellent! We now have a version of JointDistribution that handles all our desiderata: log_prob returns a scalar thanks to the use of tfd.Independent, and multiple samples work now that we fixed broadcasting by adding extra axes.\nWhat if I told you there was an easier, better way? There is, and it's called JointDistributionSequentialAutoBatched (JDSAB):",
"jds_ab = tfd.JointDistributionSequentialAutoBatched([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y\n])\n\njds_ab.log_prob(jds.sample())\n\nshaped_sample = jds_ab.sample([5, 3])\njds_ab.log_prob(shaped_sample)\n\njds_ab.log_prob(shaped_sample) - jds_ia.log_prob(shaped_sample)",
"How does this work? While you could attempt to read the code for a deep understanding, we'll give a brief overview which is sufficient for most use cases:\n- Recall that our first problem was that our distribution for Y had batch_shape=[7] and event_shape=[], and we used Independent to convert the batch dimension to an event dimension. JDSAB ignores the batch shapes of component distributions; instead it treats batch shape as an overall property of the model, which is assumed to be [] (unless specified otherwise by setting batch_ndims > 0). The effect is equivalent to using tfd.Independent to convert all batch dimensions of component distributions into event dimensions, as we did manually above.\n- Our second problem was a need to massage the shapes of m and b so that they could broadcast appropriately with X when creating multiple samples. With JDSAB, you write a model to generate a single sample, and we \"lift\" the entire model to generate multiple samples using TensorFlow's vectorized_map. (This feature is analagous to JAX's vmap.)\nExploring the batch shape issue in more detail, we can compare the batch shapes of our original \"bad\" joint distribution jds, our batch-fixed distributions jds_i and jds_ia, and our autobatched jds_ab:",
"jds.batch_shape\n\njds_i.batch_shape\n\njds_ia.batch_shape\n\njds_ab.batch_shape",
"We see that the original jds has subdistributions with different batch shapes. jds_i and jds_ia fix this by creating subdistributions with the same (empty) batch shape. jds_ab has only a single (empty) batch shape.\nIt's worth noting that JointDistributionSequentialAutoBatched offers some additional generality for free. Suppose we make the covariates X (and, implicitly, the observations Y) two-dimensional:",
"X = np.arange(14).reshape((2, 7))\nX",
"Our JointDistributionSequentialAutoBatched works with no changes (we need to redefine the model because the shape of X is cached by jds_ab.log_prob):",
"jds_ab = tfd.JointDistributionSequentialAutoBatched([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Normal(loc=m*X + b, scale=1.) # Y\n])\n\nshaped_sample = jds_ab.sample([5, 3])\nshaped_sample\n\njds_ab.log_prob(shaped_sample)",
"On the other hand, our carefully crafted JointDistributionSequential no longer works:",
"jds_ia = tfd.JointDistributionSequential([\n tfd.Normal(loc=0., scale=1.), # m\n tfd.Normal(loc=0., scale=1.), # b\n lambda b, m: tfd.Independent( # Y\n tfd.Normal(loc=m[..., tf.newaxis]*X + b[..., tf.newaxis], scale=1.),\n reinterpreted_batch_ndims=1)\n])\n\ntry:\n jds_ia.sample([5, 3])\nexcept tf.errors.InvalidArgumentError as e:\n print(e)",
"To fix this, we'd have to add a second tf.newaxis to both m and b match the shape, and increase reinterpreted_batch_ndims to 2 in the call to Independent. In this case, letting the auto-batching machinery handle the shape issues is shorter, easier, and more ergonomic.\nOnce again, we note that while this notebook explored JointDistributionSequentialAutoBatched, the other variants of JointDistribution have equivalent AutoBatched. (For users of JointDistributionCoroutine, JointDistributionCoroutineAutoBatched has the additional benefit that you no longer need to specify Root nodes; if you've never used JointDistributionCoroutine you can safely ignore this statement.)\nConcluding Thoughts\nIn this notebook, we introduced JointDistributionSequentialAutoBatched and worked through a simple example in detail. Hopefully you learned something about TFP shapes and about autobatching!"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
google-research/ott
|
docs/notebooks/soft_sort.ipynb
|
apache-2.0
|
[
"Soft Sorting",
"import functools\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.ndimage\n\nimport ott",
"Sorting operators\nGiven an array of $n$ numbers, several operators arise around the idea of sorting:\n\nThe sort operator reshuffles the values in order, from smallest to largest.\nThe rank operator associates to each value its rank, when sorting in ascending order.\nThe quantile operator consider a level value between 0 and 1, to return the element of the sorted array indexed at int(n * level), the median for instance if that level is set to $0.5$.\nThe topk operator is equivalent to the sort operator, but only returns the\nlargest $k$ values, namely the last $k$ values of the sorted vector.\n\nHere are some examples",
"x = jnp.array([1.0, 5.0, 4.0, 8.0, 12.0])\njnp.sort(x)\n\ndef rank(x):\n return jnp.argsort(jnp.argsort(x))\n\nrank(x)\n\njnp.quantile(x, 0.5)",
"Soft operators\nSorting operators are ubiquitous in CS and stats, but have several limitations when used in modern deep learning architectures. For instance, ranks is integer valued: if used at some point within a DL pipeline, one won't be able to differentiate through that step because the gradient of these integer values does not exist, or is ill-defined. Indeed, the vector of ranks of a slightly perturbed vector $x+\\Delta x$ is the same as that for $x$, or switches ranks at some indices when inversions occur. Practially speaking, any loss or intermediary operation based on ranks will break backpropagation.\nThis colab shows how soft counterparts to these operators are defined in OTT. By soft, we mean differentiable, approximate proxies to these original \"hard\" operators. For instance soft_sort.ranks returned by OTT operators won't be integer valued, but instead floating point approximations; soft_sort.sort will not contain exactly the n values contained in the input array, reordered, but instead n combinaisons of thoses values that look very close to them.\nThese soft operators trade off accuracy for a more informative Jacobian. This trade-off is controlled by a non-negative parameter epsilon: The smaller epsilon, the closer to the original ranking and sorting operations; The bigger, the more bias yet the more informative gradients. That epsilon also correponds to that used in regularized OT (see doc on sinkhorn).\nThe behavior of these operators is illustrated below.\nSoft sort",
"softsort = jax.jit(ott.tools.soft_sort.sort)\nprint(softsort(x))",
"As we can see, the values are close to the original ones but not exactly equal. Here, epsilon is set by default to 1e-2. A smaller epsilon reduces that gap, whereas a bigger one would tend to squash all returned values to the average of the input values.",
"print(softsort(x, epsilon=1e-4))\nprint(softsort(x, epsilon=1e-1))",
"Soft topk\nThe soft operators we propose build on a common idea: formulate sorting operations as optimal transports from an array of $n$ values to a predefined target measure of $m$ points. The user is free to choose $m$, providing great flexibility depending on the use case. \nTransporting an input discrete measure of $n$ points towards one of $m$ points results in a $O(nm)$ complexity. The bigger $m$, the more fine grained quantities we recover. For instance, if we wish to get both a fine grained yet differentiable sorted vector, or vector of ranks, one can define a target measure of size $m=n$, leading to a $O(n^2)$ complexity.\nOn the contrary, if we are only interested in singling out a few important ranks, such as when considering top k values, we can simply transport the inputs points onto $k+1$ targets, leading to a smaller complexity in $O(nk)$. When $k \\ll n$, the gain in time and memory can be of course substantial.\nHere is an example.",
"top5 = jax.jit(functools.partial(ott.tools.soft_sort.sort, topk=5))\n\n# Generates a vector of size 1000\nbig_x = jax.random.uniform(jax.random.PRNGKey(0), (1000,))\ntop5(big_x)",
"Soft Ranks\nSimilarly, we can compute soft ranks, which do not output integer values, but provide instead a differentiable, float valued, approximation of the vector of ranks.",
"softranks = jax.jit(ott.tools.soft_sort.ranks)\nprint(softranks(x))",
"Regularization effect\nAs mentioned earlier, epsilon controls the tradeoff between accuracy and differentiability. Larger epsilon tend to merge the soft ranks of values that are close, up to the point where they all collapse to the average rank or agverage value.",
"epsilons = np.logspace(-3, 1,100)\nsorted_values = []\nranks = []\nfor e in epsilons:\n sorted_values.append(softsort(x, epsilon=e))\n ranks.append(softranks(x, epsilon=e))\n\nfig, axes = plt.subplots(1, 2, figsize=(14, 5))\n\nfor values, ax, title in zip(\n (sorted_values, ranks), axes, ('sorted values', 'ranks')):\n ax.plot(epsilons, np.array(values), color='k', lw=11)\n ax.plot(epsilons, np.array(values), lw=7)\n ax.set_xlabel('$\\epsilon$', fontsize=24)\n ax.tick_params(axis='both', which='both', labelsize=18)\n ax.set_title(f\"Soft {title}\", fontsize=24)\n ax.set_xscale('log')\n",
"Note how none of the lines above cross. This is a fundamental property of soft-sort operators, proved in Cuturi et al. 2020: soft sorting and ranking operators are monotonic: the vector of soft-sorted values will remain increasing for any epsilon, whereas if an input value $x_i$ has a smaller (hard) rank than $x_j$, its soft-rank, for any value of epsilon, will also remain smaller than that for $x_j$.\nSoft quantile\nTo illustrate further the flexibility provided by setting target measures, one can notice that when a soft quantile is targeted (for instance the soft median), the complexity becomes simply $O(n)$. This is illustrated below to define \"soft median\" differentiable filter on a noisy image.",
"softquantile = jax.jit(ott.tools.soft_sort.quantile)\nsoftquantile(x, level=0.5)\n\nimport io\nimport requests\n\nurl = \"https://raw.githubusercontent.com/matplotlib/matplotlib/master/doc/_static/stinkbug.png\"\nresp = requests.get(url)\nimage = plt.imread(io.BytesIO(resp.content))\nimage = image[..., 0]\n\ndef salt_and_pepper(im, amount=0.05):\n result = np.copy(im)\n result = np.reshape(result, (-1,))\n num_noises = int(np.ceil(amount * im.size))\n indices = np.random.randint(0, im.size, num_noises)\n values = np.random.uniform(size=(num_noises,)) > 0.5\n result[indices] = values\n return np.reshape(result, im.shape)\n\nnoisy_image = salt_and_pepper(image, amount=0.1)\n\nsoftmedian = jax.jit(functools.partial(ott.tools.soft_sort.quantile, level=0.5))\n\nfns = {'original': None, 'median': np.median}\nfor e in [0.01, 1.0]:\n fns[f'soft {e}'] = functools.partial(softmedian, epsilon=e)\nfns.update(mean=np.mean)\n\nfig, axes = plt.subplots(1, len(fns), figsize=(len(fns)*6, 4))\nfor key, ax in zip(fns, axes):\n fn = fns[key]\n soft_denoised = (\n scipy.ndimage.generic_filter(noisy_image, fn, size=(3, 3))\n if fn is not None else noisy_image)\n ax.imshow(soft_denoised)\n ax.set_title(key, fontsize=22)",
"Learning through a soft ranks operator.\nA crucial feature of OTT lies in the ability it provides to differentiate seamlessly through any quantities that follow an optimal transport computation, making it very easy for end-users to plug them directly into end-to-end differentiable architectures. \nIn this tutorial we show how OTT can be used to implement a loss based on soft ranks. That soft 0-1 loss is used here to train a neural network for image classification, as done by Cuturi et al. 2019.\nThis implementation relies on FLAX a neural network library for JAX.\nModel\nSimilarly to Cuturi et al. 2019, we will train a vanilla CNN made of 4 convolutional blocks, in order to classify images from the CIFAR-10 dataset.",
"from typing import Any\nimport flax\nfrom flax import linen as nn\n\n\nclass ConvBlock(nn.Module):\n \"\"\"A simple CNN blockl.\"\"\"\n\n features: int = 32\n dtype: Any = jnp.float32\n\n @nn.compact\n def __call__(self, x, train: bool = True):\n x = nn.Conv(features=self.features, kernel_size=(3, 3))(x)\n x = nn.relu(x)\n x = nn.Conv(features=self.features, kernel_size=(3, 3))(x)\n x = nn.relu(x)\n x = nn.max_pool(x, window_shape=(2, 2), strides=(2, 2))\n return x\n\n\nclass CNN(nn.Module):\n \"\"\"A simple CNN model.\"\"\"\n\n num_classes: int = 10\n dtype: Any = jnp.float32\n\n @nn.compact\n def __call__(self, x, train: bool = True):\n x = ConvBlock(features=32)(x)\n x = ConvBlock(features=64)(x)\n x = x.reshape((x.shape[0], -1)) # flatten\n x = nn.Dense(features=512)(x)\n x = nn.relu(x)\n x = nn.Dense(features=self.num_classes)(x)\n return x",
"Losses & Metrics\nThe $0/1$ loss of a classifier on a labeled example is $0$ if the logit of the true class ranks on top (here, would have rank 9, since CIFAR-10 considers 10 classes). Of course the $0/1$ loss is non-differentiable, which is why the cross-entropy loss is used instead.\nHere, as in the paper, we consider a differentiable \"soft\" 0/1 loss by measuring the gap between the soft-rank of the logit of the right answer and the target rank, 9. If that gap is bigger than 0, then we incurr a loss equal to that gap.",
"def cross_entropy_loss(logits, labels):\n logits = nn.log_softmax(logits)\n return -jnp.sum(labels * logits) / labels.shape[0]\n\n\ndef soft_error_loss(logits, labels):\n \"\"\"The average distance between the best rank and the rank of the true class.\"\"\"\n ranks_fn = jax.jit(functools.partial(ott.tools.soft_sort.ranks, axis=-1))\n soft_ranks = ranks_fn(logits)\n return jnp.mean(nn.relu(\n labels.shape[-1] - 1 - jnp.sum(labels * soft_ranks, axis=1)))",
"To know more about training a neural network with Flax, please refer to the Flax Imagenet examples. After 100 epochs through the CIFAR-10 training examples, we are able to reproduce the results from Cuturi et al. 2019 and see that a soft $0/1$ error loss, building on top of soft_sort.ranks, can provide a competitive alternative to the cross entropy loss for classification tasks. As mentioned in that paper, that loss is less prone to overfitting.",
"# Plot results from training"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code"
] |
eds-uga/csci1360e-su17
|
lectures/L13.ipynb
|
mit
|
[
"Lecture 13: Statistics\nCSCI 1360E: Foundations for Informatics and Analytics\nOverview and Objectives\nContinuing this week's departure from Python, today we'll jump into statistics. This is yet another topic that could span an entire course, and like linear algebra I highly recommend taking a stats course at some point. By the end of this lecture, you should be able to\n\nDefine statistics and how to effectively employ statistical principles in answering questions\nUnderstand the roles of random variables and parametric distributions\nCompute basic first and second-order statistics on datasets\n\nPart 1: The Statistical Approach\n\n\n\nOne definition of statistics is that it is a way of summarizing data. \n\n\nAnother definition is that statistics is making predictions on the whole population from a sample of the population.\n\n\nOf course, these definitions are gross oversimplifications, but I'll illustrate with an example.\nExample: Giving a Talk\nYou're an intern at the Large Hadron Collider (LHC), and you've been instrumental in devising the experiments that seem to have uncovered hard evidence for the existence of the Higgs Boson. This evidence consists of the results of billions of subatomic collisions taking place deep in the bowels of the LHC.\nSome high-level executives from the funding agencies responsible for keeping the lights on at the LHC want to hear about these exciting results, but all your immediate bosses are indisposed and have asked you to step in.\nHow do you present the findings? Do you provide a raw list of the billions of collisions? Do you take some averages of the data? How many? How representative of the full billion data points are these handful of averages? Can you quantify the uncertainty in these averages, i.e. how far off they could potentially be?\nExample: Do first babies arrive late?\n\"My two friends that have given birth recently to their first babies, BOTH went almost 2 weeks overdue before going into labor or being induced.\"\n\"My first one came 2 weeks late and now I think the second one is going to come out two weeks early!!\"\n\"I don’t think that can be true because my sister was my mother's first and she was early, as with many of my cousins.\"\n\nWhat are the problems with this?\n\n\nSmall number of observations. If the gestation period is longer for first babies, the difference is probably small compared to the natural variation. In that case, we might have to compare a large number of pregnancies to be sure that a difference exists.\n\n\nSelection bias. People who join a discussion of this question might be interested because their first babies were late. In that case the process of selecting data would bias the results.\n\n\nConfirmation bias. People who believe the claim might be more likely to contribute examples that confirm it. People who doubt the claim are more likely to cite counterexamples.\n\n\nInaccuracy. Anecdotes are often personal stories, and often misremembered, misrepresented, repeated inaccurately, etc.\n\n\nHow might we address these limitations?\nThere is a general sequence of steps you can follow to maximize your chances of robustly answering a question in a data-driven, quantitatively significant way.\n\n\nData collection. Collect broad, unbiased, varied data related to the question you want to answer.\n\n\nDescriptive statistics. Generate statistics that summarize the data concisely, and evaluate different ways to visualize data.\n\n\nExploratory data analysis. Look for patterns, differences, and other features that address the questions you're interested in. At the same time check for inconsistencies and identify limitations.\n\n\nHypothesis testing. Where there are apparent effects, like a difference between two groups, evaluate whether the effect is real, or whether it might have happened by chance.\n\n\nEstimation. Use data from a sample to estimate characteristics of the general population.\n\n\nPart 2: Computing Statistics\nOnce we've collected data, we need to compute descriptive statistics.\nYou can probably name some of the statistics we'll compute and use; it's important to note that statistics live in a hierarchy\nFirst-order statistics\nFirst-order statistics are summaries of the data that rely only on the data itself.",
"import numpy as np\nnp.random.seed(29384924)\n\ndata = np.random.randint(10, size = 100) # 100 random numbers, from 0 to 9\nprint(data)",
"Some very straightforward statistics are the number of data points, the largest value, and the smallest value. These shouldn't be immediately ignored, but they are of limited utility.",
"print(\"Number of data points: \", data.shape[0]) # Remember our friend, ndarray.shape?\n\nprint(\"Largest value: \", data.max())\n\nprint(\"Smallest value: \", data.min())",
"Mean: You've seen this all the time--it's the average of all the data!",
"print(data.mean()) # Mean",
"The mean is very simple to compute: it's the sum of the data divided by the number of data points. The mean depends at least a little bit on every single data point. This can be advantageous in certain situations, as it varies smoothly as more data points are added or some are removed.\nHowever, this property can also be problematic. A famous example that exploits this weakness is that in the mid-1980s, the major at UNC with the highest average starting salary was geography...however, this was mostly on account of a particular NBA star by the name of Michael Jordan.",
"outlier = np.array([1, 1, 2, 3, 2, 1, 3, 2, 38]) # Note the outlier of 38 at the end.\nprint(outlier.mean())",
"The mean is sensitive to outliers, meaning one or two data points that lie well beyond all the others can disproportionately affect the value of the mean. In the above simple example, the lone outlier of 38 pulls the mean to be larger than all the other data points except for 38; not exactly a representative statistic!\nMedian: The \"middle\" data point.",
"print(np.median(data))\n",
"The median is computed by:\n\nsorting all your data, and\npicking out the middle value (or averaging the two middle data points, if you have an even amount of data)\n\nIn this way, the median does not directly depend on the vast majority of your data; just on whatever value(s) happen to be in the middle. It is also not trivial to compute: you have to sort your data first, which might be tricky if you have billions of data points.\nOn the other hand, the median is not sensitive to outliers. In fact, it's robust to outliers, meaning it wholesale ignores them.",
"print(outlier)\n\nprint(np.median(outlier))",
"For comparison:",
"print(np.mean(outlier))",
"Quite a difference! But which is more representative of data will, ultimately, depend on your data and what you're trying to do with it.\nSecond-order statistics\nSecond-order statistics rely both on the data itself, and first-order statistics, to compute.\nVariance: This measures how spread out your data are. More specifically, it measures how much your data varies from its mean.",
"print(data)\n\nprint(data.var())",
"The variance is computed by subtracting each individual data point from the average of the whole data set, squaring this difference, and summing all these differences together before finally dividing by the number of data points.\nVariance may not be familiar, but you've probably heard of its relative: standard deviation is just the square root of the variance!",
"print(np.sqrt(data.var()))\n\nprint(data.std())",
"(they should indeed both show the same number--this is just to show that the standard deviation is defined precisely as the square root of the variance)\nLike the mean, variance (and standard deviation) uses all the data points to compute, and is therefore sensitive to outliers.\nInterquartile Range: The difference between the 75% percentile and 25% of the data.\nYou've probably heard about percentiles before in the context of standardized testing. e.g., you or someone else is in the \"90th percentile\". This means your score is as good or better than 90% of the other people who took the test.\nThe interquartile range is defined specifically as the difference between the 75th percentile and the 25th percentile. To wit:",
"print(np.percentile(data, 75) - np.percentile(data, 25))",
"This, like the median, is robust to outliers. But also like the median, it relies on sorting the data first, then picking out the value 1/4 of the way down the dataset and subtracting it from the value 3/4 of the way down the dataset. This can be expensive in large datasets.\nHigher-order statistics\nThere are higher-order statistics you can compute from distributions, and depending on the application may very well involve extremely complex computations.\nSome examples include:\n\n\nSkewness: This is a measure of asymmetry in a distribution. \n\n\nKurtosis: This is a measure of \"tailed-ness\" of a distribution. \n\n\nDon't worry about higher-order statistics too much in this class. However, it's still good to know they exist--most modern machine learning and artificial intelligence applications live and die by higher-order statistics.\nPart 3: Random Variables and Distributions\nThese methods for describing and summarizing data will come in handy as we deal with random variables.\nA random variable is, first and foremost, a variable: we don't know its value. It is often represented by a capital letter, e.g. $X$.\nWhile we can't know the exact value of a random variable, we often have a handful of observations of the variable--usually denoted with a lowercase version of the corresponding capital letter, e.g. $x$--and it's from these observations that we compute things like mean and variance in order to describe the random variable itself.\nIs this all coming together, or what?!\nAs a result of these observations $x_1, x_2, ..., x_n$ of the random variable $X$, we can usually say something about how $X$ is distributed.",
"%matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# Observe 100 data points from a Gaussian random variable with mean = 0.0 and variance = 1.0.\nobservations = np.random.normal(size = 100)\n_ = plt.hist(observations)",
"It's tough to see, isn't it? Let's try 1000 observations.",
"# Observe **1000** data points from a Gaussian random variable with mean = 0.0 and variance = 1.0.\nobservations = np.random.normal(size = 1000)\n_ = plt.hist(observations)",
"That looks a little better! Maybe 10,000 data points, just for grins?",
"# Observe **** 10,000 **** data points from a Gaussian random variable with mean = 0.0 and variance = 1.0.\nobservations = np.random.normal(size = 10000)\n_ = plt.hist(observations, bins = 25)",
"There's the bell curve we know and love!\nSo what happened?\nWe had some observations $x$--a regular array with a bunch of numbers in it (10,000 by the end, to be exact). In fact, here's what the array looked like:",
"print(observations)",
"This could be any old dataset! In fact, forget for a moment that we generated this dataset ourselves, and instead think that this could be a dataset we picked up from the web.\nWe're able to compute some statistics from it:",
"print(\"Mean: {:.2f}\".format(observations.mean()))\nprint(\"Variance: {:.2f}\".format(observations.var()))",
"You'll notice the mean is very close to 0, and the variance is likewise very close to 1. Since we ourselves set the mean and variance for the random number generator, we know that these are very close to the true mean and true variance, but in general we wouldn't necessarily know that.\nInstead, we'd have computed the sample mean and sample variance from the data, as we did above, and then assumed the data to be Gaussian; after all, it certainly looks like a bell curve!\nDistributions\nThis brings us to distributions.\nWhen we made those histograms of the observations, we were creating a distribution of the data.\nThe mean and variance statistics are parameters that govern the shape of those distributions.\nTake a look at how the distribution changes when we change its parameters:",
"from scipy.stats import norm\nxs = np.linspace(-5, 5, 100)\nplt.plot(xs, norm.pdf(xs, loc = 0, scale = 1), '-', label = \"mean=0, var=1\")\nplt.plot(xs, norm.pdf(xs, loc = 0, scale = 2), '--', label = \"mean=0, var=2\")\nplt.plot(xs, norm.pdf(xs, loc = 0, scale = 0.5), ':', label = \"mean=0, var=0.5\")\nplt.plot(xs, norm.pdf(xs, loc = -1, scale = 1), '-.', label = \"mean=-1, var=1\")\nplt.legend(loc = 0)\nplt.title(\"Various Normal Distributions\")",
"Notice how changing the mean shifts the bell curve around along the x-axis, and changing the variance either squeezes the bell curve to be tall and skinny (small variance, tightly packed around the mean), or smashes it to be flat and short (large variance, spread out).\nSome notes\nIt's important to note: these shapes show what the distributions look like in the limit as the number of data points $n \\rightarrow \\infty $; more commonly, you'll have only a relatively smaller number of samples, more like the histograms we created of 100 and 1000 data points.\nFrom this limited data, you'll make assumptions about the underlying governing distribution.\nUnderlying = Latent, or unknown!\nYour assumptions will be key to solving data science problems, and solving for latent variables in the system: variables which you cannot observe directly, such as the mean and variance of the data distributions.\nBy and large, you'll have a limited data sample (hundreds or thousands of data points), you'll make an assumption about the underlying form of the data, compute statistics to summarize it, and use these statistics as stand-in representations for the latent variables of the system. Hence, statistics!\nReview Questions\nSome questions to discuss and consider:\n1: You have a very small dataset with a large variance. What first-order statistic would you use to summarize the data? Justify your answer.\n2: Correlation is an analytical strategy to determine if, when one random variable changes, a second random variable also changes. Random variables can be positively correlated (as one goes up, the other goes up), negatively correlated (as one goes up, the other goes down), or uncorrelated (the behavior of one cannot predict the behavior of the other). Without consulting Google, what statistics that we have covered in this lecture do you think would be useful for computing correlation between two random variables? Why?\n3: What differentiates anecdotal evidence from robust, statistically-significant evidence? Give some examples.\n4: The astute reader may have noticed parallels between the steps of statistical rigor and the divisions of Greater Data Science from Lecture 1. Do you think this is a coincidence?\n5: I take a survey of the 20 people in my class, asking each person their age. I note that the average reported age is 20.5, with a variance of 0.05. Using this information, I conclude the average age of all humans on the planet is around 20 or 21, with little variation. Where did I go wrong? Use the notation central to taking a statistical approach to answering questions.\nCourse Administrivia\n\n\nA5 is due tonight at 11:59pm! Post any questions to the Slack chat!\n\n\nMidterm grades should all be up.\n\n\nA6 is out tomorrow! Due Monday, July 10.\n\n\nAdditional Resources\n\nGrus, Joel. Data Science from Scratch. 2015. ISBN-13: 978-1491901427\nDowney, Allen. Think Stats: Probability and Statistics for Programmers. 2011. ISBN-13: 978-1449307110"
] |
[
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown",
"code",
"markdown"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.