Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
5,300
Given the following text description, write Python code to implement the functionality described below step by step Description: Note Step1: The ImageCollection class provides an easy way of loading and representing multiple images. Images are not read from disk until accessed. Step2: Credit Step3: For this demo, we estimate a projective transformation that relates the two images. Since the outer parts of these photographs do not comform well to such a model, we select only the central parts. To further speed up the demonstration, images are downscaled to 25% of their original size. 1. Feature detection and matching "Oriented FAST and rotated BRIEF" features are detected in both images Step4: Each feature yields a binary descriptor; those are used to find the putative matches shown. Many false matches are observed. 2. Transform estimation To filter matches, we apply RANdom SAMple Consensus (RANSAC), a common method of rejecting outliers. This iterative process estimates transformation models based on randomly chosen subsets of matches, finally selecting the model which corresponds best with the majority of matches. Step5: Note how most of the false matches have now been rejected. 3. Warping Next, we want to produce the panorama itself. The first step is to find the shape of the output image, by taking considering the extents of all warped images. Step6: Warp the images according to the estimated transformation model. Values outside the input images are set to -1 to distinguish the "background". A shift is added to make sure that both images are visible in their entirety. Note that warp takes the inverse mapping as an input. Step8: An alpha channel is now added to the warped images before they are merged together Step9: Note that, while the columns are well aligned, the color intensity is not well matched between images. 4. Blending To blend images smoothly we make use of the open source package Enblend, which in turn employs multi-resolution splines and Laplacian pyramids [1, 2]. [1] P. Burt and E. Adelson. "A Multiresolution Spline With Application to Image Mosaics". ACM Transactions on Graphics, Vol. 2, No. 4, October 1983. Pg. 217-236. [2] P. Burt and E. Adelson. "The Laplacian Pyramid as a Compact Image Code". IEEE Transactions on Communications, April 1983. Step10: <div style="height
Python Code: import numpy as np import matplotlib.pyplot as plt from skimage import io, transform from skimage.color import rgb2gray from skdemo import imshow_all ic = io.ImageCollection('../images/pano/DFM_*') Explanation: Note: This example has been significantly expanded and enhanced. The new, recommended version is located here. We retain this version intact as it was the exact example used in the scikit-image paper. Panorama stitching End of explanation imshow_all(ic[0], ic[1]) Explanation: The ImageCollection class provides an easy way of loading and representing multiple images. Images are not read from disk until accessed. End of explanation image0 = rgb2gray(ic[0][:, 500:500+1987, :]) image1 = rgb2gray(ic[1][:, 500:500+1987, :]) image0 = transform.rescale(image0, 0.25) image1 = transform.rescale(image1, 0.25) imshow_all(image0, image1) Explanation: Credit: Photographs taken in Petra, Jordan by François Malan<br/> License: CC-BY End of explanation from skimage.feature import ORB, match_descriptors orb = ORB(n_keypoints=1000, fast_threshold=0.05) orb.detect_and_extract(image0) keypoints1 = orb.keypoints descriptors1 = orb.descriptors orb.detect_and_extract(image1) keypoints2 = orb.keypoints descriptors2 = orb.descriptors matches12 = match_descriptors(descriptors1, descriptors2, cross_check=True) from skimage.feature import plot_matches fig, ax = plt.subplots(1, 1, figsize=(10, 10)) plot_matches(ax, image0, image1, keypoints1, keypoints2, matches12) ax.axis('off'); Explanation: For this demo, we estimate a projective transformation that relates the two images. Since the outer parts of these photographs do not comform well to such a model, we select only the central parts. To further speed up the demonstration, images are downscaled to 25% of their original size. 1. Feature detection and matching "Oriented FAST and rotated BRIEF" features are detected in both images: End of explanation from skimage.transform import ProjectiveTransform from skimage.measure import ransac from skimage.feature import plot_matches # Select keypoints from the source (image to be registered) # and target (reference image) src = keypoints2[matches12[:, 1]][:, ::-1] dst = keypoints1[matches12[:, 0]][:, ::-1] model_robust, inliers = ransac((src, dst), ProjectiveTransform, min_samples=4, residual_threshold=2) fig, ax = plt.subplots(1, 1, figsize=(15, 15)) plot_matches(ax, image0, image1, keypoints1, keypoints2, matches12[inliers]) ax.axis('off'); Explanation: Each feature yields a binary descriptor; those are used to find the putative matches shown. Many false matches are observed. 2. Transform estimation To filter matches, we apply RANdom SAMple Consensus (RANSAC), a common method of rejecting outliers. This iterative process estimates transformation models based on randomly chosen subsets of matches, finally selecting the model which corresponds best with the majority of matches. End of explanation from skimage.transform import SimilarityTransform r, c = image1.shape[:2] # Note that transformations take coordinates in (x, y) format, # not (row, column), in order to be consistent with most literature corners = np.array([[0, 0], [0, r], [c, 0], [c, r]]) # Warp the image corners to their new positions warped_corners = model_robust(corners) # Find the extents of both the reference image and the warped # target image all_corners = np.vstack((warped_corners, corners)) corner_min = np.min(all_corners, axis=0) corner_max = np.max(all_corners, axis=0) output_shape = (corner_max - corner_min) output_shape = np.ceil(output_shape[::-1]) Explanation: Note how most of the false matches have now been rejected. 3. Warping Next, we want to produce the panorama itself. The first step is to find the shape of the output image, by taking considering the extents of all warped images. End of explanation from skimage.color import gray2rgb from skimage.exposure import rescale_intensity from skimage.transform import warp offset = SimilarityTransform(translation=-corner_min) image0_ = warp(image0, offset.inverse, output_shape=output_shape, cval=-1) image1_ = warp(image1, (model_robust + offset).inverse, output_shape=output_shape, cval=-1) Explanation: Warp the images according to the estimated transformation model. Values outside the input images are set to -1 to distinguish the "background". A shift is added to make sure that both images are visible in their entirety. Note that warp takes the inverse mapping as an input. End of explanation def add_alpha(image, background=-1): Add an alpha layer to the image. The alpha layer is set to 1 for foreground and 0 for background. return np.dstack((gray2rgb(image), (image != background))) image0_alpha = add_alpha(image0_) image1_alpha = add_alpha(image1_) merged = (image0_alpha + image1_alpha) alpha = merged[..., 3] # The summed alpha layers give us an indication of how many # images were combined to make up each pixel. Divide by the # number of images to get an average. merged /= np.maximum(alpha, 1)[..., np.newaxis] merged = merged[..., :3] imshow_all(image0_alpha, image1_alpha, merged) Explanation: An alpha channel is now added to the warped images before they are merged together: End of explanation plt.imsave('/tmp/frame0.tif', image0_alpha) plt.imsave('/tmp/frame1.tif', image1_alpha) %%bash enblend /tmp/frame*.tif -o /tmp/pano.tif pano = io.imread('/tmp/pano.tif') plt.figure(figsize=(10, 10)) plt.imshow(pano) plt.axis('off'); Explanation: Note that, while the columns are well aligned, the color intensity is not well matched between images. 4. Blending To blend images smoothly we make use of the open source package Enblend, which in turn employs multi-resolution splines and Laplacian pyramids [1, 2]. [1] P. Burt and E. Adelson. "A Multiresolution Spline With Application to Image Mosaics". ACM Transactions on Graphics, Vol. 2, No. 4, October 1983. Pg. 217-236. [2] P. Burt and E. Adelson. "The Laplacian Pyramid as a Compact Image Code". IEEE Transactions on Communications, April 1983. End of explanation %reload_ext load_style %load_style ../themes/tutorial.css Explanation: <div style="height: 400px;"></div> End of explanation
5,301
Given the following text description, write Python code to implement the functionality described below step by step Description: 2.3 Python语言基础 1 语言语义(Language Semantics) 缩进,而不是括号 Python使用空格(tabs or spaces)来组织代码结构,而不是像R,C++,Java那样用括号。 建议使用四个空格来作为默认的缩进,设置tab键为四个空格 另外可以用分号隔开多个语句: Step1: 所有事物都是对象(object) 在python中,number,string,data structure,function,class,module都有自己的“box”,即可以理解为Python object(对象)。下面所有的对象直接用object来指代。 调用函数和对象的方法 用圆括号 Step2: 动态参考,强类型 不像C++,Java之类的语言,python中object reference是没有自带类型的。但是可以通过type来查看类型: Step3: 类型信息存储在这个对象本身。 而python可以看做是强类型,即每一个object都有一个明确的类型。所以下面的运算不会成立。但是Visual Basic会把'5'变为整数(int),而JavaScript会把5变为字符串(string) Step4: 不过像是int与float之间倒是会隐式转换: Step5: 因为知道每个Object的类型很重要,我们可以用isinstance函数来查看object的类型 Step6: 查看a、b是否是int或float类型 Step7: 属性和方法 属性(Attributes)指在当前这个object里,还有一些其他的python object。方法(method)指当前这个object自带的一些函数,这些函数可以访问object里的内部数据。 通过obj.attribute_name可以查看: Step8: 可以通过getattr函数来访问属性和方法: Step9: Duck typing 在程序设计中,鸭子类型(英语:duck typing)是动态类型的一种风格。在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由"当前方法和属性的集合"决定。这个概念的名字来源于由James Whitcomb Riley提出的鸭子测试(见下面的“历史”章节),“鸭子测试”可以这样表述: “当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。” 在鸭子类型中,关注的不是对象的类型本身,而是它是如何使用的。 比如,如果一个object能够实现迭代原则,那么这个object就是可迭代的。我们可以看这个object是否有__iter__这个magic method。或者自己写一个iter function来检测: Step10: 这个功能多用于写一些能接受多种类型的函数。比如我们写一个函数,用接收任何序列(list, tuple, ndarray) 甚至一个迭代器。如果接收的不是一个list,那么我们就人为将其转变为一个list: Step11: Import(导入) 比如我创建了一个some_module.py的文件,里面写着: Step12: 那么在别的文件里,有多重导入方式: Step13: 运算符(Binary operators) 用is,和is not, 检查两个引用(references)是否指同一个object, Step14: 因为c = list(a)中的list函数创建了一个新的list,所以c是一个新的list,不指向原来的a。 另一个is的常用法是用来检查一个instance是不是none: Step15: 另外像是,+, - ,==, <=, &, |等都也算是运算符,这个就不详细说了,可以直接看这个链接 可更改和不可更改对象(Mutable and immutable objects) 在python的object中,lists, dicts, NumPy arrays, 以及用户自定义的类型(classes), 都是可以更改的。 而string和tuple是不可以更改的: 2 标量类型(scalar types) 这种类型指的是None,str, bytes, float, bool, int 数值型 Step17: 字符串 Step18: 字符串类型是不可变的: Step19: 把其他类型转换为字符串: Step20: 因为字符串是一连串Unicode字符,所以可以当序列来处理,像list和tuple一样: Step21: 反斜线用来制定特别的字符,比如回车符\n Step22: 可以用前缀r来直接写出想要的字符串格式,而不用输入很多反斜杠: Step23: 字符串的模板,或叫做格式化,是一个很重要的课题。string ojecjt有一个format的方法: Step24: 在这个string中: {0 Step25: Bytes and Unicode 可以使用不同的编码方式 Step26: 通过加一个b前缀,变为byte文字 Step27: 类型塑造(Type casting) Step28: 日期和时间 python内建的datetime模块提供了三种类型,datatime, date and time types: Step29: 用方法(method)提取日期或时间: Step30: 输出string Step31: 把string变为datetime object Step32: 如果我们处理时间序列数据的话,把time部分换掉会比较有用,比如把minute和second变为0: Step33: 因为datetime.datetime是不可变的,所以上面的命令是新创建了一个object。 两个不同的datetime object能产生一个datetime.timedelta类型: Step34: 这个datetime.timedelta(17, 7179)表明两个时间差17天,7179秒 Step35: 还有其他一些datetime格式 3 控制流程 (Control Flow) if, elif and else for loops while loops 上面这三个比较基础的就不介绍了,如果不懂的话可以看这个教程:控制流 pass 表示不进行任何行动,当个占位的东西 Step36: range range函数返回一个能产生序列的迭代器 Step37: range的一个常用法是用来通过index迭代序列: Step38: 三元表达式 Ternary expressions value = true-expr if condition else false-expr
Python Code: a = 5; b = 6; c = 7 Explanation: 2.3 Python语言基础 1 语言语义(Language Semantics) 缩进,而不是括号 Python使用空格(tabs or spaces)来组织代码结构,而不是像R,C++,Java那样用括号。 建议使用四个空格来作为默认的缩进,设置tab键为四个空格 另外可以用分号隔开多个语句: End of explanation result = f(x, y, z) Explanation: 所有事物都是对象(object) 在python中,number,string,data structure,function,class,module都有自己的“box”,即可以理解为Python object(对象)。下面所有的对象直接用object来指代。 调用函数和对象的方法 用圆括号 End of explanation a = 5 type(a) Explanation: 动态参考,强类型 不像C++,Java之类的语言,python中object reference是没有自带类型的。但是可以通过type来查看类型: End of explanation '5' + 5 Explanation: 类型信息存储在这个对象本身。 而python可以看做是强类型,即每一个object都有一个明确的类型。所以下面的运算不会成立。但是Visual Basic会把'5'变为整数(int),而JavaScript会把5变为字符串(string) End of explanation a = 4.5 b = 2 print('a is {0}, b is {1}'.format(type(a), type(b))) a / b Explanation: 不过像是int与float之间倒是会隐式转换: End of explanation a = 5 isinstance(a, int) Explanation: 因为知道每个Object的类型很重要,我们可以用isinstance函数来查看object的类型 End of explanation a = 5; b = 4.5 isinstance(a, (int, float)) isinstance(b, (int, float)) Explanation: 查看a、b是否是int或float类型 End of explanation a = 'foo' a.<Press Tab> Explanation: 属性和方法 属性(Attributes)指在当前这个object里,还有一些其他的python object。方法(method)指当前这个object自带的一些函数,这些函数可以访问object里的内部数据。 通过obj.attribute_name可以查看: End of explanation getattr(a, 'split') Explanation: 可以通过getattr函数来访问属性和方法: End of explanation def isiterable(obj): try: iter(obj) return True except TypeError: # not iterable return False isiterable('a string') isiterable([1, 2, 3]) isiterable(5) Explanation: Duck typing 在程序设计中,鸭子类型(英语:duck typing)是动态类型的一种风格。在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由"当前方法和属性的集合"决定。这个概念的名字来源于由James Whitcomb Riley提出的鸭子测试(见下面的“历史”章节),“鸭子测试”可以这样表述: “当看到一只鸟走起来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子。” 在鸭子类型中,关注的不是对象的类型本身,而是它是如何使用的。 比如,如果一个object能够实现迭代原则,那么这个object就是可迭代的。我们可以看这个object是否有__iter__这个magic method。或者自己写一个iter function来检测: End of explanation if not isinstance(x, list) and isiterable(x): # 如果x不是list,且x可迭代 x = list(x) # 转变x为list Explanation: 这个功能多用于写一些能接受多种类型的函数。比如我们写一个函数,用接收任何序列(list, tuple, ndarray) 甚至一个迭代器。如果接收的不是一个list,那么我们就人为将其转变为一个list: End of explanation # some_module.py PI = 3.14159 def f(x): return x + 2 def g(a, b): return a + b Explanation: Import(导入) 比如我创建了一个some_module.py的文件,里面写着: End of explanation # 1 import some_module result = some_module.f(5) pi = some_module.PI # 2 from some_module import f, g, PI result = g(5, PI) # 3 import some_module as sm from some_module import PI as pi, g as gf r1 = sm.f(pi) r2 = gf(6, pi) Explanation: 那么在别的文件里,有多重导入方式: End of explanation a = [1, 2, 3] b = a c = list(a) a is b a is not c Explanation: 运算符(Binary operators) 用is,和is not, 检查两个引用(references)是否指同一个object, End of explanation a = None a is None Explanation: 因为c = list(a)中的list函数创建了一个新的list,所以c是一个新的list,不指向原来的a。 另一个is的常用法是用来检查一个instance是不是none: End of explanation ival = 123554 ival ** 6 fval = 7.234 fval2 = 5.43e-5 5/2 # 取商 5//2 # 取余数 5 % 2 Explanation: 另外像是,+, - ,==, <=, &, |等都也算是运算符,这个就不详细说了,可以直接看这个链接 可更改和不可更改对象(Mutable and immutable objects) 在python的object中,lists, dicts, NumPy arrays, 以及用户自定义的类型(classes), 都是可以更改的。 而string和tuple是不可以更改的: 2 标量类型(scalar types) 这种类型指的是None,str, bytes, float, bool, int 数值型 End of explanation a = 'one way of writing a string' b = "another way" c = This is a longer string that spans multiple lines c.count('\n') # 有三个回车符 Explanation: 字符串 End of explanation a[10] = 'f' Explanation: 字符串类型是不可变的: End of explanation a = 5.6 s = str(a) s Explanation: 把其他类型转换为字符串: End of explanation s = 'python' list(s) s[:3] Explanation: 因为字符串是一连串Unicode字符,所以可以当序列来处理,像list和tuple一样: End of explanation s = '12\\34' print(s) Explanation: 反斜线用来制定特别的字符,比如回车符\n End of explanation s = r'this\has\no\special\characters' # 实际的s s # 加法用于连接两个字符串 s + s Explanation: 可以用前缀r来直接写出想要的字符串格式,而不用输入很多反斜杠: End of explanation template = '{0:.2f} {1:s} are worth US${2:d}' template Explanation: 字符串的模板,或叫做格式化,是一个很重要的课题。string ojecjt有一个format的方法: End of explanation template.format(4.5560, 'Argentine Pesos', 1) Explanation: 在这个string中: {0:.2f} : 第一个参数为float类型,去小数点后两位 {1:s}: 把第二个参数变为string类型 {2:d}: 把第三个参数变为一个精确的整数 End of explanation val = "español" val val_utf8 = val.encode('utf-8') val_utf8 type(val_utf8) val_utf8.decode('utf-8') val.encode('latin1') val.encode('utf-16') val.encode('utf-16le') Explanation: Bytes and Unicode 可以使用不同的编码方式 End of explanation bytes_val = b'this is bytes' bytes_val decoded = bytes_val.decode('utf8') decoded # this is str (Unicode) now Explanation: 通过加一个b前缀,变为byte文字 End of explanation s = '3.14159' fval = float(s) type(fval) int(fval) bool(fval) bool(0) Explanation: 类型塑造(Type casting) End of explanation from datetime import datetime, date, time dt = datetime(2011, 10, 29, 20, 30, 21) dt.day dt.minute Explanation: 日期和时间 python内建的datetime模块提供了三种类型,datatime, date and time types: End of explanation dt.date() dt.time() Explanation: 用方法(method)提取日期或时间: End of explanation dt.strftime('%m/%d/%Y %H:%M') Explanation: 输出string: End of explanation datetime.strptime('20091031', '%Y%m%d') Explanation: 把string变为datetime object: End of explanation dt.replace(minute=0, second=0) Explanation: 如果我们处理时间序列数据的话,把time部分换掉会比较有用,比如把minute和second变为0: End of explanation dt2 = datetime(2011, 11, 15, 22, 30) delta = dt2 - dt delta type(delta) Explanation: 因为datetime.datetime是不可变的,所以上面的命令是新创建了一个object。 两个不同的datetime object能产生一个datetime.timedelta类型: End of explanation dt dt + delta Explanation: 这个datetime.timedelta(17, 7179)表明两个时间差17天,7179秒 End of explanation if x < 0: print('negative!') elif x == 0: # TODO: put something smart here pass else: print('positive!') Explanation: 还有其他一些datetime格式 3 控制流程 (Control Flow) if, elif and else for loops while loops 上面这三个比较基础的就不介绍了,如果不懂的话可以看这个教程:控制流 pass 表示不进行任何行动,当个占位的东西 End of explanation range(10) list(range(10)) list(range(0, 20, 2)) list(range(5, 0, -1)) Explanation: range range函数返回一个能产生序列的迭代器 End of explanation seq = [1, 2, 3, 4] for i in range(len(seq)): val = seq[i] Explanation: range的一个常用法是用来通过index迭代序列: End of explanation x = 5 'Non-negative' if x >= 0 else 'Negative' Explanation: 三元表达式 Ternary expressions value = true-expr if condition else false-expr End of explanation
5,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Variables and 3D Shapes In the last class we used functions and arguments to build circles, spheres and hollow spheres of different radii. Lets go ahead and build some 3D solid shapes as well. Before we can do so we need to learn about Variables and about solids shapes called Polyhedrons Variables A variable is a box or container to hold a value. You can put a different value in a box everytime. Number values like 1, 0, -10 are called integers Decimal values like 3.2, 1003.4, -4.5 are called floats Word values like "Steve", "Hi Brooks School" are called strings Variables have names. Programs can use variables names instead of raw integers and strings which is very handy. E.g., in the program below, the variable with the name positionX has the integer value 10 and the variable with name message has the value "Hi Brooks School" python positionX = 10 message = "Hi Brooks School" In the next few tasks, you will practice using variables. Start Minecraft and run the program cell below before you begin your tasks. Step1: Task 1 Set the value of the variable named userName to "Steve" and run the function in the task 1 program cell Now set the value of the variable named userName to "Brooks" and run the function in the task 1 program cell again Step2: Task 2 Run the function below in the task 2 program cell after defining the two variables below Define a new variable named radius and set its value to 5 Define a new variable named blockToUse and set its value to block.WOOD.id python drawings.drawMyCircle(radius, blockToUse) Now set the value of the variable named radius to 8 and the value of the variable named blockToUse to block.GLASS.id and run the same function in the task 2 program cell again Well done! Step3: 3D Shapes and Polyhedrons The picture above shows the solid shapes studied by the mathematicians Plato and Euclid. We will use the function drawings.drawSolid to build these solids. This function takes the arguments shape - name of the shape to build, which is one of "TETRAHEDRON", "OCTAHEDRON" or "CUBE" length - length of the side of the shape to build e.g., 5 blockId - id of the block to build with e.g., block.STONE.id ```python drawings.drawSolid(shape,length,blockId) e.g., drawings.drawSolid("TETRAHEDRON",5,block.STONE.id) ``` Task 3 Use the building function drawings.drawSolid to build a cube with length 5 and using the block block.GLASS.id Step4: Task 4 Run the function below in the task 2 program cell after defining the three variables below Define a new variable named shape and set its value to "CUBE" Define a new variable named length and set its value to 5 Define a new variable named blockToUse and set its value to block.GLASS.id python drawings.drawSolid(shape, length, blockToUse) Now set the value of the variable named shape to "TERAHEDRON" and the value of the variable named blockToUse to block.STONE.id and run the same function in the task 2 program cell again Well done!
Python Code: import sys sys.path.append('/home/pi/minecraft-programming') import mcpi.block as block import time import drawings Explanation: Variables and 3D Shapes In the last class we used functions and arguments to build circles, spheres and hollow spheres of different radii. Lets go ahead and build some 3D solid shapes as well. Before we can do so we need to learn about Variables and about solids shapes called Polyhedrons Variables A variable is a box or container to hold a value. You can put a different value in a box everytime. Number values like 1, 0, -10 are called integers Decimal values like 3.2, 1003.4, -4.5 are called floats Word values like "Steve", "Hi Brooks School" are called strings Variables have names. Programs can use variables names instead of raw integers and strings which is very handy. E.g., in the program below, the variable with the name positionX has the integer value 10 and the variable with name message has the value "Hi Brooks School" python positionX = 10 message = "Hi Brooks School" In the next few tasks, you will practice using variables. Start Minecraft and run the program cell below before you begin your tasks. End of explanation # Task 1 program userName="blah" mc.postToChat(userName) Explanation: Task 1 Set the value of the variable named userName to "Steve" and run the function in the task 1 program cell Now set the value of the variable named userName to "Brooks" and run the function in the task 1 program cell again End of explanation # Task 2 program drawings.drawMyCircle(radius, blockToUse) Explanation: Task 2 Run the function below in the task 2 program cell after defining the two variables below Define a new variable named radius and set its value to 5 Define a new variable named blockToUse and set its value to block.WOOD.id python drawings.drawMyCircle(radius, blockToUse) Now set the value of the variable named radius to 8 and the value of the variable named blockToUse to block.GLASS.id and run the same function in the task 2 program cell again Well done! End of explanation # Task 3 program Explanation: 3D Shapes and Polyhedrons The picture above shows the solid shapes studied by the mathematicians Plato and Euclid. We will use the function drawings.drawSolid to build these solids. This function takes the arguments shape - name of the shape to build, which is one of "TETRAHEDRON", "OCTAHEDRON" or "CUBE" length - length of the side of the shape to build e.g., 5 blockId - id of the block to build with e.g., block.STONE.id ```python drawings.drawSolid(shape,length,blockId) e.g., drawings.drawSolid("TETRAHEDRON",5,block.STONE.id) ``` Task 3 Use the building function drawings.drawSolid to build a cube with length 5 and using the block block.GLASS.id End of explanation # Task 4 program drawings.drawSolid(shape, length, blockToUse) Explanation: Task 4 Run the function below in the task 2 program cell after defining the three variables below Define a new variable named shape and set its value to "CUBE" Define a new variable named length and set its value to 5 Define a new variable named blockToUse and set its value to block.GLASS.id python drawings.drawSolid(shape, length, blockToUse) Now set the value of the variable named shape to "TERAHEDRON" and the value of the variable named blockToUse to block.STONE.id and run the same function in the task 2 program cell again Well done! End of explanation
5,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Sta 663 Final Project by Hao Sheng, Xiaozhou Wang netid Step1: Benchmark of vectorization Step2: As for the optimization, we employed vectorization to avoid the use of triple for-loops under the update section of the Baum-Welch algorithm. We used broadcasting with numpy.newaxis to implement Baum-Welch algorithm much faster. As we can see from Benchmark part in the report, under class HMM we have 2 functions for Baum-Welch algorithm called Baum_Welch and Baum_Welch_fast. In Baum_Welch_fast, vectorization is applied when calculating $\xi$ while in Baum_Welch, we use a for loop. Notice in Baum_Welch, all other parts are implemented with vectorization. This is just an example how vectorization greatly improve the speed. Notice that the run time for vectorized Baum-Welch algorithm is 2.43 s per loop (with scaling) and 1 s per loop (without scaling) compared to 4.01 s per loop (with scaling) and 261 s per loop (without scaling). Other functions are implemented with vectorization as well. Vectorization greatly improves our time performance. Simulations Effect of chain length Step3: From the plot we can see that the length of the chain does have an effect on the performance of Baum-Welch Algorithm and Viterbi decoding. We can see that when the chain is too long, the algorithms tend to have a bad results. Effects of initial values in Baum-Welch Algorithm Step4: From this part, we can see that the choice of initial values are greatly important. Because Baum-Welch algorithm does not guarantee global maximum, a bad choice of initial values will make Baum-Welch Algorithm to be trapped in a local maximum. Moreover, our experiments show that the initial values for emission matrix $B$ are more important by comparing initial values 3 and 4. The initial parameters represent your belief. Effect of number of iteration in Baum-Welch Algorithm Step5: In this initial condition, we can see one feature of Baum-Welch Algorithm Step6: In other situations, increasing the number of iterations in Baum-Welch Algorithm tends to better fit the data. Applications Step7: Comparative Analysis Step8: Comparing Viterbi decoding Step9: From the above we can see that we coded our Viterbi algorith correctly. But the time complexity is not good enought. When we check the source code of hmmlearn, we see that they used C to make things faster. In the future, we might want to use c++ to implement this algorithm and wrap it for python. Comparing Baum-Welch Algorithm
Python Code: import numpy as np from numpy import random from collections import deque import matplotlib.pyplot as plt import HMM import pandas as pd from hmmlearn import hmm Explanation: Sta 663 Final Project by Hao Sheng, Xiaozhou Wang netid: hs220, xw106 email: {hao.sheng,xiaozhou.wang}@duke.edu Please make sure you have installed our package before runing this ipython notebook !! hmmlearn (implmented by others) can be installed through pip3 install hmmlearn in shell This project implements the memory sparse version of Viterbi algorithm and Baum-Welch algorithm to hidden Markov Model. The whole project is based on the paper ''Implementing EM and Viterbi algorithms for Hidden Markov Model in linear memory'', written by Alexander Churbanov and Stephen Winters-Hilt. Loading packages End of explanation pi=np.array([.3,.3,.4]) A=np.array([[.2,.3,.5],[.1,.5,.4],[.6,.1,.3]]) B=np.array([[0.1,0.5,0.4],[0.2,0.4,0.4],[0.3,0.6,0.1]]) states,sequence=HMM.sim_HMM(A,B,pi,100) %timeit HMM.Baum_Welch(A,B,pi,sequence,1000,0,scale=True) %timeit HMM.hmm_unoptimized.Baum_Welch(A,B,pi,sequence,1000,0,scale=True) %timeit HMM.Baum_Welch(A,B,pi,sequence,1000,0,scale=False) %timeit HMM.hmm_unoptimized.Baum_Welch(A,B,pi,sequence,1000,0,scale=False) Explanation: Benchmark of vectorization End of explanation A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]]) B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]]) pi=np.array([0.25,0.25,0.5]) A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.3,0.3,0.4]) lengths=[50,100,200,500,1000] acc=[] k=30 for i in lengths: mean_acc=0 for j in range(k): states,sequence=HMM.sim_HMM(A,B,pi,i) Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init, pi_init,sequence,10,0,True) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) mean_acc=mean_acc+np.mean(seq_hat==states) acc.append(mean_acc/k) plt.plot(lengths,acc) Explanation: As for the optimization, we employed vectorization to avoid the use of triple for-loops under the update section of the Baum-Welch algorithm. We used broadcasting with numpy.newaxis to implement Baum-Welch algorithm much faster. As we can see from Benchmark part in the report, under class HMM we have 2 functions for Baum-Welch algorithm called Baum_Welch and Baum_Welch_fast. In Baum_Welch_fast, vectorization is applied when calculating $\xi$ while in Baum_Welch, we use a for loop. Notice in Baum_Welch, all other parts are implemented with vectorization. This is just an example how vectorization greatly improve the speed. Notice that the run time for vectorized Baum-Welch algorithm is 2.43 s per loop (with scaling) and 1 s per loop (without scaling) compared to 4.01 s per loop (with scaling) and 261 s per loop (without scaling). Other functions are implemented with vectorization as well. Vectorization greatly improves our time performance. Simulations Effect of chain length End of explanation A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]]) B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]]) pi=np.array([0.25,0.25,0.5]) ############INITIAL VALUES 1############### A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.3,0.3,0.4]) k=50 acc=np.zeros(k) for i in range(k): states,sequence=HMM.sim_HMM(A,B,pi,500) Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,10,0,False) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[i]=np.mean(seq_hat==states) print("Accuracy: ",np.mean(acc)) ############INITIAL VALUES 2############### A_init=np.array([[0.5,0.25,0.25],[0.1,0.4,0.5],[0.25,0.1,0.65]]) B_init=np.array([[0.3,0.4,0.2,0.1],[0.1,0.5,0.2,0.2],[0.1,0.1,0.4,0.4]]) pi_init=np.array([0.5,0.2,0.3]) k=50 acc=np.zeros(k) for i in range(k): states,sequence=HMM.sim_HMM(A,B,pi,500) Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,10,0,True) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[i]=np.mean(seq_hat==states) print("Accuracy: ",np.mean(acc)) ############INITIAL VALUES 3############### A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.3,0.4,0.2,0.1],[0.1,0.5,0.2,0.2],[0.1,0.1,0.4,0.4]]) pi_init=np.array([0.5,0.2,0.3]) k=50 acc=np.zeros(k) for i in range(k): states,sequence=HMM.sim_HMM(A,B,pi,500) Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,10,0,True) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[i]=np.mean(seq_hat==states) print("Accuracy: ",np.mean(acc)) ############INITIAL VALUES 4############### A_init=np.array([[0.5,0.25,0.25],[0.1,0.4,0.5],[0.25,0.1,0.65]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.5,0.2,0.3]) k=50 acc=np.zeros(k) for i in range(k): states,sequence=HMM.sim_HMM(A,B,pi,500) Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,10,0,True) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[i]=np.mean(seq_hat==states) print("Accuracy: ",np.mean(acc)) Explanation: From the plot we can see that the length of the chain does have an effect on the performance of Baum-Welch Algorithm and Viterbi decoding. We can see that when the chain is too long, the algorithms tend to have a bad results. Effects of initial values in Baum-Welch Algorithm End of explanation ############INITIAL VALUES 1############### A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.3,0.3,0.4]) n_iter=[1,5,10,25,50,100,500] acc=np.zeros([k,len(n_iter)]) k=30 for j in range(k): states,sequence=HMM.sim_HMM(A,B,pi,100) t=0 for i in n_iter: Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,i,0,False) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[j,t]=np.mean(seq_hat==states) t+=1 plt.plot(n_iter,np.mean(acc,axis=0)) Explanation: From this part, we can see that the choice of initial values are greatly important. Because Baum-Welch algorithm does not guarantee global maximum, a bad choice of initial values will make Baum-Welch Algorithm to be trapped in a local maximum. Moreover, our experiments show that the initial values for emission matrix $B$ are more important by comparing initial values 3 and 4. The initial parameters represent your belief. Effect of number of iteration in Baum-Welch Algorithm End of explanation ############INITIAL VALUES 2############### A_init=np.array([[0.5,0.25,0.25],[0.1,0.4,0.5],[0.25,0.1,0.65]]) B_init=np.array([[0.3,0.4,0.2,0.1],[0.1,0.5,0.2,0.2],[0.1,0.1,0.4,0.4]]) pi_init=np.array([0.5,0.2,0.3]) n_iter=[1,5,10,25,50,100,500] acc=np.zeros([k,len(n_iter)]) k=30 for j in range(k): states,sequence=HMM.sim_HMM(A,B,pi,100) t=0 for i in n_iter: Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,i,0,False) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[j,t]=np.mean(seq_hat==states) t+=1 plt.plot(n_iter,np.mean(acc,axis=0)) ############INITIAL VALUES 3############### A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.3,0.4,0.2,0.1],[0.1,0.5,0.2,0.2],[0.1,0.1,0.4,0.4]]) pi_init=np.array([0.5,0.2,0.3]) n_iter=[1,5,10,25,50,100,500] acc=np.zeros([k,len(n_iter)]) k=30 for j in range(k): states,sequence=HMM.sim_HMM(A,B,pi,100) t=0 for i in n_iter: Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,i,0,False) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[j,t]=np.mean(seq_hat==states) t+=1 plt.plot(n_iter,np.mean(acc,axis=0)) ############INITIAL VALUES 4############### A_init=np.array([[0.5,0.25,0.25],[0.1,0.4,0.5],[0.25,0.1,0.65]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.5,0.2,0.3]) n_iter=[1,5,10,25,50,100,500] acc=np.zeros([k,len(n_iter)]) k=30 for j in range(k): states,sequence=HMM.sim_HMM(A,B,pi,100) t=0 for i in n_iter: Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init,pi_init, sequence,i,0,False) seq_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc[j,t]=np.mean(seq_hat==states) t+=1 plt.plot(n_iter,np.mean(acc,axis=0)) Explanation: In this initial condition, we can see one feature of Baum-Welch Algorithm: Baum-Welch Algorithm tends to overfit the data, which is $P(Y|\theta_{final})>P(Y|\theta_{true})$. End of explanation dat=pd.read_csv("data/weather-test2-1000.txt",skiprows=1,header=None) dat.head(5) seq=dat[1].map({"no":0,"yes":1}).tolist() states=dat[0].map({"sunny":0,"rainy":1,"foggy":2}) initial_A=np.array([[0.7,0.2,0.1],[0.3,0.6,0.1],[0.1,0.6,0.3]]) initial_B=np.array([[0.9,0.1],[0.1,0.9],[0.4,0.6]]) initial_pi=np.array([0.4,0.4,0.2]) Ahat,Bhat,pihat=HMM.Baum_Welch(initial_A,initial_B,initial_pi,seq, max_iter=100,threshold=0,scale=True) states_hat=HMM.Viterbi(Ahat,Bhat,pihat,seq) print(np.mean(states_hat==states)) Explanation: In other situations, increasing the number of iterations in Baum-Welch Algorithm tends to better fit the data. Applications End of explanation A=np.array([[0.1,0.5,0.4],[0.3,0.5,0.2],[0.7,0.2,0.1]]) B=np.array([[0.1,0.1,0.1,0.7],[0.5,0.5,0,0],[0.7,0.1,0.1,0.1]]) pi=np.array([0.25,0.25,0.5]) A_init=np.array([[0.2,0.6,0.2],[0.25,0.5,0.25],[0.6,0.2,0.2]]) B_init=np.array([[0.05,0.1,0.15,0.7],[0.4,0.4,0.1,0.1],[0.6,0.2,0.2,0.2]]) pi_init=np.array([0.3,0.3,0.4]) states,sequence=HMM.sim_HMM(A,B,pi,100) Explanation: Comparative Analysis End of explanation mod=hmm.MultinomialHMM(n_components=3) mod.startprob_=pi mod.transmat_=A mod.emissionprob_=B res_1=mod.decode(np.array(sequence).reshape([100,1]))[1] res_2=HMM.Viterbi(A,B,pi,sequence) np.array_equal(res_1,res_2) %timeit -n100 mod.decode(np.array(sequence).reshape([100,1])) %timeit -n100 HMM.Viterbi(A,B,pi,sequence) Explanation: Comparing Viterbi decoding End of explanation k=50 acc=[] for i in range(k): Ahat,Bhat,pihat=HMM.Baum_Welch(A_init,B_init, pi_init,sequence,max_iter=10, threshold=0,scale=True) states_hat=HMM.Viterbi(Ahat,Bhat,pihat,sequence) acc.append(np.mean(states_hat==states)) plt.plot(acc) k=50 acc=[] for i in range(k): mod=hmm.MultinomialHMM(n_components=3) mod=mod.fit(np.array(sequence).reshape([100,1])) pred_states=mod.decode(np.array(sequence).reshape([100,1]))[1] acc.append(np.mean(pred_states==states)) plt.plot(acc) Explanation: From the above we can see that we coded our Viterbi algorith correctly. But the time complexity is not good enought. When we check the source code of hmmlearn, we see that they used C to make things faster. In the future, we might want to use c++ to implement this algorithm and wrap it for python. Comparing Baum-Welch Algorithm End of explanation
5,304
Given the following text description, write Python code to implement the functionality described below step by step Description: 用ConfigParser模块读写conf配置文件 ConfigParser是Python内置的一个读取配置文件的模块,用它来读取和修改配置文件非常方便,本文介绍一下它的基本用法。 数据准备 假设当前目录下有一个名为sys.conf的配置文件,其内容如下: ```bash [db] db_host=127.0.0.1 db_port=22 db_user=root db_pass=root123 [concurrent] thread = 10 processor = 20 ``` 注:配置文件中,各个配置项其实是用等号'='隔开的键值对,这个等号两边如果有空白符,在处理的时候都会被自动去掉。但是key之前不能存在空白符,否则会报错。 配置文件介绍 配置文件即conf文件,其文件结构多为键值对的文件结构,比如上面的sys.conf文件。 conf文件有2个层次结构,[]中的文本是section的名称,下面的键值对列表是item,代表每个配置项的键和值。 初始化ConfigParser实例 Step1: 读取所有的section列表 section即[]中的内容。 Step2: 读取指定section下options key列表 options即某个section下的每个键值对的key. Step3: 获取指定section下的键值对字典列表 Step4: 按照指定数据类型读取配置值 cf对象有get()、getint()、getboolean()、getfloat()四种方法来读取不同数据类型的配置项的值。 Step5: 修改某个配置项的值 比如要修改一下数据库的密码,可以这样修改: Step6: 添加一个section Step7: 执行上面代码后,sys.conf文件多了一个section,内容如下: bash [log] name = mylog.log num = 100 size = 10.55 auto_save = True info = %(bar)s is %(baz)s! 移除某个section Step8: 移除某个option
Python Code: import ConfigParser cf = ConfigParser.ConfigParser() cf.read('./sys.conf') Explanation: 用ConfigParser模块读写conf配置文件 ConfigParser是Python内置的一个读取配置文件的模块,用它来读取和修改配置文件非常方便,本文介绍一下它的基本用法。 数据准备 假设当前目录下有一个名为sys.conf的配置文件,其内容如下: ```bash [db] db_host=127.0.0.1 db_port=22 db_user=root db_pass=root123 [concurrent] thread = 10 processor = 20 ``` 注:配置文件中,各个配置项其实是用等号'='隔开的键值对,这个等号两边如果有空白符,在处理的时候都会被自动去掉。但是key之前不能存在空白符,否则会报错。 配置文件介绍 配置文件即conf文件,其文件结构多为键值对的文件结构,比如上面的sys.conf文件。 conf文件有2个层次结构,[]中的文本是section的名称,下面的键值对列表是item,代表每个配置项的键和值。 初始化ConfigParser实例 End of explanation s = cf.sections() print '【Output】' print s Explanation: 读取所有的section列表 section即[]中的内容。 End of explanation opt = cf.options('concurrent') print '【Output】' print opt Explanation: 读取指定section下options key列表 options即某个section下的每个键值对的key. End of explanation items = cf.items('concurrent') print '【Output】' print items Explanation: 获取指定section下的键值对字典列表 End of explanation db_host = cf.get('db','db_host') db_port = cf.getint('db','db_port') thread = cf.getint('concurrent','thread') print '【Output】' print db_host,db_port,thread Explanation: 按照指定数据类型读取配置值 cf对象有get()、getint()、getboolean()、getfloat()四种方法来读取不同数据类型的配置项的值。 End of explanation cf.set('db','db_pass','newpass') # 修改完了要写入才能生效 with open('sys.conf','w') as f: cf.write(f) Explanation: 修改某个配置项的值 比如要修改一下数据库的密码,可以这样修改: End of explanation cf.add_section('log') cf.set('log','name','mylog.log') cf.set('log','num',100) cf.set('log','size',10.55) cf.set('log','auto_save',True) cf.set('log','info','%(bar)s is %(baz)s!') # 同样的,要写入才能生效 with open('sys.conf','w') as f: cf.write(f) Explanation: 添加一个section End of explanation cf.remove_section('log') # 同样的,要写入才能生效 with open('sys.conf','w') as f: cf.write(f) Explanation: 执行上面代码后,sys.conf文件多了一个section,内容如下: bash [log] name = mylog.log num = 100 size = 10.55 auto_save = True info = %(bar)s is %(baz)s! 移除某个section End of explanation cf.remove_option('db','db_pass') # 同样的,要写入才能生效 with open('sys.conf','w') as f: cf.write(f) Explanation: 移除某个option End of explanation
5,305
Given the following text description, write Python code to implement the functionality described below step by step Description: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created for each input device and coroutines used to process the results. To demonstrate, we recreate the flashing LEDs example in the getting started notebook but using interrupts to avoid polling the GPIO devices. The aim is have holding a button result in the corresponding LED flashing. Initialising the Enviroment First we import an instantiate all required classes to interact with the buttons, switches and LED and ensure the base overlay is loaded. Step1: Define the flash LED task Next step is to create a task that waits for the button to be pressed and flash the LED until the button is released. The while True loop ensures that the coroutine keeps running until cancelled so that multiple presses of the same button can be handled. Step2: Create the task As there are four buttons we want to check, we create four tasks. The function asyncio.ensure_future is used to convert the coroutine to a task and schedule it in the event loop. The tasks are stored in an array so they can be referred to later when we want to cancel them. Step3: Monitoring the CPU Usage One of the advantages of interrupt-based I/O is to minimised CPU usage while waiting for events. To see how CPU usages is impacted by the flashing LED tasks we create another task that prints out the current CPU utilisation every 3 seconds. Step4: Run the event loop All of the blocking wait_for commands will run the event loop until the condition is met. All that is needed is to call the blocking wait_for_level method on the switch we are using as the termination condition. While waiting for switch 0 to get high, users can press any push button on the board to flash the corresponding LED. While this loop is running, try opening a terminal and running top to see that python is consuming no CPU cycles while waiting for peripherals. As this code runs until the switch 0 is high, make sure it is low before running the example. Step5: Clean up Even though the event loop has stopped running, the tasks are still active and will run again when the event loop is next used. To avoid this, the tasks should be cancelled when they are no longer needed. Step6: Now if we re-run the event loop, nothing will happen when we press the buttons. The process will block until the switch is set back down to the low position.
Python Code: from pynq import PL from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit") Explanation: Using Interrupts and asyncio for Buttons and Switches This notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created for each input device and coroutines used to process the results. To demonstrate, we recreate the flashing LEDs example in the getting started notebook but using interrupts to avoid polling the GPIO devices. The aim is have holding a button result in the corresponding LED flashing. Initialising the Enviroment First we import an instantiate all required classes to interact with the buttons, switches and LED and ensure the base overlay is loaded. End of explanation import asyncio @asyncio.coroutine def flash_led(num): while True: yield from base.buttons[num].wait_for_value_async(1) while base.buttons[num].read(): base.leds[num].toggle() yield from asyncio.sleep(0.1) base.leds[num].off() Explanation: Define the flash LED task Next step is to create a task that waits for the button to be pressed and flash the LED until the button is released. The while True loop ensures that the coroutine keeps running until cancelled so that multiple presses of the same button can be handled. End of explanation tasks = [asyncio.ensure_future(flash_led(i)) for i in range(4)] Explanation: Create the task As there are four buttons we want to check, we create four tasks. The function asyncio.ensure_future is used to convert the coroutine to a task and schedule it in the event loop. The tasks are stored in an array so they can be referred to later when we want to cancel them. End of explanation import psutil @asyncio.coroutine def print_cpu_usage(): # Calculate the CPU utilisation by the amount of idle time # each CPU has had in three second intervals last_idle = [c.idle for c in psutil.cpu_times(percpu=True)] while True: yield from asyncio.sleep(3) next_idle = [c.idle for c in psutil.cpu_times(percpu=True)] usage = [(1-(c2-c1)/3) * 100 for c1,c2 in zip(last_idle, next_idle)] print("CPU Usage: {0:3.2f}%, {1:3.2f}%".format(*usage)) last_idle = next_idle tasks.append(asyncio.ensure_future(print_cpu_usage())) Explanation: Monitoring the CPU Usage One of the advantages of interrupt-based I/O is to minimised CPU usage while waiting for events. To see how CPU usages is impacted by the flashing LED tasks we create another task that prints out the current CPU utilisation every 3 seconds. End of explanation if base.switches[0].read(): print("Please set switch 0 low before running") else: base.switches[0].wait_for_value(1) Explanation: Run the event loop All of the blocking wait_for commands will run the event loop until the condition is met. All that is needed is to call the blocking wait_for_level method on the switch we are using as the termination condition. While waiting for switch 0 to get high, users can press any push button on the board to flash the corresponding LED. While this loop is running, try opening a terminal and running top to see that python is consuming no CPU cycles while waiting for peripherals. As this code runs until the switch 0 is high, make sure it is low before running the example. End of explanation [t.cancel() for t in tasks] Explanation: Clean up Even though the event loop has stopped running, the tasks are still active and will run again when the event loop is next used. To avoid this, the tasks should be cancelled when they are no longer needed. End of explanation base.switches[0].wait_for_value(0) Explanation: Now if we re-run the event loop, nothing will happen when we press the buttons. The process will block until the switch is set back down to the low position. End of explanation
5,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Building a System Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). Step1: From now on, we'll just quickly do common setup at the beginning of each tutorial. For full gory details on the general concepts here, make sure to read General Concepts. We'll always start by doing our basic imports, setting up a logger, and initializing an empty Bundle. Step2: Default Systems Although the default empty Bundle doesn't include a system, there are available constructors that create default systems. To create a simple binary with component tags 'binary', 'primary', and 'secondary' (as above), you could call Step3: or for short Step4: To build the same binary but as a contact system, you would call Step5: For more details on dealing with contact binary systems, see the Contact Binary Example Script Adding Components Manually By default, an empty Bundle does not contain any information about our system. So, let's first start by adding a few stars. Here we'll call the generic add_component method. This method works for any type of component in the system - stars, orbits, planets, disks, rings, spots, etc. The first argument needs to be a callable or the name of a callable in phoebe.parameters.component which include the following options Step6: But there are also shortcut methods for add_star and add_orbit. In these cases you don't need to provide the function, but only the component tag of your star/orbit. Any of these functions also accept values for any of the qualifiers of the created parameters. Step7: Here we call the add_component method of the bundle with several arguments Step8: Defining the Hierarchy At this point all we've done is add a bunch of Parameters to our Bundle, but we still need to specify the hierarchical setup of our system. Here we want to place our two stars (with component tags 'primary' and 'secondary') in our orbit (with component tag 'binary'). This can be done with several different syntaxes Step9: or Step10: If you access the value that this set, you'll see that it really just resulted in a simple string representation Step11: We could just as easily have used this string to set the hierarchy Step12: If at any point we want to flip the primary and secondary components or make this binary a triple, its seriously as easy as changing this hierarchy and everything else will adjust as needed (including cross-ParameterSet constraints, and datasets) The Hierarchy Parameter Setting the hierarchy just sets the value of a single parameter (although it may take some time because it also does a lot of paperwork and manages constraints between components in the system). You can access that parameter as usual Step13: or through any of these shortcuts Step14: This hierarchy parameter then has several methods unique to itself. You can, for instance, list the component tags of all the stars or orbits in the hierarchy Step15: Or you can ask for the component tag of the top-level item in the hierarchy Step16: And request the parent, children, child, or sibling of any item in the hierarchy Step17: We can also check whether a given component (by component tag) is the primary or secondary component in its parent orbit. Note that here its just a coincidence (although on purpose) that the component tag is also 'secondary'.
Python Code: !pip install -I "phoebe>=2.0,<2.1" Explanation: Building a System Setup Let's first make sure we have the latest version of PHOEBE 2.0 installed. (You can comment out this line if you don't use pip for your installation or don't want to update to the latest release). End of explanation import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt logger = phoebe.logger() b = phoebe.Bundle() Explanation: From now on, we'll just quickly do common setup at the beginning of each tutorial. For full gory details on the general concepts here, make sure to read General Concepts. We'll always start by doing our basic imports, setting up a logger, and initializing an empty Bundle. End of explanation b = phoebe.Bundle.default_binary() Explanation: Default Systems Although the default empty Bundle doesn't include a system, there are available constructors that create default systems. To create a simple binary with component tags 'binary', 'primary', and 'secondary' (as above), you could call: End of explanation b = phoebe.default_binary() print b.hierarchy Explanation: or for short: End of explanation b = phoebe.default_binary(contact_binary=True) print b.hierarchy Explanation: To build the same binary but as a contact system, you would call: End of explanation b = phoebe.Bundle() b.add_component(phoebe.component.star, component='primary') b.add_component('star', component='secondary') Explanation: For more details on dealing with contact binary systems, see the Contact Binary Example Script Adding Components Manually By default, an empty Bundle does not contain any information about our system. So, let's first start by adding a few stars. Here we'll call the generic add_component method. This method works for any type of component in the system - stars, orbits, planets, disks, rings, spots, etc. The first argument needs to be a callable or the name of a callable in phoebe.parameters.component which include the following options: orbit star envelope add_component also takes a keyword argument for the 'component' tag. Here we'll give them component tags 'primary' and 'secondary' - but note that these are merely convenience labels and do not hold any special roles. Some tags, however, are forbidden if they clash with other tags or reserved values - so if you get error stating the component tag is forbidden, try using a different string. End of explanation b.add_star('extrastarforfun', teff=6000) Explanation: But there are also shortcut methods for add_star and add_orbit. In these cases you don't need to provide the function, but only the component tag of your star/orbit. Any of these functions also accept values for any of the qualifiers of the created parameters. End of explanation b.add_orbit('binary') Explanation: Here we call the add_component method of the bundle with several arguments: a function (or the name of a function) in phoebe.parameters.component. This function tells the bundle what parameters need to be added. component: the tag that we want to give this component for future reference. any additional keyword arguments: you can also provide initial values for Parameters that you know will be created. In the last example you can see that the effective temperature will already be set to 6000 (in default units which is K). and then we'll do the same to add an orbit: End of explanation b.set_hierarchy(phoebe.hierarchy.binaryorbit, b['binary'], b['primary'], b['secondary']) Explanation: Defining the Hierarchy At this point all we've done is add a bunch of Parameters to our Bundle, but we still need to specify the hierarchical setup of our system. Here we want to place our two stars (with component tags 'primary' and 'secondary') in our orbit (with component tag 'binary'). This can be done with several different syntaxes: End of explanation b.set_hierarchy(phoebe.hierarchy.binaryorbit(b['binary'], b['primary'], b['secondary'])) Explanation: or End of explanation b.get_hierarchy() Explanation: If you access the value that this set, you'll see that it really just resulted in a simple string representation: End of explanation b.set_hierarchy('orbit:binary(star:primary, star:secondary)') Explanation: We could just as easily have used this string to set the hierarchy: End of explanation b['hierarchy@system'] Explanation: If at any point we want to flip the primary and secondary components or make this binary a triple, its seriously as easy as changing this hierarchy and everything else will adjust as needed (including cross-ParameterSet constraints, and datasets) The Hierarchy Parameter Setting the hierarchy just sets the value of a single parameter (although it may take some time because it also does a lot of paperwork and manages constraints between components in the system). You can access that parameter as usual: End of explanation b.get_hierarchy() b.hierarchy Explanation: or through any of these shortcuts: End of explanation print b.hierarchy.get_stars() print b.hierarchy.get_orbits() Explanation: This hierarchy parameter then has several methods unique to itself. You can, for instance, list the component tags of all the stars or orbits in the hierarchy: End of explanation print b.hierarchy.get_top() Explanation: Or you can ask for the component tag of the top-level item in the hierarchy End of explanation print b.hierarchy.get_parent_of('primary') print b.hierarchy.get_children_of('binary') print b.hierarchy.get_child_of('binary', 0) # here 0 means primary component, 1 means secondary print b.hierarchy.get_sibling_of('primary') Explanation: And request the parent, children, child, or sibling of any item in the hierarchy End of explanation print b.hierarchy.get_primary_or_secondary('secondary') Explanation: We can also check whether a given component (by component tag) is the primary or secondary component in its parent orbit. Note that here its just a coincidence (although on purpose) that the component tag is also 'secondary'. End of explanation
5,307
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Implicit generative model An implicit generative model only provides us with samples. Here for simplicity, we use a different set of samples obtained from the data distribution (i.e, we assume a perfect model). Step2: Explicit generative models An explicit generative model allows us to query for likelihoods under the learned distribution for points in the input space of the data. Here too we assume a perfect model in the plot, by using the data distribution pdf.
Python Code: import random import numpy as np import seaborn as sns import matplotlib.pyplot as plt import scipy sns.set(rc={"lines.linewidth": 2.8}, font_scale=2) sns.set_style("whitegrid") # We implement our own very simple mixture, relying on scipy for the mixture # components. class SimpleGaussianMixture(object): def __init__(self, mixture_weights, mixture_components): self.mixture_weights = mixture_weights self.mixture_components = mixture_components def sample(self, num_samples): # First sample from the mixture mixture_choices = np.random.choice( range(0, len(self.mixture_weights)), p=self.mixture_weights, size=num_samples ) # And then sample from the chosen mixture return np.array([self.mixture_components[mixture_choice].rvs(size=1) for mixture_choice in mixture_choices]) def pdf(self, x): value = 0.0 for index, weight in enumerate(self.mixture_weights): # Assuming using scipy distributions for components value += weight * self.mixture_components[index].pdf(x) return value mix = 0.4 mixture_weight = [mix, 1.0 - mix] mixture_components = [scipy.stats.norm(loc=-1, scale=0.1), scipy.stats.norm(loc=1, scale=0.5)] mixture = SimpleGaussianMixture(mixture_weight, mixture_components) mixture.sample(10) mixture.pdf([10, 1]) data_samples = mixture.sample(30) len(data_samples) data_samples plt.figure() plt.plot(data_samples, [0] * len(data_samples), "ro", ms=10, label="data") plt.axis("off") plt.ylim(-1, 2) plt.xticks([]) plt.yticks([]) # Use another set of samples to exemplify samples from the model data_samples2 = mixture.sample(30) Explanation: <a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/genmo_types_implicit_explicit.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Types of models: implicit or explicit models Author: Mihaela Rosca We use a simple example below (a mixture of Gaussians in 1 dimension) to exemplify the different between explicit generative models (with an associated density which we can query) and implicit generative models (which have an associated density but which we cannot query for likelhoods, but we can sample from it). End of explanation plt.figure(figsize=(12, 8)) plt.plot(data_samples, [0] * len(data_samples), "ro", ms=12, label="data") plt.plot(data_samples2, [0] * len(data_samples), "bd", ms=10, alpha=0.7, label="model samples") plt.axis("off") # plt.ylim(-0.2, 2) # plt.xlim(-2, 3) plt.xticks([]) plt.yticks([]) plt.legend(framealpha=0.0) Explanation: Implicit generative model An implicit generative model only provides us with samples. Here for simplicity, we use a different set of samples obtained from the data distribution (i.e, we assume a perfect model). End of explanation plt.figure(figsize=(12, 8)) plt.plot(data_samples, [0] * len(data_samples), "ro", ms=12, label="data") x_vals = np.linspace(-2.0, 3.0, int(1e4)) pdf_vals = mixture.pdf(x_vals) plt.plot(x_vals, pdf_vals, linewidth=4, label="model density") plt.axis("off") plt.ylim(-0.2, 2) plt.xlim(-2, 3) plt.xticks([]) plt.yticks([]) plt.legend(framealpha=0) Explanation: Explicit generative models An explicit generative model allows us to query for likelihoods under the learned distribution for points in the input space of the data. Here too we assume a perfect model in the plot, by using the data distribution pdf. End of explanation
5,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Função para codificar rótulos inteiros na codificação one-hot Esta função é também chamada de conversão para dados categóricos. Temos 3 classes de flores Step1: Primeira solução Step2: Segunda solução
Python Code: import numpy as np Explanation: Função para codificar rótulos inteiros na codificação one-hot Esta função é também chamada de conversão para dados categóricos. Temos 3 classes de flores: Iris setosa, Iris virginica and Iris versicolor. Estas classes podem ser codificadas como classes 0, 1 e 2 (rótulos numéricos) ou na codificação com 3 variáveis binárias: <table border="1"> <tr> <td>Espécie</td> <td>Y</td> <td>Y_oh[0]</td> <td>Y_oh[1]</td> <td>Y_oh[2]</td> </tr> <tr> <td>Iris setosa</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <td>Iris virginica</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> </tr> <tr> <td>Iris versicolor</td> <td>2</td> <td>0</td> <td>0</td> <td>1</td> </tr> </table> A função oneHotIt a seguir implementa de forma eficiente esta conversão, utilizando a facilidade de criação de arrays esparsos. A entrada da função é o vetor Y e a saída será um array com o mesmo número de linhas que o número de elementos de Y e a largura terá o número de colunas do maior rótulo disponível em Y: A título de ilustração e exercício de programação matricial, apresentamos a seguir duas implementações da função que converte os labels para a codificação "one-hot": End of explanation def oneHotIt2(Y,n_classes): Y = Y.reshape(-1,1) # matriz coluna i = np.arange(n_classes).reshape(1,n_classes) # matriz linha Y_oh = (Y == i).astype(int) return Y_oh Explanation: Primeira solução: Qual é a técnica? End of explanation def oneHotIt(Y,n_classes): n_samples = Y.size # número de amostras i = np.arange(n_samples) Y_oh = np.zeros(shape=(n_samples,n_classes)) Y_oh[i,Y] = 1 return Y_oh Y = np.arange(10)%7 Y_oh = oneHotIt2(Y,7) Y_oh Y = np.arange(10000)%10 %timeit oneHotIt(Y,10000) %timeit oneHotIt2(Y,10000) Explanation: Segunda solução: Qual é a técnica? End of explanation
5,309
Given the following text description, write Python code to implement the functionality described below step by step Description: Andreas Alexopoulos 30 / 08 / 2016 Introduction The Beam Loss Monitoring system of the Large Hadron Collider close to the interaction points contains mostly gas ionization chambers working at room temperature, located far from the superconducting coils of the magnets. The system records particles lost from circulating proton beams, but is also sensitive to particles coming from the experimental collisions, which do not contribute significantly to the heat deposition in the superconducting coils. In the future, with beams of higher brightness resulting in higher luminosity, distinguishing between these interaction products and dangerous quench-provoking beam losses from the circulating beams will be difficult. It is proposed to optimize by locating beam loss monitors inside the cold mass of the magnets, housing the superconducting coils, in a super-fluid helium environment, at $1.9 K$. The dose then measured by such cryogenic beam loss monitors would more precisely correspond to the real dose deposited in the coil [1]. Irradiation tests of silicon & diamond detectors have been performed so that their performance and degradation under irradiation could be studied. In this contribution, data acquired during the cryogenic irradiation test of silicon and diamond detectors will be presented. The test took place between 28/10/2015 and 16/11/2015 at the IRRAD facility using a $24 GeV/c$ beam from the Proton Synchrotron. Initialization Python Packages The following analysis was performed using Python. In order for the notebook to run, an installation of Python version 2.7 is necessary, as well as additional packages such as jupyter, numpy, scipy and matplotlib. Step1: Input data Input for the analysis are data concerning the beam variables, as well as the detectors response. In addition, details which describe the different settings and actions done during the irradiation test have been introduced as constants and used. Step2: Beam Parameters In order to estimate the detectors charge collection efficiency, a good knowledge of the parameters of the beam is essential. These parameters were provided by the IRRAD facility, and included beam intensity and beam position measurements. Beam Intensity The beam intensity measurements was performed by a Secondary Emission Chamber, whose collected charge was continuously uploaded to CERNs logging database. The variable used to retrieve the data was MSC01.ZT8.107 Step3: Save to file
Python Code: from __future__ import print_function, division import warnings from collections import deque from datetime import datetime, timedelta from time import ctime from os.path import abspath, join from itertools import cycle import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch from matplotlib.lines import Line2D from matplotlib.dates import DateFormatter from matplotlib import rc from pytoolbox.syncdatasets import SyncDatasets rc('text', usetex=True) rc('font', family='serif', serif='Times New Roman') %matplotlib inline # Not always a good idea # %matplotlib nbagg Explanation: Andreas Alexopoulos 30 / 08 / 2016 Introduction The Beam Loss Monitoring system of the Large Hadron Collider close to the interaction points contains mostly gas ionization chambers working at room temperature, located far from the superconducting coils of the magnets. The system records particles lost from circulating proton beams, but is also sensitive to particles coming from the experimental collisions, which do not contribute significantly to the heat deposition in the superconducting coils. In the future, with beams of higher brightness resulting in higher luminosity, distinguishing between these interaction products and dangerous quench-provoking beam losses from the circulating beams will be difficult. It is proposed to optimize by locating beam loss monitors inside the cold mass of the magnets, housing the superconducting coils, in a super-fluid helium environment, at $1.9 K$. The dose then measured by such cryogenic beam loss monitors would more precisely correspond to the real dose deposited in the coil [1]. Irradiation tests of silicon & diamond detectors have been performed so that their performance and degradation under irradiation could be studied. In this contribution, data acquired during the cryogenic irradiation test of silicon and diamond detectors will be presented. The test took place between 28/10/2015 and 16/11/2015 at the IRRAD facility using a $24 GeV/c$ beam from the Proton Synchrotron. Initialization Python Packages The following analysis was performed using Python. In order for the notebook to run, an installation of Python version 2.7 is necessary, as well as additional packages such as jupyter, numpy, scipy and matplotlib. End of explanation ############################################################################### # INPUT DATA # ############################################################################### DATA_DIR = '/home/andalexo/cernbox/projects/cryoblm/2015_CryoIRRAD/20160801_Analysis/' AL_DOSE = np.mean([6.46e15, 7.23e15]) # FRONT, BACK, dosimetry AL_DOSE_ERR = 0.07 FILENAME_SEC = join(abspath(DATA_DIR), 'sec_counts.csv') SEC_DT_FMT = '%Y-%m-%d %H:%M:%S.%f' FILENAME_BPM = join(abspath(DATA_DIR), 'bpm3_raw.csv') BPM_DT_FMT = '%d/%m/%Y %H:%M:%S' BEAM_TIME_INTERVALS = [('2015-10-28 19:37:22.0', '2015-10-28 21:00:00.0'), ('2015-10-29 18:43:39.0', '2015-10-29 21:12:28.0'), ('2015-10-30 08:42:41.0', '2015-11-16 06:00:00.0')] # Used for the correlation of detectors charge and bpm charge FILENAME_QMBOX = join(abspath(DATA_DIR), 'qmbox_sum_out.csv') QMBOX_DT_FMT = '%Y/%m/%d %H:%M:%S.%f' vl_init = sorted([item for item in dir() if item[0] != '_'] + ['vl_init']) print('Memory init [%d]\n%s.' % (len(vl_init), vl_init) ) Explanation: Input data Input for the analysis are data concerning the beam variables, as well as the detectors response. In addition, details which describe the different settings and actions done during the irradiation test have been introduced as constants and used. End of explanation data = np.loadtxt(FILENAME_SEC, dtype=str, delimiter=',', unpack=True) ts = data[0] sec = np.asarray(data[1]).astype(np.float) # Cleaning of sec data # Values below 5000 counts for SEC will be considered invalid SEC_LOW_LIM = 5000 vi = np.where(sec > SEC_LOW_LIM)[0] # valid indexes print('Total entries: %d, Valid entries: %d, Invalid: %d' % (data[0].size, vi.size, sec.size - vi.size)) ts = ts[vi] sec = sec[vi] dt = np.array([datetime.strptime(item, SEC_DT_FMT) for item in ts]) Explanation: Beam Parameters In order to estimate the detectors charge collection efficiency, a good knowledge of the parameters of the beam is essential. These parameters were provided by the IRRAD facility, and included beam intensity and beam position measurements. Beam Intensity The beam intensity measurements was performed by a Secondary Emission Chamber, whose collected charge was continuously uploaded to CERNs logging database. The variable used to retrieve the data was MSC01.ZT8.107:COUNTS. In the following, data are loaded and displayed after removal of outliars. As outliars are considered entries with $counts\lt5000$. Load & clean data End of explanation res = np.array([ts, sec]) fn = 'sec_counts_proc.csv' np.savetxt(fn, np.transpose(res), fmt='%s', delimiter=',') print('File saved at:\n\t%s' % abspath(fn)) Explanation: Save to file End of explanation
5,310
Given the following text description, write Python code to implement the functionality described below step by step Description: Using the trained weights in an ensemble of neurons On the function points branch of nengo On the vision branch of nengo_extras Step1: Load the MNIST database Step2: Each digit is represented by a one hot vector where the index of the 1 represents the number Step3: Load the saved weight matrices that were created by training the model Step4: Functions to perform the inhibition of each ensemble Step5: The network where the mental imagery and rotation occurs The state, seed and ensemble parameters (including encoders) must all be the same for the saved weight matrices to work The number of neurons (n_hid) must be the same as was used for training The input must be shown for a short period of time to be able to view the rotation The recurrent connection must be from the neurons because the weight matices were trained on the neuron activities Step6: The following is not part of the brain model, it is used to view the output for the ensemble Since it's probing the neurons themselves, the output must be transformed from neuron activity to visual image Step7: Pickle the probe's output if it takes a long time to run Step8: Testing Step9: Just for fun
Python Code: import nengo import numpy as np import cPickle from nengo_extras.data import load_mnist from nengo_extras.vision import Gabor, Mask from matplotlib import pylab import matplotlib.pyplot as plt import matplotlib.animation as animation import scipy.ndimage from scipy.ndimage.interpolation import rotate Explanation: Using the trained weights in an ensemble of neurons On the function points branch of nengo On the vision branch of nengo_extras End of explanation # --- load the data img_rows, img_cols = 28, 28 (X_train, y_train), (X_test, y_test) = load_mnist() X_train = 2 * X_train - 1 # normalize to -1 to 1 X_test = 2 * X_test - 1 # normalize to -1 to 1 Explanation: Load the MNIST database End of explanation temp = np.diag([1]*10) ZERO = temp[0] ONE = temp[1] TWO = temp[2] THREE= temp[3] FOUR = temp[4] FIVE = temp[5] SIX = temp[6] SEVEN =temp[7] EIGHT= temp[8] NINE = temp[9] labels =[ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE] dim =28 Explanation: Each digit is represented by a one hot vector where the index of the 1 represents the number End of explanation label_weights = cPickle.load(open("label_weights_choose_enc1000.p", "rb")) activity_to_img_weights = cPickle.load(open("activity_to_img_weights_choose_enc1000.p", "rb")) #rotated_clockwise_after_encoder_weights = cPickle.load(open("rotated_clockwise_after_encoder_weights_rot_enc1000.p", "r")) rotated_counter_after_encoder_weights = cPickle.load(open("rotated_counter_after_encoder_weights_choose_enc1000.p", "r")) #identity_after_encoder_weights = cPickle.load(open("identity_after_encoder_weights1000.p","r")) #rotation_clockwise_weights = cPickle.load(open("rotation_clockwise_weights1000.p","rb")) #rotation_counter_weights = cPickle.load(open("rotation_weights1000.p","rb")) #Training with filters used on train images #low_pass_weights = cPickle.load(open("low_pass_weights1000.p", "rb")) #rotated_counter_after_encoder_weights_noise = cPickle.load(open("rotated_after_encoder_weights_counter_filter_noise5000.p", "r")) #rotated_counter_after_encoder_weights_filter = cPickle.load(open("rotated_after_encoder_weights_counter_filter5000.p", "r")) Explanation: Load the saved weight matrices that were created by training the model End of explanation #A value of zero gives no inhibition def inhibit_rotate_clockwise(t): if t < 0.5: return dim**2 else: return 0 def inhibit_rotate_counter(t): if t < 0.5: return 0 else: return dim**2 def inhibit_identity(t): if t < 0.3: return dim**2 else: return dim**2 def intense(img): newImg = img.copy() newImg[newImg < 0] = -1 newImg[newImg > 0] = 1 return newImg def node_func(t,x): #clean = scipy.ndimage.gaussian_filter(x, sigma=1) #clean = scipy.ndimage.median_filter(x, 3) clean = intense(x) return clean #Create stimulus at horizontal weight = np.dot(label_weights,activity_to_img_weights) img = np.dot(THREE,weight) img = scipy.ndimage.rotate(img.reshape(28,28),90).ravel() pylab.imshow(img.reshape(28,28),cmap="gray") plt.show() Explanation: Functions to perform the inhibition of each ensemble End of explanation rng = np.random.RandomState(9) n_hid = 1000 model = nengo.Network(seed=3) with model: #Stimulus only shows for brief period of time stim = nengo.Node(lambda t: THREE if t < 0.1 else 0) #nengo.processes.PresentInput(labels,1))# For cycling through input #Starting the image at horizontal #stim = nengo.Node(lambda t:img if t< 0.1 else 0) ens_params = dict( eval_points=X_train, neuron_type=nengo.LIF(), #Why not use LIF? intercepts=nengo.dists.Choice([-0.5]), max_rates=nengo.dists.Choice([100]), ) # linear filter used for edge detection as encoders, more plausible for human visual system #encoders = Gabor().generate(n_hid, (11, 11), rng=rng) #encoders = Mask((28, 28)).populate(encoders, rng=rng, flatten=True) ''' degrees = 6 #must have same number of excoders as neurons (Want each random encoder to have same encoder at every angle) encoders = Gabor().generate(n_hid/(360/degrees), (11, 11), rng=rng) encoders = Mask((28, 28)).populate(encoders, rng=rng, flatten=True) rotated_encoders = encoders.copy() #For each randomly generated encoder, create the same encoder at every angle (increments chosen by degree) for encoder in encoders: rotated_encoders = np.append(rotated_encoders, [encoder],axis =0) for i in range(1,59): #new_gabor = rotate(encoder.reshape(28,28),degrees*i,reshape = False).ravel() rotated_encoders = np.append(rotated_encoders, [rotate(encoder.reshape(28,28),degrees*i,reshape = False).ravel()],axis =0) #rotated_encoders = np.append(rotated_encoders, [encoder],axis =0) ''' rotated_encoders = cPickle.load(open("encoders.p", "r")) #Num of neurons does not divide evenly with 6 degree increments, so add random encoders extra_encoders = Gabor().generate(n_hid - len(rotated_encoders), (11, 11), rng=rng) extra_encoders = Mask((28, 28)).populate(extra_encoders, rng=rng, flatten=True) all_encoders = np.append(rotated_encoders, extra_encoders, axis =0) encoders = all_encoders #Ensemble that represents the image with different transformations applied to it ens = nengo.Ensemble(n_hid, dim**2, seed=3, encoders=encoders, **ens_params) #Connect stimulus to ensemble, transform using learned weight matrices nengo.Connection(stim, ens, transform = np.dot(label_weights,activity_to_img_weights).T) #nengo.Connection(stim, ens) #for rotated stim #Recurrent connection on the neurons of the ensemble to perform the rotation nengo.Connection(ens.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1) #nengo.Connection(ens.neurons, ens.neurons, transform = low_pass_weights.T, synapse=0.1) #Identity ensemble #ens_iden = nengo.Ensemble(n_hid,dim**2, seed=3, encoders=encoders, **ens_params) #Rotation ensembles #ens_clock_rot = nengo.Ensemble(n_hid,dim**2,seed=3,encoders=encoders, **ens_params) ens_counter_rot = nengo.Ensemble(n_hid,dim**2,seed=3,encoders=encoders, **ens_params) #Inhibition nodes #inhib_iden = nengo.Node(inhibit_identity) #inhib_clock_rot = nengo.Node(inhibit_rotate_clockwise) #inhib_counter_rot = nengo.Node(inhibit_rotate_counter) #Connect the main ensemble to each manipulation ensemble and back with appropriate transformation #Identity #nengo.Connection(ens.neurons, ens_iden.neurons,transform=identity_after_encoder_weights.T,synapse=0.1) #nengo.Connection(ens_iden.neurons, ens.neurons,transform=identity_after_encoder_weights.T,synapse=0.1) #Clockwise #nengo.Connection(ens.neurons, ens_clock_rot.neurons, transform = rotated_clockwise_after_encoder_weights.T,synapse=0.1) #nengo.Connection(ens_clock_rot.neurons, ens.neurons, transform = rotated_clockwise_after_encoder_weights.T,synapse = 0.1) #Counter-clockwise #nengo.Connection(ens.neurons, ens_counter_rot.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1) #nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1) #nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights_filter.T, synapse=0.1) #nengo.Connection(ens.neurons, ens_counter_rot.neurons, transform = low_pass_weights.T, synapse=0.1) #nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = low_pass_weights.T, synapse=0.1) #Clean up by a node #n = nengo.Node(node_func, size_in=dim**2) #nengo.Connection(ens.neurons,n,transform=activity_to_img_weights.T, synapse=0.1) #nengo.Connection(n,ens_counter_rot,synapse=0.1) #Connect the inhibition nodes to each manipulation ensemble #nengo.Connection(inhib_iden, ens_iden.neurons, transform=[[-1]] * n_hid) #nengo.Connection(inhib_clock_rot, ens_clock_rot.neurons, transform=[[-1]] * n_hid) #nengo.Connection(inhib_counter_rot, ens_counter_rot.neurons, transform=[[-1]] * n_hid) #Collect output, use synapse for smoothing probe = nengo.Probe(ens.neurons,synapse=0.1) sim = nengo.Simulator(model) sim.run(5) Explanation: The network where the mental imagery and rotation occurs The state, seed and ensemble parameters (including encoders) must all be the same for the saved weight matrices to work The number of neurons (n_hid) must be the same as was used for training The input must be shown for a short period of time to be able to view the rotation The recurrent connection must be from the neurons because the weight matices were trained on the neuron activities End of explanation '''Animation for Probe output''' fig = plt.figure() output_acts = [] for act in sim.data[probe]: output_acts.append(np.dot(act,activity_to_img_weights)) def updatefig(i): im = pylab.imshow(np.reshape(output_acts[i],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'),animated=True) return im, ani = animation.FuncAnimation(fig, updatefig, interval=0.1, blit=True) plt.show() #ouput_acts = sim.data[probe] plt.subplot(261) plt.title("100") pylab.imshow(np.reshape(output_acts[100],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(262) plt.title("500") pylab.imshow(np.reshape(output_acts[500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(263) plt.title("1000") pylab.imshow(np.reshape(output_acts[1000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(264) plt.title("1500") pylab.imshow(np.reshape(output_acts[1500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(265) plt.title("2000") pylab.imshow(np.reshape(output_acts[2000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(266) plt.title("2500") pylab.imshow(np.reshape(output_acts[2500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(267) plt.title("3000") pylab.imshow(np.reshape(output_acts[3000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(268) plt.title("3500") pylab.imshow(np.reshape(output_acts[3500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(269) plt.title("4000") pylab.imshow(np.reshape(output_acts[4000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(2,6,10) plt.title("4500") pylab.imshow(np.reshape(output_acts[4500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(2,6,11) plt.title("5000") pylab.imshow(np.reshape(output_acts[4999],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.show() Explanation: The following is not part of the brain model, it is used to view the output for the ensemble Since it's probing the neurons themselves, the output must be transformed from neuron activity to visual image End of explanation #The filename includes the number of neurons and which digit is being rotated filename = "mental_rotation_output_ONE_" + str(n_hid) + ".p" cPickle.dump(sim.data[probe], open( filename , "wb" ) ) Explanation: Pickle the probe's output if it takes a long time to run End of explanation testing = np.dot(ONE,np.dot(label_weights,activity_to_img_weights)) testing = output_acts[300] plt.subplot(131) pylab.imshow(np.reshape(testing,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) #Get image #testing = np.dot(ONE,np.dot(label_weights,activity_to_img_weights)) #noise = np.random.random([28,28]).ravel() testing = node_func(0,testing) plt.subplot(132) pylab.imshow(np.reshape(testing,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) #Get activity of image _, testing_act = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=testing) #Get encoder outputs testing_filter = np.dot(testing_act,rotated_counter_after_encoder_weights_filter) #Get activities testing_filter = ens.neuron_type.rates(testing_filter, sim.data[ens].gain, sim.data[ens].bias) for i in range(5): testing_filter = np.dot(testing_filter,rotated_counter_after_encoder_weights_filter) testing_filter = ens.neuron_type.rates(testing_filter, sim.data[ens].gain, sim.data[ens].bias) testing_filter = np.dot(testing_filter,activity_to_img_weights) testing_filter = node_func(0,testing_filter) _, testing_filter = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=testing_filter) #testing_rotate = np.dot(testing_rotate,rotation_weights) testing_filter = np.dot(testing_filter,activity_to_img_weights) plt.subplot(133) pylab.imshow(np.reshape(testing_filter,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.show() plt.subplot(121) pylab.imshow(np.reshape(X_train[0],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) #Get activity of image _, testing_act = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=X_train[0]) testing_rotate = np.dot(testing_act,activity_to_img_weights) plt.subplot(122) pylab.imshow(np.reshape(testing_rotate,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.show() Explanation: Testing End of explanation letterO = np.dot(ZERO,np.dot(label_weights,activity_to_img_weights)) plt.subplot(161) pylab.imshow(np.reshape(letterO,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) letterL = np.dot(SEVEN,label_weights) for _ in range(30): letterL = np.dot(letterL,rotation_weights) letterL = np.dot(letterL,activity_to_img_weights) plt.subplot(162) pylab.imshow(np.reshape(letterL,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) letterI = np.dot(ONE,np.dot(label_weights,activity_to_img_weights)) plt.subplot(163) pylab.imshow(np.reshape(letterI,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.subplot(165) pylab.imshow(np.reshape(letterI,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) letterV = np.dot(SEVEN,label_weights) for _ in range(40): letterV = np.dot(letterV,rotation_weights) letterV = np.dot(letterV,activity_to_img_weights) plt.subplot(164) pylab.imshow(np.reshape(letterV,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) letterA = np.dot(SEVEN,label_weights) for _ in range(10): letterA = np.dot(letterA,rotation_weights) letterA = np.dot(letterA,activity_to_img_weights) plt.subplot(166) pylab.imshow(np.reshape(letterA,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r')) plt.show() Explanation: Just for fun End of explanation
5,311
Given the following text description, write Python code to implement the functionality described below step by step Description: Useful Scripts Location of the scripts Here are some scripts that you may find useful. They are in the folder "./eppy/useful_scripts" And now for some housekeeping before we start off Step1: If you look in the folder "./eppy/useful_scripts", you fill find the following scripts The scripts are Step2: That was useful ! Now let us try running the program Step3: Redirecting output to a file Most scripts will print the output to a terminal. Sometimes we want to send the output to a file, so that we can save it for posterity. We can do that py using ">" with the filename after that. For eppy_version.py, it will look like this Step4: Now let us try this with two "idf" files that are slightly different. If we open them in a file comparing software, it would look like this Step5: There are 4 differences between the files. Let us see what idfdiff.py does with the two files. We will use the --html option to print out the diff in html format. Step6: It does look like html Step7: Pretty straight forward. Scroll up and look at the origin text files, and see how idfdiff.py understands the difference Now let us try the same thin in csv format Step8: We see the same output, but now in csv format. You can redirect it to a ".csv" file and open it up as a spreadsheet loopdiagram.py Diagrams of HVAC loops This script will draw all the loops in an idf file. It is a bit of a hack. So it will work on most files, but sometimes it will not Step9: Pretty straightforward. Simply open png file and you will see the loop diagram. (ignore the dot file for now. it will be documented later) So let us try this out with and simple example file. We have a very simple plant loop in "../resources/idffiles/V_7_2/plantloop.idf" Step10: The script prints out it's progress. On larger files, this might take a few seconds. If we open this file, it will look like the diagram below Note
Python Code: import os os.chdir("../eppy/useful_scripts") # changes directory, so we are where the scripts are located # you would normaly install eppy by doing # python setup.py install # or # pip install eppy # or # easy_install eppy # if you have not done so, the following three lines are needed import sys # pathnameto_eppy = 'c:/eppy' pathnameto_eppy = '../../' sys.path.append(pathnameto_eppy) Explanation: Useful Scripts Location of the scripts Here are some scripts that you may find useful. They are in the folder "./eppy/useful_scripts" And now for some housekeeping before we start off End of explanation %%bash # ignore the line above. It simply lets me run a command line from ipython notebook python eppy_version.py --help Explanation: If you look in the folder "./eppy/useful_scripts", you fill find the following scripts The scripts are: - eppy_version.py - idfdiff.py - loopdiagram.py - eppyreadtest_folder.py - eppyreadtest_file.py eppy_version.py Many scripts will print out some help information, if you use the --help option. Let us try that End of explanation %%bash # ignore the line above. It simply lets me run a command line from ipython notebook python eppy_version.py Explanation: That was useful ! Now let us try running the program End of explanation %%bash # ignore the line above. It simply lets me run a command line from ipython notebook python idfdiff.py -h Explanation: Redirecting output to a file Most scripts will print the output to a terminal. Sometimes we want to send the output to a file, so that we can save it for posterity. We can do that py using ">" with the filename after that. For eppy_version.py, it will look like this: Some of the following scripts will generate csv or html outputs. We can direct the output to a file with .html extension and open it in a browser Compare two idf files - idfdiff.py This script will compare two idf files. The results will be displayed printed in "csv" format or in "html" format. You would run the script from the command line. This would be the terminal on Mac or unix, and the dos prompt on windows. Let us look at the help for this script, by typing: End of explanation from eppy.useful_scripts import doc_images #no need to know this code, it just shows the image below for_images = doc_images for_images.display_png(for_images.filemerge) # display the image below Explanation: Now let us try this with two "idf" files that are slightly different. If we open them in a file comparing software, it would look like this: End of explanation %%bash # python idfdiff.py idd file1 file2 python idfdiff.py --html --idd ../resources/iddfiles/Energy+V7_2_0.idd ../resources/idffiles/V_7_2/constructions.idf ../resources/idffiles/V_7_2/constructions_diff.idf Explanation: There are 4 differences between the files. Let us see what idfdiff.py does with the two files. We will use the --html option to print out the diff in html format. End of explanation from eppy.useful_scripts import doc_images #no need to know this code, it just shows the image below from IPython.display import HTML h = HTML(open(doc_images.idfdiff_path, 'r').read()) h Explanation: It does look like html :-). We need to redirect this output to a file and then open the file in a browser to see what it looks like. Displayed below is the html file End of explanation %%bash # python idfdiff.py idd file1 file2 python idfdiff.py --csv --idd ../resources/iddfiles/Energy+V7_2_0.idd ../resources/idffiles/V_7_2/constr.idf ../resources/idffiles/V_7_2/constr_diff.idf Explanation: Pretty straight forward. Scroll up and look at the origin text files, and see how idfdiff.py understands the difference Now let us try the same thin in csv format End of explanation %%bash # ignore the line above. It simply lets me run a command line from ipython notebook python loopdiagram.py --help Explanation: We see the same output, but now in csv format. You can redirect it to a ".csv" file and open it up as a spreadsheet loopdiagram.py Diagrams of HVAC loops This script will draw all the loops in an idf file. It is a bit of a hack. So it will work on most files, but sometimes it will not :-(. But it is pretty useful when it works. If it does not work, send us the idf file and we'll try to fix the code Make sure grapphviz is installed for this script to work Again, we'll have to run the script from the terminal. Let us look at the help for this script End of explanation %%bash # ignore the line above. It simply lets me run a command line from ipython notebook python loopdiagram.py ../resources/iddfiles/Energy+V7_2_0.idd ../resources/idffiles/V_7_2/plantloop.idf Explanation: Pretty straightforward. Simply open png file and you will see the loop diagram. (ignore the dot file for now. it will be documented later) So let us try this out with and simple example file. We have a very simple plant loop in "../resources/idffiles/V_7_2/plantloop.idf" End of explanation from eppy.useful_scripts import doc_images #no need to know this code, it just shows the image below for_images = doc_images for_images.display_png(for_images.plantloop) # display the image below Explanation: The script prints out it's progress. On larger files, this might take a few seconds. If we open this file, it will look like the diagram below Note: the supply and demnd sides are not connected in the diagram, but shown seperately for clarity End of explanation
5,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Smart Underwriter! Step1: Underwrting Step2: Let's take a peek at the data. Step3: How many morgages have been prepaid in these three years? Step4: Remember prepay includes a common case that if you want to switch to another house. You will sell the current house that you live in. That would count as prepay too. Default Rate? Step5: Default rate is not very high in these three years. The general trend is going down, which make senses because the economy is getting better. Step6: It is very interesting to find out that "default" loans tends to have slightly higher loan-to-value (LTV) ratio on average, meaning they tends to have lower downpayment. Step7: Again, it is very interesting to find that default loans tend to have slightly lower credit score, on average.
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib import seaborn as sns pd.options.display.max_columns = 999 %matplotlib inline matplotlib.rcParams['savefig.dpi'] = 1.5 * matplotlib.rcParams['savefig.dpi'] Explanation: Smart Underwriter! End of explanation # Read the data inside: loan2011 = pd.read_csv('merged_summary_2011.csv') loan2010 = pd.read_csv('merged_summary_2010.csv') loan2012 = pd.read_csv('merged_summary_2012.csv') Explanation: Underwrting: In insurance, underwriting is to sign and accept liability and guaranteeing payment in case loss or damage occurs. Underwriting is provided by a large financial service provider such as a bank, insurer or investment house. From Wikipedia Drawbacks It was mainly done by human before. Subjective, concerns of equality. Need for computer aid underwriting Objective Non bias (regulatory requirement!) Fast There are products outside already: Desktop Underwriter From Fannie Loan Prospector From Freddie Goal: Develop a prediction model to predict the risk of the morgage Data: Fannie Mae Single Family House Morgage data (2000 - 2014) End of explanation loan2011.head() loan2011['Monthly.Rpt.Prd'] = pd.to_datetime(loan2011['Monthly.Rpt.Prd'], format = '%m/%d/%Y') loan2011['ORIG_DTE'] = pd.to_datetime(loan2011['ORIG_DTE'], format = '%m/%Y') loan = {'2011':loan2011, '2012': loan2012, '2010': loan2010} years = [] prepaid = {} default = {} loan_num = {} for key in loan.keys(): temp_size =len(loan[key]) temp_count = loan[key].groupby('Zero.Bal.Code')['LOAN_ID'].count() loan_num[key] = temp_size prepaid[key] = temp_count[1]/temp_size default[key] = 1 - sum(temp_count[0:2])/temp_size Explanation: Let's take a peek at the data. End of explanation def plot_dict_bar(val_dict): x_axis = sorted(list(val_dict.keys())) y_axis = [val_dict[key] for key in x_axis] x = np.arange(3) - 0.175 y = np.array(y_axis)*100 fig, ax = plt.subplots() ax.bar(x,y,0.35) ax.set_xticks(np.arange(3)) ax.set_xticklabels(x_axis) ax.set_xlabel("Year") ax.set_ylabel("Percentage (%)") ax.set_title("Prepaid Ratio") plt.show() plot_dict_bar(prepaid) Explanation: How many morgages have been prepaid in these three years? End of explanation def plot_dict_bar(val_dict): x_axis = sorted(list(val_dict.keys())) y_axis = [val_dict[key] for key in x_axis] x = np.arange(3) - 0.175 y = np.array(y_axis)*100 fig, ax = plt.subplots() ax.bar(x,y,0.35) ax.set_xticks(np.arange(3)) ax.set_xticklabels(x_axis) ax.set_xlabel("Year") ax.set_ylabel("Percentage (%)") ax.set_title("Default Ratio") plt.show() plot_dict_bar(default) Explanation: Remember prepay includes a common case that if you want to switch to another house. You will sell the current house that you live in. That would count as prepay too. Default Rate? End of explanation def plot_dict_bar(val_dict): x_axis = sorted(list(val_dict.keys())) y_axis = [val_dict[key] for key in x_axis] x = np.arange(3) - 0.175 y = np.array(y_axis) fig, ax = plt.subplots() ax.bar(x,y,0.35) ax.set_xticks(np.arange(3)) ax.set_xticklabels(x_axis) ax.set_xlabel("Year") ax.set_ylabel("Percentage (%)") ax.set_title("Loan Initiation Amount") plt.show() plot_dict_bar(loan_num) years = [] loan_to_value = {} for key in loan.keys(): temp_ltv = {} temp_mean = loan[key].groupby('Zero.Bal.Code')['OLTV'].mean() temp_ltv['Current'] = temp_mean[0] temp_ltv['Prepaid'] = temp_mean[1] temp_ltv['Default'] = np.mean(temp_mean[2:]) loan_to_value[key] = temp_ltv result = pd.DataFrame.from_dict(loan_to_value) result.head() Explanation: Default rate is not very high in these three years. The general trend is going down, which make senses because the economy is getting better. End of explanation years = [] credit_score = {} for key in loan.keys(): temp_cscore = {} temp_mean = loan[key].groupby('Zero.Bal.Code')['CSCORE_C'].mean() temp_cscore['Current'] = temp_mean[0] temp_cscore['Prepaid'] = temp_mean[1] temp_cscore['Default'] = np.mean(temp_mean[2:]) credit_score[key] = temp_cscore result2 = pd.DataFrame.from_dict(credit_score) result2.head() Explanation: It is very interesting to find out that "default" loans tends to have slightly higher loan-to-value (LTV) ratio on average, meaning they tends to have lower downpayment. End of explanation # Last one, default by states... years = [] state_res = {} for key in loan.keys(): temp_state_count = loan[key][(loan[key]['Zero.Bal.Code'] == 3) | (loan[key]['Zero.Bal.Code'] == 6) | (loan[key]['Zero.Bal.Code'] == 9)].groupby('STATE')['LOAN_ID'].count() states = list(temp_state_count.index) for state in states: if state_res.get(state) == None: state_res[state] = temp_state_count[state] else: state_res[state] = state_res[state] + temp_state_count[state] total_state_res = pd.DataFrame.from_dict(state_res, orient='index') total_state_res.columns=['Default'] total_state_res.sort_values(by='Default', ascending=False) Explanation: Again, it is very interesting to find that default loans tend to have slightly lower credit score, on average. End of explanation
5,313
Given the following text description, write Python code to implement the functionality described below step by step Description: <H1>Pattern similarities</H1> <P>We will compare similarities between the patterns in a network before (input) and after (output) the effect of inhibition.</P> <P> If patterns of activity are less similar after inhibition, we will have pattern separation</P> Step2: <H2>Definition of random pattern $\boldsymbol{z}$</H2> <P>A memory random pattern $\boldsymbol{z}$ is the representation of the activity of all the neurons in the network. It is a vector of lenght n, being n the total number of neurons in the network.</P> $\boldsymbol{z}_i Step3: <H2>Vector norm</H2> The most commonly encountered vector norm (often simply called "the norm" of a vector, or sometimes the magnitude of a vector) is the L2-norm, given by \begin{equation} \left\| \boldsymbol{z} \right\|_2 Step5: <H2>Definition of similarity</H2> It is the cosine of the normalized dot product of two vectors. It is equivalent to the Pearson correlation coefficient. $$ \text{similarity} = \cos(\theta) = {\mathbf{a} \cdot \mathbf{b} \over \|\mathbf{a}\|2 \|\mathbf{b}\|_2} = \frac{ \sum\limits{i=1}^{n}{a_i b_i} }{ \sqrt{\sum\limits_{i=1}^{n}{a_i^2}} \sqrt{\sum\limits_{i=1}^{n}{b_i^2}} } $$ Step7: <H2>Pattern separation</H2> It is the devation in the similarities between the input vectors and the output vectors. If both input and output vectors have the same similarity, then the relationship between their similarities is linear. Any positive deviation from the identity line when plotting similarities of input and output vectors will be because the output pattner are less similar than the input patterns. Step8: <H2> Percentage of separated patterns</H2> It is the number of patterns whose input similarity is larger than the output similarity. Step9: <H2>Magnitude of separation</H2> Is the averge distance to the identity line from the patterns that were separated Step10: <H2>Now with the pattern object</H2>
Python Code: # load necessary modules %pylab inline import numpy as np np.random.seed(0) from __future__ import division from inet import __version__ from inet.plots import separation_plot print(__version__) Explanation: <H1>Pattern similarities</H1> <P>We will compare similarities between the patterns in a network before (input) and after (output) the effect of inhibition.</P> <P> If patterns of activity are less similar after inhibition, we will have pattern separation</P> End of explanation def randpattern(size, prob): Creates a pattern of activities (ones) with a given probability. Activity is 1 if the cell is active, zero otherwise. Parameters ---------- size : ndarray vector size prob : float probability of having ones z = np.zeros(size, dtype=int) mysize = int(size*prob) z[np.random.choice(size, mysize, replace=False)]=1 # without replacement. Thank you Clau!!!! return(z) Explanation: <H2>Definition of random pattern $\boldsymbol{z}$</H2> <P>A memory random pattern $\boldsymbol{z}$ is the representation of the activity of all the neurons in the network. It is a vector of lenght n, being n the total number of neurons in the network.</P> $\boldsymbol{z}_i: i = {0, 1, \cdots, n},$ <P>The i-th element of the pattern is an independent random variable of probability a to be one when the neuron is active, and zero if not (1-a). </P> \begin{equation} \Pr(\boldsymbol{z}_i) = \begin{cases} 1, & \text{if} \ \ \boldsymbol{z}_i < a,\ 0, & \text{if} \ \ \boldsymbol{z}_i \geq 1-a\ \end{cases} \end{equation} End of explanation z = randpattern(size=10, prob=0.5) # example for testing mycount = list() for _ in range(100): mycount.append(np.count_nonzero(randpattern(10,.5)) ) np.mean(mycount) np.linalg.norm(z, ord=2) #norm2 of a vector np.linalg.norm([1,1],2) # must be sqrt(2) Explanation: <H2>Vector norm</H2> The most commonly encountered vector norm (often simply called "the norm" of a vector, or sometimes the magnitude of a vector) is the L2-norm, given by \begin{equation} \left\| \boldsymbol{z} \right\|_2 := \sqrt{z_1^2 + \cdots + z_n^2}.\end{equation} End of explanation def similarity(a, b): Compute cosine similarity between samples in A and B. Cosine similarity, or the cosine kernel, computes similarity as the normalized dot product of A and B: K(a, b) = <a, b> / (||a||*||b||) Parameters ---------- a : ndarray . b : ndarray. # dot product is scalar product return np.dot( a/np.linalg.norm(a), b/np.linalg.norm(b)) sim = list() for _ in range(1000): a = randpattern(100,.5) b = randpattern(100,.5) sim.append(similarity(a, b)) print(np.mean(sim)) # get this analytically! similarity([1,0,1],[0,1,0]) # must be zero Explanation: <H2>Definition of similarity</H2> It is the cosine of the normalized dot product of two vectors. It is equivalent to the Pearson correlation coefficient. $$ \text{similarity} = \cos(\theta) = {\mathbf{a} \cdot \mathbf{b} \over \|\mathbf{a}\|2 \|\mathbf{b}\|_2} = \frac{ \sum\limits{i=1}^{n}{a_i b_i} }{ \sqrt{\sum\limits_{i=1}^{n}{a_i^2}} \sqrt{\sum\limits_{i=1}^{n}{b_i^2}} } $$ End of explanation def plot_pattern_separation(inputpattern, outputpattern, ax = None): input pattern: a list containing tuples of input patterns outputpattern: a list containing tuples of outputpatterns Computes the linear regression of the similarity between paired patterns and plot a line with the 95% confident intervals. Returns: pattern_completion: int 0 if no pattern completion. if ax is None: ax = plt.gca() yval = np.array([similarity(x,y) for x,y in inputpattern]) xval = np.array([similarity(x,y) for x,y in outputpattern]) xlin = np.linspace(0,1,100) # identity line ax.scatter(xval, yval, color='gray') ax.plot(xlin, xlin, '--', color='brown', alpha=.6) ax.set_xlim(0,1), ax.set_ylim(0,1) ax.fill_between(xlin, 1, xlin, color='yellow', alpha=.1) # area of pattern comp. ax.set_ylabel('Input similarity ($\cos(x_i, y_i)$)', fontsize=20) ax.set_xlabel('Output similarity ($\cos(x_o, y_o)$)', fontsize=20) return ax # generate 100 input patterns of 30% and 50% activity npatterns = 100 inputpattern = [(randpattern(1000, .3), randpattern(1000,.5)) for _ in range(npatterns)] len(inputpattern) # there is no pattern separation of the inputs and outputs are the same plot_pattern_separation(inputpattern, inputpattern) ; I_network1 = randpattern(1000,.1) # 90% of neurons are active (are zeros) I = I_network1 outpattern = [(I*x, I*y) for x,y in inputpattern] Explanation: <H2>Pattern separation</H2> It is the devation in the similarities between the input vectors and the output vectors. If both input and output vectors have the same similarity, then the relationship between their similarities is linear. Any positive deviation from the identity line when plotting similarities of input and output vectors will be because the output pattner are less similar than the input patterns. End of explanation in_sim = np.array([similarity(x,y) for x,y in inputpattern]) out_sim = np.array([similarity(x,y) for x,y in outpattern]) separated = in_sim[in_sim>out_sim] prop = len(separated)/len(in_sim) print('Percentage of separated patterns {:2.2f} %.'.format(prop*100)) Explanation: <H2> Percentage of separated patterns</H2> It is the number of patterns whose input similarity is larger than the output similarity. End of explanation point = [(x,y) for x,y in zip(out_sim, in_sim) if x<y] # patterns separated # test that the proportion remains the same prop = len(point)/len(in_sim) print('Percentage of separated patterns {:2.2f} %'.format(prop*100)) dist = list() for x,y in point: dist.append( np.abs(x-y)/np.sqrt(2)) mean_separation = np.mean(dist) max_separation = (mean_separation*100)/(1/np.sqrt(2)) print('Magnitude of separation {:2.4f} '.format(mean_separation)) print('Percentage of max separation {:2.4f} %'.format(max_separation)) fig = plt.figure() ax = fig.add_subplot(111) ax = plot_pattern_separation(inputpattern, outpattern) Explanation: <H2>Magnitude of separation</H2> Is the averge distance to the identity line from the patterns that were separated End of explanation from inet.patterns import separation separation(inputpattern, inputpattern) separation_plot(separation.insimilarity, separation.outsimilarity) separation(inputpattern, outpattern) separation_plot(separation.insimilarity, separation.outsimilarity) Explanation: <H2>Now with the pattern object</H2> End of explanation
5,314
Given the following text description, write Python code to implement the functionality described below step by step Description: 2A.ML101.1 Step1: Numpy Arrays Manipulating numpy arrays is an important part of doing machine learning (or, really, any type of scientific computation) in Python. This will likely be review for most Step2: There is much, much more to know, but these few operations are fundamental to what we'll do during this tutorial. Scipy Sparse Matrices We won't make very much use of these in this tutorial, but sparse matrices are very nice in some situations. For example, in some machine learning tasks, especially those associated with textual analysis, the data may be mostly zeros. Storing all these zeros is very inefficient. We can create and manipulate sparse matrices as follows Step3: Matplotlib Another important part of machine learning is visualization of data. The most common tool for this in Python is matplotlib. It is an extremely flexible package, but we will go over some basics here. First, something special to IPython notebook. We can turn on the "IPython inline" mode, which will make plots show up inline in the notebook. Step4: There are many, many more plot types available. One useful way to explore these is by looking at the matplotlib gallery
Python Code: # Start pylab inline mode, so figures will appear in the notebook %matplotlib inline Explanation: 2A.ML101.1: Introduction to data manipulation with scientific Python In this section we'll go through the basics of the scientific Python stack for data manipulation: using numpy and matplotlib. Source: Course on machine learning with scikit-learn by Gaël Varoquaux You can skip this section if you already know the scipy stack. To learn the scientific Python ecosystem: http://scipy-lectures.org End of explanation import numpy as np # Generating a random array X = np.random.random((3, 5)) # a 3 x 5 array print(X) # Accessing elements # get a single element print(X[0, 0]) # get a row print(X[1]) # get a column print(X[:, 1]) # Transposing an array print(X.T) # Turning a row vector into a column vector y = np.linspace(0, 12, 5) print(y) # make into a column vector print(y[:, np.newaxis]) Explanation: Numpy Arrays Manipulating numpy arrays is an important part of doing machine learning (or, really, any type of scientific computation) in Python. This will likely be review for most: we'll quickly go through some of the most important features. End of explanation from scipy import sparse # Create a random array with a lot of zeros X = np.random.random((10, 5)) print(X) # set the majority of elements to zero X[X < 0.7] = 0 print(X) # turn X into a csr (Compressed-Sparse-Row) matrix X_csr = sparse.csr_matrix(X) print(X_csr) # convert the sparse matrix to a dense array print(X_csr.toarray()) Explanation: There is much, much more to know, but these few operations are fundamental to what we'll do during this tutorial. Scipy Sparse Matrices We won't make very much use of these in this tutorial, but sparse matrices are very nice in some situations. For example, in some machine learning tasks, especially those associated with textual analysis, the data may be mostly zeros. Storing all these zeros is very inefficient. We can create and manipulate sparse matrices as follows: End of explanation %matplotlib inline # Here we import the plotting functions import matplotlib.pyplot as plt # plotting a line x = np.linspace(0, 10, 100) plt.plot(x, np.sin(x)); # scatter-plot points x = np.random.normal(size=500) y = np.random.normal(size=500) plt.scatter(x, y); # showing images x = np.linspace(1, 12, 100) y = x[:, np.newaxis] im = y * np.sin(x) * np.cos(y) print(im.shape) # imshow - note that origin is at the top-left by default! plt.imshow(im); # Contour plot - note that origin here is at the bottom-left by default! plt.contour(im); Explanation: Matplotlib Another important part of machine learning is visualization of data. The most common tool for this in Python is matplotlib. It is an extremely flexible package, but we will go over some basics here. First, something special to IPython notebook. We can turn on the "IPython inline" mode, which will make plots show up inline in the notebook. End of explanation # %load http://matplotlib.org/mpl_examples/pylab_examples/ellipse_collection.py import matplotlib.pyplot as plt import numpy as np from matplotlib.collections import EllipseCollection x = np.arange(10) y = np.arange(15) X, Y = np.meshgrid(x, y) XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis])) ww = X/10.0 hh = Y/15.0 aa = X*9 fig, ax = plt.subplots() ec = EllipseCollection(ww, hh, aa, units='x', offsets=XY, transOffset=ax.transData) ec.set_array((X + Y).ravel()) ax.add_collection(ec) ax.autoscale_view() ax.set_xlabel('X') ax.set_ylabel('y') cbar = plt.colorbar(ec) cbar.set_label('X+Y'); Explanation: There are many, many more plot types available. One useful way to explore these is by looking at the matplotlib gallery: http://matplotlib.org/gallery.html You can test these examples out easily in the notebook: simply copy the Source Code link on each page, and put it in a notebook using the %load magic. For example: End of explanation
5,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Slider Example This example will allow the user to use sliders to interact with the ISR spectra. Currently this notebook creates two images. The first is a dual plot of the ACF and Power spectra expected for 100% O+ ionosphere and k = 18.5 with ion and electron temperature from the sliders. The second image is an image of the spectra that varies over wave number and an ion temperature derived from the sliders. Step2: ACF and Spectra This will show a plot of the spectra and ACF with sliders for the electron and ion temperatures. The frequency of the radar is 440 MHz carrier frequency (UHF). Step4: Spectra Image Varying by Wave Number A plot will be created showing how the IS spectra will vary with wave number using the ion temperature from the slider.
Python Code: import numpy as np import matplotlib as mpl import scipy.fftpack as scfft import scipy.constants as spconst import matplotlib.pylab as plt import seaborn as sns sns.set_style("white") sns.set_context("notebook") # from ISRSpectrum import Specinit import ipywidgets from IPython.display import display #%matplotlib inline %matplotlib notebook def plot1dspec(Ti,Te): Plot an IS spectra and ACF given ion and electron temperatures. Will plot a spectra and ACF over a sampling rate of 50 kHz 256 samples with a center frequency of 440 MHz Parameters ---------- Ti : float Ion temperture in degrees K. Te : float Ion temperture in degrees K. databloc = np.array([[1e11, Ti], [1e11,Te]]) # Select Number of points and sampling frequency in the spectra nspec=256 spfreq=50e3 cfreq = 440e6 kvec = 4*spconst.pi*cfreq/spconst.c ISpec_ion = Specinit(centerFrequency=cfreq, nspec=nspec, sampfreq=spfreq,dFlag=True) species=['O+','e-'] ylim=[0,1.4] ylim2=[-.5,1.4] flims=np.array([3.03e6,3.034e6]) fion,ionline= ISpec_ion.getspecsep(databloc,species) acf=scfft.ifft(scfft.ifftshift(ionline)).real tau=scfft.ifftshift(np.arange(-np.ceil((float(nspec)-1)/2),np.floor((float(nspec)-1)/2)+1))/spfreq if 'fig' in locals(): fig.close() del fig del ax fig,ax = plt.subplots(1,2,sharey=False,facecolor='w') l1=ax[0].plot(fion*1e-3,ionline/ionline.max(),'-',lw=3)[0] sns.despine() ax[0].set_xlim([-15,15]) ax[0].spines['right'].set_visible(False) ax[0].set_xlabel('Frequency (kHz)',fontsize=14) kstr = '{:0.1f}'.format(kvec) ax[0].set_title('Spectra K={:0.1f}'.format(kvec),fontsize=18) ax[0].set_ylabel('Normalized Magnitude',fontsize=14) ax[0].set_ylim(ylim) l1=ax[1].plot(tau[:64]*1e6,acf[:64]/acf[0],'-',lw=3)[0] sns.despine() ax[1].set_xlim([0,480]) ax[1].spines['right'].set_visible(False) ax[1].set_xlabel('Lag in Microseconds ',fontsize=14) ax[1].set_title('ACF K={:0.1f}'.format(kvec),fontsize=18) ax[1].set_ylabel('Normalized Magnitude',fontsize=14) ax[1].set_ylim(ylim2) plt.tight_layout() plt.show() Explanation: Slider Example This example will allow the user to use sliders to interact with the ISR spectra. Currently this notebook creates two images. The first is a dual plot of the ACF and Power spectra expected for 100% O+ ionosphere and k = 18.5 with ion and electron temperature from the sliders. The second image is an image of the spectra that varies over wave number and an ion temperature derived from the sliders. End of explanation slideTi = ipywidgets.FloatSlider( value=1000., min=500., max=5000., step=500., description='Ti in K:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', slider_color='white' ) slideTe = ipywidgets.FloatSlider( value=1000., min=500., max=5000., step=500., description='Te in K:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', slider_color='white' ) w=ipywidgets.interactive(plot1dspec,Ti=slideTi,Te=slideTe) output = w.children[-1] output.layout.height = '800px' output.layout.width= '100%' display(w) Explanation: ACF and Spectra This will show a plot of the spectra and ACF with sliders for the electron and ion temperatures. The frequency of the radar is 440 MHz carrier frequency (UHF). End of explanation slide1 = ipywidgets.FloatSlider( value=1000., min=500., max=5000., step=500., description='Ti in K:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', slider_color='white' ) def plot2dspec(Ti): Create a 2-D plot of spectra from wave number and frequency. Parameters ---------- Ti : float Ion temperture in degrees K. databloc = np.array([[1e11,Ti],[1e11,2.5e3]]) species=['O+','e-'] newcentfreq = 449e6 +np.linspace(-200,550,250)*1e6 k_all= 2*2*np.pi*newcentfreq/spconst.c k_lims=np.array([k_all.min(),k_all.max()]) freq_lims=np.array([newcentfreq.min(),newcentfreq.max()]) oution = [] for i,if_0 in enumerate(newcentfreq): ISpec_ion = Specinit(centerFrequency = if_0, nspec=256, sampfreq=50e3,dFlag=False) fion,ionline= ISpec_ion.getspecsep(databloc,species) oution.append(ionline) oution=np.array(oution) F,K_b=np.meshgrid(fion,k_all) fig,ax = plt.subplots(1,1,sharey=True, figsize=(6,4),facecolor='w') l1=ax.pcolor(F*1e-3,K_b,oution/oution.max(),cmap='viridis') cb1 = plt.colorbar(l1, ax=ax) ax.set_xlim([-25,25]) ax.set_ylim(k_lims) ax.set_xlabel('Frequency (kHz)',fontsize=14) ax.set_title(r'$\langle|n_e(\mathbf{k},\omega)|^2\rangle$',fontsize=18) ax.set_ylabel(r'$|\mathbf{k}|$ (rad/m)',fontsize=14) w = ipywidgets.interactive(plot2dspec, Ti=slide1) output = w.children[-1] output.layout.height = '1200px' display(w) Explanation: Spectra Image Varying by Wave Number A plot will be created showing how the IS spectra will vary with wave number using the ion temperature from the slider. End of explanation
5,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Unsupervised Learning Project 3 Step1: Data Exploration In 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. Run the code block below to observe a statistical description of the dataset. Note that the dataset is composed of six important product categories Step2: Implementation Step3: Question 1 Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. What kind of establishment (customer) could each of the three samples you've chosen represent? Hint Step4: Question 2 Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits? Hint Step5: Question 3 Are 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? Hint Step6: Observation After 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). Run the code below to see how the sample data has changed after having the natural logarithm applied to it. Step7: Implementation Step8: Question 4 Are 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. Answer Step9: Question 5 How 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. Hint Step10: Implementation Step11: Observation Run 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. Step12: Clustering In 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. Question 6 What 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? Answer Step13: Question 7 Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score? Answer Step14: Implementation Step15: Question 8 Consider 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? Hint Step16: Answer Step17: Conclusion In 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. Question 10 Companies 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 reach positively to the change in delivery service? Hint
Python Code: # Import libraries necessary for this project import numpy as np import pandas as pd import renders as rs from IPython.display import display # Allows the use of display() for DataFrames # Show matplotlib plots inline (nicely formatted in the notebook) %matplotlib inline # Load the wholesale customers dataset try: data = pd.read_csv("customers.csv") data.drop(['Region', 'Channel'], axis = 1, inplace = True) print "Wholesale customers dataset has {} samples with {} features each.".format(*data.shape) except: print "Dataset could not be loaded. Is the dataset missing?" Explanation: Machine Learning Engineer Nanodegree Unsupervised Learning Project 3: Creating Customer Segments Welcome 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! In 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. Note: 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. Getting Started In 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. The 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. Run 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. End of explanation # Display a description of the dataset display(data.describe()) Explanation: Data Exploration In 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. Run 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. End of explanation # TODO: Select three indices of your choice you wish to sample from the dataset indices = [30,60,90] # Create a DataFrame of the chosen samples samples = pd.DataFrame(data.loc[indices], columns = data.keys()).reset_index(drop = True) print "Chosen samples of wholesale customers dataset:" display(samples) display(samples - data.median().round()) Explanation: Implementation: Selecting Samples To 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. End of explanation # TODO: Make a copy of the DataFrame, using the 'drop' function to drop the given feature new_data = data.drop('Milk', axis = 1) from sklearn import cross_validation # TODO: Split the data into training and testing sets using the given feature as the target X_train, X_test, y_train, y_test = cross_validation.train_test_split(new_data, data['Milk'], test_size =0.25, random_state = 0) from sklearn import tree # TODO: Create a decision tree regressor and fit it to the training set regressor = tree.DecisionTreeRegressor(min_samples_leaf = 20, random_state = 0) regressor.fit(X_train, y_train) from sklearn import metrics # TODO: Report the score of the prediction using the testing set score = metrics.r2_score(y_test, regressor.predict(X_test)) print 'R2 score is {}'.format(score) Explanation: Question 1 Consider the total purchase cost of each product category and the statistical description of the dataset above for your sample customers. What kind of establishment (customer) could each of the three samples you've chosen represent? Hint: 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. Answer: By comparing the spendings with median spendings, customer 0 and customer 1 have more spendings on Grocery, Detegents_paper, and thus are more like a retailer. Custormer 2 have more spending on fresh food and frozen food and thus is more like a restaurant. Implementation: Feature Relevance One 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. In the code block below, you will need to implement the following: - Assign new_data a copy of the data by removing a feature of your choice using the DataFrame.drop function. - Use sklearn.cross_validation.train_test_split to split the dataset into training and testing sets. - Use the removed feature as your target label. Set a test_size of 0.25 and set a random_state. - Import a decision tree regressor, set a random_state, and fit the learner to the training data. - Report the prediction score of the testing set using the regressor's score function. End of explanation # Produce a scatter matrix for each pair of features in the data pd.scatter_matrix(data, alpha = 0.3, figsize = (14,8), diagonal = 'kde'); data.corr() data.corr('spearman') Explanation: Question 2 Which feature did you attempt to predict? What was the reported prediction score? Is this feature is necessary for identifying customers' spending habits? Hint: 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. Answer: I attempt to predict Milk. The reported R2 is 0.556. Though 'Milk' can be partially predicted by other feature. The feature is necessary for identifying custormers' spending habits because using other feature can not well predict Milk. Visualize Feature Distributions To 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. End of explanation # TODO: Scale the data using the natural logarithm log_data = np.log(data) # TODO: Scale the sample data using the natural logarithm log_samples = np.log(samples) # Produce a scatter matrix for each pair of newly-transformed features pd.scatter_matrix(log_data, alpha = 0.3, figsize = (14,8), diagonal = 'kde'); Explanation: Question 3 Are 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? Hint: Is the data normally distributed? Where do most of the data points lie? Answer: The pair 'Detergents_paper' and 'Grocery' seems to have high correlation. Meanwhile, the pair {'Milk','Grocery'} and {'Milk','Detergents_paper'} also have some degree of correlatin. This agree with my concluding about relevence of 'Milk' with other features. They have some relavence, but 'Milk' contain information that can not be well present by other features. The data is not normally distributed. Most features are skewed distribution. Data Preprocessing In 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. Implementation: Feature Scaling If 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. In the code block below, you will need to implement the following: - Assign a copy of the data to log_data after applying a logarithm scaling. Use the np.log function for this. - Assign a copy of the sample data to log_samples after applying a logrithm scaling. Again, use np.log. End of explanation # Display the log-transformed sample data display(log_samples) Explanation: Observation After 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). Run the code below to see how the sample data has changed after having the natural logarithm applied to it. End of explanation # For each feature find the data points with extreme high or low values count = np.zeros(len(log_data.index)) for feature in log_data.keys(): # TODO: Calculate Q1 (25th percentile of the data) for the given feature Q1 = np.percentile(log_data[feature], q=25) # TODO: Calculate Q3 (75th percentile of the data) for the given feature Q3 = np.percentile(log_data[feature], q=75) # TODO: Use the interquartile range to calculate an outlier step (1.5 times the interquartile range) step = 1.5 * (Q3 - Q1) # Display the outliers print "Data points considered outliers for the feature '{}':".format(feature) display(log_data[~((log_data[feature] >= Q1 - step) & (log_data[feature] <= Q3 + step))]) count += ((log_data[feature] < Q1 - step) | (log_data[feature] > Q3 + step)) # OPTIONAL: Select the indices for data points you wish to remove row_outlier = np.where(count>1) print "Data points considered outliers more than once '{}':".format(row_outlier) outliers = row_outlier # Remove the outliers, if any were specified good_data = log_data.drop(log_data.index[outliers]).reset_index(drop = True) Explanation: Implementation: Outlier Detection Detecting 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. In the code block below, you will need to implement the following: - Assign the value of the 25th percentile for the given feature to Q1. Use np.percentile for this. - Assign the value of the 75th percentile for the given feature to Q3. Again, use np.percentile. - Assign the calculation of an outlier step for the given feature to step. - Optionally remove data points from the dataset by adding indices to the outliers list. NOTE: If you choose to remove any outliers, ensure that the sample data does not contain any of these points! Once you have performed this implementation, the dataset will be stored in the variable good_data. End of explanation # TODO: Apply PCA by fitting the good data with the same number of dimensions as features from sklearn import decomposition pca = decomposition.PCA(n_components=6) pca.fit(good_data) # TODO: Transform the sample log-data using the PCA fit above pca_samples = pca.transform(log_samples) # Generate PCA results plot pca_results = rs.pca_results(good_data, pca) Explanation: Question 4 Are 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. Answer: Yes, there are 5 data points considered outlier for more than one feature. These data should be removed. If a data point have more than one outlier, then the data point might have sevier measrement error or the data is not plausable. Feature Transformation In 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. Implementation: PCA Now 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. In the code block below, you will need to implement the following: - Import sklearn.decomposition.PCA and assign the results of fitting PCA in six dimensions with good_data to pca. - Apply a PCA transformation of the sample log-data log_samples using pca.transform, and assign the results to pca_samples. End of explanation # Display sample log-data after having a PCA transformation applied display(pd.DataFrame(np.round(pca_samples, 4), columns = pca_results.index.values)) Explanation: Question 5 How 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. Hint: 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. Answer: 1st and 2nd PC explained 0.7068 of variance. The first 4 PCs explained 0.9311 of variance. The 1st PC resprents patterns of spending with positive wegiht on detergents_papers, milk and Grocery, and negative weights on Fresh and Frozen. That is to say, customers with large value on 1st PC would spend a lot on detergents_papers, milk, and Grocery and spend little on Fresh and Frozen. And customor with small value on 1st PC would spend little on detergents_papers, milk, and Grocery and spend a lot on Frozen and Fresh. The 2nd PC represents patterns of spending with heavy positive weight on Fresh, Frozen and Delicatessen. That is to say, customer with large value on 2nd PC would spend a lot on Fresh, Frozen and Delicatessen, and customer with small value on 2nd PC would spend little on Fresh, Frozen and Delicatessen. The 3rd PC represents pattern of spending with positive weight on Delicatssen and negative weight on Fresh. Customers with large value on 3rd PC would spend a lot on Delicatssen and little on Fresh, vice versa for those with small value on 3rd PC. The 4th PC represents pattern of spending with positive weight on frozen and negative weight on Delicatssen. Customers with large value on 4th PC would spend a lot on Frozen and little on Delicatssen, vice versa for those with small value on 4th PC. Observation Run 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. End of explanation # TODO: Apply PCA by fitting the good data with only two dimensions pca = decomposition.PCA(n_components=2) pca.fit(good_data) # TODO: Transform the good data using the PCA fit above reduced_data = pca.transform(good_data) # TODO: Transform the sample log-data using the PCA fit above pca_samples = pca.transform(log_samples) # Create a DataFrame for the reduced data reduced_data = pd.DataFrame(reduced_data, columns = ['Dimension 1', 'Dimension 2']) # Produce a scatter matrix for pca reduced data pd.scatter_matrix(reduced_data, alpha = 0.8, figsize = (8,4), diagonal = 'kde'); Explanation: Implementation: Dimensionality Reduction When 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. In the code block below, you will need to implement the following: - Assign the results of fitting PCA in two dimensions with good_data to pca. - Apply a PCA transformation of good_data using pca.transform, and assign the reuslts to reduced_data. - Apply a PCA transformation of the sample log-data log_samples using pca.transform, and assign the results to pca_samples. End of explanation # Display sample log-data after applying PCA transformation in two dimensions display(pd.DataFrame(np.round(pca_samples, 4), columns = ['Dimension 1', 'Dimension 2'])) Explanation: Observation Run 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. End of explanation # TODO: Apply your clustering algorithm of choice to the reduced data from sklearn import mixture from sklearn import cluster for i in range(4,1,-1): clusterer = cluster.KMeans(i, random_state=0).fit(reduced_data) # Predict the cluster for each data point preds = clusterer.predict(reduced_data) # Calculate the mean silhouette coefficient for the number of clusters chosen score = metrics.silhouette_score(reduced_data, preds) print i, 'clusters:', score.round(5) # TODO: Apply your clustering algorithm of choice to the reduced data from sklearn import mixture from sklearn import cluster #clusterer = mixture.GMM(n_components=2, random_state=0 ) clusterer = cluster.KMeans(n_clusters=2, random_state=0) clusterer.fit(reduced_data) # TODO: Predict the cluster for each data point preds = clusterer.predict(reduced_data) # TODO: Find the cluster centers #centers = clusterer.means_ centers = clusterer.cluster_centers_ # TODO: Predict the cluster for each transformed sample data point sample_preds = clusterer.predict(pca_samples) # TODO: Calculate the mean silhouette coefficient for the number of clusters chosen score = metrics.silhouette_score(reduced_data, preds, random_state=0) print 'silhouette score is {}'.format(score) Explanation: Clustering In 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. Question 6 What 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? Answer: K-means Clustering is very fast and always converge, but it may reach to a local minimum. GMM is also fast, though not as fast as K-means. GMM has problistic interpratation for clustering. I would use K-means, since it always converge and runs faster. Implementation: Creating Clusters Depending 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. In the code block below, you will need to implement the following: - Fit a clustering algorithm to the reduced_data and assign it to clusterer. - Predict the cluster for each data point in reduced_data using clusterer.predict and assign them to preds. - Find the cluster centers using the algorithm's respective attribute and assign them to centers. - Predict the cluster for each sample data point in pca_samples and assign them sample_preds. - Import sklearn.metrics.silhouette_score and calculate the silhouette score of reduced_data against preds. - Assign the silhouette score to score and print the result. End of explanation # Display the results of the clustering from implementation rs.cluster_results(reduced_data, preds, centers, pca_samples) Explanation: Question 7 Report the silhouette score for several cluster numbers you tried. Of these, which number of clusters has the best silhouette score? Answer: I tried n-cluster = 2, 3, 4, with sihouette score = 0.426, 0.397, 0.332. n-cluster = 2 have the best silhouette score. Cluster Visualization Once 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. End of explanation # TODO: Inverse transform the centers log_centers = pca.inverse_transform(centers) # TODO: Exponentiate the centers true_centers = np.exp(log_centers) # Display the true centers segments = ['Segment {}'.format(i) for i in range(0,len(centers))] true_centers = pd.DataFrame(np.round(true_centers), columns = data.keys()) true_centers.index = segments display(true_centers) display(true_centers - (np.exp(good_data)).mean().round()) display(true_centers - (np.exp(good_data)).median().round()) Explanation: Implementation: Data Recovery Each 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. In the code block below, you will need to implement the following: - Apply the inverse transform to centers using pca.inverse_transform and assign the new centers to log_centers. - Apply the inverse function of np.log to log_centers using np.exp and assign the true centers to true_centers. End of explanation # Display the predictions for i, pred in enumerate(sample_preds): print "Sample point", i, "predicted to be in Cluster", pred Explanation: Question 8 Consider 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? Hint: A customer who is assigned to 'Cluster X' should best identify with the establishments represented by the feature set of 'Segment X'. Answer: By comparing with mean and median with original data, we see that data points assigned to cluster 0 have more than average spending on Milk, Grocery and Detergents_Paper and less than average spending on Fresh and Frozen, and thus likely to represent 'Retailer' cluster. Data points assigned to cluster 1 have less than average spending on Milk, Grocery and Detergents_Paper and more tha average spending on Fresh and Frozen, and thus likely to represent 'Restraunt' cluster. Question 9 For each sample point, which customer segment from Question 8 best represents it? Are the predictions for each sample point consistent with this? Run the code block below to find which cluster each sample point is predicted to be. End of explanation display(samples - (np.exp(good_data)).median().round()) Explanation: Answer: Sample point 0 predicted to be in Cluster 0, Sample point 1 predicted to be in Cluster 0, Sample point 2 predicted to be in Cluster 1. The predictins are consistent. Sample 0 and 1 have above median spending on Grocery and Detergents_Paper and below median spending on Frozen, and thus closer to center of cluster 0. Sample 2 have below median spending on Grocery and Detergents_Paper and above median spending on Frozen, and thus closer to center of cluster 1. End of explanation # Display the clustering results based on 'Channel' data rs.channel_results(reduced_data, outliers, pca_samples) Explanation: Conclusion In 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. Question 10 Companies 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 reach positively to the change in delivery service? Hint: Can we assume the change affects all customers equally? How can we determine which group of customers it affects the most? Answer: the wholesale distributor can first cluster their custermor to several group, for example, using the above 2 clusters. Then using A/B test to test whether the small change affect customers positively or negatively. Yes, we can determine which group it affects the most, by comparing the difference for each group (with consideration of multiple testing). Question 11 Additional 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. How can the wholesale distributor label the new customers using only their estimated product spending and the customer segment data? Hint: A supervised learner could be used to train on the original customers. What would be the target variable? Answer: Without knowing the clustering algorithm applied on original data, we can treat the product spending as features and 'custermor segment' as labels. Then we can use a supervised learner, e.g., SVM, to learn the "clustering algorithm", and use it to predict "custermor segment" for the new customers. Visualizing Underlying Distributions At 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. Run 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. End of explanation
5,317
Given the following text description, write Python code to implement the functionality described below step by step Description: Numpy Exercise 4 Imports Step1: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don't have directionality, the graph is said to be undirected. Graphs are used to model social and communications networks (Twitter, Facebook, Internet) as well as natural systems such as molecules. A Complete Graph, $K_n$ on $n$ nodes has an edge that connects each node to every other node. Here is $K_5$ Step3: The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defined as $L=D-A$. Where $D$ is the degree matrix and $A$ is the adjecency matrix. For the purpose of this problem you don't need to understand the details of these matrices, although their definitions are relatively simple. The degree matrix for $K_n$ is an $n \times n$ diagonal matrix with the value $n-1$ along the diagonal and zeros everywhere else. Write a function to compute the degree matrix for $K_n$ using NumPy. Step5: The adjacency matrix for $K_n$ is an $n \times n$ matrix with zeros along the diagonal and ones everywhere else. Write a function to compute the adjacency matrix for $K_n$ using NumPy. Step6: Use NumPy to explore the eigenvalues or spectrum of the Laplacian L of $K_n$. What patterns do you notice as $n$ changes? Create a conjecture about the general Laplace spectrum of $K_n$.
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns Explanation: Numpy Exercise 4 Imports End of explanation import networkx as nx K_5=nx.complete_graph(5) nx.draw(K_5) Explanation: Complete graph Laplacian In discrete mathematics a Graph is a set of vertices or nodes that are connected to each other by edges or lines. If those edges don't have directionality, the graph is said to be undirected. Graphs are used to model social and communications networks (Twitter, Facebook, Internet) as well as natural systems such as molecules. A Complete Graph, $K_n$ on $n$ nodes has an edge that connects each node to every other node. Here is $K_5$: End of explanation def complete_deg(n): Return the integer valued degree matrix D for the complete graph K_n. x = np.eye(n,n,dtype=np.int) #Starts with the identity matrix x = (n-1)*x #Scalar * n-1 return x #raise NotImplementedError() print complete_deg(5) D = complete_deg(5) assert D.shape==(5,5) assert D.dtype==np.dtype(int) assert np.all(D.diagonal()==4*np.ones(5)) assert np.all(D-np.diag(D.diagonal())==np.zeros((5,5),dtype=int)) Explanation: The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defined as $L=D-A$. Where $D$ is the degree matrix and $A$ is the adjecency matrix. For the purpose of this problem you don't need to understand the details of these matrices, although their definitions are relatively simple. The degree matrix for $K_n$ is an $n \times n$ diagonal matrix with the value $n-1$ along the diagonal and zeros everywhere else. Write a function to compute the degree matrix for $K_n$ using NumPy. End of explanation def complete_adj(n): Return the integer valued adjacency matrix A for the complete graph K_n. x = np.eye(n,n,dtype=np.int) y = np.eye(n,n,dtype=np.int) y.fill(1) y = y - x #Subtract the identity matrix from a matrix of all 1's return y print complete_adj(6) #raise NotImplementedError() A = complete_adj(5) assert A.shape==(5,5) assert A.dtype==np.dtype(int) assert np.all(A+np.eye(5,dtype=int)==np.ones((5,5),dtype=int)) Explanation: The adjacency matrix for $K_n$ is an $n \times n$ matrix with zeros along the diagonal and ones everywhere else. Write a function to compute the adjacency matrix for $K_n$ using NumPy. End of explanation K_5=nx.complete_graph(22) nx.draw(K_5) #raise NotImplementedError() Explanation: Use NumPy to explore the eigenvalues or spectrum of the Laplacian L of $K_n$. What patterns do you notice as $n$ changes? Create a conjecture about the general Laplace spectrum of $K_n$. End of explanation
5,318
Given the following text description, write Python code to implement the functionality described below step by step Description: WARNING It is a non-public API. It may change with no previous notice We are going to show how to work with the CARTO custom visualizations (aka Kuviz). We are going to start creating tje Auth client and we will use it in every example. You only need to complete the following cell Step1: Kuviz manager creation Step2: Create public Kuviz Step3: Create Kuviz protected by password Step4: Update a kuviz Step5: If you want to remove the password Step6: And if you want to add the password again Step7: Delete a kuviz
Python Code: USERNAME = "" BASE_URL = "https://{u}.carto.com".format(u=USERNAME) API_KEY = "" from carto.auth import APIKeyAuthClient auth_client = APIKeyAuthClient(api_key=API_KEY, base_url=BASE_URL) Explanation: WARNING It is a non-public API. It may change with no previous notice We are going to show how to work with the CARTO custom visualizations (aka Kuviz). We are going to start creating tje Auth client and we will use it in every example. You only need to complete the following cell: End of explanation from carto.kuvizs import KuvizManager km = KuvizManager(auth_client) Explanation: Kuviz manager creation End of explanation html = "<html><body><h1>Working with CARTO Kuviz</h1></body></html>" public_kuviz = km.create(html=html, name="kuviz-public-test") print(public_kuviz.id) print(public_kuviz.url) print(public_kuviz.privacy) Explanation: Create public Kuviz End of explanation html = "<html><body><h1>Working with CARTO Kuviz</h1></body></html>" password_kuviz = km.create(html=html, name="kuviz-password-test", password="1234") print(password_kuviz.id) print(password_kuviz.url) print(password_kuviz.privacy) Explanation: Create Kuviz protected by password End of explanation new_html = "<html><body><h1>Another HTML</h1></body></html>" password_kuviz.data = new_html password_kuviz.save() print(password_kuviz.id) print(password_kuviz.url) print(password_kuviz.privacy) Explanation: Update a kuviz End of explanation password_kuviz.password = None password_kuviz.save() print(password_kuviz.id) print(password_kuviz.url) print(password_kuviz.privacy) Explanation: If you want to remove the password: End of explanation password_kuviz.password = "1234" password_kuviz.save() print(password_kuviz.id) print(password_kuviz.url) print(password_kuviz.privacy) Explanation: And if you want to add the password again: End of explanation password_kuviz.delete() Explanation: Delete a kuviz End of explanation
5,319
Given the following text description, write Python code to implement the functionality described below step by step Description: Xhistogram Tutorial Histograms are the foundation of many forms of data analysis. The goal of xhistogram is to make it easy to calculate weighted histograms in multiple dimensions over n-dimensional arrays, with control over the axes. Xhistogram builds on top of xarray, for automatic coordiantes and labels, and dask, for parallel scalability. Toy Data We start by showing an example with toy data. First we use xarray to create some random, normally distributed data. 1D Histogram Step1: By default xhistogram operates on all dimensions of an array, just like numpy. However, it operates on xarray DataArrays, taking labels into account. Step2: TODO Step3: TODO Step4: Weighted Histogram Weights can be the same shape as the input Step5: Or can use Xarray broadcasting Step6: 2D Histogram Now let's say we have multiple input arrays. We can calculate their joint distribution Step7: Real Data Example Ocean Volume Census in TS Space Here we show how to use xhistogram to do a volume census of the ocean in Temperature-Salinity Space First we open the World Ocean Atlas dataset from the opendap dataset (http Step8: Use histogram to bin data points. Use canonical ocean T/S ranges, and bin size of $0.1^0C$, and $0.025psu$. Similar ranges and bin size as this review paper on Mode Waters Step9: However, we would like to do a volume census, which requires the data points to be weighted by volume of the grid box. \begin{equation} dV = dzdxdy \end{equation} Step10: The ridges of this above plot are indicative of T/S classes with a lot of volume, and some of them are indicative of Mode Waters (example Eighteen Degree water with T$\sim18^oC$, and S$\sim36.5psu$. Averaging a variable Next we calculate the mean oxygen value in each TS bin. \begin{equation} \overline{A} (m,n) = \frac{\sum_{T(x,y,z)=m, S(x,y,z)=n} (A(x,y,z) dV)}{\sum_{T(x,y,z)=m, S(x,y,z)=n}dV}. \end{equation}
Python Code: import xarray as xr import numpy as np %matplotlib inline nt, nx = 100, 30 da = xr.DataArray(np.random.randn(nt, nx), dims=['time', 'x'], name='foo') # all inputs need a name display(da) da.plot() Explanation: Xhistogram Tutorial Histograms are the foundation of many forms of data analysis. The goal of xhistogram is to make it easy to calculate weighted histograms in multiple dimensions over n-dimensional arrays, with control over the axes. Xhistogram builds on top of xarray, for automatic coordiantes and labels, and dask, for parallel scalability. Toy Data We start by showing an example with toy data. First we use xarray to create some random, normally distributed data. 1D Histogram End of explanation from xhistogram.xarray import histogram bins = np.linspace(-4, 4, 20) h = histogram(da, bins=[bins]) display(h) h.plot() Explanation: By default xhistogram operates on all dimensions of an array, just like numpy. However, it operates on xarray DataArrays, taking labels into account. End of explanation h_x = histogram(da, bins=[bins], dim=['time']) h_x.plot() Explanation: TODO: - Bins needs to be a list; this is annoying, would be good to accept single items - The foo_bin coordinate is the estimated bin center, not the bounds. We need to add the bounds to the coordinates, but we can as long as we are returning DataArray and not Dataset. Both of the above need GitHub Issues Histogram over a single axis End of explanation h_x.mean(dim='x').plot() Explanation: TODO: - Relax / explain requirement that dims is always a list End of explanation weights = 0.4 * xr.ones_like(da) histogram(da, bins=[bins], weights=weights) Explanation: Weighted Histogram Weights can be the same shape as the input: End of explanation weights = 0.2 * xr.ones_like(da.x) histogram(da, bins=[bins], weights=weights) Explanation: Or can use Xarray broadcasting: End of explanation db = xr.DataArray(np.random.randn(nt, nx), dims=['time', 'x'], name='bar') - 2 histogram(da, db, bins=[bins, bins]).plot() Explanation: 2D Histogram Now let's say we have multiple input arrays. We can calculate their joint distribution: End of explanation # Read WOA using opendap Temp_url = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/WOA/WOA13/5_deg/annual/temp' Salt_url = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/WOA/WOA13/5_deg/annual/salt' Oxy_url = 'http://apdrc.soest.hawaii.edu:80/dods/public_data/WOA/WOA13/5_deg/annual/doxy' ds = xr.merge([ xr.open_dataset(Temp_url).tmn.load(), xr.open_dataset(Salt_url).smn.load(), xr.open_dataset(Oxy_url).omn.load()]) ds Explanation: Real Data Example Ocean Volume Census in TS Space Here we show how to use xhistogram to do a volume census of the ocean in Temperature-Salinity Space First we open the World Ocean Atlas dataset from the opendap dataset (http://apdrc.soest.hawaii.edu/dods/public_data/WOA/WOA13/1_deg/annual). Here we read the annual mean Temparature, Salinity and Oxygen on a 5 degree grid. End of explanation sbins = np.arange(31,38, 0.025) tbins = np.arange(-2, 32, 0.1) # histogram of number of data points # histogram of number of data points hTS = histogram(ds.smn, ds.tmn, bins=[sbins, tbins]) np.log10(hTS.T).plot(levels=31) Explanation: Use histogram to bin data points. Use canonical ocean T/S ranges, and bin size of $0.1^0C$, and $0.025psu$. Similar ranges and bin size as this review paper on Mode Waters: https://doi.org/10.1016/B978-0-12-391851-2.00009-X . End of explanation # histogram of number of data points weighted by volume resolution # Note that depth is a non-uniform axis # Create a dz variable dz = np.diff(ds.lev) dz =np.insert(dz, 0, dz[0]) dz = xr.DataArray(dz, coords= {'lev':ds.lev}, dims='lev') # weight by volume of grid cell (resolution = 5degree, 1degree=110km) dVol = dz * (5*110e3) * (5*110e3*np.cos(ds.lat*np.pi/180)) # Note: The weights are automatically broadcast to the right size hTSw = histogram(ds.smn, ds.tmn, bins=[sbins, tbins], weights=dVol) np.log10(hTSw.T).plot(levels=31, vmin=11.5, vmax=16, cmap='brg') Explanation: However, we would like to do a volume census, which requires the data points to be weighted by volume of the grid box. \begin{equation} dV = dzdxdy \end{equation} End of explanation hTSO2 = (histogram(ds.smn.where(~np.isnan(ds.omn)), ds.tmn.where(~np.isnan(ds.omn)), bins=[sbins, tbins], weights=ds.omn.where(~np.isnan(ds.omn))*dVol)/ histogram(ds.smn.where(~np.isnan(ds.omn)), ds.tmn.where(~np.isnan(ds.omn)), bins=[sbins, tbins], weights=dVol)) (hTSO2.T).plot(vmin=1, vmax=8) Explanation: The ridges of this above plot are indicative of T/S classes with a lot of volume, and some of them are indicative of Mode Waters (example Eighteen Degree water with T$\sim18^oC$, and S$\sim36.5psu$. Averaging a variable Next we calculate the mean oxygen value in each TS bin. \begin{equation} \overline{A} (m,n) = \frac{\sum_{T(x,y,z)=m, S(x,y,z)=n} (A(x,y,z) dV)}{\sum_{T(x,y,z)=m, S(x,y,z)=n}dV}. \end{equation} End of explanation
5,320
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Project Euler Step2: I realize this probably isn't the fastest or most concise code, but it works. Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. Step4: Now define a count_letters(n) that returns the number of letters used to write out the words for all of the the numbers 1 to n inclusive. Step5: Someone can probably do this in less lines but this method makes the most sense to me. Now write a set of assert tests for your count_letters function that verifies that it is working as expected. Step6: Finally used your count_letters function to solve the original question. Step7: Success!
Python Code: def number_to_words(n): Given a number n between 1-1000 inclusive return a list of words for the number. words = {0:'',1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',10:'ten',11:'eleven',12:'twelve',13:'thirteen',14:'fourteen',15:'fifteen',16:'sixteen',17:'seventeen',18:'eighteen',19:'nineteen'} if n<20: return words[n] elif n>=20 and n<30: return 'twenty'+ words[(n-20)] elif n>=30 and n<40: return 'thirty'+ words[(n-30)] elif n>=40 and n<50: return 'forty'+ words[(n-40)] elif n>=50 and n<60: return 'fifty'+ words[(n-50)] elif n>=60 and n<70: return 'sixty'+ words[(n-60)] elif n>=70 and n<80: return 'seventy'+ words[(n-70)] elif n>=80 and n<90: return 'eighty'+ words[(n-80)] elif n>=90 and n<100: return 'ninety'+ words[(n-90)] elif n%100==0 and n<1000: return words[n/100] + 'hundred' elif n>100 and n<1000: i = n%100 x=0 if i<20: x=words[i] elif i>=20 and i<30: x= 'twenty'+ words[(i-20)] elif i>=30 and i<40: x= 'thirty'+ words[(i-30)] elif i>=40 and i<50: x= 'forty'+ words[(i-40)] elif i>=50 and i<60: x= 'fifty'+ words[(i-50)] elif i>=60 and i<70: x= 'sixty'+ words[(i-60)] elif i>=70 and i<80: x= 'seventy'+ words[(i-70)] elif i>=80 and i<90: x= 'eighty'+ words[(i-80)] elif i>=90 and i<100: x= 'ninety'+ words[(i-90)] return words[(n-n%100)/100] + 'hundred' + 'and' + x elif n==1000: return 'onethousand' Explanation: Project Euler: Problem 17 https://projecteuler.net/problem=17 If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage. First write a number_to_words(n) function that takes an integer n between 1 and 1000 inclusive and returns a list of words for the number as described above End of explanation assert number_to_words(25)=='twentyfive' assert number_to_words(467)=='fourhundredandsixtyseven' assert number_to_words(1000)=='onethousand' assert number_to_words(1)=='one' assert number_to_words(30)=='thirty' assert True # use this for grading the number_to_words tests. Explanation: I realize this probably isn't the fastest or most concise code, but it works. Now write a set of assert tests for your number_to_words function that verifies that it is working as expected. End of explanation def count_letters(n): Count the number of letters used to write out the words for 1-n inclusive. x=n count=0 while x>0: count += len(number_to_words(x)) x -= 1 return count Explanation: Now define a count_letters(n) that returns the number of letters used to write out the words for all of the the numbers 1 to n inclusive. End of explanation assert count_letters(1)==3 assert count_letters(3)==11 assert count_letters(10)==39 assert True # use this for grading the count_letters tests. Explanation: Someone can probably do this in less lines but this method makes the most sense to me. Now write a set of assert tests for your count_letters function that verifies that it is working as expected. End of explanation count_letters(1000) Explanation: Finally used your count_letters function to solve the original question. End of explanation assert True # use this for gradig the answer to the original question. Explanation: Success! End of explanation
5,321
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="http Step1: Pick the initial and run conditions Step2: Elapsed time starts at 1 second. This prevents errors when setting our boundary conditions. Step3: Use Landlab methods to import an ARC ascii grid, and load the data into the field that the component needs to look at to get the data. This loads the elevation data, z, into a "field" in the grid itself, defined on the nodes. Step4: We can get at this data with this syntax Step5: Note that the boundary conditions for this grid mainly got handled with the final line of those three, but for the sake of completeness, we should probably manually "open" the outlet. We can find and set the outlet like this Step6: Now initialize a couple more grid fields that the component is going to need Step7: Let's look at our watershed topography Step8: Now instantiate the component itself Step9: Now we're going to run the loop that drives the component Step10: Now let's get clever, and run a set of time slices
Python Code: from landlab.components.overland_flow import OverlandFlow from landlab.plot.imshow import imshow_grid from landlab.plot.colors import water_colormap from landlab import RasterModelGrid from landlab.io.esri_ascii import read_esri_ascii from matplotlib.pyplot import figure import numpy as np from time import time %matplotlib inline Explanation: <a href="http://landlab.github.io"><img style="float: left" src="../../landlab_header.png"></a> The deAlmeida Overland Flow Component <hr> <small>For more Landlab tutorials, click here: <a href="https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html">https://landlab.readthedocs.io/en/latest/user_guide/tutorials.html</a></small> <hr> This notebook illustrates running the deAlmeida overland flow component in an extremely simple-minded way on a real topography, then shows it creating a flood sequence along an inclined surface with an oscillating water surface at one end. First, import what we'll need: End of explanation run_time = 100 # duration of run, (s) h_init = 0.1 # initial thin layer of water (m) n = 0.01 # roughness coefficient, (s/m^(1/3)) g = 9.8 # gravity (m/s^2) alpha = 0.7 # time-step factor (nondimensional; from Bates et al., 2010) u = 0.4 # constant velocity (m/s, de Almeida et al., 2012) run_time_slices = (10, 50, 100) Explanation: Pick the initial and run conditions End of explanation elapsed_time = 1.0 Explanation: Elapsed time starts at 1 second. This prevents errors when setting our boundary conditions. End of explanation rmg, z = read_esri_ascii('Square_TestBasin.asc') rmg.add_field('topographic__elevation', z, at='node') rmg.set_closed_boundaries_at_grid_edges(True, True, True, True) Explanation: Use Landlab methods to import an ARC ascii grid, and load the data into the field that the component needs to look at to get the data. This loads the elevation data, z, into a "field" in the grid itself, defined on the nodes. End of explanation np.all(rmg.at_node['topographic__elevation'] == z) Explanation: We can get at this data with this syntax: End of explanation my_outlet_node = 100 # This DEM was generated using Landlab and the outlet node ID was known rmg.status_at_node[my_outlet_node] = 1 # 1 is the code for fixed value Explanation: Note that the boundary conditions for this grid mainly got handled with the final line of those three, but for the sake of completeness, we should probably manually "open" the outlet. We can find and set the outlet like this: End of explanation rmg.add_zeros('surface_water__depth', at='node') # water depth (m) rmg.at_node['surface_water__depth'] += h_init Explanation: Now initialize a couple more grid fields that the component is going to need: End of explanation imshow_grid(rmg, 'topographic__elevation') Explanation: Let's look at our watershed topography End of explanation of = OverlandFlow( rmg, steep_slopes=True ) #for stability in steeper environments, we set the steep_slopes flag to True Explanation: Now instantiate the component itself End of explanation while elapsed_time < run_time: # First, we calculate our time step. dt = of.calc_time_step() # Now, we can generate overland flow. of.overland_flow() # Increased elapsed time print('Elapsed time: ', elapsed_time) elapsed_time += dt imshow_grid(rmg, 'surface_water__depth', cmap='Blues') Explanation: Now we're going to run the loop that drives the component: End of explanation elapsed_time = 1. for t in run_time_slices: while elapsed_time < t: # First, we calculate our time step. dt = of.calc_time_step() # Now, we can generate overland flow. of.overland_flow() # Increased elapsed time elapsed_time += dt figure(t) imshow_grid(rmg, 'surface_water__depth', cmap='Blues') Explanation: Now let's get clever, and run a set of time slices: End of explanation
5,322
Given the following text description, write Python code to implement the functionality described below step by step Description: Umbrella sampling simulations The bias is computed via a harmonic potential based on the deviation of a frame from a reference structure. In the usual one-dimensional case, this reads $$b^{(i)}(\mathbf{x}) = \frac{k^{(i)}}{2} \left\Vert \mathbf{x} - \mathbf{x}^{(i)} \right\Vert^2.$$ In the more general case, though, one can use a non-symmetric force matrix Step1: First step Step2: Plot 1-D histograms of the trajectories. Step3: Second step Step4: Third step Step5: Fourth step Step6: Mixed simulations data
Python Code: adw_x, adw_f, adw_pi = shortcuts.adw_reference(-1, 5, 100) fig, ax = plt.subplots(1, 2, figsize=(2 * pw, ph)) ax[0].plot(adw_x, adw_pi, linewidth=3, color='black') ax[0].set_ylabel(r"$\pi(x)$", fontsize=20) ax[0].semilogy() ax[1].plot(adw_x, adw_f, linewidth=3, color='black') ax[1].set_ylabel(r"$f(x)$ / kT", fontsize=20) for _ax in ax: _ax.set_xlabel(r"$x$ / a.u.", fontsize=20) _ax.tick_params(labelsize=15) fig.tight_layout() fig, ax = plt.subplots(1, 2, figsize=(2 * pw, ph)) # plot the thermodynamic ground/unbiased state (kT=1.0) ax[0].plot(adw_x, adw_pi, linewidth=3, color='black', label='unbiased') ax[1].plot(adw_x, adw_f, linewidth=3, color='black', label='unbiased') # plot the sixth umbrella _, adw_f2, adw_pi2 = shortcuts.adw_reference(adw_x[0], adw_x[-1], adw_x.shape[0], k_bias=30.0, x_bias=1.07894737) ax[0].plot(adw_x, adw_pi2, linewidth=3, color='blue', label='umbrella 6') ax[1].plot(adw_x, adw_f2, linewidth=3, color='blue', label='umbrella 6') # plot the 10th umbrella _, adw_f2, adw_pi2 = shortcuts.adw_reference(adw_x[0], adw_x[-1], adw_x.shape[0], k_bias=30.0, x_bias=2.13157895) ax[0].plot(adw_x, adw_pi2, linewidth=3, color='green', label='umbrella 10') ax[1].plot(adw_x, adw_f2, linewidth=3, color='green', label='umbrella 10') # plot the 14th umbrella _, adw_f2, adw_pi2 = shortcuts.adw_reference(adw_x[0], adw_x[-1], adw_x.shape[0], k_bias=30.0, x_bias=3.18421053) ax[0].plot(adw_x, adw_pi2, linewidth=3, color='red', label='umbrella 14') ax[1].plot(adw_x, adw_f2, linewidth=3, color='red', label='umbrella 14') # finish the figure ax[0].set_ylabel(r"$\pi^{(j)}(x)$", fontsize=20) ax[0].semilogy() ax[0].set_ylim([1.0E-10, 1.0]) ax[0].legend(loc=3, fontsize=12, fancybox=True, framealpha=0.5) ax[1].set_ylabel(r"$f^{(j)}(x) - f^{(j)}$ / kT", fontsize=20) ax[1].set_ylim([0.0, 30.0]) ax[1].legend(loc=2, fontsize=12, fancybox=True, framealpha=0.5) for _ax in ax: _ax.set_xlabel(r"$x$ / a.u.", fontsize=20) _ax.tick_params(labelsize=15) fig.tight_layout() Explanation: Umbrella sampling simulations The bias is computed via a harmonic potential based on the deviation of a frame from a reference structure. In the usual one-dimensional case, this reads $$b^{(i)}(\mathbf{x}) = \frac{k^{(i)}}{2} \left\Vert \mathbf{x} - \mathbf{x}^{(i)} \right\Vert^2.$$ In the more general case, though, one can use a non-symmetric force matrix: $$b^{(i)}(\mathbf{x}) = \frac{1}{2} \left\langle \mathbf{x} - \mathbf{x}^{(i)} \middle\vert \mathbf{k}^{(i)} \middle\vert \mathbf{x} - \mathbf{x}^{(i)} \right\rangle.$$ API functions for umbrella sampling For these simulation types, the pyemma.thermo module provides the API functions ```python def estimate_umbrella_sampling( us_trajs, us_dtrajs, us_centers, us_force_constants, md_trajs=None, md_dtrajs=None, kT=None, maxiter=10000, maxerr=1.0E-15, save_convergence_info=0, estimator='wham', lag=1, dt_traj='1 step', init=None): ... ``` Example Model 1: one-dimensional asymmetric double well potential We start by looking at the stationary distribution and free energy profile which are available analytically. End of explanation _adw_us_data_path = "data/asymmetric_double_well/umbrella_sampling/" _adw_us_meta = np.loadtxt(_adw_us_data_path + "meta.dat") adw_us_trajs = [np.load(_adw_us_data_path + "us_traj_%03d.npy" % int(i)) for i in _adw_us_meta[:, 0]] adw_us_umbrella_centers = list(_adw_us_meta[:, 1]) adw_us_force_constants = list(_adw_us_meta[:, 2]) type(adw_us_trajs) len(adw_us_trajs) adw_us_trajs[0].size print(len(adw_us_trajs)) print(len(adw_us_umbrella_centers)) print(len(adw_us_force_constants)) plt.errorbar(np.arange(len(adw_us_umbrella_centers)), adw_us_umbrella_centers, yerr=1.0/np.array(adw_us_force_constants)**0.5, fmt='_') plt.xlabel('trajectory number') plt.ylabel('x') import glob print('order parameter trajectory shape', adw_us_trajs[0].shape) location = "/Users/weilu/Research/server/jul_2017/pulling/free_energy/k_0.1/simulation/dis_169.69696969696972/0/" file = location + "data" type(adw_us_trajs[0]) my_umbrella_centers = [i for i in np.linspace(0, 400, 100)] my_force_constants = [0.1]*100 f = "/Users/weilu/Research/server/jul_2017/pulling/free_energy/k_0.1/simulation/dis_" umbrella_list = glob.glob("/Users/weilu/Research/server/jul_2017/pulling/free_energy/k_0.1/simulation/dis_*") import re numbers = re.compile(r'(\d+)') def numericalSort(value): parts = numbers.split(value) parts[1::2] = map(int, parts[1::2]) return parts umbrella_list = sorted(umbrella_list, key=numericalSort) myTrajs = [] myEnergys = [] for location in umbrella_list: file = location + "/0/data" tmp = np.loadtxt(file)[:,0].reshape(600,1).copy() myEnergys.append(tmp) tmp = np.loadtxt(file)[:,1].reshape(600,1).copy() myTrajs.append(tmp) for t in myTrajs: plt.hist(t) plt.ylabel('counts') plt.xlabel('x') myTrajs[0].flags myTrajs[0].copy().flags len(adw_us_umbrella_centers) myCluster = pyemma.coordinates.cluster_regspace(myTrajs, max_centers=500, dmin=10) myEstimator = pyemma.thermo.estimate_umbrella_sampling( myTrajs, myCluster.dtrajs, my_umbrella_centers, my_force_constants, maxiter=1000000, maxerr=1.0E-15, save_convergence_info=50, estimator='wham') pyemma.plots.plot_convergence_info(myEstimator) plt.plot(myEstimator.umbrella_centers[:, 0], myEstimator.f_therm, 's', markersize=10, label=adw_us_estimator.name) plt.set_xlabel(r"umbrella_center", fontsize=20) plt.set_ylabel(r"f_therm / kT", fontsize=20) Explanation: First step: import the data from 100 precomputed umbrella sampling trajectories as listed in the file meta.dat... End of explanation for t in adw_us_trajs: plt.hist(t) plt.ylabel('counts') plt.xlabel('x') Explanation: Plot 1-D histograms of the trajectories. End of explanation adw_us_cluster = pyemma.coordinates.cluster_regspace(adw_us_trajs, max_centers=500, dmin=0.2) ?pyemma.coordinates.cluster_regspace Explanation: Second step: run a clustering algorithm on the configuration trajectories to define the bins (and to compute the bin counts later on). End of explanation adw_us_estimator = pyemma.thermo.estimate_umbrella_sampling( adw_us_trajs, adw_us_cluster.dtrajs, adw_us_umbrella_centers, adw_us_force_constants, maxiter=100000, maxerr=1.0E-15, save_convergence_info=50, estimator='wham') pyemma.plots.plot_convergence_info(adw_us_estimator) Explanation: Third step: run WHAM estimations using the estimate_umbrella_sampling API function and plot the convergence info... End of explanation adw_us_x, adw_us_f = shortcuts.adw_match_reference_to_binning(adw_us_trajs, adw_us_cluster.clustercenters) fig, ax = plt.subplots(1, 2, figsize=(2 * pw, ph)) ax[0].plot( adw_us_cluster.clustercenters[adw_us_estimator.active_set, 0], adw_us_estimator.f, 's', markersize=10, label=adw_us_estimator.name) ax[0].plot(adw_us_x, adw_us_f, '-*', linewidth=2, markersize=9, color='black', label='Reference') ax[0].set_xlabel(r"configuration state", fontsize=20) ax[0].set_ylabel(r"f / kT", fontsize=20) ax[1].plot(adw_us_estimator.umbrella_centers[:, 0], adw_us_estimator.f_therm, 's', markersize=10, label=adw_us_estimator.name) ax[1].set_xlabel(r"umbrella_center", fontsize=20) ax[1].set_ylabel(r"f_therm / kT", fontsize=20) for _ax in ax: _ax.tick_params(labelsize=15) _ax.set_ylim([0, 12]) _ax.legend(loc=4, fontsize=10, fancybox=True, framealpha=0.5) fig.tight_layout() Explanation: Fourth step: plot the free energies f and f_therm... End of explanation # load unbiased data adw_md_trajs = [np.load(_adw_us_data_path + "md_traj_%03d.npy" % i) for i in range(5)] # redo clustering with both, biased and unbiased data adw_us_cluster = pyemma.coordinates.cluster_regspace(adw_us_trajs + adw_md_trajs, max_centers=500, dmin=0.2) # split dtrajs into biased and unbiased adw_us_dtrajs = adw_us_cluster.dtrajs[:len(adw_us_trajs)] adw_md_dtrajs = adw_us_cluster.dtrajs[len(adw_us_trajs):] # plot order parameter trajectories of the unbiased simulations for t in adw_md_trajs: plt.plot(t) plt.ylabel('x') plt.xlabel('step') # run the estimator again for a sequence of lag times lags = [1, 2, 5, 7, 10, 15, 20, 30, 40, 50, 70, 100] memms = pyemma.thermo.estimate_umbrella_sampling( adw_us_trajs, adw_us_dtrajs, adw_us_umbrella_centers, adw_us_force_constants, md_trajs=adw_md_trajs, md_dtrajs=adw_md_dtrajs, lag=lags, maxiter=100000, maxerr=1.0E-15, save_convergence_info=50, estimator='dtram') # TRAM #lags = [1, 10, 50] #memms = pyemma.thermo.estimate_umbrella_sampling( # adw_us_trajs, adw_us_dtrajs, adw_us_umbrella_centers, adw_us_force_constants, # md_trajs=adw_md_trajs, md_dtrajs=adw_md_dtrajs, # lag=lags, # maxiter=100000, maxerr=1.0E-6, init_maxerr=1.0, save_convergence_info=50, estimator='tram', direct_space=True) [ m.name for m in memms ] # plot implied time scales depending on lag time pyemma.plots.plot_memm_implied_timescales(memms) # at 10 steps the implied time scales look converged, pick that model for analysis print(memms[4].lag) dtram_estiamtor = memms[4] # for TRAM #print(memms[1].lag) #dtram_estiamtor = memms[1] # plot estimate of the stationary distribution adw_us_x, adw_us_f = shortcuts.adw_match_reference_to_binning(adw_us_trajs, adw_us_cluster.clustercenters) plt.figure(figsize=(2 * pw, ph)) plt.plot( adw_us_cluster.clustercenters[dtram_estiamtor.active_set, 0], dtram_estiamtor.f, 's', markersize=10, label=dtram_estiamtor.name) plt.plot(adw_us_x, adw_us_f, '-*', linewidth=2, markersize=9, color='black', label='Reference') plt.xlabel(r"configuration state", fontsize=20) plt.ylabel(r"f / kT", fontsize=20) Explanation: Mixed simulations data: US simulations + unbiased simulations End of explanation
5,323
Given the following text description, write Python code to implement the functionality described below step by step Description: TinyDB TinyDB is a small and lightweight NoSQL database framework based on simple JSON files. Source Official Website Step1: Insert some data into db. Step2: Fill with some data (iris). Step3: Error Handling Step4: If the actual data is irrelevant, to check for the existance of an element, use contains or count. Step5: IDs Step6: Regex and nested queries
Python Code: path = './testData.json' from tinydb import TinyDB, where db = TinyDB(path) Explanation: TinyDB TinyDB is a small and lightweight NoSQL database framework based on simple JSON files. Source Official Website: - getting started - advanced usage Code Some examples to create a database and insert, delete and seach for elements. Basics Generate new database. If path leads to an existing file, the data is read. Otherwise a new database is created. End of explanation print(db.insert({'a':1, 'b':3})) # return the elements id [1,2,..] db.all() # returns list of dicts Explanation: Insert some data into db. End of explanation db.purge() from sklearn import datasets iris = datasets.load_iris() data = iris.data keys = iris.feature_names print('== data ==\n', data[:5], '\n ...') print('== keys ==\n', keys) if(0 == len(db)): for d in data: db.insert({ keys[0]: d[0], keys[1]: d[1], keys[2]: d[2], keys[3]: d[3] }) # or # db.insert_multiple([ {}, {}, ...]) # returns list of ids db.search(where(keys[0]) >= 7.6 and where(keys[1]) >= 4.2) Explanation: Fill with some data (iris). End of explanation try: r = db.search(where(keys[0]) > 1000)[0] print(r) except: print('Not in db.') r = db.get(where(keys[0]) > 1000) if not r: print('Not in db.') # r is None Explanation: Error Handling End of explanation db.contains(where(keys[2]) == 1) db.count(where(keys[2]) == 1) Explanation: If the actual data is irrelevant, to check for the existance of an element, use contains or count. End of explanation elem = db.get(where(keys[2]) == 1) elem.eid if db.contains(eids=[11, 12]): e1 = db.get(eid=11) e2 = db.get(eid=12) db.remove(eids=[11, 12]) db.insert_multiple([e1, e2]) print(len(db)) # db.remove(eids=list(arange(70, 75))) # print(len(db)) Explanation: IDs End of explanation # db.remove(where('field').has('name').has('last_name') == 'Doe') db.insert({'field': {'name': {'first_name': 'John', 'last_name': 'Doe'}}}) # print(db.search(where('field.name.last_name') == 'Doe')) # print(db.search(where('field.name.last_name').matches('[0-9]*')),'\n') db.remove(where('field').any(where('val') == 1)) db.insert({'field': [{'val': 1}, {'val': 2}, {'val': 3}]}) print(db.search(where('field').any(where('val') == 1))) Explanation: Regex and nested queries End of explanation
5,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Autoencoder Step5: Task Step6: Visualize reconstruction quality Step7: Illustrating latent space Next, we train a VAE with 2d latent space and illustrates how the encoder (the recognition network) encodes some of the labeled inputs (collapsing the Gaussian distribution in latent space to its mean). This gives us some insights into the structure of the learned manifold (latent space) Step8: An other way of getting insights into the latent space is to use the generator network to plot reconstrunctions at the positions in the latent space for which they have been generated
Python Code: import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import matplotlib.pyplot as plt %matplotlib inline import input_data mnist = input_data.read_data_sets('fashion-mnist/data/fashion', one_hot=True) n_samples = mnist.train.num_examples Explanation: Variational Autoencoder End of explanation class VAE: def __init__(self, network_architecture, transfer_fct=tf.nn.softplus, learning_rate=0.001, batch_size=100): self.network_architecture = network_architecture self.transfer_fct = transfer_fct self.learning_rate = learning_rate self.batch_size = batch_size self.x = tf.placeholder(tf.float32, [None, network_architecture["n_input"]]) self._create_network() self._create_loss_optimizer() init = tf.global_variables_initializer() self.sess = tf.InteractiveSession() self.sess.run(init) def _create_network(self): # Use recognition network to determine mean and # (log) variance of Gaussian distribution in latent # space self.z_mean, self.z_log_sigma_sq = self._recognition_network() # Draw one sample z from Gaussian distribution n_z = self.network_architecture["n_z"] # tip: use tf.random_normal eps = # # z = mu + sigma*epsilon self.z = tf.add(self.z_mean, tf.multiply(tf.sqrt(tf.exp(self.z_log_sigma_sq)), eps)) # Use generator to determine mean of # Bernoulli distribution of reconstructed input self.x_reconstr_mean = self._generator_network() def _recognition_network(self): layer_1 = slim.fully_connected(self.x, self.network_architecture['n_hidden_recog_1']) layer_2 = slim.fully_connected(layer_1, self.network_architecture['n_hidden_recog_2']) z_mean = slim.fully_connected(layer_2, self.network_architecture['n_z']) z_log_sigma_sq = slim.fully_connected(layer_2, self.network_architecture['n_z']) return z_mean, z_log_sigma_sq def _generator_network(self): layer_1 = slim.fully_connected(self.z, self.network_architecture['n_hidden_recog_1']) layer_2 = slim.fully_connected(layer_1, self.network_architecture['n_hidden_recog_2']) x_reconstr_mean = slim.fully_connected(layer_2, self.network_architecture['n_input']) return x_reconstr_mean def _create_loss_optimizer(self): reconstr_loss = #\ latent_loss = # self.cost = tf.reduce_mean(reconstr_loss + latent_loss) # average over batch self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate).minimize(self.cost) def partial_fit(self, X): Train model based on mini-batch of input data. Return cost of mini-batch. opt, cost = self.sess.run((self.optimizer, self.cost), feed_dict={self.x: X}) return cost def transform(self, X): Transform data by mapping it into the latent space. # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.z_mean, feed_dict={self.x: X}) def generate(self, z_mu=None): Generate data by sampling from latent space. If z_mu is not None, data for this point in latent space is generated. Otherwise, z_mu is drawn from prior in latent space. if z_mu is None: z_mu = np.random.normal(size=self.network_architecture["n_z"]) # Note: This maps to mean of distribution, we could alternatively # sample from Gaussian distribution return self.sess.run(self.x_reconstr_mean, feed_dict={self.z: z_mu}) def reconstruct(self, X): Use VAE to reconstruct given data. return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X}) def train(network_architecture, learning_rate=0.001, batch_size=1000, training_epochs=10, display_step=5): vae = VAE(network_architecture, learning_rate=learning_rate, batch_size=batch_size) # Training cycle for epoch in range(training_epochs): avg_cost = 0. total_batch = int(n_samples / batch_size) # Loop over all batches for i in range(total_batch): batch_xs, _ = mnist.train.next_batch(batch_size) # Fit training using batch data cost = vae.partial_fit(batch_xs) # Compute average loss avg_cost += cost / n_samples * batch_size # Display logs per epoch step if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)) return vae Explanation: Task: fill the gaps in VAE End of explanation network_architecture = \ dict(n_hidden_recog_1=500, # 1st layer encoder neurons n_hidden_recog_2=500, # 2nd layer encoder neurons n_hidden_gener_1=500, # 1st layer decoder neurons n_hidden_gener_2=500, # 2nd layer decoder neurons n_input=784, # MNIST data input (img shape: 28*28) n_z=20) # dimensionality of latent space # vae = train(network_architecture, training_epochs=75) x_sample = mnist.test.next_batch(1000)[0] x_reconstruct = vae.reconstruct(x_sample) plt.figure(figsize=(8, 12)) for i in range(5): plt.subplot(5, 2, 2*i + 1) plt.imshow(x_sample[i].reshape(28, 28), vmin=0, vmax=1, cmap="gray") plt.title("Test input") plt.colorbar() plt.subplot(5, 2, 2*i + 2) plt.imshow(x_reconstruct[i].reshape(28, 28), vmin=0, vmax=1, cmap="gray") plt.title("Reconstruction") plt.colorbar() plt.tight_layout() Explanation: Visualize reconstruction quality End of explanation network_architecture = \ dict(n_hidden_recog_1=500, # 1st layer encoder neurons n_hidden_recog_2=500, # 2nd layer encoder neurons n_hidden_gener_1=500, # 1st layer decoder neurons n_hidden_gener_2=500, # 2nd layer decoder neurons n_input=784, # MNIST data input (img shape: 28*28) n_z=`) # dimensionality of latent space vae_2d = train(network_architecture, training_epochs=75) x_sample, y_sample = mnist.test.next_batch(5000) z_mu = vae_2d.transform(x_sample) plt.figure(figsize=(8, 6)) plt.scatter(z_mu[:, 0], z_mu[:, 1], c=np.argmax(y_sample, 1)) plt.colorbar() plt.grid() Explanation: Illustrating latent space Next, we train a VAE with 2d latent space and illustrates how the encoder (the recognition network) encodes some of the labeled inputs (collapsing the Gaussian distribution in latent space to its mean). This gives us some insights into the structure of the learned manifold (latent space) End of explanation nx = ny = 20 x_values = np.linspace(-3, 3, nx) y_values = np.linspace(-3, 3, ny) canvas = np.empty((28*ny, 28*nx)) for i, yi in enumerate(x_values): for j, xi in enumerate(y_values): z_mu = np.array([[xi, yi]]*vae.batch_size) x_mean = vae_2d.generate(z_mu) canvas[(nx-i-1)*28:(nx-i)*28, j*28:(j+1)*28] = x_mean[0].reshape(28, 28) plt.figure(figsize=(8, 10)) Xi, Yi = np.meshgrid(x_values, y_values) plt.imshow(canvas, origin="upper", cmap="gray") plt.tight_layout() Explanation: An other way of getting insights into the latent space is to use the generator network to plot reconstrunctions at the positions in the latent space for which they have been generated: End of explanation
5,325
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial 2 Step1: Parametrization (recap of Tutorial 1) We'll rerun the parametrization performed in Tutorial 1. Step2: Highlighting atoms and CG beads To link atoms to coarse-grained beads, it's useful to have a look at a few Cg_molecule attributes Step3: We'll want to color atoms according to beads, so let's define a color palette Step4: rdkit offers convenient rendering functions to highlight particular atoms and bonds. We will color heavy atoms involved in a particular CG bead. First let's focus on atoms Step5: Same for bonds. rdkit here comes to the rescue, because it keeps track of which heavy atoms are connected by bonds. Step6: We now have all the necessary ingredients to render a molecule with the appropriate atom and bond highlighting. Here we use the rdMolDraw2D from rdkit. We'll save this to a file, and render the file in the notebook
Python Code: import auto_martini as am import numpy as np from rdkit import Chem from rdkit.Chem.Draw import IPythonConsole from IPython.display import Image import rdkit from rdkit.Chem import Draw from rdkit.Chem import AllChem from rdkit.Chem import rdDepictor from rdkit.Chem.Draw import rdMolDraw2D print(rdkit.__version__) Explanation: Tutorial 2: Highlighting Following the parametrization of phenylmethanimine in Tutorial 1, let's visualize the correspondance between atoms and coarse-grained beads. First let's import a number of packages, especially auto_martini, various rdkit submodules, as well as IPython.display.Image to visualize an image in the notebook, and numpy. End of explanation smiles = "N=Cc1ccccc1" mol = Chem.MolFromSmiles(smiles) Chem.AddHs(mol) AllChem.EmbedMolecule(mol) mol # Load the molecule in auto_martini and coarse-grain it mol_am, _ = am.topology.gen_molecule_smi(smiles) cg = am.solver.Cg_molecule(mol_am, "PHM") Explanation: Parametrization (recap of Tutorial 1) We'll rerun the parametrization performed in Tutorial 1. End of explanation print("list_heavyatom_names:",cg.list_heavyatom_names) print("cg_bead_names: ",cg.cg_bead_names) print("atom_partitioning: ",cg.atom_partitioning) Explanation: Highlighting atoms and CG beads To link atoms to coarse-grained beads, it's useful to have a look at a few Cg_molecule attributes: - cg.list_heavyatom_names: lists the chemical elements of each heavy atom - cg.cg_bead_names: lists the CG bead names - cg.atom_partitioning: dictionary relating atom ID to CG bead ID. We'll mostly make use of the last one, here End of explanation colors = [(0.121, 0.466, 0.705), (1.0, 0.498, 0.0549), (0.172, 0.627, 0.172)] Explanation: We'll want to color atoms according to beads, so let's define a color palette End of explanation hit_ats = list(cg.atom_partitioning.keys()) atom_cols = {} for i, at in enumerate(hit_ats): atom_cols[at] = colors[cg.atom_partitioning[i]%4] Explanation: rdkit offers convenient rendering functions to highlight particular atoms and bonds. We will color heavy atoms involved in a particular CG bead. First let's focus on atoms: for each atom we want the CG bead ID it maps to. This is simply obtained from the keys() of the atom_partinioning dictionary. As for the colors, we can use the colors array defined above. End of explanation hit_bonds = [] bond_cols = {} for i, at in enumerate(hit_ats): for j, att in enumerate(hit_ats): if i > j and atom_cols[i] == atom_cols[j] and mol.GetBondBetweenAtoms(i,j): b_idx = mol.GetBondBetweenAtoms(i,j).GetIdx() hit_bonds.append(b_idx) bond_cols[b_idx] = colors[cg.atom_partitioning[i]%4] Explanation: Same for bonds. rdkit here comes to the rescue, because it keeps track of which heavy atoms are connected by bonds. End of explanation d = rdMolDraw2D.MolDraw2DCairo(400,400) rdMolDraw2D.PrepareAndDrawMolecule(d, mol, highlightAtoms=hit_ats, highlightAtomColors=atom_cols, highlightBonds=hit_bonds, highlightBondColors=bond_cols) d.DrawMolecule(mol) d.FinishDrawing() d.WriteDrawingText('phm_highlight.png') Image('phm_highlight.png') Explanation: We now have all the necessary ingredients to render a molecule with the appropriate atom and bond highlighting. Here we use the rdMolDraw2D from rdkit. We'll save this to a file, and render the file in the notebook: End of explanation
5,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Exact solution used in MES runs We would like to MES the operation $$ \partial_\theta f^2 $$ Using cylindrical geometry. Step1: Initialize Step2: Define the variables Step3: Define the function to take the derivative of NOTE Step4: Calculating the solution Step5: Plot Step6: Print the variables in BOUT++ format
Python Code: %matplotlib notebook from sympy import init_printing from sympy import S from sympy import sin, cos, tanh, exp, pi, sqrt from boutdata.mms import x, y, z, t from boutdata.mms import DDZ import os, sys # If we add to sys.path, then it must be an absolute path common_dir = os.path.abspath('./../../../../common') # Sys path is a list of system paths sys.path.append(common_dir) from CELMAPy.MES import get_metric, make_plot, BOUT_print init_printing() Explanation: Exact solution used in MES runs We would like to MES the operation $$ \partial_\theta f^2 $$ Using cylindrical geometry. End of explanation folder = '../gaussianWSinAndParabola/' metric = get_metric() Explanation: Initialize End of explanation # Initialization the_vars = {} Explanation: Define the variables End of explanation # We need Lx from boututils.options import BOUTOptions myOpts = BOUTOptions(folder) Lx = eval(myOpts.geom['Lx']) # Gaussian with sinus and parabola # The skew sinus # In cartesian coordinates we would like a sinus with with a wave-vector in the direction # 45 degrees with respect to the first quadrant. This can be achieved with a wave vector # k = [1/sqrt(2), 1/sqrt(2)] # sin((1/sqrt(2))*(x + y)) # We would like 2 nodes, so we may write # sin((1/sqrt(2))*(x + y)*(2*pi/(2*Lx))) # Rewriting this to cylindrical coordinates, gives # sin((1/sqrt(2))*(x*(cos(z)+sin(z)))*(2*pi/(2*Lx))) # The gaussian # In cartesian coordinates we would like # f = exp(-(1/(2*w^2))*((x-x0)^2 + (y-y0)^2)) # In cylindrical coordinates, this translates to # f = exp(-(1/(2*w^2))*(x^2 + y^2 + x0^2 + y0^2 - 2*(x*x0+y*y0) )) # = exp(-(1/(2*w^2))*(rho^2 + rho0^2 - 2*rho*rho0*(cos(theta)*cos(theta0)+sin(theta)*sin(theta0)) )) # = exp(-(1/(2*w^2))*(rho^2 + rho0^2 - 2*rho*rho0*(cos(theta - theta0)) )) # A parabola # In cartesian coordinates, we have # ((x-x0)/Lx)^2 # Chosing this function to have a zero value at the edge yields in cylindrical coordinates # ((x*cos(z)+Lx)/(2*Lx))^2 w = 0.8*Lx rho0 = 0.3*Lx theta0 = 5*pi/4 the_vars['f'] = sin((1/sqrt(2))*(x*(cos(z)+sin(z)))*(2*pi/(2*Lx)))*\ exp(-(1/(2*w**2))*(x**2 + rho0**2 - 2*x*rho0*(cos(z - theta0)) ))*\ ((x*cos(z)+Lx)/(2*Lx))**2 Explanation: Define the function to take the derivative of NOTE: z must be periodic The field $f(\rho, \theta)$ must be of class infinity in $z=0$ and $z=2\pi$ The field $f(\rho, \theta)$ must be single valued when $\rho\to0$ The field $f(\rho, \theta)$ must be continuous in the $\rho$ direction with $f(\rho, \theta + \pi)$ Eventual BC in $\rho$ must be satisfied End of explanation the_vars['S'] = DDZ(DDZ(the_vars['f'], metric=metric), metric=metric) Explanation: Calculating the solution End of explanation make_plot(folder=folder, the_vars=the_vars, plot2d=True, include_aux=False) Explanation: Plot End of explanation BOUT_print(the_vars, rational=False) Explanation: Print the variables in BOUT++ format End of explanation
5,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Tutorial Brief numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high dimentional arrays too. Finding Help Step1: Working with ndarray We will generate an ndarray with np.arange method. np.arange([start,] stop[, step,], dtype=None) Step2: Examining ndrray Step3: Why to use numpy? We will compare the time it takes to create two lists and do some basic operations on them. Generate a list Step4: Basic Operation Step5: Most Common Functions List Creation array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) ``` Parameters object Step6: Multi Dimentional Array Step7: zeros(shape, dtype=float, order='C') and ones(shape, dtype=float, order='C') ``` Parameters shape Step8: np.linspace(start, stop, num=50, endpoint=True, retstep=False) ``` Parameters start Step9: random_sample(size=None) ``` Parameters size Step10: Statistical Analysis Step11: np.max(a, axis=None, out=None, keepdims=False) ``` Parameters a Step12: np.min(a, axis=None, out=None, keepdims=False) Step13: np.mean(a, axis=None, dtype=None, out=None, keepdims=False) Step14: np.median(a, axis=None, out=None, overwrite_input=False) Step15: np.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False) Step16: np.sum(a, axis=None, dtype=None, out=None, keepdims=False) Step17: Reshaping np.reshape(a, newshape, order='C') Step18: np.ravel(a, order='C') Step19: Slicing Step20: Slicing a range Step21: Stepping Step22: Matrix Operations Step23: Addition Step24: Subtraction Step25: Multiplication (Element by Element) Step26: Multiplication (Matrix Multiplication) Step27: Division Step28: Square Step29: Power Step30: Transpose Step31: Inverse
Python Code: import numpy as np Explanation: Tutorial Brief numpy is a powerful set of tools to perform mathematical operations of on lists of numbers. It works faster than normal python lists operations and can manupilate high dimentional arrays too. Finding Help: http://wiki.scipy.org/Tentative_NumPy_Tutorial http://docs.scipy.org/doc/numpy/reference/ SciPy (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering. http://www.scipy.org/ So NumPy is a part of a bigger ecosystem of libraries that build on the optimized performance of NumPy NDArray. It contain these core packages: <table> <tr> <td style="background:Lavender;"><img src="http://www.scipy.org/_static/images/numpylogo_med.png" style="width:50px;height:50px;" /></td> <td style="background:Lavender;"><h4>NumPy</h4> Base N-dimensional array package </td> <td><img src="http://www.scipy.org/_static/images/scipy_med.png" style="width:50px;height:50px;" /></td> <td><h4>SciPy</h4> Fundamental library for scientific computing </td> <td><img src="http://www.scipy.org/_static/images/matplotlib_med.png" style="width:50px;height:50px;" /></td> <td><h4>Matplotlib</h4> Comprehensive 2D Plotting </td> </tr> <tr> <td><img src="http://www.scipy.org/_static/images/ipython.png" style="width:50px;height:50px;" /></td> <td><h4>IPython</h4> Enhanced Interactive Console </td> <td><img src="http://www.scipy.org/_static/images/sympy_logo.png" style="width:50px;height:50px;" /></td> <td><h4>SymPy</h4> Symbolic mathematics </td> <td><img src="http://www.scipy.org/_static/images/pandas_badge2.jpg" style="width:50px;height:50px;" /></td> <td><h4>Pandas</h4> Data structures & analysis </td> </tr> </table> Importig the library Import numpy library as np This helps in writing code and it's almost a standard in scientific work End of explanation np.arange(10) np.arange(1,10) np.arange(1,10, 0.5) np.arange(1,10, 3) np.arange(1,10, 2, dtype=np.float64) Explanation: Working with ndarray We will generate an ndarray with np.arange method. np.arange([start,] stop[, step,], dtype=None) End of explanation ds = np.arange(1,10,2) ds.ndim ds.shape ds.size ds.dtype ds.itemsize x=ds.data list(x) ds # Memory Usage ds.size * ds.itemsize Explanation: Examining ndrray End of explanation %%capture timeit_results # Regular Python %timeit python_list_1 = range(1,1000) python_list_1 = range(1,1000) python_list_2 = range(1,1000) #Numpy %timeit numpy_list_1 = np.arange(1,1000) numpy_list_1 = np.arange(1,1000) numpy_list_2 = np.arange(1,1000) print timeit_results # Function to calculate time in seconds def return_time(timeit_result): temp_time = float(timeit_result.split(" ")[5]) temp_unit = timeit_result.split(" ")[6] if temp_unit == "ms": temp_time = temp_time * 1e-3 elif temp_unit == "us": temp_time = temp_time * 1e-6 elif temp_unit == "ns": temp_time = temp_time * 1e-9 return temp_time python_time = return_time(timeit_results.stdout.split("\n")[0]) numpy_time = return_time(timeit_results.stdout.split("\n")[1]) print "Python/NumPy: %.1f" % (python_time/numpy_time) Explanation: Why to use numpy? We will compare the time it takes to create two lists and do some basic operations on them. Generate a list End of explanation %%capture timeit_python %%timeit # Regular Python [(x + y) for x, y in zip(python_list_1, python_list_2)] [(x - y) for x, y in zip(python_list_1, python_list_2)] [(x * y) for x, y in zip(python_list_1, python_list_2)] [(x / y) for x, y in zip(python_list_1, python_list_2)]; print timeit_python %%capture timeit_numpy %%timeit #Numpy numpy_list_1 + numpy_list_2 numpy_list_1 - numpy_list_2 numpy_list_1 * numpy_list_2 numpy_list_1 / numpy_list_2; print timeit_numpy python_time = return_time(timeit_python.stdout) numpy_time = return_time(timeit_numpy.stdout) print "Python/NumPy: %.1f" % (python_time/numpy_time) Explanation: Basic Operation End of explanation np.array([1,2,3,4,5]) Explanation: Most Common Functions List Creation array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) ``` Parameters object : array_like An array, any object exposing the array interface, an object whose array method returns an array, or any (nested) sequence. dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to 'upcast' the array. For downcasting, use the .astype(t) method. copy : bool, optional If true (default), then the object is copied. Otherwise, a copy will only be made if array returns a copy, if obj is a nested sequence, or if a copy is needed to satisfy any of the other requirements (dtype, order, etc.). order : {'C', 'F', 'A'}, optional Specify the order of the array. If order is 'C' (default), then the array will be in C-contiguous order (last-index varies the fastest). If order is 'F', then the returned array will be in Fortran-contiguous order (first-index varies the fastest). If order is 'A', then the returned array may be in any order (either C-, Fortran-contiguous, or even discontiguous). subok : bool, optional If True, then sub-classes will be passed-through, otherwise the returned array will be forced to be a base-class array (default). ndmin : int, optional Specifies the minimum number of dimensions that the resulting array should have. Ones will be pre-pended to the shape as needed to meet this requirement. ``` End of explanation np.array([[1,2],[3,4],[5,6]]) Explanation: Multi Dimentional Array End of explanation np.zeros((3,4)) np.zeros((3,4), dtype=np.int64) np.ones((3,4)) Explanation: zeros(shape, dtype=float, order='C') and ones(shape, dtype=float, order='C') ``` Parameters shape : int or sequence of ints Shape of the new array, e.g., (2, 3) or 2. dtype : data-type, optional The desired data-type for the array, e.g., numpy.int8. Default is numpy.float64. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. ``` End of explanation np.linspace(1,5) np.linspace(0,2,num=4) np.linspace(0,2,num=4,endpoint=False) Explanation: np.linspace(start, stop, num=50, endpoint=True, retstep=False) ``` Parameters start : scalar The starting value of the sequence. stop : scalar The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded. Note that the step size changes when endpoint is False. num : int, optional Number of samples to generate. Default is 50. endpoint : bool, optional If True, stop is the last sample. Otherwise, it is not included. Default is True. retstep : bool, optional If True, return (samples, step), where step is the spacing between samples. ``` End of explanation np.random.random((2,3)) np.random.random_sample((2,3)) Explanation: random_sample(size=None) ``` Parameters size : int or tuple of ints, optional Defines the shape of the returned array of random floats. If None (the default), returns a single float. ``` End of explanation data_set = np.random.random((2,3)) data_set Explanation: Statistical Analysis End of explanation np.max(data_set) np.max(data_set, axis=0) np.max(data_set, axis=1) Explanation: np.max(a, axis=None, out=None, keepdims=False) ``` Parameters a : array_like Input data. axis : int, optional Axis along which to operate. By default, flattened input is used. out : ndarray, optional Alternative output array in which to place the result. Must be of the same shape and buffer length as the expected output. See doc.ufuncs (Section "Output arguments") for more details. keepdims : bool, optional If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the original arr. ``` End of explanation np.min(data_set) Explanation: np.min(a, axis=None, out=None, keepdims=False) End of explanation np.mean(data_set) Explanation: np.mean(a, axis=None, dtype=None, out=None, keepdims=False) End of explanation np.median(data_set) Explanation: np.median(a, axis=None, out=None, overwrite_input=False) End of explanation np.std(data_set) Explanation: np.std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False) End of explanation np.sum(data_set) Explanation: np.sum(a, axis=None, dtype=None, out=None, keepdims=False) End of explanation np.reshape(data_set, (3,2)) np.reshape(data_set, (6,1)) np.reshape(data_set, (6)) Explanation: Reshaping np.reshape(a, newshape, order='C') End of explanation np.ravel(data_set) Explanation: np.ravel(a, order='C') End of explanation data_set = np.random.random((5,10)) data_set data_set[1] data_set[1][0] data_set[1,0] Explanation: Slicing End of explanation data_set[2:4] data_set[2:4,0] data_set[2:4,0:2] data_set[:,0] Explanation: Slicing a range End of explanation data_set[2:4:1] data_set[::] data_set[::2] data_set[2:4] data_set[2:4,::2] Explanation: Stepping End of explanation import numpy as np # Matrix A A = np.array([[1,2],[3,4]]) # Matrix B B = np.array([[3,4],[5,6]]) Explanation: Matrix Operations End of explanation A+B Explanation: Addition End of explanation A-B Explanation: Subtraction End of explanation A*B Explanation: Multiplication (Element by Element) End of explanation A.dot(B) Explanation: Multiplication (Matrix Multiplication) End of explanation A/B Explanation: Division End of explanation np.square(A) Explanation: Square End of explanation np.power(A,3) #cube of matrix Explanation: Power End of explanation A.transpose() Explanation: Transpose End of explanation np.linalg.inv(A) Explanation: Inverse End of explanation
5,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Video 1 Step1: Simply printing out the DataFrame will give us similar information to R's str() Step2: And for the summary we'll use an equivalent method, DataFrame.describe() Step3: Video 2 Now we want to create a table with Playoffs and Wins. In R, the command is table(NBA$W, NBA$Playoffs). Step4: Create a new column in NBA, which contains the difference between points scored and lost. (R Step5: Now we plot Wins as a function of points difference to get an idea whether there is a corellation. Step6: To build a linear regression model, I followed this blog post. We need to import LinearRegression from scikit-learn Step7: And build the model Step8: I didn't find a method that would print a nice R-like summary of the model in python, so we need to print them manually Step9: I've just found a method in pandas that prints out a summary! Step10: Multiple linear regression (Video 3) There are several ways of creating a multidimensional model, but I like this one Step11: Let's print the residuals Step12: Video 4
Python Code: NBA = pd.read_csv("NBA_train.csv") Explanation: Video 1 End of explanation NBA Explanation: Simply printing out the DataFrame will give us similar information to R's str(): End of explanation NBA.describe() Explanation: And for the summary we'll use an equivalent method, DataFrame.describe(): End of explanation NBA[['Playoffs', 'W']].groupby('W').aggregate(sum) Explanation: Video 2 Now we want to create a table with Playoffs and Wins. In R, the command is table(NBA$W, NBA$Playoffs). End of explanation NBA['PTSdiff'] = NBA['PTS'] - NBA['oppPTS'] NBA Explanation: Create a new column in NBA, which contains the difference between points scored and lost. (R: NBA$PTSdiff = NBA$PTS - NBA$oppPTS) End of explanation NBA.plot(x='PTSdiff', y='W', kind='scatter') Explanation: Now we plot Wins as a function of points difference to get an idea whether there is a corellation. End of explanation from sklearn.linear_model import LinearRegression Explanation: To build a linear regression model, I followed this blog post. We need to import LinearRegression from scikit-learn: End of explanation lr = LinearRegression() lr.fit(NBA[['PTSdiff']], NBA[['W']]) Explanation: And build the model: End of explanation print(lr.score(NBA[['PTSdiff']], NBA[['W']])) # R^2 print(lr.intercept_) print(lr.coef_) Explanation: I didn't find a method that would print a nice R-like summary of the model in python, so we need to print them manually: End of explanation from pandas.stats.api import ols model = ols(x=NBA['PTSdiff'], y=NBA['W']) model Explanation: I've just found a method in pandas that prints out a summary! End of explanation NBA['X2PA'] = NBA['2PA'] NBA['X3PA'] = NBA['3PA'] import statsmodels.formula.api as sm model = sm.ols(formula="PTS ~ X2PA + X3PA + FTA + AST + ORB + DRB + TOV + STL + BLK", data=NBA).fit() model.summary() Explanation: Multiple linear regression (Video 3) There are several ways of creating a multidimensional model, but I like this one: link. First, we need to convert column names like in R --- otherwise the methods will throw an error End of explanation model.resid SSE = sum(model.resid**2) SSE RMSE = np.sqrt(SSE/len(NBA)) RMSE np.mean(NBA['PTS']) model1 = sm.ols(formula="PTS ~ X2PA + X3PA + FTA + AST + ORB + DRB + STL + BLK", data=NBA).fit() model1.summary() model2 = sm.ols(formula="PTS ~ X2PA + X3PA + FTA + AST + ORB + STL + BLK", data=NBA).fit() model2.summary() model3 = sm.ols(formula="PTS ~ X2PA + X3PA + FTA + AST + ORB + STL", data=NBA).fit() model3.summary() SSE3 = sum(model3.resid**2) SSE3 RMSE3 = np.sqrt(SSE3/len(NBA)) RMSE3 Explanation: Let's print the residuals: End of explanation NBA_test = pd.read_csv("NBA_test.csv") NBA_test['X2PA'] = NBA_test['2PA'] NBA_test['X3PA'] = NBA_test['3PA'] prediction = model3.predict(NBA_test) SSE_pred = sum((prediction-NBA_test['PTS'])**2) SST_pred = sum((np.mean(NBA['PTS']) - NBA_test['PTS'])**2) R2 = 1-SSE_pred/SST_pred R2 RMSE_pred = np.sqrt(SSE_pred/len(NBA_test)) RMSE_pred Explanation: Video 4: Making predictions End of explanation
5,329
Given the following text description, write Python code to implement the functionality described below step by step Description: Rydberg Pair Potentials Near Surfaces This tutorial is based on results that were published by J. Block and S. Scheel, "van der Waals interaction potential between Rydberg atoms near surfaces" Phys. Rev. A 96, 062509 (2017). We will reproduce the pair potentials shown in Figure 4. The final result is that for states around the $|70p_{3/2};70p_{3/2}\rangle$-asymptote of Rubidium the strength of the pair interaction is reduced when placing the atoms in front of a perfect mirror (perfectly conducting plate) compared to the vacuum interaction. As described in the introduction, we start our code with some preparations and load the necessary modules. Step1: The plate lies in the $xy$-plane with the surface at $z = 0$. The atoms lie in the $xz$-plane with $z>0$. We can set the angle between the interatomic axis and the z-axis theta and the center of mass distance from the surface distance_surface. distance_atom defines the interatomic distances for which the pair potential is plotted. The units of the respective quantities are given as comments. Be careful Step2: Next we define the state that we are interested in using pairinteraction's StateOne class . As shown in Figures 4 and 5 of Phys. Rev. A 96, 062509 (2017) we expect large changes for the $C_6$ coefficient of the $|69s_{1/2},m_j=1/2;72s_{1/2},m_j=1/2\rangle$ pair state, so this provides a good example. We set up the one-atom system using restrictions of energy, main quantum number n and angular momentum l. This is done by means of the restrict... functions in SystemOne. Step3: The pair state state_two is created from the one atom states state_one1 and state_one2 using the StateTwo class. From the previously set up system_one we define system_two using SystemTwo class. This class also contains methods set.. to set angle, distance, surface distance and to enableGreenTensor in order implement a surface. Step4: Next, we diagonalize the system for the given interatomic distances in distance_atom and compare the free space system to a system at distance_surface away from the perfect mirror. The energy is calculated with respect to a Rubidium $|70p_{3/2},m_j=3/2;70p_{3/2},m_j=3/2\rangle$ two atom state, defined in energyzero.
Python Code: %matplotlib inline # Arrays import numpy as np # Plotting import matplotlib.pyplot as plt from itertools import product # Operating system interfaces import os, sys # Parallel computing from multiprocessing import Pool # pairinteraction :-) from pairinteraction import pireal as pi # Create cache for matrix elements if not os.path.exists("./cache"): os.makedirs("./cache") cache = pi.MatrixElementCache("./cache") Explanation: Rydberg Pair Potentials Near Surfaces This tutorial is based on results that were published by J. Block and S. Scheel, "van der Waals interaction potential between Rydberg atoms near surfaces" Phys. Rev. A 96, 062509 (2017). We will reproduce the pair potentials shown in Figure 4. The final result is that for states around the $|70p_{3/2};70p_{3/2}\rangle$-asymptote of Rubidium the strength of the pair interaction is reduced when placing the atoms in front of a perfect mirror (perfectly conducting plate) compared to the vacuum interaction. As described in the introduction, we start our code with some preparations and load the necessary modules. End of explanation theta = np.pi/2 # rad distance_atom = np.linspace(6, 1.5, 50) # µm distance_surface = 1 # µm Explanation: The plate lies in the $xy$-plane with the surface at $z = 0$. The atoms lie in the $xz$-plane with $z>0$. We can set the angle between the interatomic axis and the z-axis theta and the center of mass distance from the surface distance_surface. distance_atom defines the interatomic distances for which the pair potential is plotted. The units of the respective quantities are given as comments. Be careful: theta = np.pi/2 corresponds to horizontal alignment of the two atoms with respect to the surface. For different angles, large interatomic distances distance_atom might lead to one of the atoms being placed inside the plate. Make sure that distance_surface is larger than distance_atom*np.cos(theta)/2. End of explanation state_one1 = pi.StateOne("Rb", 69, 0, 0.5, 0.5) state_one2 = pi.StateOne("Rb", 72, 0, 0.5, 0.5) # Set up one-atom system system_one = pi.SystemOne(state_one1.getSpecies(), cache) system_one.restrictEnergy(min(state_one1.getEnergy(),state_one2.getEnergy()) - 50, \ max(state_one1.getEnergy(),state_one2.getEnergy()) + 50) system_one.restrictN(min(state_one1.getN(),state_one2.getN()) - 2, \ max(state_one1.getN(),state_one2.getN()) + 2) system_one.restrictL(min(state_one1.getL(),state_one2.getL()) - 2, \ max(state_one1.getL(),state_one2.getL()) + 2) Explanation: Next we define the state that we are interested in using pairinteraction's StateOne class . As shown in Figures 4 and 5 of Phys. Rev. A 96, 062509 (2017) we expect large changes for the $C_6$ coefficient of the $|69s_{1/2},m_j=1/2;72s_{1/2},m_j=1/2\rangle$ pair state, so this provides a good example. We set up the one-atom system using restrictions of energy, main quantum number n and angular momentum l. This is done by means of the restrict... functions in SystemOne. End of explanation # Set up pair state state_two = pi.StateTwo(state_one1, state_one2) # Set up two-atom system system_two = pi.SystemTwo(system_one, system_one, cache) system_two.restrictEnergy(state_two.getEnergy() - 5, state_two.getEnergy() + 5) system_two.setAngle(theta) system_two.enableGreenTensor(True) system_two.setDistance(distance_atom[0]) system_two.setSurfaceDistance(distance_surface) system_two.buildInteraction() Explanation: The pair state state_two is created from the one atom states state_one1 and state_one2 using the StateTwo class. From the previously set up system_one we define system_two using SystemTwo class. This class also contains methods set.. to set angle, distance, surface distance and to enableGreenTensor in order implement a surface. End of explanation # Diagonalize the two-atom system for different surface and interatomic distances def getDiagonalizedSystems(distances): system_two.setSurfaceDistance(distances[0]) system_two.setDistance(distances[1]) system_two.diagonalize(1e-3) return system_two.getHamiltonian().diagonal() if sys.platform != "win32": with Pool() as pool: energies = pool.map(getDiagonalizedSystems, product([1e12, distance_surface], distance_atom)) else: energies = list(map(getDiagonalizedSystems, product([1e12, distance_surface], distance_atom))) energyzero = pi.StateTwo(["Rb", "Rb"], [70, 70], [1, 1], [1.5, 1.5], [1.5, 1.5]).getEnergy() y = np.array(energies).reshape(2, -1)-energyzero x = np.repeat(distance_atom, system_two.getNumBasisvectors()) # Plot pair potentials fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.set_xlabel(r"Distance ($\mu m$)") ax.set_ylabel(r"Energy (GHz)") ax.set_xlim(np.min(distance_atom),np.max(distance_atom)) ax.set_ylim(-3, -1.6) ax.plot(x, y[0], 'ko', ms=3, label = 'free space') ax.plot(x, y[1], 'ro', ms=3, label = 'perfect mirror') ax.legend(); Explanation: Next, we diagonalize the system for the given interatomic distances in distance_atom and compare the free space system to a system at distance_surface away from the perfect mirror. The energy is calculated with respect to a Rubidium $|70p_{3/2},m_j=3/2;70p_{3/2},m_j=3/2\rangle$ two atom state, defined in energyzero. End of explanation
5,330
Given the following text description, write Python code to implement the functionality described below step by step Description: Homework 14 (or so) Step1: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files. Step2: So great, we have 702 of them. Now let's import them. Step3: In class we had the texts variable. For the homework can just do speeches_df['content'] to get the same sort of list of stuff. Take a look at the contents of the first 5 speeches Step4: Doing our analysis Use the sklearn package and a plain boring CountVectorizer to get a list of all of the tokens used in the speeches. If it won't list them all, that's ok! Make a dataframe with those terms as columns. Be sure to include English-language stopwords Step5: Okay, it's far too big to even look at. Let's try to get a list of features from a new CountVectorizer that only takes the top 100 words. Step6: Now let's push all of that into a dataframe with nicely named columns. Step7: Everyone seems to start their speeches with "mr chairman" - how many speeches are there total, and how many don't mention "chairman" and how many mention neither "mr" nor "chairman"? Step8: What is the index of the speech which is the most thankful, a.k.a. includes the word 'thank' the most times? Step9: If I'm searching for China and trade, what are the top 3 speeches to read according to the CountVectoriser? Step10: Now what if I'm using a TfidfVectorizer? Step11: What's the content of the speeches? Here's a way to get them Step12: Now search for something else! Another two terms that might show up. elections and chaos? Whatever you thnik might be interesting. Step13: Enough of this garbage, let's cluster Using a simple counting vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. Using a term frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. Using a term frequency inverse document frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. Step14: Which one do you think works the best? Step15: Harry Potter time I have a scraped collection of Harry Potter fanfiction at https
Python Code: # If you'd like to download it through the command line... !curl -O http://www.cs.cornell.edu/home/llee/data/convote/convote_v1.1.tar.gz # And then extract it through the command line... !tar -zxf convote_v1.1.tar.gz Explanation: Homework 14 (or so): TF-IDF text analysis and clustering Hooray, we kind of figured out how text analysis works! Some of it is still magic, but at least the TF and IDF parts make a little sense. Kind of. Somewhat. No, just kidding, we're professionals now. Investigating the Congressional Record The Congressional Record is more or less what happened in Congress every single day. Speeches and all that. A good large source of text data, maybe? Let's pretend it's totally secret but we just got it leaked to us in a data dump, and we need to check it out. It was leaked from this page here. End of explanation # glob finds files matching a certain filename pattern import glob # Give me all the text files paths = glob.glob('convote_v1.1/data_stage_one/development_set/*') paths[:5] len(paths) Explanation: You can explore the files if you'd like, but we're going to get the ones from convote_v1.1/data_stage_one/development_set/. It's a bunch of text files. End of explanation speeches = [] for path in paths: with open(path) as speech_file: speech = { 'pathname': path, 'filename': path.split('/')[-1], 'content': speech_file.read() } speeches.append(speech) speeches_df = pd.DataFrame(speeches) speeches_df.head() Explanation: So great, we have 702 of them. Now let's import them. End of explanation speeches_df['content'].head(5) Explanation: In class we had the texts variable. For the homework can just do speeches_df['content'] to get the same sort of list of stuff. Take a look at the contents of the first 5 speeches End of explanation count_vectorizer = CountVectorizer(stop_words='english') X=count_vectorizer.fit_transform(speeches_df['content']) len(count_vectorizer.get_feature_names()) tokens_df=pd.DataFrame(X.toarray(), columns=count_vectorizer.get_feature_names()) tokens_df Explanation: Doing our analysis Use the sklearn package and a plain boring CountVectorizer to get a list of all of the tokens used in the speeches. If it won't list them all, that's ok! Make a dataframe with those terms as columns. Be sure to include English-language stopwords End of explanation count_vectorizer = CountVectorizer(stop_words='english', max_features=100) X=count_vectorizer.fit_transform(speeches_df['content']) len(count_vectorizer.get_feature_names()) Explanation: Okay, it's far too big to even look at. Let's try to get a list of features from a new CountVectorizer that only takes the top 100 words. End of explanation tokens_df=pd.DataFrame(X.toarray(), columns=count_vectorizer.get_feature_names()) tokens_df Explanation: Now let's push all of that into a dataframe with nicely named columns. End of explanation # 702 rows means 702 speeches, since each speech is a single string len(tokens_df) # if the speech doesnt contain a chairman, the column entry will be 0. so, 250 no-chairmain speeches. granted, # we have no idea if they stared the speech with chairman or just mentioned him somewhere len(tokens_df[tokens_df['chairman']==0]) # 76 times no mr or chairman. which means they must call the chairman just 'chairman' a lot. rude! len(tokens_df[(tokens_df['mr']==0) & (tokens_df['chairman']==0)]) Explanation: Everyone seems to start their speeches with "mr chairman" - how many speeches are there total, and how many don't mention "chairman" and how many mention neither "mr" nor "chairman"? End of explanation # so speech index 375 tokens_df[tokens_df['thank']==tokens_df['thank'].max()].index # lets look at the speech speeches_df['content'][375] # wow that was long. but its the most thankful one, so whatever. Explanation: What is the index of the speech which is the most thankful, a.k.a. includes the word 'thank' the most times? End of explanation # i sorted by china here, on a lark. lets see if it holds true if i sort by trade tokens_df[(tokens_df['china']>0) & (tokens_df['trade']>0)].sort_values(by='china', ascending=False)[['china', 'trade']].head(3) tokens_df[(tokens_df['china']>0) & (tokens_df['trade']>0)].sort_values(by='trade', ascending=False)[['china', 'trade']].head(3) # kind of! at any rate, speech 294 seems to be the most china and trade related. lets look at it! speeches_df['content'][294] # thats another super long speech, but it does seem to mostly be about trade and china. Explanation: If I'm searching for China and trade, what are the top 3 speeches to read according to the CountVectoriser? End of explanation l2_vectorizer = TfidfVectorizer(stop_words='english', use_idf=True) X = l2_vectorizer.fit_transform(speeches_df['content']) tfidf_tokens_df = pd.DataFrame(X.toarray(), columns=l2_vectorizer.get_feature_names()) china_trade_df=pd.DataFrame([tfidf_tokens_df['china'], tfidf_tokens_df['trade'], tfidf_tokens_df['china'] + tfidf_tokens_df['trade']], index=["china", "trade", "china + trade"]).T china_trade_df[china_trade_df.any(axis=1)].sort_values(by='china + trade', ascending=False).head(3) # wow, that comes up with a totally different list of speeches. lets look at speech 636 speeches_df['content'][636] # that one is very short by comparison and this time, its really only about china and trade Explanation: Now what if I'm using a TfidfVectorizer? End of explanation # index 0 is the first speech, which was the first one imported. paths[0] # Pass that into 'cat' using { } which lets you put variables in shell commands # that way you can pass the path to cat !cat {paths[0]} # i guess i probably should have read ahead to this part. oh well, dumping the index of the speeches_df # was still mostly readable Explanation: What's the content of the speeches? Here's a way to get them: End of explanation election_chaos_df=pd.DataFrame([tfidf_tokens_df['election'], tfidf_tokens_df['chaos'], tfidf_tokens_df['election'] + tfidf_tokens_df['chaos']], index=["election", "chaos", "election + chaos"]).T election_chaos_df[election_chaos_df.any(axis=1)].sort_values(by='chaos', ascending=False).head(10) # i did the sort that way because i guess they dont talk about chaos much. lets look at that speech !cat {paths[257]} # thats pretty weak. i tried to come up with something spicier but i cant tell what years these are from. # how about this? clinton_welfare_df=pd.DataFrame([tfidf_tokens_df['clinton'], tfidf_tokens_df['welfare'], tfidf_tokens_df['clinton'] + tfidf_tokens_df['welfare']], index=["clinton", "welfare", "clinton + welfare"]).T clinton_welfare_df[clinton_welfare_df.any(axis=1)].sort_values(by='clinton + welfare', ascending=False).head(10) !cat {paths[346]} # still pretty dull. oh well. Explanation: Now search for something else! Another two terms that might show up. elections and chaos? Whatever you thnik might be interesting. End of explanation from sklearn.cluster import KMeans count_vectorizer = CountVectorizer(stop_words='english') X=count_vectorizer.fit_transform(speeches_df['content']) number_of_clusters = 8 km = KMeans(n_clusters=number_of_clusters) km.fit(X) print("Top terms per cluster:") order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = count_vectorizer.get_feature_names() for i in range(number_of_clusters): top_ten_words = [terms[ind] for ind in order_centroids[i, :5]] print("Cluster {}: {}".format(i, ' '.join(top_ten_words))) tf_vectorizer = TfidfVectorizer(stop_words='english', use_idf=False) X = tf_vectorizer.fit_transform(speeches_df['content']) number_of_clusters = 8 km = KMeans(n_clusters=number_of_clusters) km.fit(X) print("Top terms per cluster:") order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = tf_vectorizer.get_feature_names() for i in range(number_of_clusters): top_ten_words = [terms[ind] for ind in order_centroids[i, :5]] print("Cluster {}: {}".format(i, ' '.join(top_ten_words))) tfidf_vectorizer = TfidfVectorizer(stop_words='english', use_idf=True) X = tfidf_vectorizer.fit_transform(speeches_df['content']) number_of_clusters = 8 km = KMeans(n_clusters=number_of_clusters) km.fit(X) print("Top terms per cluster:") order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = tfidf_vectorizer.get_feature_names() for i in range(number_of_clusters): top_ten_words = [terms[ind] for ind in order_centroids[i, :5]] print("Cluster {}: {}".format(i, ' '.join(top_ten_words))) Explanation: Enough of this garbage, let's cluster Using a simple counting vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. Using a term frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. Using a term frequency inverse document frequency vectorizer, cluster the documents into eight categories, telling me what the top terms are per category. End of explanation # well, it seems to be between results including wild horses and those including frivolous lawsuits. # i prefer wild horses but the tfidf is probably the best representation of the actual document Explanation: Which one do you think works the best? End of explanation paths = glob.glob('hp/hp/*') paths[:5] hp_fics = [] for path in paths: with open(path) as hp_file: hp_fic = { 'pathname': path, 'filename': path.split('/')[-1], 'content': hp_file.read() } hp_fics.append(hp_fic) hp_fics_df = pd.DataFrame(hp_fics) hp_fics_df.head() tfidf_vectorizer = TfidfVectorizer(stop_words='english', use_idf=True) X = tfidf_vectorizer.fit_transform(hp_fics_df['content']) number_of_clusters = 2 km = KMeans(n_clusters=number_of_clusters) km.fit(X) print("Top terms per cluster:") order_centroids = km.cluster_centers_.argsort()[:, ::-1] terms = tfidf_vectorizer.get_feature_names() for i in range(number_of_clusters): top_ten_words = [terms[ind] for ind in order_centroids[i, :5]] print("Cluster {}: {}".format(i, ' '.join(top_ten_words))) # i would say people are either writing about harry and hermione or lily and james # ive never read harry potter, but i think that means either the harry generation or their parents generation? # seems legit Explanation: Harry Potter time I have a scraped collection of Harry Potter fanfiction at https://github.com/ledeprogram/courses/raw/master/algorithms/data/hp.zip. I want you to read them in, vectorize them and cluster them. Use this process to find out the two types of Harry Potter fanfiction. What is your hypothesis? End of explanation
5,331
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Decorator Pattern 1 Step2: Tip. 튜플 결합 Step3: Decorator Step4: 중첩된 decorator python @decorator3 @decorator2 @decorator1 [function, method, class] 적용순서
Python Code: def mean(first, second, *rest): 평균값 반환 함수 numbers = (first, second) + rest return sum(numbers) / len(numbers) Explanation: Decorator Pattern 1 End of explanation (1, 2) + (3,) Explanation: Tip. 튜플 결합 End of explanation def float_args_and_return(function): def wrapper(*args, **kwargs): args = [float(arg) for arg in args] return float(function(*args, **kwargs)) return wrapper wrap_mean = float_args_and_return(mean) Explanation: Decorator: 특정함수, 클래스, 메서드를 유일한 인자로 받음. End of explanation print(mean.__name__) print(mean.__doc__) print(wrap_mean.__name__) print(wrap_mean.__doc__) import functools def float_args_and_return(function): @functools.wraps(function) # __name__, __doc__ 승계, 디버깅에 유리 def wrapper(*args, **kwargs): args = [float(arg) for arg in args] return float(function(*args, **kwargs)) return wrapper wrap_mean = float_args_and_return(mean) print(wrap_mean.__name__) print(wrap_mean.__doc__) Explanation: 중첩된 decorator python @decorator3 @decorator2 @decorator1 [function, method, class] 적용순서: [[[[function, method, class] -> @decorator1] -> @decorator2] -> @decorator3] 원본 함수의 속성값 소실문제 End of explanation
5,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Submit Structures to MPComplete This notebook documents the process of 1. Taking and validating a collection of CIFs (e.g. in a ZIP file), creating pymatgen Structure objects 3. Filtering for structures that are submittable to MP (e.g. they are not duplicates) 4. Taking and validating common metadata for the structures (authors, references, etc.) 5. Submitting the resulting StructureNL objects to MP-Complete via the pymatgen MPRester Taking and validating a collection of CIFs We first need a filename for the ZIP archive. Step1: Let's create a list of structures from the ZIP archive's CIF files. Anything invalid about the ZIP archive or CIF files will raise an exception here. Step2: Filtering for structures that are submittable to MP Reject structures already on MP web site. Step4: Create a mock "job" for each structure, and then simulate the checks the submission processor does to reject jobs. The structures that pass here will actually spawn a ready workflow, so we will filter for such structures. Step6: Taking and validating common metadata for the structures If there are issues with the metadata, an exception will be raised on attempting to create snl_list. Step7: Submitting the structures to MP-Complete
Python Code: zipfilename = '/Users/dwinston/Dropbox/best/structures/ever.zip' Explanation: Submit Structures to MPComplete This notebook documents the process of 1. Taking and validating a collection of CIFs (e.g. in a ZIP file), creating pymatgen Structure objects 3. Filtering for structures that are submittable to MP (e.g. they are not duplicates) 4. Taking and validating common metadata for the structures (authors, references, etc.) 5. Submitting the resulting StructureNL objects to MP-Complete via the pymatgen MPRester Taking and validating a collection of CIFs We first need a filename for the ZIP archive. End of explanation from zipfile import ZipFile from pymatgen.io.cif import CifParser structures = [] myzip = ZipFile(zipfilename, 'r') for name in myzip.namelist(): with myzip.open(name) as cif_file: structures.extend(CifParser(cif_file).get_structures()) len(structures) Explanation: Let's create a list of structures from the ZIP archive's CIF files. Anything invalid about the ZIP archive or CIF files will raise an exception here. End of explanation from pymatgen import MPRester mpr = MPRester() mp_ids = [] new_structures = [] for s in structures: found = mpr.find_structure(s) if len(found) > 0: mp_ids.extend(found) else: new_structures.append(s) if len(mp_ids) > 0: print("Filtered out structures already on MP: {}".format(mp_ids)) len(new_structures) Explanation: Filtering for structures that are submittable to MP Reject structures already on MP web site. End of explanation from pymatgen import Composition from pymatgen.util.provenance import StructureNL def get_meta_from_structure(structure): Used by `structure_to_mock_job`, to "fill out" a job document. comp = structure.composition elsyms = sorted(set([e.symbol for e in comp.elements])) meta = {'nsites': len(structure), 'elements': elsyms, 'nelements': len(elsyms), 'formula': comp.formula, 'reduced_cell_formula': comp.reduced_formula, 'reduced_cell_formula_abc': Composition(comp.reduced_formula) .alphabetical_formula, 'anonymized_formula': comp.anonymized_formula, 'chemsystem': '-'.join(elsyms), 'is_ordered': structure.is_ordered, 'is_valid': structure.is_valid()} return meta def structure_to_mock_job(structure): # Needs at least one author. This is for a mock job, so can put whatever. snl = StructureNL(structure, [{"name": "Evgraf Fedorov", "email": "symmetry@ftw.org"}]) job = snl.as_dict() if 'is_valid' not in job: job.update(get_meta_from_structure(snl.structure)) sorted_structure = snl.structure.get_sorted_structure() job.update(sorted_structure.as_dict()) return job # mpworks.processors.process_submissions.SubmissionProcessor#submit_new_workflow MAX_SITES = 200 # SubmissionProcessor.MAX_SITES above # from mpworks.workflows.wf_utils import NO_POTCARS NO_POTCARS = ['Po', 'At', 'Rn', 'Fr', 'Ra', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr'] def job_is_submittable(job): snl = StructureNL.from_dict(job) if len(snl.structure.sites) > MAX_SITES: print 'REJECTED WORKFLOW FOR {} - too many sites ({})'.format( snl.structure.formula, len(snl.structure.sites)) elif not job['is_valid']: print 'REJECTED WORKFLOW FOR {} - invalid structure (atoms too close)'.format( snl.structure.formula) elif len(set(NO_POTCARS) & set(job['elements'])) > 0: print 'REJECTED WORKFLOW FOR {} - invalid element (No POTCAR)'.format( snl.structure.formula) elif not job['is_ordered']: print 'REJECTED WORKFLOW FOR {} - invalid structure (disordered)'.format( snl.structure.formula) else: return True return False # No longer need separate reference for new_structures structures = new_structures submittables = [] for s in structures: if job_is_submittable(structure_to_mock_job(s)): submittables.append(s) Explanation: Create a mock "job" for each structure, and then simulate the checks the submission processor does to reject jobs. The structures that pass here will actually spawn a ready workflow, so we will filter for such structures. End of explanation # No longer need separate reference for submittables structures = submittables # List of (name, email) pairs authors = [ ('Evgraf Fedorov', 'symmetry@ftw.org'), ('Arthur Schoenflies', 'art@berlin.de'), ] # BiBTeX string of references references = @article{Graf1961, author = {Graf, Donald L}, journal = {American Mineralogist}, number = {11}, pages = {1283--1316}, title = {{Crystallographic tables for the rhombohedral carbonates}}, volume = {46}, year = {1961} } @article{Akao_1977, author = {Akao, M and Iwai, S}, doi = {10.1107/s0567740877005834}, journal = {Acta Crystallogr Sect B}, month = {apr}, number = {4}, pages = {1273--1275}, publisher = {International Union of Crystallography ({\{}IUCr{\}})}, title = {{The hydrogen bonding of hydromagnesite}}, url = {http://dx.doi.org/10.1107/s0567740877005834}, volume = {33}, year = {1977} } # Projects? List of strings. projects = [] # Remarks? List of strings. remarks = [] snl_list = StructureNL.from_structures(structures, authors, references=references, projects=projects, remarks=remarks) Explanation: Taking and validating common metadata for the structures If there are issues with the metadata, an exception will be raised on attempting to create snl_list. End of explanation # Using v1 endpoint mpr = MPRester(endpoint="https://www.materialsproject.org/rest/v1") #mpr.submit_snl(snl_list) Explanation: Submitting the structures to MP-Complete End of explanation
5,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Source alignment and coordinate frames This tutorial shows how to visually assess the spatial alignment of MEG sensor locations, digitized scalp landmark and sensor locations, and MRI volumes. This alignment process is crucial for computing the forward solution, as is understanding the different coordinate frames involved in this process. Let's start out by loading some data. Step1: .. raw Step2: Coordinate frame definitions Neuromag/Elekta/MEGIN head coordinate frame ("head", Step3: A good example Here is the same plot, this time with the trans properly defined (using a precomputed transformation matrix). Step4: Visualizing the transformations Let's visualize these coordinate frames using just the scalp surface; this will make it easier to see their relative orientations. To do this we'll first load the Freesurfer scalp surface, then apply a few different transforms to it. In addition to the three coordinate frames discussed above, we'll also show the "mri_voxel" coordinate frame. Unlike MRI Surface RAS, "mri_voxel" has its origin in the corner of the volume (the left-most, posterior-most coordinate on the inferior-most MRI slice) instead of at the center of the volume. "mri_voxel" is also not an RAS coordinate system Step5: Now that we've transformed all the points, let's plot them. We'll use the same colors used by ~mne.viz.plot_alignment and use Step6: The relative orientations of the coordinate frames can be inferred by observing the direction of the subject's nose. Notice also how the origin of the Step7: Defining the head↔MRI trans using the GUI You can try creating the head↔MRI transform yourself using Step8: Alignment without MRI The surface alignments above are possible if you have the surfaces available from Freesurfer.
Python Code: import os.path as op import numpy as np import nibabel as nib from scipy import linalg import mne from mne.io.constants import FIFF data_path = mne.datasets.sample.data_path() subjects_dir = op.join(data_path, 'subjects') raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif') trans_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw-trans.fif') raw = mne.io.read_raw_fif(raw_fname) trans = mne.read_trans(trans_fname) src = mne.read_source_spaces(op.join(subjects_dir, 'sample', 'bem', 'sample-oct-6-src.fif')) # Load the T1 file and change the header information to the correct units t1w = nib.load(op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz')) t1w = nib.Nifti1Image(t1w.dataobj, t1w.affine) t1w.header['xyzt_units'] = np.array(10, dtype='uint8') t1_mgh = nib.MGHImage(t1w.dataobj, t1w.affine) Explanation: Source alignment and coordinate frames This tutorial shows how to visually assess the spatial alignment of MEG sensor locations, digitized scalp landmark and sensor locations, and MRI volumes. This alignment process is crucial for computing the forward solution, as is understanding the different coordinate frames involved in this process. Let's start out by loading some data. End of explanation fig = mne.viz.plot_alignment(raw.info, trans=trans, subject='sample', subjects_dir=subjects_dir, surfaces='head-dense', show_axes=True, dig=True, eeg=[], meg='sensors', coord_frame='meg', mri_fiducials='estimated') mne.viz.set_3d_view(fig, 45, 90, distance=0.6, focalpoint=(0., 0., 0.)) print('Distance from head origin to MEG origin: %0.1f mm' % (1000 * np.linalg.norm(raw.info['dev_head_t']['trans'][:3, 3]))) print('Distance from head origin to MRI origin: %0.1f mm' % (1000 * np.linalg.norm(trans['trans'][:3, 3]))) dists = mne.dig_mri_distances(raw.info, trans, 'sample', subjects_dir=subjects_dir) print('Distance from %s digitized points to head surface: %0.1f mm' % (len(dists), 1000 * np.mean(dists))) Explanation: .. raw:: html <style> .pink {color:DarkSalmon; font-weight:bold} .blue {color:DeepSkyBlue; font-weight:bold} .gray {color:Gray; font-weight:bold} .magenta {color:Magenta; font-weight:bold} .purple {color:Indigo; font-weight:bold} .green {color:LimeGreen; font-weight:bold} .red {color:Red; font-weight:bold} </style> .. role:: pink .. role:: blue .. role:: gray .. role:: magenta .. role:: purple .. role:: green .. role:: red Understanding coordinate frames For M/EEG source imaging, there are three coordinate frames must be brought into alignment using two 3D transformation matrices &lt;wiki_xform_&gt;_ that define how to rotate and translate points in one coordinate frame to their equivalent locations in another. The three main coordinate frames are: :blue:"meg": the coordinate frame for the physical locations of MEG sensors :gray:"mri": the coordinate frame for MRI images, and scalp/skull/brain surfaces derived from the MRI images :pink:"head": the coordinate frame for digitized sensor locations and scalp landmarks ("fiducials") Each of these are described in more detail in the next section. A good way to start visualizing these coordinate frames is to use the mne.viz.plot_alignment function, which is used for creating or inspecting the transformations that bring these coordinate frames into alignment, and displaying the resulting alignment of EEG sensors, MEG sensors, brain sources, and conductor models. If you provide subjects_dir and subject parameters, the function automatically loads the subject's Freesurfer MRI surfaces. Important for our purposes, passing show_axes=True to ~mne.viz.plot_alignment will draw the origin of each coordinate frame in a different color, with axes indicated by different sized arrows: shortest arrow: (R)ight / X medium arrow: forward / (A)nterior / Y longest arrow: up / (S)uperior / Z Note that all three coordinate systems are RAS coordinate frames and hence are also right-handed_ coordinate systems. Finally, note that the coord_frame parameter sets which coordinate frame the camera should initially be aligned with. Let's have a look: End of explanation mne.viz.plot_alignment(raw.info, trans=None, subject='sample', src=src, subjects_dir=subjects_dir, dig=True, surfaces=['head-dense', 'white'], coord_frame='meg') Explanation: Coordinate frame definitions Neuromag/Elekta/MEGIN head coordinate frame ("head", :pink:pink axes) The head coordinate frame is defined through the coordinates of anatomical landmarks on the subject's head: usually the Nasion (NAS), and the left and right preauricular points (LPA and RPA). Different MEG manufacturers may have different definitions of the head coordinate frame. A good overview can be seen in the FieldTrip FAQ on coordinate systems. For Neuromag/Elekta/MEGIN, the head coordinate frame is defined by the intersection of the line between the LPA (:red:red sphere) and RPA (:purple:purple sphere), and the line perpendicular to this LPA-RPA line one that goes through the Nasion (:green:green sphere). The axes are oriented as X origin→RPA, Y origin→NAS, Z origin→upward (orthogonal to X and Y). .. note:: The required 3D coordinates for defining the head coordinate frame (NAS, LPA, RPA) are measured at a stage separate from the MEG data recording. There exist numerous devices to perform such measurements, usually called "digitizers". For example, see the devices by the company Polhemus_. MEG device coordinate frame ("meg", :blue:blue axes) The MEG device coordinate frame is defined by the respective MEG manufacturers. All MEG data is acquired with respect to this coordinate frame. To account for the anatomy and position of the subject's head, we use so-called head position indicator (HPI) coils. The HPI coils are placed at known locations on the scalp of the subject and emit high-frequency magnetic fields used to coregister the head coordinate frame with the device coordinate frame. From the Neuromag/Elekta/MEGIN user manual: The origin of the device coordinate system is located at the center of the posterior spherical section of the helmet with X axis going from left to right and Y axis pointing front. The Z axis is, again normal to the plane with positive direction up. .. note:: The HPI coils are shown as :magenta:magenta spheres. Coregistration happens at the beginning of the recording and the head↔meg transformation matrix is stored in raw.info['dev_head_t']. MRI coordinate frame ("mri", :gray:gray axes) Defined by Freesurfer, the "MRI surface RAS" coordinate frame has its origin at the center of a 256×256×256 1mm anisotropic volume (though the center may not correspond to the anatomical center of the subject's head). .. note:: We typically align the MRI coordinate frame to the head coordinate frame through a rotation and translation matrix &lt;wiki_xform_&gt;_, that we refer to in MNE as trans. A bad example Let's try using ~mne.viz.plot_alignment with trans=None, which (incorrectly!) equates the MRI and head coordinate frames. End of explanation mne.viz.plot_alignment(raw.info, trans=trans, subject='sample', src=src, subjects_dir=subjects_dir, dig=True, surfaces=['head-dense', 'white'], coord_frame='meg') Explanation: A good example Here is the same plot, this time with the trans properly defined (using a precomputed transformation matrix). End of explanation # The head surface is stored in "mri" coordinate frame # (origin at center of volume, units=mm) seghead_rr, seghead_tri = mne.read_surface( op.join(subjects_dir, 'sample', 'surf', 'lh.seghead')) # To put the scalp in the "head" coordinate frame, we apply the inverse of # the precomputed `trans` (which maps head → mri) mri_to_head = linalg.inv(trans['trans']) scalp_pts_in_head_coord = mne.transforms.apply_trans( mri_to_head, seghead_rr, move=True) # To put the scalp in the "meg" coordinate frame, we use the inverse of # raw.info['dev_head_t'] head_to_meg = linalg.inv(raw.info['dev_head_t']['trans']) scalp_pts_in_meg_coord = mne.transforms.apply_trans( head_to_meg, scalp_pts_in_head_coord, move=True) # The "mri_voxel"→"mri" transform is embedded in the header of the T1 image # file. We'll invert it and then apply it to the original `seghead_rr` points. # No unit conversion necessary: this transform expects mm and the scalp surface # is defined in mm. vox_to_mri = t1_mgh.header.get_vox2ras_tkr() mri_to_vox = linalg.inv(vox_to_mri) scalp_points_in_vox = mne.transforms.apply_trans( mri_to_vox, seghead_rr, move=True) Explanation: Visualizing the transformations Let's visualize these coordinate frames using just the scalp surface; this will make it easier to see their relative orientations. To do this we'll first load the Freesurfer scalp surface, then apply a few different transforms to it. In addition to the three coordinate frames discussed above, we'll also show the "mri_voxel" coordinate frame. Unlike MRI Surface RAS, "mri_voxel" has its origin in the corner of the volume (the left-most, posterior-most coordinate on the inferior-most MRI slice) instead of at the center of the volume. "mri_voxel" is also not an RAS coordinate system: rather, its XYZ directions are based on the acquisition order of the T1 image slices. End of explanation def add_head(renderer, points, color, opacity=0.95): renderer.mesh(*points.T, triangles=seghead_tri, color=color, opacity=opacity) renderer = mne.viz.backends.renderer.create_3d_figure( size=(600, 600), bgcolor='w', scene=False) add_head(renderer, seghead_rr, 'gray') add_head(renderer, scalp_pts_in_meg_coord, 'blue') add_head(renderer, scalp_pts_in_head_coord, 'pink') add_head(renderer, scalp_points_in_vox, 'green') mne.viz.set_3d_view(figure=renderer.figure, distance=800, focalpoint=(0., 30., 30.), elevation=105, azimuth=180) renderer.show() Explanation: Now that we've transformed all the points, let's plot them. We'll use the same colors used by ~mne.viz.plot_alignment and use :green:green for the "mri_voxel" coordinate frame: End of explanation # Get the nasion: nasion = [p for p in raw.info['dig'] if p['kind'] == FIFF.FIFFV_POINT_CARDINAL and p['ident'] == FIFF.FIFFV_POINT_NASION][0] assert nasion['coord_frame'] == FIFF.FIFFV_COORD_HEAD nasion = nasion['r'] # get just the XYZ values # Transform it from head to MRI space (recall that `trans` is head → mri) nasion_mri = mne.transforms.apply_trans(trans, nasion, move=True) # Then transform to voxel space, after converting from meters to millimeters nasion_vox = mne.transforms.apply_trans( mri_to_vox, nasion_mri * 1e3, move=True) # Plot it to make sure the transforms worked renderer = mne.viz.backends.renderer.create_3d_figure( size=(400, 400), bgcolor='w', scene=False) add_head(renderer, scalp_points_in_vox, 'green', opacity=1) renderer.sphere(center=nasion_vox, color='orange', scale=10) mne.viz.set_3d_view(figure=renderer.figure, distance=600., focalpoint=(0., 125., 250.), elevation=45, azimuth=180) renderer.show() Explanation: The relative orientations of the coordinate frames can be inferred by observing the direction of the subject's nose. Notice also how the origin of the :green:mri_voxel coordinate frame is in the corner of the volume (above, behind, and to the left of the subject), whereas the other three coordinate frames have their origin roughly in the center of the head. Example: MRI defacing For a real-world example of using these transforms, consider the task of defacing the MRI to preserve subject anonymity. If you know the points in the "head" coordinate frame (as you might if you're basing the defacing on digitized points) you would need to transform them into "mri" or "mri_voxel" in order to apply the blurring or smoothing operations to the MRI surfaces or images. Here's what that would look like (we'll use the nasion landmark as a representative example): End of explanation # mne.gui.coregistration(subject='sample', subjects_dir=subjects_dir) Explanation: Defining the head↔MRI trans using the GUI You can try creating the head↔MRI transform yourself using :func:mne.gui.coregistration. First you must load the digitization data from the raw file (Head Shape Source). The MRI data is already loaded if you provide the subject and subjects_dir. Toggle Always Show Head Points to see the digitization points. To set the landmarks, toggle Edit radio button in MRI Fiducials. Set the landmarks by clicking the radio button (LPA, Nasion, RPA) and then clicking the corresponding point in the image. After doing this for all the landmarks, toggle Lock radio button. You can omit outlier points, so that they don't interfere with the finetuning. .. note:: You can save the fiducials to a file and pass mri_fiducials=True to plot them in :func:mne.viz.plot_alignment. The fiducials are saved to the subject's bem folder by default. * Click Fit Head Shape. This will align the digitization points to the head surface. Sometimes the fitting algorithm doesn't find the correct alignment immediately. You can try first fitting using LPA/RPA or fiducials and then align according to the digitization. You can also finetune manually with the controls on the right side of the panel. * Click Save As... (lower right corner of the panel), set the filename and read it with :func:mne.read_trans. For more information, see step by step instructions in these slides &lt;https://www.slideshare.net/mne-python/mnepython-coregistration&gt;_. Uncomment the following line to align the data yourself. End of explanation sphere = mne.make_sphere_model(info=raw.info, r0='auto', head_radius='auto') src = mne.setup_volume_source_space(sphere=sphere, pos=10.) mne.viz.plot_alignment( raw.info, eeg='projected', bem=sphere, src=src, dig=True, surfaces=['brain', 'inner_skull', 'outer_skull', 'outer_skin'], coord_frame='meg', show_axes=True) Explanation: Alignment without MRI The surface alignments above are possible if you have the surfaces available from Freesurfer. :func:mne.viz.plot_alignment automatically searches for the correct surfaces from the provided subjects_dir. Another option is to use a spherical conductor model &lt;eeg_sphere_model&gt;. It is passed through bem parameter. End of explanation
5,334
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this Step2: Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels. Step3: What does these values look like? Let's print a training image, and a training label to see...Experiment with different indices in the array. For example, also take a look at index 42...that's a a different boot than the one at index 0 Step4: You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if we treat all values as between 0 and 1, a process called 'normalizing'...and fortunately in Python it's easy to normalize a list like this without looping. You do it like this Step5: Now you might be wondering why there are 2 sets...training and testing -- remember we spoke about this in the intro? The idea is to have 1 set of data for training, and then another set of data...that the model hasn't yet seen...to see how good it would be at classifying values. After all, when you're done, you're going to want to try it out with data that it hadn't previously seen! Let's now design the model. There's quite a few new concepts here, but don't worry, you'll get the hang of them. Step6: Sequential Step7: Once it's done training -- you should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells you that your neural network is about 91% accurate in classifying the training data. I.E., it figured out a pattern match between the image and the labels that worked 91% of the time. Not great, but not bad considering it was only trained for 5 epochs and done quite quickly. But how would it work with unseen data? That's why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back the loss for each. Let's give it a try Step8: For me, that returned a accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with unseen data as it did with data it was trained on! As you go through this course, you'll look at ways to improve this. To explore further, try the below exercises Step9: Hint Step10: What does this list represent? It's 10 random meaningless values It's the first 10 classifications that the computer made It's the probability that this item is each of the 10 classes Answer Step11: Question 1. Increase to 1024 Neurons -- What's the impact? Training takes longer, but is more accurate Training takes longer, but no impact on accuracy Training takes the same time, but is more accurate Answer The correct answer is (1) by adding more Neurons we have to do more calculations, slowing down the process, but in this case they have a good impact -- we do get more accurate. That doesn't mean it's always a case of 'more is better', you can hit the law of diminishing returns very quickly! Exercise 3 Step12: Exercise 4 Step13: Exercise 5 Step14: Exercise 6 Step15: Exercise 7 Step16: Exercise 8
Python Code: import tensorflow as tf print(tf.__version__) Explanation: <a href="https://colab.research.google.com/github/leopardbruce/FileFun/blob/master/%E2%80%9CCourse_1_Part_4_Lesson_2_Notebook_ipynb%E2%80%9D.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Beyond Hello World, A Computer Vision Example In the previous exercise you saw how to create a neural network that figured out the problem you were trying to solve. This gave an explicit example of learned behavior. Of course, in that instance, it was a bit of overkill because it would have been easier to write the function Y=2x-1 directly, instead of bothering with using Machine Learning to learn the relationship between X and Y for a fixed set of values, and extending that for all values. But what about a scenario where writing rules like that is much more difficult -- for example a computer vision problem? Let's take a look at a scenario where we can recognize different items of clothing, trained from a dataset containing 10 different types. Start Coding Let's start with our import of TensorFlow End of explanation mnist = tf.keras.datasets.fashion_mnist Explanation: The Fashion MNIST data is available directly in the tf.keras datasets API. You load it like this: End of explanation (training_images, training_labels), (test_images, test_labels) = mnist.load_data() Explanation: Calling load_data on this object will give you two sets of two lists, these will be the training and testing values for the graphics that contain the clothing items and their labels. End of explanation import matplotlib.pyplot as plt plt.imshow(training_images[0]) print(training_labels[0]) print(training_images[0]) Explanation: What does these values look like? Let's print a training image, and a training label to see...Experiment with different indices in the array. For example, also take a look at index 42...that's a a different boot than the one at index 0 End of explanation training_images = training_images / 255.0 test_images = test_images / 255.0 Explanation: You'll notice that all of the values in the number are between 0 and 255. If we are training a neural network, for various reasons it's easier if we treat all values as between 0 and 1, a process called 'normalizing'...and fortunately in Python it's easy to normalize a list like this without looping. You do it like this: End of explanation model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) Explanation: Now you might be wondering why there are 2 sets...training and testing -- remember we spoke about this in the intro? The idea is to have 1 set of data for training, and then another set of data...that the model hasn't yet seen...to see how good it would be at classifying values. After all, when you're done, you're going to want to try it out with data that it hadn't previously seen! Let's now design the model. There's quite a few new concepts here, but don't worry, you'll get the hang of them. End of explanation model.compile(optimizer = tf.train.AdamOptimizer(), loss = 'sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(training_images, training_labels, epochs=5) Explanation: Sequential: That defines a SEQUENCE of layers in the neural network Flatten: Remember earlier where our images were a square, when you printed them out? Flatten just takes that square and turns it into a 1 dimensional set. Dense: Adds a layer of neurons Each layer of neurons need an activation function to tell them what to do. There's lots of options, but just use these for now. Relu effectively means "If X>0 return X, else return 0" -- so what it does it it only passes values 0 or greater to the next layer in the network. Softmax takes a set of values, and effectively picks the biggest one, so, for example, if the output of the last layer looks like [0.1, 0.1, 0.05, 0.1, 9.5, 0.1, 0.05, 0.05, 0.05], it saves you from fishing through it looking for the biggest value, and turns it into [0,0,0,0,1,0,0,0,0] -- The goal is to save a lot of coding! The next thing to do, now the model is defined, is to actually build it. You do this by compiling it with an optimizer and loss function as before -- and then you train it by calling model.fit asking it to fit your training data to your training labels -- i.e. have it figure out the relationship between the training data and its actual labels, so in future if you have data that looks like the training data, then it can make a prediction for what that data would look like. End of explanation model.evaluate(test_images, test_labels) Explanation: Once it's done training -- you should see an accuracy value at the end of the final epoch. It might look something like 0.9098. This tells you that your neural network is about 91% accurate in classifying the training data. I.E., it figured out a pattern match between the image and the labels that worked 91% of the time. Not great, but not bad considering it was only trained for 5 epochs and done quite quickly. But how would it work with unseen data? That's why we have the test images. We can call model.evaluate, and pass in the two sets, and it will report back the loss for each. Let's give it a try: End of explanation classifications = model.predict(test_images) print(classifications[0]) Explanation: For me, that returned a accuracy of about .8838, which means it was about 88% accurate. As expected it probably would not do as well with unseen data as it did with data it was trained on! As you go through this course, you'll look at ways to improve this. To explore further, try the below exercises: Exploration Exercises Exercise 1: For this first exercise run the below code: It creates a set of classifications for each of the test images, and then prints the first entry in the classifications. The output, after you run it is a list of numbers. Why do you think this is, and what do those numbers represent? End of explanation print(test_labels[0]) Explanation: Hint: try running print(test_labels[0]) -- and you'll get a 9. Does that help you understand why this list looks the way it does? End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels) , (test_images, test_labels) = mnist.load_data() training_images = training_images/255.0 test_images = test_images/255.0 model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(1024, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Explanation: What does this list represent? It's 10 random meaningless values It's the first 10 classifications that the computer made It's the probability that this item is each of the 10 classes Answer: The correct answer is (3) The output of the model is a list of 10 numbers. These numbers are a probability that the value being classified is the corresponding value, i.e. the first value in the list is the probability that the handwriting is of a '0', the next is a '1' etc. Notice that they are all VERY LOW probabilities. For the 7, the probability was .999+, i.e. the neural network is telling us that it's almost certainly a 7. How do you know that this list tells you that the item is an ankle boot? There's not enough information to answer that question The 10th element on the list is the biggest, and the ankle boot is labelled 9 The ankle boot is label 9, and there are 0->9 elements in the list Answer The correct answer is (2). Both the list and the labels are 0 based, so the ankle boot having label 9 means that it is the 10th of the 10 classes. The list having the 10th element being the highest value means that the Neural Network has predicted that the item it is classifying is most likely an ankle boot Exercise 2: Let's now look at the layers in your model. Experiment with different values for the dense layer with 512 neurons. What different results do you get for loss, training time etc? Why do you think that's the case? End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels) , (test_images, test_labels) = mnist.load_data() training_images = training_images/255.0 test_images = test_images/255.0 model = tf.keras.models.Sequential([#tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Explanation: Question 1. Increase to 1024 Neurons -- What's the impact? Training takes longer, but is more accurate Training takes longer, but no impact on accuracy Training takes the same time, but is more accurate Answer The correct answer is (1) by adding more Neurons we have to do more calculations, slowing down the process, but in this case they have a good impact -- we do get more accurate. That doesn't mean it's always a case of 'more is better', you can hit the law of diminishing returns very quickly! Exercise 3: What would happen if you remove the Flatten() layer. Why do you think that's the case? You get an error about the shape of the data. It may seem vague right now, but it reinforces the rule of thumb that the first layer in your network should be the same shape as your data. Right now our data is 28x28 images, and 28 layers of 28 neurons would be infeasible, so it makes more sense to 'flatten' that 28,28 into a 784x1. Instead of wriitng all the code to handle that ourselves, we add the Flatten() layer at the begining, and when the arrays are loaded into the model later, they'll automatically be flattened for us. End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels) , (test_images, test_labels) = mnist.load_data() training_images = training_images/255.0 test_images = test_images/255.0 model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dense(5, activation=tf.nn.softmax)]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Explanation: Exercise 4: Consider the final (output) layers. Why are there 10 of them? What would happen if you had a different amount than 10? For example, try training the network with 5 You get an error as soon as it finds an unexpected value. Another rule of thumb -- the number of neurons in the last layer should match the number of classes you are classifying for. In this case it's the digits 0-9, so there are 10 of them, hence you should have 10 neurons in your final layer. End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels) , (test_images, test_labels) = mnist.load_data() training_images = training_images/255.0 test_images = test_images/255.0 model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dense(256, activation=tf.nn.relu), tf.keras.layers.Dense(5, activation=tf.nn.softmax)]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Explanation: Exercise 5: Consider the effects of additional layers in the network. What will happen if you add another layer between the one with 512 and the final layer with 10. Ans: There isn't a significant impact -- because this is relatively simple data. For far more complex data (including color images to be classified as flowers that you'll see in the next lesson), extra layers are often necessary. End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels) , (test_images, test_labels) = mnist.load_data() training_images = training_images/255.0 test_images = test_images/255.0 model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(5, activation=tf.nn.softmax)]) model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=30) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[34]) print(test_labels[34]) Explanation: Exercise 6: Consider the impact of training for more or less epochs. Why do you think that would be the case? Try 15 epochs -- you'll probably get a model with a much better loss than the one with 5 Try 30 epochs -- you might see the loss value stops decreasing, and sometimes increases. This is a side effect of something called 'overfitting' which you can learn about [somewhere] and it's something you need to keep an eye out for when training neural networks. There's no point in wasting your time training if you aren't improving your loss, right! :) End of explanation import tensorflow as tf print(tf.__version__) mnist = tf.keras.datasets.mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() training_images=training_images/255.0 test_images=test_images/255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) classifications = model.predict(test_images) print(classifications[0]) print(test_labels[0]) Explanation: Exercise 7: Before you trained, you normalized the data, going from values that were 0-255 to values that were 0-1. What would be the impact of removing that? Here's the complete code to give it a try. Why do you think you get different results? End of explanation import tensorflow as tf print(tf.__version__) class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('loss')<0.4): print("\nReached 60% accuracy so cancelling training!") self.model.stop_training = True callbacks = myCallback() mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() training_images=training_images/255.0 test_images=test_images/255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks]) Explanation: Exercise 8: Earlier when you trained for extra epochs you had an issue where your loss might change. It might have taken a bit of time for you to wait for the training to do that, and you might have thought 'wouldn't it be nice if I could stop the training when I reach a desired value?' -- i.e. 95% accuracy might be enough for you, and if you reach that after 3 epochs, why sit around waiting for it to finish a lot more epochs....So how would you fix that? Like any other program...you have callbacks! Let's see them in action... End of explanation
5,335
Given the following text description, write Python code to implement the functionality described below step by step Description: Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates will be used to determine the adjacency between sensors. This serves as a spatial prior to the clustering. Significant spatiotemporal clusters will then be visualized using custom matplotlib code. Step1: Set parameters Step2: Read epochs for the channel of interest Step3: Load FieldTrip neighbor definition to setup sensor connectivity Step4: Compute permutation statistic How does it work? We use clustering to bind together features which are similar. Our features are the magnetic fields measured over our sensor array at different times. This reduces the multiple comparison problem. To compute the actual test-statistic, we first sum all F-values in all clusters. We end up with one statistic for each cluster. Then we generate a distribution from the data by shuffling our conditions between our samples and recomputing our clusters and the test statistics. We test for the significance of a given cluster by computing the probability of observing a cluster of that size. For more background read Step5: Note. The same functions work with source estimate. The only differences are the origin of the data, the size, and the connectivity definition. It can be used for single trials or for groups of subjects. Visualize clusters
Python Code: # Authors: Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from mne.viz import plot_topomap import mne from mne.stats import spatio_temporal_cluster_test from mne.datasets import sample from mne.channels import read_ch_connectivity print(__doc__) Explanation: Spatiotemporal permutation F-test on full sensor data Tests for differential evoked responses in at least one condition using a permutation clustering test. The FieldTrip neighbor templates will be used to determine the adjacency between sensors. This serves as a spatial prior to the clustering. Significant spatiotemporal clusters will then be visualized using custom matplotlib code. End of explanation data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' event_id = {'Aud_L': 1, 'Aud_R': 2, 'Vis_L': 3, 'Vis_R': 4} tmin = -0.2 tmax = 0.5 # Setup for reading the raw data raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.filter(1, 30, l_trans_bandwidth='auto', h_trans_bandwidth='auto', filter_length='auto', phase='zero') events = mne.read_events(event_fname) Explanation: Set parameters End of explanation picks = mne.pick_types(raw.info, meg='mag', eog=True) reject = dict(mag=4e-12, eog=150e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=None, reject=reject, preload=True) epochs.drop_channels(['EOG 061']) epochs.equalize_event_counts(event_id) condition_names = 'Aud_L', 'Aud_R', 'Vis_L', 'Vis_R' X = [epochs[k].get_data() for k in condition_names] # as 3D matrix X = [np.transpose(x, (0, 2, 1)) for x in X] # transpose for clustering Explanation: Read epochs for the channel of interest End of explanation connectivity, ch_names = read_ch_connectivity('neuromag306mag') print(type(connectivity)) # it's a sparse matrix! plt.imshow(connectivity.toarray(), cmap='gray', origin='lower', interpolation='nearest') plt.xlabel('{} Magnetometers'.format(len(ch_names))) plt.ylabel('{} Magnetometers'.format(len(ch_names))) plt.title('Between-sensor adjacency') Explanation: Load FieldTrip neighbor definition to setup sensor connectivity End of explanation # set cluster threshold threshold = 50.0 # very high, but the test is quite sensitive on this data # set family-wise p-value p_accept = 0.001 cluster_stats = spatio_temporal_cluster_test(X, n_permutations=1000, threshold=threshold, tail=1, n_jobs=1, connectivity=connectivity) T_obs, clusters, p_values, _ = cluster_stats good_cluster_inds = np.where(p_values < p_accept)[0] Explanation: Compute permutation statistic How does it work? We use clustering to bind together features which are similar. Our features are the magnetic fields measured over our sensor array at different times. This reduces the multiple comparison problem. To compute the actual test-statistic, we first sum all F-values in all clusters. We end up with one statistic for each cluster. Then we generate a distribution from the data by shuffling our conditions between our samples and recomputing our clusters and the test statistics. We test for the significance of a given cluster by computing the probability of observing a cluster of that size. For more background read: Maris/Oostenveld (2007), "Nonparametric statistical testing of EEG- and MEG-data" Journal of Neuroscience Methods, Vol. 164, No. 1., pp. 177-190. doi:10.1016/j.jneumeth.2007.03.024 End of explanation # configure variables for visualization times = epochs.times * 1e3 colors = 'r', 'r', 'steelblue', 'steelblue' linestyles = '-', '--', '-', '--' # grand average as numpy arrray grand_ave = np.array(X).mean(axis=1) # get sensor positions via layout pos = mne.find_layout(epochs.info).pos # loop over significant clusters for i_clu, clu_idx in enumerate(good_cluster_inds): # unpack cluster information, get unique indices time_inds, space_inds = np.squeeze(clusters[clu_idx]) ch_inds = np.unique(space_inds) time_inds = np.unique(time_inds) # get topography for F stat f_map = T_obs[time_inds, ...].mean(axis=0) # get signals at significant sensors signals = grand_ave[..., ch_inds].mean(axis=-1) sig_times = times[time_inds] # create spatial mask mask = np.zeros((f_map.shape[0], 1), dtype=bool) mask[ch_inds, :] = True # initialize figure fig, ax_topo = plt.subplots(1, 1, figsize=(10, 3)) title = 'Cluster #{0}'.format(i_clu + 1) fig.suptitle(title, fontsize=14) # plot average test statistic and mark significant sensors image, _ = plot_topomap(f_map, pos, mask=mask, axes=ax_topo, cmap='Reds', vmin=np.min, vmax=np.max) # advanced matplotlib for showing image with figure and colorbar # in one plot divider = make_axes_locatable(ax_topo) # add axes for colorbar ax_colorbar = divider.append_axes('right', size='5%', pad=0.05) plt.colorbar(image, cax=ax_colorbar) ax_topo.set_xlabel('Averaged F-map ({:0.1f} - {:0.1f} ms)'.format( *sig_times[[0, -1]] )) # add new axis for time courses and plot time courses ax_signals = divider.append_axes('right', size='300%', pad=1.2) for signal, name, col, ls in zip(signals, condition_names, colors, linestyles): ax_signals.plot(times, signal, color=col, linestyle=ls, label=name) # add information ax_signals.axvline(0, color='k', linestyle=':', label='stimulus onset') ax_signals.set_xlim([times[0], times[-1]]) ax_signals.set_xlabel('time [ms]') ax_signals.set_ylabel('evoked magnetic fields [fT]') # plot significant time range ymin, ymax = ax_signals.get_ylim() ax_signals.fill_betweenx((ymin, ymax), sig_times[0], sig_times[-1], color='orange', alpha=0.3) ax_signals.legend(loc='lower right') ax_signals.set_ylim(ymin, ymax) # clean up viz mne.viz.tight_layout(fig=fig) fig.subplots_adjust(bottom=.05) plt.show() Explanation: Note. The same functions work with source estimate. The only differences are the origin of the data, the size, and the connectivity definition. It can be used for single trials or for groups of subjects. Visualize clusters End of explanation
5,336
Given the following text description, write Python code to implement the functionality described. Description: Arrangement of the characters of a word such that all vowels are at odd places Python3 program to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Function to return the factorial of a number ; calculating nPr ; Function to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Get total even positions ; Get total odd positions ; Store frequency of each character of the string ; Count total number of vowels ; Count total number of consonants ; Calculate the total number of ways ; Driver code
Python Code: import math def fact(n ) : f = 1 ; for i in range(2 , n + 1 ) : f = f * i ;  return f ;  def npr(n , r ) : return fact(n ) / fact(n - r ) ;  def countPermutations(str ) : even = math . floor(len(str ) / 2 ) ; odd = len(str ) - even ; ways = 0 ; freq =[0 ] * 26 ; for i in range(len(str ) ) : freq[ord(str[i ] ) - ord(' a ' ) ] += 1 ;  nvowels =(freq[0 ] + freq[4 ] + freq[8 ] + freq[14 ] + freq[20 ] ) ; nconsonants = len(str ) - nvowels ; ways =(npr(odd , nvowels ) * npr(nconsonants , nconsonants ) ) ; return int(ways ) ;  str = "geeks "; print(countPermutations(str ) ) ;
5,337
Given the following text description, write Python code to implement the functionality described below step by step Description: With this post I explore an alternative to ol' numpy; xarray. Numpy is still running under the hood but this very handy library applies the pandas concept of labeled dimension to large N-dimension arrays prevalent in scientific computing. The result is an ease of manipulation of dimensions without having to guess or remember what they correspond to. Moreover, xarray plays nicely with two other relatively new libraries Step1: Set up the paths for loading and saving... Step2: ..., which I now used to access the nc data Step3: Now let's peak inside the dataset we've just loaded Step4: Here Rrs refers to Remote sensing reflectance (units of per steradian or $sr^{-1}$). The number at the end of the label string refers to the corresponding wavelength, in nanometers. I don't need "palette". I am interested in the uncertainty data, however. These are 64 bits float with lat lon dimensions. Let's make sure these arrays are inter-comparable. Step5: So there are multiple arrays, one for each of 6 bands. Now I want to reorganize the data into a single array with a third dimension; band. This is as easy as 1, 2, 3... lines of code Step6: Now I can close the netcdf dataset handle. Note that the _enter_() and _exit_() methods being implemented, sticking the code above inside a "with" context would be the proper way to go about this; it'll also be how I'll do things next time. Step7: So what is rrs?... Step8: ... and what are the dimensions of rrs data ?... Step9: ... and for indexing purposes, what type are they? Step10: Basic data manipulation and plotting Accessing the data along a given dimension... Step11: ... and quickly plotting it via its matplotlib interface is pretty straightforward Step12: Storing rrs is a xarray DataArray type. To write the data it contains to netcdf format I first need to convert it to an xarray DataSet type, which then gives me the facility to export it to netcdf.
Python Code: import xarray as xr import os import seaborn from matplotlib import rcParams import matplotlib.pyplot as pl %matplotlib inline rcParams['font.size']=16 rcParams['xtick.labelsize']=14 rcParams['ytick.labelsize']=14 rcParams['legend.fontsize']=14 rcParams['axes.formatter.limits'] = (-3,3) Explanation: With this post I explore an alternative to ol' numpy; xarray. Numpy is still running under the hood but this very handy library applies the pandas concept of labeled dimension to large N-dimension arrays prevalent in scientific computing. The result is an ease of manipulation of dimensions without having to guess or remember what they correspond to. Moreover, xarray plays nicely with two other relatively new libraries: * dask, which enables out of core computation so that memory availability becomes much less an issue with large data sets; * GeoViews, a library sitting on top of HoloViews. The latter eases the burden of data visualization by offering an unusual approach that does away with step-by-step graphical coding and allows the user to concentrate how the data organization instead. This results in a substantial reduction code written, which makes data analysis much cleaner and less bug-prone. GeoViews sits on top of the visualization package HoloViews, with an emphasis on geophysical data. It's also my first good-bye to the aging (10+ years) matplotlib library. It'll still be handy now and then, but it's time to try new things. <!-- TEASER_END --> End of explanation dataDir = '/accounts/ekarakoy/disk02/UNCERTAINTIES/Monte-Carlo/DATA/AncillaryMC/' expDir = 'Lt' fname = 'S20031932003196.L3m_4D_SU50.nc' fpath = os.path.join(dataDir,expDir,fname) foutpath = os.path.join(dataDir,expDir,fname.split('.nc')[0] + '_xarray.nc') Explanation: Set up the paths for loading and saving... End of explanation ds = xr.open_dataset(fpath) Explanation: ..., which I now used to access the nc data: End of explanation ds.data_vars.keys() Explanation: Now let's peak inside the dataset we've just loaded: End of explanation bands = ['412','443','490','510','555','670'] for band in bands: var = ds.data_vars['Rrs_unc_%s' % band] print(var) print("=" * 80) Explanation: Here Rrs refers to Remote sensing reflectance (units of per steradian or $sr^{-1}$). The number at the end of the label string refers to the corresponding wavelength, in nanometers. I don't need "palette". I am interested in the uncertainty data, however. These are 64 bits float with lat lon dimensions. Let's make sure these arrays are inter-comparable. End of explanation rrsUnc = xr.concat((ds.data_vars['Rrs_unc_%s' % band] for band in bands), dim='bands') rrsUnc.coords['bands'] = ['412', '443', '490', '510', '555', '670'] rrsUnc.name = 'rrs_uncertainty' Explanation: So there are multiple arrays, one for each of 6 bands. Now I want to reorganize the data into a single array with a third dimension; band. This is as easy as 1, 2, 3... lines of code End of explanation ds.close() Explanation: Now I can close the netcdf dataset handle. Note that the _enter_() and _exit_() methods being implemented, sticking the code above inside a "with" context would be the proper way to go about this; it'll also be how I'll do things next time. End of explanation type(rrsUnc) Explanation: So what is rrs?... End of explanation print(rrsUnc.dims) Explanation: ... and what are the dimensions of rrs data ?... End of explanation print(rrsUnc.coords) Explanation: ... and for indexing purposes, what type are they? End of explanation rrsUnc412 = rrsUnc.sel(bands=['412']) rrsUncGreen = rrsUnc.sel(bands=['510','555']) Explanation: Basic data manipulation and plotting Accessing the data along a given dimension... End of explanation pl.figure(figsize=(12,7)) rrsUnc412.plot.hist(bins=50, range=(0,5e-4), histtype='stepfilled', label='uncertainty at 412nm', normed=True); rrsUncGreen.plot.hist(bins=50, range=(0,5e-4),histtype='stepfilled', alpha=0.3, label='uncertainty at all greenish bands: 510 & 555', normed=True) pl.legend(); pl.title('Histogram of Rrs Uncertainty',fontsize=18); pl.ylabel('freq', fontsize=16) pl.xlabel(r'$sr^{-1}$', fontsize=16 ); Explanation: ... and quickly plotting it via its matplotlib interface is pretty straightforward: End of explanation dsUncNew = rrsUnc.to_dataset() type(dsUncNew) dsUncNew.to_netcdf(path=foutpath, engine='netcdf4') Explanation: Storing rrs is a xarray DataArray type. To write the data it contains to netcdf format I first need to convert it to an xarray DataSet type, which then gives me the facility to export it to netcdf. End of explanation
5,338
Given the following text description, write Python code to implement the functionality described below step by step Description: ABU量化系统使用文档 <center> <img src="./image/abu_logo.png" alt="" style="vertical-align Step1: 算法交易之父托马斯•彼得菲最成功的一段经历是利用当时最快的计算机,租赁独享电话线以保证数据传输畅通无阻,甚至超越时代定制平叛电脑,使用统计套利在不同市场进行对冲策略。 这是最有保证的一段量化交易历史,在当时的交易环境下运用高科技在市场中确实可以获利。 但是这个策略放到今天肯定不适用,因为科技在不停的进步,技术的不断透明化,信息社会的高速发展,自动化交易占了美国股票市场60%以上的成交量。在美国很多高频交易为了通信速度能有几毫秒的提升,不惜在太平洋底打洞自己搭建通信网络,也有专门提供暗光纤的独享网络商,他们网络的一年租赁费用就高达几千万美元。在这种环境下,个人量化投资者是不是一点机会都没有呢? 1. 伦敦期货市场和国内期货市场中的金属期货 本节示例适合个人量化交易者的低频统计套利策略,目标市场为伦敦期货市场和国内期货市场中的金属期货。 如下先获取伦敦的金属期货symbol数据: Step2: 接下来获取国内的金属期货symbol数据: Step3: 如下分别将两两金属期货进行跨市场配对,首先可视化一下走势,可以看到每一个配对期货市场的走势都非常跟随: Step4: 如果做跨市场高频交易,需要非常好的设备,盯着盘口的数据,快速进行交易决策,且对资金量也有要求,本节的示例为适合个人量化交易者的跨市场低频统计套利示例。 注意观察上面的每一对趋势曲线,如CAD vs CU0,你可以发现CU0对趋势敏感的速度要明显快于CAD, 而且是非高频的快,即上面的蓝线在趋势下跌时先下跌,趋势上涨时先上涨,那么就可以认为CAD在非高频下跟随CU0,具有低频统计套利机会。 2. 趋势变化的敏感速度 我们不可能真的用肉眼去一个一个观察,而且也无法量化具体趋势敏感的速度,也即无法确定是否真实存在低频统计套利机会。 对于量化交易,优势是通过计算机强大的运算能力,在市场广度的优势下获取概率优势,进行交易,下面示例如何使用abupy中的api计算趋势变化的敏感速度,如下所示: 备注 Step5: 上面的计算结果0.57为CU0对趋势变化敏感速度,0.52为CAD对趋势变化敏感速度,即CU0的对趋势变化的敏感度大于CAD,且大于0.03具备低频统计套利的条件。(大于0.05认为具有安全低频统计套利机会,具体这些阀值将在之后的章节讲解) 在低频统计套利的情况下将会使用CAD做为交易目标,CU0做为趋势风标,因为它的敏感度高,下面初始化一个字典,key为将会使用做为交易目标的CAD,value为做为趋势风标CU0,如下所示: Step6: 下面计算沪铝(AL0)和伦敦铝(AHD)对趋势变化的敏感速度,如下: Step7: 上面的计算结果0.61为沪铝(AL0)对趋势变化敏感速度,0.57为伦敦铝(AHD)对趋势变化敏感速度,即AL0对趋势变化的敏感度大于AHD,且大于0.03具备低频统计套利的条件。 字典中key为将会使用做为交易目标的低敏感AHD,value为做为趋势风标的高敏感AL0,如下所示: Step8: 下面计算国内黄金(AU0)和伦敦黄金(XAU)对趋势变化的敏感速度,如下: Step9: 上面的计算结果0.58为国内黄金(AU0)对趋势变化敏感速度,0.61为伦敦黄金(XAU)对趋势变化敏感速度,即外盘敏感速度快于国内期货趋势变化敏感速度,之前的两个都为国内期货趋势变化敏感速度快于外盘敏感速度。 字典中key为将会使用做为交易目标的低敏感国内黄金(AU0),value为做为趋势风标的高敏感伦敦黄金(XAU),如下所示: Step10: 下面计算国内白银(AG0)和伦敦白银(XAG)对趋势变化的敏感速度,如下: Step11: 上面的计算结果0.55为国内白银(AG0)对趋势变化敏感速度,0.60为伦敦白银(XAG)对趋势变化敏感速度,即白银的外盘敏感速度也快于国内期货趋势变化敏感速度。 字典中key为将会使用做为交易目标的低敏感国内白银(AG0),value为做为趋势风标的高敏感伦敦白银(XAG),如下所示: Step12: 下面计算沪锌(ZN0)和伦敦锌(SND)对趋势变化的敏感速度,如下: Step13: 字典中key为将会使用做为交易目标的低敏感伦敦锌(SND),value为做为趋势风标的高敏感沪锌(ZN0),如下所示: Step14: 下面计算沪铅(PB0)和伦敦铅(PBD)对趋势变化的敏感速度,如下: Step15: 上面的计算结果0.50为沪铅(PB0)对趋势变化敏感速度,0.59为伦敦铅(PBD)对趋势变化敏感速度,差值达到0.09远大于0.03,是非常好的低频统计套利配对。 字典中key为将会使用做为交易目标的低敏感沪铅(PB0),value为做为趋势风标的高敏感伦敦铅(PBD),如下所示: Step16: 上面即选定了跨市场低频统计套利的交易配对字典,key为为交易目标的低敏感,value为做为趋势风标的高敏感,如下: Step18: 3. 基于跨市场低频统计套利的突破策略 下面编写择时交易策略实现这个跨市场低频统计套利的交易配对,如下所示: Step19: 策略编写如上AbuFactorBuyPairBreak所示和之前章节一直使用的周期突破策略AbuFactorBuyBreak唯一不同的只有突破信号发出者为趋势风标的高敏感目标,一旦高敏感目标今天突破了,则买入的是低敏感的交易目标。 下面使用这个买入策略进行回测,卖出策略依然延用之前的策略,如下所示: Step20: 回测结果如上所示,对比未基于内外盘统计套利的普通突破策略回测可以看到回测效果提升很多,如下所示: Step21: 而且即使再次降低交易频度,不使用跨市场套利的时间优势,选择再隔一天买入交易目标,即下面的构造因子参数buy_today=False,可以看到回测的结果依然好于未基于内外盘统计套利的普通突破策略回测结果。 Step22: 4. 其它市场的配对低频统计套利 上述基于期货市场的配对统计套利基于一个条件:两个市场的期货产品相关度非常高,对于期货市场这个条件是天然成立的,但对于其它市场就需要从相关度进行验证,如下使用calc_pair_speed计算比特币和莱特币的趋势变化敏感速度: Step23: 上述第一个结果0.599是btc的趋势变化敏感速度,0.583是ltc的趋势敏感速度,第三个值0.78是btc和ltc的相关度值。 如下计算btc和ltc的速度差: Step24: 可以看到结果不具备配对低频统计套利的条件,实际上面示例期货产品中如ZN0,SND这样的配对也是不符合低频统计套利的条件的,如下:
Python Code: # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() from abupy import AbuFuturesCn, AbuFuturesGB, ABuMarketDrawing, ABuSymbolPd, ABuCorrcoef, tl from abupy import ECoreCorrType, EMarketDataSplitMode, AbuBenchmark, nd, ABuScalerUtil, ABuProgress from abupy import pd_resample, AbuFactorBuyXD, BuyCallMixin, EMarketTargetType, abu, AbuFactorBuyBreak from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuMetricsBase Explanation: ABU量化系统使用文档 <center> <img src="./image/abu_logo.png" alt="" style="vertical-align:middle;padding:10px 20px;"><font size="6" color="black"><b>第25节 期货市场内外盘低频统计套利</b></font> </center> 作者: 阿布 阿布量化版权所有 未经允许 禁止转载 abu量化系统github地址 (欢迎+star) 本节ipython notebook 上一节讲解根据比特币市场的特点编写的示例策略,本节将讲解量化交易中跨市场统计套利的示例。 首先导入本节需要使用的abupy中的模块: End of explanation gb = AbuFuturesGB() metal_gb = gb.futures_gb_df[ (gb.futures_gb_df['product'] == '伦敦铅') | (gb.futures_gb_df['product'] == '伦敦锌') | (gb.futures_gb_df['product'] == '伦敦铝') | (gb.futures_gb_df['product'] == '伦敦铜') | (gb.futures_gb_df['product'] == '伦敦金') | (gb.futures_gb_df['product'] == '伦敦银') ] metal_gb Explanation: 算法交易之父托马斯•彼得菲最成功的一段经历是利用当时最快的计算机,租赁独享电话线以保证数据传输畅通无阻,甚至超越时代定制平叛电脑,使用统计套利在不同市场进行对冲策略。 这是最有保证的一段量化交易历史,在当时的交易环境下运用高科技在市场中确实可以获利。 但是这个策略放到今天肯定不适用,因为科技在不停的进步,技术的不断透明化,信息社会的高速发展,自动化交易占了美国股票市场60%以上的成交量。在美国很多高频交易为了通信速度能有几毫秒的提升,不惜在太平洋底打洞自己搭建通信网络,也有专门提供暗光纤的独享网络商,他们网络的一年租赁费用就高达几千万美元。在这种环境下,个人量化投资者是不是一点机会都没有呢? 1. 伦敦期货市场和国内期货市场中的金属期货 本节示例适合个人量化交易者的低频统计套利策略,目标市场为伦敦期货市场和国内期货市场中的金属期货。 如下先获取伦敦的金属期货symbol数据: End of explanation cn = AbuFuturesCn() metal_cn = cn.futures_cn_df[ (cn.futures_cn_df['product'] == '沪铅') | (cn.futures_cn_df['product'] == '沪锌') | (cn.futures_cn_df['product'] == '沪铝') | (cn.futures_cn_df['product'] == '沪铜') | (cn.futures_cn_df['product'] == '黄金') | (cn.futures_cn_df['product'] == '白银') ] metal_cn Explanation: 接下来获取国内的金属期货symbol数据: End of explanation from ipywidgets import interact def do_plot_pair_metal(mt_cn, mt_gb): gb_data = ABuSymbolPd.make_kl_df(mt_gb, start='2011-07-28', end='2017-07-26') cn_data = ABuSymbolPd.make_kl_df(mt_cn, start='2011-07-28', end='2017-07-26') ABuMarketDrawing.plot_simple_two_stock({mt_gb: gb_data, mt_cn: cn_data}) def plot_pair_metal(pairs): pair = pairs.split('vs') do_plot_pair_metal(pair[0], pair[1]) pairs = ['CADvsCU0', 'XAUvsAU0', 'ZN0vsSND', 'AHDvsAL0', 'XAGvsAG0', 'PBDvsPB0'] _ = interact(plot_pair_metal, pairs=pairs) Explanation: 如下分别将两两金属期货进行跨市场配对,首先可视化一下走势,可以看到每一个配对期货市场的走势都非常跟随: End of explanation speed_pair = tl.execute.calc_pair_speed('CU0', 'CAD', start='2011-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 如果做跨市场高频交易,需要非常好的设备,盯着盘口的数据,快速进行交易决策,且对资金量也有要求,本节的示例为适合个人量化交易者的跨市场低频统计套利示例。 注意观察上面的每一对趋势曲线,如CAD vs CU0,你可以发现CU0对趋势敏感的速度要明显快于CAD, 而且是非高频的快,即上面的蓝线在趋势下跌时先下跌,趋势上涨时先上涨,那么就可以认为CAD在非高频下跟随CU0,具有低频统计套利机会。 2. 趋势变化的敏感速度 我们不可能真的用肉眼去一个一个观察,而且也无法量化具体趋势敏感的速度,也即无法确定是否真实存在低频统计套利机会。 对于量化交易,优势是通过计算机强大的运算能力,在市场广度的优势下获取概率优势,进行交易,下面示例如何使用abupy中的api计算趋势变化的敏感速度,如下所示: 备注: 具体计算计算趋势速度请阅读tl模块中calc_pair_speed方法 End of explanation pair_dict = {} pair_dict['CAD'] = 'CU0' Explanation: 上面的计算结果0.57为CU0对趋势变化敏感速度,0.52为CAD对趋势变化敏感速度,即CU0的对趋势变化的敏感度大于CAD,且大于0.03具备低频统计套利的条件。(大于0.05认为具有安全低频统计套利机会,具体这些阀值将在之后的章节讲解) 在低频统计套利的情况下将会使用CAD做为交易目标,CU0做为趋势风标,因为它的敏感度高,下面初始化一个字典,key为将会使用做为交易目标的CAD,value为做为趋势风标CU0,如下所示: End of explanation speed_pair = tl.execute.calc_pair_speed('AL0', 'AHD', start='2011-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 下面计算沪铝(AL0)和伦敦铝(AHD)对趋势变化的敏感速度,如下: End of explanation pair_dict['AHD'] = 'AL0' Explanation: 上面的计算结果0.61为沪铝(AL0)对趋势变化敏感速度,0.57为伦敦铝(AHD)对趋势变化敏感速度,即AL0对趋势变化的敏感度大于AHD,且大于0.03具备低频统计套利的条件。 字典中key为将会使用做为交易目标的低敏感AHD,value为做为趋势风标的高敏感AL0,如下所示: End of explanation speed_pair = tl.execute.calc_pair_speed('AU0', 'XAU', start='2012-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 下面计算国内黄金(AU0)和伦敦黄金(XAU)对趋势变化的敏感速度,如下: End of explanation pair_dict['AU0'] = 'XAU' Explanation: 上面的计算结果0.58为国内黄金(AU0)对趋势变化敏感速度,0.61为伦敦黄金(XAU)对趋势变化敏感速度,即外盘敏感速度快于国内期货趋势变化敏感速度,之前的两个都为国内期货趋势变化敏感速度快于外盘敏感速度。 字典中key为将会使用做为交易目标的低敏感国内黄金(AU0),value为做为趋势风标的高敏感伦敦黄金(XAU),如下所示: End of explanation speed_pair = tl.execute.calc_pair_speed('AG0', 'XAG', start='2012-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 下面计算国内白银(AG0)和伦敦白银(XAG)对趋势变化的敏感速度,如下: End of explanation pair_dict['AG0'] = 'XAG' Explanation: 上面的计算结果0.55为国内白银(AG0)对趋势变化敏感速度,0.60为伦敦白银(XAG)对趋势变化敏感速度,即白银的外盘敏感速度也快于国内期货趋势变化敏感速度。 字典中key为将会使用做为交易目标的低敏感国内白银(AG0),value为做为趋势风标的高敏感伦敦白银(XAG),如下所示: End of explanation speed_pair = tl.execute.calc_pair_speed('ZN0', 'SND', start='2011-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 下面计算沪锌(ZN0)和伦敦锌(SND)对趋势变化的敏感速度,如下: End of explanation pair_dict['SND'] = 'ZN0' Explanation: 字典中key为将会使用做为交易目标的低敏感伦敦锌(SND),value为做为趋势风标的高敏感沪锌(ZN0),如下所示: End of explanation speed_pair = tl.execute.calc_pair_speed('PB0', 'PBD', start='2011-07-28', end='2016-07-26', show=True) speed_pair[0], speed_pair[1] Explanation: 下面计算沪铅(PB0)和伦敦铅(PBD)对趋势变化的敏感速度,如下: End of explanation pair_dict['PB0'] = 'PBD' Explanation: 上面的计算结果0.50为沪铅(PB0)对趋势变化敏感速度,0.59为伦敦铅(PBD)对趋势变化敏感速度,差值达到0.09远大于0.03,是非常好的低频统计套利配对。 字典中key为将会使用做为交易目标的低敏感沪铅(PB0),value为做为趋势风标的高敏感伦敦铅(PBD),如下所示: End of explanation pair_dict Explanation: 上面即选定了跨市场低频统计套利的交易配对字典,key为为交易目标的低敏感,value为做为趋势风标的高敏感,如下: End of explanation class AbuFactorBuyPairBreak(AbuFactorBuyXD, BuyCallMixin): 跨市场低频统计套利策略示例 def _init_self(self, **kwargs): # 根据做为低敏感的交易目标从字典中获取做为趋势风标的高敏感目标 pair_symbol = pair_dict[self.kl_pd.name] # 获取做为趋势风标的高敏感交易目标金融时间序列 self.pair_kl_pd = ABuSymbolPd.make_kl_df( pair_symbol, data_mode=EMarketDataSplitMode.E_DATA_SPLIT_UNDO, benchmark=self.benchmark) # 是否今天就买入,还是再降低频率明天买 self.td_buy = kwargs.pop('buy_today', True) # 下面和趋势突破策略编码一样,设置突破周期参数,eg:21,42... self.xd = kwargs['xd'] def fit_day(self, today): # 获取做为趋势风标的高敏感目标今天交易数据 pair_today = self.pair_kl_pd.iloc[self.today_ind] # 做为趋势风标的高敏感目标今天突破了,则买入的是低敏感的交易目标 if pair_today.close == self.pair_kl_pd.close[self.today_ind - self.xd + 1:self.today_ind + 1].max(): # 生成买入订单, 纯低频,明天买,也可以今天买,因为本来就是跨市场的 return self.buy_today() if self.td_buy else self.buy_tomorrow() return None Explanation: 3. 基于跨市场低频统计套利的突破策略 下面编写择时交易策略实现这个跨市场低频统计套利的交易配对,如下所示: End of explanation abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_FUTURES_CN read_cash = 10000000 # 卖出因子继续使用上一节使用的因子 sell_factors = [ {'stop_loss_n': 1.0, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} ] # 买入策略使用AbuFactorBuyPairBreak buy_factors = [{'xd': 5, 'class': AbuFactorBuyPairBreak}, {'xd': 10, 'class': AbuFactorBuyPairBreak}] abu_result_tuple, kl_pd_manger = abu.run_loop_back(read_cash, buy_factors, sell_factors, start='2016-07-26', end='2017-07-26', choice_symbols=pair_dict.keys(), n_process_pick=1) ABuProgress.clear_output() AbuMetricsBase.show_general(*abu_result_tuple, only_show_returns=True) Explanation: 策略编写如上AbuFactorBuyPairBreak所示和之前章节一直使用的周期突破策略AbuFactorBuyBreak唯一不同的只有突破信号发出者为趋势风标的高敏感目标,一旦高敏感目标今天突破了,则买入的是低敏感的交易目标。 下面使用这个买入策略进行回测,卖出策略依然延用之前的策略,如下所示: End of explanation buy_factors = [{'xd': 5, 'class': AbuFactorBuyBreak}, {'xd': 10, 'class': AbuFactorBuyBreak}] abu_result_tuple, kl_pd_manger = abu.run_loop_back(read_cash, buy_factors, sell_factors, start='2016-07-26', end='2017-07-26', choice_symbols=pair_dict.keys()) ABuProgress.clear_output() AbuMetricsBase.show_general(*abu_result_tuple, only_show_returns=True) Explanation: 回测结果如上所示,对比未基于内外盘统计套利的普通突破策略回测可以看到回测效果提升很多,如下所示: End of explanation # 买入策略使用AbuFactorBuyPairBreak buy_factors = [{'xd': 5, 'class': AbuFactorBuyPairBreak, 'buy_today': False}, {'xd': 10, 'class': AbuFactorBuyPairBreak, 'buy_today': False}] abu_result_tuple, kl_pd_manger = abu.run_loop_back(read_cash, buy_factors, sell_factors, start='2016-07-26', end='2017-07-26', choice_symbols=pair_dict.keys(), n_process_pick=1) ABuProgress.clear_output() AbuMetricsBase.show_general(*abu_result_tuple, only_show_returns=True) Explanation: 而且即使再次降低交易频度,不使用跨市场套利的时间优势,选择再隔一天买入交易目标,即下面的构造因子参数buy_today=False,可以看到回测的结果依然好于未基于内外盘统计套利的普通突破策略回测结果。 End of explanation speed_pair = tl.execute.calc_pair_speed('btc', 'ltc', start='2014-03-19', end='2017-07-26', show=True) speed_pair Explanation: 4. 其它市场的配对低频统计套利 上述基于期货市场的配对统计套利基于一个条件:两个市场的期货产品相关度非常高,对于期货市场这个条件是天然成立的,但对于其它市场就需要从相关度进行验证,如下使用calc_pair_speed计算比特币和莱特币的趋势变化敏感速度: End of explanation (0.599 - 0.583) * 0.78 Explanation: 上述第一个结果0.599是btc的趋势变化敏感速度,0.583是ltc的趋势敏感速度,第三个值0.78是btc和ltc的相关度值。 如下计算btc和ltc的速度差: End of explanation speed_pair = tl.execute.calc_pair_speed('ZN0', 'SND', start='2011-07-28', end='2016-07-26', show=False) print(speed_pair) (speed_pair[0] - speed_pair[1]) * speed_pair[2] Explanation: 可以看到结果不具备配对低频统计套利的条件,实际上面示例期货产品中如ZN0,SND这样的配对也是不符合低频统计套利的条件的,如下: End of explanation
5,339
Given the following text description, write Python code to implement the functionality described below step by step Description: Notebook to retrieve gridded climate time-series data sets Case study Step1: Establish a secure connection with HydroShare by instantiating the hydroshare class that is defined within hs_utils. In addition to connecting with HydroShare, this command also sets and prints environment variables for several parameters that will be useful for saving work back to HydroShare. Step2: 2. Re-establish the paths to the mapping file Step3: 3. Download climate data Call each get Climate data function Each function reads in the mapping file table, generates the destination folder, downloads and unzips the files, then catalogs the downloaded files within the mapping file. Meteorology - MET; Weather Research and Forecasting (WRF); Variable Infiltration Capacity - VIC 1. getDailyMET_livneh2013 2. getDailyMET_bcLivneh2013 3. getDailyMET_livneh2015 4. getDailyVIC_livneh2013 5. getDailyVIC_livneh2015 6. getDailyWRF_salathe2014 7. getDailyWRF_bcsalathe2014 View data extent Step4: Download all available datasets for Elwha Watershed Step5: Download all available datasets for Upper Rio Salado Watershed Step6: 4. Summarize the file availability from each watershed mapping file Step7: 5. Save results back into HydroShare <a name="creation"></a> Using the hs_utils library, the results of the Geoprocessing steps above can be saved back into HydroShare. First, define all of the required metadata for resource creation, i.e. title, abstract, keywords, content files. In addition, we must define the type of resource that will be created, in this case genericresource. Note
Python Code: # data processing import os import pandas as pd, numpy as np, dask, json import ogh import geopandas as gpd # data migration library from utilities import hydroshare # plotting and shape libraries %matplotlib inline import warnings warnings.filterwarnings("ignore") Explanation: Notebook to retrieve gridded climate time-series data sets Case study: the Sauk-Suiattle river watershed, the Elwha river watershed, the Upper Rio Salado watershed <img src="http://www.sauk-suiattle.com/images/Elliott.jpg" style="float:right;width:150px;padding:20px"> Use this Jupyter Notebook to: 1. HydroShare setup and preparation 2. Re-establish the paths to the mapping file 3. Download climate data 4. Summarize the file availability from each watershed mapping file 5. Save results back into HydroShare <br/><br/><br/> <img src="https://www.washington.edu/brand/files/2014/09/W-Logo_Purple_Hex.png" style="float:right;width:150px;padding:20px"> <br/><br/> This data is compiled to digitally observe the watersheds, powered by HydroShare. <br/>Provided by the Watershed Dynamics Group, Dept. of Civil and Environmental Engineering, University of Washington 1. HydroShare Setup and Preparation To run this notebook, we must import several libaries. These are listed in order of 1) Python standard libraries, 2) hs_utils library provides functions for interacting with HydroShare, including resource querying, dowloading and creation, and 3) the observatory_gridded_hydromet library that is downloaded with this notebook. End of explanation notebookdir = os.getcwd() hs=hydroshare.hydroshare() homedir = hs.getContentPath(os.environ["HS_RES_ID"]) os.chdir(homedir) print('Data will be loaded from and save to:'+homedir) # initialize ogh_meta meta_file = dict(ogh.ogh_meta()) sorted(meta_file.keys()) Explanation: Establish a secure connection with HydroShare by instantiating the hydroshare class that is defined within hs_utils. In addition to connecting with HydroShare, this command also sets and prints environment variables for several parameters that will be useful for saving work back to HydroShare. End of explanation # map the mapping files generated for Sauk-Suiattle, Elwha, and Upper Rio Salado from usecase1 mappingfile1 = os.path.join(homedir,'Sauk_mappingfile.csv') mappingfile2 = os.path.join(homedir,'Elwha_mappingfile.csv') mappingfile3 = os.path.join(homedir,'RioSalado_mappingfile.csv') t1 = ogh.mappingfileSummary(listofmappingfiles = [mappingfile1, mappingfile2, mappingfile3], listofwatershednames = ['Sauk-Suiattle river','Elwha river','Upper Rio Salado'], meta_file=meta_file) t1 Explanation: 2. Re-establish the paths to the mapping file End of explanation %%time ogh.getDailyMET_livneh2013(homedir, mappingfile1) ogh.getDailyMET_bcLivneh2013(homedir, mappingfile1) ogh.getDailyMET_livneh2015(homedir, mappingfile1) ogh.getDailyVIC_livneh2013(homedir, mappingfile1) ogh.getDailyVIC_livneh2015(homedir, mappingfile1) ogh.getDailyWRF_salathe2014(homedir, mappingfile1) ogh.getDailyWRF_bcsalathe2014(homedir, mappingfile1) Explanation: 3. Download climate data Call each get Climate data function Each function reads in the mapping file table, generates the destination folder, downloads and unzips the files, then catalogs the downloaded files within the mapping file. Meteorology - MET; Weather Research and Forecasting (WRF); Variable Infiltration Capacity - VIC 1. getDailyMET_livneh2013 2. getDailyMET_bcLivneh2013 3. getDailyMET_livneh2015 4. getDailyVIC_livneh2013 5. getDailyVIC_livneh2015 6. getDailyWRF_salathe2014 7. getDailyWRF_bcsalathe2014 View data extent: 1. Continental United States (CONUS) Livneh, B. (2017). Gridded climatology locations (1/16th degree): Continental United States extent, HydroShare, http://www.hydroshare.org/resource/14f0a6619c6b45cc90d1f8cabc4129af 2. North America (NAmer) Livneh, B. (2017). Gridded climatology locations (1/16th degree): North American extent, HydroShare, http://www.hydroshare.org/resource/ef2d82bf960144b4bfb1bae6242bcc7f 3. Pacific Northwest - Columbia River Basin Bandaragoda, C. (2017). Sauk Suiattle HydroMeteorology (WRF), HydroShare, http://www.hydroshare.org/resource/0db969e4cfb54cb18b4e1a2014a26c82 Please cite: 1. Livneh B., E.A. Rosenberg, C. Lin, B. Nijssen, V. Mishra, K.M. Andreadis, E.P. Maurer, and D.P. Lettenmaier, 2013: A Long-Term Hydrologically Based Dataset of Land Surface Fluxes and States for the Conterminous United States: Update and Extensions, Journal of Climate, 26, 9384–9392. 2. Livneh B., T.J. Bohn, D.S. Pierce, F. Munoz-Ariola, B. Nijssen, R. Vose, D. Cayan, and L.D. Brekke, 2015: A spatially comprehensive, hydrometeorological data set for Mexico, the U.S., and southern Canada 1950-2013, Nature Scientific Data, 5:150042, doi:10.1038/sdata.2015.42. 3. Salathé, EP, AF Hamlet, CF Mass, M Stumbaugh, S-Y Lee, R Steed: 2017. Estimates of 21st Century Flood Risk in the Pacific Northwest Based on Regional Scale Climate Model Simulations. J. Hydrometeorology. DOI: 10.1175/JHM-D-13-0137.1 Download all available datasets for Sauk-Suiattle Watershed End of explanation %%time ogh.getDailyMET_livneh2013(homedir, mappingfile2) ogh.getDailyMET_bcLivneh2013(homedir, mappingfile2) ogh.getDailyMET_livneh2015(homedir, mappingfile2) ogh.getDailyVIC_livneh2013(homedir, mappingfile2) ogh.getDailyVIC_livneh2015(homedir, mappingfile2) ogh.getDailyWRF_salathe2014(homedir, mappingfile2) ogh.getDailyWRF_bcsalathe2014(homedir, mappingfile2) Explanation: Download all available datasets for Elwha Watershed End of explanation %%time ogh.getDailyMET_livneh2013(homedir, mappingfile3) ogh.getDailyMET_bcLivneh2013(homedir, mappingfile3) ogh.getDailyMET_livneh2015(homedir, mappingfile3) ogh.getDailyVIC_livneh2013(homedir, mappingfile3) ogh.getDailyVIC_livneh2015(homedir, mappingfile3) ogh.getDailyWRF_salathe2014(homedir, mappingfile3) ogh.getDailyWRF_bcsalathe2014(homedir, mappingfile3) Explanation: Download all available datasets for Upper Rio Salado Watershed End of explanation t1 = ogh.mappingfileSummary(listofmappingfiles = [mappingfile1, mappingfile2, mappingfile3], listofwatershednames = ['Sauk-Suiattle river','Elwha river','Upper Rio Salado'], meta_file=meta_file) t1.to_csv(os.path.join(homedir, 'watershed_table.txt'), sep='\t', header=True, index=True) t1 Explanation: 4. Summarize the file availability from each watershed mapping file End of explanation %%time !tar -zcf livneh2013.tar.gz livneh2013 !tar -zcf livneh2015.tar.gz livneh2015 !tar -zcf salathe2014.tar.gz salathe2014 # the downloaded tar files climate2013_tar = os.path.join(homedir,'livneh2013.tar.gz') climate2015_tar = os.path.join(homedir,'livneh2015.tar.gz') wrf_tar = os.path.join(homedir,'salathe2014.tar.gz') # for each file downloaded onto the server folder, move to a new HydroShare Generic Resource title = 'Downloaded data sets from each study site for each of seven gridded data products' abstract = 'This resource contains the downloaded data files for each study site and the gridded cell centroids that intersected within the study area. The file availability is described within the watershed_table file, which summarizes each of the three mapping file catalogs.' keywords = ['Sauk', 'Elwha','Rio Salado','climate','hydromet','watershed'] rtype = 'genericresource' # files to migrate files=[mappingfile1, # sauk mappingfile2, # elwha mappingfile3, # riosalado watershed_table, # watershed summary table climate2013_tar, # Livneh et al. 2013 raw MET, bc MET, and VIC climate2015_tar, # Livneh et al. 2015 raw MET, and VIC wrf_tar] # Salathe et al. 2014 raw WRF and bc WRF # create the new resource resource_id = hs.createHydroShareResource(title=title, abstract=abstract, keywords=keywords, resource_type=rtype, content_files=files, public=False) Explanation: 5. Save results back into HydroShare <a name="creation"></a> Using the hs_utils library, the results of the Geoprocessing steps above can be saved back into HydroShare. First, define all of the required metadata for resource creation, i.e. title, abstract, keywords, content files. In addition, we must define the type of resource that will be created, in this case genericresource. Note: Make sure you save the notebook at this point, so that all notebook changes will be saved into the new HydroShare resource. Archive the downloaded data files for collaborative use Create list of files to save to HydroShare. Verify location and names. End of explanation
5,340
Given the following text description, write Python code to implement the functionality described below step by step Description: 独立成分分析 Lab 在此 notebook 中,我们将使用独立成分分析方法从三个观察结果中提取信号,每个观察结果都包含不同的原始混音信号。这个问题与 ICA 视频中解释的问题一样。 数据集 首先看看手头的数据集。我们有三个 WAVE 文件,正如我们之前提到的,每个文件都是混音形式。如果你之前没有在 python 中处理过音频文件,没关系,它们实际上就是浮点数列表。 首先加载第一个音频文件 ICA_mix_1.wav [点击即可聆听该文件]: Step1: 我们看看该 wave 文件的参数,详细了解该文件 Step2: 该文件只有一个声道(因此是单声道)。帧率是 44100,表示每秒声音由 44100 个整数组成(因为文件是常见的 PCM 16 位格式,所以是整数)。该文件总共有 264515 个整数/帧,因此时长为: Step3: 我们从该 wave 文件中提取帧,这些帧将属于我们将运行 ICA 的数据集: Step4: signal_1 现在是一个整数列表,表示第一个文件中包含的声音。 Step5: 如果将此数组绘制成线形图,我们将获得熟悉的波形: Step6: 现在我们可以按照相同的方式加载另外两个 wave 文件 ICA_mix_2.wav 和 ICA_mix_3.wav Step7: 读取所有三个文件后,可以通过 zip 运算创建数据集。 通过将 signal_1、signal_2 和 signal_3 组合成一个列表创建数据集 X Step8: 现在准备运行 ICA 以尝试获取原始信号。 导入 sklearn 的 FastICA 模块 初始化 FastICA,查看三个成分 使用 fit_transform 对数据集 X 运行 FastICA 算法 Step9: 我们将其拆分为单独的信号并查看这些信号 Step10: 我们对信号进行绘制,查看波浪线的形状 Step11: 某些波浪线看起来像音乐波形吗? 确认结果的最佳方式是聆听生成的文件。另存为 wave 文件并进行验证。在此之前,我们需要: * 将它们转换为整数(以便另存为 PCM 16 位 Wave 文件),否则只有某些媒体播放器能够播放它们 * 将值映射到 int16 音频的相应范围内。该范围在 -32768 到 +32767 之间。基本的映射方法是乘以 32767。 * 音量有点低,我们可以乘以某个值(例如 100)来提高音量
Python Code: import numpy as np import wave # Read the wave file mix_1_wave = wave.open('ICA_mix_1.wav','r') Explanation: 独立成分分析 Lab 在此 notebook 中,我们将使用独立成分分析方法从三个观察结果中提取信号,每个观察结果都包含不同的原始混音信号。这个问题与 ICA 视频中解释的问题一样。 数据集 首先看看手头的数据集。我们有三个 WAVE 文件,正如我们之前提到的,每个文件都是混音形式。如果你之前没有在 python 中处理过音频文件,没关系,它们实际上就是浮点数列表。 首先加载第一个音频文件 ICA_mix_1.wav [点击即可聆听该文件]: End of explanation mix_1_wave.getparams() Explanation: 我们看看该 wave 文件的参数,详细了解该文件 End of explanation 264515/44100 Explanation: 该文件只有一个声道(因此是单声道)。帧率是 44100,表示每秒声音由 44100 个整数组成(因为文件是常见的 PCM 16 位格式,所以是整数)。该文件总共有 264515 个整数/帧,因此时长为: End of explanation # Extract Raw Audio from Wav File signal_1_raw = mix_1_wave.readframes(-1) signal_1 = np.fromstring(signal_1_raw, 'Int16') Explanation: 我们从该 wave 文件中提取帧,这些帧将属于我们将运行 ICA 的数据集: End of explanation 'length: ', len(signal_1) , 'first 100 elements: ',signal_1[:100] Explanation: signal_1 现在是一个整数列表,表示第一个文件中包含的声音。 End of explanation import matplotlib.pyplot as plt fs = mix_1_wave.getframerate() timing = np.linspace(0, len(signal_1)/fs, num=len(signal_1)) plt.figure(figsize=(12,2)) plt.title('Recording 1') plt.plot(timing,signal_1, c="#3ABFE7") plt.ylim(-35000, 35000) plt.show() Explanation: 如果将此数组绘制成线形图,我们将获得熟悉的波形: End of explanation mix_2_wave = wave.open('ICA_mix_2.wav','r') #Extract Raw Audio from Wav File signal_raw_2 = mix_2_wave.readframes(-1) signal_2 = np.fromstring(signal_raw_2, 'Int16') mix_3_wave = wave.open('ICA_mix_3.wav','r') #Extract Raw Audio from Wav File signal_raw_3 = mix_3_wave.readframes(-1) signal_3 = np.fromstring(signal_raw_3, 'Int16') plt.figure(figsize=(12,2)) plt.title('Recording 2') plt.plot(timing,signal_2, c="#3ABFE7") plt.ylim(-35000, 35000) plt.show() plt.figure(figsize=(12,2)) plt.title('Recording 3') plt.plot(timing,signal_3, c="#3ABFE7") plt.ylim(-35000, 35000) plt.show() Explanation: 现在我们可以按照相同的方式加载另外两个 wave 文件 ICA_mix_2.wav 和 ICA_mix_3.wav End of explanation X = list(zip(signal_1, signal_2, signal_3)) # Let's peak at what X looks like X[:10] Explanation: 读取所有三个文件后,可以通过 zip 运算创建数据集。 通过将 signal_1、signal_2 和 signal_3 组合成一个列表创建数据集 X End of explanation # TODO: Import FastICA # TODO: Initialize FastICA with n_components=3 # TODO: Run the FastICA algorithm using fit_transform on dataset X ica_result.shape Explanation: 现在准备运行 ICA 以尝试获取原始信号。 导入 sklearn 的 FastICA 模块 初始化 FastICA,查看三个成分 使用 fit_transform 对数据集 X 运行 FastICA 算法 End of explanation result_signal_1 = ica_result[:,0] result_signal_2 = ica_result[:,1] result_signal_3 = ica_result[:,2] Explanation: 我们将其拆分为单独的信号并查看这些信号 End of explanation # Plot Independent Component #1 plt.figure(figsize=(12,2)) plt.title('Independent Component #1') plt.plot(result_signal_1, c="#df8efd") plt.ylim(-0.010, 0.010) plt.show() # Plot Independent Component #2 plt.figure(figsize=(12,2)) plt.title('Independent Component #2') plt.plot(result_signal_2, c="#87de72") plt.ylim(-0.010, 0.010) plt.show() # Plot Independent Component #3 plt.figure(figsize=(12,2)) plt.title('Independent Component #3') plt.plot(result_signal_3, c="#f65e97") plt.ylim(-0.010, 0.010) plt.show() Explanation: 我们对信号进行绘制,查看波浪线的形状 End of explanation from scipy.io import wavfile # Convert to int, map the appropriate range, and increase the volume a little bit result_signal_1_int = np.int16(result_signal_1*32767*100) result_signal_2_int = np.int16(result_signal_2*32767*100) result_signal_3_int = np.int16(result_signal_3*32767*100) # Write wave files wavfile.write("result_signal_1.wav", fs, result_signal_1_int) wavfile.write("result_signal_2.wav", fs, result_signal_2_int) wavfile.write("result_signal_3.wav", fs, result_signal_3_int) Explanation: 某些波浪线看起来像音乐波形吗? 确认结果的最佳方式是聆听生成的文件。另存为 wave 文件并进行验证。在此之前,我们需要: * 将它们转换为整数(以便另存为 PCM 16 位 Wave 文件),否则只有某些媒体播放器能够播放它们 * 将值映射到 int16 音频的相应范围内。该范围在 -32768 到 +32767 之间。基本的映射方法是乘以 32767。 * 音量有点低,我们可以乘以某个值(例如 100)来提高音量 End of explanation
5,341
Given the following text description, write Python code to implement the functionality described below step by step Description: M-Estimators for Robust Linear Modeling Step1: An M-estimator minimizes the function $$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$ where $\rho$ is a symmetric function of the residuals The effect of $\rho$ is to reduce the influence of outliers $s$ is an estimate of scale. The robust estimates $\hat{\beta}$ are computed by the iteratively re-weighted least squares algorithm We have several choices available for the weighting functions to be used Step2: Andrew's Wave Step3: Hampel's 17A Step4: Huber's t Step5: Least Squares Step6: Ramsay's Ea Step7: Trimmed Mean Step8: Tukey's Biweight Step9: Scale Estimators Robust estimates of the location Step10: The mean is not a robust estimator of location Step11: The median, on the other hand, is a robust estimator with a breakdown point of 50% Step12: Analogously for the scale The standard deviation is not robust Step13: Median Absolute Deviation $$ median_i |X_i - median_j(X_j)|) $$ Standardized Median Absolute Deviation is a consistent estimator for $\hat{\sigma}$ $$\hat{\sigma}=K \cdot MAD$$ where $K$ depends on the distribution. For the normal distribution for example, $$K = \Phi^{-1}(.75)$$ Step14: Another robust estimator of scale is the Interquartile Range (IQR) $$\left(\hat{X}{0.75} - \hat{X}{0.25}\right),$$ where $\hat{X}_{p}$ is the sample p-th quantile and $K$ depends on the distribution. The standardized IQR, given by $K \cdot \text{IQR}$ for $$K = \frac{1}{\Phi^{-1}(.75) - \Phi^{-1}(.25)} \approx 0.74,$$ is a consistent estimator of the standard deviation for normal data. Step15: The IQR is less robust than the MAD in the sense that it has a lower breakdown point Step16: The default for Robust Linear Models is MAD another popular choice is Huber's proposal 2 Step17: Duncan's Occupational Prestige data - M-estimation for outliers Step18: Hertzprung Russell data for Star Cluster CYG 0B1 - Leverage Points Data is on the luminosity and temperature of 47 stars in the direction of Cygnus. Step19: Why? Because M-estimators are not robust to leverage points. Step20: Let's delete that line Step21: MM estimators are good for this type of problem, unfortunately, we do not yet have these yet. It's being worked on, but it gives a good excuse to look at the R cell magics in the notebook. Step22: Note Step23: Exercise Step24: Squared error loss
Python Code: %matplotlib inline from statsmodels.compat import lmap import numpy as np from scipy import stats import matplotlib.pyplot as plt import statsmodels.api as sm Explanation: M-Estimators for Robust Linear Modeling End of explanation norms = sm.robust.norms def plot_weights(support, weights_func, xlabels, xticks): fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111) ax.plot(support, weights_func(support)) ax.set_xticks(xticks) ax.set_xticklabels(xlabels, fontsize=16) ax.set_ylim(-.1, 1.1) return ax Explanation: An M-estimator minimizes the function $$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$ where $\rho$ is a symmetric function of the residuals The effect of $\rho$ is to reduce the influence of outliers $s$ is an estimate of scale. The robust estimates $\hat{\beta}$ are computed by the iteratively re-weighted least squares algorithm We have several choices available for the weighting functions to be used End of explanation help(norms.AndrewWave.weights) a = 1.339 support = np.linspace(-np.pi*a, np.pi*a, 100) andrew = norms.AndrewWave(a=a) plot_weights(support, andrew.weights, ['$-\pi*a$', '0', '$\pi*a$'], [-np.pi*a, 0, np.pi*a]); Explanation: Andrew's Wave End of explanation help(norms.Hampel.weights) c = 8 support = np.linspace(-3*c, 3*c, 1000) hampel = norms.Hampel(a=2., b=4., c=c) plot_weights(support, hampel.weights, ['3*c', '0', '3*c'], [-3*c, 0, 3*c]); Explanation: Hampel's 17A End of explanation help(norms.HuberT.weights) t = 1.345 support = np.linspace(-3*t, 3*t, 1000) huber = norms.HuberT(t=t) plot_weights(support, huber.weights, ['-3*t', '0', '3*t'], [-3*t, 0, 3*t]); Explanation: Huber's t End of explanation help(norms.LeastSquares.weights) support = np.linspace(-3, 3, 1000) lst_sq = norms.LeastSquares() plot_weights(support, lst_sq.weights, ['-3', '0', '3'], [-3, 0, 3]); Explanation: Least Squares End of explanation help(norms.RamsayE.weights) a = .3 support = np.linspace(-3*a, 3*a, 1000) ramsay = norms.RamsayE(a=a) plot_weights(support, ramsay.weights, ['-3*a', '0', '3*a'], [-3*a, 0, 3*a]); Explanation: Ramsay's Ea End of explanation help(norms.TrimmedMean.weights) c = 2 support = np.linspace(-3*c, 3*c, 1000) trimmed = norms.TrimmedMean(c=c) plot_weights(support, trimmed.weights, ['-3*c', '0', '3*c'], [-3*c, 0, 3*c]); Explanation: Trimmed Mean End of explanation help(norms.TukeyBiweight.weights) c = 4.685 support = np.linspace(-3*c, 3*c, 1000) tukey = norms.TukeyBiweight(c=c) plot_weights(support, tukey.weights, ['-3*c', '0', '3*c'], [-3*c, 0, 3*c]); Explanation: Tukey's Biweight End of explanation x = np.array([1, 2, 3, 4, 500]) Explanation: Scale Estimators Robust estimates of the location End of explanation x.mean() Explanation: The mean is not a robust estimator of location End of explanation np.median(x) Explanation: The median, on the other hand, is a robust estimator with a breakdown point of 50% End of explanation x.std() Explanation: Analogously for the scale The standard deviation is not robust End of explanation stats.norm.ppf(.75) print(x) sm.robust.scale.mad(x) np.array([1,2,3,4,5.]).std() Explanation: Median Absolute Deviation $$ median_i |X_i - median_j(X_j)|) $$ Standardized Median Absolute Deviation is a consistent estimator for $\hat{\sigma}$ $$\hat{\sigma}=K \cdot MAD$$ where $K$ depends on the distribution. For the normal distribution for example, $$K = \Phi^{-1}(.75)$$ End of explanation sm.robust.scale.iqr(x) Explanation: Another robust estimator of scale is the Interquartile Range (IQR) $$\left(\hat{X}{0.75} - \hat{X}{0.25}\right),$$ where $\hat{X}_{p}$ is the sample p-th quantile and $K$ depends on the distribution. The standardized IQR, given by $K \cdot \text{IQR}$ for $$K = \frac{1}{\Phi^{-1}(.75) - \Phi^{-1}(.25)} \approx 0.74,$$ is a consistent estimator of the standard deviation for normal data. End of explanation sm.robust.scale.qn_scale(x) Explanation: The IQR is less robust than the MAD in the sense that it has a lower breakdown point: it can withstand 25\% outlying observations before being completely ruined, whereas the MAD can withstand 50\% outlying observations. However, the IQR is better suited for asymmetric distributions. Yet another robust estimator of scale is the $Q_n$ estimator, introduced in Rousseeuw & Croux (1993), 'Alternatives to the Median Absolute Deviation'. Then $Q_n$ estimator is given by $$ Q_n = K \left\lbrace \vert X_{i} - X_{j}\vert : i<j\right\rbrace_{(h)} $$ where $h\approx (1/4){{n}\choose{2}}$ and $K$ is a given constant. In words, the $Q_n$ estimator is the normalized $h$-th order statistic of the absolute differences of the data. The normalizing constant $K$ is usually chosen as 2.219144, to make the estimator consistent for the standard deviation in the case of normal data. The $Q_n$ estimator has a 50\% breakdown point and a 82\% asymptotic efficiency at the normal distribution, much higher than the 37\% efficiency of the MAD. End of explanation np.random.seed(12345) fat_tails = stats.t(6).rvs(40) kde = sm.nonparametric.KDEUnivariate(fat_tails) kde.fit() fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111) ax.plot(kde.support, kde.density); print(fat_tails.mean(), fat_tails.std()) print(stats.norm.fit(fat_tails)) print(stats.t.fit(fat_tails, f0=6)) huber = sm.robust.scale.Huber() loc, scale = huber(fat_tails) print(loc, scale) sm.robust.mad(fat_tails) sm.robust.mad(fat_tails, c=stats.t(6).ppf(.75)) sm.robust.scale.mad(fat_tails) Explanation: The default for Robust Linear Models is MAD another popular choice is Huber's proposal 2 End of explanation from statsmodels.graphics.api import abline_plot from statsmodels.formula.api import ols, rlm prestige = sm.datasets.get_rdataset("Duncan", "carData", cache=True).data print(prestige.head(10)) fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(211, xlabel='Income', ylabel='Prestige') ax1.scatter(prestige.income, prestige.prestige) xy_outlier = prestige.loc['minister', ['income','prestige']] ax1.annotate('Minister', xy_outlier, xy_outlier+1, fontsize=16) ax2 = fig.add_subplot(212, xlabel='Education', ylabel='Prestige') ax2.scatter(prestige.education, prestige.prestige); ols_model = ols('prestige ~ income + education', prestige).fit() print(ols_model.summary()) infl = ols_model.get_influence() student = infl.summary_frame()['student_resid'] print(student) print(student.loc[np.abs(student) > 2]) print(infl.summary_frame().loc['minister']) sidak = ols_model.outlier_test('sidak') sidak.sort_values('unadj_p', inplace=True) print(sidak) fdr = ols_model.outlier_test('fdr_bh') fdr.sort_values('unadj_p', inplace=True) print(fdr) rlm_model = rlm('prestige ~ income + education', prestige).fit() print(rlm_model.summary()) print(rlm_model.weights) Explanation: Duncan's Occupational Prestige data - M-estimation for outliers End of explanation dta = sm.datasets.get_rdataset("starsCYG", "robustbase", cache=True).data from matplotlib.patches import Ellipse fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111, xlabel='log(Temp)', ylabel='log(Light)', title='Hertzsprung-Russell Diagram of Star Cluster CYG OB1') ax.scatter(*dta.values.T) # highlight outliers e = Ellipse((3.5, 6), .2, 1, alpha=.25, color='r') ax.add_patch(e); ax.annotate('Red giants', xy=(3.6, 6), xytext=(3.8, 6), arrowprops=dict(facecolor='black', shrink=0.05, width=2), horizontalalignment='left', verticalalignment='bottom', clip_on=True, # clip to the axes bounding box fontsize=16, ) # annotate these with their index for i,row in dta.loc[dta['log.Te'] < 3.8].iterrows(): ax.annotate(i, row, row + .01, fontsize=14) xlim, ylim = ax.get_xlim(), ax.get_ylim() from IPython.display import Image Image(filename='star_diagram.png') y = dta['log.light'] X = sm.add_constant(dta['log.Te'], prepend=True) ols_model = sm.OLS(y, X).fit() abline_plot(model_results=ols_model, ax=ax) rlm_mod = sm.RLM(y, X, sm.robust.norms.TrimmedMean(.5)).fit() abline_plot(model_results=rlm_mod, ax=ax, color='red') Explanation: Hertzprung Russell data for Star Cluster CYG 0B1 - Leverage Points Data is on the luminosity and temperature of 47 stars in the direction of Cygnus. End of explanation infl = ols_model.get_influence() h_bar = 2*(ols_model.df_model + 1 )/ols_model.nobs hat_diag = infl.summary_frame()['hat_diag'] hat_diag.loc[hat_diag > h_bar] sidak2 = ols_model.outlier_test('sidak') sidak2.sort_values('unadj_p', inplace=True) print(sidak2) fdr2 = ols_model.outlier_test('fdr_bh') fdr2.sort_values('unadj_p', inplace=True) print(fdr2) Explanation: Why? Because M-estimators are not robust to leverage points. End of explanation l = ax.lines[-1] l.remove() del l weights = np.ones(len(X)) weights[X[X['log.Te'] < 3.8].index.values - 1] = 0 wls_model = sm.WLS(y, X, weights=weights).fit() abline_plot(model_results=wls_model, ax=ax, color='green') Explanation: Let's delete that line End of explanation yy = y.values[:,None] xx = X['log.Te'].values[:,None] Explanation: MM estimators are good for this type of problem, unfortunately, we do not yet have these yet. It's being worked on, but it gives a good excuse to look at the R cell magics in the notebook. End of explanation params = [-4.969387980288108, 2.2531613477892365] # Computed using R print(params[0], params[1]) abline_plot(intercept=params[0], slope=params[1], ax=ax, color='red') Explanation: Note: The R code and the results in this notebook has been converted to markdown so that R is not required to build the documents. The R results in the notebook were computed using R 3.5.1 and robustbase 0.93. ```ipython %load_ext rpy2.ipython %R library(robustbase) %Rpush yy xx %R mod <- lmrob(yy ~ xx); %R params <- mod$coefficients; %Rpull params ``` ipython %R print(mod) Call: lmrob(formula = yy ~ xx) \--&gt; method = "MM" Coefficients: (Intercept) xx -4.969 2.253 End of explanation np.random.seed(12345) nobs = 200 beta_true = np.array([3, 1, 2.5, 3, -4]) X = np.random.uniform(-20,20, size=(nobs, len(beta_true)-1)) # stack a constant in front X = sm.add_constant(X, prepend=True) # np.c_[np.ones(nobs), X] mc_iter = 500 contaminate = .25 # percentage of response variables to contaminate all_betas = [] for i in range(mc_iter): y = np.dot(X, beta_true) + np.random.normal(size=200) random_idx = np.random.randint(0, nobs, size=int(contaminate * nobs)) y[random_idx] = np.random.uniform(-750, 750) beta_hat = sm.RLM(y, X).fit().params all_betas.append(beta_hat) all_betas = np.asarray(all_betas) se_loss = lambda x : np.linalg.norm(x, ord=2)**2 se_beta = lmap(se_loss, all_betas - beta_true) Explanation: Exercise: Breakdown points of M-estimator End of explanation np.array(se_beta).mean() all_betas.mean(0) beta_true se_loss(all_betas.mean(0) - beta_true) Explanation: Squared error loss End of explanation
5,342
Given the following text description, write Python code to implement the functionality described below step by step Description: Problem setup Step1: Traditional model-fitting explanation Step2: Here a polynomial won't be look great, but it's relatively stable in the region around the data. However, the fit becomes unstable as the order increases up to the number of data points, and the errors go crazy goes crazy. Step5: The points are all interpolated here, but the fit inbetween is terrible. This is generally shown to be the reason for keeping model complexity low compared to the size of the data. Back to the sine/cosine model Step6: Case Step7: For a more "energy-like" view, we'll plot in a log scale. Any peaks above 0 can be considered "noise energy", as the truth would be all 0s. Step8: The model has order number of large humps, where large, badly-fitting spikes occur (where the humps might wrap around the 2 pi point, since the sines/cosines are periodic there). Overfitting Step9: Overfitting? Try n > m Let's use twice as many parameters as data points Step10: Now there are still badly fitting spikes, but there peaks start to all go down... The "noise energy" is getting spread across higher frequencies, and the average misfit to the truth goes down. Harmless overfitting? n = 10m Way more parameters Step11: Show the misfit as a function of number of sin/cos terms Step12: References [1] Muthukumar, Vidya, et al. "Harmless interpolation of noisy data in regression." IEEE Journal on Selected Areas in Information Theory (2020). The final figure is replicating one case from Figure 2
Python Code: X_MAX = 2 * np.pi def make_data(m): # Make Xs scattered on interval [0, 2pi] X = X_MAX * np.random.rand(m,) # Y's are all zero (1e-10 for plotting purposes) Y = 1e-9 + np.zeros((m,)) # ...except for one noise point Y[m//2] = 1 return X, Y Explanation: Problem setup: We're going to have a small number of (X, Y) data points. We will see how the model misfit changes as we increase the number of parameters. The type of model we'll use is a sum of sines and cosines of increasing frequency. The model parameters are the amplitudes of these sinusoids. That is, given the m data points $(x_1, y_1) ,\ldots, (x_m, y_m)$ , we'll fit \begin{align} y_i = a_0 + a_1 \cos(x_i) + a_2 \cos(2x_i) + \ldots a_n \cos(nx_i) + b_1 \sin(x_i) + \ldots + b_n \sin(nx_i) \end{align} But before we work with this, we'll first show what happens with Numpy's Polynomial.fit function, which is often used to show the danger of high complexity model fitting. Make the truth data: all zeros, but there's one noise point at 1 For illustration purposes, the data generation process will just be all zeros. But we'll add noise to one single point to move it from 0 to 1. An omniscient model would ignore the noise point and predict all zeros... but it will try to fit through that noise point at y=1. End of explanation from numpy.polynomial import Polynomial m = 9 X, Y = make_data(m) n = 4 p = Polynomial.fit(X, Y, n) xx, yy = p.linspace(domain=[np.min(X), np.max(X)]) plt.figure() plt.plot(xx, yy, label=f"poly fit {n = }") plt.plot(X, Y, 'rx', label='sample points') plt.legend() Explanation: Traditional model-fitting explanation: Use fewer parameters than data (n << m) End of explanation n = 9 p = Polynomial.fit(X, Y, n) xx, yy = p.linspace(domain=[np.min(X), np.max(X)]) plt.figure() plt.plot(xx, yy, label=f"poly fit {n = }") plt.plot(X, Y, 'rx', label='sample points') plt.ylim(-10, 10) plt.legend() Explanation: Here a polynomial won't be look great, but it's relatively stable in the region around the data. However, the fit becomes unstable as the order increases up to the number of data points, and the errors go crazy goes crazy. End of explanation def form_A(X, order): # N is the highest order sin/cos, so num terms is n = 2order + 1 # X has m data points m = X.shape[0] A = np.zeros((m, 2*order + 1)) A[:, 0] = 1 for k in range(1, order + 1): A[:, k] = np.cos(X * k) A[:, k + order] = np.sin(X * k) return A def predict(coeffs, xs): Take in the coefficients of the sin/cosine terms from the fitting, along with the x locations, and output the model predicted ys The `coeffs` vector are the a_i and b_i cos/sin coefficients order = (len(coeffs) - 1) // 2 m = len(xs) idxs = np.arange(1, order+1).reshape((1, order)) a0 = coeffs[0] cos_terms = np.sum(coeffs[1:(order+1)] * np.cos(xs.reshape((-1, 1)) * idxs), axis=1) sin_terms = np.sum(coeffs[order+1:] * np.sin(xs.reshape((-1, 1)) * idxs), axis=1) ys = a0 + cos_terms + sin_terms return ys def calculate_avg_misfit(y_hat, y_truth = 0): # The real data should be all 0s (except that one noisy point), so a 0 line would be perfect return np.sum(np.abs(y_hat - y_truth)) / len(y_hat) def fit(X, Y, order, x_test=None, x_max=X_MAX, print_misfit=True): Fit the sin/cos model, return the [a_i, b_i] coefficients A = form_A(X, order) m = len(X) n = 2*order + 1 assert A.shape == (m, n) # If overdetermined system (m > n, more data points (rows) than features (columns)), # this would be a least squares fitting of the model. # coeffs = np.linalg.lstsq(A, Y, rcond=None)[0] # For fat A (m < n), we'll use the pseudoinverse to fit coeffs = np.linalg.pinv(A) @ Y if x_test is None: x_test = np.linspace(0, X_MAX, 500) y_hat = predict(coeffs, x_test) misfit = calculate_avg_misfit(y_hat) if print_misfit: print(f"Average misfit: {misfit}") return x_test, y_hat, misfit Explanation: The points are all interpolated here, but the fit inbetween is terrible. This is generally shown to be the reason for keeping model complexity low compared to the size of the data. Back to the sine/cosine model: Now to show what happens as we increase the number of model parameters above and beyond the number of data points, we'll use the Fourier model: \begin{align} y_i = a_0 + a_1 \cos(x_i) + a_2 \cos(2x_i) + \ldots a_n \cos(nx_i) + b_1 \sin(x_i) + \ldots + b_n \sin(nx_i) \end{align} (Note that we're using this sine/cosine model to match [1], and because the Polynomial.fit fails for when the deg, polynomial order, exceeds m, the number of points). Below are the functions for the making $\mathbf{A}$ matrix for fitting the system $\mathbf{y = Ax}$, along with fit() and predict() functions for the model: End of explanation # m = Number of data points # n = Number of parameters to fit # m = 9 # X, Y = make_data(m) order = 3 # n = 2*order + 1 x_test, y_hat, misfit = fit(X, Y, order) plt.figure() plt.plot(x_test, y_hat, 'b.-', label='predicted') plt.plot(X, Y, 'rx', label='sample points') plt.title("Predicted y vs x (linear scale)") plt.legend() Explanation: Case: m > n, more data points than model parameters The model does it's best to fit all points, but there are fewer parameters than data points, so we're doing a least-squares regression End of explanation plt.figure() plt.semilogy(x_test, y_hat, 'b.-', label='predicted') plt.semilogy(X, Y, 'rx', label='sample points') plt.title("Predicted y vs x (log-scale)") plt.legend() Explanation: For a more "energy-like" view, we'll plot in a log scale. Any peaks above 0 can be considered "noise energy", as the truth would be all 0s. End of explanation order = m // 2 n = 2*order + 1 assert n == m x_test, y_hat, misfit = fit(X, Y, order) plt.figure() plt.semilogy(x_test, y_hat, 'b.-') plt.semilogy(X, Y, 'rx') plt.show() Explanation: The model has order number of large humps, where large, badly-fitting spikes occur (where the humps might wrap around the 2 pi point, since the sines/cosines are periodic there). Overfitting: m == n The number of sin and cosine terms will now be equal to the number of data points to fit. This is the worst-case scenario here, where we can interpolate the data (match the training points exactly), but in between those, the model goes wildly off the rails (just like with the polynomail fit). End of explanation order = m # n = 2*order + 1 x_test, y_hat, misfit = fit(X, Y, order) plt.figure() plt.semilogy(x_test, y_hat, 'b.-') plt.semilogy(X, Y, 'rx') plt.show() Explanation: Overfitting? Try n > m Let's use twice as many parameters as data points End of explanation order = 10*m x_test, y_hat, misfit = fit(X, Y, order) plt.figure() plt.semilogy(x_test, y_hat, 'b.-') plt.semilogy(X, Y, 'rx') plt.show() plt.figure() plt.plot(x_test, y_hat, 'b.-', label='predicted') plt.plot(X, Y, 'rx', label='sample points') plt.title("Predicted y vs x (linear scale)") plt.legend() Explanation: Now there are still badly fitting spikes, but there peaks start to all go down... The "noise energy" is getting spread across higher frequencies, and the average misfit to the truth goes down. Harmless overfitting? n = 10m Way more parameters: now use 10 times the number of parameters as data points End of explanation orders = list(range(0, m)) + list(np.logspace(np.log10(m), np.log10(8*m), 10).astype(int)) ns = 2*np.array(orders) + 1 # print(ns) misfits = [] for order in orders: x_test, y_hat, misfit = fit(X, Y, order, print_misfit=False) misfits.append(misfit) interp_thresh = m plt.figure(); plt.semilogy(ns, misfits, '.-') plt.semilogy(np.ones(5) * interp_thresh, np.linspace(0, np.max(misfits), 5), 'k-', label='interpolation threshold') plt.ylabel("Average error") plt.xlabel("Number of sin/cosine terms used to fit") plt.legend() Explanation: Show the misfit as a function of number of sin/cos terms End of explanation import torch import torch.nn as nn import torch.nn.functional as F nwide = 1000 class Net(nn.Module): def __init__(self): super(Net, self).__init__() # an affine operation: y = Wx + b self.fc1 = nn.Linear(1, nwide) self.fc2 = nn.Linear(nwide, nwide) self.fc3 = nn.Linear(nwide, 1) def forward(self, x): # x = F.relu(self.fc1(x)) # x = F.relu(self.fc2(x)) # x = self.fc1(x) # x = self.fc2(x) # x = torch.tanh(self.fc1(x)) # x = torch.tanh(self.fc2(x)) x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() print(net) import torch.optim as optim inp = torch.Tensor(X.reshape(-1, 1)) target = torch.Tensor(Y).view(-1, 1) criterion = nn.MSELoss() # create your optimizer optimizer = optim.SGD(net.parameters(), lr=0.01) num_epochs = 5000 for epoch in range(num_epochs): # in your training loop: optimizer.zero_grad() # zero the gradient buffers output = net(inp) loss = criterion(output, target) loss.backward() optimizer.step() # Does the update if epoch % 500 == 0: print(f"{epoch = }, {loss.item() = }") plt.figure() x_test = np.linspace(0, X_MAX, 500).reshape(-1, 1) y_test = net(torch.Tensor(x_test)).detach().numpy() # xx, yy = inp.detach().numpy(), output.detach().numpy() plt.plot(x_test, y_test, 'b.-') plt.semilogy(x_test, y_test, 'b.-') plt.semilogy(X, Y, 'rx') plt.figure() plt.plot(x_test, y_test, 'b.-') plt.plot(X, Y, 'rx') Explanation: References [1] Muthukumar, Vidya, et al. "Harmless interpolation of noisy data in regression." IEEE Journal on Selected Areas in Information Theory (2020). The final figure is replicating one case from Figure 2: https://arxiv.org/pdf/1903.09139.pdf Random extra test: Fitting with a wide neural network TODO: check similar "average error" graph as above with a NN of increasing width End of explanation
5,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Multiple Kernel Learning By Saurabh Mahindre - <a href="https Step1: Introduction <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. Kernel 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> Selecting the kernel function $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. In shogun the CMKL is the base class for MKL. We can do classifications Step2: Prediction on toy data In 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. Step3: Generating Kernel weights Just 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. Step4: Binary classification using MKL Now 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. Step5: 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. Step6: 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. Step7: MKL for knowledge discovery MKL 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. Step8: These are the type of circles we want to distinguish between. We can try classification with a constant separation between the circles first. Step9: 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). Step10: 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 Step11: Let's plot five of the examples to get a feel of the dataset. Step12: We combine a Gaussian kernel and a PolyKernel. To test, examples not included in training data are used. This 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. Step13: 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. One-class classification using MKL One-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. Step14: Now that everything is initialized, let's see MKLOneclass in action by applying it on the test data and on the X-Y grid.
Python Code: %pylab inline %matplotlib inline import os SHOGUN_DATA_DIR=os.getenv('SHOGUN_DATA_DIR', '../../../data') # import all shogun classes from modshogun import * Explanation: Multiple Kernel Learning By Saurabh Mahindre - <a href="https://github.com/Saurabh7">github.com/Saurabh7</a> This 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. Introduction Mathematical formulation Using a Combined kernel Example: Toy Data Generating Kernel weights Binary classification using MKL MKL for knowledge discovery Multiclass classification using MKL One-class classification using MKL End of explanation kernel = CombinedKernel() Explanation: Introduction <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. Kernel 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> Selecting the kernel function $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. In shogun the CMKL is the base class for MKL. We can do classifications: binary, one-class, multiclass and regression too: regression. Mathematical formulation (skip if you just want code examples) </br>In a SVM, defined as: $$f({\bf x})=\text{sign} \left(\sum_{i=0}^{N-1} \alpha_i k({\bf x}, {\bf x_i})+b\right)$$</br> where ${\bf x_i},{i = 1,...,N}$ are labeled training examples ($y_i \in {±1}$). One could make a combination of kernels like: $${\bf k}(x_i,x_j)=\sum_{k=0}^{K} \beta_k {\bf k_k}(x_i, x_j)$$ where $\beta_k > 0$ and $\sum_{k=0}^{K} \beta_k = 1$ In the multiple kernel learning problem for binary classification one is given $N$ data points ($x_i, y_i$ ) ($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. In MKL $\alpha_i$,$\beta$ and bias are determined by solving the following optimization program. For details see [1]. $$\mbox{min} \hspace{4mm} \gamma-\sum_{i=1}^N\alpha_i$$ $$ \mbox{w.r.t.} \hspace{4mm} \gamma\in R, \alpha\in R^N \nonumber$$ $$\mbox {s.t.} \hspace{4mm} {\bf 0}\leq\alpha\leq{\bf 1}C,\;\;\sum_{i=1}^N \alpha_i y_i=0 \nonumber$$ $$ {\frac{1}{2}\sum_{i,j=1}^N \alpha_i \alpha_j y_i y_j \leq \gamma}, \forall k=1,\ldots,K\nonumber\ $$ Here C is a pre-specified regularization parameter. Within shogun this optimization problem is solved using semi-infinite programming. For 1-norm MKL one of the two approaches described in [1] is used. The 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. The second much faster but also more memory demanding approach performing interleaved optimization, is integrated into the chunking-based SVMlight. Using a Combined kernel Shogun 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 End of explanation num=30; num_components=4 means=zeros((num_components, 2)) means[0]=[-1,1] means[1]=[2,-1.5] means[2]=[-1,-3] means[3]=[2,1] covs=array([[1.0,0.0],[0.0,1.0]]) gmm=GMM(num_components) [gmm.set_nth_mean(means[i], i) for i in range(num_components)] [gmm.set_nth_cov(covs,i) for i in range(num_components)] gmm.set_coef(array([1.0,0.0,0.0,0.0])) xntr=array([gmm.sample() for i in xrange(num)]).T xnte=array([gmm.sample() for i in xrange(5000)]).T gmm.set_coef(array([0.0,1.0,0.0,0.0])) xntr1=array([gmm.sample() for i in xrange(num)]).T xnte1=array([gmm.sample() for i in xrange(5000)]).T gmm.set_coef(array([0.0,0.0,1.0,0.0])) xptr=array([gmm.sample() for i in xrange(num)]).T xpte=array([gmm.sample() for i in xrange(5000)]).T gmm.set_coef(array([0.0,0.0,0.0,1.0])) xptr1=array([gmm.sample() for i in xrange(num)]).T xpte1=array([gmm.sample() for i in xrange(5000)]).T traindata=concatenate((xntr,xntr1,xptr,xptr1), axis=1) trainlab=concatenate((-ones(2*num), ones(2*num))) testdata=concatenate((xnte,xnte1,xpte,xpte1), axis=1) testlab=concatenate((-ones(10000), ones(10000))) #convert to shogun features and generate labels for data feats_train=RealFeatures(traindata) labels=BinaryLabels(trainlab) _=jet() figure(figsize(18,5)) subplot(121) # plot train data _=scatter(traindata[0,:], traindata[1,:], c=trainlab, s=100) title('Toy data for classification') axis('equal') colors=["blue","blue","red","red"] # a tool for visualisation from matplotlib.patches import Ellipse def get_gaussian_ellipse_artist(mean, cov, nstd=1.96, color="red", linewidth=3): vals, vecs = eigh(cov) order = vals.argsort()[::-1] vals, vecs = vals[order], vecs[:, order] theta = numpy.degrees(arctan2(*vecs[:, 0][::-1])) width, height = 2 * nstd * sqrt(vals) e = Ellipse(xy=mean, width=width, height=height, angle=theta, \ edgecolor=color, fill=False, linewidth=linewidth) return e for i in range(num_components): gca().add_artist(get_gaussian_ellipse_artist(means[i], covs, color=colors[i])) Explanation: Prediction on toy data In 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. End of explanation width0=0.5 kernel0=GaussianKernel(feats_train, feats_train, width0) width1=25 kernel1=GaussianKernel(feats_train, feats_train, width1) #combine kernels kernel.append_kernel(kernel0) kernel.append_kernel(kernel1) kernel.init(feats_train, feats_train) mkl = MKLClassification() #set the norm, weights sum to 1. mkl.set_mkl_norm(1) mkl.set_C(1, 1) mkl.set_kernel(kernel) mkl.set_labels(labels) #train to get weights mkl.train() w=kernel.get_subkernel_weights() print w Explanation: Generating Kernel weights Just 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. End of explanation size=100 x1=linspace(-5, 5, size) x2=linspace(-5, 5, size) x, y=meshgrid(x1, x2) #Generate X-Y grid test data grid=RealFeatures(array((ravel(x), ravel(y)))) kernel0t=GaussianKernel(feats_train, grid, width0) kernel1t=GaussianKernel(feats_train, grid, width1) kernelt=CombinedKernel() kernelt.append_kernel(kernel0t) kernelt.append_kernel(kernel1t) #initailize with test grid kernelt.init(feats_train, grid) mkl.set_kernel(kernelt) #prediction grid_out=mkl.apply() z=grid_out.get_values().reshape((size, size)) figure(figsize=(10,5)) title("Classification using MKL") c=pcolor(x, y, z) _=contour(x, y, z, linewidths=1, colors='black', hold=True) _=colorbar(c) Explanation: Binary classification using MKL Now 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. End of explanation z=grid_out.get_labels().reshape((size, size)) # MKL figure(figsize=(20,5)) subplot(131, title="Multiple Kernels combined") c=pcolor(x, y, z) _=contour(x, y, z, linewidths=1, colors='black', hold=True) _=colorbar(c) comb_ker0=CombinedKernel() comb_ker0.append_kernel(kernel0) comb_ker0.init(feats_train, feats_train) mkl.set_kernel(comb_ker0) mkl.train() comb_ker0t=CombinedKernel() comb_ker0t.append_kernel(kernel0) comb_ker0t.init(feats_train, grid) mkl.set_kernel(comb_ker0t) out0=mkl.apply() # subkernel 1 z=out0.get_labels().reshape((size, size)) subplot(132, title="Kernel 1") c=pcolor(x, y, z) _=contour(x, y, z, linewidths=1, colors='black', hold=True) _=colorbar(c) comb_ker1=CombinedKernel() comb_ker1.append_kernel(kernel1) comb_ker1.init(feats_train, feats_train) mkl.set_kernel(comb_ker1) mkl.train() comb_ker1t=CombinedKernel() comb_ker1t.append_kernel(kernel1) comb_ker1t.init(feats_train, grid) mkl.set_kernel(comb_ker1t) out1=mkl.apply() # subkernel 2 z=out1.get_labels().reshape((size, size)) subplot(133, title="kernel 2") c=pcolor(x, y, z) _=contour(x, y, z, linewidths=1, colors='black', hold=True) _=colorbar(c) Explanation: 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. End of explanation kernelt.init(feats_train, RealFeatures(testdata)) mkl.set_kernel(kernelt) out=mkl.apply() evaluator=ErrorRateMeasure() print "Test error is %2.2f%% :MKL" % (100*evaluator.evaluate(out,BinaryLabels(testlab))) comb_ker0t.init(feats_train,RealFeatures(testdata)) mkl.set_kernel(comb_ker0t) out=mkl.apply() evaluator=ErrorRateMeasure() print "Test error is %2.2f%% :Subkernel1"% (100*evaluator.evaluate(out,BinaryLabels(testlab))) comb_ker1t.init(feats_train, RealFeatures(testdata)) mkl.set_kernel(comb_ker1t) out=mkl.apply() evaluator=ErrorRateMeasure() print "Test error is %2.2f%% :subkernel2" % (100*evaluator.evaluate(out,BinaryLabels(testlab))) Explanation: 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. End of explanation def circle(x, radius, neg): y=sqrt(square(radius)-square(x)) if neg: return[x, -y] else: return [x,y] def get_circle(radius): neg=False range0=linspace(-radius,radius,100) pos_a=array([circle(i, radius, neg) for i in range0]).T neg=True neg_a=array([circle(i, radius, neg) for i in range0]).T c=concatenate((neg_a,pos_a), axis=1) return c def get_data(r1, r2): c1=get_circle(r1) c2=get_circle(r2) c=concatenate((c1, c2), axis=1) feats_tr=RealFeatures(c) return c, feats_tr l=concatenate((-ones(200),ones(200))) lab=BinaryLabels(l) #get two circles with radius 2 and 4 c, feats_tr=get_data(2,4) c1, feats_tr1=get_data(2,3) _=gray() figure(figsize=(10,5)) subplot(121) title("Circles with different separation") p=scatter(c[0,:], c[1,:], c=lab) subplot(122) q=scatter(c1[0,:], c1[1,:], c=lab) Explanation: MKL for knowledge discovery MKL 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. End of explanation def train_mkl(circles, feats_tr): #Four kernels with different widths kernel0=GaussianKernel(feats_tr, feats_tr, 1) kernel1=GaussianKernel(feats_tr, feats_tr, 5) kernel2=GaussianKernel(feats_tr, feats_tr, 7) kernel3=GaussianKernel(feats_tr, feats_tr, 10) kernel = CombinedKernel() kernel.append_kernel(kernel0) kernel.append_kernel(kernel1) kernel.append_kernel(kernel2) kernel.append_kernel(kernel3) kernel.init(feats_tr, feats_tr) mkl = MKLClassification() mkl.set_mkl_norm(1) mkl.set_C(1, 1) mkl.set_kernel(kernel) mkl.set_labels(lab) mkl.train() w=kernel.get_subkernel_weights() return w, mkl def test_mkl(mkl, grid): kernel0t=GaussianKernel(feats_tr, grid, 1) kernel1t=GaussianKernel(feats_tr, grid, 5) kernel2t=GaussianKernel(feats_tr, grid, 7) kernel3t=GaussianKernel(feats_tr, grid, 10) kernelt = CombinedKernel() kernelt.append_kernel(kernel0t) kernelt.append_kernel(kernel1t) kernelt.append_kernel(kernel2t) kernelt.append_kernel(kernel3t) kernelt.init(feats_tr, grid) mkl.set_kernel(kernelt) out=mkl.apply() return out size=50 x1=linspace(-10, 10, size) x2=linspace(-10, 10, size) x, y=meshgrid(x1, x2) grid=RealFeatures(array((ravel(x), ravel(y)))) w, mkl=train_mkl(c, feats_tr) print w out=test_mkl(mkl,grid) z=out.get_values().reshape((size, size)) figure(figsize=(5,5)) c=pcolor(x, y, z) _=contour(x, y, z, linewidths=1, colors='black', hold=True) title('classification with constant separation') _=colorbar(c) Explanation: These are the type of circles we want to distinguish between. We can try classification with a constant separation between the circles first. End of explanation range1=linspace(5.5,7.5,50) x=linspace(1.5,3.5,50) temp=[] for i in range1: #vary separation between circles c, feats=get_data(4,i) w, mkl=train_mkl(c, feats) temp.append(w) y=array([temp[i] for i in range(0,50)]).T figure(figsize=(20,5)) _=plot(x, y[0,:], color='k', linewidth=2) _=plot(x, y[1,:], color='r', linewidth=2) _=plot(x, y[2,:], color='g', linewidth=2) _=plot(x, y[3,:], color='y', linewidth=2) title("Comparison between kernel widths and weights") ylabel("Weight") xlabel("Distance between circles") _=legend(["1","5","7","10"]) Explanation: 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). End of explanation from scipy.io import loadmat, savemat from os import path, sep mat = loadmat(sep.join(['..','..','..','data','multiclass', 'usps.mat'])) Xall = mat['data'] Yall = array(mat['label'].squeeze(), dtype=double) # map from 1..10 to 0..9, since shogun # requires multiclass labels to be # 0, 1, ..., K-1 Yall = Yall - 1 random.seed(0) subset = random.permutation(len(Yall)) #get first 1000 examples Xtrain = Xall[:, subset[:1000]] Ytrain = Yall[subset[:1000]] Nsplit = 2 all_ks = range(1, 21) print Xall.shape print Xtrain.shape Explanation: 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. Multiclass classification using MKL MKL 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. To 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. End of explanation def plot_example(dat, lab): for i in xrange(5): ax=subplot(1,5,i+1) title(int(lab[i])) ax.imshow(dat[:,i].reshape((16,16)), interpolation='nearest') ax.set_xticks([]) ax.set_yticks([]) _=figure(figsize=(17,6)) gray() plot_example(Xtrain, Ytrain) Explanation: Let's plot five of the examples to get a feel of the dataset. End of explanation # MKL training and output labels = MulticlassLabels(Ytrain) feats = RealFeatures(Xtrain) #get test data from 5500 onwards Xrem=Xall[:,subset[5500:]] Yrem=Yall[subset[5500:]] #test features not used in training feats_rem=RealFeatures(Xrem) labels_rem=MulticlassLabels(Yrem) kernel = CombinedKernel() feats_train = CombinedFeatures() feats_test = CombinedFeatures() #append gaussian kernel subkernel = GaussianKernel(10,15) feats_train.append_feature_obj(feats) feats_test.append_feature_obj(feats_rem) kernel.append_kernel(subkernel) #append PolyKernel feats = RealFeatures(Xtrain) subkernel = PolyKernel(10,2) feats_train.append_feature_obj(feats) feats_test.append_feature_obj(feats_rem) kernel.append_kernel(subkernel) kernel.init(feats_train, feats_train) mkl = MKLMulticlass(1.2, kernel, labels) mkl.set_epsilon(1e-2) mkl.set_mkl_epsilon(0.001) mkl.set_mkl_norm(1) mkl.train() #initialize with test features kernel.init(feats_train, feats_test) out = mkl.apply() evaluator = MulticlassAccuracy() accuracy = evaluator.evaluate(out, labels_rem) print "Accuracy = %2.2f%%" % (100*accuracy) idx=where(out.get_labels() != Yrem)[0] Xbad=Xrem[:,idx] Ybad=Yrem[idx] _=figure(figsize=(17,6)) gray() plot_example(Xbad, Ybad) w=kernel.get_subkernel_weights() print w # Single kernel:PolyKernel C=1 pk=PolyKernel(10,2) svm=GMNPSVM(C, pk, labels) _=svm.train(feats) out=svm.apply(feats_rem) evaluator = MulticlassAccuracy() accuracy = evaluator.evaluate(out, labels_rem) print "Accuracy = %2.2f%%" % (100*accuracy) idx=np.where(out.get_labels() != Yrem)[0] Xbad=Xrem[:,idx] Ybad=Yrem[idx] _=figure(figsize=(17,6)) gray() plot_example(Xbad, Ybad) #Single Kernel:Gaussian kernel width=15 C=1 gk=GaussianKernel() gk.set_width(width) svm=GMNPSVM(C, gk, labels) _=svm.train(feats) out=svm.apply(feats_rem) evaluator = MulticlassAccuracy() accuracy = evaluator.evaluate(out, labels_rem) print "Accuracy = %2.2f%%" % (100*accuracy) idx=np.where(out.get_labels() != Yrem)[0] Xbad=Xrem[:,idx] Ybad=Yrem[idx] _=figure(figsize=(17,6)) gray() plot_example(Xbad, Ybad) Explanation: We combine a Gaussian kernel and a PolyKernel. To test, examples not included in training data are used. This 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. End of explanation X = -0.3 * random.randn(100,2) traindata=r_[X + 2, X - 2].T X = -0.3 * random.randn(20, 2) testdata = r_[X + 2, X - 2].T trainlab=concatenate((ones(99),-ones(1))) #convert to shogun features and generate labels for data feats=RealFeatures(traindata) labels=BinaryLabels(trainlab) xx, yy = meshgrid(linspace(-5, 5, 500), linspace(-5, 5, 500)) grid=RealFeatures(array((ravel(xx), ravel(yy)))) #test features feats_t=RealFeatures(testdata) x_out=(random.uniform(low=-4, high=4, size=(20, 2))).T feats_out=RealFeatures(x_out) kernel=CombinedKernel() feats_train=CombinedFeatures() feats_test=CombinedFeatures() feats_test_out=CombinedFeatures() feats_grid=CombinedFeatures() #append gaussian kernel subkernel=GaussianKernel(10,8) feats_train.append_feature_obj(feats) feats_test.append_feature_obj(feats_t) feats_test_out.append_feature_obj(feats_out) feats_grid.append_feature_obj(grid) kernel.append_kernel(subkernel) #append PolyKernel feats = RealFeatures(traindata) subkernel = PolyKernel(10,3) feats_train.append_feature_obj(feats) feats_test.append_feature_obj(feats_t) feats_test_out.append_feature_obj(feats_out) feats_grid.append_feature_obj(grid) kernel.append_kernel(subkernel) kernel.init(feats_train, feats_train) mkl = MKLOneClass() mkl.set_kernel(kernel) mkl.set_labels(labels) mkl.set_interleaved_optimization_enabled(False) mkl.set_epsilon(1e-2) mkl.set_mkl_epsilon(0.1) mkl.set_mkl_norm(1) Explanation: 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. One-class classification using MKL One-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. End of explanation mkl.train() print "Weights:" w=kernel.get_subkernel_weights() print w #initialize with test features kernel.init(feats_train, feats_test) normal_out = mkl.apply() #test on abnormally generated data kernel.init(feats_train, feats_test_out) abnormal_out = mkl.apply() #test on X-Y grid kernel.init(feats_train, feats_grid) grid_out=mkl.apply() z=grid_out.get_values().reshape((500,500)) z_lab=grid_out.get_labels().reshape((500,500)) a=abnormal_out.get_labels() n=normal_out.get_labels() #check for normal and abnormal classified data idx=where(normal_out.get_labels() != 1)[0] abnormal=testdata[:,idx] idx=where(normal_out.get_labels() == 1)[0] normal=testdata[:,idx] figure(figsize(15,6)) pl =subplot(121) title("One-class classification using MKL") _=pink() c=pcolor(xx, yy, z) _=contour(xx, yy, z_lab, linewidths=1, colors='black', hold=True) _=colorbar(c) p1=pl.scatter(traindata[0, :], traindata[1,:], cmap=gray(), s=100) p2=pl.scatter(normal[0,:], normal[1,:], c="red", s=100) p3=pl.scatter(abnormal[0,:], abnormal[1,:], c="blue", s=100) p4=pl.scatter(x_out[0,:], x_out[1,:], c=a, cmap=jet(), s=100) _=pl.legend((p1, p2, p3), ["Training samples", "normal samples", "abnormal samples"], loc=2) subplot(122) c=pcolor(xx, yy, z) title("One-class classification output") _=gray() _=contour(xx, yy, z, linewidths=1, colors='black', hold=True) _=colorbar(c) Explanation: Now that everything is initialized, let's see MKLOneclass in action by applying it on the test data and on the X-Y grid. End of explanation
5,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Ant Colony Optimization for Energy Systems Research This notebook explores using Ant Colony Optimization to solve the combinatorial optimization problem of optimally configuring a branch of an energy system. NOTICE The implementation in this document is flawed. First, my 'Ant Colony Optimization' optimization does in no way correspond to the state of the art. This combines badly with an error in the heuristic I used Step1: The above expression was obtained by solving the equation for $P_{th}$ and $E_{th}$ for $\ln{P_{el}}$. The resulting equation is thus of the form $\ln{x} = f(x)$, where $f$ is a rational function in $x$. This can only be solved numerically. The following function uses scipy.optimize.brentq to solve the aforementioned equation (numpy.vectorize as the input is going to be the energy demand vector E_therm). Step2: With the above definitions computing the annual biogas demand is straight-forward Step3: With that, we are now able to find a suitable plant for a building whose annual thermal energy demand is known. What is more, we can also compute the amount of biogas that particular plant will need over the year. With that, we are able to start designing swarms. Sample building list Of course first, we need a building list to actually design plants against. Here, purely synthetic data will be used, based on the assumptions Step4: Optimization process As mentioned in the introduction, the objective in the following will be to find a set of $N$ buildings that, when equipped with CHPPs both optimize total swarm operation costs (presuming all biogas has to be bought at the beginning of the period). Now we proceed to a formal mathematical formulation. We note Step5: Let's assume the biogas potential is enough to cover 10% of the demand Step6: Manual solution To get an idea of what awaits, we try a manual optimization. The graph below shows the total fuel use of a swarm composed of the $N$ most powerful engines that can be installed. Step7: The profits associated to such a configuration are shown below Step8: Ant Colony Optimization (ACO) For a general overview, and as a general reference for this section, see Dorigo and Stülze, 2004. The Ant Colony Optimization algorithm mimmicks the food gathering behavior of an ant colony - a prominent example of swarm intelligence. Indeed, individually, ants are neither very smart, nor do they have a capacity to communicate complex information such as the shortest path to a food resource. Still, collectively, the logistic operations of an ant hill are highly structured and very efficient (in terms of distance travelled). In the common model thinking, ants achieve this through swarm intelligence Step9: With individual ant behavior implemented, we now need to construct the "ant system" around it. The latter primarily consists of the shared "trail vector" $\tau$, storing the pheromone concentration assigned to (in this implementation) each site. Furthermore, the ant system takes care of the control flow, which comprises Step10: The following plot shows the pheromone levels of each node, as a function of its electrical nominal output power. IT is very clear that very powerful nodes are more desirable to have in a swarm. This is an indication that the optimization works! Step11: Results So let's see what this produces. The best solution from all candidate solutions seems to indeed be the extremum on what could very well be a normal distribution - that's promising. Step12: Looking at the swarm composition, it seems to include a couple of larger devices, and a portfolio of smaller machines. Step13: If we try to build a swarm manually, starting with the biggest machines Step14: Now it seems that, with the current implementation, the swarm converges to larger and larger CHPPs, as the number of iterations is increased. It seems that the revenues it finds are actually higher than what the initial manual calculation indicated - stemming from a better fuel utilization Step15: Systematic investigation With those promising results, it is time to look into computational efforts (although I have not at all profiled the code yet) and convergence. In the following, a number of simulations with increasing number of iterations will be run, wall-clock times will be measured and both fuel utilization and revenues will be used as quality indicators for the solutions. Note that evaluation is automated in the wrapper below Step16: There is definitely convergence; a more or less stable result can be found after some 1000 iterations. The amount of unburnt fuel seems to fluctuate, however even $300 kWh$ is a minimal amount compared to $E_{tot}$. Nevertheless, also in the convergence plot (left) there is definitely some fluctuation beyond 1000 iterations. This is probably due to the stochastic nature of the algorithm. Closing thoughts With fairly little effort, an Ant Colony Optimization based combinatorial problem solver was implemented in Python. With any optimizations having been done thus far, the solver was able to produce sensible results on a problem set involving 1000 buildings in under 5 minutes. That is very reasonable, considering that the the search space is theoretically composed of all possible subsets of $N=1000$ elements, i.e. the combinations of 1, 2, ... and 1000 buildings. In other words, a priori, the number of candidate solutions is a staggering Step17: Now at its core, the ACO uses sampling of random subsets, very much as a brute-force approach would. However, by giving the "ants" heuristic knowledge of the problem, and of course by the swarm intelligence, the number of candidate solutions that have to be investigated comes down to several 10'000 Step18: It is worth noting that the ACO implementation was able to improve on the solution of our initial heuristic approach, which was maximizing revenues by only chosing the largest, i.e. most efficient, CHP production sites. The ACO seems to do the same, but it further includes a few mcuh smaller plants to simultaneously maximize fuel utilization. It was feared that this might destabilize the solver. Indeed there are many, more or less equivalent small sites to chose from. That apparently did not hinder convergence, although it may explain the fluctuations after convergence at $N_{iter} > 10^3$. In any case, ACO appears to be a very attractive method for solving our energy-system composition combinatorial optimization problem. Of course some further testing is mandated, as well as the exploration of Particle Swarm Optimization. Addendum
Python Code: a, b, P_el = sympy.symbols("a b P_el ") eta_el = a * sympy.log(P_el) + b t_op, E_th, eta_th = sympy.symbols("t_op E_th eta_th") P_th = P_el / eta_el * (1 - eta_el) * eta_th sols = sympy.solve(sympy.Eq(P_th, E_th/t_op), sympy.log(P_el)) assert len(sols) == 1 sols[0] Explanation: Ant Colony Optimization for Energy Systems Research This notebook explores using Ant Colony Optimization to solve the combinatorial optimization problem of optimally configuring a branch of an energy system. NOTICE The implementation in this document is flawed. First, my 'Ant Colony Optimization' optimization does in no way correspond to the state of the art. This combines badly with an error in the heuristic I used: since I did not include investment costs in the model, and since heat is significantly more valuable than electricity, large CHPPs are actually not economically beneficial (as the heuristic presumes). There is thus a much more profitable swarm that can be found using general purpose solvers (as we discovered when using Particle Swarm Optimization in Pol Duhr's BT). To address this, towards the end an IP approach using Gurobi was added as an illustration. The performance of branch and bound seems much better than that of ant-searc - of course one would have to redo the whole calculation and adjust the implementation of the 'Ant' class to get a fair comparison. I may adjust all of this at a later time - for now, this current version has to do, even though it is somewhat messy. Problem setting This notebook illustrates the procedure on a simplified version of the decentralized energy provision problem the Energy Systems Group solves in the CHPswarm project: a list of buildings and their annual thermal energy demand (for space heating and warm water supply) is given. Each building is a potential installation site for a CHP plant - per our modeling paradigm, plants are designed so as to be completely (at all times and without the need for auxiliary heaters) satisfy the local heat demand. However, the number of production sites is limited: to ensure sustainability, individual plants may only burn biogas; the supply of which is finite. Now the challenge is to build a swarm, i.e. select a subset of production sites that, collectively, optimally utilize the biogas potential at minimal costs. These distinct objectives can be unified by combined by assuming that swarm operator buys all the available fuel ahead of time, so that being left with unburnt fuel at the end of the booking period becomes an economic inefficienc (the net worth of the fuel is not considered). Note that many important aspects to the "CHP swarm" problem are ignored here, to keep this demonstration lean and focused on the actual Ant Colony Optimization. The results from this study should in no way be considered representative as an assessment of CHP technology or decentralized energy provision. Mathematical analysis Abstractly speaking, the problem at hand is a variant of the Knapsack problem (in short: which items to pack into a bag of finite volume, if each item has a given volume and worth, if the goal is to maximize the total worth of the cargo). Model formulation Modeling is kept simple in this example: the total thermal energy demand of each building is given via the vector E_therm - which is just randomly generated assuming a normally distributed average heat demand per square meter and a normally distributed building surface area. We further assume that plants are designed so as to reach an annual operation time of $t_{op}=200h$ (outside that period, power is provided via an adiabatic buffer), which defines their nominal power rating. This is in accordance of our modeling paradigm of maximizing exergy efficiency; in other words, plants may not be run at part-load. Instead they operate at maximum efficiency (generally higher than the average thermal power demand), buffering the excess production in a suitable storage device (generally a hot water tank). The maximum overall efficiency (fuel to electricity) follows the following approximation (see annual report): $$\eta_{el} = 2.43\cdot 10^{-2} \cdot \ln{\left(P_{el}\right)} + 2.42 \cdot 10^{-1} $$ Finally, it is assumed that $\eta_{th}=90\%$ of the waste heat stream from the engine are effectively available for heating. Now, the thermal output power $P_{th}$ is related to the annual thermal energy demand $E_{th}$ via the annual operation time $t_{op}$: $$ \frac{E_{th}}{t_{op}} = P_{th} = \frac{P_{el}}{\eta_{el}\left(P_{el}\right)} \cdot \left(1 - \eta_{el}\left(P_{el}\right)\right) \cdot \eta_{th} $$ End of explanation def eta_el(P_el): return 2.43e-2*np.log(P_el) + 2.421e-1 def design_CHP(E_th, t_op=200*3600.): P_th_avg = E_th/t_op def f(P_el): P_th = P_el * (1/eta_el(P_el) - 1) * 0.9 return P_th - P_th_avg return scipy.optimize.brentq(f, 1, 10e6) design_CHP = np.vectorize(design_CHP) Explanation: The above expression was obtained by solving the equation for $P_{th}$ and $E_{th}$ for $\ln{P_{el}}$. The resulting equation is thus of the form $\ln{x} = f(x)$, where $f$ is a rational function in $x$. This can only be solved numerically. The following function uses scipy.optimize.brentq to solve the aforementioned equation (numpy.vectorize as the input is going to be the energy demand vector E_therm). End of explanation def annual_biogas_demand(P_el, t_op=200*3600.): return P_el / eta_el(P_el) * t_op Explanation: With the above definitions computing the annual biogas demand is straight-forward: End of explanation def load_region(N_b=1e3): e_therm = scipy.stats.weibull_min(1.8, 0, 100).ppf(np.random.rand(N_b)) * 3.6e6 A_build = scipy.stats.weibull_min(1.8, 0, 200).ppf(np.random.rand(N_b)) return e_therm * A_build E_th = load_region(5e5) ax = plt.subplot(111) ax.hist(E_th / 3.6e9, bins=30) ax.set_xlabel("thermal energy demand [MWh]") ax.set_ylabel("building count [-]"); ax = plt.subplot(111) ax.hist(design_CHP(E_th)*1e-3, bins=60) ax.set_xlabel("nominal electrical power output [kW]"); Explanation: With that, we are now able to find a suitable plant for a building whose annual thermal energy demand is known. What is more, we can also compute the amount of biogas that particular plant will need over the year. With that, we are able to start designing swarms. Sample building list Of course first, we need a building list to actually design plants against. Here, purely synthetic data will be used, based on the assumptions: the annual energy demand per unit surface varies from $30 \ldots 300 \frac{kWh}{m^2}$ its distribution skews towards lower values the surface are for various building types varies from $80 \ldots 2000 m^2$ its distribution skews towards the lower end End of explanation t_op = 200 * 3600. P_el = design_CHP(E_th, t_op=t_op) E_el = P_el * t_op E_fl = annual_biogas_demand(P_el, t_op=t_op) Explanation: Optimization process As mentioned in the introduction, the objective in the following will be to find a set of $N$ buildings that, when equipped with CHPPs both optimize total swarm operation costs (presuming all biogas has to be bought at the beginning of the period). Now we proceed to a formal mathematical formulation. We note: the index $i$ indicates that a quantity applies only to building $i$ $E_{th,i}$ is the cumulative annual thermal energy demand of building $i$ $P_{el,i}$ is the nominal electric output of the designed CHPP for building $i$ $E_{el,i} = P_{el,i} \cdot t_{op}$ is the annual electricity output (electricity) $E_{fl,i} = E_{el,i} \cdot \eta_{el}\left( P_{el,_i}\right)^{-1}$ is the annual fuel demand (chemical energy) $E_{tot}$ is the totally available amount of biogas (chemical energy) to all buildings $\nu_i$, a binary variable, indicates whether a CHPP is installed in building $i$; note that, for this problem formulation, the vector $\nu$ of all $\nu_i$ is a complete description of a CHP swarm The optimization target, as explained previously, is to maximize cost efficiency, assuming that the total available biogas potential $E_{tot}$ has to be bought in advance. Now let $c_{gas}$ be the biogas price, $c_{th}$ the heat energy retail price and $c_{el}$ the electricity retail price in monetary units per $kWh$. Then we can pose the problem: $$ \max_{\nu} \left(\sum_i \nu_i \cdot \left(E_{el,i} \cdot c_{el} + E_{th,i} \cdot c_{th} \right)\right) - E_{tot} \cdot c_{gas}$$ $$\text{subject to: } \sum_i \nu_i \cdot E_{fl, i} \le E_{tot} $$ With this simple formulation it is rather straight-forward to predict the outcome: the above cost-balance depends directly on the conversion ratios of the individual CHPPs: the more efficient the average CHPP, the more revenue can be generated from the available biogas potential $E_{tot}$. Since the efficiency of the conversion process increases with nominal electrical power (which increases with average thermal power), the revenue of a swarm is higher the higher the absolute energy-demand of the reunited sites. The optimal swarm(s) is thus a compromise between maximizing the revenues with the highest $E_{th,i}$ yet keeping the portfolio diverse enough to minimize the amount of unused fuel at the end of the period. End of explanation E_tot = np.sum(E_fl) * 1e-1 def CHPswarm_fuel_demand(swarm): return np.sum(np.take(E_fl, swarm)) def CHPswarm_production_revenues(swarm, c_el=0.07, c_th=0.11): E_el_swarm = np.take(E_el, swarm) E_th_swarm = np.take(E_th, swarm) return (E_el_swarm * c_el + E_el_swarm * c_th) / 3.6e6 def CHPswarm_cost_balance(swarm, c_gas=0.05, **kwargs): return np.sum(CHPswarm_production_revenues(swarm, **kwargs)) - E_tot / 3.6e6 * c_gas Explanation: Let's assume the biogas potential is enough to cover 10% of the demand: End of explanation idx = np.argsort(-P_el) ax = plt.subplot(111) fl_tot = np.cumsum(E_fl[idx]) ax.plot(fl_tot/3.6e12, '+') ax.plot([0, idx.shape[0]], [E_tot/3.6e12, E_tot/3.6e12], 'r') ax.set_xlim([0, 50]) ax.set_xlabel("number of CHPPs in the swarm") ax.set_ylabel("swarm-wide fuel consumption [MWh]") ax.set_ylim([0, 5]); idx_constr_opt = np.nonzero(fl_tot <= E_tot)[0][-1] ax.plot(idx_constr_opt, fl_tot[idx_constr_opt]/3.6e12, 'yo'); Explanation: Manual solution To get an idea of what awaits, we try a manual optimization. The graph below shows the total fuel use of a swarm composed of the $N$ most powerful engines that can be installed. End of explanation ax = plt.subplot(111) profits = np.cumsum(CHPswarm_production_revenues(idx)) - E_tot / 3.6e6 * 0.05 ax.plot(profits * 1e-6, '+') ax.set_xlabel("number of CHPPs in the swarm") ax.set_ylabel("swarm-wide profits [MCHF]") ax.set_xlim([0, 50]) ax.set_ylim([-.2, 1]) ax.plot(idx_constr_opt, profits[idx_constr_opt]*1e-6, 'yo'); print "profits = {:.2f} CHF".format(profits[idx_constr_opt]) manual_utilization = fl_tot[idx_constr_opt]/E_tot print "fuel uzilization: {:.2f} kWh of {:.2f} kWh total ({:.2f} %)".format(fl_tot[idx_constr_opt]/3.6e6, E_tot/3.6e6, manual_utilization*100) Explanation: The profits associated to such a configuration are shown below: End of explanation class Ant(object): def __init__(self, trail, initial_position=None): self.path = [] if initial_position is not None: self.path.append(int(initial_position)) self.trail = trail def worth(self): return CHPswarm_cost_balance(self.path) def chose_next_site(self): # viable next candidates E_fl_swarm = CHPswarm_fuel_demand(self.path) candidates = np.flatnonzero(E_fl_swarm + E_fl < E_tot) # eliminate already selected paths candidates = np.setdiff1d(candidates, self.path, assume_unique=True) # got a complete swarm if no more sites can be added if candidates.size==0: return # heuristic value --> just revenues: # since operation times are identical for all, the largest plant always gets to produce most # so there is no need to account for efficiency, e.g. by taking the fuel costs into consideration revenues = CHPswarm_production_revenues(candidates) # transition probabilities p = revenues * self.trail[candidates] p /= np.sum(p) return np.random.choice(candidates, size=1, p=p) def forage(self): next_site = self.chose_next_site() # nowhere to go = found a solution, give control back to ant system if next_site is None: raise FoundViableSolution(self) # continue foraging self.path.append(int(next_site)) class FoundViableSolution(Exception): def __init__(self, ant): self.path = frozenset(ant.path) self.score = ant.worth() Explanation: Ant Colony Optimization (ACO) For a general overview, and as a general reference for this section, see Dorigo and Stülze, 2004. The Ant Colony Optimization algorithm mimmicks the food gathering behavior of an ant colony - a prominent example of swarm intelligence. Indeed, individually, ants are neither very smart, nor do they have a capacity to communicate complex information such as the shortest path to a food resource. Still, collectively, the logistic operations of an ant hill are highly structured and very efficient (in terms of distance travelled). In the common model thinking, ants achieve this through swarm intelligence: initially, individual ants wander the surroundings of their colony more or less aimlessly (they forage). As soon as an ant encounters food, it gathers as much as it can carry and attempts to find its way back to the colony. In the following, we are going to assume that the ant remembers its path, and that it follows it back without deviation. On its way back, the ant secretes a special pheromon, leaving a chemical trail to the food resource. The pheromon entices another foraging ants to follow the same path - although they may deviate from it. Probabilistically, the liklihood of a foraging ant heading a certain direction increases with the pheromone concentration in that particular direction; but the pheromon evaporates over time. Given a large number of ants and enough time, this mechanism stabilizes along the most effective paths. The above describes the classical ACO algorithm used to find the shortest path in a weighted graph. Here, we try to essentially solve the Knapsack problem though, so the behavior of the "ants" has to be somewhat modified. From a problem-oriented perspective, the ants become swarm configurators: starting from an initial "swarm of one", each ant sequentially includes one more buildings from the list, until no other building could be added without violating the biogas constraint (total swarm consumption exceeding $E_{tot}$). The result is a viable candidate solution, denoted by $J_k$, in terms of the set of all building indices making up the candidate solution of ant $k$. As per the previous description, the ant now starts "heading back" to where it came from, deposing pheromone along the "way" $J_k$. where $J_k$ is the candidate solution generated by ant $k$. Practically, (for now) this translates to the "pheromone balance" $\tau_i$ at each building $i$ included in the candidate solution being increased by an amount $\Delta_t$, proportional to the score (cost-revenue balance) of the candidate solution. Note that before any pheromone is added to any $\tau_i$, evaporation is modeled by the equation: $$ \tau_{i}^{k + 1} = \tau_{i} \cdot (1 - \rho) $$ The decision of an "ant" to include a certain building over another is influenced by "pheromones": The latter is scored using the cost to revenue balance, and a "pheromon amount". With all of that, we define the 'Ant' class, basically as an agent: End of explanation def ant_system(N_ants=1000, N_iter=1000, trail=None, initial_pheromone_level=1e-3, rho=1e-2): # initialization: create trail and ants if trail is None: trail = np.ones(E_th.shape[0]) * initial_pheromone_level ants = [Ant(trail, i) for i in np.random.choice(trail.shape[0], size=N_ants)] solutions = dict() pb = progressbar.ProgressBar() pb.update(0) max_score = E_tot / 3.6e6 * 0.05 for z in xrange(N_iter): # foraging for ant in ants: try: ant.forage() except FoundViableSolution as s: solutions[frozenset(ant.path)] = s.score trail[ant.path] += s.score / max_score ant.path = [] # reset ant to empty path --> picks starting node iteself # evaporation trail *= (1 - rho) pb.update((z + 1)/float(N_iter)) pb.forced_update(1) return solutions pheromones = np.ones(E_th.shape[0]) * 1e-3 trail = ant_system(trail=pheromones) Explanation: With individual ant behavior implemented, we now need to construct the "ant system" around it. The latter primarily consists of the shared "trail vector" $\tau$, storing the pheromone concentration assigned to (in this implementation) each site. Furthermore, the ant system takes care of the control flow, which comprises: initialization of: the "trail", shared by all "ants", storing the pheromone levels (in this implementation, pheromone levels are attributed to individual sites, not the "edges" between a couple of buildings as often the case in ACO) $N_{ants}$ individual 'Ant' instances, evenly distributed to random starting positions throughout the entire search space repeat $N_{iter}$ times: for each ant, call the 'forage' method; that causes the ant to either select one more site or return to its original position apply pheromone evaporation (let $\tau_i^z$ denote the pheromone level at building $i$ during iteration $z$): $$ \tau_i^{z+1} = \tau_i^z \cdot (1 - \rho) $$ possibly reassign ants that just found a solution to other starting positions if their solution score is low select the ant with the highest scoring solution End of explanation ax = plt.subplot(111) ax2 = ax.twinx() ax2.plot(P_el*1e-3, pheromones, 'r+') ax.hist(design_CHP(E_th)*1e-3, bins=60) ax.set_xlabel("nominal electrical power at site [kW]") ax2.set_ylabel("pheromone level at end of run [a.u.]") ax.set_ylabel("number of sites [-]"); Explanation: The following plot shows the pheromone levels of each node, as a function of its electrical nominal output power. IT is very clear that very powerful nodes are more desirable to have in a swarm. This is an indication that the optimization works! End of explanation swarm, score = max(trail.iteritems(), key=lambda s: s[1]) plt.hist(list(trail.itervalues()), bins=60); score Explanation: Results So let's see what this produces. The best solution from all candidate solutions seems to indeed be the extremum on what could very well be a normal distribution - that's promising. End of explanation ax = plt.subplot(111) ax.hist(P_el*1e-3, bins=60); ax.hist(P_el[list(swarm)]*1e-3, bins=60, color="r"); Explanation: Looking at the swarm composition, it seems to include a couple of larger devices, and a portfolio of smaller machines. End of explanation print "fuel utilization: {:.2f} of {:.2f} kWh".format(CHPswarm_fuel_demand(list(swarm)) / 3.6e6, E_tot/3.6e6) Explanation: If we try to build a swarm manually, starting with the biggest machines: The fuel utilization seems to be very good: End of explanation s = "<table>" s += "<tr><th>method</th><th>revenues</th><th>utilization</th></td>" s += "<tr><td>manually</td><td>{:.2f} CHF</td><td>{:.4f} %</td></tr>".format(profits[idx_constr_opt], manual_utilization*100) s += "<tr><td>ant-search</td><td>{:.2f} CHF</td><td>{:.4f} %</td></tr>".format(score, CHPswarm_fuel_demand(list(swarm))/E_tot*100) IPython.display.HTML(s + "</table>") Explanation: Now it seems that, with the current implementation, the swarm converges to larger and larger CHPPs, as the number of iterations is increased. It seems that the revenues it finds are actually higher than what the initial manual calculation indicated - stemming from a better fuel utilization: End of explanation def ACO_run(**kwargs): t0 = time.clock() swarms = ant_system(**kwargs) score, swarm = 0, [] if swarms: swarm, score = max(swarms.iteritems(), key=lambda s: s[1]) return np.array([score, CHPswarm_fuel_demand(list(swarm)), time.clock() - t0]) results = np.array([ACO_run(N_iter=n) for n in np.logspace(2, 4, base=10, num=15, dtype=int)]) N_iter = np.logspace(2, 4, base=10, num=15, dtype=int) fig, ax = plt.subplots(1, 3, figsize=(12, 4)) ax[0].plot(N_iter, results[:, 0]*1e-3, '+') ax[0].plot([0, 10000], np.ones(2) * np.max(results[:, 0])*1e-3, 'c') ax[0].set_title("swarm revenues [kCHF]") ax[1].plot(N_iter, (E_tot-results[:, 1])/3.6e6, '+') ax[1].set_title("remaining, unburnt fuel [kWh]") ax[2].plot(N_iter, results[:, 2]/60., '+'); ax[2].set_title("wall-clock time [min]") for i in xrange(3): ax[i].set_xlabel("number of iterations [-]") ax[i].set_xscale("log") Explanation: Systematic investigation With those promising results, it is time to look into computational efforts (although I have not at all profiled the code yet) and convergence. In the following, a number of simulations with increasing number of iterations will be run, wall-clock times will be measured and both fuel utilization and revenues will be used as quality indicators for the solutions. Note that evaluation is automated in the wrapper below: End of explanation np.sum([scipy.misc.comb(1000, i+1) for i in xrange(1000)]) Explanation: There is definitely convergence; a more or less stable result can be found after some 1000 iterations. The amount of unburnt fuel seems to fluctuate, however even $300 kWh$ is a minimal amount compared to $E_{tot}$. Nevertheless, also in the convergence plot (left) there is definitely some fluctuation beyond 1000 iterations. This is probably due to the stochastic nature of the algorithm. Closing thoughts With fairly little effort, an Ant Colony Optimization based combinatorial problem solver was implemented in Python. With any optimizations having been done thus far, the solver was able to produce sensible results on a problem set involving 1000 buildings in under 5 minutes. That is very reasonable, considering that the the search space is theoretically composed of all possible subsets of $N=1000$ elements, i.e. the combinations of 1, 2, ... and 1000 buildings. In other words, a priori, the number of candidate solutions is a staggering: End of explanation print "{} candidate solutions were explored".format(len(trail)) Explanation: Now at its core, the ACO uses sampling of random subsets, very much as a brute-force approach would. However, by giving the "ants" heuristic knowledge of the problem, and of course by the swarm intelligence, the number of candidate solutions that have to be investigated comes down to several 10'000: End of explanation import gurobipy as grb m = grb.Model("energy_knapsack") # site selection indicator: x_i = 1 --> CHPP at site i X = [m.addVar(0.0, 1.0, vtype=grb.GRB.BINARY, name="x_{}".format(i)) for i in xrange(E_fl.shape[0])] m.update() # objective: gas expenditures + revenues from heat and electricity sales c_el=0.07 c_th=0.11 c_gas=0.05 rev = (E_el * c_el + E_th * c_th) / 3.6e6 m.setObjective(- E_tot / 3.6e6 * c_gas + grb.quicksum(rev[i] * x for i, x in enumerate(X))) m.update() # constraint: total amount of biogas m.addConstr(grb.quicksum(E_fl[i] * x for i, x in enumerate(X)) <= E_tot) # run model m.modelSense = grb.GRB.MAXIMIZE m.optimize() print "successfull" if m.status == grb.GRB.status.OPTIMAL else "failed" swarm = np.array([bool(x.X) for x in X]) ax = plt.subplot(111) bins = np.linspace(0, np.ceil(np.max(P_el)*1e-6)*1e3, 120) ax.hist(P_el*1e-3, bins=bins) ax.hist(P_el[swarm]*1e-3, bins=bins, color="r"); ax.set_xlim([0, 1000]); E_swarm = np.dot(E_fl, swarm) print "fuel utilization: {:.2f} of {:.2f} kWh ({:.2f} kWh or {:.7f} %)".format(E_swarm / 3.6e6, E_tot/3.6e6, (E_tot - E_swarm) / 3.6e6, E_swarm/E_tot * 100) Explanation: It is worth noting that the ACO implementation was able to improve on the solution of our initial heuristic approach, which was maximizing revenues by only chosing the largest, i.e. most efficient, CHP production sites. The ACO seems to do the same, but it further includes a few mcuh smaller plants to simultaneously maximize fuel utilization. It was feared that this might destabilize the solver. Indeed there are many, more or less equivalent small sites to chose from. That apparently did not hinder convergence, although it may explain the fluctuations after convergence at $N_{iter} > 10^3$. In any case, ACO appears to be a very attractive method for solving our energy-system composition combinatorial optimization problem. Of course some further testing is mandated, as well as the exploration of Particle Swarm Optimization. Addendum: using branch and bound (Gurobi 6.0) According to Paschos's "concepts of combinatorial optimization", the integer Knapsack problem can be efficiently solved using the "branc and bounds" approach. It traverses the binary decision tree constructed around the $N$ binary decision variables $x_i$, using a relaxation of the original integer problem (decision variables $x_i \in {0, 1}$) to a constrained linear problem (decision variables $\tilde{x}_i \in [0, 1]$) as a metric. End of explanation
5,345
Given the following text description, write Python code to implement the functionality described below step by step Description: Period Change (dpdt) Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). Step1: As always, let's do imports and initialize a new Bundle. Step2: In order to easily differentiate between the components in a light curve and in the orbits, we'll set the secondary temperature and the mass ratio. Step3: and set dpdt to an unrealistically large value so that we can easily see the effect over just a few orbits. Step4: We'll add several light curve, RV, and orbit datasets, each covering successive cycles of the orbit so that we can differentiate between them later when plotting. Step5: It is important to note that the dpdt parameter is the time-derivative of period (the anomalistic period). However, the anomalistic and sidereal periods are only different in the case of apsidal motion. Step6: Zero-point for orbital period The orbital period itself, period, is defined at time t0 (in the system context). If the dataset times are far from t0@system then we begin to lose precision on the period parameter as a small change, coupled with the propagation of dpdt * (times - t0) can cause a large effect. It is important to try to define the system at a time t0@system that are near the dataset times (and near the other various t0s). By default, t0@system is set to 0 and we have set our dataset times to start at zero as well. Step7: Considerations in compute_phases and mask_phases By default, the mapping between compute_times and compute_phases will account for dpdt. In this case, we set compute_phases to cover successive orbits... so therefore the resulting compute_times will adjust as necessary. Step8: For the case of this tutorial, we would rather the compute_times be even cycles based on period alone, so that we can color by cycles of period and easily visualize the effect of dpdt. We could have set compute_times directly instead, but then we would need to keep the period fixed and know it in advance. Alternatively, we can set phases_dpdt = 'none' to tell this mapping to ignore dpdt. Step9: As noted in the description, the phases_dpdt parameter will also affect phase-masking. Step10: Now we see that our resulting compute_times are direct multiples of the period (at time=t0@system). Step11: Contribution to Eclipse Timings in Light Curves Now we'll run the forward model, but with light travel time effects disabled, just to avoid any confusion with small contributions from the finite speed of light. Step12: By default, the phasing in plotting accounts for dpdt. Step13: To override this behavior, we can pass dpdt=0.0 so that we can see the eclipses spread across the phase-space. dpdt is passed directly to b.to_phase (see also Step14: Contribution to Orbits and Mass-Conservation As the orbital period is instantaneously changing, the instantaneous semi-major axis of the orbit is also adjusted in order to conserve the total mass in the system (under Kepler's third law). This results in an automatic in or out-spiral of the system whenever dpdt != 0.0. Note that, like the period, sma is defined at t0@system. Just for visualization purposes, let's rerun our forward model, but this time with an even more exaggerated value for dpdt Step15: By plotting us vs times, we can see the position of the stars at integer periods (when we'd expect eclipses if it weren't for dpdt) as well as the times of the resulting eclipses (when the two stars cross at u=0, ignoring ltte, etc). Here we clearly see the increasing orbit size as a function of time. Step16: Contributions to RVs Due to the changing size of the orbit due to mass conservation (increasing the RV amplitude for a positive dpdt), as well as the changing orbital period (decreasing the RV amplitude for a positive dpdt), the RVs will also have a change in amplitude as a function of time (in addition to the phase-effects seen for the light curve above).
Python Code: #!pip install "phoebe>=2.4,<2.5" Explanation: Period Change (dpdt) Setup Let's first make sure we have the latest version of PHOEBE 2.4 installed (uncomment this line if running in an online notebook session such as colab). End of explanation import phoebe from phoebe import u # units import numpy as np import matplotlib.pyplot as plt b = phoebe.default_binary() Explanation: As always, let's do imports and initialize a new Bundle. End of explanation b.set_value('q', 0.8) b.set_value('teff', component='secondary', value=5000) Explanation: In order to easily differentiate between the components in a light curve and in the orbits, we'll set the secondary temperature and the mass ratio. End of explanation b.set_value('per0', 60) b.set_value('dpdt', 0.005*u.d/u.d) Explanation: and set dpdt to an unrealistically large value so that we can easily see the effect over just a few orbits. End of explanation for i in range(3): b.add_dataset('lc', compute_phases=phoebe.linspace(i,i+1,101)) b.add_dataset('rv', compute_phases=phoebe.linspace(i,i+1,101)) b.add_dataset('orb', compute_phases=phoebe.linspace(i,i+1,101)) Explanation: We'll add several light curve, RV, and orbit datasets, each covering successive cycles of the orbit so that we can differentiate between them later when plotting. End of explanation print(b.get_parameter(qualifier='dpdt').description) Explanation: It is important to note that the dpdt parameter is the time-derivative of period (the anomalistic period). However, the anomalistic and sidereal periods are only different in the case of apsidal motion. End of explanation print(b.filter('t0', context='system')) print(b.get_parameter('t0', context='system').description) Explanation: Zero-point for orbital period The orbital period itself, period, is defined at time t0 (in the system context). If the dataset times are far from t0@system then we begin to lose precision on the period parameter as a small change, coupled with the propagation of dpdt * (times - t0) can cause a large effect. It is important to try to define the system at a time t0@system that are near the dataset times (and near the other various t0s). By default, t0@system is set to 0 and we have set our dataset times to start at zero as well. End of explanation print(b.filter(qualifier='compute_times', kind='lc', context='dataset')) Explanation: Considerations in compute_phases and mask_phases By default, the mapping between compute_times and compute_phases will account for dpdt. In this case, we set compute_phases to cover successive orbits... so therefore the resulting compute_times will adjust as necessary. End of explanation print(b.filter(qualifier='phases_dpdt')) print(b.get_parameter(qualifier='phases_dpdt', dataset='lc01').description) Explanation: For the case of this tutorial, we would rather the compute_times be even cycles based on period alone, so that we can color by cycles of period and easily visualize the effect of dpdt. We could have set compute_times directly instead, but then we would need to keep the period fixed and know it in advance. Alternatively, we can set phases_dpdt = 'none' to tell this mapping to ignore dpdt. End of explanation b.set_value_all('phases_dpdt', 'none') Explanation: As noted in the description, the phases_dpdt parameter will also affect phase-masking. End of explanation print(b.filter(qualifier='compute_times', kind='lc', context='dataset')) Explanation: Now we see that our resulting compute_times are direct multiples of the period (at time=t0@system). End of explanation b.run_compute(ltte=False) _ = b.plot(kind='lc', x='times', legend=True, show=True) Explanation: Contribution to Eclipse Timings in Light Curves Now we'll run the forward model, but with light travel time effects disabled, just to avoid any confusion with small contributions from the finite speed of light. End of explanation _ = b.plot(kind='lc', x='phases', legend=True, show=True) Explanation: By default, the phasing in plotting accounts for dpdt. End of explanation _ = b.plot(kind='lc', x='phases', dpdt=0.0, legend=True, show=True) Explanation: To override this behavior, we can pass dpdt=0.0 so that we can see the eclipses spread across the phase-space. dpdt is passed directly to b.to_phase (see also: b.to_time and b.get_ephemeris) End of explanation b.set_value('dpdt', 0.1*u.d/u.d) b.run_compute(ltte=False) _ = b.plot(kind='orb', x='us', y='ws', time=b.get_value('t0_supconj@component')+1*np.arange(0,3), linestyle={'primary': 'solid', 'secondary': 'dotted'}, color={'orb01': 'blue', 'orb02': 'orange', 'orb03': 'green'}, #color='dataset', # TODO: we should support this to say color BY dataset legend=True, show=True) Explanation: Contribution to Orbits and Mass-Conservation As the orbital period is instantaneously changing, the instantaneous semi-major axis of the orbit is also adjusted in order to conserve the total mass in the system (under Kepler's third law). This results in an automatic in or out-spiral of the system whenever dpdt != 0.0. Note that, like the period, sma is defined at t0@system. Just for visualization purposes, let's rerun our forward model, but this time with an even more exaggerated value for dpdt End of explanation _ = b.plot(kind='orb', time=b.get_value('t0_supconj@component')+1*np.arange(0,3), linestyle={'primary': 'solid', 'secondary': 'dotted'}, color={'orb01': 'blue', 'orb02': 'orange', 'orb03': 'green'}, x='times', y='us', show=True) Explanation: By plotting us vs times, we can see the position of the stars at integer periods (when we'd expect eclipses if it weren't for dpdt) as well as the times of the resulting eclipses (when the two stars cross at u=0, ignoring ltte, etc). Here we clearly see the increasing orbit size as a function of time. End of explanation _ = b.plot(kind='rv', x='times', linestyle={'primary': 'solid', 'secondary': 'dotted'}, color={'rv01': 'blue', 'rv02': 'orange', 'rv03': 'green'}, show=True) Explanation: Contributions to RVs Due to the changing size of the orbit due to mass conservation (increasing the RV amplitude for a positive dpdt), as well as the changing orbital period (decreasing the RV amplitude for a positive dpdt), the RVs will also have a change in amplitude as a function of time (in addition to the phase-effects seen for the light curve above). End of explanation
5,346
Given the following text description, write Python code to implement the functionality described below step by step Description: Rechunker Tutorial This tutorial notebook explains how to use rechunker with real datasets. We will also use xarray to make some things easier and prettier, but we note that xarray is not a dependency for rechunker. Toy Example Create Example Data Here we load one of xarray's tutorial datasets and write it to Zarr. This is not actually a big dataset, so rechunker is not really needed here. But it's a convenient example. Step1: We can examine the chunk structure of the data variable using Dask's pretty Array repr. Step2: Now we open up a Zarr Group and Array that we will use as inputs to rechunker. Step3: Rechunk a single Array The original array has chunks of (100, 25, 53). Let's rechunk it to be contiguous in time, but chunked in space. We specify a small value of max_mem in order to force rechunker to create an intermediate dataset. We also have to specify a place to store the final and intermediate data. We use the rechunk function, which returns a Rechunked object. Step4: Since this array has dimensions, we can also specify the chunks using a dictionary syntax. Step5: The array_plan is a Rechunked object. It has not actually performed the rechunking yet. To do this, we need to call the execute method. This will use Dask to perform the rechunking. Step6: By default, Dask will use the multi-threaded scheduler. Since rechunking can take a long time, we might want to use a progress bar. Step7: If we create a distributed cluster, then rechunker will use that when it executes. Step8: Now that it is written to disk, we can open the rechunked array however we please. Using Zarr... Step9: ...or Dask Step10: Rechunk a Group In the example above, we only rechunked a single array. We can open it with Dask, but not Xarray, because it doesn't contain any coordinates or metadata. Rechunker also supports rechunking entire groups. In this case, target_chunks must be a dictionary. Step11: Now that we have written a group, we can open it back up with Xarray. Step12: Often groups have many variables sharing all or a subset of dimensions. In the common case that a given dimension should have equivalent chunks in each variable that contains it, chunks can be provided as a simpler dictionary, mapping dimension names to chunksize. Step13: Note that all the variables now have the same time chunks. Other dimensions (if they exist) also have consistent chunks. Cloud Example In this example we use real data from Pangeo's Cloud Data Catalog. This dataset is stored in Google Cloud Storage. We also use a Dask Gateway distributed cluster to scale up our processing. This part of the tutorial won't work for you unless you are in a Pangeo Cloud environment or binder. Step14: Open Zarr Array Step15: Make a Rechunking Plan Step16: Execute the Plan
Python Code: import xarray as xr xr.set_options(display_style='text') import zarr import dask.array as dsa ds = xr.tutorial.open_dataset("air_temperature") # create initial chunk structure ds = ds.chunk({'time': 100}) ds.air.encoding = {} # helps when writing to zarr ds Explanation: Rechunker Tutorial This tutorial notebook explains how to use rechunker with real datasets. We will also use xarray to make some things easier and prettier, but we note that xarray is not a dependency for rechunker. Toy Example Create Example Data Here we load one of xarray's tutorial datasets and write it to Zarr. This is not actually a big dataset, so rechunker is not really needed here. But it's a convenient example. End of explanation ds.air.data ! rm -rf *.zarr # clean up any existing temporary data ds.to_zarr('air_temperature.zarr') Explanation: We can examine the chunk structure of the data variable using Dask's pretty Array repr. End of explanation source_group = zarr.open('air_temperature.zarr') print(source_group.tree()) source_array = source_group['air'] source_array.info Explanation: Now we open up a Zarr Group and Array that we will use as inputs to rechunker. End of explanation from rechunker import rechunk target_chunks = (2920, 25, 1) max_mem = '1MB' target_store = 'air_rechunked.zarr' temp_store = 'air_rechunked-tmp.zarr' array_plan = rechunk(source_array, target_chunks, max_mem, target_store, temp_store=temp_store) array_plan Explanation: Rechunk a single Array The original array has chunks of (100, 25, 53). Let's rechunk it to be contiguous in time, but chunked in space. We specify a small value of max_mem in order to force rechunker to create an intermediate dataset. We also have to specify a place to store the final and intermediate data. We use the rechunk function, which returns a Rechunked object. End of explanation target_chunks_dict = {'time': 2920, 'lat': 25, 'lon': 1} # need to remove the existing stores or it won't work !rm -rf air_rechunked.zarr air_rechunked-tmp.zarr array_plan = rechunk(source_array, target_chunks_dict, max_mem, target_store, temp_store=temp_store) array_plan Explanation: Since this array has dimensions, we can also specify the chunks using a dictionary syntax. End of explanation result = array_plan.execute() result.chunks Explanation: The array_plan is a Rechunked object. It has not actually performed the rechunking yet. To do this, we need to call the execute method. This will use Dask to perform the rechunking. End of explanation from dask.diagnostics import ProgressBar with ProgressBar(): array_plan.execute() Explanation: By default, Dask will use the multi-threaded scheduler. Since rechunking can take a long time, we might want to use a progress bar. End of explanation from dask.distributed import Client, LocalCluster, progress cluster = LocalCluster() client = Client(cluster) future = array_plan.persist() progress(future) Explanation: If we create a distributed cluster, then rechunker will use that when it executes. End of explanation target_array = zarr.open('air_rechunked.zarr') target_array Explanation: Now that it is written to disk, we can open the rechunked array however we please. Using Zarr... End of explanation target_array_dask = dsa.from_zarr('air_rechunked.zarr') target_array_dask Explanation: ...or Dask End of explanation target_chunks = { 'air': {'time': 2920, 'lat': 25, 'lon': 1}, 'time': None, # don't rechunk this array 'lon': None, 'lat': None, } max_mem = '1MB' target_store = 'group_rechunked.zarr' temp_store = 'group_rechunked-tmp.zarr' # need to remove the existing stores or it won't work !rm -rf group_rechunked.zarr group_rechunked-tmp.zarr array_plan = rechunk(source_group, target_chunks, max_mem, target_store, temp_store=temp_store) array_plan array_plan.execute() Explanation: Rechunk a Group In the example above, we only rechunked a single array. We can open it with Dask, but not Xarray, because it doesn't contain any coordinates or metadata. Rechunker also supports rechunking entire groups. In this case, target_chunks must be a dictionary. End of explanation xr.open_zarr('group_rechunked.zarr') Explanation: Now that we have written a group, we can open it back up with Xarray. End of explanation # extend the dataset with some more variables ds_complex = ds ds_complex['air_slice'] = ds.air.isel(lat=10) ds_complex['air_timeseries'] = ds.air.isel(lat=10, lon=10) ds_complex target_chunks = {'time': 2920, 'lat': 25, 'lon': 1} max_mem = '1MB' target_store = 'group_complex_rechunked.zarr' temp_store = 'group_complex_rechunked-tmp.zarr' # need to remove the existing stores or it won't work !rm -rf group_complex_rechunked.zarr group_complex_rechunked-tmp.zarr # rechunk directly from dataset this time array_plan = rechunk(ds_complex, target_chunks, max_mem, target_store, temp_store=temp_store) array_plan array_plan.execute() xr.open_zarr('group_complex_rechunked.zarr') Explanation: Often groups have many variables sharing all or a subset of dimensions. In the common case that a given dimension should have equivalent chunks in each variable that contains it, chunks can be provided as a simpler dictionary, mapping dimension names to chunksize. End of explanation from dask_gateway import GatewayCluster cluster = GatewayCluster() cluster.scale(20) cluster from dask.distributed import Client client = Client(cluster) client import gcsfs # a zarr group lives here url = 'gs://pangeo-cmems-duacs' gcs = gcsfs.GCSFileSystem(requester_pays=True) source_store = gcs.get_mapper(url) Explanation: Note that all the variables now have the same time chunks. Other dimensions (if they exist) also have consistent chunks. Cloud Example In this example we use real data from Pangeo's Cloud Data Catalog. This dataset is stored in Google Cloud Storage. We also use a Dask Gateway distributed cluster to scale up our processing. This part of the tutorial won't work for you unless you are in a Pangeo Cloud environment or binder. End of explanation group = zarr.open_consolidated(source_store, mode='r') source_array = group['sla'] source_array source_array.chunks Explanation: Open Zarr Array End of explanation max_mem = '1GB' target_chunks = (8901, 72, 72) # you must have write access to this location store_tmp = gcs.get_mapper('pangeo-scratch/rabernat/rechunker_demo/temp.zarr') store_target = gcs.get_mapper('pangeo-scratch/rabernat/rechunker_demo/target.zarr') r = rechunk(source_array, target_chunks, max_mem, store_target, temp_store=store_tmp) r Explanation: Make a Rechunking Plan End of explanation result = r.execute() result dsa.from_zarr(result) Explanation: Execute the Plan End of explanation
5,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Taxi Fare Prediction Using Realtime Traffic Data This will be the same as our previous taxi fare model, but with the addition of ‘trips_last_5min’ data as a feature. This is our proxy for traffic Step1: Load raw data These are the same files used previously for taxi fare prediction, however an additional field trips_last_5min has been added Step2: Train and Evaluate input functions Step3: Feature Engineering Step4: Feature Engineering Step5: Gather list of feature columns Note we're standard normalizing our traffic proxy. The mean and standard deviation were calculated on the full dataset in BigQuery, then hardcoded here. Step6: Serving Input Receiver function Step7: Train and Evaluate
Python Code: import tensorflow as tf import numpy as np import shutil print(tf.__version__) Explanation: Taxi Fare Prediction Using Realtime Traffic Data This will be the same as our previous taxi fare model, but with the addition of ‘trips_last_5min’ data as a feature. This is our proxy for traffic End of explanation !gsutil cp gs://cloud-training-demos/taxifare/traffic/small/*.csv . !ls -l *.csv Explanation: Load raw data These are the same files used previously for taxi fare prediction, however an additional field trips_last_5min has been added End of explanation CSV_COLUMN_NAMES = ["fare_amount","dayofweek","hourofday","pickuplon","pickuplat",\ "dropofflon","dropofflat","trips_last_5min"] CSV_DEFAULTS = [[0.0],[1],[0],[-74.0],[40.0],[-74.0],[40.7],[0]] def read_dataset(csv_path): def _parse_row(row): # Decode the CSV row into list of TF tensors fields = tf.decode_csv(records = row, record_defaults = CSV_DEFAULTS) # Pack the result into a dictionary features = dict(zip(CSV_COLUMN_NAMES, fields)) # NEW: Add engineered features features = add_engineered_features(features) # Separate the label from the features label = features.pop("fare_amount") # remove label from features and store return features, label # Create a dataset containing the text lines. dataset = tf.data.Dataset.list_files(file_pattern = csv_path) # (i.e. data_file_*.csv) dataset = dataset.flat_map(map_func = lambda filename:tf.data.TextLineDataset(filenames = filename).skip(count = 1)) # Parse each CSV row into correct (features,label) format for Estimator API dataset = dataset.map(map_func = _parse_row) return dataset def train_input_fn(csv_path, batch_size = 128): #1. Convert CSV into tf.data.Dataset with (features,label) format dataset = read_dataset(csv_path) #2. Shuffle, repeat, and batch the examples. dataset = dataset.shuffle(buffer_size = 1000).repeat(count = None).batch(batch_size = batch_size) return dataset def eval_input_fn(csv_path, batch_size = 128): #1. Convert CSV into tf.data.Dataset with (features,label) format dataset = read_dataset(csv_path) #2.Batch the examples. dataset = dataset.batch(batch_size = batch_size) return dataset Explanation: Train and Evaluate input functions End of explanation # 1. One hot encode dayofweek and hourofday fc_dayofweek = tf.feature_column.categorical_column_with_identity(key = "dayofweek", num_buckets = 7) fc_hourofday = tf.feature_column.categorical_column_with_identity(key = "hourofday", num_buckets = 24) # 2. Bucketize latitudes and longitudes NBUCKETS = 16 latbuckets = np.linspace(start = 38.0, stop = 42.0, num = NBUCKETS).tolist() lonbuckets = np.linspace(start = -76.0, stop = -72.0, num = NBUCKETS).tolist() def bucketize_fc(key,boundaries): return tf.feature_column.bucketized_column( source_column = tf.feature_column.numeric_column(key = key), boundaries = boundaries) fc_bucketized_plat = bucketize_fc("pickuplon",lonbuckets) fc_bucketized_plon = bucketize_fc("pickuplat",latbuckets) fc_bucketized_dlat = bucketize_fc("dropofflon",lonbuckets) fc_bucketized_dlon = bucketize_fc("dropofflat",latbuckets) # 3. Cross features to get combination of day and hour fc_crossed_day_hr = tf.feature_column.crossed_column(keys = [fc_dayofweek, fc_hourofday], hash_bucket_size = 24 * 7) Explanation: Feature Engineering: feature columns End of explanation def add_engineered_features(features): features["dayofweek"] = features["dayofweek"] - 1 # subtract one since our days of week are 1-7 instead of 0-6 features["latdiff"] = features["pickuplat"] - features["dropofflat"] # East/West features["londiff"] = features["pickuplon"] - features["dropofflon"] # North/South features["euclidean_dist"] = tf.sqrt(x = features["latdiff"]**2 + features["londiff"]**2) return features Explanation: Feature Engineering: input function End of explanation feature_cols = [ #1. Engineered using tf.feature_column module tf.feature_column.indicator_column(categorical_column = fc_crossed_day_hr), fc_bucketized_plat, fc_bucketized_plon, fc_bucketized_dlat, fc_bucketized_dlon, #2. Engineered in input functions tf.feature_column.numeric_column(key = "latdiff"), tf.feature_column.numeric_column(key = "londiff"), tf.feature_column.numeric_column(key = "euclidean_dist"), #3. Traffic proxy tf.feature_column.numeric_column(key = "trips_last_5min", normalizer_fn=lambda x: (x - 2070) / 616) ] Explanation: Gather list of feature columns Note we're standard normalizing our traffic proxy. The mean and standard deviation were calculated on the full dataset in BigQuery, then hardcoded here. End of explanation def serving_input_receiver_fn(): receiver_tensors = { 'dayofweek' : tf.placeholder(dtype = tf.int32, shape = [None]), # shape is vector to allow batch of requests 'hourofday' : tf.placeholder(dtype = tf.int32, shape = [None]), 'pickuplon' : tf.placeholder(dtype = tf.float32, shape = [None]), 'pickuplat' : tf.placeholder(dtype = tf.float32, shape = [None]), 'dropofflat' : tf.placeholder(dtype = tf.float32, shape = [None]), 'dropofflon' : tf.placeholder(dtype = tf.float32, shape = [None]), 'trips_last_5min' : tf.placeholder(dtype = tf.float32, shape = [None]), } features = add_engineered_features(receiver_tensors) # 'features' is what is passed on to the model return tf.estimator.export.ServingInputReceiver(features = features, receiver_tensors = receiver_tensors) Explanation: Serving Input Receiver function End of explanation %%time OUTDIR = "taxi_trained" shutil.rmtree(path = OUTDIR, ignore_errors = True) # start fresh each time tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file tf.logging.set_verbosity(v = tf.logging.INFO) # so loss is printed during training model = tf.estimator.DNNRegressor( hidden_units = [10,10], # specify neural architecture feature_columns = feature_cols, model_dir = OUTDIR, config = tf.estimator.RunConfig( tf_random_seed = 1, # for reproducibility save_checkpoints_steps = 200 # checkpoint every N steps ) ) # Add custom evaluation metric def my_rmse(labels, predictions): pred_values = tf.squeeze(input = predictions["predictions"], axis = -1) return {"rmse": tf.metrics.root_mean_squared_error(labels = labels, predictions = pred_values)} model = tf.contrib.estimator.add_metrics(estimator = model, metric_fn = my_rmse) train_spec = tf.estimator.TrainSpec( input_fn = lambda: train_input_fn("./taxi-train.csv"), max_steps = 5000) exporter = tf.estimator.FinalExporter(name = "exporter", serving_input_receiver_fn = serving_input_receiver_fn) # export SavedModel once at the end of training # Note: alternatively use tf.estimator.BestExporter to export at every checkpoint that has lower loss than the previous checkpoint eval_spec = tf.estimator.EvalSpec( input_fn = lambda: eval_input_fn("./taxi-valid.csv"), steps = None, start_delay_secs = 1, # wait at least N seconds before first evaluation (default 120) throttle_secs = 1, # wait at least N seconds before each subsequent evaluation (default 600) exporters = exporter) # export SavedModel once at the end of training tf.estimator.train_and_evaluate(estimator = model, train_spec = train_spec, eval_spec = eval_spec) Explanation: Train and Evaluate End of explanation
5,348
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step3: Clone and build tensorflow_enterprise_addons To use the latest version of the tensorflow_enterprise_addons, we will clone and build the repo. The resulting whl file is both used in the client side as well as in construction of a docker image for remote execution. Step4: Restart the Kernel We will automatically restart your kernel so the notebook has access to the packages you installed. Step5: Import libraries and define constants Step6: Created a docker file with tensorflow_enterprise_addons In the next step we create a base docker file with the latest wheel file to use for remote training. You may use any base image however DLVM base images come pre-installed with most needed packages. Step8: Tutorial 1 - Functional model In this sample we will demonstrate using numpy.array as input data by creating a basic model and and submit it for remote training. Define model building function Step9: Prepare Data Step10: Run the model locally for validation Step11: Submit model and dataset for remote training Step12: Retrieve the trained model Once the training is complete you can access the trained model at remote_folder/output Step13: Tutorial 2 - Sequential Models and Datasets In this sample we will demonstrate using datasets by creating a basic model and submitting it for remote training. Define model building function Step14: Prepare Data Step15: Run the model locally for validation Step16: Submit model and dataset for remote training Step17: Retrieve the trained model Once the training is complete you can access the trained model at remote_folder/output
Python Code: import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your Google Cloud account. This provides access # to your Cloud Storage bucket and lets you submit training jobs and prediction # requests. if 'google.colab' in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this tutorial in a notebook locally, replace the string # below with the path to your service account key and run this cell to # authenticate your Google Cloud account. else: %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json # Log in to your account on Google Cloud ! gcloud auth application-default login --quiet ! gcloud auth login --quiet Explanation: <table align="left"> <td> <a href="https://console.cloud.google.com/mlengine/notebooks/deploy-notebook?q=download_url%3Dhttps://github.com/GoogleCloudPlatform/tensorflow-gcp-tools/blob/master/examples/cloud_fit.ipynb"> <img src="https://www.gstatic.com/images/branding/product/1x/google_cloud_48dp.png" alt="AI Platform Notebooks"> Run in AI Platform Notebooks </a> </td> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/tensorflow-gcp-tools/blob/master/examples/cloud_fit.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/tensorflow-gcp-tools/blob/master/examples/cloud_fit.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">View on GitHub </a> </td> </table> Overview Following is a quick introduction to cloud_fit. cloud_fit enables training on Google Cloud AI Platform in the same manner as model.fit(). In this notebook, we will start by installing libraries required, then proceed with two samples showing how to use Numpy.array and TF.data.dataset with cloud_fit What are the components of the cloud_fit() Cloud fit has two main components as follows: client.py: serializes the provided data and model along with typical model.fit() parameters and triggers a AI platform training ``` python def cloud_fit(model, remote_dir: Text, region: Text = None, project_id: Text = None, image_uri: Text = None, distribution_strategy: Text = DEFAULT_DISTRIBUTION_STRATEGY, job_spec: Dict[str, Any] = None, job_id: Text = None, **fit_kwargs) -> Text: Facilitates remote execution of in memory Models and Datasets on AI Platform. Args: model: A compiled Keras Model. remote_dir: Google Cloud Storage path for temporary assets and AI Platform training output. Will overwrite value in job_spec. region: Target region for running the AI Platform Training job. project_id: Project id where the training should be deployed to. image_uri: base image used to use for AI Platform Training distribution_strategy: Specifies the distribution strategy for remote execution when a jobspec is provided. Accepted values are strategy names as specified by 'tf.distribute.<strategy>.name'. job_spec: AI Platform training job_spec, will take precedence over all other provided values except for remote_dir. If none is provided a default cluster spec and distribution strategy will be used. job_id: A name to use for the AI Platform Training job (mixed-case letters, numbers, and underscores only, starting with a letter). **fit_kwargs: Args to pass to model.fit() including training and eval data. Only keyword arguments are supported. Callback functions will be serialized as is. Returns: AI Platform job ID Raises: RuntimeError: If executing in graph mode, eager execution is required for cloud_fit. NotImplementedError: Tensorflow v1.x is not supported. ``` remote.py: A job that takes in a remote_dir as parameter , load model and data from this location and executes the training with stored parameters. ```python def run(remote_dir: Text, distribution_strategy_text: Text): deserializes Model and Dataset and runs them. Args: remote_dir: Temporary cloud storage folder that contains model and Dataset graph. This folder is also used for job output. distribution_strategy_text: Specifies the distribution strategy for remote execution when a jobspec is provided. Accepted values are strategy names as specified by 'tf.distribute.<strategy>.name'. ``` Costs This tutorial uses billable components of Google Cloud: AI Platform Training Cloud Storage Learn about AI Platform Training pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the AI Platform APIs If running locally on your own machine, you will need to install the Google Cloud SDK. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands. Authenticate your Google Cloud account If you are using AI Platform Notebooks, your environment is already authenticated. Skip these steps. End of explanation !git clone https://github.com/GoogleCloudPlatform/tensorflow-gcp-tools.git !cd tensorflow-gcp-tools/python && python3 setup.py -q bdist_wheel !pip install -U tensorflow-gcp-tools/python/dist/tensorflow_enterprise_addons-*.whl --quiet Explanation: Clone and build tensorflow_enterprise_addons To use the latest version of the tensorflow_enterprise_addons, we will clone and build the repo. The resulting whl file is both used in the client side as well as in construction of a docker image for remote execution. End of explanation # Restart the kernel after pip installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) Explanation: Restart the Kernel We will automatically restart your kernel so the notebook has access to the packages you installed. End of explanation import os import uuid import numpy as np import tensorflow as tf from tensorflow_enterprise_addons.cloud_fit import client # Setup and imports REMOTE_DIR = '[gcs-bucket-for-temporary-files]' #@param {type:"string"} REGION = 'us-central1' #@param {type:"string"} PROJECT_ID = '[your-project-id]' #@param {type:"string"} ! gcloud config set project $PROJECT_ID IMAGE_URI = 'gcr.io/{PROJECT_ID}/[name-for-docker-image]:latest' #@param {type:"string"} Explanation: Import libraries and define constants End of explanation %%file Dockerfile # Using DLVM base image FROM gcr.io/deeplearning-platform-release/tf2-cpu WORKDIR /root # Path configuration ENV PATH $PATH:/root/tools/google-cloud-sdk/bin # Make sure gsutil will use the default service account RUN echo '[GoogleCompute]\nservice_account = default' > /etc/boto.cfg # Copy and install tensorflow_enterprise_addons wheel file ADD tensorflow-gcp-tools/python/dist/tensorflow_enterprise_addons-*.whl /tmp/ RUN pip3 install --upgrade /tmp/tensorflow_enterprise_addons-*.whl --quiet # Sets up the entry point to invoke cloud_fit. ENTRYPOINT ["python3","-m","tensorflow_enterprise_addons.cloud_fit.remote"] !docker build -t {IMAGE_URI} -f Dockerfile . -q && docker push {IMAGE_URI} Explanation: Created a docker file with tensorflow_enterprise_addons In the next step we create a base docker file with the latest wheel file to use for remote training. You may use any base image however DLVM base images come pre-installed with most needed packages. End of explanation Simple model to compute y = wx + 1, with w trainable. inp = tf.keras.layers.Input(shape=(1,), dtype=tf.float32) times_w = tf.keras.layers.Dense( units=1, kernel_initializer=tf.keras.initializers.Constant([[0.5]]), kernel_regularizer=tf.keras.regularizers.l2(0.01), use_bias=False) plus_1 = tf.keras.layers.Dense( units=1, kernel_initializer=tf.keras.initializers.Constant([[1.0]]), bias_initializer=tf.keras.initializers.Constant([1.0]), trainable=False) outp = plus_1(times_w(inp)) simple_model = tf.keras.Model(inp, outp) simple_model.compile(tf.keras.optimizers.SGD(0.002), "mean_squared_error", run_eagerly=True) Explanation: Tutorial 1 - Functional model In this sample we will demonstrate using numpy.array as input data by creating a basic model and and submit it for remote training. Define model building function End of explanation # Creating sample data x = [[9.], [10.], [11.]] * 10 y = [[xi[0]/2. + 6] for xi in x] Explanation: Prepare Data End of explanation # Verify the model by training locally for one step. simple_model.fit(np.array(x), np.array(y), batch_size=len(x), epochs=1) Explanation: Run the model locally for validation End of explanation # Create a unique remote sub folder path for assets and model training output. SIMPLE_REMOTE_DIR = os.path.join(REMOTE_DIR, str(uuid.uuid4())) print('your remote folder is %s' % (SIMPLE_REMOTE_DIR)) # Using default configuration with two workers dividing the dataset between the two. simple_model_job_id = client.cloud_fit(model=simple_model, remote_dir = SIMPLE_REMOTE_DIR, region =REGION , image_uri=IMAGE_URI, x=np.array(x), y=np.array(y), epochs=100, steps_per_epoch=len(x)/2,verbose=2) !gcloud ai-platform jobs describe projects/{PROJECT_ID}/jobs/{simple_model_job_id} Explanation: Submit model and dataset for remote training End of explanation # Load the trained model from gcs bucket trained_simple_model = tf.keras.models.load_model(os.path.join(SIMPLE_REMOTE_DIR, 'output')) # Test that the saved model loads and works properly trained_simple_model.evaluate(x,y) Explanation: Retrieve the trained model Once the training is complete you can access the trained model at remote_folder/output End of explanation # create a model fashion_mnist_model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) fashion_mnist_model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) Explanation: Tutorial 2 - Sequential Models and Datasets In this sample we will demonstrate using datasets by creating a basic model and submitting it for remote training. Define model building function End of explanation train, test = tf.keras.datasets.fashion_mnist.load_data() images, labels = train images = images/255 dataset = tf.data.Dataset.from_tensor_slices((images, labels)) dataset = dataset.batch(32) Explanation: Prepare Data End of explanation # Verify the model by training locally for one step. This is not necessary prior to cloud.fit() however it is recommended. fashion_mnist_model.fit(dataset, epochs=1) Explanation: Run the model locally for validation End of explanation # Create a unique remote sub folder path for assets and model training output. FASHION_REMOTE_DIR = os.path.join(REMOTE_DIR, str(uuid.uuid4())) print('your remote folder is %s' % (FASHION_REMOTE_DIR)) fashion_mnist_model_job_id = client.cloud_fit(model=fashion_mnist_model, remote_dir = FASHION_REMOTE_DIR,region =REGION , image_uri=IMAGE_URI, x=dataset,epochs=10, steps_per_epoch=15,verbose=2) !gcloud ai-platform jobs describe projects/{PROJECT_ID}/jobs/{fashion_mnist_model_job_id} Explanation: Submit model and dataset for remote training End of explanation # Load the trained model from gcs bucket trained_fashion_mnist_model = tf.keras.models.load_model(os.path.join(FASHION_REMOTE_DIR, 'output')) # Test that the saved model loads and works properly test_images, test_labels = test test_images = test_images/255 test_dataset = tf.data.Dataset.from_tensor_slices((test_images, test_labels)) test_dataset = test_dataset.batch(32) trained_fashion_mnist_model.evaluate(test_dataset) Explanation: Retrieve the trained model Once the training is complete you can access the trained model at remote_folder/output End of explanation
5,349
Given the following text description, write Python code to implement the functionality described. Description: Remove recurring digits in a given number Removes recurring digits in num [ ] ; Index in modified string ; Traverse digits of given number one by one ; Copy the first occurrence of new digit ; Remove repeating occurrences of digit ; Driver code
Python Code: def removeRecurringDigits(num ) : l = len(num ) (i , j ) =(0 , 0 ) str = ' ' while i < l : str += num[i ] j += 1 while(i + 1 < l and num[i ] == num[i + 1 ] ) : i += 1  i += 1  return str  if __name__== ' __main __' : num = '1299888833' print(' Modified ▁ number ▁ is ▁ { } ' . format(removeRecurringDigits(num ) ) ) 
5,350
Given the following text description, write Python code to implement the functionality described below step by step Description: Clustering comparison Generate datasets We choose the size big enough to see the scalability of the algorithms, but we don't want the example to take too long. Step1: Enumerate clustering choices Step2: Perform clustering Step3: Plot
Python Code: import numpy as np from sklearn import datasets from collections import OrderedDict np.random.seed(0) n_samples = 2500 ds = OrderedDict() ds['noisy_circles'] = datasets.make_circles( n_samples=n_samples, factor=.5, noise=.05) ds['noisy_moons'] = datasets.make_moons( n_samples=n_samples, noise=.05) ds['blobs'] = np.concatenate([ np.array([[0,-1]]) + 0.5 * np.random.randn(n_samples//3, 2), np.array([[5, 0]]) + 0.1 * np.random.randn(n_samples//3, 2), np.array([[0, 5]]) + 2.0 * np.random.randn(n_samples//3, 2), ]), None ds['no_structure'] = np.random.rand(n_samples, 2), None # Scale the example data from sklearn.preprocessing import StandardScaler ds = OrderedDict((name, StandardScaler().fit_transform(X)) for name, (X, y) in ds.items()) Explanation: Clustering comparison Generate datasets We choose the size big enough to see the scalability of the algorithms, but we don't want the example to take too long. End of explanation from msmbuilder import cluster algos = [ (cluster.KCenters, 3), (cluster.RegularSpatial, 2), (cluster.KMeans, 3), (cluster.MiniBatchKMeans, 3), (cluster.KMedoids, 3), (cluster.MiniBatchKMedoids, 3), ] Explanation: Enumerate clustering choices End of explanation import time results = {} for ds_name, X in ds.items(): for algo, param in algos: algorithm = algo(param) t0 = time.time() algorithm.fit([X]) t1 = time.time() if hasattr(algorithm, 'labels_'): y_pred = algorithm.labels_[0].astype(np.int) else: y_pred = algorithm.transform([X])[0] if hasattr(algorithm, 'cluster_centers_'): centers = algorithm.cluster_centers_ else: centers = [] results[ds_name, algo.__name__] = (t1-t0, y_pred, centers) Explanation: Perform clustering End of explanation %matplotlib inline import matplotlib.pyplot as plt colors = np.array([x for x in 'bgrcmykbgrcmykbgrcmykbgrcmyk']) colors = np.hstack([colors] * 20) plt.figure(figsize=(14.5, 9.5)) plot_num = 1 titles = True for ds_name, X in ds.items(): for algo, param in algos: t, y_pred, centers = results[ds_name, algo.__name__] plt.subplot(4, 6, plot_num) if titles: plt.title(algo.__name__, size=18) plt.scatter(X[:, 0], X[:, 1], color=colors[y_pred].tolist(), s=6) center_colors = colors[:len(centers)] plt.scatter(centers[:, 0], centers[:, 1], s=100, c=center_colors) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.xticks(()) plt.yticks(()) plt.text(.99, .01, '{:.2f}s'.format(t), transform=plt.gca().transAxes, size=20, horizontalalignment='right') plot_num += 1 titles = False plt.tight_layout() Explanation: Plot End of explanation
5,351
Given the following text description, write Python code to implement the functionality described below step by step Description: 1H Magnetic Resonance Spectroscopy (1H-MRS) Measuring GABA concentrations in vivo in human Principles of MRS measurement Following a $90^\circ$ square (broadband) pulse Step1: Fourier transforming the FID yields a complex spectrum Step2: In small organic molecules (such as GABA), hydrogen atoms are free to receive and release energy in MR experiments Due to local shielding effects, their resonance frequency is shifted by some small amount Step3: Because the shift (in Hz) depends on the magnetic field strength it is quantified in parts-per-million ('ppm') The standard scale is relative to dimethyl sulfide (DMS), because its chemical shift is relatively stable in different temperatures. At body temperature, water is at 4.7 ppm Step4: Water suppression Water is present at very high concentrations drowning out signals from other molecules After excitation with a broad-band pulse, a broadband 180 to induce spin echo An additional frequency-selective 180 is applied to invert the evolution of water-bound protons Water suppression on Step5: Water-included data is used Step6: Solution Step7: How reliable is that GABA peak? Step8: What can we do to improve the situation ? First order phase correction Strategy Step9: Then - fit a model for the GABA part of the spectrum on the rephased difference spectra Step10: Quanfication Problem Step11: Similarly for the glutamate/glutamine peak at 3.7 ppm
Python Code: def FID(t, M0=1, omega_0=128, omega=150, phi=0, T2_star=1.0): Mx = M0 * np.sin((omega_0 - omega) * t + phi) * np.exp(-(t / T2_star)) My = M0 * np.cos((omega_0 - omega) * t + phi) * np.exp(-(t / T2_star)) return Mx, My def plot_fid(t, FID, omega=None, omega_0=None): fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x,y = FID ax.plot(t, x, y) ax.plot(t ,x ,ax.get_zlim()[0], 'g') ax.plot(t ,np.zeros(y.shape) + ax.get_ylim()[1], x, 'r') ax.set_xlabel('Time') ax.set_ylabel(r'$M_x$') ax.set_zlabel(r'$M_y$') if omega is not None and omega_0 is not None: ax.set_title(r'$\omega_0=%s$ $\omega=%s$'%(omega_0, omega)) fig.set_size_inches([8, 6]) t = np.linspace(0,3.5,4096) plot_fid(t, FID(t, omega=150, omega_0=128), 150, 128) Explanation: 1H Magnetic Resonance Spectroscopy (1H-MRS) Measuring GABA concentrations in vivo in human Principles of MRS measurement Following a $90^\circ$ square (broadband) pulse: $FID(R) = M_x(t) = M_0 sin[(\omega_0 - \omega)t + \phi] e^{-(t/T^*_2)} $ $FID(I) = M_y(t) = M_0 cos[(\omega_0 - \omega)t + \phi] e^{-(t/T^*_2)}$ Where $\omega_0$ is the resonance frequency of the nucleus and $\omega$ is the center frequency of the RF pulse End of explanation def fid_disp(M0=1, omega0=128, omega=np.linspace(0,1024,4096), T2_star=1.0, phi=0): A = (M0*T2_star)/(1+((omega0-omega)**2)*T2_star**2) D = (M0*T2_star**2*(omega0-omega))/(1+((omega0-omega)**2)*T2_star**2) return A,D def fid_fft(M0=1, omega0=128, omega=np.linspace(0,1024,4096), T2_star=1.0, phi=0): A,D = fid_disp(M0, omega0, omega, T2_star, phi) R = A * np.cos(phi) - D * np.sin(phi) I = A * np.sin(phi) + D * np.cos(phi) return R + I*1j phis = np.linspace(0, 2*np.pi, 6)[:-1] fig, ax = plt.subplots(len(phis)) for ii in range(len(phis)): ax[ii].plot(np.real(fid_fft(phi=phis[ii]))) ax[ii].set_ylim([-1,1]) ax[ii].text(0.5, 0.6, '$\phi=$%s $\pi$'%(phis[ii]/np.pi), transform=ax[ii].transAxes) fig.set_size_inches([8,10]) ax[-1].set_xlabel('Frequency') ax[-1].set_ylabel('Power') Explanation: Fourier transforming the FID yields a complex spectrum: $R(\omega) = A(\omega) cos \phi - D(\omega) sin \phi$ $I(\omega) = A(\omega) sin \phi + D(\omega) cos \phi$ where: $A(\omega) = \frac{M_0 T_2^}{1 + (\omega_0-\omega)^2 T_2^{2}}$ $D(\omega) = \frac{M_0 T_2^{2} (\omega_0-\omega)}{1 + (\omega_0-\omega)^2 T_2^}$ End of explanation FID1=np.vstack(FID(t, M0=0.3, omega_0=128, omega=0, phi=0, T2_star=1.0)) FID2=np.vstack(FID(t, M0=0.2, omega_0=128, omega=150, phi=0, T2_star=1.0)) FID3=np.vstack(FID(t, M0=0.5, omega_0=128, omega=250, phi=0, T2_star=1.0)) my_fid = FID1 + FID2 + FID3 my_fid = my_fid[0] + my_fid[1] * 1j plot_fid(t, (my_fid.real, my_fid.imag)) ft = np.fft.fftshift(np.fft.fft(my_fid)) plt.plot(ft) ft = np.fft.fftshift(np.fft.fft(my_fid * np.exp(-1j * 1.6))) plt.plot(ft) ft = ft/np.sum(ft) plt.plot(ft) plt.plot(np.cumsum(ft)) Explanation: In small organic molecules (such as GABA), hydrogen atoms are free to receive and release energy in MR experiments Due to local shielding effects, their resonance frequency is shifted by some small amount End of explanation fname = '12_1_PROBE_MEGA_L_Occ.nii.gz' data_file = op.join(mrd.data_folder, fname) G = mrs.GABA(data_file) water_hz = 0.0 # The center frequency of our RF pulse water_ppm = 4.7 # Per convention hz_per_ppm = 127.68 # at our 3T sampling_rate = 5000. # Hz n_samples = 4096 freq_hz = np.linspace(-sampling_rate/2., sampling_rate/2., n_samples) freq_ppm = water_ppm - (freq_hz - water_hz)/hz_per_ppm def plot_fid_fft(): fig, ax = plt.subplots(2) fig = viz.plot_tseries( nt.TimeSeries(data = [np.abs(G.water_fid[0,0])],#, np.imag(G.water_fid[0,0])], sampling_rate=5000.), ylabel='FID', fig = fig) ax[0].set_xlabel('Time(s)') #ax[1].plot(freq_ppm, np.fft.fftshift(np.fft.fft(G.water_fid[0,0]))) idx = np.where(np.logical_and(freq_ppm>3, freq_ppm<5)) ax[1].plot(freq_ppm[idx], np.fft.fftshift(np.fft.fft(G.water_fid[0,0]))[idx]) ax[1].set_xlabel('Frequency (ppm)') ax[1].set_ylabel('Power') fig.set_size_inches([10,6]) plot_fid(np.linspace(1, 3.5, n_samples), (np.real(G.water_fid[0,0]), np.imag(G.water_fid[0,0]))) plot_fid_fft() Explanation: Because the shift (in Hz) depends on the magnetic field strength it is quantified in parts-per-million ('ppm') The standard scale is relative to dimethyl sulfide (DMS), because its chemical shift is relatively stable in different temperatures. At body temperature, water is at 4.7 ppm End of explanation def plot_fid_ft_w_suppressed(): fig, ax = plt.subplots(3) fig = viz.plot_tseries( nt.TimeSeries(data = [np.abs(G.w_supp_fid[0,0])], #np.imag(G.w_supp_fid[0,0])], sampling_rate=5000.), ylabel='FID', fig = fig) idx = np.where(np.logical_and(freq_ppm>0, freq_ppm<5)) ax[1].plot(freq_ppm[idx], np.fft.fftshift(np.fft.fft(G.w_supp_fid[0,0]))[idx]) ax[1].set_xlabel('Frequency (ppm)') idx = np.where(np.logical_and(freq_ppm>0, freq_ppm<4)) ax[2].plot(freq_ppm[idx], np.fft.fftshift(np.fft.fft(G.w_supp_fid[0,0]))[idx]) ax[2].set_xlabel('Frequency (ppm)') fig.set_size_inches([10,6]) plot_fid(np.linspace(1,3.5, n_samples), (np.real(G.w_supp_fid[0,0]), np.imag(G.w_supp_fid[0,0]))) plot_fid_ft_w_suppressed() Explanation: Water suppression Water is present at very high concentrations drowning out signals from other molecules After excitation with a broad-band pulse, a broadband 180 to induce spin echo An additional frequency-selective 180 is applied to invert the evolution of water-bound protons Water suppression on End of explanation def plot_resonances(): fig, ax = plt.subplots(1) fig.set_size_inches([8,6]) ax.plot(G.f_ppm[G.idx], np.mean(G.echo_off, 0)[G.idx]) ax.invert_xaxis() ax.annotate('NAA', xy=(2, 0.65), xycoords='data', xytext=(50, -10), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.annotate('Creatine', xy=(3.1, 0.4), xycoords='data', xytext=(-80, 10), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.annotate('Glx', xy=(2.3, 0.1), xycoords='data', xytext=(-30, 60), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.annotate('Choline', xy=(3.3, 0.25), xycoords='data', xytext=(-60, 40), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.annotate('Myoinositol', xy=(4.0, 0.2), xycoords='data', xytext=(-40, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.annotate('Lipids', xy=(1.4, 0.05), xycoords='data', xytext=(20, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax.set_xlabel('ppm') ax.set_ylabel('Power') plot_resonances() Explanation: Water-included data is used: Suppressing residual water signal High SNR: used for coil combination and zero-order phase alignment J coupling Different hydrogen atoms bound covalently are physically coupled ("J coupling") Resonance in one affects resonance in another GABA has 3 resonance groups: at 1.9 ppm, 2.3 ppm and 3.0 ppm Problem : There are other resonances at these frequencies End of explanation def plot_two_echos(): fig, ax = plt.subplots(3) fig.set_size_inches([8,8]) ax[0].plot(G.f_ppm[G.idx], np.mean(G.echo_off, 0)[G.idx]) ax[1].plot(G.f_ppm[G.idx], np.mean(G.echo_on, 0)[G.idx]) ax[2].plot(G.f_ppm[G.idx], np.mean(G.diff_spectra,0)[G.idx]) ax[2].set_xlabel('ppm') ax[0].set_title('GABA included') ax[1].set_title('GABA edited') ax[2].set_title('Difference') ax[2].annotate('GABA', xy=(3.0, 0.03), xycoords='data', xytext=(-5, -40), textcoords='offset points', arrowprops=dict(arrowstyle="->")) ax[2].annotate('Glx', xy=(3.8, 0.01), xycoords='data', xytext=(-15, -40), textcoords='offset points', arrowprops=dict(arrowstyle="->")) for a in ax: a.invert_xaxis() plot_two_echos() Explanation: Solution : spectral editing A frequency selective 180 can be used to excite the resonance around 1.9 ppm Because of J-coupling, this also edits out the resonance at 3 ppm The experiment is repeated twice, with and without editing End of explanation G.fit_gaba() G.fit_glx() def plot_gaba_spec(): fig, ax = plt.subplots(1) ax.plot(G.f_ppm[G.gaba_idx], G.diff_spectra[:, G.gaba_idx].T, color='b', alpha=0.3) ax.plot(G.f_ppm[G.gaba_idx], np.mean(G.diff_spectra[:, G.gaba_idx], 0), color='r', linewidth=4, label='Average') ax.invert_xaxis() plt.legend(loc=2) ax.set_xlabel('ppm') plot_gaba_spec() Explanation: How reliable is that GABA peak? End of explanation def show_creatine_model(): fig, ax = plt.subplots(2) ax[0].matshow(np.real(G.echo1[:, G.cr_idx]), cmap=matplotlib.cm.Reds) ax[0].set_xticks([0,53]) ax[0].set_xticklabels([str(x) for x in [3.2, 2.7]]) ax[0].set_xlabel('ppm') ax[1].matshow(G.creatine_model, cmap=matplotlib.cm.Reds) ax[1].set_xticks([]) fig.set_size_inches([10,8]) fig, ax = plt.subplots(1) ax.plot(G.f_ppm[G.idx], stats.nanmean(G.sum_spectra[G._cr_transients, :], 1).squeeze()[G.idx]) ax.plot(G.f_ppm[G.cr_idx], stats.nanmean(G.creatine_model, 0), 'r') ax.invert_xaxis() ax.set_xlabel('ppm') fig.set_size_inches([10,6]) Explanation: What can we do to improve the situation ? First order phase correction Strategy : fit the creatine peak as a Lorentzian, including phase Then, rotate the phase of the spectrum by that amount across GABA-including and GABA-edited spectra Outlier exclusion Strategy : use the creating model parameters to detect the presence of outliers in the data End of explanation fig, ax = plt.subplots(2) ax[0].matshow(np.real(G.diff_spectra[:, G.gaba_idx]), cmap=matplotlib.cm.Reds) ax[0].set_xticks([0,63]) ax[0].set_xticklabels([str(x) for x in [3.4, 2.8]]) ax[0].set_xlabel('ppm') ax[1].matshow(G.gaba_model, cmap=matplotlib.cm.Reds) ax[1].set_xticks([]) fig.set_size_inches([10,8]) fig, ax = plt.subplots(1) ax.plot(G.f_ppm[G.idx], stats.nanmean(G.diff_spectra[G._gaba_transients, G.idx], 1).squeeze()) ax.plot(G.f_ppm[G.gaba_idx], stats.nanmean(G.gaba_model, 0), 'r') ax.plot(G.f_ppm[G.glx_idx], stats.nanmean(G.glx_model, 0), 'r') ax.invert_xaxis() ax.set_xlabel('ppm') fig.set_size_inches([10,6]) Explanation: Then - fit a model for the GABA part of the spectrum on the rephased difference spectra: End of explanation stats.nanmean(G.gaba_auc)/stats.nanmean(G.creatine_auc) Explanation: Quanfication Problem : the magnitude of these peaks is affected by all kinds of things The proportion of gray matter in the voxel Coil gain Editing efficiency The editing pulse is broad: GABA at 1.9 ppm is co-edited with a lysine resonance at 1.7 ppm This leads to contamination of the signal by lysine-containing macromolecules "Solution" : measure relative concentration $\frac{[GABA]}{[Cr]} \propto \frac{AUC_{GABA}}{AUC_{Cr}}$ End of explanation stats.nanmean(G.glx_auc)/stats.nanmean(G.creatine_auc) Explanation: Similarly for the glutamate/glutamine peak at 3.7 ppm: End of explanation
5,352
Given the following text description, write Python code to implement the functionality described below step by step Description: Sensivity analysis with python using SALib Written by Sarah Juricic September 21st 2018 Step1: Objectives Step2: Draw a number of samples from your problem definition Step4: Run your own model/workflow to get the output of interest Here, you use your own code, can be a python code like here, can call any other program (dymola, energy-plus, etc...) We use a lumped thermal model, aka RC model. The scientific question behind (it's not just a stupid example ^^) Step5: NOTE Step6: SALib analysis tools SALib is a python based library to perform sensitivity analysis. So far, it contains the following analysis tools Step7: It is a dictionnary with a single key 'S1', corresponding to a list of 6 items. <br> --> First order indices of all 6 input variables Step8: Event without running the sensitivity analysis with the analyze module, this graph shows us some strong non-linearities (where blue is very near red). This only tells us that we should study this model with more samples, 150 is not enough. Surprise 5th module Basic convergence check Step10: Last but not least the BOOTSTRAP principle
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt Explanation: Sensivity analysis with python using SALib Written by Sarah Juricic September 21st 2018 End of explanation # STATE THE PROBLEM DICTIONNARY # what will be varying (=inputs) ? in what bounds ? problem = { 'num_vars': 3, 'names': ['x1', 'x2', 'x3'], 'bounds': [[-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359], [-3.14159265359, 3.14159265359]] } Explanation: Objectives : with this notebook you will understand the very basics of a sensitivity analysis and the specificity of an RBD-FAST analysis use on your own the python library SALib to perform an RBD-FAST analysis NOTE : for more detail on sensitivity analysis in general, refer to the café focus by Jeanne Goffart (april 2017), presentation is on the server. CAUTION : the sensitivity analysis tools should be used and analyzed with care. Without proper design, you won't be able to draw any conclusions at all, or worse, draw wrong conclusions... Introduction : how RBD-FAST (and sensitivity analysis in general) works <img src="Principle SAnalysis.jpg" alt="oops! missing picture" title="basic principle" /> RBD-FAST principle explained in Goffart, Rabouille and Mendes (2015) <img src="RBD-FAST chez Goffart et al 2015.png" alt="oops! missing picture" title="RBD-FAST method in more detail" /> GENERAL WORKFLOW define the "problem" dictionnary that states the number of inputs, their names, their bounds : prerequisite to SALib sample values for each parameters in the space you want to study (through LHS sampler of SALib) run your model/workflow and save the output(s) you're interested in (your own code) use a SA method (from SALib analyze tools) and a surpriiiise ! Define the "problem dictionnary" It is a regular python dictionnary object with mandatory keys : - 'num_vars' - 'names' - 'bounds' TRICKY ALERT Defining the bounds is one of the trickiest part of a sensitivity analysis Do read the literature on that subject, what your fellow researchers have set as bounds for their studies etc... Here we have chosen to focus on a specific area of all the possible values taken by the parameters : ∓ 10% around a value. End of explanation # say we want to draw 150 samples num_samples = 150 # we draw a Latin Hypercube Sampling (LHS) that is fitted for an RBD FAST analysis # (other sampling metods available in the library though) from SALib.sample.latin import sample all_samples = sample(problem, num_samples) Explanation: Draw a number of samples from your problem definition End of explanation # this is where you define your own model, procedure, experiment... from SALib.test_functions import Ishigami import numpy as np def run_model(x1, x2, x3): COPY HERE YOUR OWN CODE the function takes as input 1 sample returns 1 or more output # Delete from HERE ======================================= # As an example, we'll look at the famous Ishigami function # (A and B are specific parameters for the Ishigami function) A = 7 B = 0.1 y = (np.sin(x1) + A * np.sin(x2)**2 + B * x3 ** 4 * np.sin(x1)) # ========= TO HERE and replace with your own piece of code return y Explanation: Run your own model/workflow to get the output of interest Here, you use your own code, can be a python code like here, can call any other program (dymola, energy-plus, etc...) We use a lumped thermal model, aka RC model. The scientific question behind (it's not just a stupid example ^^) : can the model be entirely calibrated ? the parameters that have not influence on the output (indoor temperature) cannot be determined by any calibration algorithm and it's also ok, it means that we can just fix its value without interfering with the calibration process, and it reduces the dimensions of the inverse problem --> also good ! End of explanation # run your model, procedure, experiment for each sample of your sampling # unpack all_samples into 3 vectors x1, x2, x3 x1, x2, x3 = all_samples.T # run the model, all samples at the same time ishigami_results = run_model(x1, x2, x3) Explanation: NOTE : you could also use outputs from a different program, you would then have to upload your data into a python numpy array. End of explanation from SALib.analyze import rbd_fast # Let us look at the analyze method rbd_fast.analyze(problem=problem, Y=ishigami_results, X=all_samples) Explanation: SALib analysis tools SALib is a python based library to perform sensitivity analysis. So far, it contains the following analysis tools : - FAST - Fourier Amplitude Sensitivity Test - RBD-FAST - Random Balance Designs Fourier Amplitude Sensitivity Test - Method of Morris - Sobol Sensitivity Analysis - Delta Moment-Independent Measure - Derivative-based Global Sensitivity Measure (DGSM) - Fractional Factorial RBD-FAST Reminder : Why do we want to use RBD-FAST ?? - not only does it robustly calculates sensitvity indices as accurately as a Sobol method with much fewer samples - but also it is based on a LH sampling : the output itself is exploitable and interesting to look at (unlike Morris method where the samples used for the calculation of the indices are useless afterwards). End of explanation # storing the first order indices of the analyze method si1 = rbd_fast.analyze(problem=problem, Y=ishigami_results, X=all_samples)['S1'] # make nice plots with the indices (looks good on your presentations) # do not use the plotting tools of SALib, they are made for the method of Morris ... fig, ax = plt.subplots() fig.set_size_inches(18, 5) ax.tick_params(labelsize=18) # ===== X-AXIS ===== ax.set_xticks(np.arange(problem['num_vars'])) ax.set_xticklabels(problem['names']) ax.set_xlim(xmin=-0.5, xmax=problem['num_vars'] - 0.5) # ===== Y-AXIS ===== ax.set_ylabel('RBD-FAST\nSensitivity indices\n', fontsize=25) # ===== BARS REPRESENTING THE SENSITIVITY INDICES ===== ax.bar(np.arange(problem['num_vars']), si1, color='DarkSeaGreen'); #in striped grey : not significant indices ax.fill_between(x=[-0.5, 5.5], y1=-0.1, y2=0.1, color='grey', alpha=0.2, hatch='//', edgecolor='white'); # take a closer look to undestand interactions (looks even better on your presentations) # this part can be done without analyzing with SALib, just with the ouput from the samples fig, ax = plt.subplots() fig.set_size_inches(8, 7) ax.tick_params(labelsize=15) ax.set_title('Output of the model studied (Ishigami)\n' 'according to the value of the 2 most influent parameters', fontsize=20) # ===== SCATTER ===== size = np.ones(num_samples) * 75 sc = ax.scatter(x1, x2, c=ishigami_results, s=size, vmin=ishigami_results.min(), vmax=ishigami_results.max(), cmap='seismic', edgecolor=None) # ===== X-AXIS ===== ax.set_xlim(xmin=problem['bounds'][0][0], xmax=problem['bounds'][0][1]) ax.set_xlabel('Parameter 1', fontsize=20) # ===== Y-AXIS ===== ax.set_ylim(ymin=problem['bounds'][1][0], ymax=problem['bounds'][1][1]) ax.set_ylabel('Parameter 2', fontsize=20) # ===== COLORBAR ===== ticks = np.arange(ishigami_results.min(), ishigami_results.max(), 5) cb = plt.colorbar(sc, ticks=ticks); cb.ax.set_yticklabels([str(round(i,1)) for i in ticks]) fig.tight_layout(); Explanation: It is a dictionnary with a single key 'S1', corresponding to a list of 6 items. <br> --> First order indices of all 6 input variables End of explanation def conv_study(n, Y, X): # take n samples among the num_samples, without replacement subset = np.random.choice(num_samples, size=n, replace=False) return rbd_fast.analyze(problem=problem, Y=Y[subset], X=X[subset])['S1'] all_indices = np.array([conv_study(n=n, Y=ishigami_result, X=all_samples) for n in np.arange(50, num_samples + 1, 5)]) # convergence check fig, ax = plt.subplots() fig.set_size_inches(15,8) ax.set_title('Convergence of the sensitivity indices', fontsize=20) ax.tick_params(labelsize=16) ax.set_xlim(xmin=0, xmax=(num_samples - 50)//10) ax.set_xticks(np.arange(0,(num_samples - 50)//10 +1,5)) ax.set_xticklabels([str(i) for i in range(50,num_samples+1,50)]) ax.set_ylim(ymin=-0.15, ymax=1) for p,param in enumerate(problem['names']): ax.plot(all_indices[:,p], linewidth=3, label=param) ax.fill_between(x=[0,(num_samples - 50)//10], y1=-0.15, y2=0.1, color='grey', alpha=0.2, hatch='//', edgecolor='white', label='REMINDER : not significant') ax.legend(fontsize=20, ncol=4); Explanation: Event without running the sensitivity analysis with the analyze module, this graph shows us some strong non-linearities (where blue is very near red). This only tells us that we should study this model with more samples, 150 is not enough. Surprise 5th module Basic convergence check : NOT in SALib BUT definitely mandatory Principle Perform the SA from a sub-sample of 50, 60, 70, ... up to the total 300. We should see that the indices stabilize around a value. If not, we need more samples ! End of explanation def bootstrap(problem, Y, X): Calculate confidence intervals of rbd-fast indices 1000 draws returns 95% confidence intervals of the 1000 indices problem : dictionnary as SALib uses it X : SA input(s) Y : SA output(s) all_indices = [] for i in range(1000): X_new = np.zeros(X.shape) Y_new = np.zeros(Y.shape).flatten() # draw with replacement tirage_indices = np.random.randint(0, high=Y.shape[0], size = Y.shape[0]) for j, index in enumerate(tirage_indices): X_new[j,:] = X[index, :] Y_new[j] = Y[index] all_indices.append(rbd_fast.analyze(problem=problem, Y=Y_new, X=X_new)['S1']) means = np.array([i.mean() for i in np.array(all_indices).T]) stds = np.array([i.std() for i in np.array(all_indices).T]) return np.array([means - 2 * stds, means + 2 * stds]) # Get bootstrap confidence intervals for each index bootstrap_conf = bootstrap(problem=problem, Y=ishigami_results, X=all_samples) # make nice plots with the indices (looks good on your presentations) # do not use the plotting tools of SALib, they are made for the method of Morris ... fig, ax = plt.subplots() fig.set_size_inches(8,4) ax.tick_params(labelsize=18) # ===== X-AXIS ===== ax.set_xticks(np.arange(problem['num_vars'])) ax.set_xticklabels(problem['names']) ax.set_xlim(xmin=-0.5, xmax=problem['num_vars'] - 0.5) # ===== Y-AXIS ===== ax.set_ylabel('RBD-FAST\nSensitivity indices\n', fontsize=25) # ===== BARS REPRESENTING THE SENSITIVITY INDICES ===== ax.bar(np.arange(problem['num_vars']), si1, color='DarkSeaGreen'); # ===== LINES REPRESENTING THE BOOTSTRAP "CONFIDENCE INTERVALS" ===== for j in range(problem['num_vars']): ax.plot([j, j], [bootstrap_conf[0, j], bootstrap_conf[1, j]], 'k') #ax.fill_between(x=[-0.5, 5.5], y1=-0.1, y2=0.1, color='grey', alpha=0.2, hatch='//', edgecolor='white'); Explanation: Last but not least the BOOTSTRAP principle : select a subset of n_sub samples, with n_sub < num_samples (say on 200 over 300) and perform the sensitivity analysis on that subset. Repeat 1000 times that operation. The indices will vary : the bigger they vary the larger the influence of the samples (aka some of the samples influence greatly the outcome of the SA). The values taken by the indices are trustworthy if the indices show robustness in the bootstrap process (i.e. the "confidence intervals" are not too wide). In any case, it is a valuable information about the uncertainty around the indices. End of explanation
5,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Currenlty the market basket analysis we are performing is only looking within a time slice to determin if thigs are occuring at the same time, not if they can be used to predict what is in the next timeslice. for within the same basket nodes a,b,c,d listed as frequest should generate undirected edges (a,b) (a,c) (a,d) (b,c) (b,d) (c,d) for across baskets edges would generate directed edges (a,b) (b,c) (c,d) Step1: Write the output for the D3 force graph start edge, end edge, weight, start edge words, end edge words
Python Code: import itertools for p in procLine: l = p.split(' ') if len(l) > 1: comb = itertools.combinations(l, 2) for start,finish in comb: val = (start,finish) edgeDict[val] += 1 edgeSet.add(val) Explanation: Currenlty the market basket analysis we are performing is only looking within a time slice to determin if thigs are occuring at the same time, not if they can be used to predict what is in the next timeslice. for within the same basket nodes a,b,c,d listed as frequest should generate undirected edges (a,b) (a,c) (a,d) (b,c) (b,d) (c,d) for across baskets edges would generate directed edges (a,b) (b,c) (c,d) End of explanation import networkx as nx from wordcloud import WordCloud import matplotlib.pyplot as plt G=nx.Graph() G.add_edges_from(edgeDict.iterkeys()) components = list(nx.connected_components(G)) nodeweight = defaultdict(int) # make some relative size based on frequency for k,v in edgeDict.iteritems(): nodeweight[k[0]] += v nodeweight[k[1]] += v #make the canvas the correct size for the number of #images to be generated numFigs = math.ceil(math.sqrt(len(components))) fig = plt.figure() edge2PicDict = dict() for e in edgeDict.iterkeys(): for index,c in enumerate(components): if e[0] in c: edge2PicDict[e]=index temp = 1 for c in components: wordWeight = defaultdict(int) wordList = list() for cID in c: for word in clusterDict[cID].split(): #dont output punctuation if word not in [' ','{','}','[',']',':'] : wordWeight[word] += nodeweight[cID] for k,v in wordWeight.iteritems(): wordList.append((k,v)) wordcloud = WordCloud(max_font_size=100,width=640,height=480, relative_scaling=.5).generate_from_frequencies(wordList) ax= plt.subplot(numFigs,numFigs,temp) plt.title('component:%i n:%i' % (temp-1,len(c))) plt.imshow(wordcloud) # puts the graphs into a file wordcloud.to_file('wordCloud%i.png'%(temp-1)) plt.axis("off") temp=temp+1 plt.show() fig.savefig('allWordCloud.png') import math dataOutFile = '/Users/dgrossman/work/magichour/d3/data3.csv' header = 'source,target,image,value,sTitle,tTitle\n' outFile = openFile(dataOutFile,'w') outFile.write(header) for edge,count in edgeDict.iteritems(): o = '%s,%s,%s,%f,%s %s,%s %s\n' % (edge[0],edge[1],'wordCloud%i.png'%(edge2PicDict[edge]), math.log(int(count))+1, edge[0],clusterDict[edge[0]], edge[1],clusterDict[edge[1]]) outFile.write(o) outFile.close() Explanation: Write the output for the D3 force graph start edge, end edge, weight, start edge words, end edge words End of explanation
5,354
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: We import all the necessary packages. We are going to work with the fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models. Step2: If you're using a computer with an unusually small GPU, you may get an out of memory error when running this notebook. If this happens, click Kernel->Restart, uncomment the 2nd line below to use a smaller batch size (you'll learn all about what this means during the course), and try again. Step3: Looking at the data We are going to use the Oxford-IIIT Pet Dataset by O. M. Parkhi et al., 2012 which features 12 cat breeds and 25 dogs breeds. Our model will need to learn to differentiate between these 37 distinct categories. According to their paper, the best accuracy they could get in 2012 was 59.21%, using a complex model that was specific to pet detection, with separate "Image", "Head", and "Body" models for the pet photos. Let's see how accurate we can be using deep learning! We are going to use the untar_data function to which we must pass a URL as an argument and which will download and extract the data. Step4: The first thing we do when we approach a problem is to take a look at the data. We always need to understand very well what the problem is and what the data looks like before we can figure out how to solve it. Taking a look at the data means understanding how the data directories are structured, what the labels are and what some sample images look like. The main difference between the handling of image classification datasets is the way labels are stored. In this particular dataset, labels are stored in the filenames themselves. We will need to extract them to be able to classify the images into the correct categories. Fortunately, the fastai library has a handy function made exactly for this, ImageDataBunch.from_name_re gets the labels from the filenames using a regular expression. Step5: Training Step6: Results Let's see what results we have got. We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not. In this case the mistakes look reasonable (none of the mistakes seems obviously naive). This is an indicator that our classifier is working correctly. Furthermore, when we plot the confusion matrix, we can see that the distribution is heavily skewed Step7: Unfreezing, fine-tuning, and learning rates Since our model is working as we expect it to, we will unfreeze our model and train some more. Step8: That's a pretty accurate model! Training Step9: It's astonishing that it's possible to recognize pet breeds so accurately! Let's see if full fine-tuning helps Step10: If it doesn't, you can always go back to your previous model. Step11: Other data formats
Python Code: %reload_ext autoreload %autoreload 2 %matplotlib inline Explanation: <a href="https://colab.research.google.com/github/astronstar/astronstar.github.io/blob/master/%E2%80%9Clesson1_pets_ipynb%E2%80%9D%E7%9A%84%E5%89%AF%E6%9C%AC.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lesson 1 - What's your pet Welcome to lesson 1! For those of you who are using a Jupyter Notebook for the first time, you can learn about this useful tool in a tutorial we prepared specially for you; click File->Open now and click 00_notebook_tutorial.ipynb. In this lesson we will build our first image classifier from scratch, and see if we can achieve world-class results. Let's dive in! Every notebook starts with the following three lines; they ensure that any edits to libraries you make are reloaded here automatically, and also that any charts or images displayed are shown in this notebook. End of explanation from fastai.vision import * from fastai.metrics import error_rate Explanation: We import all the necessary packages. We are going to work with the fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models. End of explanation bs = 64 # bs = 16 # uncomment this line if you run out of memory even after clicking Kernel->Restart Explanation: If you're using a computer with an unusually small GPU, you may get an out of memory error when running this notebook. If this happens, click Kernel->Restart, uncomment the 2nd line below to use a smaller batch size (you'll learn all about what this means during the course), and try again. End of explanation help(untar_data) path = untar_data(URLs.PETS); path path.ls() path_anno = path/'annotations' path_img = path/'images' Explanation: Looking at the data We are going to use the Oxford-IIIT Pet Dataset by O. M. Parkhi et al., 2012 which features 12 cat breeds and 25 dogs breeds. Our model will need to learn to differentiate between these 37 distinct categories. According to their paper, the best accuracy they could get in 2012 was 59.21%, using a complex model that was specific to pet detection, with separate "Image", "Head", and "Body" models for the pet photos. Let's see how accurate we can be using deep learning! We are going to use the untar_data function to which we must pass a URL as an argument and which will download and extract the data. End of explanation fnames = get_image_files(path_img) fnames[:5] np.random.seed(2) pat = r'/([^/]+)_\d+.jpg$' data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transforms(), size=224, bs=bs ).normalize(imagenet_stats) data.show_batch(rows=3, figsize=(7,6)) print(data.classes) len(data.classes),data.c print(len(data)) doc(ImageDataBunch) Explanation: The first thing we do when we approach a problem is to take a look at the data. We always need to understand very well what the problem is and what the data looks like before we can figure out how to solve it. Taking a look at the data means understanding how the data directories are structured, what the labels are and what some sample images look like. The main difference between the handling of image classification datasets is the way labels are stored. In this particular dataset, labels are stored in the filenames themselves. We will need to extract them to be able to classify the images into the correct categories. Fortunately, the fastai library has a handy function made exactly for this, ImageDataBunch.from_name_re gets the labels from the filenames using a regular expression. End of explanation learn = cnn_learner(data, models.resnet34, metrics=error_rate) learn.model learn.fit_one_cycle(4) learn.save('stage-1') Explanation: Training: resnet34 Now we will start training our model. We will use a convolutional neural network backbone and a fully connected head with a single hidden layer as a classifier. Don't know what these things mean? Not to worry, we will dive deeper in the coming lessons. For the moment you need to know that we are building a model which will take images as input and will output the predicted probability for each of the categories (in this case, it will have 37 outputs). We will train for 4 epochs (4 cycles through all our data). End of explanation interp = ClassificationInterpretation.from_learner(learn) losses,idxs = interp.top_losses() len(data.valid_ds)==len(losses)==len(idxs) interp.plot_top_losses(9, figsize=(15,11)) doc(interp.plot_top_losses) interp.plot_confusion_matrix(figsize=(12,12), dpi=60) interp.most_confused(min_val=2) Explanation: Results Let's see what results we have got. We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not. In this case the mistakes look reasonable (none of the mistakes seems obviously naive). This is an indicator that our classifier is working correctly. Furthermore, when we plot the confusion matrix, we can see that the distribution is heavily skewed: the model makes the same mistakes over and over again but it rarely confuses other categories. This suggests that it just finds it difficult to distinguish some specific categories between each other; this is normal behaviour. End of explanation learn.unfreeze() learn.fit_one_cycle(1) learn.load('stage-1'); learn.lr_find() learn.recorder.plot() learn.unfreeze() learn.fit_one_cycle(2, max_lr=slice(1e-6,1e-4)) Explanation: Unfreezing, fine-tuning, and learning rates Since our model is working as we expect it to, we will unfreeze our model and train some more. End of explanation data = ImageDataBunch.from_name_re(path_img, fnames, pat, ds_tfms=get_transforms(), size=299, bs=bs//2).normalize(imagenet_stats) learn = cnn_learner(data, models.resnet50, metrics=error_rate) learn.lr_find() learn.recorder.plot() learn.fit_one_cycle(8) learn.save('stage-1-50') Explanation: That's a pretty accurate model! Training: resnet50 Now we will train in the same way as before but with one caveat: instead of using resnet34 as our backbone we will use resnet50 (resnet34 is a 34 layer residual network while resnet50 has 50 layers. It will be explained later in the course and you can learn the details in the resnet paper). Basically, resnet50 usually performs better because it is a deeper network with more parameters. Let's see if we can achieve a higher performance here. To help it along, let's us use larger images too, since that way the network can see more detail. We reduce the batch size a bit since otherwise this larger network will require more GPU memory. End of explanation learn.unfreeze() learn.fit_one_cycle(3, max_lr=slice(1e-6,1e-4)) Explanation: It's astonishing that it's possible to recognize pet breeds so accurately! Let's see if full fine-tuning helps: End of explanation learn.load('stage-1-50'); interp = ClassificationInterpretation.from_learner(learn) interp.most_confused(min_val=2) Explanation: If it doesn't, you can always go back to your previous model. End of explanation path = untar_data(URLs.MNIST_SAMPLE); path tfms = get_transforms(do_flip=False) data = ImageDataBunch.from_folder(path, ds_tfms=tfms, size=26) data.show_batch(rows=3, figsize=(5,5)) learn = cnn_learner(data, models.resnet18, metrics=accuracy) learn.fit(2) df = pd.read_csv(path/'labels.csv') df.head() data = ImageDataBunch.from_csv(path, ds_tfms=tfms, size=28) data.show_batch(rows=3, figsize=(5,5)) data.classes data = ImageDataBunch.from_df(path, df, ds_tfms=tfms, size=24) data.classes fn_paths = [path/name for name in df['name']]; fn_paths[:2] pat = r"/(\d)/\d+\.png$" data = ImageDataBunch.from_name_re(path, fn_paths, pat=pat, ds_tfms=tfms, size=24) data.classes data = ImageDataBunch.from_name_func(path, fn_paths, ds_tfms=tfms, size=24, label_func = lambda x: '3' if '/3/' in str(x) else '7') data.classes labels = [('3' if '/3/' in str(x) else '7') for x in fn_paths] labels[:5] data = ImageDataBunch.from_lists(path, fn_paths, labels=labels, ds_tfms=tfms, size=24) data.classes Explanation: Other data formats End of explanation
5,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Példa 1 Step1: A stack egymásra rakja az oszlopokat. Step2: Most nem teljesen jó, mert előbb az országot és a tevékenységet ki kellene ragadjuk onnan. Ezért indexet csinálunk belőlük. Step3: Az eddig műveleteket memóriában végeztük. Most felülírjuk a dfet. Step4: reset_index paranccsal újra visszatesszük az index oszlopot az adatoszlopok közé. Step5: Átnevezzük az oszlopokat azzá amit szeretnénk. Step6: Az év és érték oszlopokat előbb egész számmá kell konvertáljuk plottolás előtt. Step7: A space karaktereket először ki kell cseréljük. A pandasban a replace függvény a teljes cella tartalmára vonatkozik, ezért a str.replpace-t használjuk. Step8: Mentés Step9: Példa 2
Python Code: df=pd.read_excel('formazottbi2.xlsx') df Explanation: Példa 1 End of explanation pd.DataFrame(df.stack()).head() Explanation: A stack egymásra rakja az oszlopokat. End of explanation df.columns df.set_index(['Tevékenység','Ország']).head(2) Explanation: Most nem teljesen jó, mert előbb az országot és a tevékenységet ki kellene ragadjuk onnan. Ezért indexet csinálunk belőlük. End of explanation df=pd.DataFrame(df.set_index(['Tevékenység','Ország']).stack()) Explanation: Az eddig műveleteket memóriában végeztük. Most felülírjuk a dfet. End of explanation df=df.reset_index() df.head() Explanation: reset_index paranccsal újra visszatesszük az index oszlopot az adatoszlopok közé. End of explanation df.columns=['Tevékenység', 'Ország','Év','Érték'] df.head() Explanation: Átnevezzük az oszlopokat azzá amit szeretnénk. End of explanation df['Év']=df['Év'].astype(int) Explanation: Az év és érték oszlopokat előbb egész számmá kell konvertáljuk plottolás előtt. End of explanation import numpy as np df['Érték']=df['Érték'].str.replace('\xa0','')\ .str.replace('..','') df['Érték']=df['Érték'].replace('b','').replace('e','').replace('',np.nan).astype(float) df.plot(x='Év',y='Érték') Explanation: A space karaktereket először ki kell cseréljük. A pandasban a replace függvény a teljes cella tartalmára vonatkozik, ezért a str.replpace-t használjuk. End of explanation df.to_excel('bi_formazott.xlsx') df.to_csv('bi_formazott.csv') Explanation: Mentés End of explanation dg=pd.read_csv('data_tobbacco_europe_filtered.csv') dg.head() dg.columns dg.T.head() dh=dg.T dh.index[0] dh.columns=dh.loc[dh.index[0]] dh=dh.loc[dh.index[1:]] dh=dh.set_index('Country',append=True).T dh.head(2) import numpy as np dh=pd.DataFrame(dh.set_index(dh.columns[0],append=True).\ replace('Not available',np.nan).astype(float).stack().stack()).reset_index() dh.head(2) dh.columns=['Ország','Év','Nem','Kérdés','Érték'] dh.to_excel('cigi.xlsx') Explanation: Példa 2 End of explanation
5,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian perspective. It also contains tips and data visualization techniques for assessing goodness-of-fit for your Bayesian model. A little more on PyMC Parent and Child relationships To assist with describing Bayesian relationships, and to be consistent with PyMC's documentation, we introduce parent and child variables. parent variables are variables that influence another variable. child variable are variables that are affected by other variables, i.e. are the subject of parent variables. A variable can be both a parent and child. For example, consider the PyMC code below. Step1: parameter controls the parameter of data_generator, hence influences its values. The former is a parent of the latter. By symmetry, data_generator is a child of parameter. Likewise, data_generator is a parent to the variable data_plus_one (hence making data_generator both a parent and child variable). Although it does not look like one, data_plus_one should be treated as a PyMC variable as it is a function of another PyMC variable, hence is a child variable to data_generator. This nomenclature is introduced to help us describe relationships in PyMC modeling. You can access a variable's children and parent variables using the children and parents attributes attached to variables. Step2: Of course a child can have more than one parent, and a parent can have many children. PyMC Variables All PyMC variables also expose a value attribute. This method produces the current (possibly random) internal value of the variable. If the variable is a child variable, its value changes given the variable's parents' values. Using the same variables from before Step3: PyMC is concerned with two types of programming variables Step4: The call to random stores a new value into the variable's value attribute. In fact, this new value is stored in the computer's cache for faster recall and efficiency. Warning Step5: The use of the deterministic wrapper was seen in the previous chapter's text-message example. Recall the model for $\lambda$ looked like Step6: Clearly, if $\tau, \lambda_1$ and $\lambda_2$ are known, then $\lambda$ is known completely, hence it is a deterministic variable. Inside the deterministic decorator, the Stochastic variables passed in behave like scalars or Numpy arrays (if multivariable), and not like Stochastic variables. For example, running the following Step7: To frame this in the notation of the first chapter, though this is a slight abuse of notation, we have specified $P(A)$. Our next goal is to include data/evidence/observations $X$ into our model. PyMC stochastic variables have a keyword argument observed which accepts a boolean (False by default). The keyword observed has a very simple role Step8: This is how we include data into our models Step9: Finally... We wrap all the created variables into a pm.Model class. With this Model class, we can analyze the variables as a single unit. This is an optional step, as the fitting algorithms can be sent an array of the variables rather than a Model class. I may or may not use this class in future examples ;) Step10: Modeling approaches A good starting point in Bayesian modeling is to think about how your data might have been generated. Put yourself in an omniscient position, and try to imagine how you would recreate the dataset. In the last chapter we investigated text message data. We begin by asking how our observations may have been generated Step11: 2. Draw $\lambda_1$ and $\lambda_2$ from an $\text{Exp}(\alpha)$ distribution Step12: 3. For days before $\tau$, represent the user's received SMS count by sampling from $\text{Poi}(\lambda_1)$, and sample from $\text{Poi}(\lambda_2)$ for days after $\tau$. For example Step13: 4. Plot the artificial dataset Step14: It is okay that our fictional dataset does not look like our observed dataset Step15: Later we will see how we use this to make predictions and test the appropriateness of our models. Example Step16: Had we had stronger beliefs, we could have expressed them in the prior above. For this example, consider $p_A = 0.05$, and $N = 1500$ users shown site A, and we will simulate whether the user made a purchase or not. To simulate this from $N$ trials, we will use a Bernoulli distribution Step17: The observed frequency is Step18: We combine the observations into the PyMC observed variable, and run our inference algorithm Step19: We plot the posterior distribution of the unknown $p_A$ below Step20: Our posterior distribution puts most weight near the true value of $p_A$, but also some weights in the tails. This is a measure of how uncertain we should be, given our observations. Try changing the number of observations, N, and observe how the posterior distribution changes. A and B Together A similar analysis can be done for site B's response data to determine the analogous $p_B$. But what we are really interested in is the difference between $p_A$ and $p_B$. Let's infer $p_A$, $p_B$, and $\text{delta} = p_A - p_B$, all at once. We can do this using PyMC's deterministic variables. (We'll assume for this exercise that $p_B = 0.04$, so $\text{delta} = 0.01$, $N_B = 750$ (significantly less than $N_A$) and we will simulate site B's data like we did for site A's data ) Step21: Below we plot the posterior distributions for the three unknowns Step22: Notice that as a result of N_B &lt; N_A, i.e. we have less data from site B, our posterior distribution of $p_B$ is fatter, implying we are less certain about the true value of $p_B$ than we are of $p_A$. With respect to the posterior distribution of $\text{delta}$, we can see that the majority of the distribution is above $\text{delta}=0$, implying there site A's response is likely better than site B's response. The probability this inference is incorrect is easily computable Step23: If this probability is too high for comfortable decision-making, we can perform more trials on site B (as site B has less samples to begin with, each additional data point for site B contributes more inferential "power" than each additional data point for site A). Try playing with the parameters true_p_A, true_p_B, N_A, and N_B, to see what the posterior of $\text{delta}$ looks like. Notice in all this, the difference in sample sizes between site A and site B was never mentioned Step24: The special case when $N = 1$ corresponds to the Bernoulli distribution. There is another connection between Bernoulli and Binomial random variables. If we have $X_1, X_2, ... , X_N$ Bernoulli random variables with the same $p$, then $Z = X_1 + X_2 + ... + X_N \sim \text{Binomial}(N, p )$. The expected value of a Bernoulli random variable is $p$. This can be seen by noting the more general Binomial random variable has expected value $Np$ and setting $N=1$. Example Step25: Again, thinking of our data-generation model, we assign Bernoulli random variables to the 100 students Step26: If we carry out the algorithm, the next step that occurs is the first coin-flip each student makes. This can be modeled again by sampling 100 Bernoulli random variables with $p=1/2$ Step27: Although not everyone flips a second time, we can still model the possible realization of second coin-flips Step28: Using these variables, we can return a possible realization of the observed proportion of "Yes" responses. We do this using a PyMC deterministic variable Step29: The line fc*t_a + (1-fc)*sc contains the heart of the Privacy algorithm. Elements in this array are 1 if and only if i) the first toss is heads and the student cheated or ii) the first toss is tails, and the second is heads, and are 0 else. Finally, the last line sums this vector and divides by float(N), produces a proportion. Step30: Next we need a dataset. After performing our coin-flipped interviews the researchers received 35 "Yes" responses. To put this into a relative perspective, if there truly were no cheaters, we should expect to see on average 1/4 of all responses being a "Yes" (half chance of having first coin land Tails, and another half chance of having second coin land Heads), so about 25 responses in a cheat-free world. On the other hand, if all students cheated, we should expect to see approximately 3/4 of all responses be "Yes". The researchers observe a Binomial random variable, with N = 100 and p = observed_proportion with value = 35 Step31: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. Step32: With regards to the above plot, we are still pretty uncertain about what the true frequency of cheaters might be, but we have narrowed it down to a range between 0.05 to 0.35 (marked by the solid lines). This is pretty good, as a priori we had no idea how many students might have cheated (hence the uniform distribution for our prior). On the other hand, it is also pretty bad since there is a .3 length window the true value most likely lives in. Have we even gained anything, or are we still too uncertain about the true frequency? I would argue, yes, we have discovered something. It is implausible, according to our posterior, that there are no cheaters, i.e. the posterior assigns low probability to $p=0$. Since we started with a uniform prior, treating all values of $p$ as equally plausible, but the data ruled out $p=0$ as a possibility, we can be confident that there were cheaters. This kind of algorithm can be used to gather private information from users and be reasonably confident that the data, though noisy, is truthful. Alternative PyMC Model Given a value for $p$ (which from our god-like position we know), we can find the probability the student will answer yes Step33: I could have typed p_skewed = 0.5*p + 0.25 instead for a one-liner, as the elementary operations of addition and scalar multiplication will implicitly create a deterministic variable, but I wanted to make the deterministic boilerplate explicit for clarity's sake. If we know the probability of respondents saying "Yes", which is p_skewed, and we have $N=100$ students, the number of "Yes" responses is a binomial random variable with parameters N and p_skewed. This is where we include our observed 35 "Yes" responses. In the declaration of the pm.Binomial, we include value = 35 and observed = True. Step34: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. Step35: More PyMC Tricks Protip Step36: The remainder of this chapter examines some practical examples of PyMC and PyMC modeling Step37: It looks clear that the probability of damage incidents occurring increases as the outside temperature decreases. We are interested in modeling the probability here because it does not look like there is a strict cutoff point between temperature and a damage incident occurring. The best we can do is ask "At temperature $t$, what is the probability of a damage incident?". The goal of this example is to answer that question. We need a function of temperature, call it $p(t)$, that is bounded between 0 and 1 (so as to model a probability) and changes from 1 to 0 as we increase temperature. There are actually many such functions, but the most popular choice is the logistic function. $$p(t) = \frac{1}{ 1 + e^{ \;\beta t } } $$ In this model, $\beta$ is the variable we are uncertain about. Below is the function plotted for $\beta = 1, 3, -5$. Step38: But something is missing. In the plot of the logistic function, the probability changes only near zero, but in our data above the probability changes around 65 to 70. We need to add a bias term to our logistic function Step39: Adding a constant term $\alpha$ amounts to shifting the curve left or right (hence why it is called a bias). Let's start modeling this in PyMC. The $\beta, \alpha$ parameters have no reason to be positive, bounded or relatively large, so they are best modeled by a Normal random variable, introduced next. Normal distributions A Normal random variable, denoted $X \sim N(\mu, 1/\tau)$, has a distribution with two parameters Step40: A Normal random variable can be take on any real number, but the variable is very likely to be relatively close to $\mu$. In fact, the expected value of a Normal is equal to its $\mu$ parameter Step41: We have our probabilities, but how do we connect them to our observed data? A Bernoulli random variable with parameter $p$, denoted $\text{Ber}(p)$, is a random variable that takes value 1 with probability $p$, and 0 else. Thus, our model can look like Step42: We have trained our model on the observed data, now we can sample values from the posterior. Let's look at the posterior distributions for $\alpha$ and $\beta$ Step43: All samples of $\beta$ are greater than 0. If instead the posterior was centered around 0, we may suspect that $\beta = 0$, implying that temperature has no effect on the probability of defect. Similarly, all $\alpha$ posterior values are negative and far away from 0, implying that it is correct to believe that $\alpha$ is significantly less than 0. Regarding the spread of the data, we are very uncertain about what the true parameters might be (though considering the low sample size and the large overlap of defects-to-nondefects this behaviour is perhaps expected). Next, let's look at the expected probability for a specific value of the temperature. That is, we average over all samples from the posterior to get a likely value for $p(t_i)$. Step44: Above we also plotted two possible realizations of what the actual underlying system might be. Both are equally likely as any other draw. The blue line is what occurs when we average all the 20000 possible dotted lines together. An interesting question to ask is for what temperatures are we most uncertain about the defect-probability? Below we plot the expected value line and the associated 95% intervals for each temperature. Step45: The 95% credible interval, or 95% CI, painted in purple, represents the interval, for each temperature, that contains 95% of the distribution. For example, at 65 degrees, we can be 95% sure that the probability of defect lies between 0.25 and 0.75. More generally, we can see that as the temperature nears 60 degrees, the CI's spread out over [0,1] quickly. As we pass 70 degrees, the CI's tighten again. This can give us insight about how to proceed next Step46: Is our model appropriate? The skeptical reader will say "You deliberately chose the logistic function for $p(t)$ and the specific priors. Perhaps other functions or priors will give different results. How do I know I have chosen a good model?" This is absolutely true. To consider an extreme situation, what if I had chosen the function $p(t) = 1,\; \forall t$, which guarantees a defect always occurring Step47: Note that the above plots are different (if you can think of a cleaner way to present this, please send a pull request and answer here!). We wish to assess how good our model is. "Good" is a subjective term of course, so results must be relative to other models. We will be doing this graphically as well, which may seem like an even less objective method. The alternative is to use Bayesian p-values. These are still subjective, as the proper cutoff between good and bad is arbitrary. Gelman emphasises that the graphical tests are more illuminating [7] than p-value tests. We agree. The following graphical test is a novel data-viz approach to logistic regression. The plots are called separation plots[8]. For a suite of models we wish to compare, each model is plotted on an individual separation plot. I leave most of the technical details about separation plots to the very accessible original paper, but I'll summarize their use here. For each model, we calculate the proportion of times the posterior simulation proposed a value of 1 for a particular temperature, i.e. compute $P( \;\text{Defect} = 1 | t, \alpha, \beta )$ by averaging. This gives us the posterior probability of a defect at each data point in our dataset. For example, for the model we used above Step48: Next we sort each column by the posterior probabilities Step49: We can present the above data better in a figure Step50: The snaking-line is the sorted probabilities, blue bars denote defects, and empty space (or grey bars for the optimistic readers) denote non-defects. As the probability rises, we see more and more defects occur. On the right hand side, the plot suggests that as the posterior probability is large (line close to 1), then more defects are realized. This is good behaviour. Ideally, all the blue bars should be close to the right-hand side, and deviations from this reflect missed predictions. The black vertical line is the expected number of defects we should observe, given this model. This allows the user to see how the total number of events predicted by the model compares to the actual number of events in the data. It is much more informative to compare this to separation plots for other models. Below we compare our model (top) versus three others Step51: In the random model, we can see that as the probability increases there is no clustering of defects to the right-hand side. Similarly for the constant model. The perfect model, the probability line is not well shown, as it is stuck to the bottom and top of the figure. Of course the perfect model is only for demonstration, and we cannot infer any scientific inference from it. Exercises 1. Try putting in extreme values for our observations in the cheating example. What happens if we observe 25 affirmative responses? 10? 50? 2. Try plotting $\alpha$ samples versus $\beta$ samples. Why might the resulting plot look like this? Step52: References [1] Dalal, Fowlkes and Hoadley (1989),JASA, 84, 945-957. [2] German Rodriguez. Datasets. In WWS509. Retrieved 30/01/2013, from http
Python Code: import pymc as pm parameter = pm.Exponential("poisson_param", 1) data_generator = pm.Poisson("data_generator", parameter) data_plus_one = data_generator + 1 Explanation: Chapter 2 This chapter introduces more PyMC syntax and design patterns, and ways to think about how to model a system from a Bayesian perspective. It also contains tips and data visualization techniques for assessing goodness-of-fit for your Bayesian model. A little more on PyMC Parent and Child relationships To assist with describing Bayesian relationships, and to be consistent with PyMC's documentation, we introduce parent and child variables. parent variables are variables that influence another variable. child variable are variables that are affected by other variables, i.e. are the subject of parent variables. A variable can be both a parent and child. For example, consider the PyMC code below. End of explanation print "Children of `parameter`: " print parameter.children print "\nParents of `data_generator`: " print data_generator.parents print "\nChildren of `data_generator`: " print data_generator.children Explanation: parameter controls the parameter of data_generator, hence influences its values. The former is a parent of the latter. By symmetry, data_generator is a child of parameter. Likewise, data_generator is a parent to the variable data_plus_one (hence making data_generator both a parent and child variable). Although it does not look like one, data_plus_one should be treated as a PyMC variable as it is a function of another PyMC variable, hence is a child variable to data_generator. This nomenclature is introduced to help us describe relationships in PyMC modeling. You can access a variable's children and parent variables using the children and parents attributes attached to variables. End of explanation print "parameter.value =", parameter.value print "data_generator.value =", data_generator.value print "data_plus_one.value =", data_plus_one.value Explanation: Of course a child can have more than one parent, and a parent can have many children. PyMC Variables All PyMC variables also expose a value attribute. This method produces the current (possibly random) internal value of the variable. If the variable is a child variable, its value changes given the variable's parents' values. Using the same variables from before: End of explanation lambda_1 = pm.Exponential("lambda_1", 1) # prior on first behaviour lambda_2 = pm.Exponential("lambda_2", 1) # prior on second behaviour tau = pm.DiscreteUniform("tau", lower=0, upper=10) # prior on behaviour change print "lambda_1.value = %.3f" % lambda_1.value print "lambda_2.value = %.3f" % lambda_2.value print "tau.value = %.3f" % tau.value print lambda_1.random(), lambda_2.random(), tau.random() print "After calling random() on the variables..." print "lambda_1.value = %.3f" % lambda_1.value print "lambda_2.value = %.3f" % lambda_2.value print "tau.value = %.3f" % tau.value Explanation: PyMC is concerned with two types of programming variables: stochastic and deterministic. stochastic variables are variables that are not deterministic, i.e., even if you knew all the values of the variables' parents (if it even has any parents), it would still be random. Included in this category are instances of classes Poisson, DiscreteUniform, and Exponential. deterministic variables are variables that are not random if the variables' parents were known. This might be confusing at first: a quick mental check is if I knew all of variable foo's parent variables, I could determine what foo's value is. We will detail each below. Initializing Stochastic variables Initializing a stochastic variable requires a name argument, plus additional parameters that are class specific. For example: some_variable = pm.DiscreteUniform("discrete_uni_var", 0, 4) where 0, 4 are the DiscreteUniform-specific lower and upper bound on the random variable. The PyMC docs contain the specific parameters for stochastic variables. (Or use object??, for example pm.DiscreteUniform?? if you are using IPython!) The name attribute is used to retrieve the posterior distribution later in the analysis, so it is best to use a descriptive name. Typically, I use the Python variable's name as the name. For multivariable problems, rather than creating a Python array of stochastic variables, addressing the size keyword in the call to a Stochastic variable creates multivariate array of (independent) stochastic variables. The array behaves like a Numpy array when used like one, and references to its value attribute return Numpy arrays. The size argument also solves the annoying case where you may have many variables $\beta_i, \; i = 1,...,N$ you wish to model. Instead of creating arbitrary names and variables for each one, like: beta_1 = pm.Uniform("beta_1", 0, 1) beta_2 = pm.Uniform("beta_2", 0, 1) ... we can instead wrap them into a single variable: betas = pm.Uniform("betas", 0, 1, size=N) Calling random() We can also call on a stochastic variable's random() method, which (given the parent values) will generate a new, random value. Below we demonstrate this using the texting example from the previous chapter. End of explanation type(lambda_1 + lambda_2) Explanation: The call to random stores a new value into the variable's value attribute. In fact, this new value is stored in the computer's cache for faster recall and efficiency. Warning: Don't update stochastic variables' values in-place. Straight from the PyMC docs, we quote [4]: Stochastic objects' values should not be updated in-place. This confuses PyMC's caching scheme... The only way a stochastic variable's value should be updated is using statements of the following form: A.value = new_value The following are in-place updates and should never be used: A.value += 3 A.value[2,1] = 5 A.value.attribute = new_attribute_value Deterministic variables Since most variables you will be modeling are stochastic, we distinguish deterministic variables with a pymc.deterministic wrapper. (If you are unfamiliar with Python wrappers (also called decorators), that's no problem. Just prepend the pymc.deterministic decorator before the variable declaration and you're good to go. No need to know more. ) The declaration of a deterministic variable uses a Python function: @pm.deterministic def some_deterministic_var(v1=v1,): #jelly goes here. For all purposes, we can treat the object some_deterministic_var as a variable and not a Python function. Prepending with the wrapper is the easiest way, but not the only way, to create deterministic variables: elementary operations, like addition, exponentials etc. implicitly create deterministic variables. For example, the following returns a deterministic variable: End of explanation import numpy as np n_data_points = 5 # in CH1 we had ~70 data points @pm.deterministic def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2): out = np.zeros(n_data_points) out[:tau] = lambda_1 # lambda before tau is lambda1 out[tau:] = lambda_2 # lambda after tau is lambda2 return out Explanation: The use of the deterministic wrapper was seen in the previous chapter's text-message example. Recall the model for $\lambda$ looked like: $$ \lambda = \begin{cases} \lambda_1 & \text{if } t \lt \tau \cr \lambda_2 & \text{if } t \ge \tau \end{cases} $$ And in PyMC code: End of explanation %matplotlib inline from IPython.core.pylabtools import figsize from matplotlib import pyplot as plt figsize(12.5, 4) samples = [lambda_1.random() for i in range(20000)] plt.hist(samples, bins=70, normed=True, histtype="stepfilled") plt.title("Prior distribution for $\lambda_1$") plt.xlim(0, 8); Explanation: Clearly, if $\tau, \lambda_1$ and $\lambda_2$ are known, then $\lambda$ is known completely, hence it is a deterministic variable. Inside the deterministic decorator, the Stochastic variables passed in behave like scalars or Numpy arrays (if multivariable), and not like Stochastic variables. For example, running the following: @pm.deterministic def some_deterministic(stoch=some_stochastic_var): return stoch.value**2 will return an AttributeError detailing that stoch does not have a value attribute. It simply needs to be stoch**2. During the learning phase, it's the variable's value that is repeatedly passed in, not the actual variable. Notice in the creation of the deterministic function we added defaults to each variable used in the function. This is a necessary step, and all variables must have default values. Including observations in the Model At this point, it may not look like it, but we have fully specified our priors. For example, we can ask and answer questions like "What does my prior distribution of $\lambda_1$ look like?" End of explanation data = np.array([10, 5]) fixed_variable = pm.Poisson("fxd", 1, value=data, observed=True) print "value: ", fixed_variable.value print "calling .random()" fixed_variable.random() print "value: ", fixed_variable.value Explanation: To frame this in the notation of the first chapter, though this is a slight abuse of notation, we have specified $P(A)$. Our next goal is to include data/evidence/observations $X$ into our model. PyMC stochastic variables have a keyword argument observed which accepts a boolean (False by default). The keyword observed has a very simple role: fix the variable's current value, i.e. make value immutable. We have to specify an initial value in the variable's creation, equal to the observations we wish to include, typically an array (and it should be an Numpy array for speed). For example: End of explanation # We're using some fake data here data = np.array([10, 25, 15, 20, 35]) obs = pm.Poisson("obs", lambda_, value=data, observed=True) print obs.value Explanation: This is how we include data into our models: initializing a stochastic variable to have a fixed value. To complete our text message example, we fix the PyMC variable observations to the observed dataset. End of explanation model = pm.Model([obs, lambda_, lambda_1, lambda_2, tau]) Explanation: Finally... We wrap all the created variables into a pm.Model class. With this Model class, we can analyze the variables as a single unit. This is an optional step, as the fitting algorithms can be sent an array of the variables rather than a Model class. I may or may not use this class in future examples ;) End of explanation tau = pm.rdiscrete_uniform(0, 80) print tau Explanation: Modeling approaches A good starting point in Bayesian modeling is to think about how your data might have been generated. Put yourself in an omniscient position, and try to imagine how you would recreate the dataset. In the last chapter we investigated text message data. We begin by asking how our observations may have been generated: We started by thinking "what is the best random variable to describe this count data?" A Poisson random variable is a good candidate because it can represent count data. So we model the number of sms's received as sampled from a Poisson distribution. Next, we think, "Ok, assuming sms's are Poisson-distributed, what do I need for the Poisson distribution?" Well, the Poisson distribution has a parameter $\lambda$. Do we know $\lambda$? No. In fact, we have a suspicion that there are two $\lambda$ values, one for the earlier behaviour and one for the latter behaviour. We don't know when the behaviour switches though, but call the switchpoint $\tau$. What is a good distribution for the two $\lambda$s? The exponential is good, as it assigns probabilities to positive real numbers. Well the exponential distribution has a parameter too, call it $\alpha$. Do we know what the parameter $\alpha$ might be? No. At this point, we could continue and assign a distribution to $\alpha$, but it's better to stop once we reach a set level of ignorance: whereas we have a prior belief about $\lambda$, ("it probably changes over time", "it's likely between 10 and 30", etc.), we don't really have any strong beliefs about $\alpha$. So it's best to stop here. What is a good value for $\alpha$ then? We think that the $\lambda$s are between 10-30, so if we set $\alpha$ really low (which corresponds to larger probability on high values) we are not reflecting our prior well. Similar, a too-high alpha misses our prior belief as well. A good idea for $\alpha$ as to reflect our belief is to set the value so that the mean of $\lambda$, given $\alpha$, is equal to our observed mean. This was shown in the last chapter. We have no expert opinion of when $\tau$ might have occurred. So we will suppose $\tau$ is from a discrete uniform distribution over the entire timespan. Below we give a graphical visualization of this, where arrows denote parent-child relationships. (provided by the Daft Python library ) <img src="http://i.imgur.com/7J30oCG.png" width = 700/> PyMC, and other probabilistic programming languages, have been designed to tell these data-generation stories. More generally, B. Cronin writes [5]: Probabilistic programming will unlock narrative explanations of data, one of the holy grails of business analytics and the unsung hero of scientific persuasion. People think in terms of stories - thus the unreasonable power of the anecdote to drive decision-making, well-founded or not. But existing analytics largely fails to provide this kind of story; instead, numbers seemingly appear out of thin air, with little of the causal context that humans prefer when weighing their options. Same story; different ending. Interestingly, we can create new datasets by retelling the story. For example, if we reverse the above steps, we can simulate a possible realization of the dataset. 1. Specify when the user's behaviour switches by sampling from $\text{DiscreteUniform}(0, 80)$: End of explanation alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) print lambda_1, lambda_2 Explanation: 2. Draw $\lambda_1$ and $\lambda_2$ from an $\text{Exp}(\alpha)$ distribution: End of explanation data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] Explanation: 3. For days before $\tau$, represent the user's received SMS count by sampling from $\text{Poi}(\lambda_1)$, and sample from $\text{Poi}(\lambda_2)$ for days after $\tau$. For example: End of explanation plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlabel("Time (days)") plt.ylabel("count of text-msgs received") plt.title("Artificial dataset") plt.xlim(0, 80) plt.legend(); Explanation: 4. Plot the artificial dataset: End of explanation def plot_artificial_sms_dataset(): tau = pm.rdiscrete_uniform(0, 80) alpha = 1. / 20. lambda_1, lambda_2 = pm.rexponential(alpha, 2) data = np.r_[pm.rpoisson(lambda_1, tau), pm.rpoisson(lambda_2, 80 - tau)] plt.bar(np.arange(80), data, color="#348ABD") plt.bar(tau - 1, data[tau - 1], color="r", label="user behaviour changed") plt.xlim(0, 80) figsize(12.5, 5) plt.suptitle("More examples of artificial datasets", fontsize=14) for i in range(1, 5): plt.subplot(4, 1, i) plot_artificial_sms_dataset() Explanation: It is okay that our fictional dataset does not look like our observed dataset: the probability is incredibly small it indeed would. PyMC's engine is designed to find good parameters, $\lambda_i, \tau$, that maximize this probability. The ability to generate artificial datasets is an interesting side effect of our modeling, and we will see that this ability is a very important method of Bayesian inference. We produce a few more datasets below: End of explanation import pymc as pm # The parameters are the bounds of the Uniform. p = pm.Uniform('p', lower=0, upper=1) Explanation: Later we will see how we use this to make predictions and test the appropriateness of our models. Example: Bayesian A/B testing A/B testing is a statistical design pattern for determining the difference of effectiveness between two different treatments. For example, a pharmaceutical company is interested in the effectiveness of drug A vs drug B. The company will test drug A on some fraction of their trials, and drug B on the other fraction (this fraction is often 1/2, but we will relax this assumption). After performing enough trials, the in-house statisticians sift through the data to determine which drug yielded better results. Similarly, front-end web developers are interested in which design of their website yields more sales or some other metric of interest. They will route some fraction of visitors to site A, and the other fraction to site B, and record if the visit yielded a sale or not. The data is recorded (in real-time), and analyzed afterwards. Often, the post-experiment analysis is done using something called a hypothesis test like difference of means test or difference of proportions test. This involves often misunderstood quantities like a "Z-score" and even more confusing "p-values" (please don't ask). If you have taken a statistics course, you have probably been taught this technique (though not necessarily learned this technique). And if you were like me, you may have felt uncomfortable with their derivation -- good: the Bayesian approach to this problem is much more natural. A Simple Case As this is a hacker book, we'll continue with the web-dev example. For the moment, we will focus on the analysis of site A only. Assume that there is some true $0 \lt p_A \lt 1$ probability that users who, upon shown site A, eventually purchase from the site. This is the true effectiveness of site A. Currently, this quantity is unknown to us. Suppose site A was shown to $N$ people, and $n$ people purchased from the site. One might conclude hastily that $p_A = \frac{n}{N}$. Unfortunately, the observed frequency $\frac{n}{N}$ does not necessarily equal $p_A$ -- there is a difference between the observed frequency and the true frequency of an event. The true frequency can be interpreted as the probability of an event occurring. For example, the true frequency of rolling a 1 on a 6-sided die is $\frac{1}{6}$. Knowing the true frequency of events like: fraction of users who make purchases, frequency of social attributes, percent of internet users with cats etc. are common requests we ask of Nature. Unfortunately, often Nature hides the true frequency from us and we must infer it from observed data. The observed frequency is then the frequency we observe: say rolling the die 100 times you may observe 20 rolls of 1. The observed frequency, 0.2, differs from the true frequency, $\frac{1}{6}$. We can use Bayesian statistics to infer probable values of the true frequency using an appropriate prior and observed data. With respect to our A/B example, we are interested in using what we know, $N$ (the total trials administered) and $n$ (the number of conversions), to estimate what $p_A$, the true frequency of buyers, might be. To set up a Bayesian model, we need to assign prior distributions to our unknown quantities. A priori, what do we think $p_A$ might be? For this example, we have no strong conviction about $p_A$, so for now, let's assume $p_A$ is uniform over [0,1]: End of explanation # set constants p_true = 0.05 # remember, this is unknown. N = 1500 # sample N Bernoulli random variables from Ber(0.05). # each random variable has a 0.05 chance of being a 1. # this is the data-generation step occurrences = pm.rbernoulli(p_true, N) print occurrences # Remember: Python treats True == 1, and False == 0 print occurrences.sum() Explanation: Had we had stronger beliefs, we could have expressed them in the prior above. For this example, consider $p_A = 0.05$, and $N = 1500$ users shown site A, and we will simulate whether the user made a purchase or not. To simulate this from $N$ trials, we will use a Bernoulli distribution: if $X\ \sim \text{Ber}(p)$, then $X$ is 1 with probability $p$ and 0 with probability $1 - p$. Of course, in practice we do not know $p_A$, but we will use it here to simulate the data. End of explanation # Occurrences.mean is equal to n/N. print "What is the observed frequency in Group A? %.4f" % occurrences.mean() print "Does this equal the true frequency? %s" % (occurrences.mean() == p_true) Explanation: The observed frequency is: End of explanation # include the observations, which are Bernoulli obs = pm.Bernoulli("obs", p, value=occurrences, observed=True) # To be explained in chapter 3 mcmc = pm.MCMC([p, obs]) mcmc.sample(18000, 1000) Explanation: We combine the observations into the PyMC observed variable, and run our inference algorithm: End of explanation figsize(12.5, 4) plt.title("Posterior distribution of $p_A$, the true effectiveness of site A") plt.vlines(p_true, 0, 90, linestyle="--", label="true $p_A$ (unknown)") plt.hist(mcmc.trace("p")[:], bins=25, histtype="stepfilled", normed=True) plt.legend() Explanation: We plot the posterior distribution of the unknown $p_A$ below: End of explanation import pymc as pm figsize(12, 4) # these two quantities are unknown to us. true_p_A = 0.05 true_p_B = 0.04 # notice the unequal sample sizes -- no problem in Bayesian analysis. N_A = 1500 N_B = 750 # generate some observations observations_A = pm.rbernoulli(true_p_A, N_A) observations_B = pm.rbernoulli(true_p_B, N_B) print "Obs from Site A: ", observations_A[:30].astype(int), "..." print "Obs from Site B: ", observations_B[:30].astype(int), "..." print observations_A.mean() print observations_B.mean() # Set up the pymc model. Again assume Uniform priors for p_A and p_B. p_A = pm.Uniform("p_A", 0, 1) p_B = pm.Uniform("p_B", 0, 1) # Define the deterministic delta function. This is our unknown of interest. @pm.deterministic def delta(p_A=p_A, p_B=p_B): return p_A - p_B # Set of observations, in this case we have two observation datasets. obs_A = pm.Bernoulli("obs_A", p_A, value=observations_A, observed=True) obs_B = pm.Bernoulli("obs_B", p_B, value=observations_B, observed=True) # To be explained in chapter 3. mcmc = pm.MCMC([p_A, p_B, delta, obs_A, obs_B]) mcmc.sample(20000, 1000) Explanation: Our posterior distribution puts most weight near the true value of $p_A$, but also some weights in the tails. This is a measure of how uncertain we should be, given our observations. Try changing the number of observations, N, and observe how the posterior distribution changes. A and B Together A similar analysis can be done for site B's response data to determine the analogous $p_B$. But what we are really interested in is the difference between $p_A$ and $p_B$. Let's infer $p_A$, $p_B$, and $\text{delta} = p_A - p_B$, all at once. We can do this using PyMC's deterministic variables. (We'll assume for this exercise that $p_B = 0.04$, so $\text{delta} = 0.01$, $N_B = 750$ (significantly less than $N_A$) and we will simulate site B's data like we did for site A's data ) End of explanation p_A_samples = mcmc.trace("p_A")[:] p_B_samples = mcmc.trace("p_B")[:] delta_samples = mcmc.trace("delta")[:] figsize(12.5, 10) # histogram of posteriors ax = plt.subplot(311) plt.xlim(0, .1) plt.hist(p_A_samples, histtype='stepfilled', bins=25, alpha=0.85, label="posterior of $p_A$", color="#A60628", normed=True) plt.vlines(true_p_A, 0, 80, linestyle="--", label="true $p_A$ (unknown)") plt.legend(loc="upper right") plt.title("Posterior distributions of $p_A$, $p_B$, and delta unknowns") ax = plt.subplot(312) plt.xlim(0, .1) plt.hist(p_B_samples, histtype='stepfilled', bins=25, alpha=0.85, label="posterior of $p_B$", color="#467821", normed=True) plt.vlines(true_p_B, 0, 80, linestyle="--", label="true $p_B$ (unknown)") plt.legend(loc="upper right") ax = plt.subplot(313) plt.hist(delta_samples, histtype='stepfilled', bins=30, alpha=0.85, label="posterior of delta", color="#7A68A6", normed=True) plt.vlines(true_p_A - true_p_B, 0, 60, linestyle="--", label="true delta (unknown)") plt.vlines(0, 0, 60, color="black", alpha=0.2) plt.legend(loc="upper right"); Explanation: Below we plot the posterior distributions for the three unknowns: End of explanation # Count the number of samples less than 0, i.e. the area under the curve # before 0, represent the probability that site A is worse than site B. print "Probability site A is WORSE than site B: %.3f" % \ (delta_samples < 0).mean() print "Probability site A is BETTER than site B: %.3f" % \ (delta_samples > 0).mean() Explanation: Notice that as a result of N_B &lt; N_A, i.e. we have less data from site B, our posterior distribution of $p_B$ is fatter, implying we are less certain about the true value of $p_B$ than we are of $p_A$. With respect to the posterior distribution of $\text{delta}$, we can see that the majority of the distribution is above $\text{delta}=0$, implying there site A's response is likely better than site B's response. The probability this inference is incorrect is easily computable: End of explanation figsize(12.5, 4) import scipy.stats as stats binomial = stats.binom parameters = [(10, .4), (10, .9)] colors = ["#348ABD", "#A60628"] for i in range(2): N, p = parameters[i] _x = np.arange(N + 1) plt.bar(_x - 0.5, binomial.pmf(_x, N, p), color=colors[i], edgecolor=colors[i], alpha=0.6, label="$N$: %d, $p$: %.1f" % (N, p), linewidth=3) plt.legend(loc="upper left") plt.xlim(0, 10.5) plt.xlabel("$k$") plt.ylabel("$P(X = k)$") plt.title("Probability mass distributions of binomial random variables"); Explanation: If this probability is too high for comfortable decision-making, we can perform more trials on site B (as site B has less samples to begin with, each additional data point for site B contributes more inferential "power" than each additional data point for site A). Try playing with the parameters true_p_A, true_p_B, N_A, and N_B, to see what the posterior of $\text{delta}$ looks like. Notice in all this, the difference in sample sizes between site A and site B was never mentioned: it naturally fits into Bayesian analysis. I hope the readers feel this style of A/B testing is more natural than hypothesis testing, which has probably confused more than helped practitioners. Later in this book, we will see two extensions of this model: the first to help dynamically adjust for bad sites, and the second will improve the speed of this computation by reducing the analysis to a single equation. An algorithm for human deceit Social data has an additional layer of interest as people are not always honest with responses, which adds a further complication into inference. For example, simply asking individuals "Have you ever cheated on a test?" will surely contain some rate of dishonesty. What you can say for certain is that the true rate is less than your observed rate (assuming individuals lie only about not cheating; I cannot imagine one who would admit "Yes" to cheating when in fact they hadn't cheated). To present an elegant solution to circumventing this dishonesty problem, and to demonstrate Bayesian modeling, we first need to introduce the binomial distribution. The Binomial Distribution The binomial distribution is one of the most popular distributions, mostly because of its simplicity and usefulness. Unlike the other distributions we have encountered thus far in the book, the binomial distribution has 2 parameters: $N$, a positive integer representing $N$ trials or number of instances of potential events, and $p$, the probability of an event occurring in a single trial. Like the Poisson distribution, it is a discrete distribution, but unlike the Poisson distribution, it only weighs integers from $0$ to $N$. The mass distribution looks like: $$P( X = k ) = {{N}\choose{k}} p^k(1-p)^{N-k}$$ If $X$ is a binomial random variable with parameters $p$ and $N$, denoted $X \sim \text{Bin}(N,p)$, then $X$ is the number of events that occurred in the $N$ trials (obviously $0 \le X \le N$), and $p$ is the probability of a single event. The larger $p$ is (while still remaining between 0 and 1), the more events are likely to occur. The expected value of a binomial is equal to $Np$. Below we plot the mass probability distribution for varying parameters. End of explanation import pymc as pm N = 100 p = pm.Uniform("freq_cheating", 0, 1) Explanation: The special case when $N = 1$ corresponds to the Bernoulli distribution. There is another connection between Bernoulli and Binomial random variables. If we have $X_1, X_2, ... , X_N$ Bernoulli random variables with the same $p$, then $Z = X_1 + X_2 + ... + X_N \sim \text{Binomial}(N, p )$. The expected value of a Bernoulli random variable is $p$. This can be seen by noting the more general Binomial random variable has expected value $Np$ and setting $N=1$. Example: Cheating among students We will use the binomial distribution to determine the frequency of students cheating during an exam. If we let $N$ be the total number of students who took the exam, and assuming each student is interviewed post-exam (answering without consequence), we will receive integer $X$ "Yes I did cheat" answers. We then find the posterior distribution of $p$, given $N$, some specified prior on $p$, and observed data $X$. This is a completely absurd model. No student, even with a free-pass against punishment, would admit to cheating. What we need is a better algorithm to ask students if they had cheated. Ideally the algorithm should encourage individuals to be honest while preserving privacy. The following proposed algorithm is a solution I greatly admire for its ingenuity and effectiveness: In the interview process for each student, the student flips a coin, hidden from the interviewer. The student agrees to answer honestly if the coin comes up heads. Otherwise, if the coin comes up tails, the student (secretly) flips the coin again, and answers "Yes, I did cheat" if the coin flip lands heads, and "No, I did not cheat", if the coin flip lands tails. This way, the interviewer does not know if a "Yes" was the result of a guilty plea, or a Heads on a second coin toss. Thus privacy is preserved and the researchers receive honest answers. I call this the Privacy Algorithm. One could of course argue that the interviewers are still receiving false data since some Yes's are not confessions but instead randomness, but an alternative perspective is that the researchers are discarding approximately half of their original dataset since half of the responses will be noise. But they have gained a systematic data generation process that can be modeled. Furthermore, they do not have to incorporate (perhaps somewhat naively) the possibility of deceitful answers. We can use PyMC to dig through this noisy model, and find a posterior distribution for the true frequency of liars. Suppose 100 students are being surveyed for cheating, and we wish to find $p$, the proportion of cheaters. There are a few ways we can model this in PyMC. I'll demonstrate the most explicit way, and later show a simplified version. Both versions arrive at the same inference. In our data-generation model, we sample $p$, the true proportion of cheaters, from a prior. Since we are quite ignorant about $p$, we will assign it a $\text{Uniform}(0,1)$ prior. End of explanation true_answers = pm.Bernoulli("truths", p, size=N) Explanation: Again, thinking of our data-generation model, we assign Bernoulli random variables to the 100 students: 1 implies they cheated and 0 implies they did not. End of explanation first_coin_flips = pm.Bernoulli("first_flips", 0.5, size=N) print first_coin_flips.value Explanation: If we carry out the algorithm, the next step that occurs is the first coin-flip each student makes. This can be modeled again by sampling 100 Bernoulli random variables with $p=1/2$: denote a 1 as a Heads and 0 a Tails. End of explanation second_coin_flips = pm.Bernoulli("second_flips", 0.5, size=N) Explanation: Although not everyone flips a second time, we can still model the possible realization of second coin-flips: End of explanation @pm.deterministic def observed_proportion(t_a=true_answers, fc=first_coin_flips, sc=second_coin_flips): observed = fc * t_a + (1 - fc) * sc return observed.sum() / float(N) Explanation: Using these variables, we can return a possible realization of the observed proportion of "Yes" responses. We do this using a PyMC deterministic variable: End of explanation observed_proportion.value Explanation: The line fc*t_a + (1-fc)*sc contains the heart of the Privacy algorithm. Elements in this array are 1 if and only if i) the first toss is heads and the student cheated or ii) the first toss is tails, and the second is heads, and are 0 else. Finally, the last line sums this vector and divides by float(N), produces a proportion. End of explanation X = 35 observations = pm.Binomial("obs", N, observed_proportion, observed=True, value=X) Explanation: Next we need a dataset. After performing our coin-flipped interviews the researchers received 35 "Yes" responses. To put this into a relative perspective, if there truly were no cheaters, we should expect to see on average 1/4 of all responses being a "Yes" (half chance of having first coin land Tails, and another half chance of having second coin land Heads), so about 25 responses in a cheat-free world. On the other hand, if all students cheated, we should expect to see approximately 3/4 of all responses be "Yes". The researchers observe a Binomial random variable, with N = 100 and p = observed_proportion with value = 35: End of explanation model = pm.Model([p, true_answers, first_coin_flips, second_coin_flips, observed_proportion, observations]) # To be explained in Chapter 3! mcmc = pm.MCMC(model) mcmc.sample(40000, 15000) figsize(12.5, 3) p_trace = mcmc.trace("freq_cheating")[:] plt.hist(p_trace, histtype="stepfilled", normed=True, alpha=0.85, bins=30, label="posterior distribution", color="#348ABD") plt.vlines([.05, .35], [0, 0], [5, 5], alpha=0.3) plt.xlim(0, 1) plt.legend(); Explanation: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. End of explanation p = pm.Uniform("freq_cheating", 0, 1) @pm.deterministic def p_skewed(p=p): return 0.5 * p + 0.25 Explanation: With regards to the above plot, we are still pretty uncertain about what the true frequency of cheaters might be, but we have narrowed it down to a range between 0.05 to 0.35 (marked by the solid lines). This is pretty good, as a priori we had no idea how many students might have cheated (hence the uniform distribution for our prior). On the other hand, it is also pretty bad since there is a .3 length window the true value most likely lives in. Have we even gained anything, or are we still too uncertain about the true frequency? I would argue, yes, we have discovered something. It is implausible, according to our posterior, that there are no cheaters, i.e. the posterior assigns low probability to $p=0$. Since we started with a uniform prior, treating all values of $p$ as equally plausible, but the data ruled out $p=0$ as a possibility, we can be confident that there were cheaters. This kind of algorithm can be used to gather private information from users and be reasonably confident that the data, though noisy, is truthful. Alternative PyMC Model Given a value for $p$ (which from our god-like position we know), we can find the probability the student will answer yes: \begin{align} P(\text{"Yes"}) &= P( \text{Heads on first coin} )P( \text{cheater} ) + P( \text{Tails on first coin} )P( \text{Heads on second coin} ) \\ & = \frac{1}{2}p + \frac{1}{2}\frac{1}{2}\\ & = \frac{p}{2} + \frac{1}{4} \end{align} Thus, knowing $p$ we know the probability a student will respond "Yes". In PyMC, we can create a deterministic function to evaluate the probability of responding "Yes", given $p$: End of explanation yes_responses = pm.Binomial("number_cheaters", 100, p_skewed, value=35, observed=True) Explanation: I could have typed p_skewed = 0.5*p + 0.25 instead for a one-liner, as the elementary operations of addition and scalar multiplication will implicitly create a deterministic variable, but I wanted to make the deterministic boilerplate explicit for clarity's sake. If we know the probability of respondents saying "Yes", which is p_skewed, and we have $N=100$ students, the number of "Yes" responses is a binomial random variable with parameters N and p_skewed. This is where we include our observed 35 "Yes" responses. In the declaration of the pm.Binomial, we include value = 35 and observed = True. End of explanation model = pm.Model([yes_responses, p_skewed, p]) # To Be Explained in Chapter 3! mcmc = pm.MCMC(model) mcmc.sample(25000, 2500) figsize(12.5, 3) p_trace = mcmc.trace("freq_cheating")[:] plt.hist(p_trace, histtype="stepfilled", normed=True, alpha=0.85, bins=30, label="posterior distribution", color="#348ABD") plt.vlines([.05, .35], [0, 0], [5, 5], alpha=0.2) plt.xlim(0, 1) plt.legend(); Explanation: Below we add all the variables of interest to a Model container and run our black-box algorithm over the model. End of explanation N = 10 x = np.empty(N, dtype=object) for i in range(0, N): x[i] = pm.Exponential('x_%i' % i, (i + 1) ** 2) Explanation: More PyMC Tricks Protip: Lighter deterministic variables with Lambda class Sometimes writing a deterministic function using the @pm.deterministic decorator can seem like a chore, especially for a small function. I have already mentioned that elementary math operations can produce deterministic variables implicitly, but what about operations like indexing or slicing? Built-in Lambda functions can handle this with the elegance and simplicity required. For example, beta = pm.Normal("coefficients", 0, size=(N, 1)) x = np.random.randn((N, 1)) linear_combination = pm.Lambda(lambda x=x, beta=beta: np.dot(x.T, beta)) Protip: Arrays of PyMC variables There is no reason why we cannot store multiple heterogeneous PyMC variables in a Numpy array. Just remember to set the dtype of the array to object upon initialization. For example: End of explanation figsize(12.5, 3.5) np.set_printoptions(precision=3, suppress=True) challenger_data = np.genfromtxt("data/challenger_data.csv", skip_header=1, usecols=[1, 2], missing_values="NA", delimiter=",") # drop the NA values challenger_data = challenger_data[~np.isnan(challenger_data[:, 1])] # plot it, as a function of temperature (the first column) print "Temp (F), O-Ring failure?" print challenger_data plt.scatter(challenger_data[:, 0], challenger_data[:, 1], s=75, color="k", alpha=0.5) plt.yticks([0, 1]) plt.ylabel("Damage Incident?") plt.xlabel("Outside temperature (Fahrenheit)") plt.title("Defects of the Space Shuttle O-Rings vs temperature") Explanation: The remainder of this chapter examines some practical examples of PyMC and PyMC modeling: Example: Challenger Space Shuttle Disaster <span id="challenger"/> On January 28, 1986, the twenty-fifth flight of the U.S. space shuttle program ended in disaster when one of the rocket boosters of the Shuttle Challenger exploded shortly after lift-off, killing all seven crew members. The presidential commission on the accident concluded that it was caused by the failure of an O-ring in a field joint on the rocket booster, and that this failure was due to a faulty design that made the O-ring unacceptably sensitive to a number of factors including outside temperature. Of the previous 24 flights, data were available on failures of O-rings on 23, (one was lost at sea), and these data were discussed on the evening preceding the Challenger launch, but unfortunately only the data corresponding to the 7 flights on which there was a damage incident were considered important and these were thought to show no obvious trend. The data are shown below (see [1]): End of explanation figsize(12, 3) def logistic(x, beta): return 1.0 / (1.0 + np.exp(beta * x)) x = np.linspace(-4, 4, 100) plt.plot(x, logistic(x, 1), label=r"$\beta = 1$") plt.plot(x, logistic(x, 3), label=r"$\beta = 3$") plt.plot(x, logistic(x, -5), label=r"$\beta = -5$") plt.title("Logistic functon plotted for several value of $\\beta$ parameter", fontsize=14) plt.legend(); Explanation: It looks clear that the probability of damage incidents occurring increases as the outside temperature decreases. We are interested in modeling the probability here because it does not look like there is a strict cutoff point between temperature and a damage incident occurring. The best we can do is ask "At temperature $t$, what is the probability of a damage incident?". The goal of this example is to answer that question. We need a function of temperature, call it $p(t)$, that is bounded between 0 and 1 (so as to model a probability) and changes from 1 to 0 as we increase temperature. There are actually many such functions, but the most popular choice is the logistic function. $$p(t) = \frac{1}{ 1 + e^{ \;\beta t } } $$ In this model, $\beta$ is the variable we are uncertain about. Below is the function plotted for $\beta = 1, 3, -5$. End of explanation def logistic(x, beta, alpha=0): return 1.0 / (1.0 + np.exp(np.dot(beta, x) + alpha)) x = np.linspace(-4, 4, 100) plt.plot(x, logistic(x, 1), label=r"$\beta = 1$", ls="--", lw=1) plt.plot(x, logistic(x, 3), label=r"$\beta = 3$", ls="--", lw=1) plt.plot(x, logistic(x, -5), label=r"$\beta = -5$", ls="--", lw=1) plt.plot(x, logistic(x, 1, 1), label=r"$\beta = 1, \alpha = 1$", color="#348ABD") plt.plot(x, logistic(x, 3, -2), label=r"$\beta = 3, \alpha = -2$", color="#A60628") plt.plot(x, logistic(x, -5, 7), label=r"$\beta = -5, \alpha = 7$", color="#7A68A6") plt.title("Logistic functon with bias, plotted for several value of $\\alpha$ bias parameter", fontsize=14) plt.legend(loc="lower left"); Explanation: But something is missing. In the plot of the logistic function, the probability changes only near zero, but in our data above the probability changes around 65 to 70. We need to add a bias term to our logistic function: $$p(t) = \frac{1}{ 1 + e^{ \;\beta t + \alpha } } $$ Some plots are below, with differing $\alpha$. End of explanation import scipy.stats as stats nor = stats.norm x = np.linspace(-8, 7, 150) mu = (-2, 0, 3) tau = (.7, 1, 2.8) colors = ["#348ABD", "#A60628", "#7A68A6"] parameters = zip(mu, tau, colors) for _mu, _tau, _color in parameters: plt.plot(x, nor.pdf(x, _mu, scale=1. / _tau), label="$\mu = %d,\;\\tau = %.1f$" % (_mu, _tau), color=_color) plt.fill_between(x, nor.pdf(x, _mu, scale=1. / _tau), color=_color, alpha=.33) plt.legend(loc="upper right") plt.xlabel("$x$") plt.ylabel("density function at $x$") plt.title("Probability distribution of three different Normal random \ variables"); Explanation: Adding a constant term $\alpha$ amounts to shifting the curve left or right (hence why it is called a bias). Let's start modeling this in PyMC. The $\beta, \alpha$ parameters have no reason to be positive, bounded or relatively large, so they are best modeled by a Normal random variable, introduced next. Normal distributions A Normal random variable, denoted $X \sim N(\mu, 1/\tau)$, has a distribution with two parameters: the mean, $\mu$, and the precision, $\tau$. Those familiar with the Normal distribution already have probably seen $\sigma^2$ instead of $\tau^{-1}$. They are in fact reciprocals of each other. The change was motivated by simpler mathematical analysis and is an artifact of older Bayesian methods. Just remember: the smaller $\tau$, the larger the spread of the distribution (i.e. we are more uncertain); the larger $\tau$, the tighter the distribution (i.e. we are more certain). Regardless, $\tau$ is always positive. The probability density function of a $N( \mu, 1/\tau)$ random variable is: $$ f(x | \mu, \tau) = \sqrt{\frac{\tau}{2\pi}} \exp\left( -\frac{\tau}{2} (x-\mu)^2 \right) $$ We plot some different density functions below. End of explanation import pymc as pm temperature = challenger_data[:, 0] D = challenger_data[:, 1] # defect or not? # notice the`value` here. We explain why below. beta = pm.Normal("beta", 0, 0.001, value=0) alpha = pm.Normal("alpha", 0, 0.001, value=0) @pm.deterministic def p(t=temperature, alpha=alpha, beta=beta): return 1.0 / (1. + np.exp(beta * t + alpha)) Explanation: A Normal random variable can be take on any real number, but the variable is very likely to be relatively close to $\mu$. In fact, the expected value of a Normal is equal to its $\mu$ parameter: $$ E[ X | \mu, \tau] = \mu$$ and its variance is equal to the inverse of $\tau$: $$Var( X | \mu, \tau ) = \frac{1}{\tau}$$ Below we continue our modeling of the Challenger space craft: End of explanation p.value # connect the probabilities in `p` with our observations through a # Bernoulli random variable. observed = pm.Bernoulli("bernoulli_obs", p, value=D, observed=True) model = pm.Model([observed, beta, alpha]) # Mysterious code to be explained in Chapter 3 map_ = pm.MAP(model) map_.fit() mcmc = pm.MCMC(model) mcmc.sample(120000, 100000, 2) Explanation: We have our probabilities, but how do we connect them to our observed data? A Bernoulli random variable with parameter $p$, denoted $\text{Ber}(p)$, is a random variable that takes value 1 with probability $p$, and 0 else. Thus, our model can look like: $$ \text{Defect Incident, $D_i$} \sim \text{Ber}( \;p(t_i)\; ), \;\; i=1..N$$ where $p(t)$ is our logistic function and $t_i$ are the temperatures we have observations about. Notice in the above code we had to set the values of beta and alpha to 0. The reason for this is that if beta and alpha are very large, they make p equal to 1 or 0. Unfortunately, pm.Bernoulli does not like probabilities of exactly 0 or 1, though they are mathematically well-defined probabilities. So by setting the coefficient values to 0, we set the variable p to be a reasonable starting value. This has no effect on our results, nor does it mean we are including any additional information in our prior. It is simply a computational caveat in PyMC. End of explanation alpha_samples = mcmc.trace('alpha')[:, None] # best to make them 1d beta_samples = mcmc.trace('beta')[:, None] figsize(12.5, 6) # histogram of the samples: plt.subplot(211) plt.title(r"Posterior distributions of the variables $\alpha, \beta$") plt.hist(beta_samples, histtype='stepfilled', bins=35, alpha=0.85, label=r"posterior of $\beta$", color="#7A68A6", normed=True) plt.legend() plt.subplot(212) plt.hist(alpha_samples, histtype='stepfilled', bins=35, alpha=0.85, label=r"posterior of $\alpha$", color="#A60628", normed=True) plt.legend(); Explanation: We have trained our model on the observed data, now we can sample values from the posterior. Let's look at the posterior distributions for $\alpha$ and $\beta$: End of explanation t = np.linspace(temperature.min() - 5, temperature.max() + 5, 50)[:, None] p_t = logistic(t.T, beta_samples, alpha_samples) mean_prob_t = p_t.mean(axis=0) figsize(12.5, 4) plt.plot(t, mean_prob_t, lw=3, label="average posterior \nprobability \ of defect") plt.plot(t, p_t[0, :], ls="--", label="realization from posterior") plt.plot(t, p_t[-2, :], ls="--", label="realization from posterior") plt.scatter(temperature, D, color="k", s=50, alpha=0.5) plt.title("Posterior expected value of probability of defect; \ plus realizations") plt.legend(loc="lower left") plt.ylim(-0.1, 1.1) plt.xlim(t.min(), t.max()) plt.ylabel("probability") plt.xlabel("temperature"); Explanation: All samples of $\beta$ are greater than 0. If instead the posterior was centered around 0, we may suspect that $\beta = 0$, implying that temperature has no effect on the probability of defect. Similarly, all $\alpha$ posterior values are negative and far away from 0, implying that it is correct to believe that $\alpha$ is significantly less than 0. Regarding the spread of the data, we are very uncertain about what the true parameters might be (though considering the low sample size and the large overlap of defects-to-nondefects this behaviour is perhaps expected). Next, let's look at the expected probability for a specific value of the temperature. That is, we average over all samples from the posterior to get a likely value for $p(t_i)$. End of explanation from scipy.stats.mstats import mquantiles # vectorized bottom and top 2.5% quantiles for "confidence interval" qs = mquantiles(p_t, [0.025, 0.975], axis=0) plt.fill_between(t[:, 0], *qs, alpha=0.7, color="#7A68A6") plt.plot(t[:, 0], qs[0], label="95% CI", color="#7A68A6", alpha=0.7) plt.plot(t, mean_prob_t, lw=1, ls="--", color="k", label="average posterior \nprobability of defect") plt.xlim(t.min(), t.max()) plt.ylim(-0.02, 1.02) plt.legend(loc="lower left") plt.scatter(temperature, D, color="k", s=50, alpha=0.5) plt.xlabel("temp, $t$") plt.ylabel("probability estimate") plt.title("Posterior probability estimates given temp. $t$"); Explanation: Above we also plotted two possible realizations of what the actual underlying system might be. Both are equally likely as any other draw. The blue line is what occurs when we average all the 20000 possible dotted lines together. An interesting question to ask is for what temperatures are we most uncertain about the defect-probability? Below we plot the expected value line and the associated 95% intervals for each temperature. End of explanation figsize(12.5, 2.5) prob_31 = logistic(31, beta_samples, alpha_samples) plt.xlim(0.995, 1) plt.hist(prob_31, bins=1000, normed=True, histtype='stepfilled') plt.title("Posterior distribution of probability of defect, given $t = 31$") plt.xlabel("probability of defect occurring in O-ring"); Explanation: The 95% credible interval, or 95% CI, painted in purple, represents the interval, for each temperature, that contains 95% of the distribution. For example, at 65 degrees, we can be 95% sure that the probability of defect lies between 0.25 and 0.75. More generally, we can see that as the temperature nears 60 degrees, the CI's spread out over [0,1] quickly. As we pass 70 degrees, the CI's tighten again. This can give us insight about how to proceed next: we should probably test more O-rings around 60-65 temperature to get a better estimate of probabilities in that range. Similarly, when reporting to scientists your estimates, you should be very cautious about simply telling them the expected probability, as we can see this does not reflect how wide the posterior distribution is. What about the day of the Challenger disaster? On the day of the Challenger disaster, the outside temperature was 31 degrees Fahrenheit. What is the posterior distribution of a defect occurring, given this temperature? The distribution is plotted below. It looks almost guaranteed that the Challenger was going to be subject to defective O-rings. End of explanation simulated = pm.Bernoulli("bernoulli_sim", p) N = 10000 mcmc = pm.MCMC([simulated, alpha, beta, observed]) mcmc.sample(N) figsize(12.5, 5) simulations = mcmc.trace("bernoulli_sim")[:] print simulations.shape plt.title("Simulated dataset using posterior parameters") figsize(12.5, 6) for i in range(4): ax = plt.subplot(4, 1, i + 1) plt.scatter(temperature, simulations[1000 * i, :], color="k", s=50, alpha=0.6) Explanation: Is our model appropriate? The skeptical reader will say "You deliberately chose the logistic function for $p(t)$ and the specific priors. Perhaps other functions or priors will give different results. How do I know I have chosen a good model?" This is absolutely true. To consider an extreme situation, what if I had chosen the function $p(t) = 1,\; \forall t$, which guarantees a defect always occurring: I would have again predicted disaster on January 28th. Yet this is clearly a poorly chosen model. On the other hand, if I did choose the logistic function for $p(t)$, but specified all my priors to be very tight around 0, likely we would have very different posterior distributions. How do we know our model is an expression of the data? This encourages us to measure the model's goodness of fit. We can think: how can we test whether our model is a bad fit? An idea is to compare observed data (which if we recall is a fixed stochastic variable) with an artificial dataset which we can simulate. The rationale is that if the simulated dataset does not appear similar, statistically, to the observed dataset, then likely our model is not accurately represented the observed data. Previously in this Chapter, we simulated artificial datasets for the SMS example. To do this, we sampled values from the priors. We saw how varied the resulting datasets looked like, and rarely did they mimic our observed dataset. In the current example, we should sample from the posterior distributions to create very plausible datasets. Luckily, our Bayesian framework makes this very easy. We only need to create a new Stochastic variable, that is exactly the same as our variable that stored the observations, but minus the observations themselves. If you recall, our Stochastic variable that stored our observed data was: observed = pm.Bernoulli( "bernoulli_obs", p, value=D, observed=True) Hence we create: simulated_data = pm.Bernoulli("simulation_data", p) Let's simulate 10 000: End of explanation posterior_probability = simulations.mean(axis=0) print "posterior prob of defect | realized defect " for i in range(len(D)): print "%.2f | %d" % (posterior_probability[i], D[i]) Explanation: Note that the above plots are different (if you can think of a cleaner way to present this, please send a pull request and answer here!). We wish to assess how good our model is. "Good" is a subjective term of course, so results must be relative to other models. We will be doing this graphically as well, which may seem like an even less objective method. The alternative is to use Bayesian p-values. These are still subjective, as the proper cutoff between good and bad is arbitrary. Gelman emphasises that the graphical tests are more illuminating [7] than p-value tests. We agree. The following graphical test is a novel data-viz approach to logistic regression. The plots are called separation plots[8]. For a suite of models we wish to compare, each model is plotted on an individual separation plot. I leave most of the technical details about separation plots to the very accessible original paper, but I'll summarize their use here. For each model, we calculate the proportion of times the posterior simulation proposed a value of 1 for a particular temperature, i.e. compute $P( \;\text{Defect} = 1 | t, \alpha, \beta )$ by averaging. This gives us the posterior probability of a defect at each data point in our dataset. For example, for the model we used above: End of explanation ix = np.argsort(posterior_probability) print "probb | defect " for i in range(len(D)): print "%.2f | %d" % (posterior_probability[ix[i]], D[ix[i]]) Explanation: Next we sort each column by the posterior probabilities: End of explanation from separation_plot import separation_plot figsize(11., 1.5) separation_plot(posterior_probability, D) Explanation: We can present the above data better in a figure: I've wrapped this up into a separation_plot function. End of explanation figsize(11., 1.25) # Our temperature-dependent model separation_plot(posterior_probability, D) plt.title("Temperature-dependent model") # Perfect model # i.e. the probability of defect is equal to if a defect occurred or not. p = D separation_plot(p, D) plt.title("Perfect model") # random predictions p = np.random.rand(23) separation_plot(p, D) plt.title("Random model") # constant model constant_prob = 7. / 23 * np.ones(23) separation_plot(constant_prob, D) plt.title("Constant-prediction model") Explanation: The snaking-line is the sorted probabilities, blue bars denote defects, and empty space (or grey bars for the optimistic readers) denote non-defects. As the probability rises, we see more and more defects occur. On the right hand side, the plot suggests that as the posterior probability is large (line close to 1), then more defects are realized. This is good behaviour. Ideally, all the blue bars should be close to the right-hand side, and deviations from this reflect missed predictions. The black vertical line is the expected number of defects we should observe, given this model. This allows the user to see how the total number of events predicted by the model compares to the actual number of events in the data. It is much more informative to compare this to separation plots for other models. Below we compare our model (top) versus three others: the perfect model, which predicts the posterior probability to be equal to 1 if a defect did occur. a completely random model, which predicts random probabilities regardless of temperature. a constant model: where $P(D = 1 \; | \; t) = c, \;\; \forall t$. The best choice for $c$ is the observed frequency of defects, in this case 7/23. End of explanation # type your code here. figsize(12.5, 4) plt.scatter(alpha_samples, beta_samples, alpha=0.1) plt.title("Why does the plot look like this?") plt.xlabel(r"$\alpha$") plt.ylabel(r"$\beta$") Explanation: In the random model, we can see that as the probability increases there is no clustering of defects to the right-hand side. Similarly for the constant model. The perfect model, the probability line is not well shown, as it is stuck to the bottom and top of the figure. Of course the perfect model is only for demonstration, and we cannot infer any scientific inference from it. Exercises 1. Try putting in extreme values for our observations in the cheating example. What happens if we observe 25 affirmative responses? 10? 50? 2. Try plotting $\alpha$ samples versus $\beta$ samples. Why might the resulting plot look like this? End of explanation from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling() Explanation: References [1] Dalal, Fowlkes and Hoadley (1989),JASA, 84, 945-957. [2] German Rodriguez. Datasets. In WWS509. Retrieved 30/01/2013, from http://data.princeton.edu/wws509/datasets/#smoking. [3] McLeish, Don, and Cyntha Struthers. STATISTICS 450/850 Estimation and Hypothesis Testing. Winter 2012. Waterloo, Ontario: 2012. Print. [4] Fonnesbeck, Christopher. "Building Models." PyMC-Devs. N.p., n.d. Web. 26 Feb 2013. http://pymc-devs.github.com/pymc/modelbuilding.html. [5] Cronin, Beau. "Why Probabilistic Programming Matters." 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1. [6] S.P. Brooks, E.A. Catchpole, and B.J.T. Morgan. Bayesian animal survival estimation. Statistical Science, 15: 357–376, 2000 [7] Gelman, Andrew. "Philosophy and the practice of Bayesian statistics." British Journal of Mathematical and Statistical Psychology. (2012): n. page. Web. 2 Apr. 2013. [8] Greenhill, Brian, Michael D. Ward, and Audrey Sacks. "The Separation Plot: A New Visual Method for Evaluating the Fit of Binary Models." American Journal of Political Science. 55.No.4 (2011): n. page. Web. 2 Apr. 2013. End of explanation
5,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterators [GA Table] Contructing PySAL Spatial Weights Spatial Weight Matrix File Stores the spatial weights so they do not have to be re-calculated for each analysis. In row-compressed format. Little endian byte encoded. Requires a unique long/short field to identify each features. Can NOT be the OID/FID. Construction Step1: Distance-Based Options INPUTS Step2: Example Step3: k-Nearest Neighbors Options INPUTS Step4: Example Step5: Delaunay Triangulation Options INPUTS Step6: Polygon Contiguity Options <a id="poly_options"></a> ``` INPUTS Step7: *Example Step8: Example Step9: On-the-fly Neighborhood Iterators [GA Table] Reads centroids of input features into spatial tree structure. Distance Based Queries. Scalable Step10: Example Step11: Example Step15: Contructing PySAL Spatial Weights Convert masterID to orderID when using ssdo.obtainData (SWM File, Polygon Contiguity) Data is already in orderID when using ssdo.obtainDataGA (Distance Based) Methods in next cell can be imported from pysal2ArcGIS.py Step16: Converting Spatial Weight Matrix Formats (e.g. .swm, .gwt, *.gal) Follow directions at the PySAL-ArcGIS-Toolbox Git Repository [https Step17: Calling MaxP Regions Using SWM Based on Rook Contiguity, No Row Standardization Step18: Calling MaxP Regions Using Rook Contiguity, No Row Standardization Step19: Identical results because the random seed was set to 100 and they have the same spatial neighborhood Calling MaxP Regions Using Fixed Distance 250000, Hyrbid to Assure at least 2 Neighbors
Python Code: import Weights as WEIGHTS import os as OS inputFC = r'../data/CA_Polygons.shp' fullFC = OS.path.abspath(inputFC) fullPath, fcName = OS.path.split(fullFC) masterField = "MYID" Explanation: Neighborhood Structures in the ArcGIS Spatial Statistics Library Spatial Weights Matrix On-the-fly Neighborhood Iterators [GA Table] Contructing PySAL Spatial Weights Spatial Weight Matrix File Stores the spatial weights so they do not have to be re-calculated for each analysis. In row-compressed format. Little endian byte encoded. Requires a unique long/short field to identify each features. Can NOT be the OID/FID. Construction End of explanation swmFile = OS.path.join(fullPath, "fixed250k.swm") fixedSWM = WEIGHTS.distance2SWM(fullFC, swmFile, masterField, threshold = 250000) Explanation: Distance-Based Options INPUTS: inputFC (str): path to the input feature class swmFile (str): path to the SWM file. masterField (str): field in table that serves as the mapping. fixed (boolean): fixed (1) or inverse (0) distance? concept: {str, EUCLIDEAN}: EUCLIDEAN or MANHATTAN exponent {float, 1.0}: distance decay threshold {float, None}: distance threshold kNeighs (int): number of neighbors to return rowStandard {bool, True}: row standardize weights? Example: Fixed Distance End of explanation swmFile = OS.path.join(fullPath, "inv2_250k.swm") fixedSWM = WEIGHTS.distance2SWM(fullFC, swmFile, masterField, fixed = False, exponent = 2.0, threshold = 250000) Explanation: Example: Inverse Distance Squared End of explanation swmFile = OS.path.join(fullPath, "knn8.swm") fixedSWM = WEIGHTS.kNearest2SWM(fullFC, swmFile, masterField, kNeighs = 8) Explanation: k-Nearest Neighbors Options INPUTS: inputFC (str): path to the input feature class swmFile (str): path to the SWM file. masterField (str): field in table that serves as the mapping. concept: {str, EUCLIDEAN}: EUCLIDEAN or MANHATTAN kNeighs {int, 1}: number of neighbors to return rowStandard {bool, True}: row standardize weights? Example: 8-nearest neighbors End of explanation swmFile = OS.path.join(fullPath, "fixed250k_knn8.swm") fixedSWM = WEIGHTS.distance2SWM(fullFC, swmFile, masterField, kNeighs = 8, threshold = 250000) Explanation: Example: Fixed Distance - k-nearest neighbor hybrid [i.e. at least k neighbors but may have more...] End of explanation swmFile = OS.path.join(fullPath, "delaunay.swm") fixedSWM = WEIGHTS.delaunay2SWM(fullFC, swmFile, masterField) Explanation: Delaunay Triangulation Options INPUTS: inputFC (str): path to the input feature class swmFile (str): path to the SWM file. masterField (str): field in table that serves as the mapping. rowStandard {bool, True}: row standardize weights? Example: delaunay End of explanation swmFile = OS.path.join(fullPath, "rook_bin.swm") WEIGHTS.polygon2SWM(inputFC, swmFile, masterField, rowStandard = False) Explanation: Polygon Contiguity Options <a id="poly_options"></a> ``` INPUTS: inputFC (str): path to the input feature class swmFile (str): path to the SWM file. masterField (str): field in table that serves as the mapping. concept: {str, EUCLIDEAN}: EUCLIDEAN or MANHATTAN kNeighs {int, 0}: number of neighbors to return (1) rowStandard {bool, True}: row standardize weights? contiguityType {str, Rook}: {Rook = Edges Only, Queen = Edges/Vertices} NOTES: (1) kNeighs is an option often used when you know there are polygon features that are not contiguous (e.g. islands). A kNeighs value of 2 will assure that ALL features have at least 2 neighbors. If a polygon is determined to only touch a single other polygon, then a nearest neighbor search based on true centroids are used to find the additional neighbor. ``` Example: Rook [Binary] End of explanation swmFile = OS.path.join(fullPath, "queen.swm") WEIGHTS.polygon2SWM(inputFC, swmFile, masterField, contiguityType = "QUEEN") Explanation: *Example: Queen Contiguity [Row Standardized] End of explanation swmFile = OS.path.join(fullPath, "hybrid.swm") WEIGHTS.polygon2SWM(inputFC, swmFile, masterField, kNeighs = 4) Explanation: Example: Queen Contiguity - KNN Hybrid [Prevents Islands w/ no Neighbors] (1) End of explanation import SSDataObject as SSDO inputFC = r'../data/CA_Polygons.shp' ssdo = SSDO.SSDataObject(inputFC) uniqueIDField = ssdo.oidName ssdo.obtainData(uniqueIDField, requireSearch = True) Explanation: On-the-fly Neighborhood Iterators [GA Table] Reads centroids of input features into spatial tree structure. Distance Based Queries. Scalable: In-memory/disk-space swap for large data. Requires a unique long/short field to identify each features. Can be the OID/FID. Uses requireSearch = True when using ssdo.obtainData Pre-Example: Load the Data into GA Version of SSDataObject End of explanation import arcgisscripting as ARC import WeightsUtilities as WU import gapy as GAPY gaSearch = GAPY.ga_nsearch(ssdo.gaTable) concept, gaConcept = WU.validateDistanceMethod('EUCLIDEAN', ssdo.spatialRef) gaSearch.init_nearest(0.0, 4, gaConcept) neighSearch = ARC._ss.NeighborSearch(ssdo.gaTable, gaSearch) for i in range(len(neighSearch)): neighOrderIDs = neighSearch[i] if i < 5: print(neighOrderIDs) import arcgisscripting as ARC import WeightsUtilities as WU import gapy as GAPY import SSUtilities as UTILS inputGrid = r'D:\Data\UC\UC17\Island\Dykstra\Dykstra.gdb\emerge' ssdo = SSDO.SSDataObject(inputGrid) ssdo.obtainData(ssdo.oidName, requireSearch = True) gaSearch = GAPY.ga_nsearch(ssdo.gaTable) concept, gaConcept = WU.validateDistanceMethod('EUCLIDEAN', ssdo.spatialRef) gaSearch.init_nearest(300., 0, gaConcept) neighSearch = ARC._ss.NeighborSearch(ssdo.gaTable, gaSearch) print(ssdo.distanceInfo.name) for i in range(len(neighSearch)): neighOrderIDs = neighSearch[i] x0,y0 = ssdo.xyCoords[i] if i < 5: nhs = ", ".join([str(i) for i in neighOrderIDs]) dist = [] for nh in neighOrderIDs: x1,y1 = ssdo.xyCoords[nh] dij = WU.euclideanDistance(x0,x1,y0,y1) dist.append(UTILS.formatValue(dij, "%0.2f")) print("ID {0} has {1} neighs, they are {2}".format(i, len(neighOrderIDs), nhs)) print("The Distances are... {0}".format(", ".join(dist))) Explanation: Example: NeighborSearch - When you only need your Neighbor IDs gaSearch.init_nearest(distance_band, minimum_num_neighs, {"euclidean", "manhattan") End of explanation gaSearch = GAPY.ga_nsearch(ssdo.gaTable) gaSearch.init_nearest(250000, 0, gaConcept) neighSearch = ARC._ss.NeighborWeights(ssdo.gaTable, gaSearch, weight_type = 0, exponent = 2.0) for i in range(len(neighSearch)): neighOrderIDs, neighWeights = neighSearch[i] if i < 3: print(neighOrderIDs) print(neighWeights) Explanation: Example: NeighborWeights - When you need non-uniform spatial weights (E.g. Inverse Distance Squared) NeighborWeights(gaTable, gaSearch, weight_type [0: inverse_distance, 1: fixed_distance], exponent = 1.0, row_standard = True, include_self = False) End of explanation import pysal as PYSAL import WeightsUtilities as WU import SSUtilities as UTILS def swm2Weights(ssdo, swmfile): Converts ArcGIS Sparse Spatial Weights Matrix (*.swm) file to PySAL Sparse Spatial Weights Class. INPUTS: ssdo (class): instance of SSDataObject [1,2] swmFile (str): full path to swm file NOTES: (1) Data must already be obtained using ssdo.obtainData() (2) The masterField for the swm file and the ssdo object must be the same and may NOT be the OID/FID/ObjectID neighbors = {} weights = {} #### Create SWM Reader Object #### swm = WU.SWMReader(swmfile) #### SWM May NOT be a Subset of the Data #### if ssdo.numObs > swm.numObs: ARCPY.AddIDMessage("ERROR", 842, ssdo.numObs, swm.numObs) raise SystemExit() #### Parse All SWM Records #### for r in UTILS.ssRange(swm.numObs): info = swm.swm.readEntry() masterID, nn, nhs, w, sumUnstandard = info #### Must Have at Least One Neighbor #### if nn: #### Must be in Selection Set (If Exists) #### if masterID in ssdo.master2Order: outNHS = [] outW = [] #### Transform Master ID to Order ID #### orderID = ssdo.master2Order[masterID] #### Neighbors and Weights Adjusted for Selection #### for nhInd, nhVal in enumerate(nhs): try: nhOrder = ssdo.master2Order[nhVal] outNHS.append(nhOrder) weightVal = w[nhInd] if swm.rowStandard: weightVal = weightVal * sumUnstandard[0] outW.append(weightVal) except KeyError: pass #### Add Selected Neighbors/Weights #### if len(outNHS): neighbors[orderID] = outNHS weights[orderID] = outW swm.close() #### Construct PySAL Spatial Weights and Standardize as per SWM #### w = PYSAL.W(neighbors, weights) if swm.rowStandard: w.transform = 'R' return w def poly2Weights(ssdo, contiguityType = "ROOK", rowStandard = True): Uses GP Polygon Neighbor Tool to construct contiguity relationships and stores them in PySAL Sparse Spatial Weights class. INPUTS: ssdo (class): instance of SSDataObject [1] contiguityType {str, ROOK}: ROOK or QUEEN contiguity rowStandard {bool, True}: whether to row standardize the spatial weights NOTES: (1) Data must already be obtained using ssdo.obtainData() or ssdo.obtainDataGA () neighbors = {} weights = {} polyNeighDict = WU.polygonNeighborDict(ssdo.inputFC, ssdo.masterField, contiguityType = contiguityType) for masterID, neighIDs in UTILS.iteritems(polyNeighDict): orderID = ssdo.master2Order[masterID] neighbors[orderID] = [ssdo.master2Order[i] for i in neighIDs] w = PYSAL.W(neighbors) if rowStandard: w.transform = 'R' return w def distance2Weights(ssdo, neighborType = 1, distanceBand = 0.0, numNeighs = 0, distanceType = "euclidean", exponent = 1.0, rowStandard = True, includeSelf = False): Uses ArcGIS Neighborhood Searching Structure to create a PySAL Sparse Spatial Weights Matrix. INPUTS: ssdo (class): instance of SSDataObject [1] neighborType {int, 1}: 0 = inverse distance, 1 = fixed distance, 2 = k-nearest-neighbors, 3 = delaunay distanceBand {float, 0.0}: return all neighbors within this distance for inverse/fixed distance numNeighs {int, 0}: number of neighbors for k-nearest-neighbor, can also be used to set a minimum number of neighbors for inverse/fixed distance distanceType {str, euclidean}: manhattan or euclidean distance [2] exponent {float, 1.0}: distance decay factor for inverse distance rowStandard {bool, True}: whether to row standardize the spatial weights includeSelf {bool, False}: whether to return self as a neighbor NOTES: (1) Data must already be obtained using ssdo.obtainDataGA() (2) Chordal Distance is used for GCS Data neighbors = {} weights = {} gaSearch = GAPY.ga_nsearch(ssdo.gaTable) if neighborType == 3: gaSearch.init_delaunay() neighSearch = ARC._ss.NeighborWeights(ssdo.gaTable, gaSearch, weight_type = 1) else: if neighborType == 2: distanceBand = 0.0 weightType = 1 else: weightType = neighborType concept, gaConcept = WU.validateDistanceMethod(distanceType.upper(), ssdo.spatialRef) gaSearch.init_nearest(distanceBand, numNeighs, gaConcept) neighSearch = ARC._ss.NeighborWeights(ssdo.gaTable, gaSearch, weight_type = weightType, exponent = exponent, include_self = includeSelf) for i in range(len(neighSearch)): neighOrderIDs, neighWeights = neighSearch[i] neighbors[i] = neighOrderIDs weights[i] = neighWeights w = PYSAL.W(neighbors, weights) if rowStandard: w.transform = 'R' return w Explanation: Contructing PySAL Spatial Weights Convert masterID to orderID when using ssdo.obtainData (SWM File, Polygon Contiguity) Data is already in orderID when using ssdo.obtainDataGA (Distance Based) Methods in next cell can be imported from pysal2ArcGIS.py End of explanation import WeightConvertor as W_CONVERT swmFile = OS.path.join(fullPath, "queen.swm") galFile = OS.path.join(fullPath, "queen.gal") convert = W_CONVERT.WeightConvertor(swmFile, galFile, inputFC, "MYID", "SWM", "GAL") convert.createOutput() Explanation: Converting Spatial Weight Matrix Formats (e.g. .swm, .gwt, *.gal) Follow directions at the PySAL-ArcGIS-Toolbox Git Repository [https://github.com/Esri/PySAL-ArcGIS-Toolbox] Please make note of the section on Adding a Git Project to your ArcGIS Installation Python Path. End of explanation import numpy as NUM NUM.random.seed(100) ssdo = SSDO.SSDataObject(inputFC) uniqueIDField = "MYID" fieldNames = ['PCR2010', 'POP2010', 'PERCNOHS'] ssdo.obtainDataGA(uniqueIDField, fieldNames) df = ssdo.getDataFrame() X = df.as_matrix() swmFile = OS.path.join(fullPath, "rook_bin.swm") w = swm2Weights(ssdo, swmFile) maxp = PYSAL.region.Maxp(w, X[:,0:2], 3000000., floor_variable = X[:,2]) maxpGroups = NUM.empty((ssdo.numObs,), int) for regionID, orderIDs in enumerate(maxp.regions): maxpGroups[orderIDs] = regionID print((regionID, orderIDs)) Explanation: Calling MaxP Regions Using SWM Based on Rook Contiguity, No Row Standardization End of explanation NUM.random.seed(100) w = poly2Weights(ssdo, rowStandard = False) maxp = PYSAL.region.Maxp(w, X[:,0:2], 3000000., floor_variable = X[:,2]) maxpGroups = NUM.empty((ssdo.numObs,), int) for regionID, orderIDs in enumerate(maxp.regions): maxpGroups[orderIDs] = regionID print((regionID, orderIDs)) Explanation: Calling MaxP Regions Using Rook Contiguity, No Row Standardization End of explanation NUM.random.seed(100) w = distance2Weights(ssdo, distanceBand = 250000.0, numNeighs = 2) maxp = PYSAL.region.Maxp(w, X[:,0:2], 3000000., floor_variable = X[:,2]) maxpGroups = NUM.empty((ssdo.numObs,), int) for regionID, orderIDs in enumerate(maxp.regions): maxpGroups[orderIDs] = regionID print((regionID, orderIDs)) Explanation: Identical results because the random seed was set to 100 and they have the same spatial neighborhood Calling MaxP Regions Using Fixed Distance 250000, Hyrbid to Assure at least 2 Neighbors End of explanation
5,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Metaprogramming (the sometimes useful but often interesting) Why? Repetative code is an excuse to waste time? Might allow you to control functions, classes behavior at a higher level than just writing code Using decorators that are available in the Python standard library might save you time/preserve functionality of your code https Step1: NOTE! decorated sum and debugging point to the same function! Step2: What about class or a class functions? An example class Step3: So it works on classes too. Why? (Left for the reader) Ok, so the syntax for debugging the class is kind of annoying... can we debug all the methods with a single @? python def debug_on_classes(cls) Step4: What is the deal with the parameter? @(args,*kwargs) Decorators can take arguments. Basically this involves another layer on top of the decorator ```python from timeit import default_timer as timer def time_execution(symb=''10)
Python Code: from functools import wraps def debug_on(func): @wraps(func) #preserving the metadata for func def debugging(*args,**kwargs): retval = func(*args,**kwargs); print('Scope: debugging %s:%s:%s'%(func,func.__name__,retval)); return retval; print('Scope: debug_on',debugging) return debugging # the @ syntax is equivalent to function nesting https://www.python.org/dev/peps/pep-0318/ # debug_on(sum) @debug_on def sum(x,y): # sum->debugging '''Return the sum''' return x+y; @debug_on def sum2(x,y): #sum2->debugging, but seperate instance '''Return the square of the sum''' return (x+y)**2.; print('Scope: main sum %s, sum2 %s'%(sum,sum2)) print('-'*10) print('Q:What does %s do? A:%s'%(sum2.__name__,sum2.__doc__)) Explanation: Python Metaprogramming (the sometimes useful but often interesting) Why? Repetative code is an excuse to waste time? Might allow you to control functions, classes behavior at a higher level than just writing code Using decorators that are available in the Python standard library might save you time/preserve functionality of your code https://docs.python.org/3/library/functools.html What are they? Decorators apply operations to functions/classes that are generally applicable to many objects. They are functions that take function/classes as arguments and change their behavior Special syntax @decorator Decorators example: Debugging with the print statement Let's start with a simple function that does something: python def sum(x,y): print x+y; return x+y; Ok, but you probably want to remove the print before you let someone see your code... and maybe changes in the future will also need this debugging step. Our first 'decorator' ```python def debug(val): print val; return val; def sum(x,y): return x+y; x,y=2,3; 'explicit decorator' debug(sum(x,y)) Ok but we moved the print statement -out- of the function. Version controling between the master and debugging branch might still be weird. What we really want is a modified version of the function sum. What if a function could modify the call to sum:python def debug_on(func): def debugging(args,kwargs): print 'Scope: debugging',func(args,kwargs); return func(*args,kwargs); print 'Scope: debug_on',debugging return debugging Read what is happening here carefully.python def debug_on(func): def debugging(args,*kwargs): ... return debugging; We take in a function, and return a function. What happens for example:python a = debug_on(sum); # a->debugging # Note that debugging calls our original function sum Scope: debug_on <function debugging at 0xf4b4d3ac> We pass all positional (\*args) and keyword (\*\*kwargs) through debugging to sum and return the result.python print(a(3,4)); Scope: debugging, 7 7 ``` End of explanation sum(3,4) sum2(3,4) Explanation: NOTE! decorated sum and debugging point to the same function! End of explanation @debug_on class point(): @debug_on def __init__(self,x,y): self.x=x; self.y=y; @debug_on def dist(self): return self.x**2.+self.y**2; a = point(1,2); a.dist() Explanation: What about class or a class functions? An example class: python class point(): def __init__(self,x,y): self.x=x; self.y=y; def dist(self,x,y): return self.x**2.+self.y**2; End of explanation def debug_on_classes(cls): @wraps(cls) #preserving the cls metadata def debugging(*args,**kwargs): cdict = cls.__dict__; for item in cdict: func = getattr(cls,item); if( hasattr(func,'__call__') ): setattr(cls,item,debug_on(func)) return cls(*args,**kwargs); return debugging; @debug_on_classes class point(): def __init__(self,x,y): self.x=x; self.y=y; def dist(self): return self.x**2.+self.y**2; a = point(1,2); a.dist(); Explanation: So it works on classes too. Why? (Left for the reader) Ok, so the syntax for debugging the class is kind of annoying... can we debug all the methods with a single @? python def debug_on_classes(cls): def debugging(*args,**kwargs): cdict = cls.__dict__; for item in cdict: func = getattr(cls,item); if( hasattr(func,'__call__') ): setattr(cls,item,debug_on(func)) return cls(*args,**kwargs); return debugging; Note the careful syntax. Here we simply ask for all the items in the class dictionary and, if they are callable, we wrap then with the debug_on decorator. Test it out! End of explanation from timeit import default_timer as timer from time import sleep; def time_execution(*args,**kwargs): symb = kwargs.pop('symb','*'*10) def time_decorator(func): def time_function(*args,**kwargs): start = timer(); result=func(*args,**kwargs); end = timer()-start; print('%s Function call %s took %.2f seconds'%(symb,func.__name__,end)); return result; return time_function; return time_decorator; @time_execution(symb='='*10) # note that @profile is provided by https://mg.pov.lt/profilehooks/ def recursive_counter(n=0): while(n<10): sleep(0.1); n = recursive_counter(n+1); return n; print( recursive_counter(0) ) Explanation: What is the deal with the parameter? @(args,*kwargs) Decorators can take arguments. Basically this involves another layer on top of the decorator ```python from timeit import default_timer as timer def time_execution(symb=''10): def time_decorator(func): def time_function(args,kwargs): start = timer(); result=func(args,**kwargs); end = timer()-start; print('Function call %s took %.2f seconds'%(func.name,end)); return result; return time_function; return time_decorator; ``` Note that this is just another function pointer on top of the time_decorator function. It manages the *args and **kwargs passed to the decorator End of explanation
5,359
Given the following text description, write Python code to implement the functionality described below step by step Description: Create a classifier to predict the wine color from wine quality attributes using this dataset Step1: Split the data into features (x) and target (y, the last column in the table) Remember you can cast the results into an numpy array and then slice out what you want Step2: Create a decision tree with the data Step3: Run 10-fold cross validation on the model Step4: If you have time, calculate the feature importance and graph based on the code in the slides from last class Use this tip for getting the column names from your cursor object
Python Code: import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline import dateutil.parser import pg8000 from pandas import DataFrame from sklearn.externals.six import StringIO import pydotplus from sklearn import tree from sklearn.cross_validation import train_test_split from sklearn import metrics conn = pg8000.connect(host="training.c1erymiua9dx.us-east-1.rds.amazonaws.com", user='dot_student', password='qgis', database='training') cursor = conn.cursor() cursor.execute("select column_name from information_schema.columns where table_name='winequality'") column_list = [] for row in cursor.fetchall(): column_list.append(row[0]) column_list database=cursor.execute("SELECT * FROM winequality") import pandas as pd import matplotlib.pyplot as plt %matplotlib inline df = pd.read_sql("SELECT * FROM winequality", conn) df.head() df.columns df.info() Explanation: Create a classifier to predict the wine color from wine quality attributes using this dataset: http://archive.ics.uci.edu/ml/datasets/Wine+Quality The data is in the database we've been using host='training.c1erymiua9dx.us-east-1.rds.amazonaws.com' database='training' port=5432 user='dot_student' password='qgis' table name = 'winequality' Query for the data and create a numpy array End of explanation numpyMatrix = df.as_matrix() numpyMatrix x = numpyMatrix[:,:11] x y = numpyMatrix[:,11:] y Explanation: Split the data into features (x) and target (y, the last column in the table) Remember you can cast the results into an numpy array and then slice out what you want End of explanation dt = tree.DecisionTreeClassifier() dt = dt.fit(x,y) x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.25,train_size=0.75) dt = dt.fit(x_train,y_train) def measure_performance(X,y,clf, show_accuracy=True, show_classification_report=True, show_confussion_matrix=True): y_pred=clf.predict(X) if show_accuracy: print("Accuracy:{0:.3f}".format(metrics.accuracy_score(y, y_pred)),"\n") if show_classification_report: print("Classification report") print(metrics.classification_report(y,y_pred),"\n") if show_confussion_matrix: print("Confusion matrix") print(metrics.confusion_matrix(y,y_pred),"\n") measure_performance(x_test,y_test,dt) #measure on the test data (rather than train) def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(iris.target_names)) plt.xticks(tick_marks, iris.target_names, rotation=45) plt.yticks(tick_marks, iris.target_names) plt.tight_layout() plt.ylabel('True color') plt.xlabel('Predicted color') y_pred = dt.fit(x_train, y_train).predict(x_test) Explanation: Create a decision tree with the data End of explanation from sklearn.cross_validation import cross_val_score x = numpyMatrix[:,:11] x y = numpyMatrix[:,11] y scores = cross_val_score(dt,x,y,cv=10) scores np.mean(scores) Explanation: Run 10-fold cross validation on the model End of explanation cursor.execute("Select * FROM winequality") colnames = [desc[0] for desc in cursor.description] colnames plt.plot(dt.feature_importances_,'o') plt.ylim(-5,10) plt.ylim(-5,10) Explanation: If you have time, calculate the feature importance and graph based on the code in the slides from last class Use this tip for getting the column names from your cursor object End of explanation
5,360
Given the following text description, write Python code to implement the functionality described below step by step Description: TO DO Step1: This notebook calculates and plots the theoretical tilt angles. It will also plot the alpha and p0 factors vs temperature that are given in the cell below this. Material Characteristics Step2: Data Step4: Langevin-Debye Model $$ U(\theta,\phi) = -\rho_0E\ Step5: Second, Calculate the Tilt Angle $\psi$ $$ numerator() \ Step6: $$ denominator()\ Step9: $$ tan(2\psi) = \frac{\int_{\theta_{min}}^{\theta_{max}} \int_0^{2\pi} {sin\
Python Code: import numpy as np from scipy.integrate import quad, dblquad %matplotlib inline import matplotlib.pyplot as plt import scipy.optimize as opt Explanation: TO DO: Need to be able to scatter plot measured values of Psi on top of the current Psi plot. Alpha and rho LaTeX not working in plots. Legend needs to be move in the Psi plot. Consider also applying the scatter of the data and curve fit style of plotting for the parameters Plots in general need to look better LaTeX in all of the equations End of explanation thetamin = 25.6*np.pi/180 thetamax = 33.7*np.pi/180 t = 1*10**-6 #Cell Thickness Explanation: This notebook calculates and plots the theoretical tilt angles. It will also plot the alpha and p0 factors vs temperature that are given in the cell below this. Material Characteristics End of explanation tempsC = np.array([26, 27, 29, 31, 33, 35, 37]) voltages = np.array([2,3,6,7,9,11,12.5,14,16,18,20,22,23.5,26,27.5,29,31,32.5,34,36]) alpha_micro = np.array([.2575,.2475,.2275,.209,.189,.176,.15]) p0Debye = np.array([650,475,300,225,160,125,100]) #Temperature Increases to the right #This Block just converts units fields = np.array([entry/t for entry in voltages]) debye = 3.33564e-30 p0_array = np.array([entry*debye for entry in p0Debye]) #debye units to SI units k = 1.3806488e-23 p0k_array = np.array([entry/k for entry in p0_array]) #p0k is used because it helps with the integration KC = 273.15 tempsK = np.array([entry+KC for entry in tempsC]) #Celsius to Kelvin alpha_array = np.array([entry*1e-6 for entry in alpha_micro]) PSIdata = np.array([11.4056,20.4615,25.4056,27.9021,29.028,29.6154,30.2517,30.8392,31.1329,31.5245,31.8671,32.014,32.3077,32.5034,32.7972,32.9929,33.1399,33.3357,33.4336,33.6783]) Edata = fields T = tempsK[0] Explanation: Data End of explanation def Boltz(theta,phi,T,p0k,alpha,E): Compute the integrand for the Boltzmann factor. Returns ------- A function of theta,phi,T,p0k,alpha,E to be used within dblquad return np.exp((1/T)*p0k*E*np.sin(theta)*np.cos(phi)*(1+alpha*E*np.cos(phi)))*np.sin(theta) Explanation: Langevin-Debye Model $$ U(\theta,\phi) = -\rho_0E\:sin\:\theta\:cos\:\phi\:(1+\alpha E\:cos\:\phi) $$ First, Calculate the Boltzmann Factor and the Partition Function $$ {Boltz() returns:}\:\: e^{\frac{-U}{k_bT}}\:sin\:{\theta}\ $$ End of explanation def numerator(theta,phi,T,p0k,alpha,E): boltz = Boltz(theta,phi,T,p0k,alpha,E) return np.sin(2*theta)*np.cos(phi)*boltz Explanation: Second, Calculate the Tilt Angle $\psi$ $$ numerator() \:returns: {sin\:{2\theta}\:cos\:{\phi}}\:e^{\frac{-U}{k_bT}}\:sin\:{\theta} $$ End of explanation def denominator(theta,phi,T,p0k,alpha,E): boltz = Boltz(theta,phi,T,p0k,alpha,E) return ((np.cos(theta)**2) - ((np.sin(theta)**2) * (np.cos(phi)**2)))*boltz Explanation: $$ denominator()\: returns: {({cos}^2{\theta} - {sin}^2{\theta}\:{cos}^2{\phi}})\:e^{\frac{-U}{k_bT}}\:sin\:{\theta} $$ End of explanation def compute_psi(E,p0k,alpha): def Boltz(theta,phi,T,p0k,alpha,E): Compute the integrand for the Boltzmann factor. Returns ------- A function of theta,phi,T,p0k,alpha,E to be used within dblquad return np.exp((1/T)*p0k*E*np.sin(theta)*np.cos(phi)*(1+alpha*E*np.cos(phi)))*np.sin(theta) def numerator(theta,phi,T,p0k,alpha,E): boltz = Boltz(theta,phi,T,p0k,alpha,E) return np.sin(2*theta)*np.cos(phi)*boltz def denominator(theta,phi,T,p0k,alpha,E): boltz = Boltz(theta,phi,T,p0k,alpha,E) return ((np.cos(theta)**2) - ((np.sin(theta)**2) * (np.cos(phi)**2)))*boltz Computes the tilt angle(psi) by use of our tan(2psi) equation Returns ------- Float: The statistical tilt angle with conditions T,p0k,alpha,E avg_numerator, avg_numerator_error = dblquad(numerator, 0, 2*np.pi, lambda theta: thetamin, lambda theta: thetamax,args=(T,p0k,alpha,E)) avg_denominator, avg_denominator_error = dblquad(denominator, 0, 2*np.pi, lambda theta: thetamin, lambda theta: thetamax,args=(T,p0k,alpha,E)) psi = np.arctan(avg_numerator / (avg_denominator)) * (180 /(2*np.pi)) #Converting to degrees from radians and divide by two return psi compute_psi(tdata[0],p0k_array[0]*1e7,alpha_array[0]*1e10) PSIdata[0] guess = [p0k_array[0]*1e7,alpha_array[0]*1e10] guess theta_best, theta_cov = opt.curve_fit(compute_psi, Edata, PSIdata,guess,absolute_sigma=True) Explanation: $$ tan(2\psi) = \frac{\int_{\theta_{min}}^{\theta_{max}} \int_0^{2\pi} {sin\:{2\theta}\:cos\:{\phi}}\:e^{\frac{-U}{k_bT}}\:sin\:{\theta}\: d\theta d\phi}{\int_{\theta_{min}}^{\theta_{max}} \int_0^{2\pi} ({{cos}^2{\theta} - {sin}^2{\theta}\:{cos}^2{\phi}})\:e^{\frac{-U}{k_bT}}\:sin\:{\theta}\: d\theta d\phi} $$ End of explanation
5,361
Given the following text description, write Python code to implement the functionality described below step by step Description: One vs All Step1: Loading and visualizing training data The training data is 5000 digit images of digits of size 20x20. We will display a random selection of 25 of them. Step2: Part 2 Step3: Training set accuracy
Python Code: import pandas import numpy as np import scipy.io import scipy.optimize import functools import matplotlib.pyplot as plt %matplotlib inline Explanation: One vs All End of explanation ex3data1 = scipy.io.loadmat("./ex3data1.mat") X = ex3data1['X'] y = ex3data1['y'][:,0] y[y==10] = 0 m, n = X.shape m, n fig = plt.figure(figsize=(5,5)) fig.subplots_adjust(wspace=0.05, hspace=0.15) import random display_rows, display_cols = (5, 5) for i in range(display_rows * display_cols): ax = fig.add_subplot(display_rows, display_cols, i+1) ax.set_axis_off() image = X[random.randint(0, m-1)].reshape(20, 20).T image /= np.max(image) ax.imshow(image, cmap=plt.cm.Greys_r) X = np.insert(X, 0, np.ones(m), 1) Explanation: Loading and visualizing training data The training data is 5000 digit images of digits of size 20x20. We will display a random selection of 25 of them. End of explanation def sigmoid(z): return 1 / (1 + np.exp(-z)) def h(theta, x): return sigmoid(x.dot(theta)) #LRCOSTFUNCTION Compute cost and gradient for logistic regression with #regularization # J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using # theta as the parameter for regularized logistic regression and the # gradient of the cost w.r.t. to the parameters. def cost(X, y, theta, lambda_=None): # You need to return the following variables correctly J = 0 # ====================== YOUR CODE HERE ====================== # Instructions: Compute the cost of a particular choice of theta. # You should set J to the cost. # Compute the partial derivatives and set grad to the partial # derivatives of the cost w.r.t. each parameter in theta # # Hint: The computation of the cost function and gradients can be # efficiently vectorized. For example, consider the computation # # sigmoid(X * theta) # # Each row of the resulting matrix will contain the value of the # prediction for that example. You can make use of this to vectorize # the cost function and gradient computations. # # ============================================================= return J def gradient(X, y, theta, lambda_=None): # You need to return the following variables correctly grad = np.zeros(theta.shape) # ====================== YOUR CODE HERE ====================== # Hint: When computing the gradient of the regularized cost function, # there're many possible vectorized solutions, but one solution # looks like: # grad = (unregularized gradient for logistic regression) # temp = theta; # temp[0] = 0; # because we don't add anything for j = 0 # grad = grad + YOUR_CODE_HERE (using the temp variable) # ============================================================= return grad initial_theta = np.zeros(n + 1) lambda_ = 0.1 cost(X, y, initial_theta, lambda_) gradient(X, y, initial_theta, lambda_).shape def one_vs_all(X, y, num_labels, lambda_): #ONEVSALL trains multiple logistic regression classifiers and returns all #the classifiers in a matrix all_theta, where the i-th row of all_theta #corresponds to the classifier for label i # [all_theta] = ONEVSALL(X, y, num_labels, lambda) trains num_labels # logisitc regression classifiers and returns each of these classifiers # in a list all_theta, where the i-th item of all_theta corresponds # to the classifier for label i # You need to return the following variables correctly all_theta = [None] * num_labels # ====================== YOUR CODE HERE ====================== # Instructions: You should complete the following code to train num_labels # logistic regression classifiers with regularization # parameter lambda. # # Hint: You can use y == c to obtain a vector of True's and False's # # Note: For this assignment, we recommend using scipy.optimize.minimize with method='L-BFGS-B' # to optimize the cost function. # It is okay to use a for-loop (for i in range(num_labels)) to # loop over the different classes. # # Example Code for scipy.optimize.minimize: # # result = scipy.optimize.minimize(lambda t: cost(X, y==digit, t, lambda_), # initial_theta, # jac=lambda t: gradient(X, y==digit, t, lambda_), # method='L-BFGS-B') # theta = result.x # ========================================================================= num_labels = 10 thetas = one_vs_all(X, y, num_labels, lambda_) fig = plt.figure(figsize=(10,10)) for d in range(10): ax = fig.add_subplot(5, 2, d+1) ax.scatter(range(m), h(thetas[d], X), s=1) def predict_one_vs_all(X, thetas): #PREDICT Predict the label for a trained one-vs-all classifier. The labels #are in the range 1..K, where K = len(thetas) # p = PREDICTONEVSALL(all_theta, X) will return a vector of predictions # for each example in the matrix X. Note that X contains the examples in # rows. all_theta is a list where the i-th entry is a trained logistic # regression theta vector for the i-th class. You should set p to a vector # of values from 1..K (e.g., p = [1; 3; 1; 2] predicts classes 1, 3, 1, 2 # for 4 examples) # You need to return the following variables correctly p = np.zeros(X.shape[0]); # ====================== YOUR CODE HERE ====================== # Instructions: Complete the following code to make predictions using # your learned logistic regression parameters (one-vs-all). # You should set p to a vector of predictions (from 1 to # num_labels). # # Hint: This code can be done all vectorized using the max function. # In particular, the max function can also return the index of the # max element, for more information see 'help max'. If your examples # are in rows, then, you can use max(A, [], 2) to obtain the max # for each row. # # ========================================================================= return p predictions = predict_one_vs_all(X, thetas) plt.scatter(range(m), predictions, s=1) Explanation: Part 2: Vectorize Logistic Regression In this part of the exercise, you will reuse your logistic regression code from the last exercise. You task here is to make sure that your regularized logistic regression implementation is vectorized. After that, you will implement one-vs-all classification for the handwritten digit dataset. End of explanation (predictions == y).mean() Explanation: Training set accuracy: End of explanation
5,362
Given the following text description, write Python code to implement the functionality described below step by step Description: <table align="left"> <td> <a href="https Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Step2: Before you begin Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the Vertex AI API. {TODO Step3: Otherwise, set your project ID here. Step4: Get your project number {TODO Step5: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas Step6: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial. Step7: Authenticate your Google Cloud account If you are using Vertex AI Workbench Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps Step8: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. {TODO Step9: Only if your bucket doesn't already exist Step10: Finally, validate access to your Cloud Storage bucket by examining its contents Step11: Service Account {TODO Step12: Set service account access for {TODO; e.g., Vertex AI Pipelines} Run the following commands to grant your service account access to {TODO; i.e., read and write pipeline artifacts} in the bucket that you created in the previous step. You only need to run this step once per service account. Step13: Import libraries Step14: Initialize Vertex AI SDK for Python Initialize the Vertex AI SDK for Python for your project and corresponding bucket. Step15: General style examples Notebook heading Include the collapsed license at the top (this uses Colab's "Form" mode to hide the cells). Only include a single H1 title. Include the button-bar immediately under the H1. Check that the Colab and GitHub links at the top are correct. Notebook sections Use H2 (##) and H3 (###) titles for notebook section headings. Use sentence case to capitalize titles and headings. ("Train the model" instead of "Train the Model") Include a brief text explanation before any code cells. Use short titles/headings Step16: Keep examples quick. Use small datasets, or small slices of datasets. You don't need to train to convergence, train until it's obvious it's making progress. For a large example, don't try to fit all the code in the notebook. Add python files to tensorflow examples, and in the notebook run
Python Code: import os # The Vertex AI Workbench Notebook product has specific requirements IS_WORKBENCH_NOTEBOOK = os.getenv("DL_ANACONDA_HOME") IS_USER_MANAGED_WORKBENCH_NOTEBOOK = os.path.exists( "/opt/deeplearning/metadata/env_version" ) # Vertex AI Notebook requires dependencies to be installed with '--user' USER_FLAG = "" if IS_WORKBENCH_NOTEBOOK: USER_FLAG = "--user" ! pip3 install --upgrade google-cloud-aiplatform {USER_FLAG} -q # TODO: Add remaining package installs here Explanation: <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Run in Colab </a> </td> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb"> <img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo"> View on GitHub </a> </td> <td> <a href="https://console.cloud.google.com/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/notebook_template.ipynb"> <img src="https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32" alt="Vertex AI logo"> Open in Vertex AI Workbench </a> </td> </table> Overview {TODO: Include a paragraph or two explaining what this example demonstrates, who should be interested in it, and what you need to know before you get started.} Dataset {TODO: Include a paragraph with Dataset information and where to obtain it.} {TODO: Make sure the dataset is accessible to the public. Googlers: Add your dataset to the public samples bucket within gs://cloud-samples-data/ai-platform-unified, if it doesn't already exist there.} Objective In this tutorial, you learn how to {TODO: Complete the sentence explaining briefly what you will learn from the notebook, such as training, hyperparameter tuning, or serving}: This tutorial uses the following Google Cloud ML services and resources: {TODO: Add high level bullets for the services/resources demonstrated; e.g., Vertex AI Training} The steps performed include: {TODO: Add high level bullets for the steps of performed in the notebook} Costs {TODO: Update the list of billable products that your tutorial uses.} This tutorial uses billable components of Google Cloud: Vertex AI Cloud Storage {TODO: Include links to pricing documentation for each product you listed above.} Learn about Vertex AI pricing and Cloud Storage pricing, and use the Pricing Calculator to generate a cost estimate based on your projected usage. Set up your local development environment If you are using Colab or Vertex AI Workbench Notebooks, your environment already meets all the requirements to run this notebook. You can skip this step. Otherwise, make sure your environment meets this notebook's requirements. You need the following: The Google Cloud SDK Git Python 3 virtualenv Jupyter notebook running in a virtual environment with Python 3 The Google Cloud guide to Setting up a Python development environment and the Jupyter installation guide provide detailed instructions for meeting these requirements. The following steps provide a condensed set of instructions: Install and initialize the Cloud SDK. Install Python 3. Install virtualenv and create a virtual environment that uses Python 3. Activate the virtual environment. To install Jupyter, run pip3 install jupyter on the command-line in a terminal shell. To launch Jupyter, run jupyter notebook on the command-line in a terminal shell. Open this notebook in the Jupyter Notebook Dashboard. Install additional packages Install the following packages required to execute this notebook. {TODO: Suggest using the latest major GA version of each package; i.e., --upgrade} End of explanation # Automatically restart kernel after installs import os if not os.getenv("IS_TESTING"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) Explanation: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. End of explanation PROJECT_ID = "" # Get your Google Cloud project ID from gcloud if not os.getenv("IS_TESTING"): shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID: ", PROJECT_ID) Explanation: Before you begin Set up your Google Cloud project The following steps are required, regardless of your notebook environment. Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the Vertex AI API. {TODO: Update the APIs needed for your tutorial. Edit the API names, and update the link to append the API IDs, separating each one with a comma. For example, container.googleapis.com,cloudbuild.googleapis.com} If you are running this notebook locally, you will need to install the Cloud SDK. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands. Set your project ID If you don't know your project ID, you may be able to get your project ID using gcloud. End of explanation if PROJECT_ID == "" or PROJECT_ID is None: PROJECT_ID = "[your-project-id]" # @param {type:"string"} ! gcloud config set project $PROJECT_ID Explanation: Otherwise, set your project ID here. End of explanation shell_output = ! gcloud projects list --filter="PROJECT_ID:'{PROJECT_ID}'" --format='value(PROJECT_NUMBER)' PROJECT_NUMBER = shell_output[0] print("Project Number:", PROJECT_NUMBER) Explanation: Get your project number {TODO: Include these cells if the notebook uses a project number} Now that the project ID is set, you get your corresponding project number. End of explanation REGION = "[your-region]" # @param {type: "string"} if REGION == "[your-region]": REGION = "us-central1" Explanation: Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend that you choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You may not use a multi-regional bucket for training with Vertex AI. Not all regions provide support for all Vertex AI services. Learn more about Vertex AI regions. End of explanation from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") Explanation: Timestamp If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial. End of explanation # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your GCP account. This provides access to your # Cloud Storage bucket and lets you submit training jobs and prediction # requests. import os import sys # If on Vertex AI Workbench, then don't execute this code IS_COLAB = "google.colab" in sys.modules if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv( "DL_ANACONDA_HOME" ): if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this notebook locally, replace the string below with the # path to your service account key and run this cell to authenticate your GCP # account. elif not os.getenv("IS_TESTING"): %env GOOGLE_APPLICATION_CREDENTIALS '' Explanation: Authenticate your Google Cloud account If you are using Vertex AI Workbench Notebooks, your environment is already authenticated. Skip this step. If you are using Colab, run the cell below and follow the instructions when prompted to authenticate your account via oAuth. Otherwise, follow these steps: In the Cloud Console, go to the Create service account key page. Click Create service account. In the Service account name field, enter a name, and click Create. In the Grant this service account access to project section, click the Role drop-down list. Type "Vertex AI" into the filter box, and select Vertex AI Administrator. Type "Storage Object Admin" into the filter box, and select Storage Object Admin. Click Create. A JSON file that contains your key downloads to your local environment. Enter the path to your service account key as the GOOGLE_APPLICATION_CREDENTIALS variable in the cell below and run the cell. End of explanation BUCKET_NAME = "[your-bucket-name]" # @param {type:"string"} BUCKET_URI = f"gs://{BUCKET_NAME}" if BUCKET_NAME == "" or BUCKET_NAME is None or BUCKET_NAME == "[your-bucket-name]": BUCKET_NAME = PROJECT_ID + "aip-" + TIMESTAMP BUCKET_URI = f"gs://{BUCKET_NAME}" Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. {TODO: Adjust wording in the first paragraph to fit your use case - explain how your tutorial uses the Cloud Storage bucket. The example below shows how Vertex AI uses the bucket for training.} When you submit a training job using the Cloud SDK, you upload a Python package containing your training code to a Cloud Storage bucket. Vertex AI runs the code from this package. In this tutorial, Vertex AI also saves the trained model that results from your job in the same bucket. Using this model artifact, you can then create Vertex AI model and endpoint resources in order to serve online predictions. Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets. End of explanation ! gsutil mb -l $REGION -p $PROJECT_ID $BUCKET_URI Explanation: Only if your bucket doesn't already exist: Run the following cell to create your Cloud Storage bucket. End of explanation ! gsutil ls -al $BUCKET_URI Explanation: Finally, validate access to your Cloud Storage bucket by examining its contents: End of explanation SERVICE_ACCOUNT = "[your-service-account]" # @param {type:"string"} if ( SERVICE_ACCOUNT == "" or SERVICE_ACCOUNT is None or SERVICE_ACCOUNT == "[your-service-account]" ): # Get your service account from gcloud if not IS_COLAB: shell_output = !gcloud auth list 2>/dev/null SERVICE_ACCOUNT = shell_output[2].replace("*", "").strip() else: # IS_COLAB: shell_output = ! gcloud projects describe $PROJECT_ID project_number = shell_output[-1].split(":")[1].strip().replace("'", "") SERVICE_ACCOUNT = f"{project_number}-compute@developer.gserviceaccount.com" print("Service Account:", SERVICE_ACCOUNT) Explanation: Service Account {TODO: Include these cells if the notebook specifies a service account} {TODO: What uses service account in the notebook; e.g., You use a service account to create Vertex AI Pipeline jobs.}. If you do not want to use your project's Compute Engine service account, set SERVICE_ACCOUNT to another service account ID. End of explanation ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectCreator $BUCKET_URI ! gsutil iam ch serviceAccount:{SERVICE_ACCOUNT}:roles/storage.objectViewer $BUCKET_URI Explanation: Set service account access for {TODO; e.g., Vertex AI Pipelines} Run the following commands to grant your service account access to {TODO; i.e., read and write pipeline artifacts} in the bucket that you created in the previous step. You only need to run this step once per service account. End of explanation import google.cloud.aiplatform as aiplatform # TODO: import remaining libraries; e.g., tensorflow Explanation: Import libraries End of explanation aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_URI) Explanation: Initialize Vertex AI SDK for Python Initialize the Vertex AI SDK for Python for your project and corresponding bucket. End of explanation # install needed for notebook ingestion test; otherwise not part of the example ! pip3 install --upgrade tensorflow # Build the model import tensorflow as tf model = tf.keras.Sequential( [ tf.keras.layers.Dense(10, activation="relu", input_shape=(None, 5)), tf.keras.layers.Dense(3), ] ) # Run the model on a single batch of data, and inspect the output. import numpy as np result = model(tf.constant(np.random.randn(10, 5), dtype=tf.float32)).numpy() print("min:", result.min()) print("max:", result.max()) print("mean:", result.mean()) print("shape:", result.shape) # Compile the model for training model.compile( optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.categorical_crossentropy ) Explanation: General style examples Notebook heading Include the collapsed license at the top (this uses Colab's "Form" mode to hide the cells). Only include a single H1 title. Include the button-bar immediately under the H1. Check that the Colab and GitHub links at the top are correct. Notebook sections Use H2 (##) and H3 (###) titles for notebook section headings. Use sentence case to capitalize titles and headings. ("Train the model" instead of "Train the Model") Include a brief text explanation before any code cells. Use short titles/headings: "Download the data", "Build the model", "Train the model". Writing style Use present tense. ("You receive a response" instead of "You will receive a response") Use active voice. ("The service processes the request" instead of "The request is processed by the service") Use second person and an imperative style. Correct examples: "Update the field", "You must update the field" Incorrect examples: "Let's update the field", "We'll update the field", "The user should update the field" Googlers: Please follow our branding guidelines. Code Put all your installs and imports in a setup section. Save the notebook with the Table of Contents open. Write Python 3 compatible code. Follow the Google Python Style guide and write readable code. Keep cells small (max ~20 lines). TensorFlow code style Use the highest level API that gets the job done (unless the goal is to demonstrate the low level API). For example, when using Tensorflow: Use TF.keras.Sequential > keras functional api > keras model subclassing > ... Use model.fit > model.train_on_batch > manual GradientTapes. Use eager-style code. Use tensorflow_datasets and tf.data where possible. Notebook code style examples Notebooks are for people. Write code optimized for clarity. Demonstrate small parts before combining them into something more complex. Like below: End of explanation # Delete endpoint resource ! gcloud ai endpoints delete $ENDPOINT_NAME --quiet --region $REGION_NAME # Delete model resource ! gcloud ai models delete $MODEL_NAME --quiet # Delete Cloud Storage objects that were created ! gsutil -m rm -r $JOB_DIR if os.getenv("IS_TESTING"): ! gsutil -m rm -r $BUCKET_URI Explanation: Keep examples quick. Use small datasets, or small slices of datasets. You don't need to train to convergence, train until it's obvious it's making progress. For a large example, don't try to fit all the code in the notebook. Add python files to tensorflow examples, and in the notebook run: ! pip3 install git+https://github.com/tensorflow/examples Cleaning up To clean up all Google Cloud resources used in this project, you can delete the Google Cloud project you used for the tutorial. Otherwise, you can delete the individual resources you created in this tutorial: {TODO: Include commands to delete individual resources below} End of explanation
5,363
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the sequence of words. Here we'll use a dataset of movie reviews, accompanied by labels. The architecture for this network is shown below. <img src="assets/network_diagram.png" width=400px> Here, we'll pass in words to an embedding layer. We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the word2vec lesson. You can actually train up an embedding with word2vec and use it here. But it's good enough to just have an embedding layer and let the network learn the embedding table on it's own. From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We're using the sigmoid because we're trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function. We don't care about the sigmoid outputs except for the very last one, we can ignore the rest. We'll calculate the cost from the output of the last step and the training label. Step1: Data preprocessing The first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit. You can see an example of the reviews data above. We'll want to get rid of those periods. Also, you might notice that the reviews are delimited with newlines \n. To deal with those, I'm going to split the text into each review using \n as the delimiter. Then I can combined all the reviews back together into one big string. First, let's remove all punctuation. Then get all the text without the newlines and split it into individual words. Step2: Encoding the words The embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network. Exercise Step3: Encoding the labels Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1. Exercise Step4: If you built labels correctly, you should see the next output. Step5: Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters. Exercise Step6: Exercise Step7: If you build features correctly, it should look like that cell output below. Step8: Training, Validation, Test With our data in nice shape, we'll split it into training, validation, and test sets. Exercise Step9: With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like Step10: For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be batch_size vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability. Exercise Step11: Embedding Now we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using word2vec, then load it here. But, it's fine to just make a new layer and let the network learn the weights. Exercise Step12: LSTM cell <img src="assets/network_diagram.png" width=400px> Next, we'll create our LSTM cells to use in the recurrent network (TensorFlow documentation). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph. To create a basic LSTM cell for the graph, you'll want to use tf.contrib.rnn.BasicLSTMCell. Looking at the function documentation Step13: RNN forward pass <img src="assets/network_diagram.png" width=400px> Now we need to actually run the data through the RNN nodes. You can use tf.nn.dynamic_rnn to do this. You'd pass in the RNN cell you created (our multiple layered LSTM cell for instance), and the inputs to the network. outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state) Above I created an initial state, initial_state, to pass to the RNN. This is the cell state that is passed between the hidden layers in successive time steps. tf.nn.dynamic_rnn takes care of most of the work for us. We pass in our cell and the input to the cell, then it does the unrolling and everything else for us. It returns outputs for each time step and the final_state of the hidden layer. Exercise Step14: Output We only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with outputs[ Step15: Validation accuracy Here we can add a few nodes to calculate the accuracy which we'll use in the validation pass. Step16: Batching This is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the x and y arrays and returns slices out of those arrays with size [batch_size]. Step17: Training Below is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the checkpoints directory exists. Step18: Testing
Python Code: import numpy as np import tensorflow as tf with open('../sentiment-network/reviews.txt', 'r') as f: reviews = f.read() with open('../sentiment-network/labels.txt', 'r') as f: labels = f.read() reviews[:2000] Explanation: Sentiment Analysis with an RNN In this notebook, you'll implement a recurrent neural network that performs sentiment analysis. Using an RNN rather than a feedfoward network is more accurate since we can include information about the sequence of words. Here we'll use a dataset of movie reviews, accompanied by labels. The architecture for this network is shown below. <img src="assets/network_diagram.png" width=400px> Here, we'll pass in words to an embedding layer. We need an embedding layer because we have tens of thousands of words, so we'll need a more efficient representation for our input data than one-hot encoded vectors. You should have seen this before from the word2vec lesson. You can actually train up an embedding with word2vec and use it here. But it's good enough to just have an embedding layer and let the network learn the embedding table on it's own. From the embedding layer, the new representations will be passed to LSTM cells. These will add recurrent connections to the network so we can include information about the sequence of words in the data. Finally, the LSTM cells will go to a sigmoid output layer here. We're using the sigmoid because we're trying to predict if this text has positive or negative sentiment. The output layer will just be a single unit then, with a sigmoid activation function. We don't care about the sigmoid outputs except for the very last one, we can ignore the rest. We'll calculate the cost from the output of the last step and the training label. End of explanation from string import punctuation all_text = ''.join([c for c in reviews if c not in punctuation]) reviews = all_text.split('\n') all_text = ' '.join(reviews) words = all_text.split() all_text[:2000] words[:100] Explanation: Data preprocessing The first step when building a neural network model is getting your data into the proper form to feed into the network. Since we're using embedding layers, we'll need to encode each word with an integer. We'll also want to clean it up a bit. You can see an example of the reviews data above. We'll want to get rid of those periods. Also, you might notice that the reviews are delimited with newlines \n. To deal with those, I'm going to split the text into each review using \n as the delimiter. Then I can combined all the reviews back together into one big string. First, let's remove all punctuation. Then get all the text without the newlines and split it into individual words. End of explanation # Create your dictionary that maps vocab words to integers here vocab_to_int = # Convert the reviews to integers, same shape as reviews list, but with integers reviews_ints = Explanation: Encoding the words The embedding lookup requires that we pass in integers to our network. The easiest way to do this is to create dictionaries that map the words in the vocabulary to integers. Then we can convert each of our reviews into integers so they can be passed into the network. Exercise: Now you're going to encode the words with integers. Build a dictionary that maps words to integers. Later we're going to pad our input vectors with zeros, so make sure the integers start at 1, not 0. Also, convert the reviews to integers and store the reviews in a new list called reviews_ints. End of explanation # Convert labels to 1s and 0s for 'positive' and 'negative' labels = Explanation: Encoding the labels Our labels are "positive" or "negative". To use these labels in our network, we need to convert them to 0 and 1. Exercise: Convert labels from positive and negative to 1 and 0, respectively. End of explanation from collections import Counter review_lens = Counter([len(x) for x in reviews_ints]) print("Zero-length reviews: {}".format(review_lens[0])) print("Maximum review length: {}".format(max(review_lens))) Explanation: If you built labels correctly, you should see the next output. End of explanation # Filter out that review with 0 length reviews_ints = Explanation: Okay, a couple issues here. We seem to have one review with zero length. And, the maximum review length is way too many steps for our RNN. Let's truncate to 200 steps. For reviews shorter than 200, we'll pad with 0s. For reviews longer than 200, we can truncate them to the first 200 characters. Exercise: First, remove the review with zero length from the reviews_ints list. End of explanation seq_len = 200 features = Explanation: Exercise: Now, create an array features that contains the data we'll pass to the network. The data should come from review_ints, since we want to feed integers to the network. Each row should be 200 elements long. For reviews shorter than 200 words, left pad with 0s. That is, if the review is ['best', 'movie', 'ever'], [117, 18, 128] as integers, the row will look like [0, 0, 0, ..., 0, 117, 18, 128]. For reviews longer than 200, use on the first 200 words as the feature vector. This isn't trivial and there are a bunch of ways to do this. But, if you're going to be building your own deep learning networks, you're going to have to get used to preparing your data. End of explanation features[:10,:100] Explanation: If you build features correctly, it should look like that cell output below. End of explanation split_frac = 0.8 train_x, val_x = train_y, val_y = val_x, test_x = val_y, test_y = print("\t\t\tFeature Shapes:") print("Train set: \t\t{}".format(train_x.shape), "\nValidation set: \t{}".format(val_x.shape), "\nTest set: \t\t{}".format(test_x.shape)) Explanation: Training, Validation, Test With our data in nice shape, we'll split it into training, validation, and test sets. Exercise: Create the training, validation, and test sets here. You'll need to create sets for the features and the labels, train_x and train_y for example. Define a split fraction, split_frac as the fraction of data to keep in the training set. Usually this is set to 0.8 or 0.9. The rest of the data will be split in half to create the validation and testing data. End of explanation lstm_size = 256 lstm_layers = 1 batch_size = 500 learning_rate = 0.001 Explanation: With train, validation, and text fractions of 0.8, 0.1, 0.1, the final shapes should look like: Feature Shapes: Train set: (20000, 200) Validation set: (2500, 200) Test set: (2500, 200) Build the graph Here, we'll build the graph. First up, defining the hyperparameters. lstm_size: Number of units in the hidden layers in the LSTM cells. Usually larger is better performance wise. Common values are 128, 256, 512, etc. lstm_layers: Number of LSTM layers in the network. I'd start with 1, then add more if I'm underfitting. batch_size: The number of reviews to feed the network in one training pass. Typically this should be set as high as you can go without running out of memory. learning_rate: Learning rate End of explanation n_words = len(vocab_to_int) + 1 # Adding 1 because we use 0's for padding, dictionary started at 1 # Create the graph object graph = tf.Graph() # Add nodes to the graph with graph.as_default(): inputs_ = labels_ = keep_prob = Explanation: For the network itself, we'll be passing in our 200 element long review vectors. Each batch will be batch_size vectors. We'll also be using dropout on the LSTM layer, so we'll make a placeholder for the keep probability. Exercise: Create the inputs_, labels_, and drop out keep_prob placeholders using tf.placeholder. labels_ needs to be two-dimensional to work with some functions later. Since keep_prob is a scalar (a 0-dimensional tensor), you shouldn't provide a size to tf.placeholder. End of explanation # Size of the embedding vectors (number of units in the embedding layer) embed_size = 300 with graph.as_default(): embedding = embed = Explanation: Embedding Now we'll add an embedding layer. We need to do this because there are 74000 words in our vocabulary. It is massively inefficient to one-hot encode our classes here. You should remember dealing with this problem from the word2vec lesson. Instead of one-hot encoding, we can have an embedding layer and use that layer as a lookup table. You could train an embedding layer using word2vec, then load it here. But, it's fine to just make a new layer and let the network learn the weights. Exercise: Create the embedding lookup matrix as a tf.Variable. Use that embedding matrix to get the embedded vectors to pass to the LSTM cell with tf.nn.embedding_lookup. This function takes the embedding matrix and an input tensor, such as the review vectors. Then, it'll return another tensor with the embedded vectors. So, if the embedding layer has 200 units, the function will return a tensor with size [batch_size, 200]. End of explanation with graph.as_default(): # Your basic LSTM cell lstm = # Add dropout to the cell drop = # Stack up multiple LSTM layers, for deep learning cell = # Getting an initial state of all zeros initial_state = cell.zero_state(batch_size, tf.float32) Explanation: LSTM cell <img src="assets/network_diagram.png" width=400px> Next, we'll create our LSTM cells to use in the recurrent network (TensorFlow documentation). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph. To create a basic LSTM cell for the graph, you'll want to use tf.contrib.rnn.BasicLSTMCell. Looking at the function documentation: tf.contrib.rnn.BasicLSTMCell(num_units, forget_bias=1.0, input_size=None, state_is_tuple=True, activation=&lt;function tanh at 0x109f1ef28&gt;) you can see it takes a parameter called num_units, the number of units in the cell, called lstm_size in this code. So then, you can write something like lstm = tf.contrib.rnn.BasicLSTMCell(num_units) to create an LSTM cell with num_units. Next, you can add dropout to the cell with tf.contrib.rnn.DropoutWrapper. This just wraps the cell in another cell, but with dropout added to the inputs and/or outputs. It's a really convenient way to make your network better with almost no effort! So you'd do something like drop = tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob) Most of the time, your network will have better performance with more layers. That's sort of the magic of deep learning, adding more layers allows the network to learn really complex relationships. Again, there is a simple way to create multiple layers of LSTM cells with tf.contrib.rnn.MultiRNNCell: cell = tf.contrib.rnn.MultiRNNCell([drop] * lstm_layers) Here, [drop] * lstm_layers creates a list of cells (drop) that is lstm_layers long. The MultiRNNCell wrapper builds this into multiple layers of RNN cells, one for each cell in the list. So the final cell you're using in the network is actually multiple (or just one) LSTM cells with dropout. But it all works the same from an achitectural viewpoint, just a more complicated graph in the cell. Exercise: Below, use tf.contrib.rnn.BasicLSTMCell to create an LSTM cell. Then, add drop out to it with tf.contrib.rnn.DropoutWrapper. Finally, create multiple LSTM layers with tf.contrib.rnn.MultiRNNCell. Here is a tutorial on building RNNs that will help you out. End of explanation with graph.as_default(): outputs, final_state = Explanation: RNN forward pass <img src="assets/network_diagram.png" width=400px> Now we need to actually run the data through the RNN nodes. You can use tf.nn.dynamic_rnn to do this. You'd pass in the RNN cell you created (our multiple layered LSTM cell for instance), and the inputs to the network. outputs, final_state = tf.nn.dynamic_rnn(cell, inputs, initial_state=initial_state) Above I created an initial state, initial_state, to pass to the RNN. This is the cell state that is passed between the hidden layers in successive time steps. tf.nn.dynamic_rnn takes care of most of the work for us. We pass in our cell and the input to the cell, then it does the unrolling and everything else for us. It returns outputs for each time step and the final_state of the hidden layer. Exercise: Use tf.nn.dynamic_rnn to add the forward pass through the RNN. Remember that we're actually passing in vectors from the embedding layer, embed. End of explanation with graph.as_default(): predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid) cost = tf.losses.mean_squared_error(labels_, predictions) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) Explanation: Output We only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with outputs[:, -1], the calculate the cost from that and labels_. End of explanation with graph.as_default(): correct_pred = tf.equal(tf.cast(tf.round(predictions), tf.int32), labels_) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) Explanation: Validation accuracy Here we can add a few nodes to calculate the accuracy which we'll use in the validation pass. End of explanation def get_batches(x, y, batch_size=100): n_batches = len(x)//batch_size x, y = x[:n_batches*batch_size], y[:n_batches*batch_size] for ii in range(0, len(x), batch_size): yield x[ii:ii+batch_size], y[ii:ii+batch_size] Explanation: Batching This is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the x and y arrays and returns slices out of those arrays with size [batch_size]. End of explanation epochs = 10 with graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=graph) as sess: sess.run(tf.global_variables_initializer()) iteration = 1 for e in range(epochs): state = sess.run(initial_state) for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch_size), 1): feed = {inputs_: x, labels_: y[:, None], keep_prob: 0.5, initial_state: state} loss, state, _ = sess.run([cost, final_state, optimizer], feed_dict=feed) if iteration%5==0: print("Epoch: {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Train loss: {:.3f}".format(loss)) if iteration%25==0: val_acc = [] val_state = sess.run(cell.zero_state(batch_size, tf.float32)) for x, y in get_batches(val_x, val_y, batch_size): feed = {inputs_: x, labels_: y[:, None], keep_prob: 1, initial_state: val_state} batch_acc, val_state = sess.run([accuracy, final_state], feed_dict=feed) val_acc.append(batch_acc) print("Val acc: {:.3f}".format(np.mean(val_acc))) iteration +=1 saver.save(sess, "checkpoints/sentiment.ckpt") Explanation: Training Below is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the checkpoints directory exists. End of explanation test_acc = [] with tf.Session(graph=graph) as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) test_state = sess.run(cell.zero_state(batch_size, tf.float32)) for ii, (x, y) in enumerate(get_batches(test_x, test_y, batch_size), 1): feed = {inputs_: x, labels_: y[:, None], keep_prob: 1, initial_state: test_state} batch_acc, test_state = sess.run([accuracy, final_state], feed_dict=feed) test_acc.append(batch_acc) print("Test accuracy: {:.3f}".format(np.mean(test_acc))) Explanation: Testing End of explanation
5,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Step 0 - hyperparams vocab_size is all the potential words you could have (classification for translation case) and max sequence length are the SAME thing decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our case it does not seem really to be a relationship there but we can experiment and find out later, not a priority thing right now Step1: Actual Run Step2: Arima Step3: Testing with easy mode on Step4: Testing with easy mode off
Python Code: input_len = 60 target_len = 30 batch_size = 50 with_EOS = False csv_in = '../price_history_03_seq_start_suddens_trimmed.csv' Explanation: Step 0 - hyperparams vocab_size is all the potential words you could have (classification for translation case) and max sequence length are the SAME thing decoder RNN hidden units are usually same size as encoder RNN hidden units in translation but for our case it does not seem really to be a relationship there but we can experiment and find out later, not a priority thing right now End of explanation data_path = '../../../../Dropbox/data' ph_data_path = data_path + '/price_history' assert path.isdir(ph_data_path) npz_full = ph_data_path + '/price_history_per_mobile_phone.npz' dataset_gen = PriceHistoryDatasetPerMobilePhone(random_state=random_state) dic = dataset_gen.genSaveDictionary(csv_in=csv_in, window_len=90, npz_out=npz_full) dic.keys() Explanation: Actual Run End of explanation from arima.arima_estimator import ArimaEstimator import warnings from collections import OrderedDict from mylibs.py_helper import cartesian_coord from arima.arima_cv import ArimaCV parameters = OrderedDict([ ('p_auto_regression_order', range(6)), #0-5 ('d_integration_level', range(3)), #0-2 ('q_moving_average', range(6)), #0-5 ]) cart = cartesian_coord(*parameters.values()) cart.shape cur_sku = dic.values()[0] cur_sku.keys() full_mat = cur_sku['train'] full_mat.shape target_len inputs = full_mat[:, :-target_len] inputs.shape targets = full_mat[:, -target_len:] targets.shape %%time with warnings.catch_warnings(): warnings.filterwarnings("ignore") ae = ArimaEstimator(p_auto_regression_order=0, d_integration_level=1, q_moving_average=0, easy_mode=True) ae.fit(inputs, targets).score(inputs, targets) score_dic_filepath = data_path + "/arima/scoredic_testing.npy" path.abspath(score_dic_filepath) %%time with warnings.catch_warnings(): warnings.filterwarnings("ignore") scoredic = ArimaCV.cross_validate(inputs=inputs, targets=targets, cartesian_combinations=cart, score_dic_filepath=score_dic_filepath, easy_mode=True) #4h 4min 51s / 108 cases => ~= 136 seconds per case ! arr = np.array(list(scoredic.iteritems())) arr.shape np.NaN import math float('nan') == np.NaN #np.isnan() filtered_arr = arr[ np.logical_not(arr[:, 1] != arr[:, 1]) ] filtered_arr.shape plt.plot(filtered_arr[:, 1]) minarg = np.argmin(filtered_arr[:, 1]) minarg best_params = filtered_arr[minarg, 0] best_params test_mat = cur_sku['test'] test_ins = test_mat[:-target_len] test_ins.shape test_tars = test_mat[-target_len:] test_tars.shape test_ins_vals = test_ins.values.reshape(1, -1) test_ins_vals.shape test_tars_vals = test_tars.values.reshape(1, -1) test_tars_vals.shape Explanation: Arima End of explanation %%time with warnings.catch_warnings(): warnings.filterwarnings("ignore") ae = ArimaEstimator(p_auto_regression_order=best_params[0], d_integration_level=best_params[1], q_moving_average=best_params[2], easy_mode=True) score = ae.fit(test_ins_vals, test_tars_vals).score(test_ins_vals, test_tars_vals) score plt.figure(figsize=(15,7)) plt.plot(ae.preds.flatten(), label='preds') test_tars.plot(label='real') plt.legend() plt.show() Explanation: Testing with easy mode on End of explanation %%time with warnings.catch_warnings(): warnings.filterwarnings("ignore") ae = ArimaEstimator(p_auto_regression_order=best_params[0], d_integration_level=best_params[1], q_moving_average=best_params[2], easy_mode=False) score = ae.fit(test_ins_vals, test_tars_vals).score(test_ins_vals, test_tars_vals) score plt.figure(figsize=(15,7)) plt.plot(ae.preds.flatten(), label='preds') test_tars.plot(label='real') plt.legend() plt.show() Explanation: Testing with easy mode off End of explanation
5,365
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: Estimators Most of sklearn is designed around the concept of "estimators", which are objects that can transform data. That is, we can think of an estimator as a function of the form $f(x,\theta)$, where $x$ is the input, and $\theta$ is the internal state (e.g., model parameters) of the object. Each estimator has two main methods Step2: Data preprocessing <a class="anchor" id="preprocess"></a> We often have to preprocess data before feeding it to an ML model. We give some examples below. Standardizing numeric features in Boston housing <a class="anchor" id="preprocess-boston"></a> Step5: One-hot encoding for Autompg <a class="anchor" id="preprocess-onehot"></a> We need to convert categorical inputs (aka factors) to one-hot vectors. We illustrate this below. Step6: Feature crosses for Autompg <a class="anchor" id="preprocess-feature-cross"></a> We will use the Patsy library, which provides R-like syntax for specifying feature interactions.
Python Code: # Standard Python libraries from __future__ import absolute_import, division, print_function, unicode_literals import os import time import numpy as np import glob import matplotlib.pyplot as plt import PIL import imageio from IPython import display import sklearn import seaborn as sns sns.set(style="ticks", color_codes=True) import pandas as pd pd.set_option("precision", 2) # 2 decimal places pd.set_option("display.max_rows", 20) pd.set_option("display.max_columns", 30) pd.set_option("display.width", 100) # wide windows Explanation: <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/intro/sklearn_intro.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Introduction to sklearn Scikit-learn is a widely used Python machine learning library. There are several good tutorials on it, some of which we list below. | Name | Notes | | ---- | ---- | |Python data science handbook| by Jake VanderPlas. Covers many python libraries. | |Hands-on Machine Learning with Scikit-Learn, Keras and TensorFlow v2| by Aurelion Geron. Covers sklearn and TF2.| |Python Machine Learning v3 | by Sebastian Raschka. Covers sklearn and TF2. | In the sections below, we just give a few examples of how to use it. If you want to scale up sklearn to handle datasets that do not fit into memory, and/or you want to run slow jobs in parallel (e.g., for grid search over model hyper-parameters) on multiple cores of your laptop or in the cloud, you should use ML-dask. Install necessary libraries End of explanation from sklearn.linear_model import LogisticRegression from sklearn import datasets iris = datasets.load_iris() # use 2 features and all 3 classes X = iris["data"][:, (2, 3)] # petal length, petal width y = iris["target"] # softmax_reg = LogisticRegression(multi_class="multinomial", solver="lbfgs", penalty="none") softmax_reg = LogisticRegression(multi_class="multinomial", solver="lbfgs", C=1000, random_state=42) softmax_reg.fit(X, y) # Get predictive distribution for a single example X = [[2.5, 3.0]] # (1,2) array y_probs = softmax_reg.predict_proba(X) print(np.round(y_probs, 2)) # Fit model and evaluate on separate test set from sklearn.model_selection import train_test_split iris = datasets.load_iris() X = iris.data[:, :2] # we only take the first two features to make problem harder # X = iris.data # use all data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) # compute MLE (penalty=None means do not use regularization) logreg = LogisticRegression(solver="lbfgs", multi_class="multinomial", penalty="none") logreg.fit(X_train, y_train) y_pred = logreg.predict(X_test) # categorical labels errs = y_pred != y_test nerrs = np.sum(errs) print("Made {} errors out of {}, on instances {}".format(nerrs, len(y_pred), np.where(errs))) # With ndims=2: Made 10 errors out of 50, on instances # (array([ 4, 15, 21, 32, 35, 36, 40, 41, 42, 48]),) from sklearn.metrics import zero_one_loss err_rate_test = zero_one_loss(y_test, y_pred) assert np.isclose(err_rate_test, nerrs / len(y_pred)) err_rate_train = zero_one_loss(y_train, logreg.predict(X_train)) print("Error rates on train {:0.3f} and test {:0.3f}".format(err_rate_train, err_rate_test)) # Error rates on train 0.180 and test 0.200 Explanation: Estimators Most of sklearn is designed around the concept of "estimators", which are objects that can transform data. That is, we can think of an estimator as a function of the form $f(x,\theta)$, where $x$ is the input, and $\theta$ is the internal state (e.g., model parameters) of the object. Each estimator has two main methods: fit and predict. The fit method has the form f=fit(f,data), and updates the internal state (e.g., by computing the maximum likelihood estimate of the parameters). The predict method has the form y=predict(f,x). We can also have stateless estimators (with no internal parameters), which do things like preprocess the data. We give examples of all this below. Logistic regression We illustrate how to fit a logistic regression model using the Iris dataset. End of explanation import sklearn.datasets import sklearn.linear_model as lm from sklearn.model_selection import train_test_split boston = sklearn.datasets.load_boston() X = boston.data y = boston.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42) scaler = sklearn.preprocessing.StandardScaler() scaler = scaler.fit(X_train) X_train_scaled = scaler.transform(X_train) X_test_scaled = scaler.transform(X_test) X_scaled = scaler.transform(X) # entire dataset # scatter plot of response vs each feature. # The shape of the data looks the same as the unscaled case, but the x-axis of each feature is changed. nrows = 3 ncols = 4 fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharey=True, figsize=[15, 10]) plt.tight_layout() plt.clf() for i in range(0, 12): plt.subplot(nrows, ncols, i + 1) plt.scatter(X_scaled[:, i], y) plt.xlabel(boston.feature_names[i]) plt.ylabel("house price") plt.grid() # save_fig("boston-housing-scatter-scaled.pdf") plt.show() Explanation: Data preprocessing <a class="anchor" id="preprocess"></a> We often have to preprocess data before feeding it to an ML model. We give some examples below. Standardizing numeric features in Boston housing <a class="anchor" id="preprocess-boston"></a> End of explanation # Get data url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data" column_names = ["MPG", "Cylinders", "Displacement", "Horsepower", "Weight", "Acceleration", "Year", "Origin", "Name"] df = pd.read_csv(url, names=column_names, sep="\s+", na_values="?") # The last column (name) is a unique id for the car, so we drop it df = df.drop(columns=["Name"]) # Ensure same number of rows for all features. df = df.dropna() # Convert origin integer to categorical factor df["Origin"] = df.Origin.replace([1, 2, 3], ["USA", "Europe", "Japan"]) df["Origin"] = df["Origin"].astype("category") df.info() df.tail() # Convert origin factor to integer from sklearn.preprocessing import LabelEncoder encoder = LabelEncoder() origin_cat = df["Origin"] print("before transform") print(origin_cat) origin_int = encoder.fit_transform(origin_cat) print("after transform") print(origin_int) # Make sure we can decode back to strings print("class names are {}".format(encoder.classes_)) origin_cat2 = encoder.inverse_transform(origin_int) print(origin_cat2) # Convert integer encoding to one-hot vectors from sklearn.preprocessing import OneHotEncoder encoder = OneHotEncoder() origin_onehot_sparse = encoder.fit_transform(origin_int.reshape(-1, 1)) # Sparse array origin_onehot_dense = origin_onehot_sparse.toarray() print(origin_onehot_dense[-5:, :]) # We should be able to combine LabelEncoder and OneHotEncoder together # using a Pipeline. However this fails due to known bug: https://github.com/scikit-learn/scikit-learn/issues/3956 # TypeError: fit_transform() takes 2 positional arguments but 3 were given from sklearn.pipeline import Pipeline pipeline = Pipeline([ ('str2int', LabelEncoder()), ('int2onehot', OneHotEncoder()) ]) origin_onehot2 = pipeline.fit_transform(df['Origin']) # However, as of sckit v0.20, we can now convert Categorical to OneHot directly. # https://jorisvandenbossche.github.io/blog/2017/11/20/categorical-encoder/ # https://medium.com/bigdatarepublic/integrating-pandas-and-scikit-learn-with-pipelines-f70eb6183696 from sklearn.preprocessing import CategoricalEncoder # not available :( encoder = CategoricalEncoder() origin_onehot2 = encoder.fit_transform(df['Origin']) print(origin_onehot2) # Function to add one-hot encoding as extra columns to a dataframe # See also sklearn-pandas library # https://github.com/scikit-learn-contrib/sklearn-pandas#transformation-mapping def one_hot_encode_dataframe_col(df, colname): encoder = OneHotEncoder(sparse=False) data = df[[colname]] # Extract column as (N,1) matrix data_onehot = encoder.fit_transform(data) df = df.drop(columns=[colname]) ncats = np.size(encoder.categories_) for c in range(ncats): colname_c = "{}:{}".format(colname, c) df[colname_c] = data_onehot[:, c] return df, encoder df_onehot, encoder_origin = one_hot_encode_dataframe_col(df, "Origin") df_onehot.tail() Explanation: One-hot encoding for Autompg <a class="anchor" id="preprocess-onehot"></a> We need to convert categorical inputs (aka factors) to one-hot vectors. We illustrate this below. End of explanation # Simple example of feature cross import patsy cylinders = pd.Series([4, 2, 3, 2, 4], dtype="int") colors = pd.Series(["R", "R", "G", "B", "R"], dtype="category") origin = pd.Series(["U", "J", "J", "U", "U"], dtype="category") data = {"Cyl": cylinders, "C": colors, "O": origin} df0 = pd.DataFrame(data=data) print(df0) df_cross0 = patsy.dmatrix("Cyl + C + O + C:O", df0, return_type="dataframe") print(df_cross0.tail()) # Create feature crosses for AutoMPG # For demo purposes, replace integer year with binary decade (70s and 80s) year = df.pop("Year") decade = [70 if (y >= 70 and y <= 79) else 80 for y in year] df["Decade"] = pd.Series(decade, dtype="category") # Make feature cross between #decades and origin (2*3 values) y = df.pop("MPG") # Remove target column from dataframe and store df.columns = ["Cyl", "Dsp", "HP", "Wgt", "Acc", "O", "D"] # Shorten names df["O"] = df["O"].replace(["USA", "Europe", "Japan"], ["U", "E", "J"]) df_cross = patsy.dmatrix("D:O + Cyl + Dsp + HP + Wgt + Acc", df, return_type="dataframe") print(df_cross.tail()) Explanation: Feature crosses for Autompg <a class="anchor" id="preprocess-feature-cross"></a> We will use the Patsy library, which provides R-like syntax for specifying feature interactions. End of explanation
5,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 1 Least squares and linear basis functions models 1.1 Least squares Step2: Load the data Here we will reuse the dataset height_weight_genders.csv from previous exercise section to check the correctness of your implementation. Please compare it with your previous result. Step3: Test it here Step5: 1.2 Least squares with a linear basis function model Start from this section, we will use the dataset dataEx3.csv. Implement polynomial basis functions Step7: Let us play with polynomial regression. Note that we will use your implemented function compute_mse. Please copy and paste your implementation from exercise02. Step8: Run polynomial regression Step10: 2 Evaluating model predication performance Let us show the train and test splits for various polynomial degrees. First of all, please fill in the function split_data() Step12: Then, test your split_data function below. Step13: Demo time Step16: Ridge Regression Please fill in the function below. Step17: Demo time
Python Code: def least_squares(y, tx): calculate the least squares solution. a = tx.T.dot(tx) b = tx.T.dot(y) return np.linalg.solve(a, b) Explanation: 1 Least squares and linear basis functions models 1.1 Least squares End of explanation from helpers import * def test_your_least_squares(): height, weight, gender = load_data_from_ex02(sub_sample=False, add_outlier=False) x, mean_x, std_x = standardize(height) y, tx = build_model_data(x, weight) weight = least_squares(y, tx) print(weight) Explanation: Load the data Here we will reuse the dataset height_weight_genders.csv from previous exercise section to check the correctness of your implementation. Please compare it with your previous result. End of explanation test_your_least_squares() Explanation: Test it here End of explanation # load dataset x, y = load_data() print("shape of x {}".format(x.shape)) print("shape of y {}".format(y.shape)) def build_poly(x, degree): polynomial basis functions for input data x, for j=0 up to j=degree. poly = np.ones((len(x), 1)) for deg in range(1, degree+1): poly = np.c_[poly, np.power(x, deg)] return poly Explanation: 1.2 Least squares with a linear basis function model Start from this section, we will use the dataset dataEx3.csv. Implement polynomial basis functions End of explanation from costs import compute_mse from plots import * def polynomial_regression(): Constructing the polynomial basis function expansion of the data, and then running least squares regression. # define parameters degrees = [1, 3, 7, 12] # define the structure of the figure num_row = 2 num_col = 2 f, axs = plt.subplots(num_row, num_col) for ind, degree in enumerate(degrees): # form dataset to do polynomial regression. tx = build_poly(x, degree) # least squares weights = least_squares(y, tx) # compute RMSE rmse = np.sqrt(2 * compute_mse(y, tx, weights)) print("Processing {i}th experiment, degree={d}, rmse={loss}".format( i=ind + 1, d=degree, loss=rmse)) # plot fit plot_fitted_curve( y, x, weights, degree, axs[ind // num_col][ind % num_col]) plt.tight_layout() plt.savefig("visualize_polynomial_regression") plt.show() Explanation: Let us play with polynomial regression. Note that we will use your implemented function compute_mse. Please copy and paste your implementation from exercise02. End of explanation polynomial_regression() Explanation: Run polynomial regression End of explanation def split_data(x, y, ratio, seed=1): split the dataset based on the split ratio. # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] index_te = indices[index_split:] # create split x_tr = x[index_tr] x_te = x[index_te] y_tr = y[index_tr] y_te = y[index_te] return x_tr, x_te, y_tr, y_te Explanation: 2 Evaluating model predication performance Let us show the train and test splits for various polynomial degrees. First of all, please fill in the function split_data() End of explanation def train_test_split_demo(x, y, degree, ratio, seed): polynomial regression with different split ratios and different degrees. x_tr, x_te, y_tr, y_te = split_data(x, y, ratio, seed) # form tx tx_tr = build_poly(x_tr, degree) tx_te = build_poly(x_te, degree) weight = least_squares(y_tr, tx_tr) # calculate RMSE for train and test data. rmse_tr = np.sqrt(2 * compute_mse(y_tr, tx_tr, weight)) rmse_te = np.sqrt(2 * compute_mse(y_te, tx_te, weight)) print("proportion={p}, degree={d}, Training RMSE={tr:.3f}, Testing RMSE={te:.3f}".format( p=ratio, d=degree, tr=rmse_tr, te=rmse_te)) Explanation: Then, test your split_data function below. End of explanation seed = 6 degrees = [1, 3, 7, 12] split_ratios = [0.9, 0.5, 0.1] for split_ratio in split_ratios: for degree in degrees: train_test_split_demo(x, y, degree, split_ratio, seed) Explanation: Demo time End of explanation def ridge_regression(y, tx, lambda_): implement ridge regression. aI = 2 * tx.shape[0] * lambda_ * np.identity(tx.shape[1]) a = tx.T.dot(tx) + aI b = tx.T.dot(y) return np.linalg.solve(a, b) def ridge_regression_demo(x, y, degree, ratio, seed): ridge regression demo. # define parameter lambdas = np.logspace(-5, 0, 15) # split data x_tr, x_te, y_tr, y_te = split_data(x, y, ratio, seed) # form tx tx_tr = build_poly(x_tr, degree) tx_te = build_poly(x_te, degree) # ridge regression with different lambda rmse_tr = [] rmse_te = [] for ind, lambda_ in enumerate(lambdas): # ridge regression weight = ridge_regression(y_tr, tx_tr, lambda_) rmse_tr.append(np.sqrt(2 * compute_mse(y_tr, tx_tr, weight))) rmse_te.append(np.sqrt(2 * compute_mse(y_te, tx_te, weight))) print("proportion={p}, degree={d}, lambda={l:.3f}, Training RMSE={tr:.3f}, Testing RMSE={te:.3f}".format( p=ratio, d=degree, l=lambda_, tr=rmse_tr[ind], te=rmse_te[ind])) plot_train_test(rmse_tr, rmse_te, lambdas, degree) Explanation: Ridge Regression Please fill in the function below. End of explanation seed = 56 degree = 7 split_ratio = 0.5 ridge_regression_demo(x, y, degree, split_ratio, seed) Explanation: Demo time End of explanation
5,367
Given the following text description, write Python code to implement the functionality described below step by step Description: LeNet Lab Solution Source Step1: Basic Info of the Dataset Step2: Visualize Data View a sample from the dataset. You do not need to modify this section. Step3: Preprocess Data Shuffle the training data. You do not need to modify this section. Step4: Setup TensorFlow The EPOCH and BATCH_SIZE values affect the training speed and model accuracy. You do not need to modify this section. Step5: SOLUTION Step6: Features and Labels Train LeNet to classify MNIST data. x is a placeholder for a batch of input images. y is a placeholder for a batch of output labels. You do not need to modify this section. Step7: Training Pipeline Create a training pipeline that uses the model to classify MNIST data. You do not need to modify this section. Step8: Model Evaluation Evaluate how well the loss and accuracy of the model for a given dataset. You do not need to modify this section. Step9: Train the Model Run the training data through the training pipeline to train the model. Before each epoch, shuffle the training set. After each epoch, measure the loss and accuracy of the validation set. Save the model after training. You do not need to modify this section. Step10: Evaluate the Model Once you are completely satisfied with your model, evaluate the performance of the model on the test set. Be sure to only do this once! If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data. You do not need to modify this section.
Python Code: # Load pickled data import pickle # TODO: Fill this in based on where you saved the training and testing data training_file = 'train.p' validation_file= 'valid.p' testing_file = 'test.p' with open(training_file, mode='rb') as f: train = pickle.load(f) with open(validation_file, mode='rb') as f: valid = pickle.load(f) with open(testing_file, mode='rb') as f: test = pickle.load(f) X_train, y_train = train['features'], train['labels'] X_validation, y_validation = valid['features'], valid['labels'] X_test, y_test = test['features'], test['labels'] Explanation: LeNet Lab Solution Source: Yan LeCun Load Data Load the Traffic Signal data, which comes pre-loaded with TensorFlow. You do not need to modify this section. End of explanation ### Replace each question mark with the appropriate value. ### Use python, pandas or numpy methods rather than hard coding the results import numpy as np import random # TODO: Number of training examples n_train = len(X_train) # TODO: Number of testing examples. n_test = len(X_test) # TODO: What's the shape of an traffic sign image? index = random.randint(0, len(X_train)) image = X_train[index].squeeze() image_shape = np.shape(image) # TODO: How many unique classes/labels there are in the dataset. n_classes = len(y_train) + len(y_test) print("Number of training examples =", n_train) print("Number of testing examples =", n_test) print("Image data shape =", image_shape) print("Number of classes =", n_classes) Explanation: Basic Info of the Dataset End of explanation import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline index = random.randint(0, len(X_train)) image = X_train[index].squeeze() plt.figure(figsize=(1,1)) plt.imshow(image) print(y_train[index]) Explanation: Visualize Data View a sample from the dataset. You do not need to modify this section. End of explanation from sklearn.utils import shuffle X_train, y_train = shuffle(X_train, y_train) Explanation: Preprocess Data Shuffle the training data. You do not need to modify this section. End of explanation import tensorflow as tf EPOCHS = 10 BATCH_SIZE = 128 Explanation: Setup TensorFlow The EPOCH and BATCH_SIZE values affect the training speed and model accuracy. You do not need to modify this section. End of explanation from tensorflow.contrib.layers import flatten def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6. conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 3, 6), mean = mu, stddev = sigma)) conv1_b = tf.Variable(tf.zeros(6)) conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b # SOLUTION: Activation. conv1 = tf.nn.relu(conv1) # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6. conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # SOLUTION: Layer 2: Convolutional. Output = 10x10x16. conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 6, 16), mean = mu, stddev = sigma)) conv2_b = tf.Variable(tf.zeros(16)) conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b # SOLUTION: Activation. conv2 = tf.nn.relu(conv2) # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16. conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID') # SOLUTION: Flatten. Input = 5x5x16. Output = 400. fc0 = flatten(conv2) # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120. fc1_W = tf.Variable(tf.truncated_normal(shape=(400, 120), mean = mu, stddev = sigma)) fc1_b = tf.Variable(tf.zeros(120)) fc1 = tf.matmul(fc0, fc1_W) + fc1_b # SOLUTION: Activation. fc1 = tf.nn.relu(fc1) # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84. fc2_W = tf.Variable(tf.truncated_normal(shape=(120, 84), mean = mu, stddev = sigma)) fc2_b = tf.Variable(tf.zeros(84)) fc2 = tf.matmul(fc1, fc2_W) + fc2_b # SOLUTION: Activation. fc2 = tf.nn.relu(fc2) # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43. fc3_W = tf.Variable(tf.truncated_normal(shape=(84, 43), mean = mu, stddev = sigma)) fc3_b = tf.Variable(tf.zeros(43)) logits = tf.matmul(fc2, fc3_W) + fc3_b return logits Explanation: SOLUTION: Implement LeNet-5 Implement the LeNet-5 neural network architecture. This is the only cell you need to edit. Input The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. Architecture Layer 1: Convolutional. The output shape should be 28x28x6. Activation. Your choice of activation function. Pooling. The output shape should be 14x14x6. Layer 2: Convolutional. The output shape should be 10x10x16. Activation. Your choice of activation function. Pooling. The output shape should be 5x5x16. Flatten. Flatten the output shape of the final pooling layer such that it's 1D instead of 3D. The easiest way to do is by using tf.contrib.layers.flatten, which is already imported for you. Layer 3: Fully Connected. This should have 120 outputs. Activation. Your choice of activation function. Layer 4: Fully Connected. This should have 84 outputs. Activation. Your choice of activation function. Layer 5: Fully Connected (Logits). This should have 10 outputs. Output Return the result of the 2nd fully connected layer. End of explanation x = tf.placeholder(tf.float32, (None, 32, 32, 3)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, 43) Explanation: Features and Labels Train LeNet to classify MNIST data. x is a placeholder for a batch of input images. y is a placeholder for a batch of output labels. You do not need to modify this section. End of explanation rate = 0.001 logits = LeNet(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss_operation) Explanation: Training Pipeline Create a training pipeline that uses the model to classify MNIST data. You do not need to modify this section. End of explanation correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in range(0, num_examples, BATCH_SIZE): batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE] accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y}) total_accuracy += (accuracy * len(batch_x)) return total_accuracy / num_examples Explanation: Model Evaluation Evaluate how well the loss and accuracy of the model for a given dataset. You do not need to modify this section. End of explanation with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH_SIZE batch_x, batch_y = X_train[offset:end], y_train[offset:end] sess.run(training_operation, feed_dict={x: batch_x, y: batch_y}) validation_accuracy = evaluate(X_validation, y_validation) print("EPOCH {} ...".format(i+1)) print("Validation Accuracy = {:.3f}".format(validation_accuracy)) print() saver.save(sess, './lenet') print("Model saved") Explanation: Train the Model Run the training data through the training pipeline to train the model. Before each epoch, shuffle the training set. After each epoch, measure the loss and accuracy of the validation set. Save the model after training. You do not need to modify this section. End of explanation with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_test, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy)) Explanation: Evaluate the Model Once you are completely satisfied with your model, evaluate the performance of the model on the test set. Be sure to only do this once! If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set again, that would invalidate your test results. You wouldn't get a true measure of how well your model would perform against real data. You do not need to modify this section. End of explanation
5,368
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the exercise, you will work with data from the TalkingData AdTracking competition. The goal of the competition is to predict if a user will download an app after clicking through an ad. <center><a href="https Step1: Baseline Model The first thing you'll do is construct a baseline model. We'll begin by looking at the data. Step2: 1) Construct features from timestamps Notice that the click_data DataFrame has a 'click_time' column with timestamp data. Use this column to create features for the coresponding day, hour, minute and second. Store these as new integer columns day, hour, minute, and second in a new DataFrame clicks. Step3: 2) Label Encoding For each of the categorical features ['ip', 'app', 'device', 'os', 'channel'], use scikit-learn's LabelEncoder to create new features in the clicks DataFrame. The new column names should be the original column name with '_labels' appended, like ip_labels. Step4: Run the next code cell to view your new DataFrame. Step5: 3) One-hot Encoding In the code cell above, you used label encoded features. Would it have also made sense to instead use one-hot encoding for the categorical variables 'ip', 'app', 'device', 'os', or 'channel'? Note Step6: Train, validation, and test sets With our baseline features ready, we need to split our data into training and validation sets. We should also hold out a test set to measure the final accuracy of the model. 4) Train/test splits with time series data This is time series data. Are there any special considerations when creating train/test splits for time series? If so, what are they? Uncomment the following line after you've decided your answer. Step7: Create train/validation/test splits Here we'll create training, validation, and test splits. First, clicks DataFrame is sorted in order of increasing time. The first 80% of the rows are the train set, the next 10% are the validation set, and the last 10% are the test set. Step8: Train with LightGBM Now we can create LightGBM dataset objects for each of the smaller datasets and train the baseline model. Step9: Evaluate the model Finally, with the model trained, we evaluate its performance on the test set.
Python Code: # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.feature_engineering.ex1 import * Explanation: Introduction In the exercise, you will work with data from the TalkingData AdTracking competition. The goal of the competition is to predict if a user will download an app after clicking through an ad. <center><a href="https://www.kaggle.com/c/talkingdata-adtracking-fraud-detection"><img src="https://i.imgur.com/srKxEkD.png" width=600px></a></center> For this course you will use a small sample of the data, dropping 99% of negative records (where the app wasn't downloaded) to make the target more balanced. After building a baseline model, you'll be able to see how your feature engineering and selection efforts improve the model's performance. Setup Begin by running the code cell below to set up the exercise. End of explanation import pandas as pd click_data = pd.read_csv('../input/feature-engineering-data/train_sample.csv', parse_dates=['click_time']) click_data.head() Explanation: Baseline Model The first thing you'll do is construct a baseline model. We'll begin by looking at the data. End of explanation # Add new columns for timestamp features day, hour, minute, and second clicks = click_data.copy() clicks['day'] = clicks['click_time'].dt.day.astype('uint8') # Fill in the rest clicks['hour'] = ____ clicks['minute'] = ____ clicks['second'] = ____ # Check your answer q_1.check() # Uncomment these if you need guidance q_1.hint() q_1.solution() #%%RM_IF(PROD)%% # My solution, there are a lot of ways to do this clicks = click_data.copy() # Split up the times click_times = click_data['click_time'] clicks['day'] = click_times.dt.day.astype('uint8') # Fill in the rest clicks['hour'] = click_times.dt.hour.astype('uint8') clicks['minute'] = click_times.dt.minute.astype('uint8') clicks['second'] = click_times.dt.second.astype('uint8') q_1.assert_check_passed() Explanation: 1) Construct features from timestamps Notice that the click_data DataFrame has a 'click_time' column with timestamp data. Use this column to create features for the coresponding day, hour, minute and second. Store these as new integer columns day, hour, minute, and second in a new DataFrame clicks. End of explanation from sklearn import preprocessing cat_features = ['ip', 'app', 'device', 'os', 'channel'] # Create new columns in clicks using preprocessing.LabelEncoder() for feature in cat_features: ____ # Check your answer q_2.check() # Uncomment these if you need guidance # q_2.hint() # q_2.solution() #%%RM_IF(PROD)%% from sklearn import preprocessing # Label encode categorical variables cat_features = ['ip', 'app', 'device', 'os', 'channel'] label_encoder = preprocessing.LabelEncoder() for feature in cat_features: new_feature = label_encoder.fit_transform(clicks[feature]) clicks[feature +'_labels'] = new_feature q_2.assert_check_passed() #%%RM_IF(PROD)%% clicks.drop(['ip', 'app', 'device', 'os', 'channel'], axis=1, inplace=True) q_2.assert_check_passed() Explanation: 2) Label Encoding For each of the categorical features ['ip', 'app', 'device', 'os', 'channel'], use scikit-learn's LabelEncoder to create new features in the clicks DataFrame. The new column names should be the original column name with '_labels' appended, like ip_labels. End of explanation clicks.head() Explanation: Run the next code cell to view your new DataFrame. End of explanation # Check your answer (Run this code cell to receive credit!) q_3.solution() Explanation: 3) One-hot Encoding In the code cell above, you used label encoded features. Would it have also made sense to instead use one-hot encoding for the categorical variables 'ip', 'app', 'device', 'os', or 'channel'? Note: If you're not familiar with one-hot encoding, please check out this lesson from the Intermediate Machine Learning course. Run the following line after you've decided your answer. End of explanation # Check your answer (Run this code cell to receive credit!) q_4.solution() Explanation: Train, validation, and test sets With our baseline features ready, we need to split our data into training and validation sets. We should also hold out a test set to measure the final accuracy of the model. 4) Train/test splits with time series data This is time series data. Are there any special considerations when creating train/test splits for time series? If so, what are they? Uncomment the following line after you've decided your answer. End of explanation feature_cols = ['day', 'hour', 'minute', 'second', 'ip_labels', 'app_labels', 'device_labels', 'os_labels', 'channel_labels'] valid_fraction = 0.1 clicks_srt = clicks.sort_values('click_time') valid_rows = int(len(clicks_srt) * valid_fraction) train = clicks_srt[:-valid_rows * 2] # valid size == test size, last two sections of the data valid = clicks_srt[-valid_rows * 2:-valid_rows] test = clicks_srt[-valid_rows:] Explanation: Create train/validation/test splits Here we'll create training, validation, and test splits. First, clicks DataFrame is sorted in order of increasing time. The first 80% of the rows are the train set, the next 10% are the validation set, and the last 10% are the test set. End of explanation import lightgbm as lgb dtrain = lgb.Dataset(train[feature_cols], label=train['is_attributed']) dvalid = lgb.Dataset(valid[feature_cols], label=valid['is_attributed']) dtest = lgb.Dataset(test[feature_cols], label=test['is_attributed']) param = {'num_leaves': 64, 'objective': 'binary'} param['metric'] = 'auc' num_round = 1000 bst = lgb.train(param, dtrain, num_round, valid_sets=[dvalid], early_stopping_rounds=10) Explanation: Train with LightGBM Now we can create LightGBM dataset objects for each of the smaller datasets and train the baseline model. End of explanation from sklearn import metrics ypred = bst.predict(test[feature_cols]) score = metrics.roc_auc_score(test['is_attributed'], ypred) print(f"Test score: {score}") Explanation: Evaluate the model Finally, with the model trained, we evaluate its performance on the test set. End of explanation
5,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Vertex pipelines Learning Objectives Step1: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import libraries and define constants Step2: Check the versions of the packages you installed. The KFP SDK version should be >=1.6. Step3: Set your environment variables Next, we'll set up our project variables, like GCP project ID, the bucket and region. Also, to avoid name collisions between resources created, we'll create a timestamp and append it onto the name of resources we create in this lab. Step4: We'll save pipeline artifacts in a directory called pipeline_root within our bucket. Validate access to your Cloud Storage bucket by examining its contents. It should be empty at this stage. Step5: Give your default service account storage bucket access This pipeline will read .csv files from Cloud storage for training and will write model checkpoints and artifacts to a specified bucket. So, we need to give our default service account storage.objectAdmin access. You can do this by running the command below in Cloud Shell Step6: Now, you define the pipeline. The experimental.run_as_aiplatform_custom_job method takes as args the component defined above, and the list of worker_pool_specs— in this case one— with which the custom training job is configured. See full function code here Then, google_cloud_pipeline_components components are used to define the rest of the pipeline Step7: Compile and run the pipeline Now, you're ready to compile the pipeline Step8: The pipeline compilation generates the train_upload_endpoint_deploy.json job spec file. Next, instantiate the pipeline job object Step9: Then, you run the defined pipeline like this
Python Code: !pip3 install --user google-cloud-pipeline-components==0.1.1 --upgrade Explanation: Vertex pipelines Learning Objectives: Use components from google_cloud_pipeline_components to create a Vertex Pipeline which will 1. train a custom model on Vertex AI 1. create an endpoint to host the model 1. upload the trained model, and 1. deploy the uploaded model to the endpoint for serving Overview This notebook shows how to use the components defined in google_cloud_pipeline_components in conjunction with an experimental run_as_aiplatform_custom_job method, to build a Vertex Pipelines workflow that trains a custom model, uploads the model, creates an endpoint, and deploys the model to the endpoint. We'll use the kfp.v2.google.experimental.run_as_aiplatform_custom_job method to train a custom model. The google cloud pipeline components are documented here. From this github page you can also find other examples in how to build a Vertex pipeline with AutoML here. You can see other available methods from the Vertex AI SDK. Set up your local development environment and install necessary packages End of explanation import os from datetime import datetime import kfp from google.cloud import aiplatform from google_cloud_pipeline_components import aiplatform as gcc_aip from kfp.v2 import compiler from kfp.v2.dsl import component from kfp.v2.google import experimental Explanation: Restart the kernel After you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import libraries and define constants End of explanation print(f"KFP SDK version: {kfp.__version__}") Explanation: Check the versions of the packages you installed. The KFP SDK version should be >=1.6. End of explanation # Change below if necessary PROJECT = !gcloud config get-value project # noqa: E999 PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") PIPELINE_ROOT = f"gs://{BUCKET}/pipeline_root" print(PIPELINE_ROOT) Explanation: Set your environment variables Next, we'll set up our project variables, like GCP project ID, the bucket and region. Also, to avoid name collisions between resources created, we'll create a timestamp and append it onto the name of resources we create in this lab. End of explanation !gsutil ls -la gs://{BUCKET}/pipeline_root Explanation: We'll save pipeline artifacts in a directory called pipeline_root within our bucket. Validate access to your Cloud Storage bucket by examining its contents. It should be empty at this stage. End of explanation @component def training_op(input1: str): print(f"VertexAI pipeline: {input1}") Explanation: Give your default service account storage bucket access This pipeline will read .csv files from Cloud storage for training and will write model checkpoints and artifacts to a specified bucket. So, we need to give our default service account storage.objectAdmin access. You can do this by running the command below in Cloud Shell: bash PROJECT=$(gcloud config get-value project) PROJECT_NUMBER=$(gcloud projects list --filter="name=$PROJECT" --format="value(PROJECT_NUMBER)") gcloud projects add-iam-policy-binding $PROJECT \ --member="serviceAccount:$PROJECT_NUMBER-compute@developer.gserviceaccount.com" \ --role="roles/storage.objectAdmin" Note, it may take some time for the permissions to propogate to the service account. You can confirm the status from the IAM page here. Define a pipeline that uses the components We'll start by defining a component with which the custom training job is run. For this example, this component doesn't do anything (but run a print statement). End of explanation # Output directory and job_name OUTDIR = f"gs://{BUCKET}/taxifare/trained_model_{TIMESTAMP}" MODEL_DISPLAY_NAME = f"taxifare_{TIMESTAMP}" PYTHON_PACKAGE_URIS = f"gs://{BUCKET}/taxifare/taxifare_trainer-0.1.tar.gz" MACHINE_TYPE = "n1-standard-16" REPLICA_COUNT = 1 PYTHON_PACKAGE_EXECUTOR_IMAGE_URI = ( "us-docker.pkg.dev/vertex-ai/training/tf-cpu.2-3:latest" ) SERVING_CONTAINER_IMAGE_URI = ( "us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-3:latest" ) PYTHON_MODULE = "trainer.task" # Model and training hyperparameters BATCH_SIZE = 500 NUM_EXAMPLES_TO_TRAIN_ON = 10000 NUM_EVALS = 1000 NBUCKETS = 10 LR = 0.001 NNSIZE = "32 8" # GCS paths GCS_PROJECT_PATH = f"gs://{BUCKET}/taxifare" DATA_PATH = f"{GCS_PROJECT_PATH}/data" TRAIN_DATA_PATH = f"{DATA_PATH}/taxi-train*" EVAL_DATA_PATH = f"{DATA_PATH}/taxi-valid*" @kfp.dsl.pipeline(name="taxifare--train-upload-endpoint-deploy") def pipeline( project: str = PROJECT, model_display_name: str = MODEL_DISPLAY_NAME, ): train_task = training_op("taxifare training pipeline") experimental.run_as_aiplatform_custom_job( train_task, display_name=f"pipelines-train-{TIMESTAMP}", worker_pool_specs=[ { "pythonPackageSpec": { "executor_image_uri": PYTHON_PACKAGE_EXECUTOR_IMAGE_URI, "package_uris": [PYTHON_PACKAGE_URIS], "python_module": PYTHON_MODULE, "args": [ f"--eval_data_path={EVAL_DATA_PATH}", f"--output_dir={OUTDIR}", f"--train_data_path={TRAIN_DATA_PATH}", f"--batch_size={BATCH_SIZE}", f"--num_examples_to_train_on={NUM_EXAMPLES_TO_TRAIN_ON}", # noqa: E501 f"--num_evals={NUM_EVALS}", f"--nbuckets={NBUCKETS}", f"--lr={LR}", f"--nnsize={NNSIZE}", ], }, "replica_count": f"{REPLICA_COUNT}", "machineSpec": { "machineType": f"{MACHINE_TYPE}", }, } ], ) model_upload_op = gcc_aip.ModelUploadOp( project=f"{PROJECT}", display_name=f"pipelines-ModelUpload-{TIMESTAMP}", artifact_uri=f"{OUTDIR}/savedmodel", serving_container_image_uri=f"{SERVING_CONTAINER_IMAGE_URI}", serving_container_environment_variables={"NOT_USED": "NO_VALUE"}, ) model_upload_op.after(train_task) endpoint_create_op = gcc_aip.EndpointCreateOp( project=f"{PROJECT}", display_name=f"pipelines-EndpointCreate-{TIMESTAMP}", ) model_deploy_op = gcc_aip.ModelDeployOp( project=f"{PROJECT}", endpoint=endpoint_create_op.outputs["endpoint"], model=model_upload_op.outputs["model"], deployed_model_display_name=f"{MODEL_DISPLAY_NAME}", machine_type=f"{MACHINE_TYPE}", ) Explanation: Now, you define the pipeline. The experimental.run_as_aiplatform_custom_job method takes as args the component defined above, and the list of worker_pool_specs— in this case one— with which the custom training job is configured. See full function code here Then, google_cloud_pipeline_components components are used to define the rest of the pipeline: upload the model, create an endpoint, and deploy the model to the endpoint. (While not shown in this example, the model deploy will create an endpoint if one is not provided). Note that the code we're using the exact same code that we developed in the previous lab 1_training_at_scale_vertex.ipynb. In fact, we are pulling the same python package executor image URI that we pushed to Cloud storage in that lab. Note that we also include the SERVING_CONTAINER_IMAGE_URI since we'll need to specify that when uploading and deploying our model. End of explanation if not os.path.isdir("vertex_pipelines"): os.mkdir("vertex_pipelines") compiler.Compiler().compile( pipeline_func=pipeline, package_path="./vertex_pipelines/train_upload_endpoint_deploy.json", ) Explanation: Compile and run the pipeline Now, you're ready to compile the pipeline: End of explanation pipeline_job = aiplatform.pipeline_jobs.PipelineJob( display_name="taxifare_pipeline", template_path="./vertex_pipelines/train_upload_endpoint_deploy.json", pipeline_root=f"{PIPELINE_ROOT}", project=PROJECT, location=REGION, ) Explanation: The pipeline compilation generates the train_upload_endpoint_deploy.json job spec file. Next, instantiate the pipeline job object: End of explanation pipeline_job.run() Explanation: Then, you run the defined pipeline like this: End of explanation
5,370
Given the following text description, write Python code to implement the functionality described below step by step Description: DAY 11 - Mar 7, 2017 Today I'll do something a little different. This morning I tweeted something along the lines of "will be working with matplotlib." In terms of visualization, I'm more familiar with R and ggplot2 and so this is a perfect opportunity to explore matplotlib. But first I need data. Acquiring the data What data to choose? At the time, my younger brother had League of Legends on his computer screen. Inspiration. I'll use League of Legend data. Plotting game data is always fun. My brother said use the League of Legends Step1: We now have data to plot. Matplotlib According to the cheatsheet that Kirk Borne tweeted out this morning. The components are Step2: 2. Create Plot
Python Code: website_base_stats = "http://leagueoflegends.wikia.com/wiki/Base_champion_statistics" # Save HTML to soup html_data = requests.get(website_base_stats).text soup = BeautifulSoup(html_data, "html5lib") # Parse table table = soup.find('table', attrs={'class' : 'wikitable'}) # Parse table header lol_thead = [h.text.strip() for h in soup.find_all("th")] # Parse table body table_body = table.tbody data = [] rows = table_body.find_all('tr') for row in rows: cols = row.find_all('td') if len(cols) == 0: continue cols[0] = cols[0].span cols = [c.text.strip() for c in cols] data.append(cols) lol_table = pd.DataFrame(data, columns=lol_thead) # Print print(lol_table.shape) lol_table.head() # Parse href link info to url with more info lol_links = table.tbody.find_all("a", href=True, class_=False) link_data = [] for l in lol_links: link_data.append(l.attrs) link_data = pd.DataFrame(link_data) link_data = link_data.rename(columns={"title": "Champions"}) # Use full link link_data.href = "http://leagueoflegends.wikia.com" + link_data.href link_data.tail() # Join tables lol_table = pd.merge(lol_table, link_data, on="Champions", how="left") print(lol_table.shape) lol_table.head() Explanation: DAY 11 - Mar 7, 2017 Today I'll do something a little different. This morning I tweeted something along the lines of "will be working with matplotlib." In terms of visualization, I'm more familiar with R and ggplot2 and so this is a perfect opportunity to explore matplotlib. But first I need data. Acquiring the data What data to choose? At the time, my younger brother had League of Legends on his computer screen. Inspiration. I'll use League of Legend data. Plotting game data is always fun. My brother said use the League of Legends: Base champion statistics website. End of explanation # Fix problematic data print(lol_table[lol_table["Champions"]=="Kled"]) # by replacing with None type lol_table.iloc[56, 7:9] = None lol_table[lol_table["Champions"]=="Kled"] # Convert data types to float columns_to_float = list(lol_table.columns[1:12])+ list(lol_table.columns[13:-1]) lol_table[columns_to_float] = lol_table[columns_to_float].astype(float) lol_table # Convert AS+ data types lol_table[lol_table.columns[12]] = lol_table[lol_table.columns[12]].map(lambda x: float(x.strip("%"))/100) lol_table.to_csv("lol_base_stats.tsv", index=False, sep="\t") Explanation: We now have data to plot. Matplotlib According to the cheatsheet that Kirk Borne tweeted out this morning. The components are: 1. Prepare the data End of explanation import matplotlib.pyplot as plt %matplotlib inline plt.rcParams["figure.figsize"] = [15,6] # 2. Create plot fig = plt.figure() ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) ax4 = fig.add_subplot(224) # Add title so know which plot is which ax1.title.set_text('Plot 1') ax2.title.set_text('Plot 2') ax3.title.set_text('Plot 3') ax4.title.set_text('Plot 4') # 3. Plotting routines # Add the data (same data to all plots) ax1.scatter(x=lol_table.HP, y=lol_table.Range) ax2.scatter(x=lol_table.HP, y=lol_table.Range) ax3.scatter(x=lol_table.HP, y=lol_table.Range) ax4.scatter(x=lol_table.HP, y=lol_table.Range, marker="+", color="red") # 4. Customize plots ax2.spines['top'].set_visible(False) ax2.spines['right'].set_visible(False) ax2.set(xlabel = "HP", ylabel = "Ranage") for vline in range(300, 700, 100): ax3.axvline(vline, color="grey", linestyle="dashed", linewidth=0.5) ax3.xaxis.set( ticks=range(300, 700, 100), ticklabels=["HP:{}".format(x) for x in range(300, 700, 50)] ) ax4.set( xlim=[450, 650], ylim=[400, 700] ) ax4.text(600, 550, "Zoom!", style='italic', fontsize="x-large") # 5. Save figures # plt.savefig('foo.png') # plt.savefig('foo.png', transparent=True) plt.tight_layout() Explanation: 2. Create Plot End of explanation
5,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Matrix Factorization In a recommendation system, there is a group of users and a set of items. Given that each users have rated some items in the system, we would like to predict how the users would rate the items that they have not yet rated, such that we can make recommendations to the users. Matrix factorization is one of the mainly used algorithm in recommendation systems. It can be used to discover latent features underlying the interactions between two different kinds of entities. Assume we assign a k-dimensional vector to each user and a k-dimensional vector to each item such that the dot product of these two vectors gives the user's rating of that item. We can learn the user and item vectors directly, which is essentially performing SVD on the user-item matrix. We can also try to learn the latent features using multi-layer neural networks. In this tutorial, we will work though the steps to implement these ideas in MXNet. Prepare Data We use the MovieLens data here, but it can apply to other datasets as well. Each row of this dataset contains a tuple of user id, movie id, rating, and time stamp, we will only use the first three items. We first define the a batch which contains n tuples. It also provides name and shape information to MXNet about the data and label. Step1: Then we define a data iterator, which returns a batch of tuples each time. Step2: Now we download the data and provide a function to obtain the data iterator Step3: Finally we calculate the numbers of users and items for later use. Step4: Optimization We first implement the RMSE (root-mean-square error) measurement, which is commonly used by matrix factorization. Step5: Then we define a general training module, which is borrowed from the image classification application. Step6: Networks Now we try various networks. We first learn the latent vectors directly. Step7: Next we try to use 2 layers neural network to learn the latent variables, which stack a fully connected layer above the embedding layers Step8: Adding dropout layers to relief the over-fitting.
Python Code: class Batch(object): def __init__(self, data_names, data, label_names, label): self.data = data self.label = label self.data_names = data_names self.label_names = label_names @property def provide_data(self): return [(n, x.shape) for n, x in zip(self.data_names, self.data)] @property def provide_label(self): return [(n, x.shape) for n, x in zip(self.label_names, self.label)] Explanation: Matrix Factorization In a recommendation system, there is a group of users and a set of items. Given that each users have rated some items in the system, we would like to predict how the users would rate the items that they have not yet rated, such that we can make recommendations to the users. Matrix factorization is one of the mainly used algorithm in recommendation systems. It can be used to discover latent features underlying the interactions between two different kinds of entities. Assume we assign a k-dimensional vector to each user and a k-dimensional vector to each item such that the dot product of these two vectors gives the user's rating of that item. We can learn the user and item vectors directly, which is essentially performing SVD on the user-item matrix. We can also try to learn the latent features using multi-layer neural networks. In this tutorial, we will work though the steps to implement these ideas in MXNet. Prepare Data We use the MovieLens data here, but it can apply to other datasets as well. Each row of this dataset contains a tuple of user id, movie id, rating, and time stamp, we will only use the first three items. We first define the a batch which contains n tuples. It also provides name and shape information to MXNet about the data and label. End of explanation import mxnet as mx import random class Batch(object): def __init__(self, data_names, data, label_names, label): self.data = data self.label = label self.data_names = data_names self.label_names = label_names @property def provide_data(self): return [(n, x.shape) for n, x in zip(self.data_names, self.data)] @property def provide_label(self): return [(n, x.shape) for n, x in zip(self.label_names, self.label)] class DataIter(mx.io.DataIter): def __init__(self, fname, batch_size): super(DataIter, self).__init__() self.batch_size = batch_size self.data = [] for line in file(fname): tks = line.strip().split('\t') if len(tks) != 4: continue self.data.append((int(tks[0]), int(tks[1]), float(tks[2]))) self.provide_data = [('user', (batch_size, )), ('item', (batch_size, ))] self.provide_label = [('score', (self.batch_size, ))] def __iter__(self): for k in range(len(self.data) / self.batch_size): users = [] items = [] scores = [] for i in range(self.batch_size): j = k * self.batch_size + i user, item, score = self.data[j] users.append(user) items.append(item) scores.append(score) data_all = [mx.nd.array(users), mx.nd.array(items)] label_all = [mx.nd.array(scores)] data_names = ['user', 'item'] label_names = ['score'] data_batch = Batch(data_names, data_all, label_names, label_all) yield data_batch def reset(self): random.shuffle(self.data) Explanation: Then we define a data iterator, which returns a batch of tuples each time. End of explanation import os import urllib import zipfile if not os.path.exists('ml-100k.zip'): urllib.urlretrieve('http://files.grouplens.org/datasets/movielens/ml-100k.zip', 'ml-100k.zip') with zipfile.ZipFile("ml-100k.zip","r") as f: f.extractall("./") def get_data(batch_size): return (DataIter('./ml-100k/u1.base', batch_size), DataIter('./ml-100k/u1.test', batch_size)) Explanation: Now we download the data and provide a function to obtain the data iterator: End of explanation def max_id(fname): mu = 0 mi = 0 for line in file(fname): tks = line.strip().split('\t') if len(tks) != 4: continue mu = max(mu, int(tks[0])) mi = max(mi, int(tks[1])) return mu + 1, mi + 1 max_user, max_item = max_id('./ml-100k/u.data') (max_user, max_item) Explanation: Finally we calculate the numbers of users and items for later use. End of explanation import math def RMSE(label, pred): ret = 0.0 n = 0.0 pred = pred.flatten() for i in range(len(label)): ret += (label[i] - pred[i]) * (label[i] - pred[i]) n += 1.0 return math.sqrt(ret / n) Explanation: Optimization We first implement the RMSE (root-mean-square error) measurement, which is commonly used by matrix factorization. End of explanation def train(network, batch_size, num_epoch, learning_rate): batch_size = batch_size train, test = get_data(batch_size) model = mx.mod.Module(symbol = network, data_names=[x[0] for x in train.provide_data], label_names=[y[0] for y in train.provide_label], context=[mx.gpu(0)]) import logging head = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.DEBUG) model.fit(train_data = train, eval_data = test, num_epoch=num_epoch, optimizer='sgd', optimizer_params={'learning_rate':learning_rate, 'momentum':0.9, 'wd':0.0001}, eval_metric = RMSE, batch_end_callback=mx.callback.Speedometer(batch_size, 20000/batch_size),) Explanation: Then we define a general training module, which is borrowed from the image classification application. End of explanation # @@@ AUTOTEST_OUTPUT_IGNORED_CELL def plain_net(k): # input user = mx.symbol.Variable('user') item = mx.symbol.Variable('item') score = mx.symbol.Variable('score') # user feature lookup user = mx.symbol.Embedding(data = user, input_dim = max_user, output_dim = k) # item feature lookup item = mx.symbol.Embedding(data = item, input_dim = max_item, output_dim = k) # predict by the inner product, which is elementwise product and then sum pred = user * item pred = mx.symbol.sum_axis(data = pred, axis = 1) pred = mx.symbol.Flatten(data = pred) # loss layer pred = mx.symbol.LinearRegressionOutput(data = pred, label = score) return pred train(plain_net(64), batch_size=64, num_epoch=10, learning_rate=.05) Explanation: Networks Now we try various networks. We first learn the latent vectors directly. End of explanation # @@@ AUTOTEST_OUTPUT_IGNORED_CELL def get_one_layer_mlp(hidden, k): # input user = mx.symbol.Variable('user') item = mx.symbol.Variable('item') score = mx.symbol.Variable('score') # user latent features user = mx.symbol.Embedding(data = user, input_dim = max_user, output_dim = k) user = mx.symbol.Activation(data = user, act_type="relu") user = mx.symbol.FullyConnected(data = user, num_hidden = hidden) # item latent features item = mx.symbol.Embedding(data = item, input_dim = max_item, output_dim = k) item = mx.symbol.Activation(data = item, act_type="relu") item = mx.symbol.FullyConnected(data = item, num_hidden = hidden) # predict by the inner product pred = user * item pred = mx.symbol.sum_axis(data = pred, axis = 1) pred = mx.symbol.Flatten(data = pred) # loss layer pred = mx.symbol.LinearRegressionOutput(data = pred, label = score) return pred train(get_one_layer_mlp(64, 64), batch_size=64, num_epoch=10, learning_rate=.05) Explanation: Next we try to use 2 layers neural network to learn the latent variables, which stack a fully connected layer above the embedding layers: End of explanation # @@@ AUTOTEST_OUTPUT_IGNORED_CELL def get_one_layer_dropout_mlp(hidden, k): # input user = mx.symbol.Variable('user') item = mx.symbol.Variable('item') score = mx.symbol.Variable('score') # user latent features user = mx.symbol.Embedding(data = user, input_dim = max_user, output_dim = k) user = mx.symbol.Activation(data = user, act_type="relu") user = mx.symbol.FullyConnected(data = user, num_hidden = hidden) user = mx.symbol.Dropout(data=user, p=0.5) # item latent features item = mx.symbol.Embedding(data = item, input_dim = max_item, output_dim = k) item = mx.symbol.Activation(data = item, act_type="relu") item = mx.symbol.FullyConnected(data = item, num_hidden = hidden) item = mx.symbol.Dropout(data=item, p=0.5) # predict by the inner product pred = user * item pred = mx.symbol.sum_axis(data = pred, axis = 1) pred = mx.symbol.Flatten(data = pred) # loss layer pred = mx.symbol.LinearRegressionOutput(data = pred, label = score) return pred train(get_one_layer_mlp(256, 512), batch_size=64, num_epoch=10, learning_rate=.05) Explanation: Adding dropout layers to relief the over-fitting. End of explanation
5,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Making New Layers and Models via Subclassing Learning Objectives Use Layer class as the combination of state (weights) and computation. Defer weight creation until the shape of the inputs is known. Build recursively composable layers. Compute loss using add_loss() method. Compute average using add_metric() method. Enable serialization on layers. Introduction This tutorial shows how to build new layers and models via subclassing. Subclassing is a term that refers inheriting properties for a new object from a base or superclass object. Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook. Setup Step1: The Layer class Step2: You would use a layer by calling it on some tensor input(s), much like a Python function. Step3: Note that the weights w and b are automatically tracked by the layer upon being set as layer attributes Step4: Note you also have access to a quicker shortcut for adding weight to a layer Step5: Layers can have non-trainable weights Besides trainable weights, you can add non-trainable weights to a layer as well. Such weights are meant not to be taken into account during backpropagation, when you are training the layer. Here's how to add and use a non-trainable weight Step6: It's part of layer.weights, but it gets categorized as a non-trainable weight Step7: Best practice Step8: In many cases, you may not know in advance the size of your inputs, and you would like to lazily create weights when that value becomes known, some time after instantiating the layer. In the Keras API, we recommend creating layer weights in the build(self, input_shape) method of your layer. Like this Step9: The __call__() method of your layer will automatically run build the first time it is called. You now have a layer that's lazy and thus easier to use Step10: Layers are recursively composable If you assign a Layer instance as an attribute of another Layer, the outer layer will start tracking the weights of the inner layer. We recommend creating such sublayers in the __init__() method (since the sublayers will typically have a build method, they will be built when the outer layer gets built). Step11: The add_loss() method When writing the call() method of a layer, you can create loss tensors that you will want to use later, when writing your training loop. This is doable by calling self.add_loss(value) Step12: These losses (including those created by any inner layer) can be retrieved via layer.losses. This property is reset at the start of every __call__() to the top-level layer, so that layer.losses always contains the loss values created during the last forward pass. Step13: In addition, the loss property also contains regularization losses created for the weights of any inner layer Step14: These losses are meant to be taken into account when writing training loops, like this Step15: The add_metric() method Similarly to add_loss(), layers also have an add_metric() method for tracking the moving average of a quantity during training. Consider the following layer Step16: Metrics tracked in this way are accessible via layer.metrics Step17: Just like for add_loss(), these metrics are tracked by fit() Step18: You can optionally enable serialization on your layers If you need your custom layers to be serializable as part of a Functional model, you can optionally implement a get_config() method Step19: Note that the __init__() method of the base Layer class takes some keyword arguments, in particular a name and a dtype. It's good practice to pass these arguments to the parent class in __init__() and to include them in the layer config Step20: If you need more flexibility when deserializing the layer from its config, you can also override the from_config() class method. This is the base implementation of from_config() Step25: Privileged mask argument in the call() method The other privileged argument supported by call() is the mask argument. You will find it in all Keras RNN layers. A mask is a boolean tensor (one boolean value per timestep in the input) used to skip certain input timesteps when processing timeseries data. Keras will automatically pass the correct mask argument to __call__() for layers that support it, when a mask is generated by a prior layer. Mask-generating layers are the Embedding layer configured with mask_zero=True, and the Masking layer. To learn more about masking and how to write masking-enabled layers, please check out the guide "understanding padding and masking". The Model class In general, you will use the Layer class to define inner computation blocks, and will use the Model class to define the outer model -- the object you will train. For instance, in a ResNet50 model, you would have several ResNet blocks subclassing Layer, and a single Model encompassing the entire ResNet50 network. The Model class has the same API as Layer, with the following differences Step26: Let's write a simple training loop on MNIST Step27: Note that since the VAE is subclassing Model, it features built-in training loops. So you could also have trained it like this Step28: Beyond object-oriented development
Python Code: # Import necessary libraries import tensorflow as tf from tensorflow import keras Explanation: Making New Layers and Models via Subclassing Learning Objectives Use Layer class as the combination of state (weights) and computation. Defer weight creation until the shape of the inputs is known. Build recursively composable layers. Compute loss using add_loss() method. Compute average using add_metric() method. Enable serialization on layers. Introduction This tutorial shows how to build new layers and models via subclassing. Subclassing is a term that refers inheriting properties for a new object from a base or superclass object. Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook. Setup End of explanation # Define a Linear class class Linear(keras.layers.Layer): def __init__(self, units=32, input_dim=32): super(Linear, self).__init__() w_init = tf.random_normal_initializer() self.w = tf.Variable( initial_value=w_init(shape=(input_dim, units), dtype="float32"), trainable=True, ) b_init = tf.zeros_initializer() self.b = tf.Variable( initial_value=b_init(shape=(units,), dtype="float32"), trainable=True ) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b Explanation: The Layer class: the combination of state (weights) and some computation One of the central abstraction in Keras is the Layer class. A layer encapsulates both a state (the layer's "weights") and a transformation from inputs to outputs (a "call", the layer's forward pass). Here's a densely-connected layer. It has a state: the variables w and b. End of explanation x = tf.ones((2, 2)) linear_layer = Linear(4, 2) y = linear_layer(x) print(y) Explanation: You would use a layer by calling it on some tensor input(s), much like a Python function. End of explanation assert linear_layer.weights == [linear_layer.w, linear_layer.b] Explanation: Note that the weights w and b are automatically tracked by the layer upon being set as layer attributes: End of explanation # TODO # Use `add_weight()` method for adding weight to a layer class Linear(keras.layers.Layer): def __init__(self, units=32, input_dim=32): super(Linear, self).__init__() self.w = self.add_weight( shape=(input_dim, units), initializer="random_normal", trainable=True ) self.b = self.add_weight(shape=(units,), initializer="zeros", trainable=True) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b x = tf.ones((2, 2)) linear_layer = Linear(4, 2) y = # TODO: Your code goes here print(y) Explanation: Note you also have access to a quicker shortcut for adding weight to a layer: the add_weight() method: End of explanation # Add and use a non-trainable weight class ComputeSum(keras.layers.Layer): def __init__(self, input_dim): super(ComputeSum, self).__init__() self.total = tf.Variable(initial_value=tf.zeros((input_dim,)), trainable=False) def call(self, inputs): self.total.assign_add(tf.reduce_sum(inputs, axis=0)) return self.total x = tf.ones((2, 2)) my_sum = ComputeSum(2) y = my_sum(x) print(y.numpy()) y = my_sum(x) print(y.numpy()) Explanation: Layers can have non-trainable weights Besides trainable weights, you can add non-trainable weights to a layer as well. Such weights are meant not to be taken into account during backpropagation, when you are training the layer. Here's how to add and use a non-trainable weight: End of explanation print("weights:", len(my_sum.weights)) print("non-trainable weights:", len(my_sum.non_trainable_weights)) # It's not included in the trainable weights: print("trainable_weights:", my_sum.trainable_weights) Explanation: It's part of layer.weights, but it gets categorized as a non-trainable weight: End of explanation class Linear(keras.layers.Layer): def __init__(self, units=32, input_dim=32): super(Linear, self).__init__() self.w = self.add_weight( shape=(input_dim, units), initializer="random_normal", trainable=True ) self.b = self.add_weight(shape=(units,), initializer="zeros", trainable=True) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b Explanation: Best practice: deferring weight creation until the shape of the inputs is known Our Linear layer above took an input_dim argument that was used to compute the shape of the weights w and b in __init__(): End of explanation # TODO class Linear(keras.layers.Layer): def __init__(self, units=32): super(Linear, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight( shape=# TODO: Your code goes here, initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.units,), initializer="random_normal", trainable=True ) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b Explanation: In many cases, you may not know in advance the size of your inputs, and you would like to lazily create weights when that value becomes known, some time after instantiating the layer. In the Keras API, we recommend creating layer weights in the build(self, input_shape) method of your layer. Like this: End of explanation # At instantiation, we don't know on what inputs this is going to get called linear_layer = Linear(32) # The layer's weights are created dynamically the first time the layer is called y = linear_layer(x) Explanation: The __call__() method of your layer will automatically run build the first time it is called. You now have a layer that's lazy and thus easier to use: End of explanation # TODO # Let's assume we are reusing the Linear class # with a `build` method that we defined above. class MLPBlock(keras.layers.Layer): def __init__(self): super(MLPBlock, self).__init__() self.linear_1 = Linear(32) self.linear_2 = Linear(32) self.linear_3 = Linear(1) def call(self, inputs): x = self.linear_1(inputs) x = tf.nn.relu(x) x = self.linear_2(x) x = tf.nn.relu(x) return self.linear_3(x) mlp = # TODO: Your code goes here y = mlp(tf.ones(shape=(3, 64))) # The first call to the `mlp` will create the weights print("weights:", len(mlp.weights)) print("trainable weights:", len(mlp.trainable_weights)) Explanation: Layers are recursively composable If you assign a Layer instance as an attribute of another Layer, the outer layer will start tracking the weights of the inner layer. We recommend creating such sublayers in the __init__() method (since the sublayers will typically have a build method, they will be built when the outer layer gets built). End of explanation # A layer that creates an activity regularization loss class ActivityRegularizationLayer(keras.layers.Layer): def __init__(self, rate=1e-2): super(ActivityRegularizationLayer, self).__init__() self.rate = rate def call(self, inputs): self.add_loss(self.rate * tf.reduce_sum(inputs)) return inputs Explanation: The add_loss() method When writing the call() method of a layer, you can create loss tensors that you will want to use later, when writing your training loop. This is doable by calling self.add_loss(value): End of explanation # TODO class OuterLayer(keras.layers.Layer): def __init__(self): super(OuterLayer, self).__init__() self.activity_reg = # TODO: Your code goes here def call(self, inputs): return self.activity_reg(inputs) layer = OuterLayer() assert len(layer.losses) == 0 # No losses yet since the layer has never been called _ = layer(tf.zeros(1, 1)) assert len(layer.losses) == 1 # We created one loss value # `layer.losses` gets reset at the start of each __call__ _ = layer(tf.zeros(1, 1)) assert len(layer.losses) == 1 # This is the loss created during the call above Explanation: These losses (including those created by any inner layer) can be retrieved via layer.losses. This property is reset at the start of every __call__() to the top-level layer, so that layer.losses always contains the loss values created during the last forward pass. End of explanation class OuterLayerWithKernelRegularizer(keras.layers.Layer): def __init__(self): super(OuterLayerWithKernelRegularizer, self).__init__() self.dense = keras.layers.Dense( 32, kernel_regularizer=tf.keras.regularizers.l2(1e-3) ) def call(self, inputs): return self.dense(inputs) layer = OuterLayerWithKernelRegularizer() _ = layer(tf.zeros((1, 1))) # This is `1e-3 * sum(layer.dense.kernel ** 2)`, # created by the `kernel_regularizer` above. print(layer.losses) Explanation: In addition, the loss property also contains regularization losses created for the weights of any inner layer: End of explanation import numpy as np inputs = keras.Input(shape=(3,)) outputs = ActivityRegularizationLayer()(inputs) model = keras.Model(inputs, outputs) # If there is a loss passed in `compile`, the regularization # losses get added to it model.compile(optimizer="adam", loss="mse") model.fit(np.random.random((2, 3)), np.random.random((2, 3))) # It's also possible not to pass any loss in `compile`, # since the model already has a loss to minimize, via the `add_loss` # call during the forward pass! model.compile(optimizer="adam") model.fit(np.random.random((2, 3)), np.random.random((2, 3))) Explanation: These losses are meant to be taken into account when writing training loops, like this: ```python Instantiate an optimizer. optimizer = tf.keras.optimizers.SGD(learning_rate=1e-3) loss_fn = keras.losses.SparseCategoricalCrossentropy(from_logits=True) Iterate over the batches of a dataset. for x_batch_train, y_batch_train in train_dataset: with tf.GradientTape() as tape: logits = layer(x_batch_train) # Logits for this minibatch # Loss value for this minibatch loss_value = loss_fn(y_batch_train, logits) # Add extra losses created during this forward pass: loss_value += sum(model.losses) grads = tape.gradient(loss_value, model.trainable_weights) optimizer.apply_gradients(zip(grads, model.trainable_weights)) ``` For a detailed guide about writing training loops, see the guide to writing a training loop from scratch. These losses also work seamlessly with fit() (they get automatically summed and added to the main loss, if any): End of explanation # TODO class LogisticEndpoint(keras.layers.Layer): def __init__(self, name=None): super(LogisticEndpoint, self).__init__(name=name) self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True) self.accuracy_fn = keras.metrics.BinaryAccuracy() def call(self, targets, logits, sample_weights=None): # Compute the training-time loss value and add it # to the layer using `self.add_loss()`. loss = self.loss_fn(targets, logits, sample_weights) self.add_loss(loss) # Log accuracy as a metric and add it # to the layer using `self.add_metric()`. acc = # TODO: Your code goes here # Return the inference-time prediction tensor (for `.predict()`). return tf.nn.softmax(logits) Explanation: The add_metric() method Similarly to add_loss(), layers also have an add_metric() method for tracking the moving average of a quantity during training. Consider the following layer: a "logistic endpoint" layer. It takes as inputs predictions & targets, it computes a loss which it tracks via add_loss(), and it computes an accuracy scalar, which it tracks via add_metric(). End of explanation layer = LogisticEndpoint() targets = tf.ones((2, 2)) logits = tf.ones((2, 2)) y = layer(targets, logits) print("layer.metrics:", layer.metrics) print("current accuracy value:", float(layer.metrics[0].result())) Explanation: Metrics tracked in this way are accessible via layer.metrics: End of explanation inputs = keras.Input(shape=(3,), name="inputs") targets = keras.Input(shape=(10,), name="targets") logits = keras.layers.Dense(10)(inputs) predictions = LogisticEndpoint(name="predictions")(logits, targets) model = keras.Model(inputs=[inputs, targets], outputs=predictions) model.compile(optimizer="adam") data = { "inputs": np.random.random((3, 3)), "targets": np.random.random((3, 10)), } model.fit(data) Explanation: Just like for add_loss(), these metrics are tracked by fit(): End of explanation # TODO class Linear(keras.layers.Layer): def __init__(self, units=32): super(Linear, self).__init__() self.units = units def build(self, input_shape): self.w = self.add_weight( shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.units,), initializer="random_normal", trainable=True ) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b def get_config(self): return {"units": self.units} # You can enable serialization on your layers using `get_config()` method # Now you can recreate the layer from its config: layer = Linear(64) config = # TODO: Your code goes here print(config) new_layer = Linear.from_config(config) Explanation: You can optionally enable serialization on your layers If you need your custom layers to be serializable as part of a Functional model, you can optionally implement a get_config() method: End of explanation class Linear(keras.layers.Layer): def __init__(self, units=32, **kwargs): super(Linear, self).__init__(**kwargs) self.units = units def build(self, input_shape): self.w = self.add_weight( shape=(input_shape[-1], self.units), initializer="random_normal", trainable=True, ) self.b = self.add_weight( shape=(self.units,), initializer="random_normal", trainable=True ) def call(self, inputs): return tf.matmul(inputs, self.w) + self.b def get_config(self): config = super(Linear, self).get_config() config.update({"units": self.units}) return config layer = Linear(64) config = layer.get_config() print(config) new_layer = Linear.from_config(config) Explanation: Note that the __init__() method of the base Layer class takes some keyword arguments, in particular a name and a dtype. It's good practice to pass these arguments to the parent class in __init__() and to include them in the layer config: End of explanation class CustomDropout(keras.layers.Layer): def __init__(self, rate, **kwargs): super(CustomDropout, self).__init__(**kwargs) self.rate = rate def call(self, inputs, training=None): if training: return tf.nn.dropout(inputs, rate=self.rate) return inputs Explanation: If you need more flexibility when deserializing the layer from its config, you can also override the from_config() class method. This is the base implementation of from_config(): python def from_config(cls, config): return cls(**config) To learn more about serialization and saving, see the complete guide to saving and serializing models. Privileged training argument in the call() method Some layers, in particular the BatchNormalization layer and the Dropout layer, have different behaviors during training and inference. For such layers, it is standard practice to expose a training (boolean) argument in the call() method. By exposing this argument in call(), you enable the built-in training and evaluation loops (e.g. fit()) to correctly use the layer in training and inference. End of explanation from tensorflow.keras import layers class Sampling(layers.Layer): Uses (z_mean, z_log_var) to sample z, the vector encoding a digit. def call(self, inputs): z_mean, z_log_var = inputs batch = tf.shape(z_mean)[0] dim = tf.shape(z_mean)[1] epsilon = tf.keras.backend.random_normal(shape=(batch, dim)) return z_mean + tf.exp(0.5 * z_log_var) * epsilon class Encoder(layers.Layer): Maps MNIST digits to a triplet (z_mean, z_log_var, z). def __init__(self, latent_dim=32, intermediate_dim=64, name="encoder", **kwargs): super(Encoder, self).__init__(name=name, **kwargs) self.dense_proj = layers.Dense(intermediate_dim, activation="relu") self.dense_mean = layers.Dense(latent_dim) self.dense_log_var = layers.Dense(latent_dim) self.sampling = Sampling() def call(self, inputs): x = self.dense_proj(inputs) z_mean = self.dense_mean(x) z_log_var = self.dense_log_var(x) z = self.sampling((z_mean, z_log_var)) return z_mean, z_log_var, z class Decoder(layers.Layer): Converts z, the encoded digit vector, back into a readable digit. def __init__(self, original_dim, intermediate_dim=64, name="decoder", **kwargs): super(Decoder, self).__init__(name=name, **kwargs) self.dense_proj = layers.Dense(intermediate_dim, activation="relu") self.dense_output = layers.Dense(original_dim, activation="sigmoid") def call(self, inputs): x = self.dense_proj(inputs) return self.dense_output(x) class VariationalAutoEncoder(keras.Model): Combines the encoder and decoder into an end-to-end model for training. def __init__( self, original_dim, intermediate_dim=64, latent_dim=32, name="autoencoder", **kwargs ): super(VariationalAutoEncoder, self).__init__(name=name, **kwargs) self.original_dim = original_dim self.encoder = Encoder(latent_dim=latent_dim, intermediate_dim=intermediate_dim) self.decoder = Decoder(original_dim, intermediate_dim=intermediate_dim) def call(self, inputs): z_mean, z_log_var, z = self.encoder(inputs) reconstructed = self.decoder(z) # Add KL divergence regularization loss. kl_loss = -0.5 * tf.reduce_mean( z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1 ) self.add_loss(kl_loss) return reconstructed Explanation: Privileged mask argument in the call() method The other privileged argument supported by call() is the mask argument. You will find it in all Keras RNN layers. A mask is a boolean tensor (one boolean value per timestep in the input) used to skip certain input timesteps when processing timeseries data. Keras will automatically pass the correct mask argument to __call__() for layers that support it, when a mask is generated by a prior layer. Mask-generating layers are the Embedding layer configured with mask_zero=True, and the Masking layer. To learn more about masking and how to write masking-enabled layers, please check out the guide "understanding padding and masking". The Model class In general, you will use the Layer class to define inner computation blocks, and will use the Model class to define the outer model -- the object you will train. For instance, in a ResNet50 model, you would have several ResNet blocks subclassing Layer, and a single Model encompassing the entire ResNet50 network. The Model class has the same API as Layer, with the following differences: It exposes built-in training, evaluation, and prediction loops (model.fit(), model.evaluate(), model.predict()). It exposes the list of its inner layers, via the model.layers property. It exposes saving and serialization APIs (save(), save_weights()...) Effectively, the Layer class corresponds to what we refer to in the literature as a "layer" (as in "convolution layer" or "recurrent layer") or as a "block" (as in "ResNet block" or "Inception block"). Meanwhile, the Model class corresponds to what is referred to in the literature as a "model" (as in "deep learning model") or as a "network" (as in "deep neural network"). So if you're wondering, "should I use the Layer class or the Model class?", ask yourself: will I need to call fit() on it? Will I need to call save() on it? If so, go with Model. If not (either because your class is just a block in a bigger system, or because you are writing training & saving code yourself), use Layer. For instance, we could take our mini-resnet example above, and use it to build a Model that we could train with fit(), and that we could save with save_weights(): ```python class ResNet(tf.keras.Model): def __init__(self, num_classes=1000): super(ResNet, self).__init__() self.block_1 = ResNetBlock() self.block_2 = ResNetBlock() self.global_pool = layers.GlobalAveragePooling2D() self.classifier = Dense(num_classes) def call(self, inputs): x = self.block_1(inputs) x = self.block_2(x) x = self.global_pool(x) return self.classifier(x) resnet = ResNet() dataset = ... resnet.fit(dataset, epochs=10) resnet.save(filepath) ``` Putting it all together: an end-to-end example Here's what you've learned so far: A Layer encapsulate a state (created in __init__() or build()) and some computation (defined in call()). Layers can be recursively nested to create new, bigger computation blocks. Layers can create and track losses (typically regularization losses) as well as metrics, via add_loss() and add_metric() The outer container, the thing you want to train, is a Model. A Model is just like a Layer, but with added training and serialization utilities. Let's put all of these things together into an end-to-end example: we're going to implement a Variational AutoEncoder (VAE). We'll train it on MNIST digits. Our VAE will be a subclass of Model, built as a nested composition of layers that subclass Layer. It will feature a regularization loss (KL divergence). End of explanation original_dim = 784 vae = VariationalAutoEncoder(original_dim, 64, 32) optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) mse_loss_fn = tf.keras.losses.MeanSquaredError() loss_metric = tf.keras.metrics.Mean() (x_train, _), _ = tf.keras.datasets.mnist.load_data() x_train = x_train.reshape(60000, 784).astype("float32") / 255 train_dataset = tf.data.Dataset.from_tensor_slices(x_train) train_dataset = train_dataset.shuffle(buffer_size=1024).batch(64) epochs = 2 # Iterate over epochs. for epoch in range(epochs): print("Start of epoch %d" % (epoch,)) # Iterate over the batches of the dataset. for step, x_batch_train in enumerate(train_dataset): with tf.GradientTape() as tape: reconstructed = vae(x_batch_train) # Compute reconstruction loss loss = mse_loss_fn(x_batch_train, reconstructed) loss += sum(vae.losses) # Add KLD regularization loss grads = tape.gradient(loss, vae.trainable_weights) optimizer.apply_gradients(zip(grads, vae.trainable_weights)) loss_metric(loss) if step % 100 == 0: print("step %d: mean loss = %.4f" % (step, loss_metric.result())) Explanation: Let's write a simple training loop on MNIST: End of explanation vae = VariationalAutoEncoder(784, 64, 32) optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) vae.compile(optimizer, loss=tf.keras.losses.MeanSquaredError()) vae.fit(x_train, x_train, epochs=2, batch_size=64) Explanation: Note that since the VAE is subclassing Model, it features built-in training loops. So you could also have trained it like this: End of explanation original_dim = 784 intermediate_dim = 64 latent_dim = 32 # Define encoder model. original_inputs = tf.keras.Input(shape=(original_dim,), name="encoder_input") x = layers.Dense(intermediate_dim, activation="relu")(original_inputs) z_mean = layers.Dense(latent_dim, name="z_mean")(x) z_log_var = layers.Dense(latent_dim, name="z_log_var")(x) z = Sampling()((z_mean, z_log_var)) encoder = tf.keras.Model(inputs=original_inputs, outputs=z, name="encoder") # Define decoder model. latent_inputs = tf.keras.Input(shape=(latent_dim,), name="z_sampling") x = layers.Dense(intermediate_dim, activation="relu")(latent_inputs) outputs = layers.Dense(original_dim, activation="sigmoid")(x) decoder = tf.keras.Model(inputs=latent_inputs, outputs=outputs, name="decoder") # Define VAE model. outputs = decoder(z) vae = tf.keras.Model(inputs=original_inputs, outputs=outputs, name="vae") # Add KL divergence regularization loss. kl_loss = -0.5 * tf.reduce_mean(z_log_var - tf.square(z_mean) - tf.exp(z_log_var) + 1) vae.add_loss(kl_loss) # Train. optimizer = tf.keras.optimizers.Adam(learning_rate=1e-3) vae.compile(optimizer, loss=tf.keras.losses.MeanSquaredError()) vae.fit(x_train, x_train, epochs=3, batch_size=64) Explanation: Beyond object-oriented development: the Functional API Was this example too much object-oriented development for you? You can also build models using the Functional API. Importantly, choosing one style or another does not prevent you from leveraging components written in the other style: you can always mix-and-match. For instance, the Functional API example below reuses the same Sampling layer we defined in the example above: End of explanation
5,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Algorithm comparison This notebook contains the algorithm comparison for the measurements done with the DySpan 2017 testbed N_FRAMES = 50 comparison is based on different aspects, such as Step1: Placeholder for small graph Step2: Saving the models to disk We choose the models with a good performance, and we save the models to disk in order to use them in a live implementation. For this, we are going to use the "pickle" library that allows us to dump the model into a file. Based on the results recorded in this notebook, we are going to save the following models Step3: The same can be done without additional dependencies using joblib, which is shipped with scikit-learn. This has the advantage of being able to take either a file object or just the path to the file as an argument Step4: Joblib works wonders with sklearn, as well as with numpy arrays in general. For general purposes they both do their job just fine (as joblib uses pickle in the background), but joblib can be significantly faster Checking the validity of the saved models Now we just want to double-check that the models that we just saved are according to the values that we saw just after the learning process, and before savind the model persistance. In order to do this, we just load the model into a new variable from the saved file, and check for the accuracy of the new model using the same test set First, remember that our X_train, X_test, y_train and y_test has been sliced in order to simulate data sets of variable lenghts. So, we take the largest as it demostrated to provide better results in this case
Python Code: %load_ext autoreload %autoreload 2 import sys print(sys.version) import sys sys.path.append("../python") import setup_dataset data, labels = setup_dataset.setup_simple_iterables("with_dc") X_train, X_test, y_train, y_test = setup_dataset.slice_data(data, labels) # Setting up various complexities for the different algorithms. # Number of neighbors knn_c = (2, 4, 10, 50) # Maximum depth in a decision tree dtc_c = (2, 5, 10, 50) # complexities for the rbf kernel svc_c = (1, 1000, 1000000) # Number of estimators in the random forest classifier rfc_c = (1, 10, 100, 1000, 10000, 100000) # Number of parallel jobs (CPU) rfc_jobs = (3, -2) gpc_jobs = (3, -2) # Number of iteration in the Gaussian Process Classifier gpc_c = (20, 50, 100) from sklearn.preprocessing import MaxAbsScaler from sklearn.preprocessing import StandardScaler scaler, X_train_scaled, X_test_scaled = setup_dataset.scale_sliced_data(X_train, X_test, StandardScaler()) knn_list, knn_accs, knn_pred, knn_pred_times, knn_fit_times = \ setup_dataset.run_knn(X_train, X_test, y_train, y_test, knn_c) setup_dataset.compute_cm(y_test, knn_pred, knn_c) knn_list_scaled, knn_accs_scaled, knn_pred_scaled, knn_pred_times_scaled, knn_fit_times_scaled =\ setup_dataset.run_knn(X_train_scaled, X_test_scaled, y_train, y_test, knn_c) setup_dataset.compute_cm(y_test, knn_pred_scaled, knn_c) for line in knn_accs : print(line) print("====================") for line in knn_accs_scaled: print(line) dtc_list, dtc_accs, dtc_pred, dtc_pred_times, dtc_fit_times = \ setup_dataset.run_decision_tree(X_train, X_test, y_train, y_test, dtc_c) dtc_list_scaled, dtc_accs_scaled, dtc_pred_scaled, dtc_pred_times_scaled, dtc_fit_times_scaled = \ setup_dataset.run_decision_tree(X_train_scaled, X_test_scaled, y_train, y_test, dtc_c) setup_dataset.compute_cm(y_test, dtc_pred, dtc_c) setup_dataset.compute_cm(y_test, dtc_pred_scaled, dtc_c) for line in dtc_accs : print(line) print("====================") for line in dtc_accs_scaled: print(line) nbc_list, nbc_accs, nbc_pred, nbc_pred_times, nbc_fit_times = \ setup_dataset.run_naive_bayes(X_train, X_test, y_train, y_test, (1,)) nbc_list_scaled, nbc_accs_scaled, nbc_pred_scaled, nbc_pred_times_scaled, nbc_fit_times_scaled = \ setup_dataset.run_naive_bayes(X_train_scaled, X_test_scaled, y_train, y_test, (1,)) setup_dataset.compute_cm(y_test, nbc_pred, [1]) setup_dataset.compute_cm(y_test, nbc_pred_scaled, [1]) abc_list, abc_accs, abc_pred, abc_pred_times, abc_fit_times = \ setup_dataset.run_adaboost(X_train, X_test, y_train, y_test, (1,)) abc_list_scaled, abc_accs_scaled, abc_pred_scaled, abc_pred_times_scaled, abc_fit_times_scaled = \ setup_dataset.run_adaboost(X_train_scaled, X_test_scaled, y_train, y_test, (1,)) setup_dataset.compute_cm(y_test, abc_pred, [1]) setup_dataset.compute_cm(y_test, abc_pred_scaled, [1]) qda_list, qda_accs, qda_pred, qda_pred_times, qda_fit_times = \ setup_dataset.run_quadratic(X_train, X_test, y_train, y_test, (1,)) qda_list_scaled, qda_accs_scaled, qda_pred_scaled, qda_pred_times_scaled, qda_fit_times_scaled = \ setup_dataset.run_quadratic(X_train_scaled, X_test_scaled, y_train, y_test, (1,)) setup_dataset.compute_cm(y_test, qda_pred, [1]) setup_dataset.compute_cm(y_test, qda_pred_scaled, [1]) svc_list, svc_accs, svc_pred, svc_pred_times, svc_fit_times = \ setup_dataset.run_svc(X_train, X_test, y_train, y_test, svc_c) svc_list_scaled, svc_accs_scaled, svc_pred_scaled, svc_pred_times_scaled, svc_fit_times_scaled = \ setup_dataset.run_svc(X_train_scaled, X_test_scaled, y_train, y_test, svc_c) setup_dataset.compute_cm(y_test, svc_pred, svc_c) setup_dataset.compute_cm(y_test, svc_pred_scaled, svc_c) for line in svc_accs : print(line) print("====================") for line in svc_accs_scaled: print(line) for line in svc_accs : print(line) print("====================") for line in svc_accs_scaled: print(line) # THIS MAKES THE KERNEL CRASH! rfc_list, rfc_accs, rfc_pred, rfc_pred_times, rfc_fit_times = \ setup_dataset.run_random_forest(X_train, X_test, y_train, y_test, rfc_c, rfc_jobs) rfc_list_scaled, rfc_accs_scaled, rfc_pred_scaled, rfc_pred_times_scaled, rfc_fit_times_scaled = \ setup_dataset.run_random_forest(X_train_scaled, X_test_scaled, y_train, y_test, rfc_c, rfc_jobs) setup_dataset.compute_cm(y_test, rfc_pred, rfc_c) setup_dataset.compute_cm(y_test, rfc_pred_scaled, rfc_c) gpc_list, gpc_accs, gpc_pred, gpc_pred_times, gpc_fit_times = \ setup_dataset.run_gaussian(X_train, X_test, y_train, y_test, gpc_c, gpc_jobs) gpc_list_scaled, gpc_accs_scaled, gpc_pred_scaled, gpc_pred_times_scaled, gpc_fit_times_scaled = \ setup_dataset.run_gaussian(X_train_scaled, X_test_scaled, y_train, y_test, gpc_c, rfc_jobs) setup_dataset.compute_cm(y_test, gpc_pred, gpc_c) setup_dataset.compute_cm(y_test, gpc_pred_scaled, gpc_c) Explanation: Algorithm comparison This notebook contains the algorithm comparison for the measurements done with the DySpan 2017 testbed N_FRAMES = 50 comparison is based on different aspects, such as: Dataset lenght complexity: different for each algorithm, made by playing around with the parameters that it has available Pre- and post- feature scaling Aspects that are better explained in the thesis document contained in this same repository End of explanation import numpy as np import matplotlib.pyplot as plt plt.figure() x = np.arange(len(knn_accs[0])) y = [[] for _ in range(len(knn_accs[0]))] for i in range(len(knn_accs[0])): y[i] = knn_accs[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) # plt.scatter(x, y[i], label="data {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(knn_accs[0])) y = [[] for _ in range(len(knn_accs[0]))] width = 0.2 for i in range(len(knn_accs[0])): y[i] = knn_accs[i] plt.bar(x- 1.5*width + width*i, y[i], width, align='center', label="complexity {}".format(i), alpha=0.8) # plt.scatter(x, y[i], label="data {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(knn_fit_times[0])) y = [[] for _ in range(len(knn_fit_times[0]))] for i in range(len(knn_fit_times[0])): y[i] = knn_fit_times[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) # plt.scatter(x, y[i], label="data {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(knn_accs_scaled[0])) y = [[] for _ in range(len(knn_accs_scaled[0]))] for i in range(len(knn_accs_scaled[0])): y[i] = knn_accs_scaled[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) # plt.scatter(x, y[i], label="data {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(svc_accs[0])) y = [[] for _ in range(len(svc_accs[0]))] for i in range(len(svc_accs[0])): y[i] = svc_accs[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(svc_accs_scaled[0])) y = [[] for _ in range(len(svc_accs_scaled[0]))] for i in range(len(svc_accs_scaled[0])): y[i] = svc_accs_scaled[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.figure() x = np.arange(len(dtc_accs_scaled[0])) y = [[] for _ in range(len(dtc_accs_scaled[0]))] for i in range(len(dtc_accs_scaled[0])): y[i] = dtc_accs_scaled[i] plt.plot(x, y[i], linestyle='-', label="complexity {}".format(i)) # plt.scatter(x, y[i], label="data {}".format(i)) plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() for line in dtc_accs : print(line) print("====================") for line in dtc_accs_scaled: print(line) Explanation: Placeholder for small graph End of explanation import pickle pickle.dump(knn_list[3][1], open('../weights/knn_full_data_set_4_neighbors.sav', 'wb')) pickle.dump(dtc_list[3][3], open('../weights/dtc_full_data_set_depth_50.sav', 'wb')) pickle.dump(svc_list_scaled[3][2], open('../weights/svc_full_data_set_rbf_1e6.sav', 'wb')) Explanation: Saving the models to disk We choose the models with a good performance, and we save the models to disk in order to use them in a live implementation. For this, we are going to use the "pickle" library that allows us to dump the model into a file. Based on the results recorded in this notebook, we are going to save the following models: * k-nearest neighbors, not staled, with the whole data set and 4 neighbors * decision tree, not staled, with whole data set and depth=50 * Support vector classifier, scaled, with whole data and a RBF kernel complexity of 1e6 NOTE: Be sure of pickle (save) the models in the same python version that you are going to use for unplickle it later on. As I will be using GNURadio (at its master branch), it is a requirement that this notebook runs with a Python2 kernel. For issues changing the kernel please see this thread End of explanation from sklearn.externals import joblib joblib.dump(knn_list[3][1], '../weights/knn_full_data_set_4_neighbors.pkl', protocol=2) joblib.dump(dtc_list[3][3], '../weights/dtc_full_data_set_depth_50.pkl', protocol=2) joblib.dump(svc_list_scaled[3][2], '../weights/svc_full_data_set_rbf_1e6.pkl', protocol=2) Explanation: The same can be done without additional dependencies using joblib, which is shipped with scikit-learn. This has the advantage of being able to take either a file object or just the path to the file as an argument End of explanation X_test_large = X_test[3] X_test_scaled_large = X_test_scaled[3] y_test_large = y_test[3] knn_saved = pickle.load(open('../weights/knn_full_data_set_4_neighbors.sav', 'rb')) dtc_saved = pickle.load(open('../weights/dtc_full_data_set_depth_50.sav', 'rb')) svc_saved = pickle.load(open('../weights/svc_full_data_set_rbf_1e6.sav', 'rb')) print("The score achieved with the saved model is:\n") print("K-nearest Neighbors =", knn_saved.score(X_test_large, y_test_large)) print("Decision Tree =", dtc_saved.score(X_test_large,y_test_large)) print("Support Vector Machine =", svc_saved.score(X_test_scaled_large,y_test_large)) knn_saved = joblib.load('../weights/knn_full_data_set_4_neighbors.pkl') dtc_saved = joblib.load('../weights/dtc_full_data_set_depth_50.pkl') svc_saved = joblib.load('../weights/svc_full_data_set_rbf_1e6.pkl') result = knn_saved.score(X_test_large,y_test_large) print("The score achieved with the saved model is:\n") print("K-nearest Neighbors =", knn_saved.score(X_test_large, y_test_large)) print("Decision Tree =", dtc_saved.score(X_test_large,y_test_large)) print("Support Vector Machine =", svc_saved.score(X_test_scaled_large,y_test_large)) print X_test_large[4000] print len(X_test_large) scaler_saved = joblib.dump(scaler, '../weights/scaler_saved.pkl') Explanation: Joblib works wonders with sklearn, as well as with numpy arrays in general. For general purposes they both do their job just fine (as joblib uses pickle in the background), but joblib can be significantly faster Checking the validity of the saved models Now we just want to double-check that the models that we just saved are according to the values that we saw just after the learning process, and before savind the model persistance. In order to do this, we just load the model into a new variable from the saved file, and check for the accuracy of the new model using the same test set First, remember that our X_train, X_test, y_train and y_test has been sliced in order to simulate data sets of variable lenghts. So, we take the largest as it demostrated to provide better results in this case: End of explanation
5,374
Given the following text description, write Python code to implement the functionality described below step by step Description: User Defined Materials Overview Materials are implemented by subclassing the matmodlab.core.Material base class. The user material is called at each frame of every step. It is provided with the material state at the start of the increment (stress, solution-dependent state variables, temperature, etc) and with the increments in temperature, deformation, and time. The implementation of a material model will be demonstrated with a standard isotropic linear elastic model. <a name='contents'></a> Contents <a href='#linelast'>Isotropic Linear Elasticity</a> <a href='#umat.std'>Model Implementation</a> <a href='#umat.compare'>Model Comparison</a> <a href='#conc'>Conclusion</a> <a name='linelast'></a> Isotropic Linear Elasticity The mechanical response of a linear elastic material is defined by $$ \boldsymbol{\sigma} = \mathbb{C}{ Step1: Verification Test Exercising the elastic model through a path of uniaxial stress should result in the slope of axial stress vs. axial strain being equal to the input parameter E. Note
Python Code: %pycat ../matmodlab2/materials/elastic3.py %pylab inline from matmodlab2 import * Explanation: User Defined Materials Overview Materials are implemented by subclassing the matmodlab.core.Material base class. The user material is called at each frame of every step. It is provided with the material state at the start of the increment (stress, solution-dependent state variables, temperature, etc) and with the increments in temperature, deformation, and time. The implementation of a material model will be demonstrated with a standard isotropic linear elastic model. <a name='contents'></a> Contents <a href='#linelast'>Isotropic Linear Elasticity</a> <a href='#umat.std'>Model Implementation</a> <a href='#umat.compare'>Model Comparison</a> <a href='#conc'>Conclusion</a> <a name='linelast'></a> Isotropic Linear Elasticity The mechanical response of a linear elastic material is defined by $$ \boldsymbol{\sigma} = \mathbb{C}{:}\boldsymbol{\epsilon} = 3K\boldsymbol{\epsilon}^{\rm iso} + 2G\boldsymbol{\epsilon}^{\rm dev} $$ where $K$ is the bulk modulus and $G$ is the shear modulus. The strain $\boldsymbol{\epsilon}$ can be determined from the deformation gradient $\pmb{F}$ as $$ \boldsymbol{\epsilon} = \frac{1}{2\kappa}\left[\left(\boldsymbol{F}^{\rm T}{\cdot}\boldsymbol{F}\right)^{2\kappa} - \boldsymbol{I}\right] $$ where $\kappa$ is the generalized Seth-Hill strain parameter. Defined as such, several well known finite strain measures are emitted: $\kappa=1$: Green-Lagrange reference strain $\kappa=-1$: Alamansi spatial strain $\kappa=0$: Logarithmic, or true, strain The implementations of linear elasticity to follow will take as input Young's modulus E, Poisson's ratio Nu, and the Seth-Hill parameter k for changing the strain definition. <a name='umat.std'></a> Model Implementation The easiest way to implement a material model is to subclass the matmodlab2.core.material.Material class and define: name: class attribute Used for referencing the material model in the MaterialPointSimulator. eval: instance method Updates the material stress, stiffness (optional), and state dependent variables. If the stiffness is returned as None, Matmodlab will determine it numerically. Other optional attributes and methods include: num_sdv: instance attribute The number of state dependent variables. Default is None. sdv_names: instance attribute List of state dependent variable names. Default is SDV_N for the N$^{\rm th}$ state dependent variable. sdvini: instance method [optional] Initializes solution dependent state variables (otherwise assumed to be 0). In the example below, in addition to some standard functions imported from numpy, several helper functions are imported from various locations in Matmodlab: matmodlab2.core.tensor logm, powm: computes the matrix logarithm and power array_rep: converts a symmetric tensor stored as a 3x3 matrix to an array of length 6 polar_decomp: computes the polar decomposition of the deformation gradient $\pmb{F}$ isotropic_part, deviatoric_part: computes the isotropic and deviatoric parts of a second-order symmetric tensor stored as an array of length 6 VOIGT: mulitplier for converting tensor strain components to engineering strain components The relevant input parameters to the material's eval method from Matmodlab are: F: the deformation gradient at the end of the step The isotropic elastic material described above is implemented as ElasticMaterialTotal in the file matmodlab/materials/elastic3.py. The implementation can be viewed by executing the following cell. End of explanation mps1 = MaterialPointSimulator('uelastic-std') mps1.material = ElasticMaterialTotal(E=10e6, Nu=.333) mps1.run_step('ESS', (.1, 0, 0), frames=50) i = where(mps1.df['E.XX'] > 0.) E = mps1.df['S.XX'].iloc[i] / mps1.df['E.XX'].iloc[i] assert allclose(E, 10e6, atol=1e-3, rtol=1e-3) Explanation: Verification Test Exercising the elastic model through a path of uniaxial stress should result in the slope of axial stress vs. axial strain being equal to the input parameter E. Note: it is the responsibility of the model developer to define the material's instantiation. In the case of ElasticMaterialTotal, the interface takes the elastic parameters as keywords. Parameters not specified are initialized to a value of zero. End of explanation
5,375
Given the following text description, write Python code to implement the functionality described below step by step Description: 列表生成式和生成式表达式 我们可以用 map 和 filter 达到 列表生成式的效果 Step1: 对于上面的例子来说, filter/map 并不比 listcomp(列表生成式) 快, 后面的章节我们进一步讨论 列表生成式的多层循环 假如我们要制作两种颜色三种大小组成的 T 恤, 下面的代码是生成 T 恤的序列 Step2: Python中,[], {}, () 内的换行符会被忽略,所以我们在创建列表,字典等时,不必使用 \ 来换行,列表推导式的作用只有一个,生成列表,如果想生成其它类型的序列,生成器就派上了用场。 生成器表达式 生成式表达式更省存储空间,因为它背后遵守了迭代器协议,逐个的产生项目,而不是一次构建整个列表然后将列表传递到某个构造函数中。 Genexp(生成式表达式)语法和 listcomp(列表生成式) 一样,但是它使用圆括号而不是方括号 Step3: Tuple Tuple 并非只是不可变列表 Tuple 可以当成不可变序列使用,也可以当成没有字段名的记录。元组其实是对数据的记录,元组中每个元素都存放了记录中的一个字段的数据,外加这个字段的位置,正是这个位置信息给数据赋予了意义。将 tuple 当成记录时,重新排序 tuple 会破坏它表示的信息 Step4: 元组拆包 在上面我们将元组拆解成 city, year,... 等,接着在下面,我们用 "%s/%s" % passport 打印元组,这些例子是拆解元组的范例。任何可迭代对象都可以进行元组拆包,被可迭代对象的元素数量必须和接受这些元素的元组空档一致,除非你用星号(*)来处理多余的元素 在元组拆包中,最常见的是平行赋值,也就是将可迭代对象的项目指派给一个变量 tuple,如下所示 Step5: 不用中间变量交换值,是元组拆包的另一种应用 Step6: 另一种元组拆包,调用函数时,参数前面加个星号 Step7: 上面也是一种元组拆包方法,调用函数时候用 * 把可迭代对象拆开作为函数参数。 下面的例子是让一个函数可以使用元组的方式返回多个值,os.path.split() 函数返回一个以路径和最后一个文件名组成的元组(path, last_part) Step8: 如果在编写国际化的软件, 并不是一个很好的占位符,因为传统上,它会被当成 gettext.gettext 函数的别名,其他时候, 是一个好的占位符 使用 * 来处理剩下的元素 以 *args 来指定函数参数,可以获取任意数量的参数,这是 Python 中一种经典的写法 Python 3 中,这个概念被扩展到平行赋值中。 Step9: 在平行赋值情况下, * 前置符只能用在一个变量前面,但是可以这个变量可以是任意位置 Step10: 嵌套元组拆包 我们可以在需要用运算式来拆解的 tuple 中套入其它的 tuple,例如(a, b, (c, d)),而且如果运算式与嵌套结构匹配,python 就会做出正确的动作 Step11: 在 python3 之前,你可以在定义函数时,可以使用嵌套元组做形参,例如 def func(a, (b, c), d)。但是 python3 已经不支持了,不过这对函数调用者没有任何影响,它改变的是某些函数的声明方式 按照设计,tuple 是非常方便的,可以把它当成记录来使用,不过它不可以指定名字,这也是 namedtuple 被设计出来的原因 可以指定名字的元组(具名元组) collections.namedtuple 是一个工厂函数,可以构建一个带字段名的元组和一个有名字的类。这个带名字的类对调试程序有很大的帮助。使用 namedtuple 创建的实例消耗的内存与元组是一样的,因为字段名都被存储到相应的类中。这个实例跟普通的对象实例比起来要小一些,因为 Python 不会用到 __dict__ 来存放这些实例的属性 下面展示了如何用具名元组来记录一个城市的信息。 Step12: 构建 namedtuple 需要两个参数,第一个是类名,另一个是各个字段的名字,可以使用可迭代的字符串(列表),也可以使用用空格分隔的字符串。 存放在对应字段里的数据要以一串参数的形式传入到构造函数中。注意,元祖的构造函数值接受单一的可迭代对象。 可以用字段名或位置来读取数据 下面是 namedtuple 的常用属性
Python Code: symbols = "a%b&c$de$" beyond_ascii = [ord(s) for s in symbols if ord(s) > 50] beyond_ascii beyond_ascii = list(filter(lambda c: c > 50, map(ord, symbols))) beyond_ascii Explanation: 列表生成式和生成式表达式 我们可以用 map 和 filter 达到 列表生成式的效果 End of explanation colors = ['black', 'white'] sizes = ['S', 'M', 'L'] tshirts = [(color, size) for color in colors #两种颜色,三种尺寸的方式创建列表 for size in sizes] tshirts Explanation: 对于上面的例子来说, filter/map 并不比 listcomp(列表生成式) 快, 后面的章节我们进一步讨论 列表生成式的多层循环 假如我们要制作两种颜色三种大小组成的 T 恤, 下面的代码是生成 T 恤的序列 End of explanation symbols = "a%b&c$de$" tuple(ord(s) for s in symbols) #如果生成器是一个函数的唯一的参数,则不用重复使用括号 import array array.array('I', (ord(symbol) for symbol in symbols)) #不是唯一的参数,所以必须要加上括号 Explanation: Python中,[], {}, () 内的换行符会被忽略,所以我们在创建列表,字典等时,不必使用 \ 来换行,列表推导式的作用只有一个,生成列表,如果想生成其它类型的序列,生成器就派上了用场。 生成器表达式 生成式表达式更省存储空间,因为它背后遵守了迭代器协议,逐个的产生项目,而不是一次构建整个列表然后将列表传递到某个构造函数中。 Genexp(生成式表达式)语法和 listcomp(列表生成式) 一样,但是它使用圆括号而不是方括号 End of explanation lax_coordinates = (33.942, -118.4080) #经纬度 city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014) #Tokyo 的资料,包括名称年份人口人口变化和面积 traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')] #country_code,passport_number for passport in sorted(traveler_ids): print('%s/%s' % passport) for country, _ in traveler_ids: print(country) Explanation: Tuple Tuple 并非只是不可变列表 Tuple 可以当成不可变序列使用,也可以当成没有字段名的记录。元组其实是对数据的记录,元组中每个元素都存放了记录中的一个字段的数据,外加这个字段的位置,正是这个位置信息给数据赋予了意义。将 tuple 当成记录时,重新排序 tuple 会破坏它表示的信息 End of explanation lax_coordinates = (33.348, -117.932) latitude, longitude = lax_coordinates # tuple 拆解 print(latitude) print(longitude) Explanation: 元组拆包 在上面我们将元组拆解成 city, year,... 等,接着在下面,我们用 "%s/%s" % passport 打印元组,这些例子是拆解元组的范例。任何可迭代对象都可以进行元组拆包,被可迭代对象的元素数量必须和接受这些元素的元组空档一致,除非你用星号(*)来处理多余的元素 在元组拆包中,最常见的是平行赋值,也就是将可迭代对象的项目指派给一个变量 tuple,如下所示: End of explanation a = 3 b = 5 a, b = b, a a Explanation: 不用中间变量交换值,是元组拆包的另一种应用 End of explanation divmod(20, 8) #a 除 b,返回商和余数 t = (20, 8) divmod(*t) quotient, remainder = divmod(*t) quotient, remainder Explanation: 另一种元组拆包,调用函数时,参数前面加个星号 End of explanation import os _, filename = os.path.split('/home/kaka/.ssh/idrsa.pub') filename Explanation: 上面也是一种元组拆包方法,调用函数时候用 * 把可迭代对象拆开作为函数参数。 下面的例子是让一个函数可以使用元组的方式返回多个值,os.path.split() 函数返回一个以路径和最后一个文件名组成的元组(path, last_part) End of explanation a, b, *rest = range(5) a, b, rest a, b, *rest = range(3) a, b, rest a, b, *rest = range(2) a, b, rest Explanation: 如果在编写国际化的软件, 并不是一个很好的占位符,因为传统上,它会被当成 gettext.gettext 函数的别名,其他时候, 是一个好的占位符 使用 * 来处理剩下的元素 以 *args 来指定函数参数,可以获取任意数量的参数,这是 Python 中一种经典的写法 Python 3 中,这个概念被扩展到平行赋值中。 End of explanation a, *body, c, d = range(5) a, body, c, d *head, b, c, d = range(5) head, b, c, d Explanation: 在平行赋值情况下, * 前置符只能用在一个变量前面,但是可以这个变量可以是任意位置 End of explanation metro_areas = [ ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)), ('Mexico City', 'MX', 20.142, (19.43333, -99.13333)), ('Net York-Newark', 'US', 20.104, (40.808611, -74.020386)), ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635883)) ] print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.')) #^9 表示占 9 个字符,居中显示 fmt = '{:15} | {:^9} | {:^9}' for name, cc, pop, (latitude, longitude) in metro_areas: if longitude <= 0: #西半球 print(fmt.format(name, latitude, longitude)) Explanation: 嵌套元组拆包 我们可以在需要用运算式来拆解的 tuple 中套入其它的 tuple,例如(a, b, (c, d)),而且如果运算式与嵌套结构匹配,python 就会做出正确的动作 End of explanation from collections import namedtuple City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) tokyo tokyo.coordinates tokyo[1] Explanation: 在 python3 之前,你可以在定义函数时,可以使用嵌套元组做形参,例如 def func(a, (b, c), d)。但是 python3 已经不支持了,不过这对函数调用者没有任何影响,它改变的是某些函数的声明方式 按照设计,tuple 是非常方便的,可以把它当成记录来使用,不过它不可以指定名字,这也是 namedtuple 被设计出来的原因 可以指定名字的元组(具名元组) collections.namedtuple 是一个工厂函数,可以构建一个带字段名的元组和一个有名字的类。这个带名字的类对调试程序有很大的帮助。使用 namedtuple 创建的实例消耗的内存与元组是一样的,因为字段名都被存储到相应的类中。这个实例跟普通的对象实例比起来要小一些,因为 Python 不会用到 __dict__ 来存放这些实例的属性 下面展示了如何用具名元组来记录一个城市的信息。 End of explanation City._fields #是 1 个元组,里面是我们的字段名 LatLong = namedtuple('LatLong', 'lat long') delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889)) delhi = City._make(delhi_data) #_make() 可以让我们接受一个可迭代对象生成这个类的一个实例。City(*delhi_data) 也可以做这件事 delhi._asdict() #把具名元组按照 collections.OrderedDict 的形式返回, 用来友好的显示城市资料 Explanation: 构建 namedtuple 需要两个参数,第一个是类名,另一个是各个字段的名字,可以使用可迭代的字符串(列表),也可以使用用空格分隔的字符串。 存放在对应字段里的数据要以一串参数的形式传入到构造函数中。注意,元祖的构造函数值接受单一的可迭代对象。 可以用字段名或位置来读取数据 下面是 namedtuple 的常用属性: End of explanation
5,376
Given the following text description, write Python code to implement the functionality described below step by step Description: The Traveling Salesman problem Names of group members // put your names here! Goals of this assignment The main goal of this assignment is to use Monte Carlo methods to find the shortest path between several cities - the "Traveling Salesman" problem. This is an example of how randomization can be used to optimize problems that would be incredibly computationally expensive (and sometimes impossible) to solve exactly. The Traveling Salesman problem The Traveling Salesman Problem is a classic problem in computer science where the focus is on optimization. The problem is as follows Step1: This code sets up everything we need Given a number of cities, set up random x and y positions and calculate a table of distances between pairs of cities (used for calculating the total trip distance). Then set up an array that controls the order that the salesman travels between cities, and plots out the initial path. Step2: Put your code below this! Your code should take some number of steps, doing the following at each step Step4: Assignment wrapup Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment!
Python Code: import numpy as np %matplotlib inline import matplotlib.pyplot as plt from IPython.display import display, clear_output def calc_total_distance(table_of_distances, city_order): ''' Calculates distances between a sequence of cities. Inputs: N x N table containing distances between each pair of the N cities, as well as an array of length N+1 containing the city order, which starts and ends with the same city (ensuring that the path is closed) Returns: total path length for the closed loop. ''' total_distance = 0.0 # loop over cities and sum up the path length between successive pairs for i in range(city_order.size-1): total_distance += table_of_distances[city_order[i]][city_order[i+1]] return total_distance def plot_cities(city_order,city_x,city_y): ''' Plots cities and the path between them. Inputs: ordering of cities, x and y coordinates of each city. Returns: a plot showing the cities and the path between them. ''' # first make x,y arrays x = [] y = [] # put together arrays of x and y positions that show the order that the # salesman traverses the cities for i in range(0, city_order.size): x.append(city_x[city_order[i]]) y.append(city_y[city_order[i]]) # append the first city onto the end so the loop is closed x.append(city_x[city_order[0]]) y.append(city_y[city_order[0]]) #time.sleep(0.1) clear_output(wait=True) display(fig) # Reset display fig.clear() # clear output for animation plt.xlim(-0.2, 20.2) # give a little space around the edges of the plot plt.ylim(-0.2, 20.2) # plot city positions in blue, and path in red. plt.plot(city_x,city_y, 'bo', x, y, 'r-') Explanation: The Traveling Salesman problem Names of group members // put your names here! Goals of this assignment The main goal of this assignment is to use Monte Carlo methods to find the shortest path between several cities - the "Traveling Salesman" problem. This is an example of how randomization can be used to optimize problems that would be incredibly computationally expensive (and sometimes impossible) to solve exactly. The Traveling Salesman problem The Traveling Salesman Problem is a classic problem in computer science where the focus is on optimization. The problem is as follows: Imagine there is a salesman who has to travel to N cities. The order is unimportant, as long as he only visits each city once on each trip, and finishes where he started. The salesman wants to keep the distance traveled (and thus travel costs) as low as possible. This problem is interesting for a variety of reasons - it applies to transportation (finding the most efficient bus routes), logistics (finding the best UPS or FedEx delivery routes for some number of packages), or in optimizing manufacturing processes to reduce cost. The Traveling Salesman Problem is extremely difficult to solve for large numbers of cities - testing every possible combination of cities would take N! (N factorial) individual tests. For 10 cities, this would require 3,628,800 separate tests. For 20 cities, this would require 2,432,902,008,176,640,000 (approximately $2.4 \times 10^{18}$) tests - if you could test one combination per microsecond ($10^{-6}$ s) it would take approximately 76,000 years! For 30 cities, at the same rate testing every combination would take more than one billion times the age of the Universe. As a result, this is the kind of problem where a "good enough" answer is sufficient, and where randomization comes in. A good local example of a solution to the Traveling Salesman Problem is an optimized Michigan road trip calculated by a former MSU graduate student (and one across the US). There's also a widely-used software library for solving the Traveling Salesman Problem; the website has some interesting applications of the problem! End of explanation # number of cities we'll use. number_of_cities = 30 # seed for random number generator so we get the same value every time! np.random.seed(2024561414) # create random x,y positions for our current number of cities. (Distance scaling is arbitrary.) city_x = np.random.random(size=number_of_cities)*20.0 city_y = np.random.random(size=number_of_cities)*20.0 # table of city distances - empty for the moment city_distances = np.zeros((number_of_cities,number_of_cities)) # calculate distnace between each pair of cities and store it in the table. # technically we're calculating 2x as many things as we need (as well as the # diagonal, which should all be zeros), but whatever, it's cheap. for a in range(number_of_cities): for b in range(number_of_cities): city_distances[a][b] = ((city_x[a]-city_x[b])**2 + (city_y[a]-city_y[b])**2 )**0.5 # create the array of cities in the order we're going to go through them city_order = np.arange(city_distances.shape[0]) # tack on the first city to the end of the array, since that ensures a closed loop city_order = np.append(city_order, city_order[0]) Explanation: This code sets up everything we need Given a number of cities, set up random x and y positions and calculate a table of distances between pairs of cities (used for calculating the total trip distance). Then set up an array that controls the order that the salesman travels between cities, and plots out the initial path. End of explanation fig = plt.figure() # Put your code here! # number of steps we'll take N_steps = 1000 step = [0] distance = [calc_total_distance(city_distances,city_order)] for i in range(N_steps): swap1 = np.random.randint(1,city_order.shape[0]-2) swap2 = np.random.randint(1,city_order.shape[0]-2) orig_distance = calc_total_distance(city_distances,city_order) new_city_order = np.copy(city_order) hold = new_city_order[swap1] new_city_order[swap1] = new_city_order[swap2] new_city_order[swap2] = hold new_distance = calc_total_distance(city_distances,new_city_order) if new_distance < orig_distance: city_order = np.copy(new_city_order) step.append(i) distance.append(new_distance) plot_cities(city_order,city_x,city_y) plt.plot(step,distance) Explanation: Put your code below this! Your code should take some number of steps, doing the following at each step: Randomly swap two cities in the array of cities (except for the first/last city) Check the total distance traversed by the salesman If the new ordering results in a shorter path, keep it. If not, throw it away. Plot the shorter of the two paths (the original one or the new one) Also, keep track of the steps and the minimum distance traveled as a function of number of steps and plot out the minimum distance as a function of step! End of explanation from IPython.display import HTML HTML( <iframe src="https://goo.gl/forms/dDkx8yxbMC2aKHJb2?embedded=true" width="80%" height="1200px" frameborder="0" marginheight="0" marginwidth="0"> Loading... </iframe> ) Explanation: Assignment wrapup Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credit for the assignment! End of explanation
5,377
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Land MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Conservation Properties 3. Key Properties --&gt; Timestepping Framework 4. Key Properties --&gt; Software Properties 5. Grid 6. Grid --&gt; Horizontal 7. Grid --&gt; Vertical 8. Soil 9. Soil --&gt; Soil Map 10. Soil --&gt; Snow Free Albedo 11. Soil --&gt; Hydrology 12. Soil --&gt; Hydrology --&gt; Freezing 13. Soil --&gt; Hydrology --&gt; Drainage 14. Soil --&gt; Heat Treatment 15. Snow 16. Snow --&gt; Snow Albedo 17. Vegetation 18. Energy Balance 19. Carbon Cycle 20. Carbon Cycle --&gt; Vegetation 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality 26. Carbon Cycle --&gt; Litter 27. Carbon Cycle --&gt; Soil 28. Carbon Cycle --&gt; Permafrost Carbon 29. Nitrogen Cycle 30. River Routing 31. River Routing --&gt; Oceanic Discharge 32. Lakes 33. Lakes --&gt; Method 34. Lakes --&gt; Wetlands 1. Key Properties Land surface key properties 1.1. Model Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Description Is Required Step7: 1.4. Land Atmosphere Flux Exchanges Is Required Step8: 1.5. Atmospheric Coupling Treatment Is Required Step9: 1.6. Land Cover Is Required Step10: 1.7. Land Cover Change Is Required Step11: 1.8. Tiling Is Required Step12: 2. Key Properties --&gt; Conservation Properties TODO 2.1. Energy Is Required Step13: 2.2. Water Is Required Step14: 2.3. Carbon Is Required Step15: 3. Key Properties --&gt; Timestepping Framework TODO 3.1. Timestep Dependent On Atmosphere Is Required Step16: 3.2. Time Step Is Required Step17: 3.3. Timestepping Method Is Required Step18: 4. Key Properties --&gt; Software Properties Software properties of land surface code 4.1. Repository Is Required Step19: 4.2. Code Version Is Required Step20: 4.3. Code Languages Is Required Step21: 5. Grid Land surface grid 5.1. Overview Is Required Step22: 6. Grid --&gt; Horizontal The horizontal grid in the land surface 6.1. Description Is Required Step23: 6.2. Matches Atmosphere Grid Is Required Step24: 7. Grid --&gt; Vertical The vertical grid in the soil 7.1. Description Is Required Step25: 7.2. Total Depth Is Required Step26: 8. Soil Land surface soil 8.1. Overview Is Required Step27: 8.2. Heat Water Coupling Is Required Step28: 8.3. Number Of Soil layers Is Required Step29: 8.4. Prognostic Variables Is Required Step30: 9. Soil --&gt; Soil Map Key properties of the land surface soil map 9.1. Description Is Required Step31: 9.2. Structure Is Required Step32: 9.3. Texture Is Required Step33: 9.4. Organic Matter Is Required Step34: 9.5. Albedo Is Required Step35: 9.6. Water Table Is Required Step36: 9.7. Continuously Varying Soil Depth Is Required Step37: 9.8. Soil Depth Is Required Step38: 10. Soil --&gt; Snow Free Albedo TODO 10.1. Prognostic Is Required Step39: 10.2. Functions Is Required Step40: 10.3. Direct Diffuse Is Required Step41: 10.4. Number Of Wavelength Bands Is Required Step42: 11. Soil --&gt; Hydrology Key properties of the land surface soil hydrology 11.1. Description Is Required Step43: 11.2. Time Step Is Required Step44: 11.3. Tiling Is Required Step45: 11.4. Vertical Discretisation Is Required Step46: 11.5. Number Of Ground Water Layers Is Required Step47: 11.6. Lateral Connectivity Is Required Step48: 11.7. Method Is Required Step49: 12. Soil --&gt; Hydrology --&gt; Freezing TODO 12.1. Number Of Ground Ice Layers Is Required Step50: 12.2. Ice Storage Method Is Required Step51: 12.3. Permafrost Is Required Step52: 13. Soil --&gt; Hydrology --&gt; Drainage TODO 13.1. Description Is Required Step53: 13.2. Types Is Required Step54: 14. Soil --&gt; Heat Treatment TODO 14.1. Description Is Required Step55: 14.2. Time Step Is Required Step56: 14.3. Tiling Is Required Step57: 14.4. Vertical Discretisation Is Required Step58: 14.5. Heat Storage Is Required Step59: 14.6. Processes Is Required Step60: 15. Snow Land surface snow 15.1. Overview Is Required Step61: 15.2. Tiling Is Required Step62: 15.3. Number Of Snow Layers Is Required Step63: 15.4. Density Is Required Step64: 15.5. Water Equivalent Is Required Step65: 15.6. Heat Content Is Required Step66: 15.7. Temperature Is Required Step67: 15.8. Liquid Water Content Is Required Step68: 15.9. Snow Cover Fractions Is Required Step69: 15.10. Processes Is Required Step70: 15.11. Prognostic Variables Is Required Step71: 16. Snow --&gt; Snow Albedo TODO 16.1. Type Is Required Step72: 16.2. Functions Is Required Step73: 17. Vegetation Land surface vegetation 17.1. Overview Is Required Step74: 17.2. Time Step Is Required Step75: 17.3. Dynamic Vegetation Is Required Step76: 17.4. Tiling Is Required Step77: 17.5. Vegetation Representation Is Required Step78: 17.6. Vegetation Types Is Required Step79: 17.7. Biome Types Is Required Step80: 17.8. Vegetation Time Variation Is Required Step81: 17.9. Vegetation Map Is Required Step82: 17.10. Interception Is Required Step83: 17.11. Phenology Is Required Step84: 17.12. Phenology Description Is Required Step85: 17.13. Leaf Area Index Is Required Step86: 17.14. Leaf Area Index Description Is Required Step87: 17.15. Biomass Is Required Step88: 17.16. Biomass Description Is Required Step89: 17.17. Biogeography Is Required Step90: 17.18. Biogeography Description Is Required Step91: 17.19. Stomatal Resistance Is Required Step92: 17.20. Stomatal Resistance Description Is Required Step93: 17.21. Prognostic Variables Is Required Step94: 18. Energy Balance Land surface energy balance 18.1. Overview Is Required Step95: 18.2. Tiling Is Required Step96: 18.3. Number Of Surface Temperatures Is Required Step97: 18.4. Evaporation Is Required Step98: 18.5. Processes Is Required Step99: 19. Carbon Cycle Land surface carbon cycle 19.1. Overview Is Required Step100: 19.2. Tiling Is Required Step101: 19.3. Time Step Is Required Step102: 19.4. Anthropogenic Carbon Is Required Step103: 19.5. Prognostic Variables Is Required Step104: 20. Carbon Cycle --&gt; Vegetation TODO 20.1. Number Of Carbon Pools Is Required Step105: 20.2. Carbon Pools Is Required Step106: 20.3. Forest Stand Dynamics Is Required Step107: 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis TODO 21.1. Method Is Required Step108: 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration TODO 22.1. Maintainance Respiration Is Required Step109: 22.2. Growth Respiration Is Required Step110: 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation TODO 23.1. Method Is Required Step111: 23.2. Allocation Bins Is Required Step112: 23.3. Allocation Fractions Is Required Step113: 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology TODO 24.1. Method Is Required Step114: 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality TODO 25.1. Method Is Required Step115: 26. Carbon Cycle --&gt; Litter TODO 26.1. Number Of Carbon Pools Is Required Step116: 26.2. Carbon Pools Is Required Step117: 26.3. Decomposition Is Required Step118: 26.4. Method Is Required Step119: 27. Carbon Cycle --&gt; Soil TODO 27.1. Number Of Carbon Pools Is Required Step120: 27.2. Carbon Pools Is Required Step121: 27.3. Decomposition Is Required Step122: 27.4. Method Is Required Step123: 28. Carbon Cycle --&gt; Permafrost Carbon TODO 28.1. Is Permafrost Included Is Required Step124: 28.2. Emitted Greenhouse Gases Is Required Step125: 28.3. Decomposition Is Required Step126: 28.4. Impact On Soil Properties Is Required Step127: 29. Nitrogen Cycle Land surface nitrogen cycle 29.1. Overview Is Required Step128: 29.2. Tiling Is Required Step129: 29.3. Time Step Is Required Step130: 29.4. Prognostic Variables Is Required Step131: 30. River Routing Land surface river routing 30.1. Overview Is Required Step132: 30.2. Tiling Is Required Step133: 30.3. Time Step Is Required Step134: 30.4. Grid Inherited From Land Surface Is Required Step135: 30.5. Grid Description Is Required Step136: 30.6. Number Of Reservoirs Is Required Step137: 30.7. Water Re Evaporation Is Required Step138: 30.8. Coupled To Atmosphere Is Required Step139: 30.9. Coupled To Land Is Required Step140: 30.10. Quantities Exchanged With Atmosphere Is Required Step141: 30.11. Basin Flow Direction Map Is Required Step142: 30.12. Flooding Is Required Step143: 30.13. Prognostic Variables Is Required Step144: 31. River Routing --&gt; Oceanic Discharge TODO 31.1. Discharge Type Is Required Step145: 31.2. Quantities Transported Is Required Step146: 32. Lakes Land surface lakes 32.1. Overview Is Required Step147: 32.2. Coupling With Rivers Is Required Step148: 32.3. Time Step Is Required Step149: 32.4. Quantities Exchanged With Rivers Is Required Step150: 32.5. Vertical Grid Is Required Step151: 32.6. Prognostic Variables Is Required Step152: 33. Lakes --&gt; Method TODO 33.1. Ice Treatment Is Required Step153: 33.2. Albedo Is Required Step154: 33.3. Dynamics Is Required Step155: 33.4. Dynamic Lake Extent Is Required Step156: 33.5. Endorheic Basins Is Required Step157: 34. Lakes --&gt; Wetlands TODO 34.1. Description Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-hr5', 'land') Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-HR5 Topic: Land Sub-Topics: Soil, Snow, Vegetation, Energy Balance, Carbon Cycle, Nitrogen Cycle, River Routing, Lakes. Properties: 154 (96 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:50 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Conservation Properties 3. Key Properties --&gt; Timestepping Framework 4. Key Properties --&gt; Software Properties 5. Grid 6. Grid --&gt; Horizontal 7. Grid --&gt; Vertical 8. Soil 9. Soil --&gt; Soil Map 10. Soil --&gt; Snow Free Albedo 11. Soil --&gt; Hydrology 12. Soil --&gt; Hydrology --&gt; Freezing 13. Soil --&gt; Hydrology --&gt; Drainage 14. Soil --&gt; Heat Treatment 15. Snow 16. Snow --&gt; Snow Albedo 17. Vegetation 18. Energy Balance 19. Carbon Cycle 20. Carbon Cycle --&gt; Vegetation 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality 26. Carbon Cycle --&gt; Litter 27. Carbon Cycle --&gt; Soil 28. Carbon Cycle --&gt; Permafrost Carbon 29. Nitrogen Cycle 30. River Routing 31. River Routing --&gt; Oceanic Discharge 32. Lakes 33. Lakes --&gt; Method 34. Lakes --&gt; Wetlands 1. Key Properties Land surface key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of land surface model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of land surface model code (e.g. MOSES2.2) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.3. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of the processes modelled (e.g. dymanic vegation, prognostic albedo, etc.) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_atmosphere_flux_exchanges') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "water" # "energy" # "carbon" # "nitrogen" # "phospherous" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.4. Land Atmosphere Flux Exchanges Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Fluxes exchanged with the atmopshere. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.atmospheric_coupling_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.5. Atmospheric Coupling Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe 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) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_cover') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bare soil" # "urban" # "lake" # "land ice" # "lake ice" # "vegetated" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.6. Land Cover Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Types of land cover defined in the land surface model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.land_cover_change') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.7. Land Cover Change Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe how land cover change is managed (e.g. the use of net or gross transitions) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.8. Tiling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general tiling procedure used in the land surface (if any). Include treatment of physiography, land/sea, (dynamic) vegetation coverage and orography/roughness End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.energy') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Conservation Properties TODO 2.1. Energy Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how energy is conserved globally and to what level (e.g. within X [units]/year) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.water') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.2. Water Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how water is conserved globally and to what level (e.g. within X [units]/year) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.conservation_properties.carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.3. Carbon Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how carbon is conserved globally and to what level (e.g. within X [units]/year) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestep_dependent_on_atmosphere') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 3. Key Properties --&gt; Timestepping Framework TODO 3.1. Timestep Dependent On Atmosphere Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is a time step dependent on the frequency of atmosphere coupling? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 3.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overall timestep of land surface model (i.e. time between calls) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.timestepping_framework.timestepping_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.3. Timestepping Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of time stepping method and associated time step(s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4. Key Properties --&gt; Software Properties Software properties of land surface code 4.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5. Grid Land surface grid 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the grid in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.horizontal.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6. Grid --&gt; Horizontal The horizontal grid in the land surface 6.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the horizontal grid (not including any tiling) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.horizontal.matches_atmosphere_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.2. Matches Atmosphere Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the horizontal grid match the atmosphere? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.vertical.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7. Grid --&gt; Vertical The vertical grid in the soil 7.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general structure of the vertical grid in the soil (not including any tiling) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.grid.vertical.total_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 7.2. Total Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The total depth of the soil (in metres) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Soil Land surface soil 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of soil in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_water_coupling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.2. Heat Water Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the coupling between heat and water in the soil End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.number_of_soil layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 8.3. Number Of Soil layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of soil layers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the soil scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9. Soil --&gt; Soil Map Key properties of the land surface soil map 9.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of soil map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.structure') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.2. Structure Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil structure map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.texture') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.3. Texture Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil texture map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.organic_matter') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.4. Organic Matter Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil organic matter map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.albedo') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.5. Albedo Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil albedo map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.water_table') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.6. Water Table Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil water table map, if any End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.continuously_varying_soil_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 9.7. Continuously Varying Soil Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the soil properties vary continuously with depth? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.soil_map.soil_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.8. Soil Depth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil depth map End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 10. Soil --&gt; Snow Free Albedo TODO 10.1. Prognostic Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is snow free albedo prognostic? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.functions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation type" # "soil humidity" # "vegetation state" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.2. Functions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If prognostic, describe the dependancies on snow free albedo calculations End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.direct_diffuse') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "distinction between direct and diffuse albedo" # "no distinction between direct and diffuse albedo" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.3. Direct Diffuse Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, describe the distinction between direct and diffuse albedo End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.snow_free_albedo.number_of_wavelength_bands') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 10.4. Number Of Wavelength Bands Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, enter the number of wavelength bands used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 11. Soil --&gt; Hydrology Key properties of the land surface soil hydrology 11.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of the soil hydrological model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 11.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of river soil hydrology in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 11.3. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil hydrology tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.vertical_discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 11.4. Vertical Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the typical vertical discretisation End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.number_of_ground_water_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 11.5. Number Of Ground Water Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of soil layers that may contain water End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.lateral_connectivity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "perfect connectivity" # "Darcian flow" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.6. Lateral Connectivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe the lateral connectivity between tiles End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Bucket" # "Force-restore" # "Choisnel" # "Explicit diffusion" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.7. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The hydrological dynamics scheme in the land surface model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.number_of_ground_ice_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 12. Soil --&gt; Hydrology --&gt; Freezing TODO 12.1. Number Of Ground Ice Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How many soil layers may contain ground ice End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.ice_storage_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 12.2. Ice Storage Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the method of ice storage End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.freezing.permafrost') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 12.3. Permafrost Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of permafrost, if any, within the land surface scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.drainage.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 13. Soil --&gt; Hydrology --&gt; Drainage TODO 13.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General describe how drainage is included in the land surface scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.hydrology.drainage.types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Gravity drainage" # "Horton mechanism" # "topmodel-based" # "Dunne mechanism" # "Lateral subsurface flow" # "Baseflow from groundwater" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.2. Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Different types of runoff represented by the land surface model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 14. Soil --&gt; Heat Treatment TODO 14.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description of how heat treatment properties are defined End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 14.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of soil heat scheme in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 14.3. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the soil heat treatment tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.vertical_discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 14.4. Vertical Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the typical vertical discretisation End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.heat_storage') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Force-restore" # "Explicit diffusion" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 14.5. Heat Storage Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the method of heat storage End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.soil.heat_treatment.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "soil moisture freeze-thaw" # "coupling with snow temperature" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 14.6. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe processes included in the treatment of soil heat End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 15. Snow Land surface snow 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of snow in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 15.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the snow tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.number_of_snow_layers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 15.3. Number Of Snow Layers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The number of snow levels used in the land surface scheme/model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.density') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "constant" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.4. Density Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow density End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.water_equivalent') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.5. Water Equivalent Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of the snow water equivalent End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.heat_content') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.6. Heat Content Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of the heat content of snow End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.temperature') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.7. Temperature Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow temperature End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.liquid_water_content') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.8. Liquid Water Content Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of the treatment of snow liquid water End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_cover_fractions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "ground snow fraction" # "vegetation snow fraction" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.9. Snow Cover Fractions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify cover fractions used in the surface snow scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "snow interception" # "snow melting" # "snow freezing" # "blowing snow" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.10. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Snow related processes in the land surface scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 15.11. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the snow scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_albedo.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "prescribed" # "constant" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 16. Snow --&gt; Snow Albedo TODO 16.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of snow-covered land albedo End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.snow.snow_albedo.functions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation type" # "snow age" # "snow density" # "snow grain type" # "aerosol deposition" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 16.2. Functions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N *If prognostic, * End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17. Vegetation Land surface vegetation 17.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of vegetation in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 17.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of vegetation scheme in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.dynamic_vegetation') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 17.3. Dynamic Vegetation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there dynamic evolution of vegetation? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.4. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the vegetation tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_representation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "vegetation types" # "biome types" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.5. Vegetation Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Vegetation classification used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "broadleaf tree" # "needleleaf tree" # "C3 grass" # "C4 grass" # "vegetated" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.6. Vegetation Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of vegetation types in the classification, if any End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biome_types') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "evergreen needleleaf forest" # "evergreen broadleaf forest" # "deciduous needleleaf forest" # "deciduous broadleaf forest" # "mixed forest" # "woodland" # "wooded grassland" # "closed shrubland" # "opne shrubland" # "grassland" # "cropland" # "wetlands" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.7. Biome Types Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of biome types in the classification, if any End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_time_variation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed (not varying)" # "prescribed (varying from files)" # "dynamical (varying from simulation)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.8. Vegetation Time Variation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How the vegetation fractions in each tile are varying with time End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.vegetation_map') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.9. Vegetation Map Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If vegetation fractions are not dynamically updated , describe the vegetation map used (common name and reference, if possible) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.interception') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 17.10. Interception Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is vegetation interception of rainwater represented? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.phenology') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic (vegetation map)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.11. Phenology Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation phenology End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.phenology_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.12. Phenology Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation phenology End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.leaf_area_index') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prescribed" # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.13. Leaf Area Index Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation leaf area index End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.leaf_area_index_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.14. Leaf Area Index Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of leaf area index End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biomass') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.15. Biomass Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 *Treatment of vegetation biomass * End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biomass_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.16. Biomass Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation biomass End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biogeography') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.17. Biogeography Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Treatment of vegetation biogeography End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.biogeography_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.18. Biogeography Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation biogeography End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.stomatal_resistance') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "light" # "temperature" # "water availability" # "CO2" # "O3" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.19. Stomatal Resistance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify what the vegetation stomatal resistance depends on End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.stomatal_resistance_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.20. Stomatal Resistance Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of the treatment of vegetation stomatal resistance End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.vegetation.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17.21. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the vegetation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 18. Energy Balance Land surface energy balance 18.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of energy balance in land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 18.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the energy balance tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.number_of_surface_temperatures') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 18.3. Number Of Surface Temperatures Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The maximum number of distinct surface temperatures in a grid cell (for example, each subgrid tile may have its own temperature) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.evaporation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "alpha" # "beta" # "combined" # "Monteith potential evaporation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 18.4. Evaporation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify the formulation method for land surface evaporation, from soil and vegetation End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.energy_balance.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "transpiration" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 18.5. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Describe which processes are included in the energy balance scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 19. Carbon Cycle Land surface carbon cycle 19.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of carbon cycle in land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 19.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the carbon cycle tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 19.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of carbon cycle in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.anthropogenic_carbon') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "grand slam protocol" # "residence time" # "decay time" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 19.4. Anthropogenic Carbon Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Describe the treament of the anthropogenic carbon pool End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 19.5. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the carbon scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 20. Carbon Cycle --&gt; Vegetation TODO 20.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 20.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.forest_stand_dynamics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 20.3. Forest Stand Dynamics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the treatment of forest stand dyanmics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.photosynthesis.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 21. Carbon Cycle --&gt; Vegetation --&gt; Photosynthesis TODO 21.1. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for photosynthesis (e.g. type of photosynthesis, distinction between C3 and C4 grasses, Nitrogen depencence, etc.) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.maintainance_respiration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 22. Carbon Cycle --&gt; Vegetation --&gt; Autotrophic Respiration TODO 22.1. Maintainance Respiration Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for maintainence respiration End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.autotrophic_respiration.growth_respiration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 22.2. Growth Respiration Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the general method used for growth respiration End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 23. Carbon Cycle --&gt; Vegetation --&gt; Allocation TODO 23.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the allocation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_bins') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "leaves + stems + roots" # "leaves + stems + roots (leafy + woody)" # "leaves + fine roots + coarse roots + stems" # "whole plant (no distinction)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23.2. Allocation Bins Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify distinct carbon bins used in allocation End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.allocation.allocation_fractions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "function of vegetation type" # "function of plant allometry" # "explicitly calculated" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23.3. Allocation Fractions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how the fractions of allocation are calculated End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.phenology.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 24. Carbon Cycle --&gt; Vegetation --&gt; Phenology TODO 24.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the phenology scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.vegetation.mortality.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 25. Carbon Cycle --&gt; Vegetation --&gt; Mortality TODO 25.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the general principle behind the mortality scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 26. Carbon Cycle --&gt; Litter TODO 26.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 26.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 26.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.litter.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 26.4. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the general method used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.number_of_carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 27. Carbon Cycle --&gt; Soil TODO 27.1. Number Of Carbon Pools Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.carbon_pools') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 27.2. Carbon Pools Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the carbon pools used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 27.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.soil.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 27.4. Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the general method used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.is_permafrost_included') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 28. Carbon Cycle --&gt; Permafrost Carbon TODO 28.1. Is Permafrost Included Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is permafrost included? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.emitted_greenhouse_gases') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 28.2. Emitted Greenhouse Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the GHGs emitted End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.decomposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 28.3. Decomposition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List the decomposition methods used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.carbon_cycle.permafrost_carbon.impact_on_soil_properties') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 28.4. Impact On Soil Properties Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the impact of permafrost on soil properties End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 29. Nitrogen Cycle Land surface nitrogen cycle 29.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the nitrogen cycle in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 29.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the notrogen cycle tiling, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 29.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of nitrogen cycle in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.nitrogen_cycle.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 29.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the nitrogen scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30. River Routing Land surface river routing 30.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of river routing in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.tiling') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.2. Tiling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the river routing, if any. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 30.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of river routing scheme in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.grid_inherited_from_land_surface') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 30.4. Grid Inherited From Land Surface Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the grid inherited from land surface? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.grid_description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.5. Grid Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 General description of grid, if not inherited from land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.number_of_reservoirs') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 30.6. Number Of Reservoirs Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Enter the number of reservoirs End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.water_re_evaporation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "flood plains" # "irrigation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30.7. Water Re Evaporation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N TODO End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.coupled_to_atmosphere') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 30.8. Coupled To Atmosphere Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Is river routing coupled to the atmosphere model component? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.coupled_to_land') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.9. Coupled To Land Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the coupling between land and rivers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.quantities_exchanged_with_atmosphere') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30.10. Quantities Exchanged With Atmosphere Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If couple to atmosphere, which quantities are exchanged between river routing and the atmosphere model components? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.basin_flow_direction_map') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "present day" # "adapted for other periods" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30.11. Basin Flow Direction Map Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 What type of basin flow direction map is being used? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.flooding') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.12. Flooding Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the representation of flooding, if any End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.13. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the river routing End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.oceanic_discharge.discharge_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "direct (large rivers)" # "diffuse" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31. River Routing --&gt; Oceanic Discharge TODO 31.1. Discharge Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify how rivers are discharged to the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.river_routing.oceanic_discharge.quantities_transported') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31.2. Quantities Transported Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Quantities that are exchanged from river-routing to the ocean model component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 32. Lakes Land surface lakes 32.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of lakes in the land surface End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.coupling_with_rivers') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 32.2. Coupling With Rivers Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are lakes coupled to the river routing model component? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 32.3. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time step of lake scheme in seconds End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.quantities_exchanged_with_rivers') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "heat" # "water" # "tracers" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 32.4. Quantities Exchanged With Rivers Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If coupling with rivers, which quantities are exchanged between the lakes and rivers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.vertical_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 32.5. Vertical Grid Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the vertical grid of lakes End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 32.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 List the prognostic variables of the lake scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.ice_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 33. Lakes --&gt; Method TODO 33.1. Ice Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is lake ice included? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.albedo') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 33.2. Albedo Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of lake albedo End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.dynamics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "No lake dynamics" # "vertical" # "horizontal" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 33.3. Dynamics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which dynamics of lakes are treated? horizontal, vertical, etc. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.dynamic_lake_extent') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 33.4. Dynamic Lake Extent Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is a dynamic lake extent scheme included? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.method.endorheic_basins') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 33.5. Endorheic Basins Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Basins not flowing to ocean included? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.land.lakes.wetlands.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 34. Lakes --&gt; Wetlands TODO 34.1. Description Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the treatment of wetlands, if any End of explanation
5,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Imports Step1: Useful functions Step2: Reading the data Step3: Analysis of coverage Step4: Diversity plot Step5: Positions that increase in frequency in the different replicates and conditions Step6: Plotting only positions that consistently rise in frequency Step7: Write out the table Step8: Analysis of positions whose frequency varies a lot Step9: Other selection method We want to select all the positions in which the minor variant reaches >0.1 in at least two time points, in two different replicates or experiments. To do so, we get the variant at time point 0, then we look at the following time points and see if one site has some minor variant >0.1 in 2 time points. We collect all the sites with this characteristic for this experiment. We do this for all experiments, then we take all sites that appear at least twice. Step10: Analysis of positions 1670 and 2193 Step11: Focus on the 7 mutations that have been declared of interest
Python Code: from collections import Counter import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as mticker from pylab import rcParams import seaborn as sns from array import array import numpy as np from scipy.stats import ttest_ind from scipy.stats import linregress from scipy.stats import mannwhitneyu import statistics %matplotlib inline Explanation: Imports End of explanation begins=[] ends=[] names =[] with open ("CommonData/sequence.gb") as f: in_pep = False for l in f: if "mat_peptide" in l: begins.append(int(l.split()[1].split("..")[0])) ends.append(int(l.split()[1].split("..")[1])) in_pep = True elif in_pep : names.append(l.split("=")[1]) in_pep = False print(begins) print(ends) print(names) # Interesting positions positions=[316,1670,1785,2340,5935,7172,8449,9165] def plot_positions(): for x in positions: plt.axvline(x=x, linewidth=1, linestyle=':') def plot_genes(): for i in range(len(begins)): plt.plot([begins[i], begins[i]], [0.99,1.0], linewidth=2, linestyle='-', color="black") if i%2==0: plt.text (begins[i] + ((ends[i] - begins[i])/10), 1.005, (names[i].replace('"', ''))[0:3], size='xx-small') else: plt.text (begins[i] + ((ends[i] - begins[i])/10), 1.015, (names[i].replace('"', ''))[0:3], size='xx-small') plt.plot([ends[-1], ends[-1]], [0.99,1.0], linewidth=2, linestyle='-', color="black") def synonymous (row): if row['null'] or (row['Consensus_aa']==row['Secondbase_aa'] ): return "synonymous" else: return "non-synonymous" def add_columns(table): table['null'] = (table['Secondbase_aa']).isnull() table['is_synonymous'] = table.apply (lambda row: synonymous (row),axis=1) table['1_major_variant_frequency'] = 1.0 - table['Major_variant_frequency_quality_corrected'] def is_increasing(minor_frequencies): #print(minor_frequencies) tolerance = 0.01 minimum_increase = 0.1 previous = minor_frequencies[0] if minor_frequencies[-1] - minor_frequencies[0] < minimum_increase: return False for m in range(1,len(minor_frequencies)): if previous < minor_frequencies[m] or previous < minor_frequencies[m] + tolerance: #print(str(previous) + " < " + str(minor_frequencies[m])) previous = minor_frequencies[m] else: return False return True # Strict definition of an increasing position def is_strictly_increasing(minor_frequencies): #print(minor_frequencies) previous = minor_frequencies[0] for m in range(1,len(minor_frequencies)): if previous < minor_frequencies[m]: #print(str(previous) + " < " + str(minor_frequencies[m])) previous = minor_frequencies[m] else: return False return True def get_variant_frequency(variant, table, i): sum_of_bases = table['As_quality_corrected'][i]+table['Cs_quality_corrected'][i]+table['Gs_quality_corrected'][i]+table['Ts_quality_corrected'][i]+table['Ns_quality_corrected'][i] if variant == "A": return table["As_quality_corrected"][i] / sum_of_bases elif variant == "C": return table["Cs_quality_corrected"][i] / sum_of_bases elif variant == "G": return table["Gs_quality_corrected"][i] / sum_of_bases elif variant == "T": return table["Ts_quality_corrected"][i] / sum_of_bases else: return np.nan def get_increasing_variants(tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) minor_frequencies = array('d',[0.0]*num_tables) increasingVariants = dict() for i in first["Position"]: major = first["Major_variant"][i] #print(last['Major_variant_frequency_quality_corrected'][i]) major_frequencies[0] = first['Major_variant_frequency_quality_corrected'][i] if major == last["Major_variant"][i]: minor = last["Second_variant"][i] else: minor = last["Major_variant"][i] minor_frequencies[0] = get_variant_frequency(minor, first, i) for table_id in range(1, num_tables): major_frequencies[table_id] = get_variant_frequency(major, tables[table_id], i) minor_frequencies[table_id] = get_variant_frequency(minor, tables[table_id], i) if is_increasing(minor_frequencies): increasingVariants[i] = [major_frequencies.tolist(), minor_frequencies.tolist()] return increasingVariants def printMajorFrequencyThroughSamples(tables, numPos): major = tables[0]['Major_variant'][numPos] last_major = tables[0]['Major_variant'][numPos] print("Position "+ str(numPos) +", Major variant in first sample: " + major) print("Position "+ str(numPos) +", Frequencies of "+major+" through the samples: ") for i in range(len(tables)): print("\t"+str(get_variant_frequency(major, tables[i], numPos))) print("Position "+ str(numPos) +", Major variant in last sample: " + tables[-1]['Major_variant'][numPos]) def printMajorFrequencyThroughSamples_2340_7172(tables): printMajorFrequencyThroughSamples(tables, 2340) printMajorFrequencyThroughSamples(tables, 7172) # Functions to think in terms of standard deviation of the frequency per site def get_varying_variants(tables): sd_threshold = 0.1 num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) minor_frequencies = array('d',[0.0]*num_tables) varyingVariants = dict() for i in first["Position"]: major = first["Major_variant"][i] #print(last['Major_variant_frequency_quality_corrected'][i]) major_frequencies[0] = first['Major_variant_frequency_quality_corrected'][i] for table_id in range(1, num_tables): major_frequencies[table_id] = get_variant_frequency(major, tables[table_id], i) sd_value = statistics.pstdev(major_frequencies) if sd_value > sd_threshold: varyingVariants[i] = sd_value print("There are "+str(len(varyingVariants))+" positions whose major variant varies a lot in frequency.") print("Those are:") print(varyingVariants.keys()) return varyingVariants Explanation: Useful functions End of explanation # Cirseq and clones cirseq = pd.read_csv ("PKG-DREUX_HV5GLBCXY/CutAdaptPearViroMapperMapped/HV5GLBCXY_ZIKV_17s006139-1-1_DREUX_lane1CirseqD3_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(cirseq) clone_12 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD12_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_12) clone_15 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD15_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_15) clone_19 = pd.read_csv ("HJJ7JBCX2_ZIKV/Mapped_Reads/HJJ7JBCX2_ZIKV-s-and-c_18s004258-1-1_DREUX_lane1cloneD19_1_sequence.txt.assembled.fastq_mapped_AA.csv", na_values=" -nan") add_columns(clone_19) tables_clone = [cirseq, clone_12, clone_15, clone_19] # All tables all_table_names = ["cirseq", "clone_12", "clone_15", "clone_19"] Explanation: Reading the data End of explanation def plotCoverage(tables, names): variable = 'Coverage' sample = list() posList = list() variableList = list() for i in range(len(names)): sample = sample + len(tables[i][variable]) * [names[i]] posList.append(tables[i]['Position']) variableList.append(tables[i][variable]) positions = pd.concat(posList) variableValues = pd.concat(variableList) overlay_table_concat = pd.DataFrame ({'Position':positions, variable:variableValues, 'sample':sample}) sns.lmplot( x="Position", y=variable, data=overlay_table_concat, fit_reg=False, hue='sample', legend=False, size=7, aspect=2, lowess=True,scatter_kws={"s": 20}) plt.legend(loc='lower right') plot_positions() plot_genes() plotCoverage(tables_clone, all_table_names) Explanation: Analysis of coverage End of explanation f, ax = plt.subplots(figsize=(15, 7)) lm=sns.kdeplot(np.log(tables_clone[0]["1_major_variant_frequency"]), label="cirseq") lm.set_ylabel('Density') lm.set_xlabel('Logarithm of the diversity per position') lm=sns.kdeplot(np.log(tables_clone[1]["1_major_variant_frequency"]), label="clone_12") lm=sns.kdeplot(np.log(tables_clone[2]["1_major_variant_frequency"]), label="clone_15") lm=sns.kdeplot(np.log(tables_clone[3]["1_major_variant_frequency"]), label="clone_19") axes = lm.axes axes.set_xlim(-8,-4) axes.set_ylim(0,1.2) Explanation: Diversity plot End of explanation increasing = get_increasing_variants(tables_clone) print("There are "+str(len(increasing))+" positions that rise in frequency.") print("Those are:") print(increasing.keys()) Explanation: Positions that increase in frequency in the different replicates and conditions End of explanation def plot_increasing_positions(increasing_pos, last_time_point) : sns.set_palette("hls") sns.set_context("poster") increasing_pos_keys = increasing_pos.keys() Is_increasing = [] for i in last_time_point['Position']: if i in increasing_pos_keys: Is_increasing.append("Increasing") else: Is_increasing.append("Not increasing") to_plot = pd.DataFrame ({'Position':last_time_point['Position'], 'Major_variant_frequency_quality_corrected':last_time_point ['Major_variant_frequency_quality_corrected'],'Is_increasing':Is_increasing, 'is_synonymous':last_time_point ['is_synonymous']}) ax=sns.lmplot( x="Position", y="Major_variant_frequency_quality_corrected", data=to_plot, fit_reg=False, hue='Is_increasing', row='is_synonymous', legend=False, size=7, aspect=2) ax.set(xlabel='Position along the genome', ylabel='Major variant frequency, last time point') plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plot_positions() plot_increasing_positions(increasing, clone_19) Explanation: Plotting only positions that consistently rise in frequency End of explanation def write_increasing_positions(increasing_pos, tables, exp_names, filename) : increasing_pos_table = pd.DataFrame() for d in tables: increasing_pos_table = pd.concat([increasing_pos_table,d[d['Position'].isin(increasing_pos)]]) num = len(increasing_pos) expnames_iterated = [] for i in exp_names : expnames_iterated.append([i]*num) expnames = [item for sublist in expnames_iterated for item in sublist] print(len(expnames)) increasing_pos_table['expName']=expnames increasing_pos_table.to_csv( filename ) write_increasing_positions(increasing, tables_clone, all_table_names, "increasing_clone.csv") printMajorFrequencyThroughSamples_2340_7172(tables_clone) Explanation: Write out the table End of explanation varying_clone = get_varying_variants(tables_clone) # Output positions of interest based on this analysis varying_pos = [253, 322, 418, 910, 926, 1043, 1312, 1474, 1903, 2340, 2455, 2783, 2852, 2903, 3565, 3592, 4192, 4201, 4552, 5125, 5155, 5230, 5314, 5675, 6334, 6628, 6670, 6991, 7093, 7228, 7441, 7636, 8093, 8410, 8776, 9025, 9241, 9295, 9556, 9736, 9952] write_increasing_positions(varying_pos, tables_clone, all_table_names, "varying_positions_clone_samples.csv") Explanation: Analysis of positions whose frequency varies a lot End of explanation def getInterestingVariants (tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) interestingVariants = list() for i in first["Position"]: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) if minor_frequencies[j] > 0.1: counter += 1 if counter >=2: interestingVariants.append(i) return interestingVariants interesting_clone = getInterestingVariants (tables_clone) interesting_clone for_output = [322, 418, 1043, 1312, 1474, 1903, 2340, 2455, 2783, 2852, 2903, 3565, 3592, 4192, 4201, 4552, 5125, 5155, 5230, 5314, 5675, 6334, 6628, 6670, 6991, 7093, 7228, 7441, 7636, 8093, 8410, 8776, 9025, 9241, 9295, 9556, 9736, 9952, 10801, 10802, 10803, 10804, 10805] write_increasing_positions(for_output, tables_clone, all_table_names, "positions_morethan01_clone_samples.csv") Explanation: Other selection method We want to select all the positions in which the minor variant reaches >0.1 in at least two time points, in two different replicates or experiments. To do so, we get the variant at time point 0, then we look at the following time points and see if one site has some minor variant >0.1 in 2 time points. We collect all the sites with this characteristic for this experiment. We do this for all experiments, then we take all sites that appear at least twice. End of explanation def test_positions (tables, positions): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) for i in positions: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 print(str(i)+" : ") for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) print("\texp "+str(j) +", variant "+minor + " : "+str(minor_frequencies[j])) if minor_frequencies[j] > 0.1: counter += 1 print("Counter of times > 0.1: "+ str(counter)) return def test_positions_1670_2193 (tables): test_positions(tables, [1670,2193]) return def test1670_2193 (tables): num_tables = len(tables) first = tables[0] last = tables[num_tables-1] major = "" minor = "" major_frequencies = array('d',[0.0]*num_tables) for i in [1670,2193]: minor_frequencies = array('d',[0.0]*num_tables) major = first["Major_variant"][i] minor = tables[-1]["Second_variant"][i] if minor == major: minor = tables[-1]["Major_variant"][i] counter = 0 print(str(i)+" : ") for j in range(num_tables): minor_frequencies[j] = get_variant_frequency(minor, tables[j], i) print("\texp "+str(j) +", variant "+minor + " : "+str(minor_frequencies[j])) if minor_frequencies[j] > 0.1: counter += 1 print("Counter of times > 0.1: "+ str(counter)) return test_positions_1670_2193 (tables_clone) Explanation: Analysis of positions 1670 and 2193 End of explanation #positions=[316, 1785, 2340, 5662, 5935, 8449, 10006 ] positions = [1670, 1785, 2193, 2340, 5662, 7172, 10006] test_positions (tables_clone, positions) write_increasing_positions(positions, tables_clone, all_table_names, "positions_7_interesting_clone_samples.csv") Explanation: Focus on the 7 mutations that have been declared of interest End of explanation
5,379
Given the following text description, write Python code to implement the functionality described below step by step Description: COLOP in Spectral Blueing Mode IPython notebook to calculate operator for spectral blueing using seismic amplitude spectrum and well AI spectrum exported from OpendTect. First sample of the exported seismic amplitude spectrum was edited to be different than zero (0.01Hz), first row of well based AI was deleted as it was 0.00000Hz Standalone windows binary and source codes are available at my Home page Step1: Define the input and output files and input parameters for operator estimation Step2: Load spectrums from input files, and calculate linear regression based on well impedance spectrum on log-log scale Step3: Calculate raw operator, based on the ratio of trend spectrum from wells and normalized seismic amplitude spectrum Step4: Precalculation for inverse dft, to transform raw operator to time domain. First setup a complex amplitude spectrum with the given phase, then calculate ifft and reorder the result.
Python Code: import sys import numpy as np from scipy.stats import linregress import matplotlib.pyplot as plt %matplotlib inline Explanation: COLOP in Spectral Blueing Mode IPython notebook to calculate operator for spectral blueing using seismic amplitude spectrum and well AI spectrum exported from OpendTect. First sample of the exported seismic amplitude spectrum was edited to be different than zero (0.01Hz), first row of well based AI was deleted as it was 0.00000Hz Standalone windows binary and source codes are available at my Home page End of explanation #Input spectrum files seisfile="F2_01_seismic_amplitude_spectrum.dat" wellfile="F2_01_well_AI_amplitude_spectrum.dat" #Shape parameter for Kaiser window beta=150 #Normalized amplitude treshold, smaller amplitudes will be skipped during computation treshold=0.2 #Operator phase spectrum depending on polarity of the seismic data #SEG normal(AI increase = through): phase=0; SEG reverse (AI increase = Peak): phase=180 phase=0 #Number of samples of the operator num=80 #Ouput operator file operatorfile="F2_01_ssb_operator.dat" Explanation: Define the input and output files and input parameters for operator estimation End of explanation #Load exported spectrums from OpendTect freqseis, ampseis=np.loadtxt(seisfile, unpack=True) freqwell, ampwell=np.loadtxt(wellfile, unpack=True) # dB to amplitude conversion ampwell=np.power(10,ampwell/20) ampseis=np.power(10,ampseis/20) #Normalize seismic spectrum normseis = ampseis / np.max(ampseis) #Calculate logarithmic well spectrum logfreq= np.log10(freqwell) logamp=np.log10(ampwell) #Linear regression on logarithmic well spectrum slope, intercept, rvalue, pvalue, stderr = linregress(logfreq,logamp) print ('Regression results:') print ("Intercept:", intercept) print ("Slope :", slope) print ("R-value :", rvalue) #Plot well based AI spectrum with regression line lintrend=intercept+(slope)*logfreq plt.figure(0) plt.title('Well Impedance spectrum') plt.scatter(logfreq,logamp, label="AI impedance spectrum") plt.xlabel("log10(frequency)") plt.ylabel("log10(amplitude)") plt.plot(logfreq,lintrend, label="Trend line", linewidth=3, color='red') plt.xlim(np.min(logfreq),np.max(logfreq)) plt.legend() plt.grid() plt.show() Explanation: Load spectrums from input files, and calculate linear regression based on well impedance spectrum on log-log scale End of explanation #Reflectivity trend well spectrum WelltrendSpectrum = np.power(freqseis,(1+slope)) NormWellTrendSpectrum = WelltrendSpectrum / max(WelltrendSpectrum) #Calculate residual spectrum ResidualSpectrum=np.zeros(len(normseis)) for i in range(len(normseis)): if normseis[i]>treshold: ResidualSpectrum[i]= WelltrendSpectrum[i] / normseis[i] #Normalize residual spectrum ResidualSpectrum=ResidualSpectrum / np.max(ResidualSpectrum) #Plot normalized seismic spectrum with well trend spectrum plt.figure(1) thold=np.ones(len(freqseis)) thold=treshold*thold plt.title('Seismic spectrums') plt.plot(freqseis,normseis, label='Normalized seismic amplitude spectrum') plt.plot(freqseis,NormWellTrendSpectrum, label='Regression based reflectivity spectrum') plt.plot(freqseis,ResidualSpectrum, label='Frequency domain raw operator', color='red') plt.plot(freqseis,thold, label='Amplitude treshold', color='grey') plt.xlabel('Frequency [Hz]') plt.ylabel('Normalized Amplitude') plt.ylim(0,1.5) plt.xlim(0,100) plt.legend() plt.grid() plt.show() Explanation: Calculate raw operator, based on the ratio of trend spectrum from wells and normalized seismic amplitude spectrum End of explanation #Calculate dt dt=1/(2*np.max(freqseis)) #Setup complex amplitude spectrum for ifft with phase assumption cspectrum_poz=ResidualSpectrum*(np.cos(np.radians(phase))+1j*np.sin(np.radians(phase))) cspectrum_neg=ResidualSpectrum*(np.cos(-1*np.radians(phase))+1j*np.sin(-1*np.radians(phase))) rev_cspectrum_neg=np.fliplr([cspectrum_neg])[0] input_cspectrum=np.append(cspectrum_poz,rev_cspectrum_neg) #Calculate ifft and reorder arrays t_op=np.fft.ifft(input_cspectrum) start_t=(-1/2)*dt*(len(input_cspectrum))+dt t_shift=np.linspace(start_t,-1*start_t,len(t_op))-dt/2 t_op_shift=np.fft.ifftshift(t_op) #Tapering of the time domain operator using a Kaiser window, and calculation of the operator triming indexes, and plot the final operator #Tapering window_kaiser=np.kaiser(len(t_shift),beta) t_op_final=t_op_shift*window_kaiser #Operator trimming indexes start_i=((int(len(t_shift)/2))-int(num/2)) stop_i=(int(len(t_shift)/2))+int(num/2)+1 #Plot final time domain operator plt.figure(2) plt.title('Spectral blueing operator') plt.plot(t_shift,t_op_final.real, label='Time domain operator') #plt.fill_between(t_shift, t_op_final.real,0, t_op_final > 0.0, interpolate=False, hold=True, color='blue', alpha = 0.5) plt.xlim(t_shift[start_i],t_shift[stop_i]) plt.ylim(-0.07,0.25) plt.xlabel('Time [s]') plt.ylabel('Amplitude') plt.legend() plt.grid() plt.show() #Save final operator np.savetxt(operatorfile,t_op_final[start_i:stop_i].real) #QC operator by transform tapered operator to frequency domain bt_op=np.fft.fft(t_op_final) backfreq=np.fft.fftfreq(len(t_op_final),dt) #Keeping only the positive frequencies backfreq_poz=backfreq[:int(len(backfreq)/2)] bt_op_poz=bt_op[:int(len(bt_op)/2)] output_spectrum=bt_op_poz*normseis plt.figure(3) plt.title('QC tapering') plt.plot(backfreq_poz,abs(bt_op_poz), label='Tapered backtransformed operator', color='red') plt.plot(freqseis,ResidualSpectrum, label='Frequency domain raw operator') #plt.fill_between(backfreq_poz, abs(bt_op_poz),0, abs(bt_op_poz) > 0.0, interpolate=False, hold=True, color='red', alpha = 0.3) plt.ylabel('Normalized amplitude') plt.xlabel('Frequency (Hz)') plt.xlim(0,100) plt.legend() plt.grid() plt.show() print('Operator is saved to:',operatorfile) Explanation: Precalculation for inverse dft, to transform raw operator to time domain. First setup a complex amplitude spectrum with the given phase, then calculate ifft and reorder the result. End of explanation
5,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Modeling and Simulation in Python Case Study Step1: One queue or two? This notebook presents a solution to an exercise from Modeling and Simulation in Python. It uses features from the first four chapters to answer a question related to queueing theory, which is the study of systems that involve waiting in lines, also known as "queues". Suppose you are designing the checkout area for a new store. There is room for two checkout counters and a waiting area for customers. You can make two lines, one for each counter, or one line that serves both counters. In theory, you might expect a single line to be better, but it has some practical drawbacks Step2: Test this function by creating a System object with lam=1/8 and mu=1/5. Step3: Write an update function that takes as parameters x, which is the total number of customer in the store, including the one checking out; t, which is the number of minutes that have elapsed in the simulation, and system, which is a System object. If there's a customer checking out, it should use flip to decide whether they are done. And it should use flip to decide if a new customer has arrived. It should return the total number of customers at the end of the time step. Step4: Test your function by calling it with x=1, t=0, and the System object you created. If you run it a few times, you should see different results. Step6: Now we can run the simulation. Here's a version of run_simulation that creates a TimeSeries with the total number of customers in the store, including the one checking out. Step7: Call run_simulation with your update function and plot the results. Step9: After the simulation, we can compute L, which is the average number of customers in the system, and W, which is the average time customers spend in the store. L and W are related by Little's Law Step10: Call compute_metrics with the results from your simulation. Step11: Parameter sweep Since we don't know the actual value of $\lambda$, we can sweep through a range of possibilities, from 10% to 80% of the completion rate, $\mu$. (If customers arrive faster than the completion rate, the queue grows without bound. In that case the metrics L and W just depend on how long the store is open.) Create an array of values for lam. Step12: Write a function that takes an array of values for lam, a single value for mu, and an update function. For each value of lam, it should run a simulation, compute L and W, and store the value of W in a SweepSeries. It should return the SweepSeries. Step13: Call your function to generate a SweepSeries, and plot it. Step14: If we imagine that this range of values represents arrival rates on different days, we can use the average value of W, for a range of values of lam, to compare different queueing strategies. Step16: Analysis The model I chose for this system is a common model in queueing theory, in part because many of its properties can be derived analytically. In particular, we can derive the average time in the store as a function of $\mu$ and $\lambda$ Step17: Use this function to plot the theoretical results, then plot your simulation results again on the same graph. How do they compare? Step18: Multiple servers Now let's try the other two queueing strategies Step19: Use this update function to simulate the system, plot the results, and print the metrics. Step20: Since we have two checkout counters now, we can consider values for $\lambda$ that exceed $\mu$. Create a new array of values for lam from 10% to 160% of mu. Step21: Use your sweep function to simulate the two server, one queue scenario with a range of values for lam. Plot the results and print the average value of W across all values of lam. Step22: Multiple queues To simulate the scenario with two separate queues, we need two state variables to keep track of customers in each queue. Write an update function that takes x1, x2, t, and system as parameters and returns x1 and x2 as return values. f you are not sure how to return more than one return value, see compute_metrics. When a customer arrives, which queue do they join? Step23: Write a version of run_simulation that works with this update function. Step24: Test your functions by running a simulation with a single value of lam. Step25: Sweep a range of values for lam, plot the results, and print the average wait time across all values of lam. How do the results compare to the scenario with two servers and one queue.
Python Code: # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * # set the random number generator np.random.seed(7) Explanation: Modeling and Simulation in Python Case Study: Queueing theory Copyright 2017 Allen Downey License: Creative Commons Attribution 4.0 International End of explanation # Solution goes here Explanation: One queue or two? This notebook presents a solution to an exercise from Modeling and Simulation in Python. It uses features from the first four chapters to answer a question related to queueing theory, which is the study of systems that involve waiting in lines, also known as "queues". Suppose you are designing the checkout area for a new store. There is room for two checkout counters and a waiting area for customers. You can make two lines, one for each counter, or one line that serves both counters. In theory, you might expect a single line to be better, but it has some practical drawbacks: in order to maintain a single line, you would have to install rope barriers, and customers might be put off by what seems to be a longer line, even if it moves faster. So you'd like to check whether the single line is really better and by how much. Simulation can help answer this question. As we did in the bikeshare model, we'll assume that a customer is equally likely to arrive during any timestep. I'll denote this probability using the Greek letter lambda, $\lambda$, or the variable name lam. The value of $\lambda$ probably varies from day to day, so we'll have to consider a range of possibilities. Based on data from other stores, you know that it takes 5 minutes for a customer to check out, on average. But checkout times are highly variable: most customers take less than 5 minutes, but some take substantially more. A simple way to model this variability is to assume that when a customer is checking out, they have the same probability of finishing up during each time step. I'll denote this probability using the Greek letter mu, $\mu$, or the variable name mu. If we choose $\mu=1/5$, the average number of time steps for each checkout will be 5 minutes, which is consistent with the data. One server, one queue Write a function called make_system that takes lam and mu as parameters and returns a System object with variables lam, mu, and duration. Set duration, which is the number of time steps to simulate, to 10 hours, expressed in minutes. End of explanation # Solution goes here Explanation: Test this function by creating a System object with lam=1/8 and mu=1/5. End of explanation # Solution goes here Explanation: Write an update function that takes as parameters x, which is the total number of customer in the store, including the one checking out; t, which is the number of minutes that have elapsed in the simulation, and system, which is a System object. If there's a customer checking out, it should use flip to decide whether they are done. And it should use flip to decide if a new customer has arrived. It should return the total number of customers at the end of the time step. End of explanation # Solution goes here Explanation: Test your function by calling it with x=1, t=0, and the System object you created. If you run it a few times, you should see different results. End of explanation def run_simulation(system, update_func): Simulate a queueing system. system: System object update_func: function object x = 0 results = TimeSeries() results[0] = x for t in linrange(0, system.duration): x = update_func(x, t, system) results[t+1] = x return results Explanation: Now we can run the simulation. Here's a version of run_simulation that creates a TimeSeries with the total number of customers in the store, including the one checking out. End of explanation # Solution goes here Explanation: Call run_simulation with your update function and plot the results. End of explanation def compute_metrics(results, system): Compute average number of customers and wait time. results: TimeSeries of queue lengths system: System object returns: L, W L = results.mean() W = L / system.lam return L, W Explanation: After the simulation, we can compute L, which is the average number of customers in the system, and W, which is the average time customers spend in the store. L and W are related by Little's Law: $L = \lambda W$ Where $\lambda$ is the arrival rate. Here's a function that computes them. End of explanation # Solution goes here Explanation: Call compute_metrics with the results from your simulation. End of explanation # Solution goes here Explanation: Parameter sweep Since we don't know the actual value of $\lambda$, we can sweep through a range of possibilities, from 10% to 80% of the completion rate, $\mu$. (If customers arrive faster than the completion rate, the queue grows without bound. In that case the metrics L and W just depend on how long the store is open.) Create an array of values for lam. End of explanation # Solution goes here Explanation: Write a function that takes an array of values for lam, a single value for mu, and an update function. For each value of lam, it should run a simulation, compute L and W, and store the value of W in a SweepSeries. It should return the SweepSeries. End of explanation # Solution goes here # Solution goes here Explanation: Call your function to generate a SweepSeries, and plot it. End of explanation # W_avg = sweep.mean() Explanation: If we imagine that this range of values represents arrival rates on different days, we can use the average value of W, for a range of values of lam, to compare different queueing strategies. End of explanation def plot_W(lam_array, mu): Plot the theoretical mean wait time. lam_array: array of values for `lam` mu: probability of finishing a checkout W = 1 / (mu - lam_array) plot(lam_array, W, 'g-') Explanation: Analysis The model I chose for this system is a common model in queueing theory, in part because many of its properties can be derived analytically. In particular, we can derive the average time in the store as a function of $\mu$ and $\lambda$: $W = 1 / (\mu - \lambda)$ The following function plots the theoretical value of $W$ as a function of $\lambda$. End of explanation # Solution goes here Explanation: Use this function to plot the theoretical results, then plot your simulation results again on the same graph. How do they compare? End of explanation # Solution goes here Explanation: Multiple servers Now let's try the other two queueing strategies: One queue with two checkout counters. Two queues, one for each counter. The following figure shows the three scenarios: Write an update function for one queue with two servers. End of explanation # Solution goes here Explanation: Use this update function to simulate the system, plot the results, and print the metrics. End of explanation # Solution goes here Explanation: Since we have two checkout counters now, we can consider values for $\lambda$ that exceed $\mu$. Create a new array of values for lam from 10% to 160% of mu. End of explanation # Solution goes here # Solution goes here Explanation: Use your sweep function to simulate the two server, one queue scenario with a range of values for lam. Plot the results and print the average value of W across all values of lam. End of explanation # Solution goes here Explanation: Multiple queues To simulate the scenario with two separate queues, we need two state variables to keep track of customers in each queue. Write an update function that takes x1, x2, t, and system as parameters and returns x1 and x2 as return values. f you are not sure how to return more than one return value, see compute_metrics. When a customer arrives, which queue do they join? End of explanation # Solution goes here Explanation: Write a version of run_simulation that works with this update function. End of explanation # Solution goes here Explanation: Test your functions by running a simulation with a single value of lam. End of explanation # Solution goes here # Solution goes here # Solution goes here Explanation: Sweep a range of values for lam, plot the results, and print the average wait time across all values of lam. How do the results compare to the scenario with two servers and one queue. End of explanation
5,381
Given the following text description, write Python code to implement the functionality described below step by step Description: This will lean heavily on Tom Augspurger's excellent series on Modern Pandas. Quote Step2: In the original example from Tom, the code is written out as such Step3: Our function may be a bit sloppy from a DRY standpoint, but let's be serious Step4: Digression on pandas Woo, we have a moderate-sized dataframe with a lot of columns, many which are NAN or non-intuitive. Let's define a few indices on the data, which assign metadata to each row and allow for fancy selection and operations along the way. Step5: I think this clears up some thinking about the rows -- indexing by the flight operator, the airport origin, airport destination, the plan id, and the date of the flight make it clear what each row is. Selecting the data out in useful ways is somewhat straightforward, using the .loc semantics, which allow for label-oriented indexing in a dataframe. Step6: What if we wanted to get ANY flight from denver to albuquerque? Pandas IndexSlice is a brilliant help here. The semantics work as follows Step7: we can also use the powerful query function, which allows a limited vocabulary to be executed on a dataframe and is wildly useful for slightly more clear operations. Step8: These days, I prefer query most of the time, particularly for exploration, but .loc with explicit indices can be far faster in many cases. back to gathering and inspection So, at this stage, it seems reasonable to examine some of the data and see what might be problematic or needs further work. We can see that several columns that should be datetimes are not "dep_time", etc. and that the City names are not really city names but City, State pairs. In Toms' series, the cleaning operations are done in a different post, but I will copy them here to fit in our framework. I think these functions can be safelycounted as advanced preprocessing and cleaning. Step9: Note that both methods accept a pandas.DataFrame and return a pandas.DataFrame . This is critical to our upcoming methodology, and for portability to spark. It seems obvious, but writing code that operates on immutable data structures is wildly useful for data processing. DataFrames are not immutable, but can be treated as such, as many operations either implicitly return a copy or methods can be written as such. With our methods, we can now create a new top-level function that handles our preprocessing. It's not too often that your major performance bottleneck in pandas is copying dataframes. Anyway, we can now integrate our simple gathering method with some of the cleaning methods for a new top-level entry for our exploration. Step10: Exploring data From Tom's post, here's a long method chain that does an awful lot of work to generate a plot of flights per day for the top carriers. I'll break this down a bit after. Step11: If we broke this out like many people do, we might end up with code like this, where each step is broken into a variable. Step12: Naming things is hard. Given that pandas has exteremely expressive semantics and nearly all analytic methods return a fresh dataframe or series, it makes it straightforward to chain many ops together. This style will lend itself well to spark and should be familiar to those of you who have worked with Scala or other functional languages. If the chains get very verbose or hard to follow, break them up and put them in a function, where you can keep it all in one place. Try to be very specific about naming your functions (remember, naming things is hard, functions are no different). In an exploratory context, you might continue adding methods onto your chain until you can expand and continue until you get to your chart or end stage goal. In some cases, saving some exploratory work to varibles is great. Let's briefly talk about the .assign operator. This operation returns a new column for a dataframe, where the new column can be a constant, some like-indexed numpy array or series, a callable that references the dataframe in question, etc. It's very powerful in method chains and also very useful for keeping your namespace clean. the semantics of df.assign(NEW_COLUMN_NAME=lambda df Step13: This enables rapid exploration, and within the interactive context, allows you to copy a cell and change single lines to modify your results. A heatmap might be a nice way to visualize categories in this data, and the assign syntax allows creating those categoricals seamless. Step14: What about some other exploration? Pandas alows for some nifty ways of slicing up data to flexibly apply basic operations. What if we want to "center" the carrier's delay time at an airport by the mean airport delay? This is a case where we assigning variables might be useful. We'll limit our analysis to the top carrriers / airports, and save some variables for further interactive use. Step15: Pandas handles alignment along axes, so we can do an operation along an axis with another dataframe with similar index labels. Step16: Putting that together, we can then get ratios of flight delays to the overall airport delay (grand mean or daily delays). Step18: So, now that we have some working flight data, let's poke at getting some tweets. Tweets I've recently refactored the python gnip search api to be a bit more flexible, including making each search return a lazy stream. There are also some tools for programatically generated the 'city name' column and the airport abbreviation are likely sources of help for finding tweets related to flights / airport data. We'll use those and define a small function to help quickly generate our rules, which are somewhat simplistic but should serve as a reasonable start. Step19: the gnip api has some functions to handle our connection information. Please ensure that the environment variable GNIP_PW is set with your password. If it isn't already set, you can set it here. Step20: In our get_tweets function, we wrap some of the functionality of our result stream to collect specific data from tweets into a dataframe. Step21: We can test this with a single rule. Step22: Now let's collect tweets for each airport. It might be a hair overkill, but I'll wrap the process up in a function, so we have a similar high point for grabbing our inital data. It will take a minute to grab this data, and for the time being, i'm not going to save it to disk. Step23: Given our new data, let's do some quick exploration and cleaning. Step24: The number of tweets per day by airport rule is a bit odd Step25: So lets look at what is going on with LAX Step26: Far, far more people tweeting from LAX than from other airports or the number of extra tweets were dominated by the spikes in the data. Given it's size, this makes some sense, but i would question my rules a bit. Let's even out these samples a hair, by selecting tweets only from when LAX exisited Step27: Moving on, let's do some more things with our tweets, like parse out the mentions from the dict structure to something more useful. We'll be making a function that takes a dataframe and returns one, so we can use it in the .pipe method. Step28: now, what about labeling a row with strictly American Airlines mentions? We could do this a few ways... Step29: Moving on a bit, what about a simple sentiment model? We'll grab a word database that simply matches words to a value and use it as a simple baseline. Step30: seems semi-reasonable to me! Let's look at a timeseries of sentiment overall Step31: Since we have our reasonable sentiment and mentions data, let's assign it to a fresh dataframe and continue looking. Note that a full data pull step at this point might look like .python tweets = (pull_tweet_data(gnip_rules) .pipe(parse_mentions) .assign(sentiment=lambda df Step32: And let's do some basic exploration of our tweet data.
Python Code: import os import zipfile import requests import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt Explanation: This will lean heavily on Tom Augspurger's excellent series on Modern Pandas. Quote: Method chaining, where you call methods on an object one after another, is in vogue at the moment. It's always been a style of programming that's been possible with pandas, and over the past several releases, we've added methods that enable even more chaining. - assign (0.16.0): For adding new columns to a DataFrame in a chain (inspired by dplyr's mutate) - pipe (0.16.2): For including user-defined methods in method chains. - rename (0.18.0): For altering axis names (in additional to changing the actual labels as before). - Window methods (0.18): Took the top-level pd.rolling\_\* and pd.expanding\_\* functions and made them NDFrame methods with a groupby-like API. - Resample (0.18.0) Added a new groupby-like API - .where/mask/Indexers accept Callables (0.18.1): In the next release you'll be able to pass a callable to the indexing methods, to be evaluated within the DataFrame's context (like .query, but with code instead of strings). My scripts will typically start off with large-ish chain at the start getting things into a manageable state. It's good to have the bulk of your munging done with right away so you can start to do Science™: Part of the goal will be to develop different coding styles with Pandas, moving from a script-ish, verbose approach to a piped style that flows well with discrete cleaning operations grouped into single functions. This flows very well into using pyspark's dataframe as well, as pyspark requires that kind of style and there is a great deal of overlap with pandas' dataframe methods in pyspark. Method chains are a popular method in programming these days, with the rise of functional languages that can change function composition to be more readable. Examples of this in various languages: ```.scala def fooNotIndent : List[Int] = (1 to 100).view.map { _ + 3 }.filter { _ > 10 }.flatMap { table.get }.take(3).toList def fooIndent: List[Int] = (1 to 100) .view .map { _ + 3 } .filter { _ > 10 } .flatMap { table.get } .take(3) .toList ``` or comparing (from TA's post) tumble_after( broke( fell_down( fetch(went_up(jack_jill, "hill"), "water"), jack), "crown"), "jill" ) with (from TA's post) ``` jack_jill %>% went_up("hill") %>% fetch("water") %>% fell_down("jack") %>% broke("crown") %>% tumble_after("jill") ``` or jack_jill .pipe(went("hill", "up")) .pipe(fetch("water")) .pipe(fell_down("jack")) .pipe(broke("crown")) .pipe(tumble_after("jill")) There are several cases I'd like to address in this session - Effective pandas usage Interactive development strategies Balancing exploration and reproducability Joining heterogenous datatypes This might be a lot for a single session, but hey. Let's start off with a problem that we might have that we can try to answer: What Airports or flights have issues with delays? I am purposefully choosing a dataset that we will have difficulties in joining with twitter data, and also to illustrate a point... Let's use Tom's use of the BTS airline delay dataset, which requires a bit of work to obtain and parse through. In data work, I have a loose set of semantics to describe stages in a workflow: Research and understanding understand question of interest understand the data sources available evaluate requirements from stakeholders think about available methods and timeframes for implementation judge final output (serialized data, production model, figures / slides / report, etc) data gathering / pull a single stage of collecting data from some source, be it scraping a website, some form of database, reading from a csv or other binary file, etc. trivial cleaning dealing with various data sources returns data in formats that you may not want, be it with weird variable names, transformations from CamelCase to camel_case, or other very early-stages ops that you define to ease the rest of the process. E.g., renaming columns with spaces in them to be _ delinated. This can often be integrated into the basic data pull step, but should be explicit for reproducibility purposes. Non-trivial cleaning / preprocessing There might be missing data, multiple or non-standard representation of NULL values (99s, strings 'nan', etc), which finding and handling are crucial for JSON or similar formats, nested data structures might be present datetime parsing and conversion if important to underlying analysis reshaping data to facilitate analysis (wide to long, stacked to unstacked, etc). frequency normalization for time-series data text cleaning or tokenization joining additional data sources with current data (which has already be gathered and pulled) exploratory analysis with "clean" data, you can begin to poke at questions, from basic summarization and counting to faceted charts if it makes sense for the data may include branching by reformatting your data into a different set (single operations to aggregated buckets, denormalized time-series stats, etc) lots of plotting and descriptions often can loop back to previous stages to gather more data or stabilize workflow when finding good features or ways of processing data modeling / prediction potential input to ML functions, which includes sampling and so forth output could be predicted values for a database or downstream operation, figures and text for a report, etc. It's important to note that these stages are NEVER LINEAR, even though it almost always looks like it to the end consumer of posts like this. Each stage can be non-trivial for a host of reasons, and choices made in the early stages have strong effects in the rest of the process. Lots of iteration might be needed in each stage, and managing technical debt here can make each iteration faster. Given these tasks, it seems logical to define our code in simliar stages, though I have no precise guides for how to do this. In our example for today, we can start by grabbing some data from the web. We'll follow TA's flights data grab and later add some tweet data via the Gnip api. Let's play What type of questions do we want to answer? Let's say we have a project that will investigate customer sentiment around airports / airlines. Perhaps some questions of interest are: Are customer moods affected heavily by flight delays? Are customers more likely to tweet due to flight delays? Do these effects vary by airport, airlines, or other factors? What type of data will we need? Probably some detailed data about flight delays, preferabbly flight-level data that includes information about the carrier, airport, destination, etc. We'll also need tweet data that reasonably matches these critera, of course. In this context, we'll probably be satisfied with simple exploration. I chose these questions partially due to the great series of posts by Augsperger that illustrate working with complex data, such as flight delays. :) Data Gathering For most notebook purposes, I like to include all imports at the top of a notebook, even if the code they enable will not be introduced until a later point. I like to keep this cell apart from others in the notebook for easy maintenence. End of explanation def maybe_pull_airport_data(): lightly modified from TA's post. headers = { 'Referer': 'https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time', 'Origin': 'https://www.transtats.bts.gov', 'Content-Type': 'application/x-www-form-urlencoded', } params = ( ('Table_ID', '236'), ('Has_Group', '3'), ('Is_Zipped', '0'), ) # query string to be sent. can modify the 'where' dates to change the size of data returned. data = "UserTableName=On_Time_Performance&DBShortName=On_Time&RawDataTable=T_ONTIME&sqlstr=+SELECT+FL_DATE%2CUNIQUE_CARRIER%2CAIRLINE_ID%2CTAIL_NUM%2CFL_NUM%2CORIGIN_AIRPORT_ID%2CORIGIN_AIRPORT_SEQ_ID%2CORIGIN_CITY_MARKET_ID%2CORIGIN%2CORIGIN_CITY_NAME%2CDEST_AIRPORT_ID%2CDEST_AIRPORT_SEQ_ID%2CDEST_CITY_MARKET_ID%2CDEST%2CDEST_CITY_NAME%2CCRS_DEP_TIME%2CDEP_TIME%2CDEP_DELAY%2CTAXI_OUT%2CWHEELS_OFF%2CWHEELS_ON%2CTAXI_IN%2CCRS_ARR_TIME%2CARR_TIME%2CARR_DELAY%2CCANCELLED%2CCANCELLATION_CODE%2CCARRIER_DELAY%2CWEATHER_DELAY%2CNAS_DELAY%2CSECURITY_DELAY%2CLATE_AIRCRAFT_DELAY+FROM++T_ONTIME+WHERE+YEAR%3D2017&varlist=FL_DATE%2CUNIQUE_CARRIER%2CAIRLINE_ID%2CTAIL_NUM%2CFL_NUM%2CORIGIN_AIRPORT_ID%2CORIGIN_AIRPORT_SEQ_ID%2CORIGIN_CITY_MARKET_ID%2CORIGIN%2CORIGIN_CITY_NAME%2CDEST_AIRPORT_ID%2CDEST_AIRPORT_SEQ_ID%2CDEST_CITY_MARKET_ID%2CDEST%2CDEST_CITY_NAME%2CCRS_DEP_TIME%2CDEP_TIME%2CDEP_DELAY%2CTAXI_OUT%2CWHEELS_OFF%2CWHEELS_ON%2CTAXI_IN%2CCRS_ARR_TIME%2CARR_TIME%2CARR_DELAY%2CCANCELLED%2CCANCELLATION_CODE%2CCARRIER_DELAY%2CWEATHER_DELAY%2CNAS_DELAY%2CSECURITY_DELAY%2CLATE_AIRCRAFT_DELAY&grouplist=&suml=&sumRegion=&filter1=title%3D&filter2=title%3D&geo=All%A0&time=January&timename=Month&GEOGRAPHY=All&XYEAR=2017&FREQUENCY=1&VarDesc=Year&VarType=Num&VarDesc=Quarter&VarType=Num&VarDesc=Month&VarType=Num&VarDesc=DayofMonth&VarType=Num&VarDesc=DayOfWeek&VarType=Num&VarName=FL_DATE&VarDesc=FlightDate&VarType=Char&VarName=UNIQUE_CARRIER&VarDesc=UniqueCarrier&VarType=Char&VarName=AIRLINE_ID&VarDesc=AirlineID&VarType=Num&VarDesc=Carrier&VarType=Char&VarName=TAIL_NUM&VarDesc=TailNum&VarType=Char&VarName=FL_NUM&VarDesc=FlightNum&VarType=Char&VarName=ORIGIN_AIRPORT_ID&VarDesc=OriginAirportID&VarType=Num&VarName=ORIGIN_AIRPORT_SEQ_ID&VarDesc=OriginAirportSeqID&VarType=Num&VarName=ORIGIN_CITY_MARKET_ID&VarDesc=OriginCityMarketID&VarType=Num&VarName=ORIGIN&VarDesc=Origin&VarType=Char&VarName=ORIGIN_CITY_NAME&VarDesc=OriginCityName&VarType=Char&VarDesc=OriginState&VarType=Char&VarDesc=OriginStateFips&VarType=Char&VarDesc=OriginStateName&VarType=Char&VarDesc=OriginWac&VarType=Num&VarName=DEST_AIRPORT_ID&VarDesc=DestAirportID&VarType=Num&VarName=DEST_AIRPORT_SEQ_ID&VarDesc=DestAirportSeqID&VarType=Num&VarName=DEST_CITY_MARKET_ID&VarDesc=DestCityMarketID&VarType=Num&VarName=DEST&VarDesc=Dest&VarType=Char&VarName=DEST_CITY_NAME&VarDesc=DestCityName&VarType=Char&VarDesc=DestState&VarType=Char&VarDesc=DestStateFips&VarType=Char&VarDesc=DestStateName&VarType=Char&VarDesc=DestWac&VarType=Num&VarName=CRS_DEP_TIME&VarDesc=CRSDepTime&VarType=Char&VarName=DEP_TIME&VarDesc=DepTime&VarType=Char&VarName=DEP_DELAY&VarDesc=DepDelay&VarType=Num&VarDesc=DepDelayMinutes&VarType=Num&VarDesc=DepDel15&VarType=Num&VarDesc=DepartureDelayGroups&VarType=Num&VarDesc=DepTimeBlk&VarType=Char&VarName=TAXI_OUT&VarDesc=TaxiOut&VarType=Num&VarName=WHEELS_OFF&VarDesc=WheelsOff&VarType=Char&VarName=WHEELS_ON&VarDesc=WheelsOn&VarType=Char&VarName=TAXI_IN&VarDesc=TaxiIn&VarType=Num&VarName=CRS_ARR_TIME&VarDesc=CRSArrTime&VarType=Char&VarName=ARR_TIME&VarDesc=ArrTime&VarType=Char&VarName=ARR_DELAY&VarDesc=ArrDelay&VarType=Num&VarDesc=ArrDelayMinutes&VarType=Num&VarDesc=ArrDel15&VarType=Num&VarDesc=ArrivalDelayGroups&VarType=Num&VarDesc=ArrTimeBlk&VarType=Char&VarName=CANCELLED&VarDesc=Cancelled&VarType=Num&VarName=CANCELLATION_CODE&VarDesc=CancellationCode&VarType=Char&VarDesc=Diverted&VarType=Num&VarDesc=CRSElapsedTime&VarType=Num&VarDesc=ActualElapsedTime&VarType=Num&VarDesc=AirTime&VarType=Num&VarDesc=Flights&VarType=Num&VarDesc=Distance&VarType=Num&VarDesc=DistanceGroup&VarType=Num&VarName=CARRIER_DELAY&VarDesc=CarrierDelay&VarType=Num&VarName=WEATHER_DELAY&VarDesc=WeatherDelay&VarType=Num&VarName=NAS_DELAY&VarDesc=NASDelay&VarType=Num&VarName=SECURITY_DELAY&VarDesc=SecurityDelay&VarType=Num&VarName=LATE_AIRCRAFT_DELAY&VarDesc=LateAircraftDelay&VarType=Num&VarDesc=FirstDepTime&VarType=Char&VarDesc=TotalAddGTime&VarType=Num&VarDesc=LongestAddGTime&VarType=Num&VarDesc=DivAirportLandings&VarType=Num&VarDesc=DivReachedDest&VarType=Num&VarDesc=DivActualElapsedTime&VarType=Num&VarDesc=DivArrDelay&VarType=Num&VarDesc=DivDistance&VarType=Num&VarDesc=Div1Airport&VarType=Char&VarDesc=Div1AirportID&VarType=Num&VarDesc=Div1AirportSeqID&VarType=Num&VarDesc=Div1WheelsOn&VarType=Char&VarDesc=Div1TotalGTime&VarType=Num&VarDesc=Div1LongestGTime&VarType=Num&VarDesc=Div1WheelsOff&VarType=Char&VarDesc=Div1TailNum&VarType=Char&VarDesc=Div2Airport&VarType=Char&VarDesc=Div2AirportID&VarType=Num&VarDesc=Div2AirportSeqID&VarType=Num&VarDesc=Div2WheelsOn&VarType=Char&VarDesc=Div2TotalGTime&VarType=Num&VarDesc=Div2LongestGTime&VarType=Num&VarDesc=Div2WheelsOff&VarType=Char&VarDesc=Div2TailNum&VarType=Char&VarDesc=Div3Airport&VarType=Char&VarDesc=Div3AirportID&VarType=Num&VarDesc=Div3AirportSeqID&VarType=Num&VarDesc=Div3WheelsOn&VarType=Char&VarDesc=Div3TotalGTime&VarType=Num&VarDesc=Div3LongestGTime&VarType=Num&VarDesc=Div3WheelsOff&VarType=Char&VarDesc=Div3TailNum&VarType=Char&VarDesc=Div4Airport&VarType=Char&VarDesc=Div4AirportID&VarType=Num&VarDesc=Div4AirportSeqID&VarType=Num&VarDesc=Div4WheelsOn&VarType=Char&VarDesc=Div4TotalGTime&VarType=Num&VarDesc=Div4LongestGTime&VarType=Num&VarDesc=Div4WheelsOff&VarType=Char&VarDesc=Div4TailNum&VarType=Char&VarDesc=Div5Airport&VarType=Char&VarDesc=Div5AirportID&VarType=Num&VarDesc=Div5AirportSeqID&VarType=Num&VarDesc=Div5WheelsOn&VarType=Char&VarDesc=Div5TotalGTime&VarType=Num&VarDesc=Div5LongestGTime&VarType=Num&VarDesc=Div5WheelsOff&VarType=Char&VarDesc=Div5TailNum&VarType=Char" os.makedirs('data', exist_ok=True) dest = "data/flights.csv.zip" if not os.path.exists(dest): r = requests.post('https://www.transtats.bts.gov/DownLoad_Table.asp', headers=headers, params=params, data=data, stream=True) with open("data/flights.csv.zip", 'wb') as f: for chunk in r.iter_content(chunk_size=102400): if chunk: f.write(chunk) zf = zipfile.ZipFile("data/flights.csv.zip") fp = zf.extract(zf.filelist[0].filename, path='data/') df = (pd .read_csv(fp, parse_dates=["FL_DATE"]) .rename(columns=str.lower) #note this takes a callable ) return df Explanation: In the original example from Tom, the code is written out as such: ```.python headers = { 'Referer': 'https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236&DB_Short_Name=On-Time', 'Origin': 'https://www.transtats.bts.gov', 'Content-Type': 'application/x-www-form-urlencoded', } params = ( ('Table_ID', '236'), ('Has_Group', '3'), ('Is_Zipped', '0'), ) data = <TRUNCATED> os.makedirs('data', exist_ok=True) dest = "data/flights.csv.zip" if not os.path.exists(dest): r = requests.post('https://www.transtats.bts.gov/DownLoad_Table.asp', headers=headers, params=params, data=data, stream=True) with open("data/flights.csv.zip", 'wb') as f: for chunk in r.iter_content(chunk_size=102400): if chunk: f.write(chunk) ``` Given out focus today, let's wrap all initial data pulling into a function for logical separation. End of explanation flights = maybe_pull_airport_data() flights.head() flights.shape flights.info() Explanation: Our function may be a bit sloppy from a DRY standpoint, but let's be serious: there is no need for arguments in this function and no other piece of our analysis will ever touch the fields inside of here. You could argue that it could take a flexibile filename option, but again, for the purposes of this demo, that might be overkill, but refactoring the single function to take a filename argument would take a minutue or two, now that the core logic is stable. This gives us a high-level intro point for our demo, a single call to the function. Imagine this was going to go into a much larger set of functions or a library of some sort -- the function can be moved to a python file and work out of the box, which can simply your notebook or code at the risk of making more dependencies for users and disrupting the flow of analysis for a technical consumer. That was a lot of crap - let's get back to the data. End of explanation hdf = flights.set_index(["unique_carrier", "origin", "dest", "tail_num", "fl_date"]).sort_index() hdf[hdf.columns[:4]].head() Explanation: Digression on pandas Woo, we have a moderate-sized dataframe with a lot of columns, many which are NAN or non-intuitive. Let's define a few indices on the data, which assign metadata to each row and allow for fancy selection and operations along the way. End of explanation hdf.loc[["AA"], ["dep_delay"]].head() Explanation: I think this clears up some thinking about the rows -- indexing by the flight operator, the airport origin, airport destination, the plan id, and the date of the flight make it clear what each row is. Selecting the data out in useful ways is somewhat straightforward, using the .loc semantics, which allow for label-oriented indexing in a dataframe. End of explanation (hdf.loc[pd.IndexSlice[:, ["DEN"], ["ABQ"]], ["dep_delay"]] .sort_values("dep_delay", ascending=False) .head() ) Explanation: What if we wanted to get ANY flight from denver to albuquerque? Pandas IndexSlice is a brilliant help here. The semantics work as follows: : is "include all labels from this level of the index hdf.loc[pd.IndexSlice[:, ["DEN"], ["ABQ"]], ["dep_delay"]] translates to hdf.loc[pd.IndexSlice[ALL CARRIERS, origin=["DEN"], dest=["ABQ"], ALL_TAILS, ALL_DATES], ["dep_delay"]] End of explanation (hdf .query("origin == 'DEN' and dest == 'ABQ'") .loc[:, "dep_delay"] .to_frame() .sort_values("dep_delay", ascending=False) .head() ) Explanation: we can also use the powerful query function, which allows a limited vocabulary to be executed on a dataframe and is wildly useful for slightly more clear operations. End of explanation flights.head() flights.dtypes def extract_city_name(df): ''' Chicago, IL -> Chicago for origin_city_name and dest_city_name. From Augsperger. ''' cols = ['origin_city_name', 'dest_city_name'] city = df[cols].apply(lambda x: x.str.extract("(.*), \w{2}", expand=False)) df = df.copy() df[['origin_city_name', 'dest_city_name']] = city return df def time_to_datetime(df, columns): ''' Combine all time items into datetimes. From Augsperger. 2014-01-01,0914 -> 2014-01-01 09:14:00 ''' df = df.copy() def converter(col): timepart = (col.astype(str) .str.replace('\.0$', '') # NaNs force float dtype .str.pad(4, fillchar='0')) return pd.to_datetime(df['fl_date'].astype("str") + ' ' + timepart.str.slice(0, 2) + ':' + timepart.str.slice(2, 4), errors='coerce') df[columns] = df[columns].apply(converter) return df Explanation: These days, I prefer query most of the time, particularly for exploration, but .loc with explicit indices can be far faster in many cases. back to gathering and inspection So, at this stage, it seems reasonable to examine some of the data and see what might be problematic or needs further work. We can see that several columns that should be datetimes are not "dep_time", etc. and that the City names are not really city names but City, State pairs. In Toms' series, the cleaning operations are done in a different post, but I will copy them here to fit in our framework. I think these functions can be safelycounted as advanced preprocessing and cleaning. End of explanation def read_and_process_flights_data(): drop_cols = ["unnamed: 32", "security_delay", "late_aircraft_delay", "nas_delay", "origin_airport_id", "origin_city_market_id", "taxi_out", "wheels_off", "wheels_on", "crs_arr_time", "crs_dep_time", "carrier_delay"] df = (maybe_pull_airport_data() .rename(columns=str.lower) .drop(drop_cols, axis=1) .pipe(extract_city_name) .pipe(time_to_datetime, ['dep_time', 'arr_time']) .assign(fl_date=lambda x: pd.to_datetime(x['fl_date']), dest=lambda x: pd.Categorical(x['dest']), origin=lambda x: pd.Categorical(x['origin']), tail_num=lambda x: pd.Categorical(x['tail_num']), unique_carrier=lambda x: pd.Categorical(x['unique_carrier']), cancellation_code=lambda x: pd.Categorical(x['cancellation_code']))) return df ## this will take a few minutues with the full 2017 data; far faster with a month's sample flights = read_and_process_flights_data() flights.tail() flights.dtypes flights.shape Explanation: Note that both methods accept a pandas.DataFrame and return a pandas.DataFrame . This is critical to our upcoming methodology, and for portability to spark. It seems obvious, but writing code that operates on immutable data structures is wildly useful for data processing. DataFrames are not immutable, but can be treated as such, as many operations either implicitly return a copy or methods can be written as such. With our methods, we can now create a new top-level function that handles our preprocessing. It's not too often that your major performance bottleneck in pandas is copying dataframes. Anyway, we can now integrate our simple gathering method with some of the cleaning methods for a new top-level entry for our exploration. End of explanation (flights .dropna(subset=['dep_time', 'unique_carrier']) .loc[flights['unique_carrier'].isin(flights['unique_carrier'] .value_counts() .index[:5])] .set_index('dep_time') .groupby(['unique_carrier', pd.TimeGrouper("D")]) ["fl_num"] .count() .unstack(0) .fillna(0) .rename_axis("Flights per Day", axis=1) .plot() ) Explanation: Exploring data From Tom's post, here's a long method chain that does an awful lot of work to generate a plot of flights per day for the top carriers. I'll break this down a bit after. End of explanation # gets the carriers with the most traffic, hacking with the index. We use this for other ops. df_clean = flights.dropna(subset=["dep_time", "unique_carrier"]) top_carriers = flights["unique_carrier"].value_counts().index[:5] df_clean = df_clean.query("unique_carrier in @top_carriers") df_clean = df_clean.set_index("dep_time") carriers_by_hour = (df_clean .groupby(['unique_carrier', pd.TimeGrouper("H")])["fl_num"] .count()) carriers_df = carriers_by_hour.unstack(0) carriers_df = carriers_df.fillna(0) carriers_flights_per_day = (carriers_df .rolling(24) .sum() .rename_axis("Flights per Day", axis=1)) carriers_flights_per_day.plot() Explanation: If we broke this out like many people do, we might end up with code like this, where each step is broken into a variable. End of explanation #taken from Augsperger (flights[['fl_date', 'unique_carrier', 'tail_num', 'dep_time', 'dep_delay']] .dropna() .query("unique_carrier in @top_carriers") .assign(hour=lambda x: x['dep_time'].dt.hour) #.query('5 <= dep_delay < 600') .pipe((sns.boxplot, 'data'), 'hour', 'dep_delay') ) Explanation: Naming things is hard. Given that pandas has exteremely expressive semantics and nearly all analytic methods return a fresh dataframe or series, it makes it straightforward to chain many ops together. This style will lend itself well to spark and should be familiar to those of you who have worked with Scala or other functional languages. If the chains get very verbose or hard to follow, break them up and put them in a function, where you can keep it all in one place. Try to be very specific about naming your functions (remember, naming things is hard, functions are no different). In an exploratory context, you might continue adding methods onto your chain until you can expand and continue until you get to your chart or end stage goal. In some cases, saving some exploratory work to varibles is great. Let's briefly talk about the .assign operator. This operation returns a new column for a dataframe, where the new column can be a constant, some like-indexed numpy array or series, a callable that references the dataframe in question, etc. It's very powerful in method chains and also very useful for keeping your namespace clean. the semantics of df.assign(NEW_COLUMN_NAME=lambda df: df["column"] + df["column2"] can be read as assign a column named "NEW_COLUMN_NAME" to my referenced dataframe that is the sum of "column" and "column2". In the below example , the lambda references the datetime object of the departure time column to extract the hour, which gives us a convenient categorical value for examination. This is similar to R's mutate function in the dyplr world. Note -- the top_carriers variable above is a good example of something we might want to keep around, and I'll use it several times in the post. End of explanation (flights[['fl_date', "unique_carrier", 'dep_time', 'dep_delay']] .dropna() .query("unique_carrier in @top_carriers") .assign(hour=lambda x: x.dep_time.dt.hour) .assign(day=lambda x: x.dep_time.dt.dayofweek) .query('-1 < dep_delay < 600') .groupby(["day", "hour"])["dep_delay"] .median() .unstack() .pipe((sns.heatmap, 'data')) ) (flights[['fl_date', 'unique_carrier', 'dep_time', 'dep_delay']] .query("unique_carrier in @top_carriers") .dropna() .assign(hour=lambda x: x.dep_time.dt.hour) .assign(day=lambda x: x.dep_time.dt.dayofweek) #.query('0 <= dep_delay < 600') .groupby(["unique_carrier", "day"])["dep_delay"] .mean() .unstack() .sort_values(by=0) .pipe((sns.heatmap, 'data')) ) Explanation: This enables rapid exploration, and within the interactive context, allows you to copy a cell and change single lines to modify your results. A heatmap might be a nice way to visualize categories in this data, and the assign syntax allows creating those categoricals seamless. End of explanation top_airport_codes = flights["origin"].value_counts().to_frame().head(5).index top_airport_cities = flights["origin_city_name"].value_counts().head(5).index top_airport_cities top_airport_codes grand_airport_delay = (flights .query("unique_carrier in @top_carriers") .query("origin in @top_airport_codes") .groupby("origin")["dep_delay"] .mean() .dropna() .to_frame() ) airport_delay = (flights .query("unique_carrier in @top_carriers") .query("origin in @top_airport_codes") .set_index("fl_date") .groupby([pd.TimeGrouper("H"), "origin"])["dep_delay"] .mean() .to_frame() ) carrier_delay = (flights .query("unique_carrier in @top_carriers") .query("origin in @top_airport_codes") .set_index("fl_date") .groupby([pd.TimeGrouper("H"), "origin", "unique_carrier"])["dep_delay"] .mean() .to_frame() ) airport_delay.head() carrier_delay.head() grand_airport_delay airport_delay.unstack().head() carrier_delay.unstack(1).head() Explanation: What about some other exploration? Pandas alows for some nifty ways of slicing up data to flexibly apply basic operations. What if we want to "center" the carrier's delay time at an airport by the mean airport delay? This is a case where we assigning variables might be useful. We'll limit our analysis to the top carrriers / airports, and save some variables for further interactive use. End of explanation (carrier_delay .unstack(1) .div(grand_airport_delay.unstack()) .head() ) (carrier_delay .unstack(1) .div(airport_delay.unstack()) .head() ) Explanation: Pandas handles alignment along axes, so we can do an operation along an axis with another dataframe with similar index labels. End of explanation (carrier_delay .unstack(1) .div(airport_delay.unstack()) .stack() .reset_index() .assign(day=lambda x: x["fl_date"].dt.dayofweek) .set_index("fl_date") .groupby(["unique_carrier", "day"]) .mean() .dropna() .unstack() ["dep_delay"] .pipe((sns.heatmap, 'data')) ) (carrier_delay .unstack(1) .div(grand_airport_delay.unstack()) .stack() .reset_index() .assign(day=lambda x: x["fl_date"].dt.dayofweek) .set_index("fl_date") .groupby(["unique_carrier", "day"]) .mean() .dropna() .unstack() ["dep_delay"] .pipe((sns.heatmap, 'data')) ) (carrier_delay .unstack(1) .subtract(airport_delay.unstack()) .stack() .reset_index() .assign(day=lambda x: x["fl_date"].dt.dayofweek) .groupby(["unique_carrier", "day"]) .mean() .dropna() .unstack() ["dep_delay"] .pipe((sns.heatmap, 'data')) ) Explanation: Putting that together, we can then get ratios of flight delays to the overall airport delay (grand mean or daily delays). End of explanation def generate_rules(codes, cities): base_rule = ({code} OR "{city} airport") (flying OR flight OR plane OR jet) -(football OR basketball OR baseball OR party) -is:retweet rules = [] for code, city in zip(list(codes), list(cities)): _rule = base_rule.format(code=code, city=city.lower()) rule = gen_rule_payload(_rule, from_date="2017-01-01", to_date="2017-07-31", max_results=500) rules.append(rule) return rules gnip_rules = generate_rules(top_airport_codes, top_airport_cities) gnip_rules[0] Explanation: So, now that we have some working flight data, let's poke at getting some tweets. Tweets I've recently refactored the python gnip search api to be a bit more flexible, including making each search return a lazy stream. There are also some tools for programatically generated the 'city name' column and the airport abbreviation are likely sources of help for finding tweets related to flights / airport data. We'll use those and define a small function to help quickly generate our rules, which are somewhat simplistic but should serve as a reasonable start. End of explanation # os.environ["GNIP_PW"] = "" username = "agonzales@twitter.com" search_api = "fullarchive" account_name = "shendrickson" endpoint_label = "ogformat.json" og_search_endpoint = gen_endpoint(search_api, account_name, endpoint_label, count_endpoint=False) og_args = {"username": username, "password": os.environ["GNIP_PW"], "url": og_search_endpoint} Explanation: the gnip api has some functions to handle our connection information. Please ensure that the environment variable GNIP_PW is set with your password. If it isn't already set, you can set it here. End of explanation def get_tweets(result_stream, label): fields = ["id", "created_at_datetime", "all_text", "hashtags", "user_id", "user_mentions", "screen_name"] tweet_extracts = [] for tweet in result_stream.start_stream(): attrs = [tweet.__getattribute__(field) for field in fields] tweet_extracts.append(attrs) result_stream.end_stream() df = pd.DataFrame(tweet_extracts, columns=fields).assign(airport=label) return df Explanation: In our get_tweets function, we wrap some of the functionality of our result stream to collect specific data from tweets into a dataframe. End of explanation rs = ResultStream(**og_args, rule_payload=gnip_rules[0], max_results=1000) tweets = get_tweets(result_stream=rs, label=top_airport_codes[0]) tweets.head() tweets.shape Explanation: We can test this with a single rule. End of explanation def pull_tweet_data(gnip_rules, results_per_rule=25000): streams = [ResultStream(**og_args, rule_payload=rp, max_results=results_per_rule) for rp in gnip_rules] tweets = [get_tweets(rs, airport) for rs, airport in zip(streams, top_airport_codes)] return pd.concat(tweets) tweets = pull_tweet_data(gnip_rules) Explanation: Now let's collect tweets for each airport. It might be a hair overkill, but I'll wrap the process up in a function, so we have a similar high point for grabbing our inital data. It will take a minute to grab this data, and for the time being, i'm not going to save it to disk. End of explanation tweets.shape tweets.head() (tweets .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D")]) .size() .sort_values() .tail() ) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) (tweets .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D")]) .size() .plot() ) ax.annotate("united senselessly\nbeating a passenger", xytext=("2017-02-01", 1200), xy=("2017-04-04", 900), arrowprops=dict(facecolor="black", shrink=0.05)) Explanation: Given our new data, let's do some quick exploration and cleaning. End of explanation (tweets .drop(["id", "all_text"], axis=1) .set_index("created_at_datetime") .groupby([pd.TimeGrouper("H"), "airport"]) ["user_id"] .count() .unstack() .fillna(0) .rolling(24).sum() .plot() ) Explanation: The number of tweets per day by airport rule is a bit odd: End of explanation tweets["airport"].value_counts() tweets.groupby("airport")["created_at_datetime"].min().sort_values().tail(1) min_lax_time = tweets.groupby("airport")["created_at_datetime"].min().sort_values().tail(1)[0] Explanation: So lets look at what is going on with LAX: End of explanation (tweets .drop(["id", "all_text"], axis=1) .query("created_at_datetime >= @min_lax_time") .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D"), "airport"]) ["user_id"] .count() .unstack() .fillna(0) #.rolling(7).mbean() .plot() ) Explanation: Far, far more people tweeting from LAX than from other airports or the number of extra tweets were dominated by the spikes in the data. Given it's size, this makes some sense, but i would question my rules a bit. Let's even out these samples a hair, by selecting tweets only from when LAX exisited End of explanation def parse_mentions(df): extract_mentions = lambda x: [d["name"] for d in x] mentions = (pd.DataFrame([x for x in df["user_mentions"] .apply(extract_mentions)]) .loc[:, [0, 1]] .rename(columns={0: "mention_1", 1: "mention_2"}) ) return (pd.merge(df, mentions, left_index=True, right_index=True) .drop("user_mentions", axis=1) ) airline_name_code_dict = { "Southwest Airlines": "WN", "Delta": "DL", "American Airlines": "AA", "United Airlines": "UA", "Sky": "Sk" } Explanation: Moving on, let's do some more things with our tweets, like parse out the mentions from the dict structure to something more useful. We'll be making a function that takes a dataframe and returns one, so we can use it in the .pipe method. End of explanation (tweets .pipe(parse_mentions) .assign(AA=lambda df: (df["mention_1"] == "American Airlines") | (df["mention_2"] == "American Airlines")) .query("AA == True") .head() ) (tweets .pipe(parse_mentions) .query("mention_1 == 'American Airlines' or mention_2 == 'American Airlines'") .shape ) (tweets .pipe(parse_mentions) .query("mention_1 == 'American Airlines' or mention_2 == 'American Airlines'") .query("created_at_datetime >= @min_lax_time") .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D"), "airport"]) ["user_id"] .count() .unstack() .fillna(0) .rolling(7).mean() .plot() ) Explanation: now, what about labeling a row with strictly American Airlines mentions? We could do this a few ways... End of explanation from nltk.tokenize import TweetTokenizer def get_affin_dict(): url = "https://raw.githubusercontent.com/fnielsen/afinn/master/afinn/data/AFINN-111.txt" affin_words = (pd .read_table(url, sep='\t', header=None) .rename(columns={0: "word", 1: "score"}) .to_dict(orient="list") ) affin_words = {k: v for k, v in zip(affin_words["word"], affin_words["score"])} return affin_words tknizer = TweetTokenizer() def score_sentiment(words): words = set(words) union = words & affin_words.keys() return sum([affin_words[w] for w in union]) def score_tweet(tweet_text): return score_sentiment(tknizer.tokenize(tweet_text)) affin_words = get_affin_dict() (tweets .assign(sentiment=lambda df: df["all_text"].apply(score_tweet)) ["sentiment"] .plot.hist(bins=20)) (tweets .assign(sentiment=lambda df: df["all_text"].apply(score_tweet)) .pipe(lambda df: pd.concat([df.query("sentiment <= -5").head(), df.query("sentiment >= 5").head()])) ) Explanation: Moving on a bit, what about a simple sentiment model? We'll grab a word database that simply matches words to a value and use it as a simple baseline. End of explanation (tweets .assign(sentiment=lambda df: df["all_text"].apply(score_tweet)) .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D")]) ["sentiment"] .mean() .rolling(2).mean() .plot() ) Explanation: seems semi-reasonable to me! Let's look at a timeseries of sentiment overall: End of explanation tweets = (tweets .pipe(parse_mentions) .assign(sentiment=lambda df: df["all_text"].apply(score_tweet)) ) Explanation: Since we have our reasonable sentiment and mentions data, let's assign it to a fresh dataframe and continue looking. Note that a full data pull step at this point might look like .python tweets = (pull_tweet_data(gnip_rules) .pipe(parse_mentions) .assign(sentiment=lambda df: df["all_text"].apply(score_tweet)) ) End of explanation (tweets .groupby(["airport"]) ["sentiment"] .mean() .sort_values() .plot.barh() ) (tweets .assign(day=lambda x: x.created_at_datetime.dt.dayofweek) .assign(hour=lambda x: x.created_at_datetime.dt.hour) .groupby(["day", "hour"]) ["sentiment"] .mean() .unstack() .pipe((sns.heatmap, 'data') ) ) (tweets .assign(hour=lambda x: x.created_at_datetime.dt.hour) .assign(day=lambda x: x.created_at_datetime.dt.dayofweek) .groupby(["airport", "day"]) ["sentiment"] .mean() .unstack() .sort_values(by=0) .pipe((sns.heatmap, 'data') ) ) (tweets .assign(hour=lambda x: x.created_at_datetime.dt.hour) .groupby(["airport", "hour"]) ["sentiment"] .mean() .unstack() .sort_values(by=0) .pipe((sns.heatmap, 'data')) ) (tweets .assign(day=lambda x: x.created_at_datetime.dt.dayofweek) .query("airport == 'ATL' and day == 2") .sample(10) .all_text ) (tweets .assign(day=lambda x: x.created_at_datetime.dt.dayofweek) .query("airport == 'ATL' and day == 5") .sample(10) .all_text ) tweet_sent_airport = (tweets .set_index("created_at_datetime") .groupby([pd.TimeGrouper("D"), "airport"])["sentiment"] .mean() ) delay_sent = (pd.concat([airport_delay, tweet_sent_airport], axis=1, names=("day", "airport")) .sort_index()) for code in top_airport_codes: (delay_sent .loc[pd.IndexSlice[:, code], :] .plot(subplots=True, title="Sentiment and delay time at {}".format(code))) delay_sent.loc[pd.IndexSlice[:, "ATL"], :].corr() delay_sent.groupby(level=1).corr().T.loc["sentiment"].unstack()["dep_delay"].sort_values() Explanation: And let's do some basic exploration of our tweet data. End of explanation
5,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction Step1: In this chapter, we will look at the relationship between graphs and linear algebra. The deep connection between these two topics is super interesting, and I'd like to show it to you through an exploration of three topics Step2: we can visualize the graph Step3: and we can visualize its adjacency matrix Step4: and we can obtain the adjacency matrix as a NumPy array Step5: Symmetry Remember that for an undirected graph, the adjacency matrix will be symmetric about the diagonal, while for a directed graph, the adjacency matrix will be asymmetric. Path finding In the Paths chapter, we can use the breadth-first search algorithm to find a shortest path between any two nodes. As it turns out, using adjacency matrices, we can answer a related question, which is how many paths exist of length K between two nodes. To see how, we need to see the relationship between matrix powers and graph path lengths. Let's take the adjacency matrix above, raise it to the second power, and see what it tells us. Step6: Exercise Step7: Higher matrix powers The semantic meaning of adjacency matrix powers is preserved even if we go to higher powers. For example, if we go to the 3rd matrix power Step8: You should be able to convince yourself that Step9: Exercise Step10: Message Passing Let's now dive into the second topic here, that of message passing. To show how message passing works on a graph, let's start with the directed linear chain, as this will make things easier to understand. "Message" representation in matrix form Our graph adjacency matrix contains nodes ordered in a particular fashion along the rows and columns. We can also create a "message" matrix $M$, using the same ordering of nodes along the rows, with columns instead representing a "message" that is intended to be "passed" from one node to another Step11: Notice where the position of the value 1 is - at the first node. If we take M and matrix multiply it against A2, let's see what we get Step12: The message has been passed onto the next node! And if we pass the message one more time Step16: Now, the message lies on the 3rd node! We can make an animation to visualize this more clearly. There are comments in the code to explain what's going on! Step17: Bipartite Graphs & Matrices The section on message passing above assumed unipartite graphs, or at least graphs for which messages can be meaningfully passed between nodes. In this section, we will look at bipartite graphs. Recall from before the definition of a bipartite graph Step18: From this "bi-adjacency" matrix, one can compute the projection onto the customers, matrix multiplying the matrix with its transpose. Step19: What we get is the connectivity matrix of the customers, based on shared purchases. The diagonals are the degree of the customers in the original graph, i.e. the number of purchases they originally made, and the off-diagonals are the connectivity matrix, based on shared products. To get the products matrix, we make the transposed matrix the left side of the matrix multiplication. Step20: You may now try to convince yourself that the diagonals are the number of times a customer purchased that product, and the off-diagonals are the connectivity matrix of the products, weighted by how similar two customers are. Exercises In the following exercises, you will now play with a customer-product graph from Amazon. This dataset was downloaded from UCSD's Julian McAuley's website, and corresponds to the digital music dataset. This is a bipartite graph. The two partitions are Step21: Remember that with bipartite graphs, it is useful to obtain nodes from one of the partitions. Step22: You'll notice that this matrix is extremely large! There are 5541 customers and 3568 products, for a total matrix size of $5541 \times 3568 = 19770288$, but it is stored in a sparse format because only 64706 elements are filled in. Step23: Example Step24: Next, get the diagonals of the customer-customer matrix. Recall here that in customer_mat, the diagonals correspond to the degree of the customer nodes in the bipartite matrix. SciPy sparse matrices provide a .diagonal() method that returns the diagonal elements. Step25: Finally, find the index of the customer that has the highest degree. Step26: We can verify this independently by sorting the customer nodes by degree. Step27: Indeed, customer 294 was the one who had the most number of reviews! Example Step28: Performance Step29: Matrices Now, let's implement the same thing in matrix form.
Python Code: from IPython.display import YouTubeVideo YouTubeVideo(id="uTHihJiRELc", width="100%") Explanation: Introduction End of explanation import networkx as nx nodes = list(range(4)) G1 = nx.Graph() G1.add_nodes_from(nodes) G1.add_edges_from(zip(nodes, nodes[1:])) Explanation: In this chapter, we will look at the relationship between graphs and linear algebra. The deep connection between these two topics is super interesting, and I'd like to show it to you through an exploration of three topics: Path finding Message passing Bipartite projections Preliminaries Before we go deep into the linear algebra piece though, we have to first make sure some ideas are clear. The most important thing that we need when treating graphs in linear algebra form is the adjacency matrix. For example, for four nodes joined in a chain: End of explanation nx.draw(G1, with_labels=True) Explanation: we can visualize the graph: End of explanation import nxviz as nv m = nv.matrix(G1) Explanation: and we can visualize its adjacency matrix: End of explanation A1 = nx.to_numpy_array(G1, nodelist=sorted(G1.nodes())) A1 Explanation: and we can obtain the adjacency matrix as a NumPy array: End of explanation import numpy as np np.linalg.matrix_power(A1, 2) Explanation: Symmetry Remember that for an undirected graph, the adjacency matrix will be symmetric about the diagonal, while for a directed graph, the adjacency matrix will be asymmetric. Path finding In the Paths chapter, we can use the breadth-first search algorithm to find a shortest path between any two nodes. As it turns out, using adjacency matrices, we can answer a related question, which is how many paths exist of length K between two nodes. To see how, we need to see the relationship between matrix powers and graph path lengths. Let's take the adjacency matrix above, raise it to the second power, and see what it tells us. End of explanation from nams.solutions.linalg import adjacency_matrix_power from nams.functions import render_html render_html(adjacency_matrix_power()) Explanation: Exercise: adjacency matrix power? What do you think the values in the adjacency matrix are related to? If studying in a group, discuss with your neighbors; if working on this alone, write down your thoughts. End of explanation np.linalg.matrix_power(A1, 3) Explanation: Higher matrix powers The semantic meaning of adjacency matrix powers is preserved even if we go to higher powers. For example, if we go to the 3rd matrix power: End of explanation G2 = nx.DiGraph() G2.add_nodes_from(nodes) G2.add_edges_from(zip(nodes, nodes[1:])) nx.draw(G2, with_labels=True) Explanation: You should be able to convince yourself that: There's no way to go from a node back to itself in 3 steps, thus explaining the diagonals, and The off-diagonals take on the correct values when you think about them in terms of "ways to go from one node to another". With directed graphs? Does the "number of steps" interpretation hold with directed graphs? Yes it does! Let's see it in action. End of explanation A2 = nx.to_numpy_array(G2) np.linalg.matrix_power(A2, 2) np.linalg.matrix_power(A2, 3) np.linalg.matrix_power(A2, 4) Explanation: Exercise: directed graph matrix power Convince yourself that the resulting adjacency matrix power contains the same semantic meaning as that for an undirected graph, that is, the number of ways to go from "row" node to "column" node in K steps. (I have provided three different matrix powers for you.) End of explanation M = np.array([1, 0, 0, 0]) M Explanation: Message Passing Let's now dive into the second topic here, that of message passing. To show how message passing works on a graph, let's start with the directed linear chain, as this will make things easier to understand. "Message" representation in matrix form Our graph adjacency matrix contains nodes ordered in a particular fashion along the rows and columns. We can also create a "message" matrix $M$, using the same ordering of nodes along the rows, with columns instead representing a "message" that is intended to be "passed" from one node to another: End of explanation M @ A2 Explanation: Notice where the position of the value 1 is - at the first node. If we take M and matrix multiply it against A2, let's see what we get: End of explanation M @ A2 @ A2 Explanation: The message has been passed onto the next node! And if we pass the message one more time: End of explanation def propagate(G, msg, n_frames): Computes the node values based on propagation. Intended to be used before or when being passed into the anim() function (defined below). :param G: A NetworkX Graph. :param msg: The initial state of the message. :returns: A list of 1/0 representing message status at each node. # Initialize a list to store message states at each timestep. msg_states = [] # Set a variable `new_msg` to be the initial message state. new_msg = msg # Get the adjacency matrix of the graph G. A = nx.to_numpy_array(G) # Perform message passing at each time step for i in range(n_frames): msg_states.append(new_msg) new_msg = new_msg @ A # Return the message states. return msg_states from IPython.display import HTML import matplotlib.pyplot as plt from matplotlib import animation def update_func(step, nodes, colors): The update function for each animation time step. :param step: Passed in from matplotlib's FuncAnimation. Must be present in the function signature. :param nodes: Returned from nx.draw_networkx_edges(). Is an array of colors. :param colors: A list of pre-computed colors. nodes.set_array(colors[step].ravel()) return nodes def anim(G, initial_state, n_frames=4): Animation function! # First, pre-compute the message passing states over all frames. colors = propagate(G, initial_state, n_frames) # Instantiate a figure fig = plt.figure() # Precompute node positions so that they stay fixed over the entire animation pos = nx.kamada_kawai_layout(G) # Draw nodes to screen nodes = nx.draw_networkx_nodes(G, pos=pos, node_color=colors[0].ravel(), node_size=20) # Draw edges to screen ax = nx.draw_networkx_edges(G, pos) # Finally, return the animation through matplotlib. return animation.FuncAnimation(fig, update_func, frames=range(n_frames), fargs=(nodes, colors)) # Initialize the message msg = np.zeros(len(G2)) msg[0] = 1 # Animate the graph with message propagation. HTML(anim(G2, msg, n_frames=4).to_html5_video()) Explanation: Now, the message lies on the 3rd node! We can make an animation to visualize this more clearly. There are comments in the code to explain what's going on! End of explanation # Rows = customers, columns = products, 1 = customer purchased product, 0 = customer did not purchase product. cp_mat = np.array([[0, 1, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]]) Explanation: Bipartite Graphs & Matrices The section on message passing above assumed unipartite graphs, or at least graphs for which messages can be meaningfully passed between nodes. In this section, we will look at bipartite graphs. Recall from before the definition of a bipartite graph: Nodes are separated into two partitions (hence 'bi'-'partite'). Edges can only occur between nodes of different partitions. Bipartite graphs have a natural matrix representation, known as the biadjacency matrix. Nodes on one partition are the rows, and nodes on the other partition are the columns. NetworkX's bipartite module provides a function for computing the biadjacency matrix of a bipartite graph. Let's start by looking at a toy bipartite graph, a "customer-product" purchase record graph, with 4 products and 3 customers. The matrix representation might be as follows: End of explanation c_mat = cp_mat @ cp_mat.T # c_mat means "customer matrix" c_mat Explanation: From this "bi-adjacency" matrix, one can compute the projection onto the customers, matrix multiplying the matrix with its transpose. End of explanation p_mat = cp_mat.T @ cp_mat # p_mat means "product matrix" p_mat Explanation: What we get is the connectivity matrix of the customers, based on shared purchases. The diagonals are the degree of the customers in the original graph, i.e. the number of purchases they originally made, and the off-diagonals are the connectivity matrix, based on shared products. To get the products matrix, we make the transposed matrix the left side of the matrix multiplication. End of explanation from nams import load_data as cf G_amzn = cf.load_amazon_reviews() Explanation: You may now try to convince yourself that the diagonals are the number of times a customer purchased that product, and the off-diagonals are the connectivity matrix of the products, weighted by how similar two customers are. Exercises In the following exercises, you will now play with a customer-product graph from Amazon. This dataset was downloaded from UCSD's Julian McAuley's website, and corresponds to the digital music dataset. This is a bipartite graph. The two partitions are: customers: The customers that were doing the reviews. products: The music that was being reviewed. In the original dataset (see the original JSON in the datasets/ directory), they are referred to as: customers: reviewerID products: asin End of explanation from nams.solutions.bipartite import extract_partition_nodes customer_nodes = extract_partition_nodes(G_amzn, "customer") mat = nx.bipartite.biadjacency_matrix(G_amzn, row_order=customer_nodes) Explanation: Remember that with bipartite graphs, it is useful to obtain nodes from one of the partitions. End of explanation mat Explanation: You'll notice that this matrix is extremely large! There are 5541 customers and 3568 products, for a total matrix size of $5541 \times 3568 = 19770288$, but it is stored in a sparse format because only 64706 elements are filled in. End of explanation customer_mat = mat @ mat.T Explanation: Example: finding customers who reviewed the most number of music items. Let's find out which customers reviewed the most number of music items. To do so, you can break the problem into a few steps. First off, we compute the customer projection using matrix operations. End of explanation # Get the diagonal. degrees = customer_mat.diagonal() Explanation: Next, get the diagonals of the customer-customer matrix. Recall here that in customer_mat, the diagonals correspond to the degree of the customer nodes in the bipartite matrix. SciPy sparse matrices provide a .diagonal() method that returns the diagonal elements. End of explanation cust_idx = np.argmax(degrees) cust_idx Explanation: Finally, find the index of the customer that has the highest degree. End of explanation import pandas as pd import janitor # There's some pandas-fu we need to use to get this correct. deg = ( pd.Series(dict(nx.degree(G_amzn, customer_nodes))) .to_frame() .reset_index() .rename_column("index", "customer") .rename_column(0, "num_reviews") .sort_values('num_reviews', ascending=False) ) deg.head() Explanation: We can verify this independently by sorting the customer nodes by degree. End of explanation import scipy.sparse as sp # Construct diagonal elements. customer_diags = sp.diags(degrees) # Subtract off-diagonals. off_diagonals = customer_mat - customer_diags # Compute index of most similar individuals. np.unravel_index(np.argmax(off_diagonals), customer_mat.shape) Explanation: Indeed, customer 294 was the one who had the most number of reviews! Example: finding similar customers Let's now also compute which two customers are similar, based on shared reviews. To do so involves the following steps: We construct a sparse matrix consisting of only the diagonals. scipy.sparse.diags(elements) will construct a sparse diagonal matrix based on the elements inside elements. Subtract the diagonals from the customer matrix projection. This yields the customer-customer similarity matrix, which should only consist of the off-diagonal elements of the customer matrix projection. Finally, get the indices where the weight (shared number of between the customers is highest. (This code is provided for you.) End of explanation from time import time start = time() # Compute the projection G_cust = nx.bipartite.weighted_projected_graph(G_amzn, customer_nodes) # Identify the most similar customers most_similar_customers = sorted(G_cust.edges(data=True), key=lambda x: x[2]['weight'], reverse=True)[0] end = time() print(f'{end - start:.3f} seconds') print(f'Most similar customers: {most_similar_customers}') Explanation: Performance: Object vs. Matrices Finally, to motivate why you might want to use matrices rather than graph objects to compute some of these statistics, let's time the two ways of getting to the same answer. Objects Let's first use NetworkX's built-in machinery to find customers that are most similar. End of explanation start = time() # Compute the projection using matrices mat = nx.bipartite.matrix.biadjacency_matrix(G_amzn, customer_nodes) cust_mat = mat @ mat.T # Identify the most similar customers degrees = customer_mat.diagonal() customer_diags = sp.diags(degrees) off_diagonals = customer_mat - customer_diags c1, c2 = np.unravel_index(np.argmax(off_diagonals), customer_mat.shape) end = time() print(f'{end - start:.3f} seconds') print(f'Most similar customers: {customer_nodes[c1]}, {customer_nodes[c2]}, {cust_mat[c1, c2]}') Explanation: Matrices Now, let's implement the same thing in matrix form. End of explanation
5,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Filtering and resampling data Some artifacts are restricted to certain frequencies and can therefore be fixed by filtering. An artifact that typically affects only some frequencies is due to the power line. Power-line noise is a noise created by the electrical network. It is composed of sharp peaks at 50Hz (or 60Hz depending on your geographical location). Some peaks may also be present at the harmonic frequencies, i.e. the integer multiples of the power-line frequency, e.g. 100Hz, 150Hz, ... (or 120Hz, 180Hz, ...). This tutorial covers some basics of how to filter data in MNE-Python. For more in-depth information about filter design in general and in MNE-Python in particular, check out sphx_glr_auto_tutorials_plot_background_filtering.py. Step1: Removing power-line noise with notch filtering Removing power-line noise can be done with a Notch filter, directly on the Raw object, specifying an array of frequency to be cut off Step2: Removing power-line noise with low-pass filtering If you're only interested in low frequencies, below the peaks of power-line noise you can simply low pass filter the data. Step3: High-pass filtering to remove slow drifts To remove slow drifts, you can high pass. <div class="alert alert-danger"><h4>Warning</h4><p>In several applications such as event-related potential (ERP) and event-related field (ERF) analysis, high-pass filters with cutoff frequencies greater than 0.1 Hz are usually considered problematic since they significantly change the shape of the resulting averaged waveform (see examples in `tut_filtering_hp_problems`). In such applications, apply high-pass filters with caution.</p></div> Step4: To do the low-pass and high-pass filtering in one step you can do a so-called band-pass filter by running the following Step5: Downsampling and decimation When performing experiments where timing is critical, a signal with a high sampling rate is desired. However, having a signal with a much higher sampling rate than necessary needlessly consumes memory and slows down computations operating on the data. To avoid that, you can downsample your time series. Since downsampling raw data reduces the timing precision of events, it is recommended only for use in procedures that do not require optimal precision, e.g. computing EOG or ECG projectors on long recordings. <div class="alert alert-info"><h4>Note</h4><p>A *downsampling* operation performs a low-pass (to prevent aliasing) followed by *decimation*, which selects every $N^{th}$ sample from the signal. See
Python Code: import numpy as np import mne from mne.datasets import sample data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif' proj_fname = data_path + '/MEG/sample/sample_audvis_eog_proj.fif' tmin, tmax = 0, 20 # use the first 20s of data # Setup for reading the raw data (save memory by cropping the raw data # before loading it) raw = mne.io.read_raw_fif(raw_fname) raw.crop(tmin, tmax).load_data() raw.info['bads'] = ['MEG 2443', 'EEG 053'] # bads + 2 more fmin, fmax = 2, 300 # look at frequencies between 2 and 300Hz n_fft = 2048 # the FFT size (n_fft). Ideally a power of 2 # Pick a subset of channels (here for speed reason) selection = mne.read_selection('Left-temporal') picks = mne.pick_types(raw.info, meg='mag', eeg=False, eog=False, stim=False, exclude='bads', selection=selection) # Let's first check out all channel types raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) Explanation: Filtering and resampling data Some artifacts are restricted to certain frequencies and can therefore be fixed by filtering. An artifact that typically affects only some frequencies is due to the power line. Power-line noise is a noise created by the electrical network. It is composed of sharp peaks at 50Hz (or 60Hz depending on your geographical location). Some peaks may also be present at the harmonic frequencies, i.e. the integer multiples of the power-line frequency, e.g. 100Hz, 150Hz, ... (or 120Hz, 180Hz, ...). This tutorial covers some basics of how to filter data in MNE-Python. For more in-depth information about filter design in general and in MNE-Python in particular, check out sphx_glr_auto_tutorials_plot_background_filtering.py. End of explanation raw.notch_filter(np.arange(60, 241, 60), picks=picks, filter_length='auto', phase='zero') raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) Explanation: Removing power-line noise with notch filtering Removing power-line noise can be done with a Notch filter, directly on the Raw object, specifying an array of frequency to be cut off: End of explanation # low pass filtering below 50 Hz raw.filter(None, 50., fir_design='firwin') raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) Explanation: Removing power-line noise with low-pass filtering If you're only interested in low frequencies, below the peaks of power-line noise you can simply low pass filter the data. End of explanation raw.filter(1., None, fir_design='firwin') raw.plot_psd(area_mode='range', tmax=10.0, picks=picks, average=False) Explanation: High-pass filtering to remove slow drifts To remove slow drifts, you can high pass. <div class="alert alert-danger"><h4>Warning</h4><p>In several applications such as event-related potential (ERP) and event-related field (ERF) analysis, high-pass filters with cutoff frequencies greater than 0.1 Hz are usually considered problematic since they significantly change the shape of the resulting averaged waveform (see examples in `tut_filtering_hp_problems`). In such applications, apply high-pass filters with caution.</p></div> End of explanation # band-pass filtering in the range 1 Hz - 50 Hz raw.filter(1, 50., fir_design='firwin') Explanation: To do the low-pass and high-pass filtering in one step you can do a so-called band-pass filter by running the following: End of explanation raw.resample(100, npad="auto") # set sampling frequency to 100Hz raw.plot_psd(area_mode='range', tmax=10.0, picks=picks) Explanation: Downsampling and decimation When performing experiments where timing is critical, a signal with a high sampling rate is desired. However, having a signal with a much higher sampling rate than necessary needlessly consumes memory and slows down computations operating on the data. To avoid that, you can downsample your time series. Since downsampling raw data reduces the timing precision of events, it is recommended only for use in procedures that do not require optimal precision, e.g. computing EOG or ECG projectors on long recordings. <div class="alert alert-info"><h4>Note</h4><p>A *downsampling* operation performs a low-pass (to prevent aliasing) followed by *decimation*, which selects every $N^{th}$ sample from the signal. See :func:`scipy.signal.resample` and :func:`scipy.signal.resample_poly` for examples.</p></div> Data resampling can be done with resample methods. End of explanation
5,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Train Model with XLA_GPU (and CPU*) Some operations do not have XLA_GPU equivalents, so we still need to use CPU. IMPORTANT Step1: Reset TensorFlow Graph Useful in Jupyter Notebooks Step2: Create TensorFlow Session Step3: Generate Model Version (current timestamp) Step4: Load Model Training and Test/Validation Data Step5: Randomly Initialize Variables (Weights and Bias) The goal is to learn more accurate Weights and Bias during training. Step6: View Accuracy of Pre-Training, Initial Random Variables We want this to be close to 0, but it's relatively far away. This is why we train! Step7: Setup Loss Summary Operations for Tensorboard Step8: Train Model Step9: View Loss Summaries in Tensorboard Navigate to the Scalars and Graphs tab at this URL Step10: Show Graph Step11: XLA JIT Visualizations
Python Code: import tensorflow as tf from tensorflow.python.client import timeline import pylab import numpy as np import os %matplotlib inline %config InlineBackend.figure_format = 'retina' tf.logging.set_verbosity(tf.logging.INFO) Explanation: Train Model with XLA_GPU (and CPU*) Some operations do not have XLA_GPU equivalents, so we still need to use CPU. IMPORTANT: You Must STOP All Kernels and Terminal Session The GPU is wedged at this point. We need to set it free!! End of explanation tf.reset_default_graph() Explanation: Reset TensorFlow Graph Useful in Jupyter Notebooks End of explanation config = tf.ConfigProto( log_device_placement=True, ) config.gpu_options.allow_growth=True config.graph_options.optimizer_options.global_jit_level \ = tf.OptimizerOptions.ON_1 print(config) sess = tf.Session(config=config) print(sess) Explanation: Create TensorFlow Session End of explanation from datetime import datetime version = int(datetime.now().strftime("%s")) Explanation: Generate Model Version (current timestamp) End of explanation num_samples = 100000 import numpy as np import pylab x_train = np.random.rand(num_samples).astype(np.float32) print(x_train) noise = np.random.normal(scale=0.01, size=len(x_train)) y_train = x_train * 0.1 + 0.3 + noise print(y_train) pylab.plot(x_train, y_train, '.') x_test = np.random.rand(len(x_train)).astype(np.float32) print(x_test) noise = np.random.normal(scale=.01, size=len(x_train)) y_test = x_test * 0.1 + 0.3 + noise print(y_test) pylab.plot(x_test, y_test, '.') with tf.device("/cpu:0"): W = tf.get_variable(shape=[], name='weights') print(W) b = tf.get_variable(shape=[], name='bias') print(b) with tf.device("/device:XLA_GPU:0"): x_observed = tf.placeholder(shape=[None], dtype=tf.float32, name='x_observed') print(x_observed) y_pred = W * x_observed + b print(y_pred) learning_rate = 0.025 with tf.device("/device:XLA_GPU:0"): y_observed = tf.placeholder(shape=[None], dtype=tf.float32, name='y_observed') print(y_observed) loss_op = tf.reduce_mean(tf.square(y_pred - y_observed)) optimizer_op = tf.train.GradientDescentOptimizer(learning_rate) train_op = optimizer_op.minimize(loss_op) print("Loss Scalar: ", loss_op) print("Optimizer Op: ", optimizer_op) print("Train Op: ", train_op) Explanation: Load Model Training and Test/Validation Data End of explanation with tf.device("/cpu:0"): init_op = tf.global_variables_initializer() print(init_op) sess.run(init_op) print("Initial random W: %f" % sess.run(W)) print("Initial random b: %f" % sess.run(b)) Explanation: Randomly Initialize Variables (Weights and Bias) The goal is to learn more accurate Weights and Bias during training. End of explanation def test(x, y): return sess.run(loss_op, feed_dict={x_observed: x, y_observed: y}) test(x_train, y_train) Explanation: View Accuracy of Pre-Training, Initial Random Variables We want this to be close to 0, but it's relatively far away. This is why we train! End of explanation loss_summary_scalar_op = tf.summary.scalar('loss', loss_op) loss_summary_merge_all_op = tf.summary.merge_all() train_summary_writer = tf.summary.FileWriter('/root/tensorboard/linear/xla_gpu/%s/train' % version, graph=tf.get_default_graph()) test_summary_writer = tf.summary.FileWriter('/root/tensorboard/linear/xla_gpu/%s/test' % version, graph=tf.get_default_graph()) Explanation: Setup Loss Summary Operations for Tensorboard End of explanation %%time from tensorflow.python.client import timeline with tf.device("/device:XLA_GPU:0"): run_metadata = tf.RunMetadata() max_steps = 401 for step in range(max_steps): if (step < max_steps - 1): test_summary_log, _ = sess.run([loss_summary_merge_all_op, loss_op], feed_dict={x_observed: x_test, y_observed: y_test}) train_summary_log, _ = sess.run([loss_summary_merge_all_op, train_op], feed_dict={x_observed: x_train, y_observed: y_train}) else: test_summary_log, _ = sess.run([loss_summary_merge_all_op, loss_op], feed_dict={x_observed: x_test, y_observed: y_test}) train_summary_log, _ = sess.run([loss_summary_merge_all_op, train_op], feed_dict={x_observed: x_train, y_observed: y_train}, options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE), run_metadata=run_metadata) trace = timeline.Timeline(step_stats=run_metadata.step_stats) with open('timeline-xla-gpu.json', 'w') as trace_file: trace_file.write(trace.generate_chrome_trace_format(show_memory=True)) if step % 10 == 0: print(step, sess.run([W, b])) train_summary_writer.add_summary(train_summary_log, step) train_summary_writer.flush() test_summary_writer.add_summary(test_summary_log, step) test_summary_writer.flush() pylab.plot(x_train, y_train, '.', label="target") pylab.plot(x_train, sess.run(y_pred, feed_dict={x_observed: x_train, y_observed: y_train}), ".", label="predicted") pylab.legend() pylab.ylim(0, 1.0) Explanation: Train Model End of explanation import os optimize_me_parent_path = '/root/models/optimize_me/linear/xla_gpu' saver = tf.train.Saver() os.system('rm -rf %s' % optimize_me_parent_path) os.makedirs(optimize_me_parent_path) unoptimized_model_graph_path = '%s/unoptimized_xla_gpu.pb' % optimize_me_parent_path tf.train.write_graph(sess.graph_def, '.', unoptimized_model_graph_path, as_text=False) print(unoptimized_model_graph_path) model_checkpoint_path = '%s/model.ckpt' % optimize_me_parent_path saver.save(sess, save_path=model_checkpoint_path) print(model_checkpoint_path) print(optimize_me_parent_path) os.listdir(optimize_me_parent_path) sess.close() Explanation: View Loss Summaries in Tensorboard Navigate to the Scalars and Graphs tab at this URL: http://[ip-address]:6006 Save Graph For Optimization We will use this later. End of explanation %%bash summarize_graph --in_graph=/root/models/optimize_me/linear/xla_gpu/unoptimized_xla_gpu.pb from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 def convert_graph_to_dot(input_graph, output_dot, is_input_graph_binary): graph = graph_pb2.GraphDef() with open(input_graph, "rb") as fh: if is_input_graph_binary: graph.ParseFromString(fh.read()) else: text_format.Merge(fh.read(), graph) with open(output_dot, "wt") as fh: print("digraph graphname {", file=fh) for node in graph.node: output_name = node.name print(" \"" + output_name + "\" [label=\"" + node.op + "\"];", file=fh) for input_full_name in node.input: parts = input_full_name.split(":") input_name = re.sub(r"^\^", "", parts[0]) print(" \"" + input_name + "\" -> \"" + output_name + "\";", file=fh) print("}", file=fh) print("Created dot file '%s' for graph '%s'." % (output_dot, input_graph)) input_graph='/root/models/optimize_me/linear/xla_gpu/unoptimized_xla_gpu.pb' output_dot='/root/notebooks/unoptimized_xla_gpu.dot' convert_graph_to_dot(input_graph=input_graph, output_dot=output_dot, is_input_graph_binary=True) %%bash dot -T png /root/notebooks/unoptimized_xla_gpu.dot \ -o /root/notebooks/unoptimized_xla_gpu.png > /tmp/a.out from IPython.display import Image Image('/root/notebooks/unoptimized_xla_gpu.png', width=1024, height=768) Explanation: Show Graph End of explanation %%bash dot -T png /tmp/hlo_graph_1.*.dot -o /root/notebooks/hlo_graph_1.png &>/dev/null dot -T png /tmp/hlo_graph_10.*.dot -o /root/notebooks/hlo_graph_10.png &>/dev/null dot -T png /tmp/hlo_graph_50.*.dot -o /root/notebooks/hlo_graph_50.png &>/dev/null dot -T png /tmp/hlo_graph_75.*.dot -o /root/notebooks/hlo_graph_75.png &>/dev/null Explanation: XLA JIT Visualizations End of explanation
5,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Please find jax implementation of this notebook here Step2: Implementation Utility functions. Step6: Main function. Step7: Example The shape of the multi-head attention output is (batch_size, num_queries, num_hiddens).
Python Code: import numpy as np import matplotlib.pyplot as plt np.random.seed(seed=1) import math import collections try: import torch except ModuleNotFoundError: %pip install -qq torch import torch from torch import nn from torch.nn import functional as F !mkdir figures # for saving plots Explanation: Please find jax implementation of this notebook here: https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/book1/15/multi_head_attention_jax.ipynb <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/multi_head_attention.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Multi-head attention. We show how to multi-head attention. Based on sec 10.5 of http://d2l.ai/chapter_attention-mechanisms/multihead-attention.html. End of explanation def transpose_qkv(X, num_heads): # Shape of input `X`: # (`batch_size`, no. of queries or key-value pairs, `num_hiddens`). # Shape of output `X`: # (`batch_size`, no. of queries or key-value pairs, `num_heads`, # `num_hiddens` / `num_heads`) X = X.reshape(X.shape[0], X.shape[1], num_heads, -1) # Shape of output `X`: # (`batch_size`, `num_heads`, no. of queries or key-value pairs, # `num_hiddens` / `num_heads`) X = X.permute(0, 2, 1, 3) # Shape of `output`: # (`batch_size` * `num_heads`, no. of queries or key-value pairs, # `num_hiddens` / `num_heads`) return X.reshape(-1, X.shape[2], X.shape[3]) # @save def transpose_output(X, num_heads): Reverse the operation of `transpose_qkv` X = X.reshape(-1, num_heads, X.shape[1], X.shape[2]) X = X.permute(0, 2, 1, 3) return X.reshape(X.shape[0], X.shape[1], -1) Explanation: Implementation Utility functions. End of explanation def sequence_mask(X, valid_len, value=0): Mask irrelevant entries in sequences. maxlen = X.size(1) mask = torch.arange((maxlen), dtype=torch.float32, device=X.device)[None, :] < valid_len[:, None] X[~mask] = value return X def masked_softmax(X, valid_lens): Perform softmax operation by masking elements on the last axis. # `X`: 3D tensor, `valid_lens`: 1D or 2D tensor if valid_lens is None: return nn.functional.softmax(X, dim=-1) else: shape = X.shape if valid_lens.dim() == 1: valid_lens = torch.repeat_interleave(valid_lens, shape[1]) else: valid_lens = valid_lens.reshape(-1) # On the last axis, replace masked elements with a very large negative # value, whose exponentiation outputs 0 X = sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6) return nn.functional.softmax(X.reshape(shape), dim=-1) class DotProductAttention(nn.Module): Scaled dot product attention. def __init__(self, dropout, **kwargs): super(DotProductAttention, self).__init__(**kwargs) self.dropout = nn.Dropout(dropout) # Shape of `queries`: (`batch_size`, no. of queries, `d`) # Shape of `keys`: (`batch_size`, no. of key-value pairs, `d`) # Shape of `values`: (`batch_size`, no. of key-value pairs, value # dimension) # Shape of `valid_lens`: (`batch_size`,) or (`batch_size`, no. of queries) def forward(self, queries, keys, values, valid_lens=None): d = queries.shape[-1] # Set `transpose_b=True` to swap the last two dimensions of `keys` scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d) self.attention_weights = masked_softmax(scores, valid_lens) return torch.bmm(self.dropout(self.attention_weights), values) class MultiHeadAttention(nn.Module): def __init__(self, key_size, query_size, value_size, num_hiddens, num_heads, dropout, bias=False, **kwargs): super(MultiHeadAttention, self).__init__(**kwargs) self.num_heads = num_heads self.attention = DotProductAttention(dropout) self.W_q = nn.Linear(query_size, num_hiddens, bias=bias) self.W_k = nn.Linear(key_size, num_hiddens, bias=bias) self.W_v = nn.Linear(value_size, num_hiddens, bias=bias) self.W_o = nn.Linear(num_hiddens, num_hiddens, bias=bias) def forward(self, queries, keys, values, valid_lens): # Shape of `queries`, `keys`, or `values`: # (`batch_size`, no. of queries or key-value pairs, `num_hiddens`) # Shape of `valid_lens`: # (`batch_size`,) or (`batch_size`, no. of queries) # After transposing, shape of output `queries`, `keys`, or `values`: # (`batch_size` * `num_heads`, no. of queries or key-value pairs, # `num_hiddens` / `num_heads`) queries = transpose_qkv(self.W_q(queries), self.num_heads) keys = transpose_qkv(self.W_k(keys), self.num_heads) values = transpose_qkv(self.W_v(values), self.num_heads) if valid_lens is not None: # On axis 0, copy the first item (scalar or vector) for # `num_heads` times, then copy the next item, and so on valid_lens = torch.repeat_interleave(valid_lens, repeats=self.num_heads, dim=0) # Shape of `output`: (`batch_size` * `num_heads`, no. of queries, # `num_hiddens` / `num_heads`) output = self.attention(queries, keys, values, valid_lens) # Shape of `output_concat`: # (`batch_size`, no. of queries, `num_hiddens`) output_concat = transpose_output(output, self.num_heads) return self.W_o(output_concat) Explanation: Main function. End of explanation num_hiddens, num_heads = 100, 5 attention = MultiHeadAttention(num_hiddens, num_hiddens, num_hiddens, num_hiddens, num_heads, 0.5) attention.eval() batch_size, num_queries, num_kvpairs, valid_lens = 2, 4, 6, torch.tensor([3, 2]) X = torch.ones((batch_size, num_queries, num_hiddens)) Y = torch.ones((batch_size, num_kvpairs, num_hiddens)) attention(X, Y, Y, valid_lens).shape Explanation: Example The shape of the multi-head attention output is (batch_size, num_queries, num_hiddens). End of explanation
5,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Softmax exercise Adapt from the Stanford CS231n assignment1, find the original version on the course website. In this exercise we will Step5: Load CIFAR-10 data Load the data and split into training / validation / testing datasets. See notebook 00 for more details. Step7: Softmax Classifier Step8: Sanity Check In a randomly initiated weight, the loss should be close to $-\log(\frac{1}{10}) = -\log(0.1) \approx 2.303$ Step10: Vectorized loss function Step12: Stochastic Gradient Descent We now have vectorized and efficient expressions for the loss, the gradient and our gradient matches the numerical gradient. We are therefore ready to do SGD to minimize the loss.
Python Code: import random import time import numpy as np import matplotlib.pyplot as plt from cs231n.data_utils import load_CIFAR10 from cs231n.gradient_check import grad_check_sparse # plotting setting %matplotlib inline plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' Explanation: Softmax exercise Adapt from the Stanford CS231n assignment1, find the original version on the course website. In this exercise we will: implement a fully-vectorized loss function for the SVM implement the fully-vectorized expression for its analytic gradient check your implementation using numerical gradient use a validation set to tune the learning rate and regularization strength optimize the loss function with SGD visualize the final learned weights End of explanation def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000): Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the linear classifier. These are the same steps as we used for the SVM, but condensed to a single function. # Load the raw CIFAR-10 data cifar10_dir = 'cs231n/datasets/cifar-10-batches-py' X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir) # subsample the data mask = range(num_training, num_training + num_validation) X_val = X_train[mask] y_val = y_train[mask] mask = range(num_training) X_train = X_train[mask] y_train = y_train[mask] mask = range(num_test) X_test = X_test[mask] y_test = y_test[mask] # Preprocessing: reshape the image data into rows X_train = np.reshape(X_train, (X_train.shape[0], -1)) X_val = np.reshape(X_val, (X_val.shape[0], -1)) X_test = np.reshape(X_test, (X_test.shape[0], -1)) # Normalize the data: subtract the mean image mean_image = np.mean(X_train, axis = 0) X_train -= mean_image X_val -= mean_image X_test -= mean_image # add bias dimension and transform into columns X_train = np.hstack([X_train, np.ones((X_train.shape[0], 1))]).T X_val = np.hstack([X_val, np.ones((X_val.shape[0], 1))]).T X_test = np.hstack([X_test, np.ones((X_test.shape[0], 1))]).T return X_train, y_train, X_val, y_val, X_test, y_test # Invoke the above function to get our data. X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data() print('Train data shape:', X_train.shape) print('Train labels shape:', y_train.shape) print('Validation data shape:', X_val.shape) print('Validation labels shape:', y_val.shape) print('Test data shape:', X_test.shape) print('Test labels shape:', y_test.shape) class LinearClassifier: def __init__(self): self.W = None def train( self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100, batch_size=200, verbose=False, seed=None ): Train this linear classifier using stochastic gradient descent. Inputs: - X: D x N array of training data. Each training point is a D-dimensional column. - y: 1-dimensional array of length N with labels 0...K-1 for K classes. - learning_rate: (float) learning rate for optimization. - reg: (float) regularization strength. - num_iters: (integer) number of steps to take when optimizing. - batch_size: (integer) number of training examples to use at each step. - verbose: (boolean) If true, print progress during optimization. Outputs: A list containing the value of the loss function at each training iteration. dim, num_train = X.shape # assume y takes values 0...K-1 where K is number of classes num_classes = np.max(y) + 1 if self.W is None: # lazily initialize W self.W = np.random.randn(num_classes, dim) * 0.001 batch_rs = np.random.RandomState(seed) # Run stochastic gradient descent to optimize W loss_history = [] for it in range(num_iters): batch_ix = batch_rs.choice( np.arange(num_train), size=batch_size, replace=True ) X_batch = X[:, batch_ix] y_batch = y[batch_ix] # evaluate loss and gradient, internally use self.W loss, grad = self.loss(X_batch, y_batch, reg) loss_history.append(loss) # perform parameter update self.W -= grad * learning_rate if verbose and it % 100 == 0: print('iteration %d / %d: loss %f' % (it, num_iters, loss)) return loss_history def predict(self, X): Use the trained weights of this linear classifier to predict labels for data points. Inputs: - X: D x N array of training data. Each column is a D-dimensional point. Returns: - y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional array of length N, and each element is an integer giving the predicted class. score_pred = self.W.dot(X) # shape: C x N y_pred = score_pred.argmax(axis=0) return y_pred def loss(self, X_batch, y_batch, reg): Compute the loss function and its derivative. Subclasses will override this. Inputs: - X_batch: D x N array of data; each column is a data point. - y_batch: 1-dimensional array of length N with labels 0...K-1, for K classes. - reg: (float) regularization strength. Returns: A tuple containing: - loss as a single float - gradient with respect to self.W; an array of the same shape as W raise NotImplementedError Explanation: Load CIFAR-10 data Load the data and split into training / validation / testing datasets. See notebook 00 for more details. End of explanation def softmax_loss_naive(W, X, y, reg): Softmax loss function, naive implementation (with loops) Inputs: - W: C x D array of weights - X: D x N array of data. Data are D-dimensional columns - y: 1-dimensional array of length N with labels 0...K-1, for K classes - reg: (float) regularization strength Returns: a tuple of: - loss as single float - gradient with respect to weights W, an array of same size as W # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) num_train = X.shape[1] f = W.dot(X) # shape: C x N p = np.zeros(num_train, dtype=np.float) for i in range(num_train): f_i = f[:, i].copy() # shape C x 1 f_i -= np.max(f_i) # improve numerical stability f_i = np.exp(f_i) x_i = X[:, i] all_class_p_i = f_i / np.sum(f_i) p[i] = all_class_p_i[y[i]] # Update gradient # all_class_p_i no used later, don't copy dw_x_weight_i = all_class_p_i dw_x_weight_i[y[i]] -= 1 dW -= dw_x_weight_i[:, np.newaxis] * x_i[np.newaxis, :] loss += np.mean(-np.log(p)) # Add regularization loss += 0.5 * reg * np.sum(W * W) # Gradient # ref: http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression dW /= -num_train dW += reg * W return loss, dW Explanation: Softmax Classifier End of explanation %%time # Generate a random softmax weight matrix and use it to compute the loss. W = np.random.randn(10, 3073) * 0.0001 loss, grad = softmax_loss_naive(W, X_train, y_train, 0.0) # As a rough sanity check, our loss should be something close to -log(0.1). print('loss: %f' % loss) print('sanity check: %f' % (-np.log(0.1))) %%time # Complete the implementation of softmax_loss_naive and implement a (naive) # version of the gradient that uses nested loops. loss, grad = softmax_loss_naive(W, X_train, y_train, 0.0) # As we did for the SVM, use numeric gradient checking as a debugging tool. # The numeric gradient should be close to the analytic gradient. f = lambda w: softmax_loss_naive(w, X_train, y_train, 0.0)[0] grad_numerical = grad_check_sparse(f, W, grad, 5) # increase 5 here to check for more times Explanation: Sanity Check In a randomly initiated weight, the loss should be close to $-\log(\frac{1}{10}) = -\log(0.1) \approx 2.303$ End of explanation def softmax_loss_vectorized(W, X, y, reg): Softmax loss function, vectorized version. Inputs and outputs are the same as softmax_loss_naive. # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) num_train = X.shape[1] _train_ix = np.arange(num_train) # for sample coord 0...N-1 f = W.dot(X) # shape: C x N f -= np.max(f, axis=0) # improve numerical stability f = np.exp(f) p = f / np.sum(f, axis=0) # shape: C x N # loss function loss += np.mean(-np.log(p[y, _train_ix])) loss += 0.5 * reg * np.sum(W * W) # gradient # ref: http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression dW_x_weight = p # no use p later, don't copy dW_x_weight[y, _train_ix] -= 1 # CxD -= CxN dot NxD dW -= dW_x_weight.dot(X.T) dW /= -num_train dW += reg * W return loss, dW # Now that we have a naive implementation of the softmax loss function and its gradient, # implement a vectorized version in softmax_loss_vectorized. # The two versions should compute the same results, but the vectorized version should be # much faster. tic = time.time() loss_naive, grad_naive = softmax_loss_naive(W, X_train, y_train, 0.00001) toc = time.time() print('naive loss: %e computed in %fs' % (loss_naive, toc - tic)) tic = time.time() loss_vectorized, grad_vectorized = softmax_loss_vectorized(W, X_train, y_train, 0.00001) toc = time.time() print('vectorized loss: %e computed in %fs' % (loss_vectorized, toc - tic)) # The losses should match but your vectorized implementation should be much faster. # The loss is a single number, so it is easy to compare the values computed # by the two implementations. The gradient on the other hand is a matrix, so # we use the Frobenius norm to compare them. grad_difference = np.linalg.norm(grad_naive - grad_vectorized, ord='fro') print('Loss difference: %f' % np.abs(loss_naive - loss_vectorized)) print('Gradient difference: %f' % grad_difference) Explanation: Vectorized loss function End of explanation class Softmax(LinearClassifier): A subclass that uses the Softmax + Cross-entropy loss function def loss(self, X_batch, y_batch, reg): return softmax_loss_vectorized(self.W, X_batch, y_batch, reg) # Now implement SGD in LinearSVM.train() function and run it with the code below softmax = Softmax() tic = time.time() loss_hist = softmax.train( X_train, y_train, learning_rate = 5e-8, reg=1e3, # better params: # learning_rate=5e-7, reg=5e4, num_iters=1500, seed=9527, verbose=True ) toc = time.time() print('That took %fs' % (toc - tic)) # A useful debugging strategy is to plot the loss as a function of # iteration number: plt.plot(loss_hist) plt.xlabel('Iteration number') plt.ylabel('Loss value') plt.show() y_train_pred = softmax.predict(X_train) print('training accuracy: {:.3%}'.format(np.mean(y_train == y_train_pred))) y_val_pred = softmax.predict(X_val) print('validation accuracy: {:.3%}'.format(np.mean(y_val == y_val_pred))) # evaluate on test set # Evaluate the best svm on test set y_test_pred = softmax.predict(X_test) test_accuracy = np.mean(y_test == y_test_pred) print('softmax on raw pixels final test set accuracy: %f' % (test_accuracy, )) # Visualize the learned weights for each class w = softmax.W[:,:-1] # strip out the bias w = w.reshape(10, 32, 32, 3) w_min, w_max = np.min(w), np.max(w) classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'] for i in range(10): plt.subplot(2, 5, i + 1) # Rescale the weights to be between 0 and 255 wimg = 255.0 * (w[i].squeeze() - w_min) / (w_max - w_min) plt.imshow(wimg.astype('uint8')) plt.axis('off') plt.title(classes[i]) plt.show() Explanation: Stochastic Gradient Descent We now have vectorized and efficient expressions for the loss, the gradient and our gradient matches the numerical gradient. We are therefore ready to do SGD to minimize the loss. End of explanation
5,387
Given the following text description, write Python code to implement the functionality described below step by step Description: Preparing the data Data loading and putting it into a suitable format Parsing chord labels to binary pitch class sets for chord label dataset [x] see tools/add_pitch_class_sets.sh Joining DataFrames from each album and track into a common DataFrame Loading key labels and cleaning them silence/key [x] just root pitch class [x] convert minor keys to parallel majors [x] take care of trash such as D Step1: Keys Step2: Distribution of number of key segments among songs. Step3: We need to map symbolic key labels to pitch classes. Since the label are not always referring to the diatonic key but sometimes to modes, we normalize the pitch class to represent the underlying diatonic key. This would help in our further classification since it reduces the number of classes and their meaning. In order key we can limit ourselves not to discriminate between modes. Step4: Export the prepared DataFrame to TSV file. Step5: Chords Step6: Chords vs. keys - alignment Step7: Track lengths are not precisely aligned between chords and keys dataset. Roughly they're are alrigth, however. Step8: Merge chords and keys Step9: Let's try to merge keys to chords from a single example track. Step10: Append the computed key for each chord segment. Step11: Key distribution in chord segments. Step12: We can see that the key labels are heavily skewed and this might not be good for our ML models. In order to deskew the class distribution we can generate more data from the existing data by transposing each data point to all 12 keys. This way we'll have a 12x larger dataset and uniform classes. Step13: All key classes are now of uniform probability. Step14: Chord sequences Step15: Generate data points by reshaping input rows in the rolling window and selecting the most frequent output label. Do this for both original and synthetic data and for a different window sizes.
Python Code: def impute_missing_key_files(): path = 'data/beatles/keylab/The_Beatles/10CD2_-_The_Beatles/CD2_-_12_-_Revolution_9.lab' if not os.path.exists(path): df = pd.DataFrame.from_records( [("0.0", "502.204082", "Silence", None)], columns=['start', 'end', 'key_indicator', 'key_label']) df.to_csv(path, sep='\t', index=None, header=None) impute_missing_key_files() Explanation: Preparing the data Data loading and putting it into a suitable format Parsing chord labels to binary pitch class sets for chord label dataset [x] see tools/add_pitch_class_sets.sh Joining DataFrames from each album and track into a common DataFrame Loading key labels and cleaning them silence/key [x] just root pitch class [x] convert minor keys to parallel majors [x] take care of trash such as D:dorian Data sanity checks in each segment the end time is greater than the start time the start time of each segment is greater or equal than the end time of previous segment key segments are aligned with chord segments the files for each song should match between chords and keys each chord and key file should span the same time interval ie. end time of last chord and key segment in a song should be equal Features for key classification for each chord segment row we need the key choose the length of a chord context eg. 8 chords with 12 pitch classes per row it makes a block of 12*16 = 192 columns per row split the dataset into blocks of adjacent chords and put each block into a wide row -> new dataframe Missing data 10CD2_-_The_Beatles/CD2_-_12_-_Revolution_9.lab was missing in the original dataset we added "silence" throughout the song instead better would be to perform the actual annotation and add the right data End of explanation files = glob.glob('data/beatles/keylab/The_Beatles/*/*.lab') print('key files count:', len(files)) files def read_key_file(path): return pd.read_csv(path, sep='\t', header=None, names=['start','end','key_indicator','key_label']) read_key_file(files[0]) def add_track_id(df, track_id): df['track_id'] = track_id return df keys = pd.concat(add_track_id(read_key_file(file), track_id) for (track_id, file) in enumerate(files)) keys keys['duration'] = keys['end'] - keys['start'] keys['key_label'].value_counts() print('total number of key segments:', len(keys)) keys['duration'].describe() sns.distplot(keys['duration'], bins=50) title('distribution of key segment duration (sec)'); keys['key_indicator'].value_counts() # Total duration of segments with some key and with silence: keys.groupby('key_indicator').sum()['duration'] # The same in percentage: keys.groupby('key_indicator').sum()['duration'] / keys['duration'].sum() * 100 Explanation: Keys End of explanation keys.groupby('track_id').count()['start'].describe() Explanation: Distribution of number of key segments among songs. End of explanation diatonic_pitch_classes = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11} accidental_shifts = {'': 0, 'b': -1, '#': 1} mode_shifts = { '': 0, 'major': 0, 'ionian': 0, 'dorian': -2, 'phrygian': -4, 'lydian': -5, 'mixolydian': -7, 'aeolian': -9, 'minor': -9, 'locrian': -11} def tone_label_to_pitch_class(label): base = label[0].upper() pitch_class = diatonic_pitch_classes[base] accidental = label[1] if len(label) > 1 else '' shift = accidental_shifts[accidental] return ((pitch_class + shift) + 12) % 12 def diatonic_root_for_key_label(key_label): if type(key_label) is not str: return parts = key_label.split(':') modal_root_label = parts[0] modal_root_pitch_class = tone_label_to_pitch_class(modal_root_label) mode_label = parts[1].lower() if len(parts) > 1 else '' mode_shift = mode_shifts[mode_label] if mode_label in mode_shifts else 0 diatonic_root = modal_root_pitch_class + mode_shift # return (modal_root_label, mode_label, modal_root_pitch_class, mode_shift, diatonic_root) return (diatonic_root + 12) % 12 unique_key_labels = list(keys['key_label'].value_counts().index) [(label, diatonic_root_for_key_label(label)) for label in unique_key_labels] keys['key_diatonic_root'] = keys['key_label'].apply(diatonic_root_for_key_label) canonic_pitch_class_labels = dict(enumerate(['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'])) def label_for_pitch_class(pc): if pc in canonic_pitch_class_labels: return canonic_pitch_class_labels[pc] keys['key_diatonic_root_label'] = keys['key_diatonic_root'].apply(label_for_pitch_class) diatonic_keys_hist = keys.dropna()['key_diatonic_root_label'].value_counts() diatonic_keys_hist plot(diatonic_keys_hist) xticks(np.arange(len(diatonic_keys_hist)), diatonic_keys_hist.index) title('diatonic key usage among all songs'); # all tracks start at 0.0 time assert (keys.groupby('track_id').first()['start'] == 0).all() # duration of each segment should be positive # assert (keys.groupby('track_id')['duration'] < 0).all() keys.groupby('track_id').last()['end'] keys Explanation: We need to map symbolic key labels to pitch classes. Since the label are not always referring to the diatonic key but sometimes to modes, we normalize the pitch class to represent the underlying diatonic key. This would help in our further classification since it reduces the number of classes and their meaning. In order key we can limit ourselves not to discriminate between modes. End of explanation keys = keys[[ 'track_id', 'start', 'end', 'duration', 'key_indicator', 'key_label', 'key_diatonic_root_label', 'key_diatonic_root']] keys.to_csv('data/beatles/derived/all_keys.tsv', sep='\t', index=False, float_format='%.3f') Explanation: Export the prepared DataFrame to TSV file. End of explanation files = glob.glob('data/beatles/chordlab/The_Beatles/*/*.lab.pcs.tsv') print('chord files count:', len(files)) files def read_chord_file(path): return pd.read_csv(path, sep=' ', header=None, names=['start','end','chord_label']) def read_chord_file_with_pitch_classes(path): return pd.read_csv(path, sep='\t') read_chord_file_with_pitch_classes(files[0]) chords = pd.concat(add_track_id(read_chord_file_with_pitch_classes(file), track_id) for (track_id, file) in enumerate(files)) chords['duration'] = chords['end'] - chords['start'] chords = chords.reindex_axis(['track_id', 'start', 'end', 'duration', 'label', 'root', 'bass', 'C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B'], axis=1) chords # all tracks start at 0.0 time assert (chords.groupby('track_id').first()['start'] == 0).all() Explanation: Chords End of explanation chords_keys_end_diff = chords.groupby('track_id').last()[['end']].rename(columns={'end': 'chords_end'}).join(keys.groupby('track_id').last()[['end']].rename(columns={'end': 'keys_end'})) chords_keys_end_diff['diff'] = chords_keys_end_diff['chords_end'] - chords_keys_end_diff['keys_end'] chords_keys_end_diff['diff'].describe() Explanation: Chords vs. keys - alignment End of explanation chords_keys_end_diff chords_keys_end_diff['diff'].hist(bins=50); Explanation: Track lengths are not precisely aligned between chords and keys dataset. Roughly they're are alrigth, however. End of explanation chords.head() keys.head() Explanation: Merge chords and keys End of explanation track_keys = keys[keys['track_id'] == 109] track_keys track_chords = chords[chords['track_id'] == 109] track_chords def plot_time_intervals(starts, ends, **kwargs): x_lines = [el for (s, e) in zip(starts, ends) for el in (s, e, None)] y_lines = [el for i in range(len(starts)) for el in (i, i, None)] plot(x_lines, y_lines, **kwargs) def plot_chords_and_keys(track_chords, track_keys): plot_time_intervals(track_chords['start'], track_chords['end'], label='chord segments') plot_time_intervals(track_keys['start'], track_keys['end'], label='key segments') title('chord and key segments in time') legend(loc='center right') xlabel('time (sec)') ylabel('segment index') plot_chords_and_keys(track_chords, track_keys); def time_range(df, start, end): return df[(df['start'] >= start) & (df['end'] <= end)] plot_chords_and_keys(time_range(track_chords, 120, 220), time_range(track_keys, 120, 220)) def find_key(keys, track_id, start): "Finds the first key segment within a track that the chord segment spans." possible_keys = keys.query('(start <= '+str(start)+') & (track_id == '+str(track_id)+')') if len(possible_keys) > 0: row = possible_keys.iloc[-1] # return pd.Series([start, ['start']]) return row find_key(keys, 109, 198.0) track_chords['start'].apply(lambda start: find_key(track_keys, 109, start)[['key_diatonic_root_label', 'key_diatonic_root']]) track_keys track_chords chord = chords.iloc[0] keys_for_track = keys[keys['track_id'] == chord.track_id] keys_for_track[keys_for_track['start'] >= chord['start']] # this is very inefficient, it takes many seconds # TODO: optimize this! key_labels_for_chords = chords[['track_id','start']].apply( lambda row: find_key(keys, row['track_id'], row['start']), axis=1)[['key_diatonic_root_label', 'key_diatonic_root']] key_labels_for_chords[:10] Explanation: Let's try to merge keys to chords from a single example track. End of explanation for col in ('key_diatonic_root_label', 'key_diatonic_root'): chords[col] = key_labels_for_chords[col] chords Explanation: Append the computed key for each chord segment. End of explanation chords.key_diatonic_root_label.value_counts() chords.to_csv('data/beatles/derived/all_chords_with_keys.tsv', sep='\t', index=False, float_format='%.6f') Explanation: Key distribution in chord segments. End of explanation chords.head() def add_pitch_classes(a, b): return ((a + b) + 12) % 12 def rotate_columns(cols, shift): return cols[shift:] + cols[:shift] pcs_columns = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B'] [rotate_columns(pcs_columns, i) for i in range(12)] def rotate_binary_pcs_cols(df, cols, shift): return df.rename_axis(dict(zip(cols, rotate_columns(cols, shift))), axis=1) rotate_binary_pcs_cols(chords, pcs_columns, 2)[pcs_columns].head() chords[pcs_columns].head() def transpose_col(df, shift): return df.apply(lambda pc: add_pitch_classes(pc, shift)) transpose_col(chords[['root', 'bass', 'key_diatonic_root']], 11).head() def transpose_chords_df(chords, shift): chords_copy = chords.copy() chords_copy['synth_transposition'] = shift pc_cols = ['root', 'bass', 'key_diatonic_root'] chords_copy[pc_cols] = transpose_col(chords_copy[pc_cols], shift) chords_copy['key_diatonic_root_label'] = chords_copy['key_diatonic_root'].apply(label_for_pitch_class) chords_copy = rotate_binary_pcs_cols(chords_copy, pcs_columns, shift) chords_copy = chords_copy.rename_axis({'label': 'orig_chord_label'}, axis=1) return chords_copy transpose_chords_df(chords, 1).head() def generate_transpositions(chords): df = pd.concat([transpose_chords_df(chords, shift) for shift in range(12)]) df = df[['track_id', 'synth_transposition', 'start', 'end', 'duration', 'orig_chord_label', 'root', 'bass', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'key_diatonic_root_label', 'key_diatonic_root']] return df chords_all_synth = generate_transpositions(chords) chords_all_synth.columns len(chords_all_synth) Explanation: We can see that the key labels are heavily skewed and this might not be good for our ML models. In order to deskew the class distribution we can generate more data from the existing data by transposing each data point to all 12 keys. This way we'll have a 12x larger dataset and uniform classes. End of explanation chords_all_synth['key_diatonic_root'].value_counts() chords_all_synth[pcs_columns].mean() chords_all_synth.head() chords_all_synth[abs(chords_all_synth['start'] - 2.612267) < 1e-3] chords_all_synth.to_csv('data/beatles/derived/all_chords_with_keys_synth.tsv', sep='\t', index=False, float_format='%.6f') Explanation: All key classes are now of uniform probability. End of explanation chords_all = pd.read_csv('data/beatles/derived/all_chords_with_keys.tsv', sep='\t') chords_all_synth = pd.read_csv('data/beatles/derived/all_chords_with_keys_synth.tsv', sep='\t') chords_all = chords_all.dropna() chords_all_synth = chords_all_synth.dropna() chords_all.head() track_chords = chords_all[(chords_all['track_id'] == 40)].copy() track_chords.head(10) chords_all['key_index'] = ((chords_all['key_diatonic_root'].diff() != 0) | (chords_all['track_id'].diff() != 0)).cumsum() chords_all # track_chords.groupby(['track_id']).last()['key_index'] (chords_all.groupby(['track_id', 'key_index']).count()['start'] > 16).mean() c = chords_all[:200] c def pcs_block_cols(block_size): return ['%s_%02d'%(pc, i) for i in range(block_size) for pc in pcs_columns] def block_columns(block_size): return pcs_block_cols(block_size) + ['key_diatonic_root'] def merge_chord_block(block_df): all_pcs = block_df.as_matrix(columns=pcs_columns).ravel() most_frequent_key = block_df['key_diatonic_root'].value_counts().index[0] return np.hstack([all_pcs, most_frequent_key]) def roll_chords(chords_df, window_size=4): blocks = (chords_df.iloc[start:start+window_size] for start in range(len(chords_df) - window_size + 1)) c_rolling = (merge_chord_block(block) for block in blocks) df_rolling = pd.DataFrame(c_rolling, columns=block_columns(window_size)).astype(np.int16) return df_rolling Explanation: Chord sequences End of explanation # TODO: optimize this, since it is not really efficient (~20 minutes for all the files...) for postfix, chords in [('', chords_all), ('_synth', chords_all_synth)]: for window in (1,2,4,8,16): print('window:', window) chords_rolling = roll_chords(chords, window_size=window) print('shape:', chords_rolling.shape) chords_rolling.to_csv('data/beatles/derived/all_chords_with_keys'+postfix+'_rolling_'+str(window)+'.tsv', sep='\t', index=False) Explanation: Generate data points by reshaping input rows in the rolling window and selecting the most frequent output label. Do this for both original and synthetic data and for a different window sizes. End of explanation
5,388
Given the following text description, write Python code to implement the functionality described below step by step Description: Исследование поведения предложенного функционала. Часть I. Возьмем в качестве базисных функций $\cos(x)$, $\sin(x)$, $\cos(2x)$, $\sin(2x)$. Стоит посмотреть, как будет вести себя предлженная мера неинвариантности при использовании её для простых известных функций и простого оператора, например Step1: --------------------------------------------- Видно, что для достаточно большого $\alpha$ аппроксимируемая функция явно выходит за пределы линейной оболочки исходного набора. Это можно было бы строго показать, учитывая переодичность всех функций исходного набора(который имеет конечный размер) и непериодичность сигмоиды. При достаточно маленьком $\alpha$ мера неивариантости набора ожидаемо должна быть малой. (Да, тут нужно всегда оговариваться, что пока речь не идет о работе с оператором. Пока что просто представляем, что есть некоторый оператор, одной из комбинаций образов базиса которого аппроксимируемая функция и является.) ---------------------------------------------
Python Code: import numpy as np import tensorflow as tf from matplotlib import pylab as plt %matplotlib inline m = 4500 M = 4 a = -10 b = 10 x_grid = np.linspace(a, b, m, endpoint=True) sess = tf.Session() x = tf.placeholder(tf.double) trial_func = [tf.sin(x), tf.cos(x), tf.sin(2*x), tf.cos(2*x)] alpha = tf.Variable(1, dtype=tf.double) sess.run(tf.initializers.global_variables(), {x:x_grid}) alpha_loc = tf.placeholder(tf.double) ass_alpha = tf.assign(alpha, alpha_loc) y_set = [1*tf.sin(x), 0.1*tf.cos(x), tf.sin(2*x), alpha*tf.sigmoid(x), -3.1*tf.cos(2*x)] A = tf.transpose(trial_func) A_T = trial_func y_0 = tf.reduce_sum(input_tensor=y_set, axis=0) y = tf.expand_dims(y_0, -1) omega = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(A_T, A)), A_T), y) regression_fit = tf.matmul(tf.transpose(trial_func), omega) noninvariance_factor = (1 / m) * tf.reduce_sum(tf.square(y - regression_fit)) def plot_all(x_in,title): fig = plt.figure(figsize=(20,10)) func_set_matrix = sess.run(trial_func, {x:x_in}) plt.title(title, fontsize = 16) plt.grid(True) for i in range(np.array(trial_func).shape[0]): plt.plot(x_in, func_set_matrix[i]) plt.plot(x_in, sess.run(y_0, {x:x_in}), '--') plt.plot(x_in, sess.run(regression_fit, {x:x_in}), '--') noninv_list = [] i_list = [] local_alpha = 1e-5 x_grid_obs = np.linspace(a-5, b+5, 10000, endpoint=True) for i in range(15): sess.run(ass_alpha, {alpha_loc:local_alpha}) noninv_list.append(sess.run(noninvariance_factor, {x:x_grid})) i_list.append(local_alpha) if i==14: title = r'$\alpha$'+'='+ str(local_alpha) plot_all(x_grid_obs, title) if i==5: title = r'$\alpha$'+'='+ str(local_alpha) plot_all(x_grid_obs, title) if i==0: title = r'$\alpha$'+'='+ str(local_alpha) plot_all(x_grid_obs, title) local_alpha += 5 Explanation: Исследование поведения предложенного функционала. Часть I. Возьмем в качестве базисных функций $\cos(x)$, $\sin(x)$, $\cos(2x)$, $\sin(2x)$. Стоит посмотреть, как будет вести себя предлженная мера неинвариантности при использовании её для простых известных функций и простого оператора, например: $\frac{d^2 f}{dx^2}$ Однако, в качестве первого теста можно проверить, как будет вести себя значение этой меры если в качестве функции, к которой производится аппроксимация будет браться заданная комбинация функций, входящих в набор, затем та же комбинация с добавкой чего-то явно выходящего за пределы линейной оболочки исходного набора. Для этого берется сигмоида, умноженная на параметр. Результатом будет график зависимости меры неивариантности от значения этого параметра. End of explanation fig = plt.figure(figsize=(20,10)) plt.grid(True) plt.title('Noninvariance index', fontsize=26) plt.xlabel(r'$\alpha$', fontsize=20) plt.ylabel('J', fontsize=20) plt.plot(i_list, noninv_list, 'rx--') Explanation: --------------------------------------------- Видно, что для достаточно большого $\alpha$ аппроксимируемая функция явно выходит за пределы линейной оболочки исходного набора. Это можно было бы строго показать, учитывая переодичность всех функций исходного набора(который имеет конечный размер) и непериодичность сигмоиды. При достаточно маленьком $\alpha$ мера неивариантости набора ожидаемо должна быть малой. (Да, тут нужно всегда оговариваться, что пока речь не идет о работе с оператором. Пока что просто представляем, что есть некоторый оператор, одной из комбинаций образов базиса которого аппроксимируемая функция и является.) --------------------------------------------- End of explanation
5,389
Given the following text description, write Python code to implement the functionality described below step by step Description: Estimating Counts Think Bayes, Second Edition Copyright 2020 Allen B. Downey License Step1: In the previous chapter we solved problems that involve estimating proportions. In the Euro problem, we estimated the probability that a coin lands heads up, and in the exercises, you estimated a batting average, the fraction of people who cheat on their taxes, and the chance of shooting down an invading alien. Clearly, some of these problems are more realistic than others, and some are more useful than others. In this chapter, we'll work on problems related to counting, or estimating the size of a population. Again, some of the examples will seem silly, but some of them, like the German Tank problem, have real applications, sometimes in life and death situations. The Train Problem I found the train problem in Frederick Mosteller's, Fifty Challenging Problems in Probability with Solutions Step3: Now let's figure out the likelihood of the data. In a hypothetical fleet of $N$ locomotives, what is the probability that we would see number 60? If we assume that we are equally likely to see any locomotive, the chance of seeing any particular one is $1/N$. Here's the function that does the update Step4: This function might look familiar; it is the same as the update function for the dice problem in the previous chapter. In terms of likelihood, the train problem is the same as the dice problem. Here's the update Step5: Here's what the posterior looks like Step6: Not surprisingly, all values of $N$ below 60 have been eliminated. The most likely value, if you had to guess, is 60. Step7: That might not seem like a very good guess; after all, what are the chances that you just happened to see the train with the highest number? Nevertheless, if you want to maximize the chance of getting the answer exactly right, you should guess 60. But maybe that's not the right goal. An alternative is to compute the mean of the posterior distribution. Given a set of possible quantities, $q_i$, and their probabilities, $p_i$, the mean of the distribution is Step8: Or we can use the method provided by Pmf Step9: The mean of the posterior is 333, so that might be a good guess if you want to minimize error. If you played this guessing game over and over, using the mean of the posterior as your estimate would minimize the mean squared error over the long run. Sensitivity to the Prior The prior I used in the previous section is uniform from 1 to 1000, but I offered no justification for choosing a uniform distribution or that particular upper bound. We might wonder whether the posterior distribution is sensitive to the prior. With so little data---only one observation---it is. This table shows what happens as we vary the upper bound Step10: As we vary the upper bound, the posterior mean changes substantially. So that's bad. When the posterior is sensitive to the prior, there are two ways to proceed Step11: The differences are smaller, but apparently three trains are not enough for the posteriors to converge. Power Law Prior If more data are not available, another option is to improve the priors by gathering more background information. It is probably not reasonable to assume that a train-operating company with 1000 locomotives is just as likely as a company with only 1. With some effort, we could probably find a list of companies that operate locomotives in the area of observation. Or we could interview an expert in rail shipping to gather information about the typical size of companies. But even without getting into the specifics of railroad economics, we can make some educated guesses. In most fields, there are many small companies, fewer medium-sized companies, and only one or two very large companies. In fact, the distribution of company sizes tends to follow a power law, as Robert Axtell reports in Science (http Step12: For comparison, here's the uniform prior again. Step13: Here's what a power law prior looks like, compared to the uniform prior Step14: Here's the update for both priors. Step15: And here are the posterior distributions. Step16: The power law gives less prior probability to high values, which yields lower posterior means, and less sensitivity to the upper bound. Here's how the posterior means depend on the upper bound when we use a power law prior and observe three trains Step17: Now the differences are much smaller. In fact, with an arbitrarily large upper bound, the mean converges on 134. So the power law prior is more realistic, because it is based on general information about the size of companies, and it behaves better in practice. Credible Intervals So far we have seen two ways to summarize a posterior distribution Step19: With a power law prior and a dataset of three trains, the result is about 29%. So 100 trains is the 29th percentile. Going the other way, suppose we want to compute a particular percentile; for example, the median of a distribution is the 50th percentile. We can compute it by adding up probabilities until the total exceeds 0.5. Here's a function that does it Step20: The loop uses items, which iterates the quantities and probabilities in the distribution. Inside the loop we add up the probabilities of the quantities in order. When the total equals or exceeds prob, we return the corresponding quantity. This function is called quantile because it computes a quantile rather than a percentile. The difference is the way we specify prob. If prob is a percentage between 0 and 100, we call the corresponding quantity a percentile. If prob is a probability between 0 and 1, we call the corresponding quantity a quantile. Here's how we can use this function to compute the 50th percentile of the posterior distribution Step21: The result, 113 trains, is the median of the posterior distribution. Pmf provides a method called quantile that does the same thing. We can call it like this to compute the 5th and 95th percentiles Step22: The result is the interval from 91 to 243 trains, which implies Step23: The German Tank Problem During World War II, the Economic Warfare Division of the American Embassy in London used statistical analysis to estimate German production of tanks and other equipment. The Western Allies had captured log books, inventories, and repair records that included chassis and engine serial numbers for individual tanks. Analysis of these records indicated that serial numbers were allocated by manufacturer and tank type in blocks of 100 numbers, that numbers in each block were used sequentially, and that not all numbers in each block were used. So the problem of estimating German tank production could be reduced, within each block of 100 numbers, to a form of the train problem. Based on this insight, American and British analysts produced estimates substantially lower than estimates from other forms of intelligence. And after the war, records indicated that they were substantially more accurate. They performed similar analyses for tires, trucks, rockets, and other equipment, yielding accurate and actionable economic intelligence. The German tank problem is historically interesting; it is also a nice example of real-world application of statistical estimation. For more on this problem, see this Wikipedia page and Ruggles and Brodie, "An Empirical Approach to Economic Intelligence in World War II", Journal of the American Statistical Association, March 1947, available here. Informative Priors Among Bayesians, there are two approaches to choosing prior distributions. Some recommend choosing the prior that best represents background information about the problem; in that case the prior is said to be informative. The problem with using an informative prior is that people might have different information or interpret it differently. So informative priors might seem arbitrary. The alternative is a so-called uninformative prior, which is intended to be as unrestricted as possible, in order to let the data speak for itself. In some cases you can identify a unique prior that has some desirable property, like representing minimal prior information about the estimated quantity. Uninformative priors are appealing because they seem more objective. But I am generally in favor of using informative priors. Why? First, Bayesian analysis is always based on modeling decisions. Choosing the prior is one of those decisions, but it is not the only one, and it might not even be the most subjective. So even if an uninformative prior is more objective, the entire analysis is still subjective. Also, for most practical problems, you are likely to be in one of two situations Step24: Exercise Step25: Exercise Step26: Exercise Step27: For simplicity, let's assume that all families in the 4+ category have exactly 4 children. Step28: Exercise
Python Code: # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ import sys IN_COLAB = 'google.colab' in sys.modules if IN_COLAB: !pip install empiricaldist # Get utils.py from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print('Downloaded ' + local) download('https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/utils.py') from utils import set_pyplot_params set_pyplot_params() Explanation: Estimating Counts Think Bayes, Second Edition Copyright 2020 Allen B. Downey License: Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) End of explanation import numpy as np from empiricaldist import Pmf hypos = np.arange(1, 1001) prior = Pmf(1, hypos) Explanation: In the previous chapter we solved problems that involve estimating proportions. In the Euro problem, we estimated the probability that a coin lands heads up, and in the exercises, you estimated a batting average, the fraction of people who cheat on their taxes, and the chance of shooting down an invading alien. Clearly, some of these problems are more realistic than others, and some are more useful than others. In this chapter, we'll work on problems related to counting, or estimating the size of a population. Again, some of the examples will seem silly, but some of them, like the German Tank problem, have real applications, sometimes in life and death situations. The Train Problem I found the train problem in Frederick Mosteller's, Fifty Challenging Problems in Probability with Solutions: "A railroad numbers its locomotives in order 1..N. One day you see a locomotive with the number 60. Estimate how many locomotives the railroad has." Based on this observation, we know the railroad has 60 or more locomotives. But how many more? To apply Bayesian reasoning, we can break this problem into two steps: What did we know about $N$ before we saw the data? For any given value of $N$, what is the likelihood of seeing the data (a locomotive with number 60)? The answer to the first question is the prior. The answer to the second is the likelihood. We don't have much basis to choose a prior, so we'll start with something simple and then consider alternatives. Let's assume that $N$ is equally likely to be any value from 1 to 1000. Here's the prior distribution: End of explanation def update_train(pmf, data): Update pmf based on new data. hypos = pmf.qs likelihood = 1 / hypos impossible = (data > hypos) likelihood[impossible] = 0 pmf *= likelihood pmf.normalize() Explanation: Now let's figure out the likelihood of the data. In a hypothetical fleet of $N$ locomotives, what is the probability that we would see number 60? If we assume that we are equally likely to see any locomotive, the chance of seeing any particular one is $1/N$. Here's the function that does the update: End of explanation data = 60 posterior = prior.copy() update_train(posterior, data) Explanation: This function might look familiar; it is the same as the update function for the dice problem in the previous chapter. In terms of likelihood, the train problem is the same as the dice problem. Here's the update: End of explanation from utils import decorate posterior.plot(label='Posterior after train 60', color='C4') decorate(xlabel='Number of trains', ylabel='PMF', title='Posterior distribution') Explanation: Here's what the posterior looks like: End of explanation posterior.max_prob() Explanation: Not surprisingly, all values of $N$ below 60 have been eliminated. The most likely value, if you had to guess, is 60. End of explanation np.sum(posterior.ps * posterior.qs) Explanation: That might not seem like a very good guess; after all, what are the chances that you just happened to see the train with the highest number? Nevertheless, if you want to maximize the chance of getting the answer exactly right, you should guess 60. But maybe that's not the right goal. An alternative is to compute the mean of the posterior distribution. Given a set of possible quantities, $q_i$, and their probabilities, $p_i$, the mean of the distribution is: $$\mathrm{mean} = \sum_i p_i q_i$$ Which we can compute like this: End of explanation posterior.mean() Explanation: Or we can use the method provided by Pmf: End of explanation import pandas as pd df = pd.DataFrame(columns=['Posterior mean']) df.index.name = 'Upper bound' for high in [500, 1000, 2000]: hypos = np.arange(1, high+1) pmf = Pmf(1, hypos) update_train(pmf, data=60) df.loc[high] = pmf.mean() df Explanation: The mean of the posterior is 333, so that might be a good guess if you want to minimize error. If you played this guessing game over and over, using the mean of the posterior as your estimate would minimize the mean squared error over the long run. Sensitivity to the Prior The prior I used in the previous section is uniform from 1 to 1000, but I offered no justification for choosing a uniform distribution or that particular upper bound. We might wonder whether the posterior distribution is sensitive to the prior. With so little data---only one observation---it is. This table shows what happens as we vary the upper bound: End of explanation df = pd.DataFrame(columns=['Posterior mean']) df.index.name = 'Upper bound' dataset = [30, 60, 90] for high in [500, 1000, 2000]: hypos = np.arange(1, high+1) pmf = Pmf(1, hypos) for data in dataset: update_train(pmf, data) df.loc[high] = pmf.mean() df Explanation: As we vary the upper bound, the posterior mean changes substantially. So that's bad. When the posterior is sensitive to the prior, there are two ways to proceed: Get more data. Get more background information and choose a better prior. With more data, posterior distributions based on different priors tend to converge. For example, suppose that in addition to train 60 we also see trains 30 and 90. Here's how the posterior means depend on the upper bound of the prior, when we observe three trains: End of explanation alpha = 1.0 ps = hypos**(-alpha) power = Pmf(ps, hypos, name='power law') power.normalize() Explanation: The differences are smaller, but apparently three trains are not enough for the posteriors to converge. Power Law Prior If more data are not available, another option is to improve the priors by gathering more background information. It is probably not reasonable to assume that a train-operating company with 1000 locomotives is just as likely as a company with only 1. With some effort, we could probably find a list of companies that operate locomotives in the area of observation. Or we could interview an expert in rail shipping to gather information about the typical size of companies. But even without getting into the specifics of railroad economics, we can make some educated guesses. In most fields, there are many small companies, fewer medium-sized companies, and only one or two very large companies. In fact, the distribution of company sizes tends to follow a power law, as Robert Axtell reports in Science (http://www.sciencemag.org/content/293/5536/1818.full.pdf). This law suggests that if there are 1000 companies with fewer than 10 locomotives, there might be 100 companies with 100 locomotives, 10 companies with 1000, and possibly one company with 10,000 locomotives. Mathematically, a power law means that the number of companies with a given size, $N$, is proportional to $(1/N)^{\alpha}$, where $\alpha$ is a parameter that is often near 1. We can construct a power law prior like this: End of explanation hypos = np.arange(1, 1001) uniform = Pmf(1, hypos, name='uniform') uniform.normalize() Explanation: For comparison, here's the uniform prior again. End of explanation uniform.plot(color='C4') power.plot(color='C1') decorate(xlabel='Number of trains', ylabel='PMF', title='Prior distributions') Explanation: Here's what a power law prior looks like, compared to the uniform prior: End of explanation dataset = [60] update_train(uniform, dataset) update_train(power, dataset) Explanation: Here's the update for both priors. End of explanation uniform.plot(color='C4') power.plot(color='C1') decorate(xlabel='Number of trains', ylabel='PMF', title='Posterior distributions') Explanation: And here are the posterior distributions. End of explanation df = pd.DataFrame(columns=['Posterior mean']) df.index.name = 'Upper bound' alpha = 1.0 dataset = [30, 60, 90] for high in [500, 1000, 2000]: hypos = np.arange(1, high+1) ps = hypos**(-alpha) power = Pmf(ps, hypos) for data in dataset: update_train(power, data) df.loc[high] = power.mean() df Explanation: The power law gives less prior probability to high values, which yields lower posterior means, and less sensitivity to the upper bound. Here's how the posterior means depend on the upper bound when we use a power law prior and observe three trains: End of explanation power.prob_le(100) Explanation: Now the differences are much smaller. In fact, with an arbitrarily large upper bound, the mean converges on 134. So the power law prior is more realistic, because it is based on general information about the size of companies, and it behaves better in practice. Credible Intervals So far we have seen two ways to summarize a posterior distribution: the value with the highest posterior probability (the MAP) and the posterior mean. These are both point estimates, that is, single values that estimate the quantity we are interested in. Another way to summarize a posterior distribution is with percentiles. If you have taken a standardized test, you might be familiar with percentiles. For example, if your score is the 90th percentile, that means you did as well as or better than 90\% of the people who took the test. If we are given a value, x, we can compute its percentile rank by finding all values less than or equal to x and adding up their probabilities. Pmf provides a method that does this computation. So, for example, we can compute the probability that the company has less than or equal to 100 trains: End of explanation def quantile(pmf, prob): Compute a quantile with the given prob. total = 0 for q, p in pmf.items(): total += p if total >= prob: return q return np.nan Explanation: With a power law prior and a dataset of three trains, the result is about 29%. So 100 trains is the 29th percentile. Going the other way, suppose we want to compute a particular percentile; for example, the median of a distribution is the 50th percentile. We can compute it by adding up probabilities until the total exceeds 0.5. Here's a function that does it: End of explanation quantile(power, 0.5) Explanation: The loop uses items, which iterates the quantities and probabilities in the distribution. Inside the loop we add up the probabilities of the quantities in order. When the total equals or exceeds prob, we return the corresponding quantity. This function is called quantile because it computes a quantile rather than a percentile. The difference is the way we specify prob. If prob is a percentage between 0 and 100, we call the corresponding quantity a percentile. If prob is a probability between 0 and 1, we call the corresponding quantity a quantile. Here's how we can use this function to compute the 50th percentile of the posterior distribution: End of explanation power.quantile([0.05, 0.95]) Explanation: The result, 113 trains, is the median of the posterior distribution. Pmf provides a method called quantile that does the same thing. We can call it like this to compute the 5th and 95th percentiles: End of explanation power.credible_interval(0.9) Explanation: The result is the interval from 91 to 243 trains, which implies: The probability is 5% that the number of trains is less than or equal to 91. The probability is 5% that the number of trains is greater than 243. Therefore the probability is 90% that the number of trains falls between 91 and 243 (excluding 91 and including 243). For this reason, this interval is called a 90% credible interval. Pmf also provides credible_interval, which computes an interval that contains the given probability. End of explanation # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here Explanation: The German Tank Problem During World War II, the Economic Warfare Division of the American Embassy in London used statistical analysis to estimate German production of tanks and other equipment. The Western Allies had captured log books, inventories, and repair records that included chassis and engine serial numbers for individual tanks. Analysis of these records indicated that serial numbers were allocated by manufacturer and tank type in blocks of 100 numbers, that numbers in each block were used sequentially, and that not all numbers in each block were used. So the problem of estimating German tank production could be reduced, within each block of 100 numbers, to a form of the train problem. Based on this insight, American and British analysts produced estimates substantially lower than estimates from other forms of intelligence. And after the war, records indicated that they were substantially more accurate. They performed similar analyses for tires, trucks, rockets, and other equipment, yielding accurate and actionable economic intelligence. The German tank problem is historically interesting; it is also a nice example of real-world application of statistical estimation. For more on this problem, see this Wikipedia page and Ruggles and Brodie, "An Empirical Approach to Economic Intelligence in World War II", Journal of the American Statistical Association, March 1947, available here. Informative Priors Among Bayesians, there are two approaches to choosing prior distributions. Some recommend choosing the prior that best represents background information about the problem; in that case the prior is said to be informative. The problem with using an informative prior is that people might have different information or interpret it differently. So informative priors might seem arbitrary. The alternative is a so-called uninformative prior, which is intended to be as unrestricted as possible, in order to let the data speak for itself. In some cases you can identify a unique prior that has some desirable property, like representing minimal prior information about the estimated quantity. Uninformative priors are appealing because they seem more objective. But I am generally in favor of using informative priors. Why? First, Bayesian analysis is always based on modeling decisions. Choosing the prior is one of those decisions, but it is not the only one, and it might not even be the most subjective. So even if an uninformative prior is more objective, the entire analysis is still subjective. Also, for most practical problems, you are likely to be in one of two situations: either you have a lot of data or not very much. If you have a lot of data, the choice of the prior doesn't matter; informative and uninformative priors yield almost the same results. If you don't have much data, using relevant background information (like the power law distribution) makes a big difference. And if, as in the German tank problem, you have to make life and death decisions based on your results, you should probably use all of the information at your disposal, rather than maintaining the illusion of objectivity by pretending to know less than you do. Summary This chapter introduces the train problem, which turns out to have the same likelihood function as the dice problem, and which can be applied to the German Tank problem. In all of these examples, the goal is to estimate a count, or the size of a population. In the next chapter, I'll introduce "odds" as an alternative to probabilities, and Bayes's Rule as an alternative form of Bayes's Theorem. We'll compute distributions of sums and products, and use them to estimate the number of Members of Congress who are corrupt, among other problems. But first, you might want to work on these exercises. Exercises Exercise: Suppose you are giving a talk in a large lecture hall and the fire marshal interrupts because they think the audience exceeds 1200 people, which is the safe capacity of the room. You think there are fewer then 1200 people, and you offer to prove it. It would take too long to count, so you try an experiment: You ask how many people were born on May 11 and two people raise their hands. You ask how many were born on May 23 and 1 person raises their hand. Finally, you ask how many were born on August 1, and no one raises their hand. How many people are in the audience? What is the probability that there are more than 1200 people. Hint: Remember the binomial distribution. End of explanation # Solution goes here # Solution goes here # Solution goes here Explanation: Exercise: I often see rabbits in the garden behind my house, but it's not easy to tell them apart, so I don't really know how many there are. Suppose I deploy a motion-sensing camera trap that takes a picture of the first rabbit it sees each day. After three days, I compare the pictures and conclude that two of them are the same rabbit and the other is different. How many rabbits visit my garden? To answer this question, we have to think about the prior distribution and the likelihood of the data: I have sometimes seen four rabbits at the same time, so I know there are at least that many. I would be surprised if there were more than 10. So, at least as a starting place, I think a uniform prior from 4 to 10 is reasonable. To keep things simple, let's assume that all rabbits who visit my garden are equally likely to be caught by the camera trap in a given day. Let's also assume it is guaranteed that the camera trap gets a picture every day. End of explanation # Solution goes here # Solution goes here # Solution goes here Explanation: Exercise: Suppose that in the criminal justice system, all prison sentences are either 1, 2, or 3 years, with an equal number of each. One day, you visit a prison and choose a prisoner at random. What is the probability that they are serving a 3-year sentence? What is the average remaining sentence of the prisoners you observe? End of explanation import matplotlib.pyplot as plt qs = [1, 2, 3, 4] ps = [22, 41, 24, 14] prior = Pmf(ps, qs) prior.bar(alpha=0.7) plt.xticks(qs, ['1 child', '2 children', '3 children', '4+ children']) decorate(ylabel='PMF', title='Distribution of family size') Explanation: Exercise: If I chose a random adult in the U.S., what is the probability that they have a sibling? To be precise, what is the probability that their mother has had at least one other child. This article from the Pew Research Center provides some relevant data. From it, I extracted the following distribution of family size for mothers in the U.S. who were 40-44 years old in 2014: End of explanation # Solution goes here # Solution goes here # Solution goes here Explanation: For simplicity, let's assume that all families in the 4+ category have exactly 4 children. End of explanation # Solution goes here # Solution goes here # Solution goes here Explanation: Exercise: The Doomsday argument is "a probabilistic argument that claims to predict the number of future members of the human species given an estimate of the total number of humans born so far." Suppose there are only two kinds of intelligent civilizations that can happen in the universe. The "short-lived" kind go exinct after only 200 billion individuals are born. The "long-lived" kind survive until 2,000 billion individuals are born. And suppose that the two kinds of civilization are equally likely. Which kind of civilization do you think we live in? The Doomsday argument says we can use the total number of humans born so far as data. According to the Population Reference Bureau, the total number of people who have ever lived is about 108 billion. Since you were born quite recently, let's assume that you are, in fact, human being number 108 billion. If $N$ is the total number who will ever live and we consider you to be a randomly-chosen person, it is equally likely that you could have been person 1, or $N$, or any number in between. So what is the probability that you would be number 108 billion? Given this data and dubious prior, what is the probability that our civilization will be short-lived? End of explanation
5,390
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright (c) 2015, 2016 Sebastian Raschka <br> 2016 Li-Yi Wei https Step1: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see Step2: Learning with ensembles Challenge Step3: Note For historical reasons, Python 2.7's math.ceil returns a float instead of an integer like in Python 3.x. Although Although this book was written for Python >3.4, let's make it compatible to Python 2.7 by casting it to an it explicitely Step4: The ensemble outperforms individual classifiers as long as their base error $\epsilon < 0.5$. Excercise Plot ensembe error versus different number of classifiers. Does the ensemble error always go down with more classifiers? Why or why not? Can you fix the issue? Ensemble bias and variance $d_j$ are decisions made by $m$ individual base classifiers $y$ is the ensemble decision via summation (not really voting for mathematical tractability) Step5: Weighted probability If the individual classifiers can provide prediction probability $$ p\left(C_j(x) = i\right) $$ , such as predict_prob() in scikit-learn, we can also predict ensemble class probability Step11: Majority classifier implementation Step12: Combining different algorithms for classification with majority vote Let's apply the class we wrote above for classification. Load the dataset Use only 2 features for more challenge Only last 100 samples in 2 classes Step13: Build individual classifiers Mixed types * logistic regression * decision tree * knn Step14: Majority vote Step15: Notice the better performance of ensemble learning Evaluating and tuning the ensemble classifier Plot ROC curves for test data TP (true positive) versus FP (false positive) rates Step16: Plot decision regions Step17: Notice the decision boundary from majority voting is a combination of the 3 base classifiers. Hyper-parameter tuning for ensemble learning Get the parameter names Step18: Grid search parameters Step19: Observations Step20: Bagging -- Building an ensemble of classifiers from bootstrap samples Use random subsets of samples for each base classifier. * bootstrap samples Step21: Encoding and splitting Step22: Bagging classifier Step23: Notice bagging has less over-fitting than decision tree. Visualize decision regions Use meshgrid and isocontour as usual. Step24: Notice the smoother decision boundaries of bagging than decision tree. Bagging can reduce variance, but not bias. Choose base classifiers with low bias, such as unpruned decision trees. Leveraging weak learners via adaptive boosting AdaBoost for abbreviation A collection of weak base learners (diversity over accuracy) * sequential learning * later classifiers focus on the weak parts (mis-classified samples) of the earlier classifiers Original boosting procedure [Schapire 1990] Using 3 classifiers Training Step25: 10 sample example $\epsilon = 0.3$ $\alpha = 0.5\log_e(0.7/0.3) = 0.424$ $w$ before normalization Step26: Better training performance by AdaBoost, but with more overfitting than bagging
Python Code: %load_ext watermark %watermark -a '' -u -d -v -p numpy,pandas,matplotlib,scipy,sklearn Explanation: Copyright (c) 2015, 2016 Sebastian Raschka <br> 2016 Li-Yi Wei https://github.com/1iyiwei/pyml MIT License Python Machine Learning - Code Examples Chapter 7 - Combining Different Models for Ensemble Learning Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s). End of explanation from IPython.display import Image %matplotlib inline # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version Explanation: The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see: https://github.com/rasbt/watermark. Overview Learning with ensembles Implementing a simple majority vote classifier Combining different algorithms for classification with majority vote Evaluating and tuning the ensemble classifier Bagging – building an ensemble of classifiers from bootstrap samples Leveraging weak learners via adaptive boosting Summary End of explanation # combinatorial C(n, k) from scipy.misc import comb import math def ensemble_error(n_classifier, error): k_start = math.ceil(n_classifier / 2.0) probs = [comb(n_classifier, k) * error**k * (1-error)**(n_classifier - k) for k in range(k_start, n_classifier + 1)] return sum(probs) Explanation: Learning with ensembles Challenge: * No single classifier best for all circumstances * Hard to manually decide which classifier/model to use Solution: * Combine multipler classifiers for better performance than each individual classifier * Need diverse, not just accurate, individual classifiers <a href="https://en.wikipedia.org/wiki/The_Wisdom_of_Crowds"><img src="https://upload.wikimedia.org/wikipedia/en/9/95/Wisecrowds.jpg" align=right></a> Unanimity no voting necessary Majority voting for binary classification For sample $x$, each classifier $j$ decides whether the class $C_j(x)$ is $+1$ or $-1$ Majority voting is then: $$ C(x) = sign\left[ \sum_j C_j(x) \right] = \begin{cases} +1 \; if \; \sum_j C_j(x) \geq 0\ -1 \; else \end{cases} $$ Plurality voting extension of majority voting for multi-class setting $$ C(x) = mode{C_1(x), C_2(x), \cdots, C_m(x) } $$ <img src='./images/07_01.png' width=80%> Individual classifiers can be the same or different types * decision tree, svm, logistic regression, etc. Random forest * combines multiple decision trees <img src='./images/07_02.png' width=70%> Why ensemble can better than individual classifiers A simple math model: * binary classification * $n$ base classifiers * each with error rate $\epsilon$ * classifiers make independent decisions Probability that at least $K$ classifiers are wrong: $$ \begin{align} \epsilon_{ensemble} (K) &= \sum_{k=K}^n C\left(n, k\right) \epsilon^k \left(1-\epsilon\right)^{n-k} \end{align} $$ , where $C\left(n, k\right)$ is the combinatorial, i.e. binomial coefficient of n choosing k. For the ensemble to be wrong, $K \geq \frac{n}{2}$: $$ \epsilon_{ensemble} = \epsilon_{ensemble}\left( \left\lceil \frac{n}{2} \right\rceil \right) $$ For example, if * $n = 11$ * $\epsilon = 0.25$ $\epsilon_{ensemble} = 0.034$ The above assumes classifiers are making independent decisions! Humans don't always make independent decisions * elections * financial markets <a href="https://books.google.com.hk/books/about/Manias_Panics_and_Crashes.html"> <img src="https://books.google.com.hk/books/content?id=Er-6QkkQkeEC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE73PgBQLrAIbIXBTXGzeLHPtVy8RRIMF2BN_ugz1l41rEK14FFNcYrKhN2pcU0jdU0vFvIPMCmpWAqKPnJ1PxjnQLzckEiNGJ74SMKbIl3DL2Ct7tkQEgTsRyZl-t_LQeA5W-nc3" align=right> </a> End of explanation from scipy.misc import comb import math def ensemble_error(n_classifier, error): k_start = int(math.ceil(n_classifier / 2.0)) probs = [comb(n_classifier, k) * error**k * (1-error)**(n_classifier - k) for k in range(k_start, n_classifier + 1)] return sum(probs) ensemble_error(n_classifier=11, error=0.25) import numpy as np error_range = np.arange(0.0, 1.01, 0.01) ens_errors = [ensemble_error(n_classifier=11, error=error) for error in error_range] import matplotlib.pyplot as plt plt.plot(error_range, ens_errors, label='Ensemble error', linewidth=2) plt.plot(error_range, error_range, linestyle='--', label='Base error', linewidth=2) plt.xlabel('Base error') plt.ylabel('Base/Ensemble error') plt.legend(loc='upper left') plt.grid() plt.tight_layout() # plt.savefig('./figures/ensemble_err.png', dpi=300) plt.show() Explanation: Note For historical reasons, Python 2.7's math.ceil returns a float instead of an integer like in Python 3.x. Although Although this book was written for Python >3.4, let's make it compatible to Python 2.7 by casting it to an it explicitely: End of explanation import numpy as np np.argmax(np.bincount([0, 0, 1], weights=[0.2, 0.2, 0.6])) Explanation: The ensemble outperforms individual classifiers as long as their base error $\epsilon < 0.5$. Excercise Plot ensembe error versus different number of classifiers. Does the ensemble error always go down with more classifiers? Why or why not? Can you fix the issue? Ensemble bias and variance $d_j$ are decisions made by $m$ individual base classifiers $y$ is the ensemble decision via summation (not really voting for mathematical tractability): $$ y = \frac{1}{m} \sum_{j=1}^m d_j $$ For iid: $$ \begin{align} E(y) &= E\left( \frac{1}{m} \sum_{j=1}^m d_j \right) = E(d_j) \ Var(y) &= Var\left( \frac{1}{m} \sum_{j=1}^m d_j \right) = \frac{1}{m} Var(d_j) \end{align} $$ * The expected value E, and thus bias, remains the same. * The variance reduces. For general case: $$ \begin{align} Var(y) &= Var\left( \frac{1}{m} \sum_{j=1}^m d_j \right) \ & = \frac{1}{m^2} \sum_j Var(d_j) + \frac{1}{m^2} \sum_j \sum_{i \neq j} Cov(d_j, d_i) \end{align} $$ So $Var(y)$ increases/decreases for positively/negatively correlated base estimators. Diversity versus accuracy Not possible to have all base estimators accurate and yet negatively correlated. Why? * accurate estimators tend to make correct predictions * correct predictions, by definition, are positively correlated with themselves Sometimes need intentionally non-optimal base learners for better ensemble performance How to achieve diversification and accuracy Different models/algorithms * base learners complement each other * e.g. some parametric, some non-parametric Different hyper-parameters for the same algorithm/model * k in KNN * threshold in decision tree * kernel function in SVM * initial weights for perceptron and neural networks Different input representations of the same event * sensor fusion, sound and mouth shape for speech recognition * random subset of features (columns of the data matrix) Different training sets * random subset of all samples (rows of the data matrix) - bagging * sequential training - boosting, cascading inaccurately classified samples Base learners be reasonably instead of very accurate How to combine multiple classifiers Parallel: multi-expert combination Base learners work in parallel Global approach * all base learners generate outputs for a given input: voting, bagging Local approach * select only a few base learners based on the input: gating for mixture of experts Sequential: multi-stage combination Base learners work in series Later models focus on datasets not well handled by early models: cascading Start with simpler models, and increase model complexity only if necessary Implementing a simple majority vote classifier A (multi-class) majority vote classifier can be implemented via the weighted sum of $m$ individual classifier prediction: $$ \hat{y} = argmax_i \sum_{j=1}^m w_j \left( C_j(x) = i \right) $$ Here, $C_j(x) = i$ is a boolean expression for classifier $j$ to predict the class of $x$ to be $i$. The weights can come from confidence, accuracy, or Bayesian prior of each classifier. $$ p(C(x) = i) = \sum_{j=1}^m p(C_j) p\left( C_j(x) = i \; | \; C_j \right) $$ Equal weighting If the individual classifiers are weighed equally, the above would reduce to what we see earlier: $$ \hat{y} = mode{C_1(x), C_2(x), \cdots, C_m(x) } $$ $C_1(x) = 0$, $C_2(x) = 0$, $C_3(x) = 1$ $\rightarrow$ $\hat{y} = mode{0, 0, 1} = 0$ Unequal weighting $w_1 = 0.2$, $w_2 = 0.2$, $w_3 = 0.6$ $\rightarrow$ $ \begin{cases} 0.4 & class \; 0 \ 0.6 & class \; 1 \end{cases} $ $\rightarrow$ $\hat{y} = 1$ End of explanation ex = np.array([[0.9, 0.1], [0.8, 0.2], [0.4, 0.6]]) p = np.average(ex, axis=0, weights=[0.2, 0.2, 0.6]) p np.argmax(p) Explanation: Weighted probability If the individual classifiers can provide prediction probability $$ p\left(C_j(x) = i\right) $$ , such as predict_prob() in scikit-learn, we can also predict ensemble class probability: $$ \begin{align} p\left(C_{ensemble}(x) = i \right) &= \sum_{j=1}^m w_j p\left( C_j(x) = i \right) \end{align} $$ From which we can decide the predicted class (i.e. predict() in scikit-learn): $$ \hat{y} = argmax_i \; p\left(C_{ensemble}(x) = i \right) $$ In the 2-class 3-classifier example above, $w_1 = 0.2$, $w_2 = 0.2$, $w_3 = 0.6$ $$ \begin{align} C_1(x) &= [0.9, 0.1] \ C_2(x) &= [0.8, 0.2] \ C_3(x) &= [0.4, 0.6] \end{align} $$ Then $$ \begin{align} p\left(C_{ensemble} = 0\right) &= 0.2 \times 0.9 + 0.2 \times 0.8 + 0.6 \times 0.4 = 0.58 \ p\left(C_{ensemble} = 1 \right) &= 0.2 \times 0.1 + 0.2 \times 0.2 + 0.6 \times 0.6 = 0.42 \end{align} $$ $$ \hat{y} = 0 $$ End of explanation from sklearn.base import BaseEstimator from sklearn.base import ClassifierMixin from sklearn.preprocessing import LabelEncoder from sklearn.externals import six from sklearn.base import clone from sklearn.pipeline import _name_estimators import numpy as np import operator # inherits from two classes to get some methods for free class MajorityVoteClassifier(BaseEstimator, ClassifierMixin): A majority vote ensemble classifier Parameters ---------- classifiers : array-like, shape = [n_classifiers] Different classifiers for the ensemble vote : str, {'classlabel', 'probability'} (default='label') If 'classlabel' the prediction is based on the argmax of class labels. Else if 'probability', the argmax of the sum of probabilities is used to predict the class label (recommended for calibrated classifiers). weights : array-like, shape = [n_classifiers], optional (default=None) If a list of `int` or `float` values are provided, the classifiers are weighted by importance; Uses uniform weights if `weights=None`. def __init__(self, classifiers, vote='classlabel', weights=None): self.classifiers = classifiers self.named_classifiers = {key: value for key, value in _name_estimators(classifiers)} self.vote = vote self.weights = weights def fit(self, X, y): Fit classifiers. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Matrix of training samples. y : array-like, shape = [n_samples] Vector of target class labels. Returns ------- self : object if self.vote not in ('probability', 'classlabel'): raise ValueError("vote must be 'probability' or 'classlabel'" "; got (vote=%r)" % self.vote) if self.weights and len(self.weights) != len(self.classifiers): raise ValueError('Number of classifiers and weights must be equal' '; got %d weights, %d classifiers' % (len(self.weights), len(self.classifiers))) # Use LabelEncoder to ensure class labels start with 0, which # is important for np.argmax call in self.predict self.lablenc_ = LabelEncoder() self.lablenc_.fit(y) self.classes_ = self.lablenc_.classes_ self.classifiers_ = [] for clf in self.classifiers: fitted_clf = clone(clf).fit(X, self.lablenc_.transform(y)) self.classifiers_.append(fitted_clf) return self def predict(self, X): Predict class labels for X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Matrix of training samples. Returns ---------- maj_vote : array-like, shape = [n_samples] Predicted class labels. if self.vote == 'probability': maj_vote = np.argmax(self.predict_proba(X), axis=1) else: # 'classlabel' vote # Collect results from clf.predict calls predictions = np.asarray([clf.predict(X) for clf in self.classifiers_]).T maj_vote = np.apply_along_axis( lambda x: np.argmax(np.bincount(x, weights=self.weights)), axis=1, arr=predictions) maj_vote = self.lablenc_.inverse_transform(maj_vote) return maj_vote def predict_proba(self, X): Predict class probabilities for X. Parameters ---------- X : {array-like, sparse matrix}, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. Returns ---------- avg_proba : array-like, shape = [n_samples, n_classes] Weighted average probability for each class per sample. probas = np.asarray([clf.predict_proba(X) for clf in self.classifiers_]) avg_proba = np.average(probas, axis=0, weights=self.weights) return avg_proba def get_params(self, deep=True): Get classifier parameter names for GridSearch if not deep: return super(MajorityVoteClassifier, self).get_params(deep=False) else: out = self.named_classifiers.copy() for name, step in six.iteritems(self.named_classifiers): for key, value in six.iteritems(step.get_params(deep=True)): out['%s__%s' % (name, key)] = value return out import numpy as np foo = np.asarray([np.random.uniform(size=4) for k in range(3)]) foo.shape Explanation: Majority classifier implementation End of explanation from sklearn import datasets from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import LabelEncoder if Version(sklearn_version) < '0.18': from sklearn.cross_validation import train_test_split else: from sklearn.model_selection import train_test_split iris = datasets.load_iris() X, y = iris.data[50:, [1, 2]], iris.target[50:] le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test =\ train_test_split(X, y, test_size=0.5, random_state=1) Explanation: Combining different algorithms for classification with majority vote Let's apply the class we wrote above for classification. Load the dataset Use only 2 features for more challenge Only last 100 samples in 2 classes End of explanation import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline if Version(sklearn_version) < '0.18': from sklearn.cross_validation import cross_val_score else: from sklearn.model_selection import cross_val_score clf1 = LogisticRegression(penalty='l2', C=0.001, random_state=0) clf2 = DecisionTreeClassifier(max_depth=1, criterion='entropy', random_state=0) clf3 = KNeighborsClassifier(n_neighbors=1, p=2, metric='minkowski') pipe1 = Pipeline([['sc', StandardScaler()], ['clf', clf1]]) pipe3 = Pipeline([['sc', StandardScaler()], ['clf', clf3]]) clf_labels = ['Logistic Regression', 'Decision Tree', 'KNN'] print('10-fold cross validation:\n') for clf, label in zip([pipe1, clf2, pipe3], clf_labels): scores = cross_val_score(estimator=clf, X=X_train, y=y_train, cv=10, scoring='roc_auc') print("ROC AUC: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) Explanation: Build individual classifiers Mixed types * logistic regression * decision tree * knn End of explanation # Majority Rule (hard) Voting mv_clf = MajorityVoteClassifier(classifiers=[pipe1, clf2, pipe3]) clf_labels += ['Majority Voting'] all_clf = [pipe1, clf2, pipe3, mv_clf] for clf, label in zip(all_clf, clf_labels): scores = cross_val_score(estimator=clf, X=X_train, y=y_train, cv=10, scoring='roc_auc') print("ROC AUC: %0.2f (+/- %0.2f) [%s]" % (scores.mean(), scores.std(), label)) Explanation: Majority vote End of explanation from sklearn.metrics import roc_curve from sklearn.metrics import auc colors = ['black', 'orange', 'blue', 'green'] linestyles = [':', '--', '-.', '-'] for clf, label, clr, ls \ in zip(all_clf, clf_labels, colors, linestyles): # assuming the label of the positive class is 1 y_pred = clf.fit(X_train, y_train).predict_proba(X_test)[:, 1] fpr, tpr, thresholds = roc_curve(y_true=y_test, y_score=y_pred) roc_auc = auc(x=fpr, y=tpr) plt.plot(fpr, tpr, color=clr, linestyle=ls, label='%s (auc = %0.2f)' % (label, roc_auc)) plt.legend(loc='lower right') plt.plot([0, 1], [0, 1], linestyle='--', color='gray', linewidth=2) plt.xlim([-0.1, 1.1]) plt.ylim([-0.1, 1.1]) plt.grid() plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') # plt.tight_layout() # plt.savefig('./figures/roc.png', dpi=300) plt.show() Explanation: Notice the better performance of ensemble learning Evaluating and tuning the ensemble classifier Plot ROC curves for test data TP (true positive) versus FP (false positive) rates End of explanation # for visualization purposes, not necessary for pipelines with standard scalar sc = StandardScaler() X_train_std = sc.fit_transform(X_train) from itertools import product all_clf = [pipe1, clf2, pipe3, mv_clf] x_min = X_train_std[:, 0].min() - 1 x_max = X_train_std[:, 0].max() + 1 y_min = X_train_std[:, 1].min() - 1 y_max = X_train_std[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(nrows=2, ncols=2, sharex='col', sharey='row', figsize=(7, 5)) for idx, clf, tt in zip(product([0, 1], [0, 1]), all_clf, clf_labels): clf.fit(X_train_std, y_train) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx[0], idx[1]].contourf(xx, yy, Z, alpha=0.3) axarr[idx[0], idx[1]].scatter(X_train_std[y_train==0, 0], X_train_std[y_train==0, 1], c='blue', marker='^', s=50) axarr[idx[0], idx[1]].scatter(X_train_std[y_train==1, 0], X_train_std[y_train==1, 1], c='red', marker='o', s=50) axarr[idx[0], idx[1]].set_title(tt) plt.text(-3.5, -4.5, s='Sepal width [standardized]', ha='center', va='center', fontsize=12) plt.text(-10.5, 4.5, s='Petal length [standardized]', ha='center', va='center', fontsize=12, rotation=90) plt.tight_layout() # plt.savefig('./figures/voting_panel', bbox_inches='tight', dpi=300) plt.show() Explanation: Plot decision regions End of explanation mv_clf.get_params() Explanation: Notice the decision boundary from majority voting is a combination of the 3 base classifiers. Hyper-parameter tuning for ensemble learning Get the parameter names End of explanation if Version(sklearn_version) < '0.18': from sklearn.grid_search import GridSearchCV else: from sklearn.model_selection import GridSearchCV params = {'decisiontreeclassifier__max_depth': [1, 2], 'pipeline-1__clf__C': [0.001, 0.1, 100.0]} grid = GridSearchCV(estimator=mv_clf, param_grid=params, cv=10, scoring='roc_auc') grid.fit(X_train, y_train) if Version(sklearn_version) < '0.18': for params, mean_score, scores in grid.grid_scores_: print("%0.3f +/- %0.2f %r" % (mean_score, scores.std() / 2.0, params)) else: cv_keys = ('mean_test_score', 'std_test_score','params') for r, _ in enumerate(grid.cv_results_['mean_test_score']): print("%0.3f +/- %0.2f %r" % (grid.cv_results_[cv_keys[0]][r], grid.cv_results_[cv_keys[1]][r] / 2.0, grid.cv_results_[cv_keys[2]][r])) print('Best parameters: %s' % grid.best_params_) print('Accuracy: %.2f' % grid.best_score_) Explanation: Grid search parameters End of explanation grid.best_estimator_.classifiers mv_clf = grid.best_estimator_ mv_clf.set_params(**grid.best_estimator_.get_params()) mv_clf Explanation: Observations: * decision tree depth doesn't matter * lower regularization (larger $C$) better Note By default, the default setting for refit in GridSearchCV is True (i.e., GridSeachCV(..., refit=True)), which means that we can use the fitted GridSearchCV estimator to make predictions via the predict method, for example: grid = GridSearchCV(estimator=mv_clf, param_grid=params, cv=10, scoring='roc_auc') grid.fit(X_train, y_train) y_pred = grid.predict(X_test) In addition, the "best" estimator can directly be accessed via the best_estimator_ attribute. End of explanation import pandas as pd remote_source = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data' local_source = '../datasets/wine/wine.data' df_wine = pd.read_csv(local_source, header=None) df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash', 'Alcalinity of ash', 'Magnesium', 'Total phenols', 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins', 'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline'] # drop 1 class df_wine = df_wine[df_wine['Class label'] != 1] y = df_wine['Class label'].values X = df_wine[['Alcohol', 'Hue']].values Explanation: Bagging -- Building an ensemble of classifiers from bootstrap samples Use random subsets of samples for each base classifier. * bootstrap samples: random sample with/without replacement of the entire training data * rows (samples) or cols (features) Parallel method * base classifiers operate independently <img src='./images/07_06.png'> 7-sample training data example: <img src='./images/07_07.png'> Bagging example Classify the wine data set Load the dataset End of explanation from sklearn.preprocessing import LabelEncoder if Version(sklearn_version) < '0.18': from sklearn.cross_validation import train_test_split else: from sklearn.model_selection import train_test_split le = LabelEncoder() y = le.fit_transform(y) X_train, X_test, y_train, y_test =\ train_test_split(X, y, test_size=0.40, random_state=1) Explanation: Encoding and splitting End of explanation from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy', max_depth=None, # allow over-fitting to enhance diversity random_state=1) bag = BaggingClassifier(base_estimator=tree, n_estimators=500, max_samples=1.0, # rows max_features=1.0, # cols bootstrap=True, # replace? bootstrap_features=False, n_jobs=1, random_state=1) from sklearn.metrics import accuracy_score tree = tree.fit(X_train, y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) bag = bag.fit(X_train, y_train) y_train_pred = bag.predict(X_train) y_test_pred = bag.predict(X_test) bag_train = accuracy_score(y_train, y_train_pred) bag_test = accuracy_score(y_test, y_test_pred) print('Bagging train/test accuracies %.3f/%.3f' % (bag_train, bag_test)) Explanation: Bagging classifier End of explanation import numpy as np import matplotlib.pyplot as plt x_min = X_train[:, 0].min() - 1 x_max = X_train[:, 0].max() + 1 y_min = X_train[:, 1].min() - 1 y_max = X_train[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(nrows=1, ncols=2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, bag], ['Decision Tree', 'Bagging']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx].contourf(xx, yy, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='red', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('Alcohol', fontsize=12) plt.text(10.2, -1.2, s='Hue', ha='center', va='center', fontsize=12) plt.tight_layout() # plt.savefig('./figures/bagging_region.png', # dpi=300, # bbox_inches='tight') plt.show() Explanation: Notice bagging has less over-fitting than decision tree. Visualize decision regions Use meshgrid and isocontour as usual. End of explanation import matplotlib.pyplot as plt import numpy as np def alpha_func(x): return 0.5*np.log((1-x)/x) delta = 0.01 x = np.arange(delta, 0.5, delta) y = alpha_func(x) plt.plot(x, y) plt.xlabel(r'$\epsilon$') plt.ylabel(r'$\alpha$') plt.tight_layout() plt.show() Explanation: Notice the smoother decision boundaries of bagging than decision tree. Bagging can reduce variance, but not bias. Choose base classifiers with low bias, such as unpruned decision trees. Leveraging weak learners via adaptive boosting AdaBoost for abbreviation A collection of weak base learners (diversity over accuracy) * sequential learning * later classifiers focus on the weak parts (mis-classified samples) of the earlier classifiers Original boosting procedure [Schapire 1990] Using 3 classifiers Training: * Train $C_1$ with a random subset of training data Train $C_2$ with a random subset of training data $\bigcup$ misclassified samples from $C_1$ Train $C_3$ over the training samples for which $C_1$ and $C_2$ disagree Testing/Usage: * Combine $C_1$, $C_2$, $C_3$ via majority voting AdaBoost versus bagging Bagging * parallel * random sample with replacement * cannot reduce bias; same as base classifiers AdaBoost * sequential * random sample without replacement * can reduce bias AdaBoost example Give previously misclassified samples higher weights Example using decision tree stumps (i.e. very shallow trees, like just one level) Steps: 1. equal weight training of all samples by $C_1$, two blue circles are misclassified 2. larger/lower weights to wrongly/correctly classified samples, train $C_2$ 3. larger/lower weights to wrongly/correctly classified samples, train $C_3$ 4. combine $C_1$, $C_2$, $C_3$ for weighted majority voting <img src='./images/07_09.png' width=80%> AdaBoost algorithm Input data: $X$ and $y$ (label) Initial equal weight vector $w$ to all samples, $\sum_i w_i = 1$ For j in m boosting rounds, do the following: 1. Train a weak learner: $C_j.train(X, y, w)$ 2. Predict class labels: $\hat{y} = C_j.predict(X)$ 3. Compute weighted error rate: $\epsilon = w . \left(\hat{y} \neq y \right)$, $0 \leq \epsilon < 0.5$ 4. Compute re-weighting coefficients: $\alpha_j = 0.5 \log_e\left(\frac{1-\epsilon}{\epsilon}\right)$ $\geq0$ for $0 \leq \epsilon < 0.5$ * $\epsilon \uparrow$ $\rightarrow$ $\alpha_j \downarrow$ * $\epsilon = 0$ $\rightarrow$ $\alpha_j = \infty$ - equal weighting if no error * $\epsilon = 0.5$ $\rightarrow$ $\alpha_j = 0$ - no weight update if serious errors 5. Update weights: $w \leftarrow w \times \exp(-\alpha_j . \hat{y} \times y)$, $\times$ means element-wise product * correct/incorrect prediction will decrease/increase weight 6. Normalize weights: $w \leftarrow \frac{w}{\sum_i w_i}$ Compute final prediction via weighted ensemble voting: $ \hat{y} = \sum_j \alpha_j \times C_j.predict(X) $ End of explanation from sklearn.ensemble import AdaBoostClassifier tree = DecisionTreeClassifier(criterion='entropy', max_depth=1, random_state=0) ada = AdaBoostClassifier(base_estimator=tree, n_estimators=500, learning_rate=0.1, random_state=0) tree = tree.fit(X_train, y_train) y_train_pred = tree.predict(X_train) y_test_pred = tree.predict(X_test) tree_train = accuracy_score(y_train, y_train_pred) tree_test = accuracy_score(y_test, y_test_pred) print('Decision tree train/test accuracies %.3f/%.3f' % (tree_train, tree_test)) ada = ada.fit(X_train, y_train) y_train_pred = ada.predict(X_train) y_test_pred = ada.predict(X_test) ada_train = accuracy_score(y_train, y_train_pred) ada_test = accuracy_score(y_test, y_test_pred) print('AdaBoost train/test accuracies %.3f/%.3f' % (ada_train, ada_test)) Explanation: 10 sample example $\epsilon = 0.3$ $\alpha = 0.5\log_e(0.7/0.3) = 0.424$ $w$ before normalization: * correct prediction: $0.1 \times \exp(-0.424 \times 1 \times 1) = 0.066$ * incorrect prediction: $0.1 \times \exp(-0.424 \times 1 \times -1) = 0.153$ <img src='./images/07_10.png' width=80%> AdaBoost code example End of explanation x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1 y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1)) f, axarr = plt.subplots(1, 2, sharex='col', sharey='row', figsize=(8, 3)) for idx, clf, tt in zip([0, 1], [tree, ada], ['Decision Tree', 'AdaBoost']): clf.fit(X_train, y_train) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) axarr[idx].contourf(xx, yy, Z, alpha=0.3) axarr[idx].scatter(X_train[y_train == 0, 0], X_train[y_train == 0, 1], c='blue', marker='^') axarr[idx].scatter(X_train[y_train == 1, 0], X_train[y_train == 1, 1], c='red', marker='o') axarr[idx].set_title(tt) axarr[0].set_ylabel('Alcohol', fontsize=12) plt.text(10.2, -1.2, s='Hue', ha='center', va='center', fontsize=12) plt.tight_layout() # plt.savefig('./figures/adaboost_region.png', # dpi=300, # bbox_inches='tight') plt.show() Explanation: Better training performance by AdaBoost, but with more overfitting than bagging End of explanation
5,391
Given the following text description, write Python code to implement the functionality described below step by step Description: Step2: Please find torch implementation of this notebook here Step4: Basics This section is based on sec 8.2 of http Step6: Tokenization Step9: Vocabulary We map each word to a unique integer id, sorted by decreasing frequency. We reserve the special id of 0 for the "unknown word". We also allow for a list of reserved tokens, such as “pad" for padding, "bos" to present the beginning for a sequence, and “eos” for the end of a sequence. Step10: Here are the top 10 words (and their codes) in our corpus. Step11: Here is a tokenization of a few sentences. Step13: Putting it altogether We tokenize the corpus at the character level, and return the sequence of integers, as well as the corresponding Vocab object. Step14: One-hot encodings We can convert a sequence of N integers into a N*V one-hot matrix, where V is the vocabulary size. Step16: Language modeling When fitting language models, we often need to chop up a long sequence into a set of short sequences, which may be overlapping, as shown below, where we extract subsequences of length $n=5$. <img src="https Step17: For example, let us generate a sequence 0,1,..,34, and then extract subsequences of length 5. Each minibatch will have 2 such subsequences, starting at random offsets. There is no ordering between the subsequences, either within or across minibatches. There are $\lfloor (35-1)/5 \rfloor = 6$ such subsequences, so the iterator will generate 3 minibatches, each of size 2. For language modeling tasks, we define $X$ to be the first $n-1$ tokens, and $Y$ to be the $n$'th token, which is the one to be predicted. Step19: Sequential ordering We can also require that the $i$'th subsequence in minibatch $b$ follows the $i$'th subsequence in minibatch $b-1$. This is useful when training RNNs, since when the model encounters batch $b$, the hidden state of the model will already be initialized by the last token in sequence $i$ of batch $b-1$. Step20: Below we give an example. We see that the first subsequence in batch 1 is [0,1,2,3,4], and the first subsequence in batch 2 is [5,6,7,8,9], as desired. Step24: Data iterator Step26: Machine translation When dealing with sequence-to-sequence tasks, such as NMT, we need to create a vocabulary for the source and target language. In addition, the input and output sequences may have different lengths, so we need to use padding to ensure that we can create fixed-size minibatches. We show how to do this below. This is based on sec 9.5 of http Step28: Preprocessing We apply several preprocessing steps Step30: We tokenize at the word level. The following tokenize_nmt function tokenizes the the first num_examples text sequence pairs, where each token is either a word or a punctuation mark. Step31: Vocabulary We can make a source and target vocabulary. To avoid having too many unique tokens, we specify a minimum frequency of 2 - all others will get replaced by "unk". We also add special tags for padding, begin of sentence, and end of sentence. Step34: Truncation and padding To create minibatches of sequences, all of the same length, we truncate sentences that are too long, and pad ones that are too short. Step37: Data iterator Below we combine all of the above pieces into a handy function. Step38: Show the first minibatch.
Python Code: import os import numpy as np import jax import jax.numpy as jnp import matplotlib.pyplot as plt import math try: import torch except ModuleNotFoundError: %pip install -qq torch import torch from torch.utils import data if not os.path.exists("figures"): os.makedirs("figures") # for saving plots import collections import re import random import os import requests import zipfile import hashlib # Required functions for downloading data def download(name, cache_dir=os.path.join("..", "data")): Download a file inserted into DATA_HUB, return the local filename. assert name in DATA_HUB, f"{name} does not exist in {DATA_HUB}." url, sha1_hash = DATA_HUB[name] os.makedirs(cache_dir, exist_ok=True) fname = os.path.join(cache_dir, url.split("/")[-1]) if os.path.exists(fname): sha1 = hashlib.sha1() with open(fname, "rb") as f: while True: data = f.read(1048576) if not data: break sha1.update(data) if sha1.hexdigest() == sha1_hash: return fname # Hit cache print(f"Downloading {fname} from {url}...") r = requests.get(url, stream=True, verify=True) with open(fname, "wb") as f: f.write(r.content) return fname def download_extract(name, folder=None): Download and extract a zip/tar file. fname = download(name) base_dir = os.path.dirname(fname) data_dir, ext = os.path.splitext(fname) if ext == ".zip": fp = zipfile.ZipFile(fname, "r") elif ext in (".tar", ".gz"): fp = tarfile.open(fname, "r") else: assert False, "Only zip/tar files can be extracted." fp.extractall(base_dir) return os.path.join(base_dir, folder) if folder else data_dir Explanation: Please find torch implementation of this notebook here: https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/book1/01/text_preproc_torch.ipynb <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/notebooks/text_preproc_jax.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Text preprocessing We discuss how to convert a sequence of words or characters into numeric form, which can then be fed into an ML model. End of explanation DATA_HUB = dict() DATA_URL = "http://d2l-data.s3-accelerate.amazonaws.com/" DATA_HUB["time_machine"] = (DATA_URL + "timemachine.txt", "090b5e7e70c295757f55df93cb0a180b9691891a") def read_time_machine(): Load the time machine dataset into a list of text lines. with open(download("time_machine"), "r") as f: lines = f.readlines() return [re.sub("[^A-Za-z]+", " ", line).strip().lower() for line in lines] lines = read_time_machine() print(f"number of lines: {len(lines)}") for i in range(11): print(i, lines[i]) nchars = 0 nwords = 0 for i in range(len(lines)): nchars += len(lines[i]) words = lines[i].split() nwords += len(words) print("total num characters ", nchars) print("total num words ", nwords) Explanation: Basics This section is based on sec 8.2 of http://d2l.ai/chapter_recurrent-neural-networks/text-preprocessing.html Data As a simple example, we use the book "The Time Machine" by H G Wells, since it is short (30k words) and public domain. End of explanation def tokenize(lines, token="word"): Split text lines into word or character tokens. if token == "word": return [line.split() for line in lines] elif token == "char": return [list(line) for line in lines] else: print("ERROR: unknown token type: " + token) tokens = tokenize(lines) for i in range(11): print(tokens[i]) Explanation: Tokenization End of explanation class Vocab: Vocabulary for text. def __init__(self, tokens=None, min_freq=0, reserved_tokens=None): if tokens is None: tokens = [] if reserved_tokens is None: reserved_tokens = [] # Sort according to frequencies counter = count_corpus(tokens) self.token_freqs = sorted(counter.items(), key=lambda x: x[1], reverse=True) # The index for the unknown token is 0 self.unk, uniq_tokens = 0, ["<unk>"] + reserved_tokens uniq_tokens += [token for token, freq in self.token_freqs if freq >= min_freq and token not in uniq_tokens] self.idx_to_token, self.token_to_idx = [], dict() for token in uniq_tokens: self.idx_to_token.append(token) self.token_to_idx[token] = len(self.idx_to_token) - 1 def __len__(self): return len(self.idx_to_token) def __getitem__(self, tokens): if not isinstance(tokens, (list, tuple)): return self.token_to_idx.get(tokens, self.unk) return [self.__getitem__(token) for token in tokens] def to_tokens(self, indices): if not isinstance(indices, (list, tuple)): return self.idx_to_token[indices] return [self.idx_to_token[index] for index in indices] def count_corpus(tokens): Count token frequencies. # Here `tokens` is a 1D list or 2D list if len(tokens) == 0 or isinstance(tokens[0], list): # Flatten a list of token lists into a list of tokens tokens = [token for line in tokens for token in line] return collections.Counter(tokens) Explanation: Vocabulary We map each word to a unique integer id, sorted by decreasing frequency. We reserve the special id of 0 for the "unknown word". We also allow for a list of reserved tokens, such as “pad" for padding, "bos" to present the beginning for a sequence, and “eos” for the end of a sequence. End of explanation vocab = Vocab(tokens) print(list(vocab.token_to_idx.items())[:10]) Explanation: Here are the top 10 words (and their codes) in our corpus. End of explanation for i in [0, 10]: print("words:", tokens[i]) print("indices:", vocab[tokens[i]]) Explanation: Here is a tokenization of a few sentences. End of explanation def load_corpus_time_machine(max_tokens=-1): Return token indices and the vocabulary of the time machine dataset. lines = read_time_machine() tokens = tokenize(lines, "char") vocab = Vocab(tokens) # Since each text line in the time machine dataset is not necessarily a # sentence or a paragraph, flatten all the text lines into a single list corpus = [vocab[token] for line in tokens for token in line] if max_tokens > 0: corpus = corpus[:max_tokens] return corpus, vocab corpus, vocab = load_corpus_time_machine() len(corpus), len(vocab) print(corpus[:20]) print(list(vocab.token_to_idx.items())[:10]) print([vocab.idx_to_token[i] for i in corpus[:20]]) Explanation: Putting it altogether We tokenize the corpus at the character level, and return the sequence of integers, as well as the corresponding Vocab object. End of explanation x = jnp.array(corpus[:3]) print(x) X = jax.nn.one_hot(x, len(vocab)) print(X.shape) print(X) Explanation: One-hot encodings We can convert a sequence of N integers into a N*V one-hot matrix, where V is the vocabulary size. End of explanation def seq_data_iter_random(corpus, batch_size, num_steps): Generate a minibatch of subsequences using random sampling. # Start with a random offset (inclusive of `num_steps - 1`) to partition a # sequence corpus = corpus[random.randint(0, num_steps - 1) :] # Subtract 1 since we need to account for labels num_subseqs = (len(corpus) - 1) // num_steps # The starting indices for subsequences of length `num_steps` initial_indices = list(range(0, num_subseqs * num_steps, num_steps)) # In random sampling, the subsequences from two adjacent random # minibatches during iteration are not necessarily adjacent on the # original sequence random.shuffle(initial_indices) def data(pos): # Return a sequence of length `num_steps` starting from `pos` return corpus[pos : pos + num_steps] num_batches = num_subseqs // batch_size for i in range(0, batch_size * num_batches, batch_size): # Here, `initial_indices` contains randomized starting indices for # subsequences initial_indices_per_batch = initial_indices[i : i + batch_size] X = [data(j) for j in initial_indices_per_batch] Y = [data(j + 1) for j in initial_indices_per_batch] yield jnp.array(X), jnp.array(Y) Explanation: Language modeling When fitting language models, we often need to chop up a long sequence into a set of short sequences, which may be overlapping, as shown below, where we extract subsequences of length $n=5$. <img src="https://github.com/probml/pyprobml/blob/master/images/timemachine-5gram.png?raw=true"> Below we show how to do this. This section is based on sec 8.3.4 of http://d2l.ai/chapter_recurrent-neural-networks/language-models-and-dataset.html#reading-long-sequence-data Random ordering To increase variety of the data, we can start the extraction at a random offset. We can thus create a random sequence data iterator, as follows. End of explanation my_seq = list(range(35)) b = 0 for X, Y in seq_data_iter_random(my_seq, batch_size=2, num_steps=5): print("batch: ", b) print("X: ", X, "\nY:", Y) b += 1 Explanation: For example, let us generate a sequence 0,1,..,34, and then extract subsequences of length 5. Each minibatch will have 2 such subsequences, starting at random offsets. There is no ordering between the subsequences, either within or across minibatches. There are $\lfloor (35-1)/5 \rfloor = 6$ such subsequences, so the iterator will generate 3 minibatches, each of size 2. For language modeling tasks, we define $X$ to be the first $n-1$ tokens, and $Y$ to be the $n$'th token, which is the one to be predicted. End of explanation def seq_data_iter_sequential(corpus, batch_size, num_steps): Generate a minibatch of subsequences using sequential partitioning. # Start with a random offset to partition a sequence offset = random.randint(0, num_steps) num_tokens = ((len(corpus) - offset - 1) // batch_size) * batch_size Xs = jnp.array(corpus[offset : offset + num_tokens]) Ys = jnp.array(corpus[offset + 1 : offset + 1 + num_tokens]) Xs, Ys = Xs.reshape(batch_size, -1), Ys.reshape(batch_size, -1) num_batches = Xs.shape[1] // num_steps for i in range(0, num_steps * num_batches, num_steps): X = Xs[:, i : i + num_steps] Y = Ys[:, i : i + num_steps] yield X, Y Explanation: Sequential ordering We can also require that the $i$'th subsequence in minibatch $b$ follows the $i$'th subsequence in minibatch $b-1$. This is useful when training RNNs, since when the model encounters batch $b$, the hidden state of the model will already be initialized by the last token in sequence $i$ of batch $b-1$. End of explanation for X, Y in seq_data_iter_sequential(my_seq, batch_size=2, num_steps=5): print("X: ", X, "\nY:", Y) Explanation: Below we give an example. We see that the first subsequence in batch 1 is [0,1,2,3,4], and the first subsequence in batch 2 is [5,6,7,8,9], as desired. End of explanation def load_corpus_time_machine(max_tokens=-1): Return token indices and the vocabulary of the time machine dataset. lines = read_time_machine() tokens = tokenize(lines, "char") vocab = Vocab(tokens) # Since each text line in the time machine dataset is not necessarily a # sentence or a paragraph, flatten all the text lines into a single list corpus = [vocab[token] for line in tokens for token in line] if max_tokens > 0: corpus = corpus[:max_tokens] return corpus, vocab class SeqDataLoader: # @save An iterator to load sequence data. def __init__(self, batch_size, num_steps, use_random_iter, max_tokens): if use_random_iter: self.data_iter_fn = seq_data_iter_random else: self.data_iter_fn = seq_data_iter_sequential self.corpus, self.vocab = load_corpus_time_machine(max_tokens) self.batch_size, self.num_steps = batch_size, num_steps def __iter__(self): return self.data_iter_fn(self.corpus, self.batch_size, self.num_steps) def load_data_time_machine(batch_size, num_steps, use_random_iter=False, max_tokens=10000): # @save Return the iterator and the vocabulary of the time machine dataset. data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter, max_tokens) return data_iter, data_iter.vocab data_iter, vocab = load_data_time_machine(2, 5) print(list(vocab.token_to_idx.items())[:10]) b = 0 for X, Y in data_iter: print("batch: ", b) print("X: ", X, "\nY:", Y) b += 1 if b > 2: break Explanation: Data iterator End of explanation DATA_HUB["fra-eng"] = (DATA_URL + "fra-eng.zip", "94646ad1522d915e7b0f9296181140edcf86a4f5") def read_data_nmt(): Load the English-French dataset. data_dir = download_extract("fra-eng") with open(os.path.join(data_dir, "fra.txt"), "r") as f: return f.read() raw_text = read_data_nmt() print(raw_text[:100]) Explanation: Machine translation When dealing with sequence-to-sequence tasks, such as NMT, we need to create a vocabulary for the source and target language. In addition, the input and output sequences may have different lengths, so we need to use padding to ensure that we can create fixed-size minibatches. We show how to do this below. This is based on sec 9.5 of http://d2l.ai/chapter_recurrent-modern/machine-translation-and-dataset.html Data We use an English-French dataset that consists of bilingual sentence pairs from the Tatoeba Project. Each line in the dataset is a tab-delimited pair of an English text sequence (source) and the translated French text sequence (target). End of explanation def preprocess_nmt(text): Preprocess the English-French dataset. def no_space(char, prev_char): return char in set(",.!?") and prev_char != " " # Replace non-breaking space with space, and convert uppercase letters to # lowercase ones text = text.replace("\u202f", " ").replace("\xa0", " ").lower() # Insert space between words and punctuation marks out = [" " + char if i > 0 and no_space(char, text[i - 1]) else char for i, char in enumerate(text)] return "".join(out) text = preprocess_nmt(raw_text) print(text[:110]) Explanation: Preprocessing We apply several preprocessing steps: we replace non-breaking space with space, convert uppercase letters to lowercase ones, and insert space between words and punctuation marks. End of explanation def tokenize_nmt(text, num_examples=None): Tokenize the English-French dataset. source, target = [], [] for i, line in enumerate(text.split("\n")): if num_examples and i > num_examples: break parts = line.split("\t") if len(parts) == 2: source.append(parts[0].split(" ")) target.append(parts[1].split(" ")) return source, target source, target = tokenize_nmt(text) source[:10], target[:10] Explanation: We tokenize at the word level. The following tokenize_nmt function tokenizes the the first num_examples text sequence pairs, where each token is either a word or a punctuation mark. End of explanation src_vocab = Vocab(source, min_freq=2, reserved_tokens=["<pad>", "<bos>", "<eos>"]) len(src_vocab) # French has more high frequency words than English target_vocab = Vocab(target, min_freq=2, reserved_tokens=["<pad>", "<bos>", "<eos>"]) len(target_vocab) Explanation: Vocabulary We can make a source and target vocabulary. To avoid having too many unique tokens, we specify a minimum frequency of 2 - all others will get replaced by "unk". We also add special tags for padding, begin of sentence, and end of sentence. End of explanation def truncate_pad(line, num_steps, padding_token): Truncate or pad sequences. if len(line) > num_steps: return line[:num_steps] # Truncate return line + [padding_token] * (num_steps - len(line)) # Pad print(truncate_pad(source[0], 10, "pad")) print(truncate_pad(src_vocab[source[0]], 10, src_vocab["<pad>"])) def build_array_nmt(lines, vocab, num_steps): Transform text sequences of machine translation into minibatches. lines = [vocab[l] for l in lines] lines = [l + [vocab["<eos>"]] for l in lines] array = torch.tensor([truncate_pad(l, num_steps, vocab["<pad>"]) for l in lines]) valid_len = (array != vocab["<pad>"]).type(torch.int32).sum(1) return array, valid_len num_steps = 10 src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps) print(jnp.array(src_array).shape) print(jnp.array(src_valid_len).shape) print(jnp.array(src_array[0, :])) # go, ., eos, pad, ..., pad print(jnp.array(src_valid_len[0])) Explanation: Truncation and padding To create minibatches of sequences, all of the same length, we truncate sentences that are too long, and pad ones that are too short. End of explanation def load_array(data_arrays, batch_size, is_train=True): Construct a PyTorch data iterator. dataset = data.TensorDataset(*data_arrays) return data.DataLoader(dataset, batch_size, shuffle=is_train) def load_data_nmt(batch_size, num_steps, num_examples=600): Return the iterator and the vocabularies of the translation dataset. text = preprocess_nmt(read_data_nmt()) source, target = tokenize_nmt(text, num_examples) src_vocab = Vocab(source, min_freq=2, reserved_tokens=["<pad>", "<bos>", "<eos>"]) tgt_vocab = Vocab(target, min_freq=2, reserved_tokens=["<pad>", "<bos>", "<eos>"]) src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps) tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps) data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len) data_iter = load_array(data_arrays, batch_size) return data_iter, src_vocab, tgt_vocab Explanation: Data iterator Below we combine all of the above pieces into a handy function. End of explanation train_iter, src_vocab, tgt_vocab = load_data_nmt(batch_size=2, num_steps=8) for X, X_valid_len, Y, Y_valid_len in train_iter: print("X:", jnp.array(X).astype(jnp.int32)) print("valid lengths for X:", jnp.array(X_valid_len)) print("Y:", jnp.array(Y).astype(jnp.int32)) print("valid lengths for Y:", jnp.array(Y_valid_len)) break Explanation: Show the first minibatch. End of explanation
5,392
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Machine-Translation-with-Huggingface-Transformer" data-toc-modified-id="Machine-Translation-with-Huggingface-Transformer-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Machine Translation with Huggingface Transformer</a></span><ul class="toc-item"><li><span><a href="#Data-Preprocessing" data-toc-modified-id="Data-Preprocessing-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Data Preprocessing</a></span></li><li><span><a href="#Pretrained-Model" data-toc-modified-id="Pretrained-Model-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Pretrained Model</a></span></li><li><span><a href="#Training-Model-From-Scratch" data-toc-modified-id="Training-Model-From-Scratch-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Training Model From Scratch</a></span></li><li><span><a href="#Training-Tokenizer-and-Model-From-Scratch" data-toc-modified-id="Training-Tokenizer-and-Model-From-Scratch-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Training Tokenizer and Model From Scratch</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> Step4: Machine Translation with Huggingface Transformer In this article we'll be leveraging Huggingface's Transformer on our machine translation task. The library provides thousands of pretrained models that we can use on our tasks. Apart from that, we'll also take a look at how to use its pre-built tokenizer and model architecture to train a model from scratch. Data Preprocessing We'll be using the Multi30k dataset to demonstrate using the transfomer model in a machine translation task. This German to English training dataset's size is around 29K, a moderate sized dataset so that we can get our results without waiting too long. We'll start off by downloading the raw dataset and extracting them. Feel free to swap this step with any other machine translation dataset. Step5: We print out the content in the data directory and some sample data. Step7: The original dataset is splits the source and the target language into two separate files (e.g. train.de, train.en are the training dataset for German and English). This type of format is useful when we wish to train a tokenizer on top of the source or target language as we'll soon see. On the other hand, having the source and target pair together in one single file makes it easier to load them in batches for training or evaluating our machine translation model. We'll create the paired dataset, and load the dataset. For loading the dataset, it will be helpful to have some basic understanding of Huggingface's dataset. Step8: We can acsess the split, and each record/pair with the following syntax. Step9: Pretrained Model To get started we'll use the MarianMT pretrained model translation model. First thing we'll do is to load the pre-trained tokenizer, using the from_pretrained syntax. This ensures we get the tokenizer and vocabulary corresponding to the model architecture for this specific checkpoint. Step10: We can pass a single record, or a list of records to huggingface's tokenizer. Then depending on the model, we might see different keys in the dictionary returned. For example, here, we have Step12: We can apply the tokenizers to our entire raw dataset, so this preprocessing will be a one time process. By passing the function to our dataset dict's map method, it will apply the same tokenizing step to all the splits in our data. Step13: Having prepared our dataset, we'll load the pre-trained model. Similar to the tokenizer, we can use the .from_pretrained method, and specify a valid huggingface model. Step15: We can directly use this model to generate the translations, and eyeball the results. Step16: Training Model From Scratch The next section shows the steps for training the model parameters from scratch. Instead of directly instantiating the model using .from_pretrained method. We use the .from_config method, where we specify the configurations for a particular model architecture. The configuration will be created using .from_pretrained, as well as updating some of the configuration hyper parameters, where we opted for a smaller model for faster iteration. Step17: The huggingface library offers pre-built functionality to avoid writing the training logic from scratch. This step can be swapped out with other higher level trainer packages or even implementing our own logic. We setup the Step18: We can take a look at the batched examples. Understanding the output can be beneficial if we wish to customize the data collate function later. attention_mask Padded tokens will be masked out with 0.. input_ids. Input ids are padded with the padding special tokens. labels. By default -100 will be automatically ignored by PyTorch loss functions, hence it will the id to use when padding the labels. Step20: Similar to what we did before, we can use this model to generate the translations, and eyeball the results. Step21: Training Tokenizer and Model From Scratch From our raw pair, we need to use or train a tokenizer to convert them into numerical indices. Here we'll be training our tokenizer from scratch using Huggingface's tokenizer. Feel free to swap this step out with other tokenization procedures, what's important is to leave rooms for special tokens such as the init token that represents the beginning of a sentence, the end of sentence token that represents the end of a sentence, unknown token, and padding token that pads sentence batches into equivalent length. Step22: We'll perform this tokenization step for all our dataset up front, so we can do as little preprocessing as possible while feeding our dataset to model. Note that we do not perform the padding step at this stage. Step24: Given the custom tokenizer, we can also custom our data collate class that does the padding for input and labels. Step25: Given that we are using our own tokenizer instead of the pre-trained ones, we need to update a couple of other parameters in our config. The one that's worth pointing out is that this model starts generating with pad_token_id, that's why the decoder_start_token_id is the same as the pad_token_id. Then rest of model training code should be the same as the ones in the previous section. Step26: Confirming saving and loading the model gives us identical predictions. Step27: As the last step, we'll write a inferencing function that performs batch scoring on a given dataset. Here we generate the predictions and save it in a pandas dataframe along with the source and the target.
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(css_style='custom2.css', plot_style=False) os.chdir(path) # 1. magic for inline plot # 2. magic to print version # 3. magic so that the notebook will reload external python modules # 4. magic to enable retina (high resolution) plots # https://gist.github.com/minrk/3301035 %matplotlib inline %load_ext watermark %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format='retina' import os import math import time import torch import random import numpy as np import pandas as pd from datasets import load_dataset from torch.utils.data import DataLoader from tokenizers import ByteLevelBPETokenizer %watermark -a 'Ethen' -d -t -v -p datasets,numpy,torch,tokenizers,transformers Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Machine-Translation-with-Huggingface-Transformer" data-toc-modified-id="Machine-Translation-with-Huggingface-Transformer-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Machine Translation with Huggingface Transformer</a></span><ul class="toc-item"><li><span><a href="#Data-Preprocessing" data-toc-modified-id="Data-Preprocessing-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Data Preprocessing</a></span></li><li><span><a href="#Pretrained-Model" data-toc-modified-id="Pretrained-Model-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Pretrained Model</a></span></li><li><span><a href="#Training-Model-From-Scratch" data-toc-modified-id="Training-Model-From-Scratch-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Training Model From Scratch</a></span></li><li><span><a href="#Training-Tokenizer-and-Model-From-Scratch" data-toc-modified-id="Training-Tokenizer-and-Model-From-Scratch-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Training Tokenizer and Model From Scratch</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> End of explanation import tarfile import zipfile import requests import subprocess from tqdm import tqdm from urllib.parse import urlparse def download_file(url: str, directory: str): Download the file at ``url`` to ``directory``. Extract to the file content ``directory`` if the original file is a tar, tar.gz or zip file. Parameters ---------- url : str url of the file. directory : str Directory to download the file. response = requests.get(url, stream=True) response.raise_for_status() content_len = response.headers.get('Content-Length') total = int(content_len) if content_len is not None else 0 os.makedirs(directory, exist_ok=True) file_name = get_file_name_from_url(url) file_path = os.path.join(directory, file_name) with tqdm(unit='B', total=total) as pbar, open(file_path, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): if chunk: pbar.update(len(chunk)) f.write(chunk) extract_compressed_file(file_path, directory) def extract_compressed_file(compressed_file_path: str, directory: str): Extract a compressed file to ``directory``. Supports zip, tar.gz, tgz, tar extensions. Parameters ---------- compressed_file_path : str directory : str File will to extracted to this directory. basename = os.path.basename(compressed_file_path) if 'zip' in basename: with zipfile.ZipFile(compressed_file_path, "r") as zip_f: zip_f.extractall(directory) elif 'tar.gz' in basename or 'tgz' in basename: with tarfile.open(compressed_file_path) as f: f.extractall(directory) def get_file_name_from_url(url: str) -> str: Return the file_name from a URL Parameters ---------- url : str URL to extract file_name from Returns ------- file_name : str parse = urlparse(url) return os.path.basename(parse.path) urls = [ 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/training.tar.gz', 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/validation.tar.gz', 'http://www.quest.dcs.shef.ac.uk/wmt16_files_mmt/mmt16_task1_test.tar.gz' ] directory = 'multi30k' for url in urls: download_file(url, directory) Explanation: Machine Translation with Huggingface Transformer In this article we'll be leveraging Huggingface's Transformer on our machine translation task. The library provides thousands of pretrained models that we can use on our tasks. Apart from that, we'll also take a look at how to use its pre-built tokenizer and model architecture to train a model from scratch. Data Preprocessing We'll be using the Multi30k dataset to demonstrate using the transfomer model in a machine translation task. This German to English training dataset's size is around 29K, a moderate sized dataset so that we can get our results without waiting too long. We'll start off by downloading the raw dataset and extracting them. Feel free to swap this step with any other machine translation dataset. End of explanation !ls multi30k !head multi30k/train.de !head multi30k/train.en Explanation: We print out the content in the data directory and some sample data. End of explanation def create_translation_data( source_input_path: str, target_input_path: str, output_path: str, delimiter: str = '\t', encoding: str = 'utf-8' ): Creates the paired source and target dataset from the separated ones. e.g. creates `train.tsv` from `train.de` and `train.en` with open(source_input_path, encoding=encoding) as f_source_in, \ open(target_input_path, encoding=encoding) as f_target_in, \ open(output_path, 'w', encoding=encoding) as f_out: for source_raw in f_source_in: source_raw = source_raw.strip() target_raw = f_target_in.readline().strip() if source_raw and target_raw: output_line = source_raw + delimiter + target_raw + '\n' f_out.write(output_line) source_lang = 'de' target_lang = 'en' data_files = {} for split in ['train', 'val', 'test']: source_input_path = os.path.join(directory, f'{split}.{source_lang}') target_input_path = os.path.join(directory, f'{split}.{target_lang}') output_path = f'{split}.tsv' create_translation_data(source_input_path, target_input_path, output_path) data_files[split] = [output_path] data_files dataset_dict = load_dataset( 'csv', delimiter='\t', column_names=[source_lang, target_lang], data_files=data_files ) dataset_dict Explanation: The original dataset is splits the source and the target language into two separate files (e.g. train.de, train.en are the training dataset for German and English). This type of format is useful when we wish to train a tokenizer on top of the source or target language as we'll soon see. On the other hand, having the source and target pair together in one single file makes it easier to load them in batches for training or evaluating our machine translation model. We'll create the paired dataset, and load the dataset. For loading the dataset, it will be helpful to have some basic understanding of Huggingface's dataset. End of explanation dataset_dict['train'][0] Explanation: We can acsess the split, and each record/pair with the following syntax. End of explanation from transformers import AutoTokenizer model_checkpoint = "Helsinki-NLP/opus-mt-de-en" pretrained_tokenizer = AutoTokenizer.from_pretrained(model_checkpoint) pretrained_tokenizer Explanation: Pretrained Model To get started we'll use the MarianMT pretrained model translation model. First thing we'll do is to load the pre-trained tokenizer, using the from_pretrained syntax. This ensures we get the tokenizer and vocabulary corresponding to the model architecture for this specific checkpoint. End of explanation pretrained_tokenizer(dataset_dict['train']['de'][0]) # notice the last token id is 0, the end of sentence special token pretrained_tokenizer.convert_ids_to_tokens(0) pretrained_tokenizer(dataset_dict['train']['de'][0:2]) Explanation: We can pass a single record, or a list of records to huggingface's tokenizer. Then depending on the model, we might see different keys in the dictionary returned. For example, here, we have: input_ids: The tokenizer converted our raw input text into numerical ids. attention_mask Mask to avoid performing attention on padded token ids. As we haven't yet performed the padding step, the numbers are all showing up as 1, indicating they are not masked. End of explanation max_source_length = 128 max_target_length = 128 source_lang = "de" target_lang = "en" def batch_tokenize_fn(examples): Generate the input_ids and labels field for huggingface dataset/dataset dict. Truncation is enabled, so we cap the sentence to the max length, padding will be done later in a data collator, so pad examples to the longest length in the batch and not the whole dataset. sources = examples[source_lang] targets = examples[target_lang] model_inputs = pretrained_tokenizer(sources, max_length=max_source_length, truncation=True) # setup the tokenizer for targets, # huggingface expects the target tokenized ids to be stored in the labels field with pretrained_tokenizer.as_target_tokenizer(): labels = pretrained_tokenizer(targets, max_length=max_target_length, truncation=True) model_inputs["labels"] = labels["input_ids"] return model_inputs tokenized_dataset_dict = dataset_dict.map(batch_tokenize_fn, batched=True, num_proc=8) tokenized_dataset_dict # printing out the tokenized data, to check for the newly added fields tokenized_dataset_dict['train'][0] Explanation: We can apply the tokenizers to our entire raw dataset, so this preprocessing will be a one time process. By passing the function to our dataset dict's map method, it will apply the same tokenizing step to all the splits in our data. End of explanation from transformers import AutoModelForSeq2SeqLM device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') pretrained_model = AutoModelForSeq2SeqLM.from_pretrained(model_checkpoint).to(device) print('# of parameters: ', pretrained_model.num_parameters()) pretrained_model Explanation: Having prepared our dataset, we'll load the pre-trained model. Similar to the tokenizer, we can use the .from_pretrained method, and specify a valid huggingface model. End of explanation def generate_translation(model, tokenizer, example): print out the source, target and predicted raw text. source = example[source_lang] target = example[target_lang] input_ids = example['input_ids'] input_ids = torch.LongTensor(input_ids).view(1, -1).to(model.device) generated_ids = model.generate(input_ids) prediction = tokenizer.decode(generated_ids[0], skip_special_tokens=True) print('source: ', source) print('target: ', target) print('prediction: ', prediction) example = tokenized_dataset_dict['train'][0] generate_translation(pretrained_model, pretrained_tokenizer, example) example = tokenized_dataset_dict['test'][0] generate_translation(pretrained_model, pretrained_tokenizer, example) Explanation: We can directly use this model to generate the translations, and eyeball the results. End of explanation from transformers import ( AutoConfig, AutoModelForSeq2SeqLM, DataCollatorForSeq2Seq, EarlyStoppingCallback, Seq2SeqTrainingArguments, Seq2SeqTrainer ) config_params = { 'd_model': 256, 'decoder_layers': 3, 'decoder_attention_heads': 8, 'decoder_ffn_dim': 512, 'encoder_layers': 6, 'encoder_attention_heads': 8, 'encoder_ffn_dim': 512, 'max_length': 128, 'max_position_embeddings': 128 } model_checkpoint = "Helsinki-NLP/opus-mt-de-en" config = AutoConfig.from_pretrained(model_checkpoint, **config_params) config model = AutoModelForSeq2SeqLM.from_config(config) print('# of parameters: ', model.num_parameters()) model Explanation: Training Model From Scratch The next section shows the steps for training the model parameters from scratch. Instead of directly instantiating the model using .from_pretrained method. We use the .from_config method, where we specify the configurations for a particular model architecture. The configuration will be created using .from_pretrained, as well as updating some of the configuration hyper parameters, where we opted for a smaller model for faster iteration. End of explanation batch_size = 128 args = Seq2SeqTrainingArguments( output_dir="test-translation", evaluation_strategy="epoch", learning_rate=0.0005, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, weight_decay=0.01, save_total_limit=3, num_train_epochs=20, load_best_model_at_end=True, predict_with_generate=True, remove_unused_columns=True, fp16=True ) data_collator = DataCollatorForSeq2Seq(pretrained_tokenizer) callbacks = [EarlyStoppingCallback(early_stopping_patience=3)] trainer = Seq2SeqTrainer( model, args, data_collator=data_collator, train_dataset=tokenized_dataset_dict["train"], eval_dataset=tokenized_dataset_dict["val"], callbacks=callbacks ) Explanation: The huggingface library offers pre-built functionality to avoid writing the training logic from scratch. This step can be swapped out with other higher level trainer packages or even implementing our own logic. We setup the: Seq2SeqTrainingArguments a class that contains all the attributes to customize the training. At the bare minimum, it requires one folder name, which will be used to save model checkpoint. DataCollatorForSeq2Seq a helper class provided to batch our examples. Where the padding logic resides. End of explanation dataloader_train = trainer.get_train_dataloader() batch = next(iter(dataloader_train)) batch trainer_output = trainer.train() trainer_output Explanation: We can take a look at the batched examples. Understanding the output can be beneficial if we wish to customize the data collate function later. attention_mask Padded tokens will be masked out with 0.. input_ids. Input ids are padded with the padding special tokens. labels. By default -100 will be automatically ignored by PyTorch loss functions, hence it will the id to use when padding the labels. End of explanation def generate_translation(model, tokenizer, example): print out the source, target and predicted raw text. source = example[source_lang] target = example[target_lang] input_ids = tokenizer(source)['input_ids'] input_ids = torch.LongTensor(input_ids).view(1, -1).to(model.device) generated_ids = model.generate(input_ids) prediction = tokenizer.decode(generated_ids[0], skip_special_tokens=True) print('source: ', source) print('target: ', target) print('prediction: ', prediction) example = dataset_dict['train'][0] generate_translation(model, pretrained_tokenizer, example) example = dataset_dict['test'][0] generate_translation(model, pretrained_tokenizer, example) Explanation: Similar to what we did before, we can use this model to generate the translations, and eyeball the results. End of explanation # use only the training set to train our tokenizer split = 'train' source_input_path = os.path.join(directory, f'{split}.{source_lang}') target_input_path = os.path.join(directory, f'{split}.{target_lang}') print(source_input_path, target_input_path) bos_token = '<s>' unk_token = '<unk>' eos_token = '</s>' pad_token = '<pad>' special_tokens = [unk_token, bos_token, eos_token, pad_token] tokenizer_params = { 'min_frequency': 2, 'vocab_size': 5000, 'show_progress': False, 'special_tokens': special_tokens } start_time = time.time() source_tokenizer = ByteLevelBPETokenizer(lowercase=True) source_tokenizer.train(source_input_path, **tokenizer_params) target_tokenizer = ByteLevelBPETokenizer(lowercase=True) target_tokenizer.train(target_input_path, **tokenizer_params) end_time = time.time() print('elapsed: ', end_time - start_time) print('source vocab size: ', source_tokenizer.get_vocab_size()) print('target vocab size: ', target_tokenizer.get_vocab_size()) Explanation: Training Tokenizer and Model From Scratch From our raw pair, we need to use or train a tokenizer to convert them into numerical indices. Here we'll be training our tokenizer from scratch using Huggingface's tokenizer. Feel free to swap this step out with other tokenization procedures, what's important is to leave rooms for special tokens such as the init token that represents the beginning of a sentence, the end of sentence token that represents the end of a sentence, unknown token, and padding token that pads sentence batches into equivalent length. End of explanation pad_token_id = source_tokenizer.token_to_id(pad_token) eos_token_id = source_tokenizer.token_to_id(eos_token) def batch_encode_fn(examples): sources = examples[source_lang] targets = examples[target_lang] input_ids = [encoding.ids + [eos_token_id] for encoding in source_tokenizer.encode_batch(sources)] labels = [encoding.ids + [eos_token_id] for encoding in target_tokenizer.encode_batch(targets)] examples['input_ids'] = input_ids examples['labels'] = labels return examples dataset_dict_encoded = dataset_dict.map(batch_encode_fn, batched=True, num_proc=8) dataset_dict_encoded dataset_train = dataset_dict_encoded['train'] dataset_train[0] Explanation: We'll perform this tokenization step for all our dataset up front, so we can do as little preprocessing as possible while feeding our dataset to model. Note that we do not perform the padding step at this stage. End of explanation class Seq2SeqDataCollator: def __init__( self, max_length: int, pad_token_id: int, pad_label_token_id: int = -100 ): self.max_length = max_length self.pad_token_id = pad_token_id self.pad_label_token_id = pad_label_token_id def __call__(self, batch): source_batch = [] source_len = [] target_batch = [] target_len = [] for example in batch: source = example['input_ids'] source_len.append(len(source)) source_batch.append(source) target = example['labels'] target_len.append(len(target)) target_batch.append(target) source_padded = self.process_encoded_text(source_batch, source_len, self.pad_token_id) target_padded = self.process_encoded_text(target_batch, target_len, self.pad_label_token_id) attention_mask = generate_attention_mask(source_padded, self.pad_token_id) return { 'input_ids': source_padded, 'labels': target_padded, 'attention_mask': attention_mask } def process_encoded_text(self, sequences, sequences_len, pad_token_id): sequences_max_len = np.max(sequences_len) max_length = min(sequences_max_len, self.max_length) padded_sequences = pad_sequences(sequences, max_length, pad_token_id) return torch.LongTensor(padded_sequences) def generate_attention_mask(input_ids, pad_token_id): return (input_ids != pad_token_id).long() def pad_sequences(sequences, max_length, pad_token_id): Pad the list of sequences (numerical token ids) to the same length. Sequence that are shorter than the specified ``max_len`` will be appended with the specified ``pad_token_id``. Those that are longer will be truncated. Parameters ---------- sequences : list[int] List of numerical token ids. max_length : int Maximum length that all sequences will be truncated/padded to. pad_token_id : int Padding token index. Returns ------- padded_sequences : 1d ndarray num_samples = len(sequences) padded_sequences = np.full((num_samples, max_length), pad_token_id) for i, sequence in enumerate(sequences): sequence = np.array(sequence)[:max_length] padded_sequences[i, :len(sequence)] = sequence return padded_sequences Explanation: Given the custom tokenizer, we can also custom our data collate class that does the padding for input and labels. End of explanation config_params = { 'd_model': 256, 'decoder_layers': 3, 'decoder_attention_heads': 8, 'decoder_ffn_dim': 512, 'encoder_layers': 6, 'encoder_attention_heads': 8, 'encoder_ffn_dim': 512, 'max_length': 128, 'max_position_embeddings': 128, 'eos_token_id': eos_token_id, 'pad_token_id': pad_token_id, 'decoder_start_token_id': pad_token_id, "bad_words_ids": [ [ pad_token_id ] ], 'vocab_size': source_tokenizer.get_vocab_size() } model_config = AutoConfig.from_pretrained(model_checkpoint, **config_params) model_config transformers_model = AutoModelForSeq2SeqLM.from_config(model_config) print('# of parameters: ', transformers_model.num_parameters()) transformers_model batch_size = 128 args = Seq2SeqTrainingArguments( output_dir="test-translation", evaluation_strategy="epoch", learning_rate=0.0005, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, weight_decay=0.01, save_total_limit=3, num_train_epochs=20, load_best_model_at_end=True, predict_with_generate=True, remove_unused_columns=True, fp16=True ) data_collator = Seq2SeqDataCollator(model_config.max_length, pad_token_id) callbacks = [EarlyStoppingCallback(early_stopping_patience=3)] trainer = Seq2SeqTrainer( transformers_model, args, train_dataset=dataset_dict_encoded["train"], eval_dataset=dataset_dict_encoded["val"], data_collator=data_collator, callbacks=callbacks ) dataloader_train = trainer.get_train_dataloader() next(iter(dataloader_train)) trainer_output = trainer.train() trainer_output def generate_translation(model, source_tokenizer, target_tokenizer, example): source = example[source_lang] target = example[target_lang] input_ids = source_tokenizer.encode(source).ids input_ids = torch.LongTensor(input_ids).view(1, -1).to(model.device) generated_ids = model.generate(input_ids) generated_ids = generated_ids[0].detach().cpu().numpy() prediction = target_tokenizer.decode(generated_ids) print('source: ', source) print('target: ', target) print('prediction: ', prediction) example = dataset_dict['train'][0] generate_translation(transformers_model, source_tokenizer, target_tokenizer, example) example = dataset_dict['test'][0] generate_translation(transformers_model, source_tokenizer, target_tokenizer, example) Explanation: Given that we are using our own tokenizer instead of the pre-trained ones, we need to update a couple of other parameters in our config. The one that's worth pointing out is that this model starts generating with pad_token_id, that's why the decoder_start_token_id is the same as the pad_token_id. Then rest of model training code should be the same as the ones in the previous section. End of explanation model_checkpoint = 'transformers_model' transformers_model.save_pretrained(model_checkpoint) transformers_model_loaded = transformers_model.from_pretrained(model_checkpoint).to(device) example = dataset_dict['test'][0] generate_translation(transformers_model_loaded, source_tokenizer, target_tokenizer, example) Explanation: Confirming saving and loading the model gives us identical predictions. End of explanation len(dataset_dict_encoded['test']) # we use a different data collator then the one we used for training and evaluating model # replace -100 in the labels with other special tokens during inferencing # as we can't decode them. data_collator = Seq2SeqDataCollator(model_config.max_length, pad_token_id, pad_token_id) data_loader = DataLoader(dataset_dict_encoded['test'], collate_fn=data_collator, batch_size=64) data_loader start = time.time() rows = [] for example in data_loader: input_ids = example['input_ids'] generated_ids = transformers_model.generate(input_ids.to(transformers_model.device)) generated_ids = generated_ids.detach().cpu().numpy() predictions = target_tokenizer.decode_batch(generated_ids) labels = example['labels'].detach().cpu().numpy() targets = target_tokenizer.decode_batch(labels) sources = source_tokenizer.decode_batch(input_ids.detach().cpu().numpy()) for source, target, prediction in zip(sources, targets, predictions): row = [source, target, prediction] rows.append(row) end = time.time() print('elapsed: ', end - start) df_rows = pd.DataFrame(rows, columns=['source', 'target', 'prediction']) df_rows Explanation: As the last step, we'll write a inferencing function that performs batch scoring on a given dataset. Here we generate the predictions and save it in a pandas dataframe along with the source and the target. End of explanation
5,393
Given the following text description, write Python code to implement the functionality described below step by step Description: Self-Driving Car Engineer Nanodegree Project Step1: Read in an Image Step10: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are Step11: Test Images Build your pipeline to work on the images in the directory "test_images" You should make sure your pipeline works well on these images before you try the videos. Step12: Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the test_images directory, and you can use the images in your writeup report. Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. Step13: Test on Videos You know what's cooler than drawing lanes over images? Drawing lanes over video! We can test our solution on two provided videos Step14: Let's try the one with the solid white lane on the right first ... Step17: Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. Step19: Improve the draw_lines() function At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest. Step21: Now for the one with the solid yellow lane on the left. This one's more tricky! Step23: Writeup and Submission If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a link to the writeup template file. Optional Challenge Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project!
Python Code: #importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline Explanation: Self-Driving Car Engineer Nanodegree Project: Finding Lane Lines on the Road In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a series of images). Check out the video clip "raw-lines-example.mp4" (also contained in this repository) to see what the output should look like after using the helper functions below. Once you have a result that looks roughly like "raw-lines-example.mp4", you'll need to get creative and try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Ultimately, you would like to draw just one line for the left side of the lane, and one for the right. In addition to implementing code, there is a brief writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing both the code in the Ipython notebook and the writeup template will cover all of the rubric points for this project. Let's have a look at our first image called 'test_images/solidWhiteRight.jpg'. Run the 2 cells below (hit Shift-Enter or the "play" button above) to display the image. Note: If, at any point, you encounter frozen display windows or other confounding issues, you can always start again with a clean slate by going to the "Kernel" menu above and selecting "Restart & Clear Output". The tools you have are color selection, region of interest selection, grayscaling, Gaussian smoothing, Canny Edge Detection and Hough Tranform line detection. You are also free to explore and try other techniques that were not presented in the lesson. Your goal is piece together a pipeline to detect the line segments in the image, then average/extrapolate them and draw them onto the image for display (as below). Once you have a working pipeline, try it out on the video stream below. <figure> <img src="line-segments-example.jpg" width="380" alt="Combined Image" /> <figcaption> <p></p> <p style="text-align: center;"> Your output should look something like this (above) after detecting line segments using the helper functions below </p> </figcaption> </figure> <p></p> <figure> <img src="laneLines_thirdPass.jpg" width="380" alt="Combined Image" /> <figcaption> <p></p> <p style="text-align: center;"> Your goal is to connect/average/extrapolate line segments to get output like this</p> </figcaption> </figure> Run the cell below to import some packages. If you get an import error for a package you've already installed, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, see this forum post for more troubleshooting tips. Import Packages End of explanation #reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimesions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gray') Explanation: Read in an Image End of explanation import math def grayscale(img): Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') #return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # Or use BGR2GRAY if you read an image with cv2.imread() return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) def canny(img, low_threshold, high_threshold): Applies the Canny transform return cv2.Canny(img, low_threshold, high_threshold) def gaussian_blur(img, kernel_size): Applies a Gaussian Noise kernel return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) def region_of_interest(img, vertices): Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel or 1 channel color to fill the mask with depending on the input image if len(img.shape) > 2: channel_count = img.shape[2] # i.e. 3 or 4 depending on your image ignore_mask_color = (255,) * channel_count else: ignore_mask_color = 255 #filling pixels inside the polygon defined by "vertices" with the fill color cv2.fillPoly(mask, vertices, ignore_mask_color) #returning the image only where mask pixels are nonzero masked_image = cv2.bitwise_and(img, mask) return masked_image def draw_lines_old(img, lines, color=[255, 0, 0], thickness=6): NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below for line in lines: for x1,y1,x2,y2 in line: cv2.line(img,(x1,y1),(x2,y2), color, thickness) def draw_lines(img, lines, color=[255, 0, 0], thickness=5): NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that shown in P1_example.mp4). Think about things like separating line segments by their slope ((y2-y1)/(x2-x1)) to decide which segments are part of the left line vs. the right line. Then, you can average the position of each of the lines and extrapolate to the top and bottom of the lane. This function draws `lines` with `color` and `thickness`. Lines are drawn on the image inplace (mutates the image). If you want to make the lines semi-transparent, think about combining this function with the weighted_img() function below #define parameters here left_m = 0 left_bias = 0 right_m = 0 right_bias = 0 left_size = 0 right_size = 0 height = img.shape[0] width = img.shape[1] #in this function, we use y = m * x + b; m is slope, and b is bias. for line in lines: for x1,y1,x2,y2 in line: #calculate the slope slope = ((y2 - y1)/(x2 - x1)) #print(slope) #because in lane line detection, if the slope is close to 0, this line maybe is noise if(slope < 0.5 and slope > -0.5): break point = np.mean(line, axis=0) #left line if slope < -0.5: #sum of m & bias left_m += slope left_bias += point[1] - point[0] * slope left_size += 1 #print(slope) if slope > 0.5: #sum of m & bias right_m += slope right_bias += point[1] - point[0] * slope right_size += 1 #print(slope) if(right_size>0): #draw single right line cv2.line(img,(int(width*9/16), int(right_m/right_size * int(width*9/16) + right_bias/right_size)),(width, int(right_m/right_size * width +right_bias/right_size)), color, thickness ) #cv2.line(img, (int((539 - right_bias/right_size)/(right_m/right_size)), 539), (549, int(right_m/right_size * 549 + right_bias/right_size)), color, thickness) if(left_size > 0): pass #draw single left line cv2.line(img, (0, int(left_bias/left_size)), (int(width*7/16), int(left_m/left_size * int(width*7/16) + left_bias/left_size)), color, thickness) def hough_lines(img, rho, theta, threshold, min_line_len, max_line_gap, new_draw_fun = True): `img` should be the output of a Canny transform. Returns an image with hough lines drawn. lines = cv2.HoughLinesP(img, rho, theta, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) line_img = np.zeros((img.shape[0], img.shape[1], 3), dtype=np.uint8) if(new_draw_fun): draw_lines(line_img, lines) else: draw_lines_old(line_img, lines) return line_img # Python 3 has support for cool math symbols. def weighted_img(img, initial_img, α=0.8, β=1., λ=0.): `img` is the output of the hough_lines(), An image with lines drawn on it. Should be a blank image (all black) with lines drawn on it. `initial_img` should be the image before any processing. The result image is computed as follows: initial_img * α + img * β + λ NOTE: initial_img and img must be the same shape! return cv2.addWeighted(initial_img, α, img, β, λ) Explanation: Ideas for Lane Detection Pipeline Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are: cv2.inRange() for color selection cv2.fillPoly() for regions selection cv2.line() to draw lines on an image given endpoints cv2.addWeighted() to coadd / overlay two images cv2.cvtColor() to grayscale or change color cv2.imwrite() to output images to file cv2.bitwise_and() to apply a mask to an image Check out the OpenCV documentation to learn about these and discover even more awesome functionality! Helper Functions Below are some helper functions to help get you started. They should look familiar from the lesson! End of explanation import os os.listdir("test_images/") Explanation: Test Images Build your pipeline to work on the images in the directory "test_images" You should make sure your pipeline works well on these images before you try the videos. End of explanation # TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images directory. def fine_lane_lines_function(image, new_draw_func): # define parameters here kernel_size = 3 low_threshold = 50 high_threshold = 150 imshape = image.shape vertices = np.array([[(0,imshape[0]),(imshape[1]*7/16,imshape[0]*5/8), (imshape[1]*9/16, imshape[0]*5/8), (imshape[1],imshape[0])]], dtype=np.int32) #convert the RGB image to grayscale gray = grayscale(image) #blur the gray image blur_gray = gaussian_blur(gray, kernel_size) #using canny edge function for the blur gray image edges = canny(blur_gray, low_threshold, high_threshold) #masked edges image by using region_of_interest function masked_edges = region_of_interest(edges, vertices) #here we use hough transform to process the masked edges #define parameters here rho = 2 # distance resolution in pixels of the Hough grid theta = np.pi/180 # angular resolution in radians of the Hough grid threshold = 100 # minimum number of votes (intersections in Hough grid cell) min_line_len = 100 #minimum number of pixels making up a line max_line_gap = 160 # maximum gap in pixels between connectable line segments line_image = np.copy(image)*0 # creating a blank to draw lines on #calling hough transform function and output color_edges color_edges = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap, new_draw_fun = new_draw_func) lines_edges = weighted_img(color_edges, image) return lines_edges for img_ in os.listdir("test_images/"): image_address = "test_images/"+img_ #read image from input address image = cv2.imread(image_address) lines_edges = fine_lane_lines_function(image, False) #debug-code for visiulization fig = plt.figure() plt.imshow(lines_edges) #saving image to the test_images directory cv2.imwrite("test_images/test_"+img_,lines_edges) Explanation: Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the test_images directory, and you can use the images in your writeup report. Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters. End of explanation # Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the final output (image where lines are drawn on lanes) result = fine_lane_lines_function(image, False) return result Explanation: Test on Videos You know what's cooler than drawing lanes over images? Drawing lanes over video! We can test our solution on two provided videos: solidWhiteRight.mp4 solidYellowLeft.mp4 Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel). Still have problems? Try relaunching Jupyter Notebook from the terminal prompt. Also, check out this forum post for more troubleshooting tips. If you get an error that looks like this: NeedDownloadError: Need ffmpeg exe. You can download it by calling: imageio.plugins.ffmpeg.download() Follow the instructions in the error message and check out this forum post for more troubleshooting tips across operating systems. End of explanation white_output = 'white_1.mp4' clip1 = VideoFileClip("solidWhiteRight.mp4") white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!! %time white_clip.write_videofile(white_output, audio=False) Explanation: Let's try the one with the solid white lane on the right first ... End of explanation HTML( <video width="960" height="540" controls> <source src="{0}"> </video> .format(white_output)) yello_output = 'yello_1.mp4' clip1 = VideoFileClip("solidYellowLeft.mp4") white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!! %time white_clip.write_videofile(yello_output, audio=False) HTML( <video width="960" height="540" controls> <source src="{0}"> </video> .format(yello_output)) Explanation: Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. End of explanation def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the final output (image where lines are drawn on lanes) result = fine_lane_lines_function(image, True) return result white_output = 'white_2.mp4' clip1 = VideoFileClip("solidWhiteRight.mp4") white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!! %time white_clip.write_videofile(white_output, audio=False) HTML( <video width="960" height="540" controls> <source src="{0}"> </video> .format(white_output)) Explanation: Improve the draw_lines() function At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments you identified with the Hough Transform. As mentioned previously, try to average and/or extrapolate the line segments you've detected to map out the full extent of the lane lines. You can see an example of the result you're going for in the video "P1_example.mp4". Go back and modify your draw_lines function accordingly and try re-running your pipeline. The new output should draw a single, solid line over the left lane line and a single, solid line over the right lane line. The lines should start from the bottom of the image and extend out to the top of the region of interest. End of explanation yellow_output = 'yellow_2.mp4' clip2 = VideoFileClip('solidYellowLeft.mp4') yellow_clip = clip2.fl_image(process_image) %time yellow_clip.write_videofile(yellow_output, audio=False) HTML( <video width="960" height="540" controls> <source src="{0}"> </video> .format(yellow_output)) Explanation: Now for the one with the solid yellow lane on the left. This one's more tricky! End of explanation def pipeline(image, new_draw_func): # define parameters here #print(image.shape) kernel_size = 6 low_threshold = 50 high_threshold = 150 imshape = image.shape vertices = np.array([[(0,imshape[0]),(imshape[1]*7/16,imshape[0]*5/8), (imshape[1]*9/16, imshape[0]*5/8), (imshape[1],imshape[0])]], dtype=np.int32) #using hsv image hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) yellow = cv2.inRange(hsv, (20, 80, 80), (25, 255, 255)) white = cv2.inRange(hsv, (0, 0, 180), (255, 25, 255)) #convert to grayscale gray = cv2.bitwise_or(yellow, white) #using canny edge function for the blur gray image edges = canny(gray, low_threshold, high_threshold) #masked edges image by using region_of_interest function masked_edges = region_of_interest(edges, vertices) #here we use hough transform to process the masked edges #define parameters here rho = 4 # distance resolution in pixels of the Hough grid theta = np.pi/180 # angular resolution in radians of the Hough grid threshold = 100 # minimum number of votes (intersections in Hough grid cell) min_line_len = 10 #minimum number of pixels making up a line max_line_gap = 10 # maximum gap in pixels between connectable line segments line_image = np.copy(image)*0 # creating a blank to draw lines on #calling hough transform function and output color_edges color_edges = hough_lines(masked_edges, rho, theta, threshold, min_line_len, max_line_gap, new_draw_fun = new_draw_func) lines_edges = weighted_img(color_edges, image) return lines_edges def process_image_1(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the final output (image where lines are drawn on lanes) result = pipeline(image, True) return result challenge_output = 'extra.mp4' clip2 = VideoFileClip('challenge.mp4') challenge_clip = clip2.fl_image(process_image_1) %time challenge_clip.write_videofile(challenge_output, audio=False) HTML( <video width="960" height="540" controls> <source src="{0}"> </video> .format(challenge_output)) Explanation: Writeup and Submission If you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a link to the writeup template file. Optional Challenge Try your lane finding pipeline on the video below. Does it still work? Can you figure out a way to make it more robust? If you're up for the challenge, modify your pipeline so it works with this video and submit it along with the rest of your project! End of explanation
5,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Resources http Step1: Compute the traces of cross-sections
Python Code: fin = open('./../data/trench.xy', 'r') trench = [] for line in fin: aa = re.split('\s+', re.sub('^\s+', '', line)) trench.append((float(aa[0]), float(aa[1]))) fin.close() trench = Trench(numpy.array(trench)) cat = pickle.load(open("./../data/catalogue_ext_cac.p", "rb" )) Explanation: Resources http://nicoya.eas.gatech.edu/Data_Products GTDEF http://geophysics.eas.gatech.edu/anewman/classes/MGM/GTdef/ Load trench data End of explanation minlo = -110 minla = 5 maxlo = -75 maxla = 25 midlo = -100 midla = 20 from hmtk.parsers.catalogue.gcmt_ndk_parser import ParseNDKtoGCMT from obspy.imaging.beachball import beach gcmt_filename = '/Users/mpagani/Data/catalogues/gcmt/jan76_dec13.ndk' gcmtc = ParseNDKtoGCMT(gcmt_filename) gcmtc.read_file() def plot_nodal_planes(catalogue, ax, minlo, minla, maxlo, maxla): beach1 = beach(np1, xy=(-70, 80), width=30) beach2 = beach(mt, xy=(50, 50), width=50) ax.add_collection(beach1) ax.add_collection(beach2) fig = plt.figure(figsize=(12,9)) # # Plot the basemap m = Basemap(llcrnrlon=minlo, llcrnrlat=minla, urcrnrlon=maxlo, urcrnrlat=maxla, resolution='i', projection='tmerc', lon_0=midlo, lat_0=midla) # # Draw paralleles and meridians with labels # labels = [left,right,top,bottom] m.drawcoastlines() m.drawmeridians(numpy.arange(numpy.floor(minlo/10.)*10, numpy.ceil(maxlo/10.)*10,5.), labels=[False, False, False, True]) m.drawparallels(numpy.arange(numpy.floor(minla/10.)*10, numpy.ceil(maxla/10.)*10,5.), labels=[True, False, False, False]) # # Plot the instrumental catalogue xa, ya = m(cat.data['longitude'], cat.data['latitude']) szea = (cat.data['magnitude']*100)**1.5 patches = [] for x, y, sze in zip(list(xa), list(ya), szea): circle = Circle((x, y), sze, ec='white') patches.append(circle) print ('depths: %f %f ' % (min(cat.data['depth']), max(cat.data['depth']))) colors = cat.data['depth'] p = PatchCollection(patches, zorder=6, edgecolors='white') p.set_alpha(0.5) p.set_clim([0, 200]) p.set_array(numpy.array(colors)) plt.gca().add_collection(p) plt.colorbar(p,fraction=0.02, pad=0.04, extend='max') # # GCMT x, y = m(gcmtc.catalogue.data['longitude'], gcmtc.catalogue.data['latitude']) #plt.plot(x, y, 'sr', zorder=10, alpha=.5) # # Plot the traces of cross-sections distance = 100 cs_len = 400 ts = trench.resample(distance) fou = open('cs_traces.csv', 'w') x, y = m(trench.axis[:, 0], trench.axis[:, 1]) plt.plot(x, y, '-g', linewidth=2, zorder=10) x, y = m(ts.axis[:, 0], ts.axis[:, 1]) plt.plot(x, y, '--y', linewidth=4, zorder=20) for idx, cs in enumerate(trench.iterate_cross_sections(distance, cs_len)): if cs is not None: x, y = m(cs.plo, cs.pla) plt.plot(x, y, ':r', linewidth=2, zorder=20) text = plt.text(x[-1], y[-1], '%d' % idx, ha='center', va='center', size=10, zorder=30) text.set_path_effects([PathEffects.withStroke(linewidth=3, foreground="w")]) tmps = '%f %f %f %f %d\n' % (cs.plo[0], cs.pla[0], cs_len, cs.strike[0], idx) print (tmps.rstrip()) fou.write(tmps) fou.close() Explanation: Compute the traces of cross-sections End of explanation
5,395
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook shows how to extract information from a spectral line using the weak-field approximation. It uses a Bayesian approach to the problem. Index Simple case Biases Errors in both coordinates Simple case <a id='simpleCase'></a> Let us generate an artificial spectral line in the weak field regime and do the inference. Step1: Let us check if the line is in the weak-field regime. For this, we plot Stokes V vs. the wavelength derivative of Stokes I and check if it is a straight line. Step2: We can do a linear fit and get the magnetic flux density. Remember that the fit has to be $y=a*x$. To do the fit, write the $\chi^2$ and optimize it. Step3: Let us investigate a little the $\chi^2$ surface Step4: Biases <a id='bias'></a> The maximum likelihood solution can be written analytically when using $B_\parallel$ and $B_\perp$. It is interesting to analyze the behavior of $B_\perp$ when there is noise. It is given by Step5: Errors in both coordinates <a id='errorBothCoordinates'></a> In fact, we always have noise both in Stokes V and I (typically being larger in Stokes I). Therefore, our model fitting has to take this into account. Step6: The exact value of the noise in the derivative depends on how you carry out the numerical derivative. For instance, if we use a first order derivative formula, the error propagation formula states Step7: Now we sample the distribution taking into account the presence of uncertainties in both axis. Following standard techniques, we assume that our measurement fulfills $$ y_i = z_i + e_i $$ where $z_i$ is our predictor, characterized by a distribution $p_Z(z_i)$ and $e_i$ is the uncertainty in the measurement, characterized by the distribution $p_E(e_i)$. In such case, the distribution for $y_i$ is given by $$ p(y_i) = \int dz_i p_Z(z_i) p_E(y_i-z_i) $$ In our case, we are assuming that $z_i$ is uncertain because the points at which they are evaluated are uncertain. Assume that the uncertainty in $x_i$ is Gaussian, so that $$ p(x_i) = N(x_{i0},\sigma_x^2) $$ where $x_{i0}$ is the nominal value of $x_i$. Now, we know that, in our case, $z_i=\alpha x_i$, because they follow a linear relationship. In this case, it is easy to compute $p_Z(z_i)$ from the change of variables
Python Code: lambda0 = 6301.5080 JUp = 2.0 JLow = 2.0 gUp = 1.5 gLow = 1.833 lambdaStart = 6300.8 lambdaStep = 0.03 nLambda = 50 lineInfo = np.asarray([lambda0, JUp, JLow, gUp, gLow, lambdaStart, lambdaStep]) s = pymilne.milne(nLambda, lineInfo) stokes = np.zeros((4,nLambda)) BField = 100.0 BTheta = 20.0 BChi = 0.0 VMac = 2.0 damping = 0.0 B0 = 0.8 B1 = 0.2 mu = 1.0 VDop = 0.085 kl = 5.0 modelSingle = np.asarray([BField, BTheta, BChi, VMac, damping, B0, B1, VDop, kl]) stokes = s.synth(modelSingle,mu) wl = np.arange(nLambda)*lambdaStep + lambdaStart f, ax = pl.subplots(ncols=2, nrows=1, figsize=(12,6)) ax = ax.flatten() labels = ['I/I$_c$','V/I$_c$'] which = [0,3] for i in range(2): ax[i].plot(wl, stokes[which[i],:]) ax[i].set_xlabel('Wavelength [$\AA$]') ax[i].set_ylabel(labels[i]) ax[i].ticklabel_format(useOffset=False) pl.tight_layout() sigma = 1e-4 stI = stokes[0,:] + sigma*np.random.randn(nLambda) stV = stokes[3,:] + sigma*np.random.randn(nLambda) diffI = np.gradient(stI, lambdaStep) Explanation: This notebook shows how to extract information from a spectral line using the weak-field approximation. It uses a Bayesian approach to the problem. Index Simple case Biases Errors in both coordinates Simple case <a id='simpleCase'></a> Let us generate an artificial spectral line in the weak field regime and do the inference. End of explanation pl.plot(diffI, stV) Explanation: Let us check if the line is in the weak-field regime. For this, we plot Stokes V vs. the wavelength derivative of Stokes I and check if it is a straight line. End of explanation coef = np.sum(stV*diffI)/np.sum(diffI**2) print coef print "Original BLOS={0:6.2f} Mx cm-2 - Inferred BLOS={1:6.2f} Mx cm-2".format(BField*np.cos(BTheta*np.pi/180.0),-coef / (4.6686e-13*6301.**2*1.5)) Explanation: We can do a linear fit and get the magnetic flux density. Remember that the fit has to be $y=a*x$. To do the fit, write the $\chi^2$ and optimize it. End of explanation class linearFit(object): def __init__(self, diffI, V, noise): self.diffI = diffI self.V = V self.noise = noise self.lower = np.asarray([0.0, 0.0]) self.upper = np.asarray([500.0, 180.0]) def logPosterior(self, theta): if ( (theta[0] < self.lower[0]) | (theta[0] > self.upper[0]) | (theta[1] < self.lower[1]) | (theta[1] > self.upper[1]) ): return -np.inf else: model = -4.6686e-13 * 6301.0**2 * 1.5 * theta[0] * np.cos(theta[1] * np.pi/180.0) * self.diffI return -np.sum((self.V-model)**2 / (2.0*self.noise**2)) def sample(self): ndim, nwalkers = 2, 500 self.theta0 = np.asarray([50.0,30.0]) p0 = [self.theta0 + 0.01*np.random.randn(ndim) for i in range(nwalkers)] self.sampler = emcee.EnsembleSampler(nwalkers, ndim, self.logPosterior) self.sampler.run_mcmc(p0, 300) out = linearFit(diffI, stV, sigma) out.sample() BSamples = out.sampler.chain[:,-20:,0].flatten() thBSamples = out.sampler.chain[:,-20:,1].flatten() f, ax = pl.subplots(ncols=2, nrows=3, figsize=(12,8)) ax[0,0].plot(BSamples) ax[0,1].hist(BSamples) ax[0,0].set_ylabel('B') ax[0,1].set_xlabel('B') ax[1,0].plot(thBSamples) ax[1,1].hist(thBSamples) ax[1,0].set_ylabel(r'$\theta_B$') ax[1,1].set_xlabel(r'$\theta_B$') ax[2,0].plot(BSamples*np.cos(thBSamples*np.pi/180.0)) ax[2,1].hist(BSamples*np.cos(thBSamples*np.pi/180.0)) ax[2,0].set_ylabel(r'B*cos($\theta_B$)') ax[2,1].set_xlabel(r'B*cos($\theta_B$)') pl.tight_layout() pl.savefig('weakSamplingSimple.png') f, ax = pl.subplots(figsize=(12,10)) ax.hexbin(BSamples,thBSamples) ax.set_xlabel('B [G]') ax.set_ylabel(r'$\theta_B$ [deg]') Explanation: Let us investigate a little the $\chi^2$ surface End of explanation stI = stokes[0,:] + sigma*np.random.randn(nLambda) stQ = sigma*np.random.randn(nLambda) stU = sigma*np.random.randn(nLambda) stIp = 6301.0**2*1.5*np.gradient(stI, lambdaStep) stIpp = 0.25*6301.0**2*1.5*np.gradient(stIp, lambdaStep) C = 4.67e-13 Bpar = np.zeros(500) Bperp = np.zeros(500) for i in range(500): stV = stokes[3,:] + sigma*np.random.randn(nLambda) stQ = stokes[1,:] + sigma*np.random.randn(nLambda) stU = stokes[2,:] + sigma*np.random.randn(nLambda) Bpar[i] = -1.0/C * np.sum(stV*stIp) / np.sum(stIp**2) Bperp[i] = np.sqrt(1.0/C**2 * np.sqrt( np.sum(stQ*stIpp)**2 + np.sum(stU*stIpp)**2 ) / np.sum(stIpp**2)) f, ax = pl.subplots(ncols=2, nrows=2, figsize=(9,9)) ax[0,0].hist(Bpar) ax[0,1].hist(Bperp) ax[1,0].hist(180.0/np.pi*np.arctan(Bperp, Bpar)) Explanation: Biases <a id='bias'></a> The maximum likelihood solution can be written analytically when using $B_\parallel$ and $B_\perp$. It is interesting to analyze the behavior of $B_\perp$ when there is noise. It is given by: $$ B_\perp^2 = \frac{1}{C^2} \frac{\left[ \left(\sum_i Q_i I_i'' \right)^2+ \left(\sum_i U_i I_i'' \right)^2 \right]^{1/2}} {\sum_i I_i''^2} $$ Imagine the case of pure noise in Stokes $Q$ and $U$. End of explanation lambda0 = 6301.5080 JUp = 2.0 JLow = 2.0 gUp = 1.5 gLow = 1.833 lambdaStart = 6300.8 lambdaStep = 0.015 nLambda = 100 lineInfo = np.asarray([lambda0, JUp, JLow, gUp, gLow, lambdaStart, lambdaStep]) s = pymilne.milne(nLambda, lineInfo) stokes = np.zeros((4,nLambda)) BField = 100.0 BTheta = 20.0 BChi = 0.0 VMac = 2.0 damping = 0.0 B0 = 0.8 B1 = 0.2 mu = 1.0 VDop = 0.085 kl = 5.0 modelSingle = np.asarray([BField, BTheta, BChi, VMac, damping, B0, B1, VDop, kl]) stokes = s.synth(modelSingle,mu) wl = np.arange(nLambda)*lambdaStep + lambdaStart stokesNoise = np.copy(stokes) sigmaI = 5e-3 sigmaV = 1e-3 stokesNoise[0,:] = stokes[0,:] + sigmaI*np.random.randn(nLambda) stokesNoise[3,:] = stokes[3,:] + sigmaV*np.random.randn(nLambda) diffI = np.gradient(stokesNoise[0,:], lambdaStep) f, ax = pl.subplots(ncols=3, nrows=1, figsize=(15,6)) ax = ax.flatten() labels = ['I/I$_c$','V/I$_c$'] which = [0,3] for i in range(2): ax[i].plot(wl, stokesNoise[which[i],:]) ax[i].plot(wl, stokes[which[i],:]) ax[i].set_xlabel('Wavelength [$\AA$]') ax[i].set_ylabel(labels[i]) ax[i].ticklabel_format(useOffset=False) ax[2].plot(wl, diffI) ax[2].set_xlabel('Wavelength [$\AA$]') ax[2].set_ylabel('dI/d$\lambda$') ax[2].ticklabel_format(useOffset=False) pl.tight_layout() sigmaDiffI = np.std(diffI[0:25]) print "Estimated noise in dIdl in units of sigma_I={0}".format(sigmaDiffI / sigmaI) f, ax = pl.subplots(figsize=(12,6)) ax.errorbar(diffI, stokesNoise[3,:], yerr=sigmaV, xerr=sigmaDiffI, fmt='.') Explanation: Errors in both coordinates <a id='errorBothCoordinates'></a> In fact, we always have noise both in Stokes V and I (typically being larger in Stokes I). Therefore, our model fitting has to take this into account. End of explanation coef = np.sum(stokesNoise[3,:]*diffI)/np.sum(diffI**2) print "Estimated field = {0} G".format(coef / (-4.6686e-13*6301.**2*1.5)) print "Real field = {0} G".format(BField*np.cos(BTheta*np.pi/180.0)) Explanation: The exact value of the noise in the derivative depends on how you carry out the numerical derivative. For instance, if we use a first order derivative formula, the error propagation formula states: $$ \sigma_{I'}^2 = \left( \frac{2}{\Delta \lambda} \right)^2 \sigma_I^2 $$ First, let us compute the maximum-likelihood solution neglecting errors in x. This is obtained just by: End of explanation class linearBothAxisFit(object): def __init__(self, diffI, V, noiseDiffI, noiseV): self.diffI = diffI self.V = V self.noiseDiffI = noiseDiffI self.noiseV = noiseV self.lower = np.asarray([-0.01]) self.upper = np.asarray([0.01]) def logPosterior(self, theta): if ( (theta[0] < self.lower[0]) | (theta[0] > self.upper[0]) ): return -np.inf else: model = theta[0] * self.diffI variance = self.noiseV**2 + theta[0]**2 * self.noiseDiffI**2 return -0.5*np.sum(np.log(variance)) - 0.5 * np.sum((self.V-model)**2 / variance) def sample(self): ndim, nwalkers = 1, 500 self.theta0 = np.asarray([-0.005]) p0 = [self.theta0 + 0.001*np.random.randn(ndim) for i in range(nwalkers)] self.sampler = emcee.EnsembleSampler(nwalkers, ndim, self.logPosterior) self.sampler.run_mcmc(p0, 300) class linearSingleAxisFit(object): def __init__(self, diffI, V, noiseV): self.diffI = diffI self.V = V self.noiseV = noiseV self.lower = np.asarray([-0.01]) self.upper = np.asarray([0.01]) def logPosterior(self, theta): if ( (theta[0] < self.lower[0]) | (theta[0] > self.upper[0]) ): return -np.inf else: model = theta[0] * self.diffI variance = self.noiseV**2 return -0.5*np.sum(np.log(variance)) - 0.5 * np.sum((self.V-model)**2 / variance) def sample(self): ndim, nwalkers = 1, 500 self.theta0 = np.asarray([-0.005]) p0 = [self.theta0 + 0.001*np.random.randn(ndim) for i in range(nwalkers)] self.sampler = emcee.EnsembleSampler(nwalkers, ndim, self.logPosterior) self.sampler.run_mcmc(p0, 300) outBoth = linearBothAxisFit(diffI, stokesNoise[3,:], sigmaDiffI, sigmaV) outBoth.sample() samplesBoth = outBoth.sampler.chain[:,-20:,0].flatten() / (-4.6686e-13*6301.**2*1.5) outSingle = linearSingleAxisFit(diffI, stokesNoise[3,:], sigmaV) outSingle.sample() samplesSingle = outSingle.sampler.chain[:,-20:,0].flatten() / (-4.6686e-13*6301.**2*1.5) f, ax = pl.subplots(ncols=2, nrows=1, figsize=(15,6)) ax[0].plot(samplesBoth) ax[0].plot(samplesSingle) ax[1].hist(samplesBoth, bins=40, label='xy errors') ax[1].hist(samplesSingle, bins=40, label='y errors') ax[0].set_ylabel(r'$\alpha$') ax[1].set_xlabel(r'$\alpha$') ax[0].axhline(BField*np.cos(BTheta*np.pi/180.0)) ax[1].axvline(BField*np.cos(BTheta*np.pi/180.0)) pl.legend() Explanation: Now we sample the distribution taking into account the presence of uncertainties in both axis. Following standard techniques, we assume that our measurement fulfills $$ y_i = z_i + e_i $$ where $z_i$ is our predictor, characterized by a distribution $p_Z(z_i)$ and $e_i$ is the uncertainty in the measurement, characterized by the distribution $p_E(e_i)$. In such case, the distribution for $y_i$ is given by $$ p(y_i) = \int dz_i p_Z(z_i) p_E(y_i-z_i) $$ In our case, we are assuming that $z_i$ is uncertain because the points at which they are evaluated are uncertain. Assume that the uncertainty in $x_i$ is Gaussian, so that $$ p(x_i) = N(x_{i0},\sigma_x^2) $$ where $x_{i0}$ is the nominal value of $x_i$. Now, we know that, in our case, $z_i=\alpha x_i$, because they follow a linear relationship. In this case, it is easy to compute $p_Z(z_i)$ from the change of variables: $$ p_Z(z_i) = p_X(x_i) \left| \frac{dx_i}{dz_i} \right| = p_X \left( \frac{z_i}{\alpha} \right) \left| \frac{dx_i}{dz_i} \right| $$ Taking this into account, the final likelihood function is $$ p(y_i) = \frac{1}{\sqrt{2\pi \left(\sigma_y^2 + \alpha \sigma_x^2 \right)}} \exp \left[ -\frac{1}{2} \frac{(y_i-\alpha x_i)^2}{\sigma_y^2 + \alpha \sigma_x^2} \right] $$ Another equivalent way of seeing this is to include the unobserved real values of the $x$ and $y$ points into the Bayesian problem and finally marginalizing it. $$ p(\mathbf{x},\mathbf{y},\alpha|\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}) = p(\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}|\mathbf{x},\mathbf{y},\alpha) p(\mathbf{x},\mathbf{y},\alpha) $$ $$ p(\alpha|\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}) = \int d \mathbf{x} d \mathbf{y} p(\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}|\mathbf{x},\mathbf{y},\alpha) p(\mathbf{x},\mathbf{y},\alpha) $$ Given that we are assuming that $y=\alpha x$, we can remove $y$ from the previous equations (using a Dirac delta prior) and finally compute $$ p(\alpha|\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}) = \int d \mathbf{x} p(\mathbf{x}\mathrm{obs},\mathbf{y}\mathrm{obs}|\mathbf{x},\alpha) p(\mathbf{x},\alpha) $$ where the likelihood for each point is given by a 2D Gaussian distribution $$ p(x_\mathrm{obs,i},y_\mathrm{obs,i}|\mathbf{x},\alpha) = \frac{1}{2\pi \sqrt{\sigma_x^2 \sigma_y^2}} \exp \left[ -\frac{1}{2} \left( \frac{(x-x_\mathrm{obs,i})^2}{\sigma_x^2} + \frac{(\alpha x-y_\mathrm{obs,i})^2}{\sigma_y^2} \right) \right] $$ If one computes the integral over $x$, the same result is obtained. End of explanation
5,396
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks 4. Key Properties --&gt; Transport Scheme 5. Key Properties --&gt; Boundary Forcing 6. Key Properties --&gt; Gas Exchange 7. Key Properties --&gt; Carbon Chemistry 8. Tracers 9. Tracers --&gt; Ecosystem 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton 11. Tracers --&gt; Ecosystem --&gt; Zooplankton 12. Tracers --&gt; Disolved Organic Matter 13. Tracers --&gt; Particules 14. Tracers --&gt; Dic Alkalinity 1. Key Properties Ocean Biogeochemistry key properties 1.1. Model Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Model Type Is Required Step7: 1.4. Elemental Stoichiometry Is Required Step8: 1.5. Elemental Stoichiometry Details Is Required Step9: 1.6. Prognostic Variables Is Required Step10: 1.7. Diagnostic Variables Is Required Step11: 1.8. Damping Is Required Step12: 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport Time stepping method for passive tracers transport in ocean biogeochemistry 2.1. Method Is Required Step13: 2.2. Timestep If Not From Ocean Is Required Step14: 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks Time stepping framework for biology sources and sinks in ocean biogeochemistry 3.1. Method Is Required Step15: 3.2. Timestep If Not From Ocean Is Required Step16: 4. Key Properties --&gt; Transport Scheme Transport scheme in ocean biogeochemistry 4.1. Type Is Required Step17: 4.2. Scheme Is Required Step18: 4.3. Use Different Scheme Is Required Step19: 5. Key Properties --&gt; Boundary Forcing Properties of biogeochemistry boundary forcing 5.1. Atmospheric Deposition Is Required Step20: 5.2. River Input Is Required Step21: 5.3. Sediments From Boundary Conditions Is Required Step22: 5.4. Sediments From Explicit Model Is Required Step23: 6. Key Properties --&gt; Gas Exchange *Properties of gas exchange in ocean biogeochemistry * 6.1. CO2 Exchange Present Is Required Step24: 6.2. CO2 Exchange Type Is Required Step25: 6.3. O2 Exchange Present Is Required Step26: 6.4. O2 Exchange Type Is Required Step27: 6.5. DMS Exchange Present Is Required Step28: 6.6. DMS Exchange Type Is Required Step29: 6.7. N2 Exchange Present Is Required Step30: 6.8. N2 Exchange Type Is Required Step31: 6.9. N2O Exchange Present Is Required Step32: 6.10. N2O Exchange Type Is Required Step33: 6.11. CFC11 Exchange Present Is Required Step34: 6.12. CFC11 Exchange Type Is Required Step35: 6.13. CFC12 Exchange Present Is Required Step36: 6.14. CFC12 Exchange Type Is Required Step37: 6.15. SF6 Exchange Present Is Required Step38: 6.16. SF6 Exchange Type Is Required Step39: 6.17. 13CO2 Exchange Present Is Required Step40: 6.18. 13CO2 Exchange Type Is Required Step41: 6.19. 14CO2 Exchange Present Is Required Step42: 6.20. 14CO2 Exchange Type Is Required Step43: 6.21. Other Gases Is Required Step44: 7. Key Properties --&gt; Carbon Chemistry Properties of carbon chemistry biogeochemistry 7.1. Type Is Required Step45: 7.2. PH Scale Is Required Step46: 7.3. Constants If Not OMIP Is Required Step47: 8. Tracers Ocean biogeochemistry tracers 8.1. Overview Is Required Step48: 8.2. Sulfur Cycle Present Is Required Step49: 8.3. Nutrients Present Is Required Step50: 8.4. Nitrous Species If N Is Required Step51: 8.5. Nitrous Processes If N Is Required Step52: 9. Tracers --&gt; Ecosystem Ecosystem properties in ocean biogeochemistry 9.1. Upper Trophic Levels Definition Is Required Step53: 9.2. Upper Trophic Levels Treatment Is Required Step54: 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton Phytoplankton properties in ocean biogeochemistry 10.1. Type Is Required Step55: 10.2. Pft Is Required Step56: 10.3. Size Classes Is Required Step57: 11. Tracers --&gt; Ecosystem --&gt; Zooplankton Zooplankton properties in ocean biogeochemistry 11.1. Type Is Required Step58: 11.2. Size Classes Is Required Step59: 12. Tracers --&gt; Disolved Organic Matter Disolved organic matter properties in ocean biogeochemistry 12.1. Bacteria Present Is Required Step60: 12.2. Lability Is Required Step61: 13. Tracers --&gt; Particules Particulate carbon properties in ocean biogeochemistry 13.1. Method Is Required Step62: 13.2. Types If Prognostic Is Required Step63: 13.3. Size If Prognostic Is Required Step64: 13.4. Size If Discrete Is Required Step65: 13.5. Sinking Speed If Prognostic Is Required Step66: 14. Tracers --&gt; Dic Alkalinity DIC and alkalinity properties in ocean biogeochemistry 14.1. Carbon Isotopes Is Required Step67: 14.2. Abiotic Carbon Is Required Step68: 14.3. Alkalinity Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'fio-ronm', 'sandbox-2', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: FIO-RONM Source ID: SANDBOX-2 Topic: Ocnbgchem Sub-Topics: Tracers. Properties: 65 (37 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:01 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks 4. Key Properties --&gt; Transport Scheme 5. Key Properties --&gt; Boundary Forcing 6. Key Properties --&gt; Gas Exchange 7. Key Properties --&gt; Carbon Chemistry 8. Tracers 9. Tracers --&gt; Ecosystem 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton 11. Tracers --&gt; Ecosystem --&gt; Zooplankton 12. Tracers --&gt; Disolved Organic Matter 13. Tracers --&gt; Particules 14. Tracers --&gt; Dic Alkalinity 1. Key Properties Ocean Biogeochemistry key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean biogeochemistry model code (PISCES 2.0,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Geochemical" # "NPZD" # "PFT" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.3. Model Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Fixed" # "Variable" # "Mix of both" # TODO - please enter value(s) Explanation: 1.4. Elemental Stoichiometry Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe elemental stoichiometry (fixed, variable, mix of the two) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.5. Elemental Stoichiometry Details Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe which elements have fixed/variable stoichiometry End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all prognostic tracer variables in the ocean biogeochemistry component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.diagnostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.7. Diagnostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all diagnotic tracer variables in the ocean biogeochemistry component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.damping') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.8. Damping Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any tracer damping used (such as artificial correction or relaxation to climatology,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport Time stepping method for passive tracers transport in ocean biogeochemistry 2.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for passive tracers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 2.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for passive tracers (if different from ocean) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) Explanation: 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks Time stepping framework for biology sources and sinks in ocean biogeochemistry 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for biology sources and sinks End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 3.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for biology sources and sinks (if different from ocean) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline" # "Online" # TODO - please enter value(s) Explanation: 4. Key Properties --&gt; Transport Scheme Transport scheme in ocean biogeochemistry 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of transport scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Use that of ocean model" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 4.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Transport scheme used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.use_different_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.3. Use Different Scheme Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Decribe transport scheme if different than that of ocean model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.atmospheric_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Atmospheric Chemistry model" # TODO - please enter value(s) Explanation: 5. Key Properties --&gt; Boundary Forcing Properties of biogeochemistry boundary forcing 5.1. Atmospheric Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how atmospheric deposition is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.river_input') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Land Surface model" # TODO - please enter value(s) Explanation: 5.2. River Input Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how river input is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_boundary_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.3. Sediments From Boundary Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from boundary condition End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_explicit_model') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.4. Sediments From Explicit Model Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from explicit sediment model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6. Key Properties --&gt; Gas Exchange *Properties of gas exchange in ocean biogeochemistry * 6.1. CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.2. CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe CO2 gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.3. O2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is O2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.4. O2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe O2 gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.5. DMS Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is DMS gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.6. DMS Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify DMS gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.7. N2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.8. N2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.9. N2O Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2O gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.10. N2O Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2O gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.11. CFC11 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC11 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.12. CFC11 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC11 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.13. CFC12 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC12 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.14. CFC12 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC12 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.15. SF6 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is SF6 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.16. SF6 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify SF6 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.17. 13CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 13CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.18. 13CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 13CO2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.19. 14CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 14CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.20. 14CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 14CO2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.other_gases') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.21. Other Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify any other gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other protocol" # TODO - please enter value(s) Explanation: 7. Key Properties --&gt; Carbon Chemistry Properties of carbon chemistry biogeochemistry 7.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how carbon chemistry is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.pH_scale') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Sea water" # "Free" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 7.2. PH Scale Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, describe pH scale. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.constants_if_not_OMIP') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.3. Constants If Not OMIP Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, list carbon chemistry constants. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Tracers Ocean biogeochemistry tracers 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of tracers in ocean biogeochemistry End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.sulfur_cycle_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 8.2. Sulfur Cycle Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sulfur cycle modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nutrients_present') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrogen (N)" # "Phosphorous (P)" # "Silicium (S)" # "Iron (Fe)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.3. Nutrients Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List nutrient species present in ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_species_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrates (NO3)" # "Amonium (NH4)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.4. Nitrous Species If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous species. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_processes_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Dentrification" # "N fixation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.5. Nitrous Processes If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous processes. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_definition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9. Tracers --&gt; Ecosystem Ecosystem properties in ocean biogeochemistry 9.1. Upper Trophic Levels Definition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Definition of upper trophic level (e.g. based on size) ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.2. Upper Trophic Levels Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Define how upper trophic level are treated End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "PFT including size based (specify both below)" # "Size based only (specify below)" # "PFT only (specify below)" # TODO - please enter value(s) Explanation: 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton Phytoplankton properties in ocean biogeochemistry 10.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of phytoplankton End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.pft') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Diatoms" # "Nfixers" # "Calcifiers" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.2. Pft Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton functional types (PFT) (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microphytoplankton" # "Nanophytoplankton" # "Picophytoplankton" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.3. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton size classes (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "Size based (specify below)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11. Tracers --&gt; Ecosystem --&gt; Zooplankton Zooplankton properties in ocean biogeochemistry 11.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of zooplankton End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microzooplankton" # "Mesozooplankton" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.2. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Zooplankton size classes (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.bacteria_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 12. Tracers --&gt; Disolved Organic Matter Disolved organic matter properties in ocean biogeochemistry 12.1. Bacteria Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there bacteria representation ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.lability') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Labile" # "Semi-labile" # "Refractory" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.2. Lability Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe treatment of lability in dissolved organic matter End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Diagnostic" # "Diagnostic (Martin profile)" # "Diagnostic (Balast)" # "Prognostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13. Tracers --&gt; Particules Particulate carbon properties in ocean biogeochemistry 13.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is particulate carbon represented in ocean biogeochemistry? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.types_if_prognostic') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "POC" # "PIC (calcite)" # "PIC (aragonite" # "BSi" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.2. Types If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If prognostic, type(s) of particulate matter taken into account End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "No size spectrum used" # "Full size spectrum" # "Discrete size classes (specify which below)" # TODO - please enter value(s) Explanation: 13.3. Size If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, describe if a particule size spectrum is used to represent distribution of particules in water volume End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_discrete') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 13.4. Size If Discrete Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic and discrete size, describe which size classes are used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.sinking_speed_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Function of particule size" # "Function of particule type (balast)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.5. Sinking Speed If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, method for calculation of sinking speed of particules End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.carbon_isotopes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "C13" # "C14)" # TODO - please enter value(s) Explanation: 14. Tracers --&gt; Dic Alkalinity DIC and alkalinity properties in ocean biogeochemistry 14.1. Carbon Isotopes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which carbon isotopes are modelled (C13, C14)? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.abiotic_carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 14.2. Abiotic Carbon Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is abiotic carbon modelled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.alkalinity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Prognostic" # "Diagnostic)" # TODO - please enter value(s) Explanation: 14.3. Alkalinity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is alkalinity modelled ? End of explanation
5,397
Given the following text description, write Python code to implement the functionality described below step by step Description: In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines the desired fraction of shares in the total portfolio value). One initial attempt was made to train the Q-learner with multiple processes, but it was unsuccessful. Step1: Let's show the symbols data, to see how good the recommender has to be. Step2: Let's run the trained agent, with the test set First a non-learning test Step3: And now a "realistic" test, in which the learner continues to learn from past samples in the test set (it even makes some random moves, though very few). Step4: What are the metrics for "holding the position"? Step5: Conclusion
Python Code: # Basic imports import os import pandas as pd import matplotlib.pyplot as plt import numpy as np import datetime as dt import scipy.optimize as spo import sys from time import time from sklearn.metrics import r2_score, median_absolute_error from multiprocessing import Pool %matplotlib inline %pylab inline pylab.rcParams['figure.figsize'] = (20.0, 10.0) %load_ext autoreload %autoreload 2 sys.path.append('../../') import recommender.simulator as sim from utils.analysis import value_eval from recommender.agent import Agent from functools import partial NUM_THREADS = 1 LOOKBACK = 252*2 + 28 STARTING_DAYS_AHEAD = 20 POSSIBLE_FRACTIONS = [0.0, 1.0] # Get the data SYMBOL = 'SPY' total_data_train_df = pd.read_pickle('../../data/data_train_val_df.pkl').stack(level='feature') data_train_df = total_data_train_df[SYMBOL].unstack() total_data_test_df = pd.read_pickle('../../data/data_test_df.pkl').stack(level='feature') data_test_df = total_data_test_df[SYMBOL].unstack() if LOOKBACK == -1: total_data_in_df = total_data_train_df data_in_df = data_train_df else: data_in_df = data_train_df.iloc[-LOOKBACK:] total_data_in_df = total_data_train_df.loc[data_in_df.index[0]:] # Create many agents index = np.arange(NUM_THREADS).tolist() env, num_states, num_actions = sim.initialize_env(total_data_in_df, SYMBOL, starting_days_ahead=STARTING_DAYS_AHEAD, possible_fractions=POSSIBLE_FRACTIONS) agents = [Agent(num_states=num_states, num_actions=num_actions, random_actions_rate=0.98, random_actions_decrease=0.999, dyna_iterations=0, name='Agent_{}'.format(i)) for i in index] def show_results(results_list, data_in_df, graph=False): for values in results_list: total_value = values.sum(axis=1) print('Sharpe ratio: {}\nCum. Ret.: {}\nAVG_DRET: {}\nSTD_DRET: {}\nFinal value: {}'.format(*value_eval(pd.DataFrame(total_value)))) print('-'*100) initial_date = total_value.index[0] compare_results = data_in_df.loc[initial_date:, 'Close'].copy() compare_results.name = SYMBOL compare_results_df = pd.DataFrame(compare_results) compare_results_df['portfolio'] = total_value std_comp_df = compare_results_df / compare_results_df.iloc[0] if graph: plt.figure() std_comp_df.plot() Explanation: In this notebook a simple Q learner will be trained and evaluated. The Q learner recommends when to buy or sell shares of one particular stock, and in which quantity (in fact it determines the desired fraction of shares in the total portfolio value). One initial attempt was made to train the Q-learner with multiple processes, but it was unsuccessful. End of explanation print('Sharpe ratio: {}\nCum. Ret.: {}\nAVG_DRET: {}\nSTD_DRET: {}\nFinal value: {}'.format(*value_eval(pd.DataFrame(data_in_df['Close'].iloc[STARTING_DAYS_AHEAD:])))) # Simulate (with new envs, each time) n_epochs = 4 for i in range(n_epochs): tic = time() env.reset(STARTING_DAYS_AHEAD) results_list = sim.simulate_period(total_data_in_df, SYMBOL, agents[0], starting_days_ahead=STARTING_DAYS_AHEAD, possible_fractions=POSSIBLE_FRACTIONS, verbose=False, other_env=env) toc = time() print('Epoch: {}'.format(i)) print('Elapsed time: {} seconds.'.format((toc-tic))) print('Random Actions Rate: {}'.format(agents[0].random_actions_rate)) show_results([results_list], data_in_df) env.reset(STARTING_DAYS_AHEAD) results_list = sim.simulate_period(total_data_in_df, SYMBOL, agents[0], learn=False, starting_days_ahead=STARTING_DAYS_AHEAD, possible_fractions=POSSIBLE_FRACTIONS, other_env=env) show_results([results_list], data_in_df, graph=True) Explanation: Let's show the symbols data, to see how good the recommender has to be. End of explanation TEST_DAYS_AHEAD = 20 env.set_test_data(total_data_test_df, TEST_DAYS_AHEAD) tic = time() results_list = sim.simulate_period(total_data_test_df, SYMBOL, agents[0], learn=False, starting_days_ahead=TEST_DAYS_AHEAD, possible_fractions=POSSIBLE_FRACTIONS, verbose=False, other_env=env) toc = time() print('Epoch: {}'.format(i)) print('Elapsed time: {} seconds.'.format((toc-tic))) print('Random Actions Rate: {}'.format(agents[0].random_actions_rate)) show_results([results_list], data_test_df, graph=True) Explanation: Let's run the trained agent, with the test set First a non-learning test: this scenario would be worse than what is possible (in fact, the q-learner can learn from past samples in the test set without compromising the causality). End of explanation env.set_test_data(total_data_test_df, TEST_DAYS_AHEAD) tic = time() results_list = sim.simulate_period(total_data_test_df, SYMBOL, agents[0], learn=True, starting_days_ahead=TEST_DAYS_AHEAD, possible_fractions=POSSIBLE_FRACTIONS, verbose=False, other_env=env) toc = time() print('Epoch: {}'.format(i)) print('Elapsed time: {} seconds.'.format((toc-tic))) print('Random Actions Rate: {}'.format(agents[0].random_actions_rate)) show_results([results_list], data_test_df, graph=True) Explanation: And now a "realistic" test, in which the learner continues to learn from past samples in the test set (it even makes some random moves, though very few). End of explanation print('Sharpe ratio: {}\nCum. Ret.: {}\nAVG_DRET: {}\nSTD_DRET: {}\nFinal value: {}'.format(*value_eval(pd.DataFrame(data_test_df['Close'].iloc[TEST_DAYS_AHEAD:])))) Explanation: What are the metrics for "holding the position"? End of explanation import pickle with open('../../data/simple_q_learner_fast_learner.pkl', 'wb') as best_agent: pickle.dump(agents[0], best_agent) Explanation: Conclusion: Sharpe ratio is clearly better than the benchmark. Cumulative return is similar (a bit better with the non-learner, a bit worse with the learner) End of explanation
5,398
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href="https Step1: റെൻസോർഫ്ളോ വിളിക്കുന്നു tf എന്നു പേരിടുന്നു Step2: ഡേറ്റയെ വിളിക്കുന്നു.... ചിത്രങ്ങൾ ...കൈയ്യെഴുത്ത് അക്കങ്ങളുടെ മെനിസ്റ്റ് ഡാറ്റാബേസ്, 60,000 ഉദാഹരണങ്ങൾ, ഒപ്പം 10,000 സാമ്പിളുകൾ Step3: ഡേറ്റയെ തയ്യാറാകുക
Python Code: print ("Gods name is Jehova") Explanation: <a href="https://colab.research.google.com/github/Graphitenet/Fun-CSS-Java-Clock/blob/master/%E0%B4%B1%E0%B5%86%E0%B5%BB%E0%B4%B8%E0%B5%8B%E0%B5%BC%E0%B4%AB%E0%B5%8D%E0%B4%B3%E0%B5%8B_.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> End of explanation import tensorflow as tf Explanation: റെൻസോർഫ്ളോ വിളിക്കുന്നു tf എന്നു പേരിടുന്നു End of explanation mnist = tf.keras.datasets.mnist Explanation: ഡേറ്റയെ വിളിക്കുന്നു.... ചിത്രങ്ങൾ ...കൈയ്യെഴുത്ത് അക്കങ്ങളുടെ മെനിസ്റ്റ് ഡാറ്റാബേസ്, 60,000 ഉദാഹരണങ്ങൾ, ഒപ്പം 10,000 സാമ്പിളുകൾ End of explanation (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(512, activation=tf.nn.relu), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation=tf.nn.softmax) ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) Explanation: ഡേറ്റയെ തയ്യാറാകുക End of explanation
5,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: 15. 다중 회귀 분석 Step3: 14장의 내용을 추가 데이터를 사용해 모델의 성능을 높이기 위해, 더 많은 독립 변수를 사용하는 선형 모델을 시험 14장에서 다뤘던 모델 $y_i=\alpha+\beta x_i+\epsilon_i$ 여기에 독립 변수를 추가하면 $\Rightarrow$시간(분)= $\alpha+\beta_1$(친구 수)$+\beta_2$(근무 시간)$+\beta_3$*(박사 학위 취득 여부)+$\epsilon$ 15.1 모델 각 입력값 $x_i$가 숫자 하나가 아니라 $k$개의 숫자인 $x_i1,\cdot\cdot\cdot,x_ik$라고 한다면, 다중 회귀 모델은 다음과 같은 형태를 띈다. $y_i=\alpha+\beta_1 x_{i1}+\cdot\cdot\cdot+\beta_k x_{ik}+\epsilon_i$ 다중 회귀 분석에서는 보통 파라미터 벡터를 $\beta$라고 부름 여기에 상수항 $\alpha$까지 덧붙이려면, 각 데이터 x_i의 앞부분에 1을 덧붙이면 된다. beta = [alpha, beta_1,$\cdot\cdot\cdot$, x_ik] 그리고 각 데이터는 다음과 같이 된다. x_i = [1, x_i1, $\cdot\cdot\cdot$, x_ik] 이렇게 하면 모델을 다음과 같이 나타낼 수 있다. Step4: 독립 변수 x는 다음과 같은 벡터들의 열로 표현할 수 있다. [1, # 상수항 49, # 친구의 수 4, # 하루 근무 시간 0] # 박사 학위 취득 여부 15.2 최소자승법에 대한 몇 가지 추가 가정 $x$의 열은 서로 일차독립 해야 한다. 이 가정이 성립하지 않는다면 $\beta$를 추정할 수 없다. $x$의 모든 열은 오류 $\epsilon$과 상관관계가 없어야한다. 이 가정이 위배되면 잘못된 $\beta$가 추정될 것이다. 독립 변수와 오류 사이에 상관관계가 존재한다면, 최소자승법으로 만들어지는 모델은 편향된 $\beta$를 추정해 준다. 15.3 모델 학습하기 오류 함수 Step5: SGD를 사용하기 위한 오류 제곱 값 Step7: 만약 미적분을 알고 있다면, 오류를 직접 계산할 수도 있다. Step8: SGD를 사용해서 최적의 베타를 계산 Step9: 실험 데이터 셋팅 (14장과 동일) Step10: 15.4 모델 해석하기 모델의 계수는 해당 항목의 영향력을 나타낸다. 친구 수 증가 =&gt; 대략 1분 증가 근무 시간 증가 =&gt; 대략 2분 감소 박사 학위 취득 =&gt; 대략 1분 증가 이러한 해석은 변수간의 관계를 직접적으로 설명해 주지 못한다. 예를 들어, 친구의 수가 다른 사용자들의 근무 시간은 서로 다를 수 있다. 이 모델은 이러한 관계를 잡아내지 못한다. 이러한 문제는 친구 수와 근무 시간을 곱한 새로운 변수로 해결할 수 있다. 변수가 점점 추가되기 시작하면, 각 계수가 유의미한지 살펴봐야 한다. 변수끼리 곱한 값, 변수의 log값, 변수의 제곱 값 등 수 많은 변수를 추가할 수 있기 때문이다. 15.5 적합성(Goodness of fit) 모델의 R 제곱 값을 다시 계산해 보자. 14장에서의 결과 alpha 22.94755241346903 beta 0.903865945605865 r-squared 0.3291078377836305 Step13: 회귀 분석 모델에 새로운 변수를 추가하면 R 제곱 값이 어쩔 수 없이 증가한다. 따라서 다중 회귀 분석 모델은 언제나 단순 회귀 분석 모델보다 작은 오류를 갖게 된다. 이러한 이유로 다중 회귀 분석 모델에서는 각 계수의 표준 오차를 살펴 봐야 한다. 계수의 표준 오차는 추정된 $\beta_1$의 계수가 얼마나 확실한지 알려준다. 표준오차 Step14: 예를 들어, 다음과 같은 두 가지 데이터를 살펴보자. Step15: 만약 두 데이터의 중앙값을 계산해 보면 둘 다 대략 100에 가까운 것을 확인할 수 있다. Step16: 하지만 다음과 같이 bootstrap을 적용해 보면, close_to_100은 100에 대부분 가깝지만, far_from_100은 0 또는 200에 가까운 것을 확인할 수 있다. Step17: 첫번째는 표준편차가 0에 가깝지만, 두번째는 표준편차가 100에 가까운 것을 확인할 수 있다. Step18: 데이터가 이렇게 극단적인 경우에는 데이터를 직접 살펴보면 문제를 쉽게 파악할 수 있지만, 대부분의 경우 데이터만 살펴보는 것으로는 부족하다. 15.7 계수의 표준 오차 계수의 표준 오차를 추정할 때도 bootstrap을 적용할 수 있다. bootstrap을 할 때에는, 하나의 데이터에 속하는 x와 y를 (x_i, y_i) 형태로 묶어줘야 하고, 반환된 데이터를 다시 x_sample, y_sample로 나눠줘야 한다. Step19: 그리고 각 계수의 표준 오차를 추정할 수 있다. Step20: 이제 '과연 $\beta_1$는 0일까?' 같은 가설을 검증해 볼 수 있다. p-value(유의 확률)은 귀무가설이 맞을 경우 대립가설 쪽의 값이 나올 확률을 나타내는 값. 확률 값이라고도 한다. 표본 평균이 귀무가설 값에서 멀수록 작아지게 된다. Step22: 대부분의 계수들은 0이 아닌 것으로 검증되었으나, 박사 학위 취득 여부에 대한 계수에 의미가 없을 수 있다는 것을 암시 15.8 Regularization 변수가 많아질수록 오버피팅 0이 아닌 계수가 많을수록 모델 해석이 어려움 Regularization은 beta가 커지면 커질수록 해당 모델에게 패널티를 주는 방법이다. 예를 들어, ridge regression의 경우, beta_i를 제곱한 값의 합에 비례하는 패널티를 추가한다. 하지만 상수에 대한 패널티는 주지 않는다. Step26: 그리고 이전과 동일하게 경사 하강법을 적용할 수 있다. Step27: 만약 alpha가 0이라면 패널티는 전혀 없으며, 이전과 동일한 모델이 학습될 것이다. Step28: 그리고 alpha를 증가시킬수록 적합성은 감소하고, beta의 크기도 감소한다. Step29: 패널티가 증가하면 박사 학위 취득 여부 변수는 사라진다. 다른 형태의 패널티를 사용하는 lasso regression도 있다.
Python Code: from __future__ import division from collections import Counter from functools import partial from linear_algebra import dot, vector_add from stats import median, standard_deviation, de_mean from probability import normal_cdf from gradient_descent import minimize_stochastic #from simple_linear_regression import total_sum_of_squares import math, random def total_sum_of_squares(y): the total squared variation of y_i's from their mean return sum(v ** 2 for v in de_mean(y)) Explanation: 15. 다중 회귀 분석 End of explanation def predict(x_i, beta): 각 x_i의 첫 번째 항목은 1이라고 가정 return dot(x_i, beta) Explanation: 14장의 내용을 추가 데이터를 사용해 모델의 성능을 높이기 위해, 더 많은 독립 변수를 사용하는 선형 모델을 시험 14장에서 다뤘던 모델 $y_i=\alpha+\beta x_i+\epsilon_i$ 여기에 독립 변수를 추가하면 $\Rightarrow$시간(분)= $\alpha+\beta_1$(친구 수)$+\beta_2$(근무 시간)$+\beta_3$*(박사 학위 취득 여부)+$\epsilon$ 15.1 모델 각 입력값 $x_i$가 숫자 하나가 아니라 $k$개의 숫자인 $x_i1,\cdot\cdot\cdot,x_ik$라고 한다면, 다중 회귀 모델은 다음과 같은 형태를 띈다. $y_i=\alpha+\beta_1 x_{i1}+\cdot\cdot\cdot+\beta_k x_{ik}+\epsilon_i$ 다중 회귀 분석에서는 보통 파라미터 벡터를 $\beta$라고 부름 여기에 상수항 $\alpha$까지 덧붙이려면, 각 데이터 x_i의 앞부분에 1을 덧붙이면 된다. beta = [alpha, beta_1,$\cdot\cdot\cdot$, x_ik] 그리고 각 데이터는 다음과 같이 된다. x_i = [1, x_i1, $\cdot\cdot\cdot$, x_ik] 이렇게 하면 모델을 다음과 같이 나타낼 수 있다. End of explanation def error(x_i, y_i, beta): return y_i - predict(x_i, beta) Explanation: 독립 변수 x는 다음과 같은 벡터들의 열로 표현할 수 있다. [1, # 상수항 49, # 친구의 수 4, # 하루 근무 시간 0] # 박사 학위 취득 여부 15.2 최소자승법에 대한 몇 가지 추가 가정 $x$의 열은 서로 일차독립 해야 한다. 이 가정이 성립하지 않는다면 $\beta$를 추정할 수 없다. $x$의 모든 열은 오류 $\epsilon$과 상관관계가 없어야한다. 이 가정이 위배되면 잘못된 $\beta$가 추정될 것이다. 독립 변수와 오류 사이에 상관관계가 존재한다면, 최소자승법으로 만들어지는 모델은 편향된 $\beta$를 추정해 준다. 15.3 모델 학습하기 오류 함수 End of explanation def squared_error(x_i, y_i, beta): return error(x_i, y_i, beta) ** 2 Explanation: SGD를 사용하기 위한 오류 제곱 값 End of explanation def squared_error_gradient(x_i, y_i, beta): i번째 오류 제곱 값의 beta에 대한 기울기 return [-2 * x_ij * error(x_i, y_i, beta) for x_ij in x_i] Explanation: 만약 미적분을 알고 있다면, 오류를 직접 계산할 수도 있다. End of explanation def estimate_beta(x, y): beta_initial = [random.random() for x_i in x[0]] return minimize_stochastic(squared_error, squared_error_gradient, x, y, beta_initial, 0.001) Explanation: SGD를 사용해서 최적의 베타를 계산 End of explanation x = [[1,49,4,0],[1,41,9,0],[1,40,8,0],[1,25,6,0],[1,21,1,0],[1,21,0,0],[1,19,3,0],[1,19,0,0],[1,18,9,0],[1,18,8,0],[1,16,4,0],[1,15,3,0],[1,15,0,0],[1,15,2,0],[1,15,7,0],[1,14,0,0],[1,14,1,0],[1,13,1,0],[1,13,7,0],[1,13,4,0],[1,13,2,0],[1,12,5,0],[1,12,0,0],[1,11,9,0],[1,10,9,0],[1,10,1,0],[1,10,1,0],[1,10,7,0],[1,10,9,0],[1,10,1,0],[1,10,6,0],[1,10,6,0],[1,10,8,0],[1,10,10,0],[1,10,6,0],[1,10,0,0],[1,10,5,0],[1,10,3,0],[1,10,4,0],[1,9,9,0],[1,9,9,0],[1,9,0,0],[1,9,0,0],[1,9,6,0],[1,9,10,0],[1,9,8,0],[1,9,5,0],[1,9,2,0],[1,9,9,0],[1,9,10,0],[1,9,7,0],[1,9,2,0],[1,9,0,0],[1,9,4,0],[1,9,6,0],[1,9,4,0],[1,9,7,0],[1,8,3,0],[1,8,2,0],[1,8,4,0],[1,8,9,0],[1,8,2,0],[1,8,3,0],[1,8,5,0],[1,8,8,0],[1,8,0,0],[1,8,9,0],[1,8,10,0],[1,8,5,0],[1,8,5,0],[1,7,5,0],[1,7,5,0],[1,7,0,0],[1,7,2,0],[1,7,8,0],[1,7,10,0],[1,7,5,0],[1,7,3,0],[1,7,3,0],[1,7,6,0],[1,7,7,0],[1,7,7,0],[1,7,9,0],[1,7,3,0],[1,7,8,0],[1,6,4,0],[1,6,6,0],[1,6,4,0],[1,6,9,0],[1,6,0,0],[1,6,1,0],[1,6,4,0],[1,6,1,0],[1,6,0,0],[1,6,7,0],[1,6,0,0],[1,6,8,0],[1,6,4,0],[1,6,2,1],[1,6,1,1],[1,6,3,1],[1,6,6,1],[1,6,4,1],[1,6,4,1],[1,6,1,1],[1,6,3,1],[1,6,4,1],[1,5,1,1],[1,5,9,1],[1,5,4,1],[1,5,6,1],[1,5,4,1],[1,5,4,1],[1,5,10,1],[1,5,5,1],[1,5,2,1],[1,5,4,1],[1,5,4,1],[1,5,9,1],[1,5,3,1],[1,5,10,1],[1,5,2,1],[1,5,2,1],[1,5,9,1],[1,4,8,1],[1,4,6,1],[1,4,0,1],[1,4,10,1],[1,4,5,1],[1,4,10,1],[1,4,9,1],[1,4,1,1],[1,4,4,1],[1,4,4,1],[1,4,0,1],[1,4,3,1],[1,4,1,1],[1,4,3,1],[1,4,2,1],[1,4,4,1],[1,4,4,1],[1,4,8,1],[1,4,2,1],[1,4,4,1],[1,3,2,1],[1,3,6,1],[1,3,4,1],[1,3,7,1],[1,3,4,1],[1,3,1,1],[1,3,10,1],[1,3,3,1],[1,3,4,1],[1,3,7,1],[1,3,5,1],[1,3,6,1],[1,3,1,1],[1,3,6,1],[1,3,10,1],[1,3,2,1],[1,3,4,1],[1,3,2,1],[1,3,1,1],[1,3,5,1],[1,2,4,1],[1,2,2,1],[1,2,8,1],[1,2,3,1],[1,2,1,1],[1,2,9,1],[1,2,10,1],[1,2,9,1],[1,2,4,1],[1,2,5,1],[1,2,0,1],[1,2,9,1],[1,2,9,1],[1,2,0,1],[1,2,1,1],[1,2,1,1],[1,2,4,1],[1,1,0,1],[1,1,2,1],[1,1,2,1],[1,1,5,1],[1,1,3,1],[1,1,10,1],[1,1,6,1],[1,1,0,1],[1,1,8,1],[1,1,6,1],[1,1,4,1],[1,1,9,1],[1,1,9,1],[1,1,4,1],[1,1,2,1],[1,1,9,1],[1,1,0,1],[1,1,8,1],[1,1,6,1],[1,1,1,1],[1,1,1,1],[1,1,5,1]] num_friends_good = [49,41,40,25,21,21,19,19,18,18,16,15,15,15,15,14,14,13,13,13,13,12,12,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] daily_minutes_good = [68.77,51.25,52.08,38.36,44.54,57.13,51.4,41.42,31.22,34.76,54.01,38.79,47.59,49.1,27.66,41.03,36.73,48.65,28.12,46.62,35.57,32.98,35,26.07,23.77,39.73,40.57,31.65,31.21,36.32,20.45,21.93,26.02,27.34,23.49,46.94,30.5,33.8,24.23,21.4,27.94,32.24,40.57,25.07,19.42,22.39,18.42,46.96,23.72,26.41,26.97,36.76,40.32,35.02,29.47,30.2,31,38.11,38.18,36.31,21.03,30.86,36.07,28.66,29.08,37.28,15.28,24.17,22.31,30.17,25.53,19.85,35.37,44.6,17.23,13.47,26.33,35.02,32.09,24.81,19.33,28.77,24.26,31.98,25.73,24.86,16.28,34.51,15.23,39.72,40.8,26.06,35.76,34.76,16.13,44.04,18.03,19.65,32.62,35.59,39.43,14.18,35.24,40.13,41.82,35.45,36.07,43.67,24.61,20.9,21.9,18.79,27.61,27.21,26.61,29.77,20.59,27.53,13.82,33.2,25,33.1,36.65,18.63,14.87,22.2,36.81,25.53,24.62,26.25,18.21,28.08,19.42,29.79,32.8,35.99,28.32,27.79,35.88,29.06,36.28,14.1,36.63,37.49,26.9,18.58,38.48,24.48,18.95,33.55,14.24,29.04,32.51,25.63,22.22,19,32.73,15.16,13.9,27.2,32.01,29.27,33,13.74,20.42,27.32,18.23,35.35,28.48,9.08,24.62,20.12,35.26,19.92,31.02,16.49,12.16,30.7,31.22,34.65,13.13,27.51,33.2,31.57,14.1,33.42,17.44,10.12,24.42,9.82,23.39,30.93,15.03,21.67,31.09,33.29,22.61,26.89,23.48,8.38,27.81,32.35,23.84] random.seed(0) beta = estimate_beta(x, daily_minutes_good) beta # 분 = 30.63 + 0.972 친구 수 - 1.868 근무 시간 + 0.911 박사 학위 취득 여부 Explanation: 실험 데이터 셋팅 (14장과 동일) End of explanation def multiple_r_squared(x, y, beta): sum_of_squared_errors = sum(error(x_i, y_i, beta) ** 2 for x_i, y_i in zip(x, y)) return 1.0 - sum_of_squared_errors / total_sum_of_squares(y) multiple_r_squared(x, daily_minutes_good, beta) Explanation: 15.4 모델 해석하기 모델의 계수는 해당 항목의 영향력을 나타낸다. 친구 수 증가 =&gt; 대략 1분 증가 근무 시간 증가 =&gt; 대략 2분 감소 박사 학위 취득 =&gt; 대략 1분 증가 이러한 해석은 변수간의 관계를 직접적으로 설명해 주지 못한다. 예를 들어, 친구의 수가 다른 사용자들의 근무 시간은 서로 다를 수 있다. 이 모델은 이러한 관계를 잡아내지 못한다. 이러한 문제는 친구 수와 근무 시간을 곱한 새로운 변수로 해결할 수 있다. 변수가 점점 추가되기 시작하면, 각 계수가 유의미한지 살펴봐야 한다. 변수끼리 곱한 값, 변수의 log값, 변수의 제곱 값 등 수 많은 변수를 추가할 수 있기 때문이다. 15.5 적합성(Goodness of fit) 모델의 R 제곱 값을 다시 계산해 보자. 14장에서의 결과 alpha 22.94755241346903 beta 0.903865945605865 r-squared 0.3291078377836305 End of explanation def bootstrap_sample(data): len(data)개의 항목을 중복을 허용한 무작위 추출 return [random.choice(data) for _ in data] def bootstrap_statistic(data, stats_fn, num_samples): num_samples개의 bootstrap 샘플에 대해 stats_fn을 적용 return [stats_fn(bootstrap_sample(data)) for _ in range(num_samples)] Explanation: 회귀 분석 모델에 새로운 변수를 추가하면 R 제곱 값이 어쩔 수 없이 증가한다. 따라서 다중 회귀 분석 모델은 언제나 단순 회귀 분석 모델보다 작은 오류를 갖게 된다. 이러한 이유로 다중 회귀 분석 모델에서는 각 계수의 표준 오차를 살펴 봐야 한다. 계수의 표준 오차는 추정된 $\beta_1$의 계수가 얼마나 확실한지 알려준다. 표준오차 : 모집단 전체를 알 수 없는 상황에서, 모집단이 정상분포(정규분포)를 이루고 있다는 가정 하에, 여러번의 샘플링을 통해 각 표본 집단의 평균들로 이루어진 표준 평균 분포를 얻고, 이 표준 평균 분포의 표준 편차가 표준 오차가 된다. 표준오차는 모평균과 표본평균 사이의 오차를 알려주므로, 모집단의 표준편차가 클수록 표준오차도 커지고, 사례가 많을 수록 작아진다. 오차를 측정하기 위해서는 각 오류 $\epsilon_1$는 독립이며, 평균은 0이고 표준편차는 $\sigma$인 정규분포의 확률변수라는 가정이 필요하다. 표준오차가 클수록 해당 계수는 무의미해 진다. 15.6 여담: bootstrap 알 수 없는 분포에서 생성된 표본 데이터가 주어졌을 때, 이 표본 데이터의 중앙값을 찾으려면? 만약 표본 데이터가 모두 100 근처에 위치하고 있다면, 중앙값 또한 100 근처에 위치할 것이지만, 표본 데이터의 반은 0, 나머지 반은 200 근처에 위치하고 있다면, 추정된 중앙값을 신뢰하기 힘들다. bootstrap은 중복이 허용된 재추출을 통해 새로운 데이터의 각 항목을 생성한다. 이를 통해 만들어진 데이터로 중앙값을 계산해 볼 수 있다. End of explanation # 101개의 데이터가 모두 100에 인접 close_to_100 = [99.5 + random.random() for _ in range(101)] # 101개의 데이터 중 50개는 0에 인접, 50개는 200에 인접 far_from_100 = ([99.5 + random.random()] + [random.random() for _ in range(50)] + [200 + random.random() for _ in range(50)]) print(close_to_100) print(far_from_100) Explanation: 예를 들어, 다음과 같은 두 가지 데이터를 살펴보자. End of explanation print(median(close_to_100)) print(median(far_from_100)) Explanation: 만약 두 데이터의 중앙값을 계산해 보면 둘 다 대략 100에 가까운 것을 확인할 수 있다. End of explanation print(bootstrap_statistic(close_to_100, median, 100)) print(bootstrap_statistic(far_from_100, median, 100)) Explanation: 하지만 다음과 같이 bootstrap을 적용해 보면, close_to_100은 100에 대부분 가깝지만, far_from_100은 0 또는 200에 가까운 것을 확인할 수 있다. End of explanation standard_deviation(bootstrap_statistic(close_to_100, median, 100)) standard_deviation(bootstrap_statistic(far_from_100, median, 100)) Explanation: 첫번째는 표준편차가 0에 가깝지만, 두번째는 표준편차가 100에 가까운 것을 확인할 수 있다. End of explanation def estimate_sample_beta(sample): x_sample, y_sample = zip(*sample) # magic unzipping trick return estimate_beta(x_sample, y_sample) random.seed(0) # 예시와 동일한 결과를 얻기 위해 설정 bootstrap_betas = bootstrap_statistic(list(zip(x, daily_minutes_good)), estimate_sample_beta, 100) bootstrap_betas Explanation: 데이터가 이렇게 극단적인 경우에는 데이터를 직접 살펴보면 문제를 쉽게 파악할 수 있지만, 대부분의 경우 데이터만 살펴보는 것으로는 부족하다. 15.7 계수의 표준 오차 계수의 표준 오차를 추정할 때도 bootstrap을 적용할 수 있다. bootstrap을 할 때에는, 하나의 데이터에 속하는 x와 y를 (x_i, y_i) 형태로 묶어줘야 하고, 반환된 데이터를 다시 x_sample, y_sample로 나눠줘야 한다. End of explanation bootstrap_standard_errors = [ standard_deviation([beta[i] for beta in bootstrap_betas]) for i in range(4) ] bootstrap_standard_errors Explanation: 그리고 각 계수의 표준 오차를 추정할 수 있다. End of explanation def p_value(beta_hat_j, sigma_hat_j): if beta_hat_j > 0: return 2 * (1 - normal_cdf(beta_hat_j / sigma_hat_j)) else: return 2 * normal_cdf(beta_hat_j / sigma_hat_j) print(p_value(30.63, 1.174)) print(p_value(0.972, 0.079)) print(p_value(-1.868, 0.131)) print(p_value(0.911, 0.990)) Explanation: 이제 '과연 $\beta_1$는 0일까?' 같은 가설을 검증해 볼 수 있다. p-value(유의 확률)은 귀무가설이 맞을 경우 대립가설 쪽의 값이 나올 확률을 나타내는 값. 확률 값이라고도 한다. 표본 평균이 귀무가설 값에서 멀수록 작아지게 된다. End of explanation # alpha는 패널티의 강도를 조절하는 하이퍼 파라미터 # 보통 "lamda"라고 표현하지만 파이썬에서는 이미 사용 중인 키워드이다. def ridge_penalty(beta, alpha): return alpha * dot(beta[1:], beta[1:]) def squared_error_ridge(x_i, y_i, beta, alpha): beta를 사용할 때 오류와 패널티의 합을 추정 return error(x_i, y_i, beta) ** 2 + ridge_penalty(beta, alpha) Explanation: 대부분의 계수들은 0이 아닌 것으로 검증되었으나, 박사 학위 취득 여부에 대한 계수에 의미가 없을 수 있다는 것을 암시 15.8 Regularization 변수가 많아질수록 오버피팅 0이 아닌 계수가 많을수록 모델 해석이 어려움 Regularization은 beta가 커지면 커질수록 해당 모델에게 패널티를 주는 방법이다. 예를 들어, ridge regression의 경우, beta_i를 제곱한 값의 합에 비례하는 패널티를 추가한다. 하지만 상수에 대한 패널티는 주지 않는다. End of explanation def ridge_penalty_gradient(beta, alpha): 패널티의 기울기 return [0] + [2 * alpha * beta_j for beta_j in beta[1:]] def squared_error_ridge_gradient(x_i, y_i, beta, alpha): i번 오류 제곱 값과 패널티의 기울기 return vector_add(squared_error_gradient(x_i, y_i, beta), ridge_penalty_gradient(beta, alpha)) def estimate_beta_ridge(x, y, alpha): 패널티가 alpha인 리지 회귀를 경사 하강법으로 학습 beta_initial = [random.random() for x_i in x[0]] return minimize_stochastic(partial(squared_error_ridge, alpha=alpha), partial(squared_error_ridge_gradient, alpha=alpha), x, y, beta_initial, 0.001) Explanation: 그리고 이전과 동일하게 경사 하강법을 적용할 수 있다. End of explanation random.seed(0) beta_0 = estimate_beta_ridge(x, daily_minutes_good, alpha=0.0) beta_0 dot(beta_0[1:], beta_0[1:]) multiple_r_squared(x, daily_minutes_good, beta_0) Explanation: 만약 alpha가 0이라면 패널티는 전혀 없으며, 이전과 동일한 모델이 학습될 것이다. End of explanation beta_0_01 = estimate_beta_ridge(x, daily_minutes_good, alpha=0.01) print(beta_0_01) print(dot(beta_0_01[1:], beta_0_01[1:])) print(multiple_r_squared(x, daily_minutes_good, beta_0_01)) beta_0_1 = estimate_beta_ridge(x, daily_minutes_good, alpha=0.1) print(beta_0_1) print(dot(beta_0_1[1:], beta_0_1[1:])) print(multiple_r_squared(x, daily_minutes_good, beta_0_1)) beta_1 = estimate_beta_ridge(x, daily_minutes_good, alpha=1) print(beta_1) print(dot(beta_1[1:], beta_1[1:])) print(multiple_r_squared(x, daily_minutes_good, beta_1)) beta_10 = estimate_beta_ridge(x, daily_minutes_good, alpha=10) print(beta_10) print(dot(beta_10[1:], beta_10[1:])) multiple_r_squared(x, daily_minutes_good, beta_10) Explanation: 그리고 alpha를 증가시킬수록 적합성은 감소하고, beta의 크기도 감소한다. End of explanation def lasso_penalty(beta, alpha): return alpha * sum(abs(beta_i) for beta_i in beta[1:]) Explanation: 패널티가 증가하면 박사 학위 취득 여부 변수는 사라진다. 다른 형태의 패널티를 사용하는 lasso regression도 있다. End of explanation