repo_name
stringlengths
6
77
path
stringlengths
8
215
license
stringclasses
15 values
content
stringlengths
335
154k
turnerbw/JNBinder
Periodic_Trends.ipynb
mit
# Import modules that contain functions we need import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt """ Explanation: Periodic Trends Charting the Patterns of Elements This data was modified from a data set that came from Data-Scientists Matthew Renze. Thanks to UCF undergraduates Sam Borges, for finding the data set, and Lissa Galguera, for formatting it. End of explanation """ # This code imports the image of the periodic table from the URL below #uncomment the image(url=... for the periodic table you would like to see. Be sure only one is uncommented at a time. from IPython.display import Image from IPython.core.display import HTML # The periodic table of elements with symbols, atomic numbers, and atomic masses Image(url= 'http://www.chem.qmul.ac.uk/iupac/AtWt/table.gif') # The periodic table of elements color-coded by type of element (metals, nonmetals, and metalloids) #Image(url= 'https://fthmb.tqn.com/I1J8fd6q-skC40aXr7LkJJN9Bew=/1500x1000/filters:fill(auto,1)/about/periodic-table-58ea5e0a5f9b58ef7ed0a788.jpg') # The periodic table of the elements with elemental families identified #Image(url= 'http://images.tutorcircle.com/cms/images/44/periodic-table11.PNG') """ Explanation: Pre-Questions Using the coding block below and what you've learned in this unit, answer questions 1-3. End of explanation """ # Read in data that will be used for the calculations. # The data needs to be in the same directory(folder) as the program # Using pandas read_csv method, we can create a data frame #data = pd.read_csv("./data/elements.csv") # If you're not using a Binder link, you can get the data with this instead: data = pd.read_csv("https://gist.githubusercontent.com/GoodmanSciences/c2dd862cd38f21b0ad36b8f96b4bf1ee/raw/1d92663004489a5b6926e944c1b3d9ec5c40900e/Periodic%2520Table%2520of%2520Elements.csv") # displays a preview of the first several rows of the data set data.head(3) # shows you what data you can graph the names of all the columns in the dataset data.columns """ Explanation: Importing the Data into your Jupyter Notebook End of explanation """ ax = data.plot('AtomicNumber', 'AtomicMass', title="Trends Related to Atomic Number", legend=False) ax.set(xlabel="Atomic Number", ylabel="Comparison Factor") """ Explanation: PART 1: Trends Related to Atomic Number End of explanation """ ax = data.plot('AtomicNumber', 'BoilingPoint', title="Looking for Periodicity of Properties", legend=False) ax.set(xlabel="Atomic Number", ylabel="Comparison Factor") """ Explanation: PART 2: The Periodicity of Element Properties End of explanation """ data.Radioactive.count() # Set variables for scatter plot x = data.Group y = data.NumberofValence plt.scatter(x,y) plt.title('Looking For Patterns') plt.xlabel('x-axis') plt.ylabel('y-axis') #this sets the interval on the x-axis plt.xticks(np.arange(min(x), max(x)+1, 1.0)) # This actually shows the plot plt.show() data[['AtomicNumber', 'Element', 'Type']].sort_values(by='AtomicNumber') """ Explanation: PART 3: Unstructured Coding End of explanation """
hetaodie/hetaodie.github.io
assets/media/uda-ml/fjd/ica/独立成分分析/Independent Component Analysis Lab [SOLUTION]-zh.ipynb
mit
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 from sklearn.decomposition import FastICA # TODO: Initialize FastICA with n_components=3 ica = FastICA(n_components=3) # TODO: Run the FastICA algorithm using fit_transform on dataset X ica_result = ica.fit_transform(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 """
flohorovicic/pynoddy
docs/notebooks/Experiment_entropy_analysis_2D_py3_hspace.ipynb
gpl-2.0
from IPython.core.display import HTML css_file = 'pynoddy.css' HTML(open(css_file, "r").read()) %matplotlib inline # here the usual imports. If any of the imports fails, # make sure that pynoddy is installed # properly, ideally with 'python setup.py develop' # or 'python setup.py install' import sys, os import matplotlib.pyplot as plt import numpy as np # adjust some settings for matplotlib from matplotlib import rcParams # print rcParams rcParams['font.size'] = 15 # determine path of repository to set paths corretly below repo_path = os.path.realpath('../..') sys.path.append('../..') import pynoddy import importlib importlib.reload(pynoddy) import pynoddy.history import pynoddy.experiment importlib.reload(pynoddy.experiment) rcParams.update({'font.size': 15}) pynoddy.history.NoddyHistory(history="typeb.his") """ Explanation: Uncertainty analysis of a 2-D slice model Possible paper titles: Posterior analysis of geological models/ geophysical inversions? with information theory ...with measures from information theory ...with information theoretic measures ...with information measures ...with information Ensemble analysis... Posterior and ensemble analysis... (Note: reference to posterior analysis, e.g. in Tarantola paper!) Include: Analysis of pynoddy models: simple example of graben (because the uncertainty reduction is so counter-intuitive), and maybe more complex example of folding structure? Analysis of object modelling results? (i.e. the typical "Stanford channels"? but: only two outcomes, so not so meaningful... better example?) Analysis of posterior ensemble from geophysical inversion (Greenstone model? Other examples from Mark & Mark?) Journal? Math. Geo? Tectonophysics (note: relevance to strucural geological models!) Include theory: error bounds on information measures! End of explanation """ # from pynoddy.experiment import monte_carlo model_url = 'http://tectonique.net/asg/ch3/ch3_7/his/typeb.his' ue = pynoddy.experiment.Experiment(history="typeb.his") ue.change_cube_size(100) sec = ue.get_section('y') tmp = open("typeb.his").readlines() """ Explanation: Model set-up Subsequently, we will use a model from the "Atlas of Structural Geophysics" as an example model. End of explanation """ sec.block.shape ue.plot_section('y') plt.imshow(sec.block[:,50,:].transpose(), origin = 'lower left', interpolation = 'none') tmp = sec.block[:,50,:] tmp.shape ue.set_random_seed(12345) ue.info(events_only = True) """ Explanation: BUG!!!! Note: there is either a bug in pynoddy or in Noddy itself: but the slice plotting method fails: actually, not a slice is computed but the entire model (and the extent is also not correct!). Check with Mark in course of paper prep! End of explanation """ param_stats = [{'event' : 2, 'parameter': 'Amplitude', 'stdev': 100.0, 'type': 'normal'}, {'event' : 2, 'parameter': 'Wavelength', 'stdev': 500.0, 'type': 'normal'}, {'event' : 2, 'parameter': 'X', 'stdev': 500.0, 'type': 'normal'}] ue.set_parameter_statistics(param_stats) """ Explanation: We now define the parameter uncertainties: End of explanation """ ue.set_random_seed(112358) # perfrom random sampling resolution = 100 sec = ue.get_section('y') tmp = sec.block[:,50,:] n_draws = 5000 model_sections = np.empty((n_draws, tmp.shape[0], tmp.shape[1])) for i in range(n_draws): ue.random_draw() tmp_sec = ue.get_section('y', resolution = resolution, remove_tmp_files = True) model_sections[i,:,:] = tmp_sec.block[:,50,:] """ Explanation: And, in a next step, perform the model sampling: End of explanation """ import pickle f_out = open("model_sections_5k2.pkl", 'wb') pickle.dump(model_sections, f_out) f_in = open("model_sections_5k2.pkl", 'rb') model_sections = pickle.load(f_in) """ Explanation: Save the model data for later re-use (e.g. to extend the data set): End of explanation """ sys.path.append('/Users/flow/git/hspace') import hspace.measures importlib.reload(hspace.measures) model_sections.shape """ Explanation: Use hspace to calculate joint entropies Adjusted notebook: use hspace-package to calculate information theoretic measures End of explanation """ hspace.measures.joint_entropy(model_sections[:,50,:], [0,1]) h = np.empty_like(model_sections[0,:,:]) for i in range(100): for j in range(40): h[i,j] = hspace.measures.joint_entropy(model_sections[:,i,j]) h[50,30] """ Explanation: Calculation of cell information entropy (Include note on: theory of entropy calculation) (Include in this paper: estimates on error bounds?) Here now the function to calculate entropy from a data array in general. What we will need to do later is to pass all results at a single position as a "data array" and we can then estimate the information entropy at this position. This function already expects a sorted array as an input and then uses the (ultra-fast) switchpoint method to calculate entropy: The algorithm works on the simple idea that we do not explicitly require the single outputs at each location, but only the relative probability values. This may not matter too much for single entropy estimates (uni-variate), but it will matter a lot for multivariate cases, because we do not need to check all possible outcomes! Note that all outcomes with zero probability are simply not considered in the sorting algorithm (and they do not play any role in the calculation of the entropy, anyway), and that's exactly what we want to have! In this new version, we use the implementation the hspace package: End of explanation """ plt.imshow(h.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') """ Explanation: We now visualise the cell information entropy, shown in Fig. (). We can here clearly identify uncertain regions within this model section. It is interesting to note that we can mostly still identify the distinct layer boundaries in the fuzzy areas of uncertainty around their borders (note: highlight in Figure!). However, additional aspects of uncertainty are now introduced: (a) the uncertainty about the x-position of the folds (see parameters: event 2, parameter x) is now clearly visible, and (b) uncertianties now seem to concentrate on the fold hinges. However, this is not so clear in the left part of the model, where the fold hing seems to be the least uncertain part. (check why: is this where the fold is actually fixed (even though still uncertain). My current interpretation: the fold location is fixed somewhere near this point, and so the wavelength uncertainty does not play a significant role. Furthermore, the fold is quite "open" at this position (i.e.: low angle between hinges) and therefore lateral shifts do not play a significant role. End of explanation """ plt.imshow(model_sections[70,:,:].transpose(), origin = 'lower left', interpolation = 'none') """ Explanation: Here again an example of single models (adjust to visualise and probably include something like a "table plot" of multiple images for a paper!): End of explanation """ plt.imshow(np.mean(model_sections, axis = 0).transpose(), origin = 'lower left', interpolation = 'none') """ Explanation: And here the "mean" lithologies (note: not really a distinct meaning, simply showing the average litho ids - could be somehow interpreted as characteristic functions, though...). End of explanation """ # step 1: estimate probabilities (note: unfortunate workaround with ones multiplication, # there may be a better way, but this is somehow a recurring problem of implicit # array flattening in numpy) litho_id = 4 prob = np.sum(np.ones_like(model_sections) * (model_sections == litho_id), axis = 0) / model_sections.shape[0] plt.imshow(prob.transpose(), origin = 'lower left', interpolation = 'none', cmap = 'gray_r') plt.colorbar(orientation = 'horizontal') """ Explanation: And here a bit more meaningful: the analysis of single layer probabilities: End of explanation """ importlib.reload(hspace.measures) dx = 15 xvals = np.ones(dx, dtype=int) * 20 yvals = np.arange(11,11+dx, dtype=int) pos = np.vstack([xvals, yvals]) hspace.measures.joint_entropy(model_sections, pos.T) # now: define position of "drill": nx = 10 xvals = np.ones(nx, dtype=int) * 60 yvals = np.arange(39,39-nx, -1, dtype=int) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add new position to positions vector: pos_all = np.vstack([pos, np.array([i,j])]) # determine joint entropy h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow(h_cond_drill.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,100]) plt.ylim([0,40]) """ Explanation: Idea: also include a "new" consideration: where to collect information to reduce uncertainty of a single layer? Could be identified by reducing layer fuzziness, for example! Or: what are most likely positions/ locations of a specific unit, given collected information? <div class="alert alert-warning"> <b>More ideas:</b> <ul> <li>General methods to create simple representations in 1-D, 2-D? <li>Automatic probability plots (note: simple in 1-D, but also for slices in 2-D?) => Compare visualisations in previous notebooks! </ul> </div> Analysis of multivariate condtional entropy Later also: "opposite" question, i.e.: if we would like to resolve uncertainty in a specific region: where to look best? "complete" uncertainty (i.e.: joint entropy!) greedy search for best spots for uncertainty reduction, simple (cell-wise), complex (related to potential drilling positions) further ideas for "greedy search" to reduce uncertainties in a specific "search region" (i.e.: expected location of a deposit, etc.): start with cell with highest (multivariate) mutual information rank cells with highest I due to their own mutual information with other cells, which are not part of a defined "search region" for simple, cell-wise: describe similarity to mapping! Maybe even a field example with data from Belgium? But this is still one or two MSc theses away...) For the joint entropy analysis, we now use the new lexicographic (correct term?) sorting algorithm, implemented in the module hspace: End of explanation """ h_max = np.max(h) plt.imshow(h_cond_drill.transpose(), origin = 'lower left', cmap = 'viridis', interpolation = 'none', vmax=h_max) plt.colorbar(orientation = 'horizontal') # half-step contour lines contour_levels = np.log2(np.arange(1., n_max + 0.001, .5)) plt.contour(h_cond_drill.transpose(), contour_levels, colors = 'gray') # superpose 1-step contour lines contour_levels = np.log2(np.arange(1., n_max + 0.001, 1.)) plt.contour(h_cond_drill.transpose(), contour_levels, colors = 'white') plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: Try own "entropy colormap": End of explanation """ plt.imshow(h.transpose(), origin = 'lower left', cmap = 'viridis', interpolation = 'none', vmax=h_max) plt.colorbar(orientation = 'horizontal') # half-step contour lines contour_levels = np.log2(np.arange(1., n_max + 0.001, .5)) plt.contour(h.transpose(), contour_levels, colors = 'gray') # superpose 1-step contour lines contour_levels = np.log2(np.arange(1., n_max + 0.001, 1.)) plt.contour(h.transpose(), contour_levels, colors = 'white') """ Explanation: For comparison again: the entropy of the initial model: End of explanation """ plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'viridis', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: And the difference, for clarity: End of explanation """ # define position of "drill": nx = 10 xvals = np.ones(nx, dtype=int) * 20 yvals = np.arange(39,39-nx, -1, dtype=int) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) """ Explanation: Clearly, the highset reduction is in the area around the borehole, but interestingly, the uncertianty in other areas is also reduced! Note specifically the reduction of uncertainties in the two neighbouring fold hinges. Let's check some other positions (and drilling "depths"): End of explanation """ %%timeit pos_all = np.vstack([pos, np.array([50,20])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # esimated total time: ttime = 100 * 40 * 0.000271 print("Estimated total time: %.3f seconds or %.3f minutes" % (ttime, ttime/60.)) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add position to locations pos_all = np.vstack([pos, np.array([i,j])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: We also just include one timing step to estimate the approximate simualtion time: End of explanation """ # define position of "drill": nx = 30 xvals = np.ones(nx, dtype=int) * 20 yvals = np.arange(39,39-nx, -1, dtype=int) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add position to locations pos_all = np.vstack([pos, np.array([i,j])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) plt.imshow(h.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: Intersting! Only a local reduction around the drilling position, however: extending to the deeper layers, as well! Why? Drill deeper: End of explanation """ # define position of "drill": nx = 30 xvals = np.ones(nx, dtype=int) * 60 yvals = np.arange(39,39-nx, -1, dtype=int) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add position to locations pos_all = np.vstack([pos, np.array([i,j])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow(h_cond_drill.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: Check deep "drilling" at pos 60 End of explanation """ # define position of "drill": nx = 30 xvals = np.hstack([np.ones(nx, dtype=int) * 60, np.ones(nx, dtype=int) * 30]) yvals = np.hstack([np.arange(39,39-nx, -1, dtype=int), np.arange(39,39-nx, -1, dtype=int)]) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) %%timeit h_joint_loc = hspace.measures.joint_entropy(model_sections, pos) # esimated total time: ttime = 100 * 40 * 0.0002 print("Estimated total time: %.3f seconds or %.3f minutes" % (ttime, ttime/60.)) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add position to locations pos_all = np.vstack([pos, np.array([i,j])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow(h_cond_drill.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: Interesting! And now both combined: End of explanation """ # define position of "drill": nx = 30 xvals = np.hstack([np.ones(nx, dtype=int) * 60, np.ones(nx, dtype=int) * 30, np.ones(nx, dtype=int) * 5]) yvals = np.hstack([np.arange(39,39-nx, -1, dtype=int), np.arange(39,39-nx, -1, dtype=int), np.arange(39,39-nx, -1, dtype=int)]) pos = np.vstack([xvals, yvals]).T # determine joint entropy of drill_locs: h_joint_drill = hspace.measures.joint_entropy(model_sections, pos) # generate conditional entropies for entire section: h_cond_drill = np.zeros_like(h) for i in range(100): for j in range(40): # add position to locations pos_all = np.vstack([pos, np.array([i,j])]) h_joint_loc = hspace.measures.joint_entropy(model_sections, pos_all) # subtract joint entropy of drill locs to obtain conditional entropy h_cond_drill[i,j] = h_joint_loc - h_joint_drill plt.imshow(h_cond_drill.transpose(), origin = 'lower left', cmap = 'gray', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) plt.imshow((h - h_cond_drill).transpose(), origin = 'lower left', cmap = 'RdBu', interpolation = 'none') plt.colorbar(orientation = 'horizontal') # plot drilling positions above it: plt.plot(pos[:,0], pos[:,1], 'ws') plt.xlim([0,99]) plt.ylim([0,39]) """ Explanation: We can see that now only a part on the left remains with significant uncertainties. So, let's "drill" into this, as well: End of explanation """
agiovann/Constrained_NMF
demos/notebooks/demo_dendritic.ipynb
gpl-2.0
import cv2 import glob import logging import matplotlib.pyplot as plt import numpy as np import os try: cv2.setNumThreads(0) except(): pass try: if __IPYTHON__: get_ipython().magic('load_ext autoreload') get_ipython().magic('autoreload 2') except NameError: pass import caiman as cm from caiman.motion_correction import MotionCorrect from caiman.source_extraction.cnmf import cnmf as cnmf from caiman.source_extraction.cnmf import params as params from caiman.utils.utils import download_demo from caiman.utils.visualization import nb_view_patches from skimage.util import montage import bokeh.plotting as bpl import holoviews as hv bpl.output_notebook() hv.notebook_extension('bokeh') """ Explanation: Analyzing dendritic data with CaImAn This notebook shows an example on how to analyze two-photon dendritic data with CaImAn. It follows closely the other notebooks. End of explanation """ fnames = [download_demo('data_dendritic.tif')] """ Explanation: Selecting the data We provide an example file from mouse barrel cortex, courtesy of Clay Lacefield and Randy Bruno, Columbia University. The download_demo command will automatically download the file and store it in your caiman_data folder the first time you run it. To use the demo in your own dataset you can set: fnames = [/path/to/file(s)]. End of explanation """ display_movie = False if display_movie: m_orig = cm.load_movie_chain(fnames) ds_ratio = 0.25 m_orig.resize(1, 1, ds_ratio).play( q_max=99.5, fr=30, magnification=4) """ Explanation: Viewing the data Prior to analysis you can view the data by setting display_movie = False. The example file provided here is small, with FOV size 128 x 128. To view it larger we set magnification = 4 in the play command. This will result to a movie of resolution 512 x 512. For larger files, you will want to reduce this magnification factor (for memory and display purposes). End of explanation """ # dataset dependent parameters fr = 30 # imaging rate in frames per second decay_time = 0.5 # motion correction parameters strides = (48, 48) # start a new patch for pw-rigid motion correction every x pixels overlaps = (24, 24) # overlap between pathes (size of patch strides+overlaps) max_shifts = (6, 6) # maximum allowed rigid shifts (in pixels) max_deviation_rigid = 3 # maximum shifts deviation allowed for patch with respect to rigid shifts pw_rigid = True # flag for performing non-rigid motion correction # parameters for source extraction and deconvolution p = 0 # order of the autoregressive system gnb = 2 # number of global background components merge_thr = 0.75 # merging threshold, max correlation allowed rf = None # half-size of the patches in pixels. e.g., if rf=25, patches are 50x50 stride_cnmf = None # amount of overlap between the patches in pixels K = 60 # number of components per patch method_init = 'graph_nmf' # initialization method (if analyzing dendritic data using 'sparse_nmf') ssub = 1 # spatial subsampling during initialization tsub = 1 # temporal subsampling during intialization opts_dict = {'fnames': fnames, 'fr': fr, 'decay_time': decay_time, 'strides': strides, 'overlaps': overlaps, 'max_shifts': max_shifts, 'max_deviation_rigid': max_deviation_rigid, 'pw_rigid': pw_rigid, 'p': p, 'nb': gnb, 'rf': rf, 'K': K, 'stride': stride_cnmf, 'method_init': method_init, 'rolling_sum': True, 'only_init': True, 'ssub': ssub, 'tsub': tsub, 'merge_thr': merge_thr} opts = params.CNMFParams(params_dict=opts_dict) #%% start a cluster for parallel processing (if a cluster already exists it will be closed and a new session will be opened) if 'dview' in locals(): cm.stop_server(dview=dview) c, dview, n_processes = cm.cluster.setup_cluster( backend='local', n_processes=None, single_thread=False) """ Explanation: Parameter setting First we'll perform motion correction followed by CNMF. One of the main differences when analyzing dendritic data, is that dendritic segments are not localized and can traverse significant parts of the FOV. They can also be spatially non-contiguous. To capture this property, CaImAn has two methods for initializing CNMF: sparse_nmf where a sparse non-negative matrix factorization is deployed, and graph-nmf, where the Laplacian of the pixel affinity matrix is used as a regularizer to promote spatial components that capture pixels that have similar timecourses. These can be selected with the parameter method_init. In this demo we use the graph_nmf initialization method although sparse_nmf can also be used. Since the dataset is small we can run CNMF without splitting the FOV in patches. This can be helpful because of the non-localized nature of the dendritic segments. To do that we set rf = None. Using patches is also supported as demonstrated below. Also note, that spatial and temporal downsampling can also be used to reduce the data dimensionality by appropriately modifying the parameters ssub and tsub. Here they are set to 1 since it is not necessary. The graph NMF method was originally presented in the paper: Cai, D., He, X., Han, J., & Huang, T. S. (2010). Graph regularized nonnegative matrix factorization for data representation. IEEE transactions on pattern analysis and machine intelligence, 33(8), 1548-1560. End of explanation """ mc = MotionCorrect(fnames, dview=dview, **opts.get_group('motion')) %%capture #%% Run piecewise-rigid motion correction using NoRMCorre mc.motion_correct(save_movie=True) m_els = cm.load(mc.fname_tot_els) border_to_0 = 0 if mc.border_nan is 'copy' else mc.border_to_0 # maximum shift to be used for trimming against NaNs """ Explanation: Motion correction First we create a motion correction object and then perform the registration. The provided dataset has already been registered with a different method so we do not expect to see a lot of motion. End of explanation """ #%% compare with original movie display_movie = False if display_movie: m_orig = cm.load_movie_chain(fnames) ds_ratio = 0.2 cm.concatenate([m_orig.resize(1, 1, ds_ratio) - mc.min_mov*mc.nonneg_movie, m_els.resize(1, 1, ds_ratio)], axis=2).play(fr=60, q_max=99.5, magnification=4, offset=0) # press q to exit """ Explanation: Display registered movie next to the original End of explanation """ #%% MEMORY MAPPING # memory map the file in order 'C' fname_new = cm.save_memmap(mc.mmap_file, base_name='memmap_', order='C', border_to_0=border_to_0) # exclude borders # now load the file Yr, dims, T = cm.load_memmap(fname_new) images = np.reshape(Yr.T, [T] + list(dims), order='F') #load frames in python format (T x X x Y) #%% restart cluster to clean up memory cm.stop_server(dview=dview) c, dview, n_processes = cm.cluster.setup_cluster( backend='local', n_processes=None, single_thread=False) """ Explanation: Memory mapping End of explanation """ cnm = cnmf.CNMF(n_processes, params=opts, dview=dview) cnm = cnm.fit(images) """ Explanation: Now run CNMF with the chosen initialization method Note that in the parameter setting we have set only_init = True so only the initialization will be run. End of explanation """ CI = cm.local_correlations(images[::1].transpose(1,2,0)) CI[np.isnan(CI)] = 0 cnm.estimates.hv_view_components(img=CI) """ Explanation: Display components And compute the correlation image as a reference image End of explanation """ A = cnm.estimates.A.toarray().reshape(opts.data['dims'] + (-1,), order='F').transpose([2, 0, 1]) Nc = A.shape[0] grid_shape = (np.ceil(np.sqrt(Nc/2)).astype(int), np.ceil(np.sqrt(Nc*2)).astype(int)) plt.figure(figsize=np.array(grid_shape[::-1])*1.5) plt.imshow(montage(A, rescale_intensity=True, grid_shape=grid_shape)) plt.title('Montage of found spatial components'); plt.axis('off'); """ Explanation: Plot a montage array of all the components We can also plot a montage of all the identified spatial footprints. End of explanation """ cnm2 = cnm.refit(images, dview=dview) """ Explanation: Run CNMF to sparsify the components The components found by the initialization have captured a lot of structure but they are not sparse. Using the refit command will sparsify them. End of explanation """ cnm2.estimates.hv_view_components(img=CI) A2 = cnm2.estimates.A.toarray().reshape(opts.data['dims'] + (-1,), order='F').transpose([2, 0, 1]) Nc = A2.shape[0] grid_shape = (np.ceil(np.sqrt(Nc/2)).astype(int), np.ceil(np.sqrt(Nc*2)).astype(int)) plt.figure(figsize=np.array(grid_shape[::-1])*1.5) plt.imshow(montage(A2, rescale_intensity=True, grid_shape=grid_shape)) plt.title('Montage of found spatial components'); plt.axis('off'); """ Explanation: Now plot the components again End of explanation """ cnm2.estimates.play_movie(images, q_max=99.9, magnification=4, include_bck=False) # press q to exit """ Explanation: The resulting components are significantly more sparse and capture a lot of the data structure. Play a movie with the results The movie will show three panels with the original, denoised and residual movies respectively. The flag include_bck = False will remove the estimated background from the original and denoised panels. To include it set it to True. End of explanation """ #cnm2.estimates.Cn = CI # save the correlation image for displaying in the background #cnm2.save('dendritic_analysis.hdf5') """ Explanation: Save the object You can save the results of the analysis for future use and/or to load them on the GUI. End of explanation """ #%% restart cluster to clean up memory cm.stop_server(dview=dview) c, dview, n_processes = cm.cluster.setup_cluster( backend='local', n_processes=None, single_thread=False) """ Explanation: Now try CNMF with patches As mentioned above, the file shown here is small enough to be processed at once. For larger files patches and/or downsampling can be used. We show how to use patches below. Note that unlike in somatic imaging, for dendritic imaging we want the patches to be large and have significant overlap so enough structure of the dendritic segments is captured in the overlapping region. This will help with merging the components. However, a too large patch size can result to memory issues due to large amount of data loaded concurrently onto memory. End of explanation """ rf = 48 # size of each patch is (2*rf, 2*rf) stride_cnmf = 16 Kp = 25 # reduce the number of component as it is now per patch opts.change_params({'rf': rf, 'stride': stride_cnmf, 'K': Kp}); cnm_patches = cnmf.CNMF(n_processes, params=opts, dview=dview) cnm_patches = cnm_patches.fit(images) cnm_patches.estimates.hv_view_components(img=CI) Ap = cnm_patches.estimates.A.toarray().reshape(opts.data['dims'] + (-1,), order='F').transpose([2, 0, 1]) Nc = Ap.shape[0] grid_shape = (np.ceil(np.sqrt(Nc/2)).astype(int), np.ceil(np.sqrt(Nc*2)).astype(int)) plt.figure(figsize=np.array(grid_shape[::-1])*1.5) plt.imshow(montage(Ap, rescale_intensity=True, grid_shape=grid_shape)) plt.title('Montage of found spatial components'); plt.axis('off'); """ Explanation: Change some parameters to enable patches To enable patches the rf parameter should be changed from None to some integer value. Moreover the amount of overlap controlled by stride_cnmf should also change. Finally, since the parameter K specifies components per patch it should be reduced compared to its value when operating on the whole FOV at once. It is important to experiment with different values for these parameters since results can sensitive, due to the non stereotypical shapes and activity patterns of dendrites. End of explanation """ cnm_patches2 = cnm_patches.refit(images, dview=dview) Ap2 = cnm_patches2.estimates.A.toarray().reshape(opts.data['dims'] + (-1,), order='F').transpose([2, 0, 1]) Nc = Ap2.shape[0] grid_shape = (np.ceil(np.sqrt(Nc/2)).astype(int), np.ceil(np.sqrt(Nc*2)).astype(int)) plt.figure(figsize=np.array(grid_shape[::-1])*1.5) plt.imshow(montage(Ap2, rescale_intensity=True, grid_shape=grid_shape)) plt.title('Montage of found spatial components'); plt.axis('off'); cnm_patches2.estimates.play_movie(images, q_max=99.9, magnification=4, include_bck=False) # press q to exit """ Explanation: Refit to sparsify As before we can pass the results through the CNMF refit function that can yield more sparse components. End of explanation """ AA = np.corrcoef(cnm2.estimates.A.toarray(), cnm_patches2.estimates.A.toarray(), rowvar=False) plt.imshow(AA[:cnm2.estimates.A.shape[1], cnm2.estimates.A.shape[1]:]) plt.colorbar(); plt.xlabel('with patches') plt.ylabel('without patches') plt.title('Correlation coefficients'); """ Explanation: Compare the two approaches To identify how similar components and the two approaches yield, we can compute the cross-correlation matrix between the spatial footprints derived from the two approaches. End of explanation """ #%% STOP CLUSTER and clean up log files cm.stop_server(dview=dview) log_files = glob.glob('*_LOG_*') for log_file in log_files: os.remove(log_file) """ Explanation: Stop the cluster when you're done End of explanation """
tpin3694/tpin3694.github.io
python/pandas_dataframe_examples.ipynb
mit
import pandas as pd """ Explanation: Title: Simple Example Dataframes In Pandas Slug: pandas_dataframe_examples Summary: Simple Example Dataframes In Pandas Date: 2016-05-01 12:00 Category: Python Tags: Data Wrangling Authors: Chris Albon import modules End of explanation """ raw_data = {'first_name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], 'last_name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze'], 'age': [42, 52, 36, 24, 73], 'preTestScore': [4, 24, 31, 2, 3], 'postTestScore': [25, 94, 57, 62, 70]} df = pd.DataFrame(raw_data, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore']) df """ Explanation: Create dataframe End of explanation """ raw_data_2 = {'first_name': ['Sarah', 'Gueniva', 'Know', 'Sara', 'Cat'], 'last_name': ['Mornig', 'Jaker', 'Alom', 'Ormon', 'Koozer'], 'age': [53, 26, 72, 73, 24], 'preTestScore': [13, 52, 72, 26, 26], 'postTestScore': [82, 52, 56, 234, 254]} df_2 = pd.DataFrame(raw_data_2, columns = ['first_name', 'last_name', 'age', 'preTestScore', 'postTestScore']) df_2 """ Explanation: Create 2nd dataframe End of explanation """ raw_data_3 = {'first_name': ['Sarah', 'Gueniva', 'Know', 'Sara', 'Cat'], 'last_name': ['Mornig', 'Jaker', 'Alom', 'Ormon', 'Koozer'], 'postTestScore_2': [82, 52, 56, 234, 254]} df_3 = pd.DataFrame(raw_data_3, columns = ['first_name', 'last_name', 'postTestScore_2']) df_3 """ Explanation: Create 3rd dataframe End of explanation """
jacobdein/alpine-soundscapes
archive/Landcover factor exploration.ipynb
mit
import pandas from Pymilio import database import numpy as np from colour import Color import matplotlib.pylab as plt %matplotlib inline """ Explanation: Landcover factor exploration This notebook explores the relationship between the soundscape power and contributing land cover area for sounds in a pumilio database. Required packages pandas <br /> numpy <br /> matplotlib <br /> pymilio <br /> colour Import statements End of explanation """ db = database.Pymilio_db_connection(user='pumilio', database='pumilio', read_default_file='~/.my.cnf.pumilio') Sounds = db.fetch_as_pandas_df(table='Sounds', fields=['SoundID', 'SiteID', 'ColID']).set_index('SoundID') Sites = db.fetch_as_pandas_df(table='Sites', fields=['SiteID', 'ID', 'SiteName'], where='ID > 0 AND ID <= 30').set_index('ID') LandcoverTypes = db.fetch_as_pandas_df(table='LandcoverTypes', fields=['*']).set_index('ID') """ Explanation: Connect to database End of explanation """ LandcoverArea = db.fetch_as_pandas_df(table='LandcoverAreas', fields=['*'], where='IncludedArea = "500m"').set_index('ID') landcover_area = LandcoverArea.join(Sites.drop('SiteID', axis=1), on='SiteID', how='right').sort_values(by='SiteID') full_area = 775665.717 """ Explanation: ... End of explanation """ landcover_area_nosort = landcover_area landcover_area.sort_values(by=['9', '2'], ascending=[False, True], inplace=True) landcover_area['SiteID'].as_matrix() # all categories plt.figure(figsize=(15, 5)) bar_width = 0.9 ID = np.array([ n for n in range(len(landcover_area)) ]) SiteIDs = landcover_area['SiteID'].as_matrix() left = ID + 0.05 height = np.zeros(len(landcover_area)) bottom = np.zeros(len(landcover_area)) for index, column in landcover_area.ix[:,'1':'15'].iteritems(): height = column.as_matrix() plt.bar(left=left, height=height, bottom=bottom, width=bar_width, color=LandcoverTypes['Color'][int(index)], edgecolor=None, linewidth=0) bottom = bottom + height plt.xlim(0, 30) plt.ylim(0, full_area) plt.xlabel('Sites') plt.ylabel('Area (square meters)') plt.title('Landcover') xticks = ID + 0.5 xticklabels = landcover_area['SiteName'].as_matrix() xticklabels = [ "{0} - {1}".format(xticklabels[i], SiteIDs[i]) for i in ID ] plt.xticks(xticks, xticklabels, rotation='vertical') plt.show() """ Explanation: sort on landcover percentage End of explanation """ IndexNDSI = db.fetch_as_pandas_df(table='IndexNDSI', fields=['Sound', 'ndsi_left', 'ndsi_right', 'biophony_left', 'biophony_right', 'anthrophony_left', 'anthrophony_right']).set_index('Sound') ndsi = IndexNDSI.join(Sounds).join(Sites.drop('SiteID', axis=1), on='SiteID') ndsi_collection1 = ndsi.groupby('ColID').get_group(1) ndsi_collection1 = ndsi_collection1.rename(columns={"SiteID": "ID"}) ndsi_collection1_byID = ndsi_collection1.groupby('ID') xticklabels = landcover_area['SiteName'].as_matrix() xticklabels = [ "{0} - {1}".format(xticklabels[i], SiteIDs[i]) for i in ID ] plt.figure(figsize=(15,10)) for name, group in ndsi_collection1_byID: x = (group['ID'].as_matrix() - 100) - 0.1 y = group['biophony_left'].as_matrix() plt.plot(x, y, 'r-') plt.scatter(x, y, color='red', marker='.') x = (group['ID'].as_matrix() - 100) + 0.1 y = group['biophony_right'].as_matrix() plt.plot(x, y, 'b-') plt.scatter(x, y, color='blue', marker='.') plt.xlim(0, 31) plt.ylim(0, 2.5) plt.xlabel('Sites') plt.ylabel('biophony') plt.title('biophony_left and biophony_right') xticks = [i for i in range(1, len(ndsi_collection1_byID)+1)] xticklabels = Sites.sort_index()['SiteName'].as_matrix() xticklabels = ["{0} - {1}".format(xticklabels[i-1], i) for i in xticks] plt.xticks(xticks, xticklabels, rotation='vertical') plt.grid() """ Explanation: NDSI End of explanation """
vberaudi/utwt
demo.ipynb
apache-2.0
import pandas as pd #channels = read_storage('channels.csv') _names = pd.read_csv("https://raw.githubusercontent.com/vberaudi/utwt/master/bank_customers.csv", names =["customerid","name"]) offers = pd.read_csv("https://raw.githubusercontent.com/vberaudi/utwt/master/bank_behaviors.csv", names =["customerid","Product1","Confidence1","Product2","Confidence2"]) names = { t[0] : t[1] for t in _names.itertuples(index=False)} """ Explanation: <span style="color:blue">How to make targeted offers to customers?</span> <span style="color:blue">Marketing Campaign Optimization</span> This notebook is part of the Prescriptive Analytics for Python <span style="color:blue">Describe the business problem</span> This example is based on a fictional banking company. The marketing department wants to achieve more profitable results in future campaigns by matching the right offer of financial services to each customer. The data science team needs to compute this best plan: it first predicted the current customer behavior with SPSS and stored the data in a CSV. Now they need to apply optimization on this dataset to determine the next best action. The Self-Learning Response Model (SLRM) node from SPSS Modeler enables you to build a model that you can continually update. Such updates are useful in building a model that assists with predicting which offers are most appropriate for customers and the probability of the offers being accepted. These sorts of models are most beneficial in customer relationship management, such as marketing applications or call centers. Specifically, the example uses a Self-Learning Response Model to identify the characteristics of customers who are most likely to respond favorably based on previous offers and responses and to promote the best current offer based on the results. <br> A set of business constraints have to be respected: We have a limited budget to run a marketing campaign based on "gifts", "newsletter", "seminar"... Each has a cost and an impact (weight) We want to determine which is the unique best way to contact the customers. We need to identify which customers to contact. <span style="color:blue">Why are Prescriptive Analytics useful?</span> <span style="color:blue">Solving a very simple Marketing Campaign</span> For each possible <b>campaign</b>, a <b>cost</b> C and an <b>expected return</b> R are provided We have a <b>limited budget</b> to spend efficiently. <table align=left> <tr> <td> <table> <tr><th>Revenue</th><th> Cost </th></tr> <tr><td> 39 </td><td> 20 </td></tr> <tr><td> 20 </td><td> 11 </td></tr> <tr><td> 22 </td><td> 12 </td></tr> <tr><td> 26 </td><td> 14 </td></tr> </table> </td> <td> </td> <td> <table> <tr><th> Revenue </th><th> Cost </th></tr> <tr><td> 36 </td><td> 20 </td></tr> <tr><td> 30 </td><td> 16 </td></tr> <tr><td> 17 </td><td> 9 </td></tr> <tr><td> 34 </td><td> 19 </td></tr> </table> </td> </tr> <tr><h6> How do you spend your $100? </h6></tr> </table> Trying a custom algorithm What about the following rule (heuristic): Sort campaigns according to decreasing return to cost ratio R / C to have the "best" ROI at first. Choose campaigns in this order until the $100k budget is exhausted <table align=left> <tr><th>Revenue</th><th> Cost </th><th> Ratio </th></tr> <tr><td> <b>39</b> </td><td> <b>20</b> </td><td> <b>1.95</b> </td></tr> <tr><td> <b>17</b> </td><td> <b>9</b> </td><td> <b>1.89</b> </td></tr> <tr><td> <b>30</b> </td><td> <b>16</b> </td><td> <b>1.88</b> </td></tr> <tr><td> <b>26</b> </td><td> <b>14</b> </td><td> <b>1.86</b> </td></tr> <tr><td> <b>22</b> </td><td> <b>12</b> </td><td> <b>1.83</b> </td></tr> <tr><td> <b>20</b> </td><td> <b>11</b> </td><td> <b>1.82</b> </td></tr> <tr><td> 36 </td><td> 20 </td><td> 1.80 </td></tr> <tr><td> 34 </td><td> 19 </td><td> 1.19 </td></tr> </table> You will end up selecting the bold columns, with a revenue of 154 for a cost of 82. <b>Your profit is \$72 </b> Using prescriptive analytics Using CPLEX algorithm, you will be able to express your business constraints as mathematical sentences, then CPLEX will compute the values of decision variables (should I select an item or not?) mapped to the data. Asking for the maximum ROI, you will get a different <b>optimal</b> solution You could write a custom algorithm to the combinations (handle holes)… and search for the best solution but these are usually not trivial, time-consuming to implement whereas solving your problem with CPLEX Optimizer, you benefit from already implemented search algorithm that have been proven very efficient. <table align=left> <tr><th>Revenue</th><th> Cost </th><th> Ratio </th></tr> <tr><td> <b>39</b> </td><td> <b>20</b> </td><td> <b>1.95</b> </td></tr> <tr><td> 17 </td><td> 9 </td><td> 1.89 </td></tr> <tr><td> <b>30</b> </td><td> <b>16</b> </td><td> <b>1.88</b> </td></tr> <tr><td> <b>26</b> </td><td> <b>14</b> </td><td> <b>1.86</b> </td></tr> <tr><td> 22 </td><td> 12 </td><td> 1.83 </td></tr> <tr><td> <b>20</b> </td><td> <b>11</b> </td><td> <b>1.82</b> </td></tr> <tr><td> <b>36</b> </td><td> <b>20</b> </td><td> <b>1.80</b> </td></tr> <tr><td> <b>34</b> </td><td> <b>19</b> </td><td> <b>1.79</b> </td></tr> </table> You will end up selecting the bold columns, with a revenue of 185 for a cost of 100. <b> Your profit is \$85 (\$13 more than previously) </b> <span style="color:blue">Conclusion</span> This kind of problem is highly combinatorial, that is it cannot be solved by hand or with a simple custom algorithm. In general, a SPSS-like algorithm will give you a full list of actions with their advantages and drawbacks. But in real life, you cannot put them all into action, because of limited budget, time... Prescriptive analytics is the next step on the path to insight-based actions. It creates value through <b>synergy with predictive analytics</b>, which analyzes data to predict future outcomes. Prescriptive analytics takes that insight to the next level by <b>suggesting the optimal way to handle that future situation</b>. One of the most powerful aspects of mathematical optimization is that <b>you don't need to know how to solve a problem to get a solution, the engine will provide it to you</b> <b>You “just” need to express the problem using a non-ambiguous mathematical language</b> (i.e. you need to write a mathematical model) <span style="color:blue">Back to the business problem: let's solve it!</span> <span style="color:blue">Prepare the data</span> <span style="color:blue">Step 1 : Model the data</span> The predictions show which offers a customer is most likely to accept, and the confidence that they will accept, depending on each customer’s details. For example: * (139987, "Pension", 0.13221, "Mortgage", 0.10675) indicates that customer Id=139987 will certainly not buy a Pension as the level is only 13.2%, * (140030, "Savings", 0.95678, "Pension", 0.84446) is more than likely to buy Savings and a Pension as the rates are 95.7% and 84.4%. This data is taken from a SPSS example, except that the names of the customers were modified. It was uploaded as CSV files on DSX. Data is coming from a statistic tool. Here we use csv files that are supposedly produced by SPSS for example. End of explanation """ from IPython.core.display import HTML from IPython.display import display products = ["Car loan", "Savings", "Mortgage", "Pension"] productValue = [100, 200, 300, 400] budgetShare = [0.6, 0.1, 0.2, 0.1] availableBudget = 500 channels = pd.DataFrame(data=[("gift", 20.0, 0.20), ("newsletter", 15.0, 0.05), ("seminar", 23.0, 0.30)], columns=["name", "cost", "factor"]) display(channels) print("Budget is %d $" %availableBudget) offers.insert(0,'name',pd.Series(names[i[0]] for i in offers.itertuples(index=False))) import sys sys.path.append("/gpfs/fs01/user/s683-f3dde465f37390-d7318baf8c6d/notebook/work/lib/python2.7/site-packages") """ Explanation: Data for the marketing campaign. End of explanation """ offers.drop('customerid',1).sort(columns = ['Confidence1', 'Confidence2'], ascending=False).head() """ Explanation: The data Highest expectations per customer End of explanation """ offers.drop('customerid',1).sort(columns = ['Confidence1', 'Confidence2'], ascending=True).head() """ Explanation: Lowest expectations End of explanation """ import sys import docplex.mp """ Explanation: <span style="color:blue">Use IBM Decision Optimization CPLEX Modeling for Python</span> Let's create the optimization model to select the best ways to contact customers and stay within the limited budget. <span style="color:blue">Step 1: Set up the prescriptive engine</span> Subscribe to the Decision Optimization on Cloud solve service here. Get the service URL and your personal API key and enter your credentials here: First import docplex and set the credentials to solve the model using IBM ILOG CPLEX Optimizer on Cloud. docplex is already installed with its dependancies in XSD. End of explanation """ from docplex.mp.model import Model mdl = Model(name="marketing_campaign") """ Explanation: <span style="color:blue">Step 2: Set up the prescriptive model</span> <span style="color:blue">Create the model</span> End of explanation """ offersR = xrange(0, len(offers)) productsR = xrange(0, len(products)) channelsR = xrange(0, len(channels)) channelVars = mdl.binary_var_cube(offersR, productsR, channelsR) totaloffers = mdl.integer_var() budgetSpent = mdl.continuous_var() budgetMax = mdl.integer_var(lb=availableBudget, ub=availableBudget, name="budgetMax") print("we created %d decision variables for this problem" %(len(offersR)*len(productsR)*len(channelsR)+1+1)) """ Explanation: Define the decision variables The integer decision variables channelVars, represent whether or not a customer will be made an offer for a particular product via a particular channel. The integer decision variable totaloffers represents the total number of offers made. The continuous variable budgetSpent represents the total cost of the offers made. End of explanation """ # Only 1 product is offered to each customer mdl.add_constraints( mdl.sum(channelVars[o,p,c] for p in productsR for c in channelsR) <=1 for o in offersR) mdl.add_constraint( totaloffers == mdl.sum(channelVars[o,p,c] for o in offersR for p in productsR for c in channelsR) ) mdl.add_constraint( budgetSpent == mdl.sum(channelVars[o,p,c]*channels.get_value(index=c, col="cost") for o in offersR for p in productsR for c in channelsR) ) # Balance the offers among products for p in productsR: mdl.add_constraint( mdl.sum(channelVars[o,p,c] for o in offersR for c in channelsR) <= budgetShare[p] * totaloffers ) # Do not exceed the budget mdl.add_constraint( mdl.sum(channelVars[o,p,c]*channels.get_value(index=c, col="cost") for o in offersR for p in productsR for c in channelsR) <= budgetMax ) mdl.print_information() """ Explanation: Set up the constraints Offer only one product per customer. Compute the budget and set a maximum on it. Compute the number of offers to be made. End of explanation """ mdl.maximize( mdl.sum( channelVars[idx,p,idx2] * c.factor * productValue[p]* o.Confidence1 for p in productsR for idx,o in offers[offers['Product1'] == products[p]].iterrows() for idx2, c in channels.iterrows()) + mdl.sum( channelVars[idx,p,idx2] * c.factor * productValue[p]* o.Confidence2 for p in productsR for idx,o in offers[offers['Product2'] == products[p]].iterrows() for idx2, c in channels.iterrows()) ) """ Explanation: Express the objective We want to maximize the expected revenue. End of explanation """ s = mdl.solve()#url=url, key=key) assert s, "No Solution !!!" mdl.report() """ Explanation: Solve with the Decision Optimization solve service End of explanation """ def build_report(disp = True): report = [(channels.get_value(index=c, col="name"), products[p], names[offers.get_value(o, "customerid")]) for c in channelsR for p in productsR for o in offersR if channelVars[o,p,c].solution_value>=0.9] assert len(report) == totaloffers.solution_value if disp: print("Marketing plan has {0} offers costing {1}".format(totaloffers.solution_value, budgetSpent.solution_value)) report_bd = pd.DataFrame(report, columns=['channel', 'product', 'customer']) #report_bd.head() return report_bd report_bd = build_report() """ Explanation: <span style="color:blue">Step 3: Analyze the solution</span> End of explanation """ display(report_bd[report_bd['channel'] == "newsletter"].drop('channel',1)) display(report_bd[report_bd['channel'] == "seminar"].drop('channel',1)) """ Explanation: Then let's focus on newsletter. (in fact, seems efficient way to push customers) End of explanation """ mdl.add_kpi(totaloffers, "nb_offers") mdl.add_kpi(budgetSpent, "budgetSpent") for c in channelsR: channel = channels.get_value(index=c, col="name") kpi = mdl.sum(channelVars[o,p,c] for p in productsR for o in offersR) mdl.add_kpi(kpi, channel) def what_if(model = None, max_budget=500, disp=True): assert model var = model.get_var_by_name("budgetMax") var.lb = max_budget var.ub = max_budget s = model.solve()#url=url, key=key) model.report() if disp: report_bd = build_report(disp = disp) display(report_bd[report_bd['channel'] == "seminar"].drop('channel',1)) return (model.kpi_value_by_name("budgetSpent"), \ model.kpi_value_by_name("nb_offers"), \ model.kpi_value_by_name("gift"), \ model.kpi_value_by_name("newsletter"), \ model.kpi_value_by_name("seminar")) x250 = what_if(model= mdl, max_budget=250, disp=False) x1000 = what_if(model= mdl, max_budget=1000, disp=False) display(pd.DataFrame([x250, x1000], columns=["budgetSpent", "nb_offers", "nb_gift", "nb_newsletter", "nb_seminar"])) """ Explanation: Playing naive What-if analysis We will now make the allowed budget move and see what happens. First, we add some kpis to get the total number of offers, the number of gitfs, seminar... End of explanation """ r = range(20) """ Explanation: The following models are run in parralel on docplexcloud. The idea is to launch dozens of models with increasing budget to detect the maximum expense we can imagine End of explanation """ import sys #import redis import concurrent.futures ret = [] def what_if2(max_budget=500): model = mdl.copy() var = model.get_var_by_name("budgetMax") var.lb = max_budget var.ub = max_budget s = model.solve()#url=url, key=key) return (max_budget, \ model.kpi_value_by_name("budgetSpent"), \ model.kpi_value_by_name("nb_offers"), \ model.kpi_value_by_name("gift"), \ model.kpi_value_by_name("newsletter"), \ model.kpi_value_by_name("seminar") ) with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor: jobs = [executor.submit(what_if2, max_budget=100+50*i) for i in r] for future in concurrent.futures.as_completed(jobs): ret.append(future.result()) index=["Budget", "budgetSpent", "nb_offers", "nb_gift", "nb_newsletter", "nb_seminar"] what_pd = pd.DataFrame(data = ret, columns=index) what_pd = what_pd.sort(columns = ['Budget'], ascending=True) #display(what_pd.sort(columns = ['Budget'], ascending=True)) %matplotlib inline import matplotlib matplotlib.style.use('ggplot') what_pd.plot(x='Budget', y='budgetSpent') """ Explanation: We clone the model, modif the budget bound and push it in a process executor to be solved in // End of explanation """
harmsm/pythonic-science
chapters/02_regression/01_fitting-with-least-squares.ipynb
unlicense
d = pd.read_csv("data/dataset_0.csv") fig, ax = plt.subplots() ax.plot(d.x,d.y,'o') """ Explanation: What does the following code do? End of explanation """ def linear(x,a,b): return a + b*x """ Explanation: What does the following code do? End of explanation """ def linear(x,a,b): return a + b*x def linear_r(param,x,y): return linear(x,param[0],param[1]) - y """ Explanation: What does the following code do? End of explanation """ def linear_r(param,x,y): # copied from previous cell return linear(x,param[0],param[1]) - y # copied from previous cell param_guesses = [1,1] fit = scipy.optimize.least_squares(linear_r,param_guesses, args=(d.x,d.y)) fit_a = fit.x[0] fit_b = fit.x[1] sum_of_square_residuals = fit.cost """ Explanation: What does the following code do? End of explanation """ x_range = np.linspace(np.min(d.x),np.max(d.x),100) fig, ax = plt.subplots() ax.plot(d.x,d.y,"o") ax.plot(x_range,linear(x_range,fit_a,fit_b)) """ Explanation: What does the following code do? What the heck is linspace? What are we plotting? End of explanation """ def linear(x,a,b): """Linear model of x using a (slope) and b (intercept)""" return a + b*x def linear_r(param,x,y): """Residuals function for linear""" return linear(x,param[0],param[1]) - y fig, ax = plt.subplots() # Read data d = pd.read_csv("data/dataset_0.csv") ax.plot(d.x,d.y,'o') # Perform regression param_guesses = [1,1] fit = scipy.optimize.least_squares(linear_r,param_guesses,args=(d.x,d.y)) fit_a = fit.x[0] fit_b = fit.x[1] sum_of_square_residuals = fit.cost # Plot result x_range = np.linspace(np.min(d.x),np.max(d.x),100) ax.plot(x_range,linear(x_range,fit_a,fit_b)) fit """ Explanation: Put together End of explanation """
gee-community/gee_tools
notebooks/.ipynb_checkpoints/chart-checkpoint.ipynb
mit
import ee from geetools import ui test_site = ee.Geometry.Point([-71, -42]) test_feat = ee.Feature(test_site, {'name': 'test feature'}) test_featcol = ee.FeatureCollection([ test_feat, test_feat.buffer(100).set('name', 'buffer 100'), test_feat.buffer(1000).set('name', 'buffer 1000') ]) """ Explanation: chart module This module relies on pygal library, so the returned charts are instances of pygal.chart. See options at pygal site I made a JavaScript 'equivalent': https://code.earthengine.google.com/b2922b860b85c1120250794fb82dfda8 End of explanation """ years = ee.List([2015, 2016, 2017, 2018]) col = ee.ImageCollection('COPERNICUS/S2').filterBounds(test_site) def make_time_series(year): ''' make a time series from year's list ''' eefilter = ee.Filter.calendarRange(year, field='year') filtered = col.filter(eefilter) return filtered.mean().set('system:time_start', ee.Date.fromYMD(year, 1, 1).millis()) time_series = ee.ImageCollection(years.map(make_time_series)) """ Explanation: Time Series End of explanation """ chart_ts = ui.chart.Image.series(**{ 'imageCollection': time_series, 'region': test_site, 'scale': 10, 'bands': ['B1', 'B2', 'B3'], # 'xProperty': 'B4', # You can use a band too! 'labels': ['band B1', 'B2 band', 'this is B3'] }) chart_ts.render_widget(width='50%') """ Explanation: Chart series End of explanation """ chart_ts_region = ui.chart.Image.seriesByRegion(**{ 'imageCollection': time_series, 'reducer': ee.Reducer.median(), 'regions': test_featcol, 'scale': 10, 'band': 'B11', 'seriesProperty': 'name' }) chart_ts_region.render_widget(height=500) """ Explanation: Chart seriesByRegion End of explanation """
gmonce/datascience
src/Predict_Shakespeare_with_Cloud_TPUs_and_Keras.ipynb
gpl-3.0
# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ Explanation: <a href="https://colab.research.google.com/github/gmonce/datascience/blob/master/Predict_Shakespeare_with_Cloud_TPUs_and_Keras.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ !wget --show-progress --continue -O /content/shakespeare.txt http://www.gutenberg.org/files/100/100-0.txt """ Explanation: Predict Shakespeare with Cloud TPUs and Keras Overview This example uses tf.keras to build a language model and train it on a Cloud TPU. This language model predicts the next character of text given the text so far. The trained model can generate new snippets of text that read in a similar style to the text training data. The model trains for 10 epochs and completes in approximately 5 minutes. This notebook is hosted on GitHub. To view it in its original repository, after opening the notebook, select File > View on GitHub. Learning objectives In this Colab, you will learn how to: * Build a two-layer, forward-LSTM model. * Use distribution strategy to produce a tf.keras model that runs on TPU version and then use the standard Keras methods to train: fit, predict, and evaluate. * Use the trained model to make predictions and generate your own Shakespeare-esque play. Instructions <h3> &nbsp;&nbsp;Train on TPU&nbsp;&nbsp; <a href="https://cloud.google.com/tpu/"><img valign="middle" src="https://raw.githubusercontent.com/GoogleCloudPlatform/tensorflow-without-a-phd/master/tensorflow-rl-pong/images/tpu-hexagon.png" width="50"></a></h3> On the main menu, click Runtime and select Change runtime type. Set "TPU" as the hardware accelerator. Click Runtime again and select Runtime > Run All. You can also run the cells manually with Shift-ENTER. TPUs are located in Google Cloud, for optimal performance, they read data directly from Google Cloud Storage (GCS) Data, model, and training In this example, you train the model on the combined works of William Shakespeare, then use the model to compose a play in the style of The Great Bard: <blockquote> Loves that led me no dumbs lack her Berjoy's face with her to-day. The spirits roar'd; which shames which within his powers Which tied up remedies lending with occasion, A loud and Lancaster, stabb'd in me Upon my sword for ever: 'Agripo'er, his days let me free. Stop it of that word, be so: at Lear, When I did profess the hour-stranger for my life, When I did sink to be cried how for aught; Some beds which seeks chaste senses prove burning; But he perforces seen in her eyes so fast; And _ </blockquote> Download data Download The Complete Works of William Shakespeare as a single text file from Project Gutenberg. You use snippets from this file as the training data for the model. The target snippet is offset by one character. End of explanation """ !head -n5 /content/shakespeare.txt !echo "..." !shuf -n5 /content/shakespeare.txt import numpy as np import tensorflow as tf import os import distutils if distutils.version.LooseVersion(tf.__version__) < '1.14': raise Exception('This notebook is compatible with TensorFlow 1.14 or higher, for TensorFlow 1.13 or lower please use the previous version at https://github.com/tensorflow/tpu/blob/r1.13/tools/colab/shakespeare_with_tpu_and_keras.ipynb') # This address identifies the TPU we'll use when configuring TensorFlow. TPU_WORKER = 'grpc://' + os.environ['COLAB_TPU_ADDR'] SHAKESPEARE_TXT = '/content/shakespeare.txt' def transform(txt): return np.asarray([ord(c) for c in txt if ord(c) < 255], dtype=np.int32) def input_fn(seq_len=100, batch_size=1024): """Return a dataset of source and target sequences for training.""" with tf.io.gfile.GFile(SHAKESPEARE_TXT, 'r') as f: txt = f.read() source = tf.constant(transform(txt), dtype=tf.int32) ds = tf.data.Dataset.from_tensor_slices(source).batch(seq_len+1, drop_remainder=True) def split_input_target(chunk): input_text = chunk[:-1] target_text = chunk[1:] return input_text, target_text BUFFER_SIZE = 10000 ds = ds.map(split_input_target).shuffle(BUFFER_SIZE).batch(batch_size, drop_remainder=True) return ds.repeat() """ Explanation: Build the input dataset We just downloaded some text. The following shows the start of the text and a random snippet so we can get a feel for the whole text. End of explanation """ EMBEDDING_DIM = 512 def lstm_model(seq_len=100, batch_size=None, stateful=True): """Language model: predict the next word given the current word.""" source = tf.keras.Input( name='seed', shape=(seq_len,), batch_size=batch_size, dtype=tf.int32) embedding = tf.keras.layers.Embedding(input_dim=256, output_dim=EMBEDDING_DIM)(source) lstm_1 = tf.keras.layers.LSTM(EMBEDDING_DIM, stateful=stateful, return_sequences=True)(embedding) lstm_2 = tf.keras.layers.LSTM(EMBEDDING_DIM, stateful=stateful, return_sequences=True)(lstm_1) predicted_char = tf.keras.layers.TimeDistributed(tf.keras.layers.Dense(256, activation='softmax'))(lstm_2) return tf.keras.Model(inputs=[source], outputs=[predicted_char]) """ Explanation: Build the model The model is defined as a two-layer, forward-LSTM, the same model should work both on CPU and TPU. Because our vocabulary size is 256, the input dimension to the Embedding layer is 256. When specifying the arguments to the LSTM, it is important to note how the stateful argument is used. When training we will make sure that stateful=False because we do want to reset the state of our model between batches, but when sampling (computing predictions) from a trained model, we want stateful=True so that the model can retain information across the current batch and generate more interesting text. End of explanation """ tf.keras.backend.clear_session() resolver = tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER) tf.contrib.distribute.initialize_tpu_system(resolver) strategy = tf.contrib.distribute.TPUStrategy(resolver) with strategy.scope(): training_model = lstm_model(seq_len=100, stateful=False) training_model.compile( optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.01), loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) training_model.fit( input_fn(), steps_per_epoch=100, epochs=10 ) training_model.save_weights('/tmp/bard.h5', overwrite=True) """ Explanation: Train the model First, we need to create a distribution strategy that can use the TPU. In this case it is TPUStrategy. You can create and compile the model inside its scope. Once that is done, future calls to the standard Keras methods fit, evaluate and predict use the TPU. Again note that we train with stateful=False because while training, we only care about one batch at a time. End of explanation """ BATCH_SIZE = 5 PREDICT_LEN = 250 # Keras requires the batch size be specified ahead of time for stateful models. # We use a sequence length of 1, as we will be feeding in one character at a # time and predicting the next character. prediction_model = lstm_model(seq_len=1, batch_size=BATCH_SIZE, stateful=True) prediction_model.load_weights('/tmp/bard.h5') # We seed the model with our initial string, copied BATCH_SIZE times seed_txt = 'Looks it not like the king? Verily, we must go! ' seed = transform(seed_txt) seed = np.repeat(np.expand_dims(seed, 0), BATCH_SIZE, axis=0) # First, run the seed forward to prime the state of the model. prediction_model.reset_states() for i in range(len(seed_txt) - 1): prediction_model.predict(seed[:, i:i + 1]) # Now we can accumulate predictions! predictions = [seed[:, -1:]] for i in range(PREDICT_LEN): last_word = predictions[-1] next_probits = prediction_model.predict(last_word)[:, 0, :] # sample from our output distribution next_idx = [ np.random.choice(256, p=next_probits[i]) for i in range(BATCH_SIZE) ] predictions.append(np.asarray(next_idx, dtype=np.int32)) for i in range(BATCH_SIZE): print('PREDICTION %d\n\n' % i) p = [predictions[j][i] for j in range(PREDICT_LEN)] generated = ''.join([chr(c) for c in p]) # Convert back to text print(generated) print() assert len(generated) == PREDICT_LEN, 'Generated text too short' """ Explanation: Make predictions with the model Use the trained model to make predictions and generate your own Shakespeare-esque play. Start the model off with a seed sentence, then generate 250 characters from it. The model makes five predictions from the initial seed. The predictions are done on the CPU so the batch size (5) in this case does not have to be divisible by 8. Note that when we are doing predictions or, to be more precise, text generation, we set stateful=True so that the model's state is kept between batches. If stateful is false, the model state is reset between each batch, and the model will only be able to use the information from the current batch (a single character) to make a prediction. The output of the model is a set of probabilities for the next character (given the input so far). To build a paragraph, we predict one character at a time and sample a character (based on the probabilities provided by the model). For example, if the input character is "o" and the output probabilities are "p" (0.65), "t" (0.30), others characters (0.05), then we allow our model to generate text other than just "Ophelia" and "Othello." End of explanation """
ponderousmad/pyndent
depth_setup.ipynb
mit
%matplotlib inline from __future__ import print_function import ipywidgets import os import re import sys import urllib import zipfile from IPython.display import display import outputer import improc drive_files = [] for root, dirs, files in os.walk('internal'): for name in files: if name.lower().endswith(".csv"): drive_files.append(os.path.join(root, name)) drive_files def load_file_map(path, mapping=None): if mapping is None: mapping = [] with open(path, "r") as folder_data: lines = folder_data.readlines() for line in lines: parts = line.split(",") if len(parts) == 3: mapping.append(parts) return mapping all_files = [] for drive_data_path in drive_files: load_file_map(drive_data_path, all_files) print(len(all_files)) data_path = outputer.setup_directory("captures") def download(file_info): base_url = "https://drive.google.com/uc?export=download&id=" url = base_url + file_info[1] path = os.path.join(data_path, file_info[0]) size = int(file_info[2]) try: stats = os.stat(path) if stats.st_size == size: return except (IOError, OSError): pass filename, headers = urllib.urlretrieve(url, path) stats = os.stat(filename) if stats.st_size != size: print("File", file_info[0], "does not have expected size", file_info[2]) def download_files(files_info): progress_bar = ipywidgets.FloatProgress(min=0, max=len(files_info), description="Downloading:") display(progress_bar) for i, entry in enumerate(files_info): download(entry) progress_bar.value = i progress_bar.value = progress_bar.max print("Download Complete!") """ Explanation: Download Data for Pyndent/Classydepth The code below does download the whole data set, but it's a slow and error prone way to do it. It's easier to just download each of this zip files below and uncompress them into /captures 0000-1000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegZFFwNU5KWkcwbDQ 1000-2000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegQU9hal9jUEhDeUk 2000-3000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegaVhxNTNoWlN2eDQ 3000-4000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegeUFpenQ5V2M3cEU 4000-5000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegNnoxZTJnUUs5bTQ 5000-6000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegMTV4MjRMVXJrcHc 6000-7000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegeXJrb3J4SHJycnc 7000-8000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegdl8zNklXeU9oTTQ 8000-9000.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegdlNHZHdCTjV2aUE 9000-9400.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegLXVNUUkzQm5GS0k noattitude.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegSlN3dWFfUDQta2c objects.zip: https://drive.google.com/uc?export=download&id=0B8WcbXogHvegcVlrSm8xRUJYSjA End of explanation """ download_files(all_files) """ Explanation: Download the Whole Dataset NOTE: This will download ~6 gb! End of explanation """ training, test = improc.enumerate_images("captures") print("Training:", len(training), "Test:", len(test)) print(training[:2]) print(test[:2]) training_mean = improc.compute_mean_depth(training) # Expected result: 1680.2417905486018 (Erroneously calculated as 1688.97 previously) print(training_mean) training_standard_deviation = improc.compute_std_dev(training, training_mean) # Expected result: 884.750172634 print(training_standard_deviation) print(training_standard_deviation / improc.MAX_DEPTH) test_mean = improc.compute_mean_depth(test) # Expected result: 1676.3290505903665 print(test_mean) test_standard_deviation = improc.compute_std_dev(test, test_mean) # Expected result: 875.721862131 print(test_standard_deviation) print(test_standard_deviation / improc.MAX_DEPTH) """ Explanation: Compute Stats End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/test-institute-2/cmip6/models/sandbox-1/ocnbgchem.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'test-institute-2', 'sandbox-1', 'ocnbgchem') """ Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: TEST-INSTITUTE-2 Source ID: SANDBOX-1 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:44 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 """
mne-tools/mne-tools.github.io
dev/_downloads/499a81f33500445fc2e1eac0be346d47/temporal_whitening.ipynb
bsd-3-clause
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD-3-Clause import numpy as np from scipy import signal import matplotlib.pyplot as plt import mne from mne.time_frequency import fit_iir_model_raw from mne.datasets import sample print(__doc__) data_path = sample.data_path() meg_path = data_path / 'MEG' / 'sample' raw_fname = meg_path / 'sample_audvis_raw.fif' proj_fname = meg_path / 'sample_audvis_ecg-proj.fif' raw = mne.io.read_raw_fif(raw_fname) proj = mne.read_proj(proj_fname) raw.add_proj(proj) raw.info['bads'] = ['MEG 2443', 'EEG 053'] # mark bad channels # Set up pick list: Gradiometers - bad channels picks = mne.pick_types(raw.info, meg='grad', exclude='bads') order = 5 # define model order picks = picks[:1] # Estimate AR models on raw data b, a = fit_iir_model_raw(raw, order=order, picks=picks, tmin=60, tmax=180) d, times = raw[0, 10000:20000] # look at one channel from now on d = d.ravel() # make flat vector innovation = signal.convolve(d, a, 'valid') d_ = signal.lfilter(b, a, innovation) # regenerate the signal d_ = np.r_[d_[0] * np.ones(order), d_] # dummy samples to keep signal length """ Explanation: Temporal whitening with AR model Here we fit an AR model to the data and use it to temporally whiten the signals. End of explanation """ plt.close('all') plt.figure() plt.plot(d[:100], label='signal') plt.plot(d_[:100], label='regenerated signal') plt.legend() plt.figure() plt.psd(d, Fs=raw.info['sfreq'], NFFT=2048) plt.psd(innovation, Fs=raw.info['sfreq'], NFFT=2048) plt.psd(d_, Fs=raw.info['sfreq'], NFFT=2048, linestyle='--') plt.legend(('Signal', 'Innovation', 'Regenerated signal')) plt.show() """ Explanation: Plot the different time series and PSDs End of explanation """
mne-tools/mne-tools.github.io
0.16/_downloads/plot_stats_spatio_temporal_cluster_sensors.ipynb
bsd-3-clause
# Authors: Denis Engemann <denis.engemann@gmail.com> # Jona Sassenhagen <jona.sassenhagen@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 find_ch_connectivity from mne.viz import plot_compare_evokeds 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. Spatiotemporal clusters will then be visualized using custom matplotlib code. Caveat for the interpretation of "significant" clusters: see the FieldTrip website_. 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, fir_design='firwin') 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) X = [epochs[k].get_data() for k in event_id] # 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 = find_ch_connectivity(epochs.info, ch_type='mag') 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: Find the 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.01 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 colors = {"Aud": "crimson", "Vis": 'steelblue'} linestyles = {"L": '-', "R": '--'} # get sensor positions via layout pos = mne.find_layout(epochs.info).pos # organize data for plotting evokeds = {cond: epochs[cond].average() for cond in event_id} # loop over 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 the sensors contributing to the cluster sig_times = epochs.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)) # 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, show=False) # create additional axes (for ERF and colorbar) 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.3f} - {:0.3f} s)'.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) title = 'Cluster #{0}, {1} sensor'.format(i_clu + 1, len(ch_inds)) if len(ch_inds) > 1: title += "s (mean)" plot_compare_evokeds(evokeds, title=title, picks=ch_inds, axes=ax_signals, colors=colors, linestyles=linestyles, show=False, split_legend=True, truncate_yaxis='max_ticks') # plot temporal cluster extent ymin, ymax = ax_signals.get_ylim() ax_signals.fill_betweenx((ymin, ymax), sig_times[0], sig_times[-1], color='orange', alpha=0.3) # 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 """
ucsd-ccbb/jupyter-genomics
notebooks/rnaSeq/ToppGeneAPI.ipynb
mit
##importing python module import os import pandas import qgrid qgrid.nbinstall(overwrite=True) qgrid.set_defaults(remote_js=True, precision=4) import mygene ##change directory os.chdir("/Users/nicole/Documents/CCBB Internship") """ Explanation: ToppGene API Authors: N. Mouchamel, T. Nguyen & K. Fisch Email: Kfisch@ucsd.edu Date: June 2016 Goal: Create Jupyter notebook cell that runs an enrichment analysis in ToppGene through the API Toppgene website https://toppgene.cchmc.org/enrichment.jsp *Note: request ToppGene API through ToppGene developers Steps: 1. Read in differentially expressed gene list 2. Convert differentially expressed gene list to xml file as input to ToppGene API 3. Run enrichment analysis of DE genes through ToppGene API 4. Parse ToppGene API results from xml to csv and Pandas data frame 5. Display results in notebook End of explanation """ ##read in DESeq2 results genes=pandas.read_csv("DE_genes.csv") ##View interactive table ##qgrid.show_grid(genes.sample(1000), grid_options={'forceFitColumns': False, 'defaultColumnWidth': 100}) #View top of file genes.head(10) #Extract genes that are differentially expressed with a pvalue less than a certain cutoff (pvalue < 0.05 or padj < 0.05) genes_DE_only = genes.loc[(genes.pvalue < 0.05)] #View top of file genes_DE_only.head(10) #Check how many rows in original genes file len(genes) #Check how many rows in DE genes file len(genes_DE_only) """ Explanation: Read in differential expression results as a Pandas data frame to get differentially expressed gene list End of explanation """ #Extract list of DE genes (Check to make sure this code works, this was adapted from a different notebook) de_list = genes_DE_only[genes_DE_only.columns[0]] #Remove .* from end of Ensembl ID de_list2 = de_list.replace("\.\d","",regex=True) #Add new column with reformatted Ensembl IDs genes_DE_only["Full_Ensembl"] = de_list2 #View top of file genes_DE_only.head(10) #Set up mygene.info API and query mg = mygene.MyGeneInfo() gene_ids = mg.getgenes(de_list2, 'name, symbol, entrezgene', as_dataframe=True) gene_ids.index.name = "Ensembl" gene_ids.reset_index(inplace=True) #View top of file gene_ids.head(10) #Merge mygene.info query results with original DE genes list DE_with_ids = genes_DE_only.merge(gene_ids, left_on="Full_Ensembl", right_on="Ensembl", how="outer") #Check top of file DE_with_ids.head(10) #Write results to file DE_with_ids.to_csv("./DE_genes_converted.csv") #Dataframe to only contain gene symbol DE_with_ids=pandas.read_csv("./DE_genes_converted.csv") cols = DE_with_ids.columns.tolist() cols.insert(0, cols.pop(cols.index('symbol'))) for_xmlfile = DE_with_ids.reindex(columns= cols) #Condense dataframe to contain only symbol for_xmlfile.drop(for_xmlfile.columns[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12,13,14]], axis=1, inplace=True) #Exclude NaN values for_xmlfile.dropna(axis=0, how='any', thresh=None, subset=None, inplace=True) for_xmlfile.head(10) #Write results to file for_xmlfile.to_csv("./for_xmlfile.csv", index=False) #.XML file generator from gene list in .csv file import xml.etree.cElementTree as ET import xml.etree.cElementTree as ElementTree import lxml root=ET.Element("requests") doc=ET.SubElement(root, "toppfun", id= "nicole's gene list") config=ET.SubElement(doc, "enrichment-config") gene_list=ET.SubElement(doc, "trainingset") gene_list.set('accession-source','HGNC') #for gene symbol in gene_list toppgene = pandas.read_csv("./for_xmlfile.csv") for i in toppgene.ix[:,0]: gene_symbol = i gene = ET.SubElement(gene_list, "gene") gene.text= gene_symbol tree = ET.ElementTree(root) def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i indent(root) import xml.dom.minidom from lxml import etree with open('/Users/nicole/Documents/test.xml', 'w') as f: f.write('<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE requests SYSTEM "https://toppgene.cchmc.org/toppgenereq.dtd">') ElementTree.ElementTree(root).write(f, 'utf-8') xml = xml.dom.minidom.parse("/Users/nicole/Documents/test.xml") pretty_xml_as_string = xml.toprettyxml() print(pretty_xml_as_string) """ Explanation: Translate Ensembl IDs to Gene Symbols and Entrez IDs using mygene.info API End of explanation """ import xml.etree.cElementTree as ET import lxml root=ET.Element("requests") doc=ET.SubElement(root, "toppfun", id="a") config=ET.SubElement(doc, "enrichment-config") #training=ET.SubElement(doc, "trainingset accession-source='HGNC'") training=ET.SubElement(doc, "trainingset") training.set('accession-source','HGNC') #features=ET.SubElement(config, "features") gene1=ET.SubElement(training, "gene") gene2=ET.SubElement(training, "gene") gene3=ET.SubElement(training, "gene") gene1.text="APOB" gene2.text="APOE" gene3.text="AIR1" #### doc2= ET.SubElement(root, "toppgene", id="b") config2=ET.SubElement(doc2, "enrichment-config") prior=ET.SubElement(doc2,"prioritization-config") training2=ET.SubElement(doc2, "trainingset") training2.set('accession-source','HGNC') gene4=ET.SubElement(training2, "gene") gene4.text="SRF" #testset=ET.SubElement(doc2, "testset accession-source='HGNC'") testset=ET.SubElement(doc2, "testset") testset.set('accession-source','HGNC') gene5=ET.SubElement(testset, "gene") gene5.text="APOB" #### doc3= ET.SubElement(root, "toppnet", id="Pattern") config3=ET.SubElement(doc3, "net-config") ##net-config markov=ET.SubElement (config3, "k-step-markov step-size='6'") #k-step-markov step-size='6' visual=ET.SubElement (config3, "visualizer neighborhood-distance='1'") ##visualizer neighborhood-distance="1" training3=ET.SubElement(doc3, "trainingset") training3.set('accession-source','HGNC') gene6=ET.SubElement(training3, "gene") gene6.text="SRF" #testset2=ET.SubElement(doc3, "testset accession-source='ENTREZ'") testset2=ET.SubElement(doc3, "testset") testset2.set('accession-source','ENTREZ') gene7=ET.SubElement(testset2,"gene") gene7.text="338" ### doc4= ET.SubElement (root, "toppgenet", id="d") config4=ET.SubElement(doc4, "enrichment-config") training4=ET.SubElement(doc4, "trainingset") training4.set('accession-source','HGNC') gene8=ET.SubElement(training4, "gene") gene8.text="APOB" tree = ET.ElementTree(root) def indent(elem, level=0): i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level+1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i import xml.dom.minidom from lxml import etree indent(root) with open('/Users/nicole/Documents/nicolez.xml', 'w') as f: f.write('<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE requests SYSTEM "https://toppgene.cchmc.org/toppgenereq.dtd">') ElementTree.ElementTree(root).write(f,'utf-8') xml = xml.dom.minidom.parse("/Users/nicole/Documents/nicolez.xml") pretty_xml_as_string = xml.toprettyxml() print(pretty_xml_as_string) #!sed -e 's/X/ /g' -e 's/Q/=/g' -e 's/9/\"/g' -e 's/\../\-/g' filename.xml >newfile.xml import xml.dom.minidom xml = xml.dom.minidom.parse("/Users/nicole/Documents/zcopy.xml") pretty_xml_as_string = xml.toprettyxml() print(pretty_xml_as_string) """ Explanation: Reformat list of genes to xml input format as in the test file z.xml Reformat list of gene IDs (DE_with_ids, symbol) into xml format to look like example below. Documentation (along with google searching) http://stackoverflow.com/questions/3605680/creating-a-simple-xml-file-using-python End of explanation """ #Run command line tool through Python #this works on test file !curl -v -H 'Content-Type: text/xml' --data @/Users/nicole/Documents/test.xml -X POST https://toppgene.cchmc.org/api/44009585-27C5-41FD-8279-A5FE1C86C8DB > /Users/nicole/Documents/testoutfile.xml import xml.dom.minidom xml = xml.dom.minidom.parse("/Users/nicole/Documents/testoutfile.xml") pretty_xml_as_string = xml.toprettyxml() print(pretty_xml_as_string) """ Explanation: Run ToppGene API via command line through provided instructions https://toppgene.cchmc.org/api/44009585-27C5-41FD-8279-A5FE1C86C8DB The input data is an XML payload that conforms to the DTD specified by https://toppgene.cchmc.org/toppgenereq.dtd An example of how you might run a command line query from a UNIX (including Linux and Mac) command line: curl -v -H 'Content-Type: text/xml' --data @z.xml -X POST https://toppgene.cchmc.org/api/44009585-27C5-41FD-8279-A5FE1C86C8DB fix on server vim ~/.curlrc then add this to file cacert=/etc/ssl/certs/ca-certificates.crt End of explanation """ #xml to pandas dataframe http://pandas.pydata.org/pandas-docs/stable/api.html#input-output import xml.dom.minidom import pandas as pd import numpy import pyexcel #Parse through .xml file def load_parse_xml(data_file): """Check if file exists. If file exists, load and parse the data file. """ if os.path.isfile(data_file): print "File exists. Parsing..." data_parse = ET.ElementTree(file=data_file) print "File parsed." return data_parse xmlfile = load_parse_xml("/Users/nicole/Documents/testoutfile.xml") #Generate array of annotation arrays for .csv file root_tree = xmlfile.getroot() gene_list=[] for child in root_tree: child.find("enrichment-results") new_array = [] array_of_arrays=[] for type in child.iter("enrichment-result"): for annotation in type.iter("annotation"): array_of_arrays.append(new_array) new_array = [] new_array.append(type.attrib['type']) new_array.append(annotation.attrib['name']) new_array.append(annotation.attrib['id']) new_array.append(annotation.attrib['pvalue']) new_array.append(annotation.attrib['genes-in-query']) new_array.append(annotation.attrib['genes-in-term']) new_array.append(annotation.attrib['source']) for gene in annotation.iter("gene"): gene_list.append(gene.attrib['symbol']) new_array.append(gene_list) gene_list =[] print array_of_arrays import pyexcel data = array_of_arrays pyexcel.save_as(array = data, dest_file_name = '/Users/nicole/Documents/plswork.csv') df=pandas.read_csv('/Users/nicole/Documents/plswork.csv', header=None) df.columns=['ToppGene Feature','Annotation Name','ID','pValue','Genes-in-Query','Genes-in-Term','Source','Genes'] #df.head(15) #Dataframe for GeneOntologyMolecularFunction df.loc[df['ToppGene Feature'] == 'GeneOntologyMolecularFunction'] #Dataframe for GeneOntologyBiologicalProcess df.loc[df['ToppGene Feature'] == 'GeneOntologyBiologicalProcess'] #Dataframe for GeneOntologyCellularComponent df.loc[df['ToppGene Feature'] == 'GeneOntologyCellularComponent'] #Dataframe for Human Phenotype df.loc[df['ToppGene Feature'] == 'HumanPheno'] #Dataframe for Mouse Phenotype df.loc[df['ToppGene Feature'] == 'MousePheno'] #Dataframe for Domain df.loc[df['ToppGene Feature'] == 'Domain'] #Dataframe for Pathways df.loc[df['ToppGene Feature'] == 'Pathway'] #Dataframe for Pubmed df.loc[df['ToppGene Feature'] == 'Pubmed'] #Dataframe for Interactions df.loc[df['ToppGene Feature'] == 'Interaction'] #Dataframe for Cytobands df.loc[df['ToppGene Feature'] == 'Cytoband'] #Dataframe for Transcription Factor Binding Sites df.loc[df['ToppGene Feature'] == 'TranscriptionFactorBindingSite'] #Dataframe for Gene Family df.loc[df['ToppGene Feature'] == 'GeneFamily'] #Dataframe for Coexpression df.loc[df['ToppGene Feature'] == 'Coexpression'] #DataFrame for Coexpression Atlas df.loc[df['ToppGene Feature'] == 'CoexpressionAtlas'] #Dataframe for Computational df.loc[df['ToppGene Feature'] == 'Computational'] #Dataframe for MicroRNAs df.loc[df['ToppGene Feature'] == 'MicroRNA'] #Dataframe for Drugs df.loc[df['ToppGene Feature'] == 'Drug'] #Dataframe for Diseases df.loc[df['ToppGene Feature'] == 'Disease'] """ Explanation: Parse ToppGene results into Pandas data frame End of explanation """
seewhydee/ntuphys_nb
jupyter/gradqm/electromagnetism.ipynb
gpl-3.0
%matplotlib inline ## Numerical solver for Schrodinger equation for electron in 2D ## See below for detailed documentation and usage examples. ## Phi, Ax, Ay : functions specifying scalar and vector potential ## args : tuple of additional inputs to the potential functions ## L : length of computational domain ## N : no. of grid points in each direction (x and y) ## num : no. of solutions to find ## E0 : approximate energy of solutions to find def schrodinger2d(Phi, Ax, Ay, args=(), L=1.0, N=100, num=12, E0=-100.0): from numpy import linspace, meshgrid, reshape, exp, argsort from scipy.sparse import diags from scipy.sparse.linalg import eigsh a = L/(N+1) # lattice spacing p = linspace(-L/2+a, L/2-a, N) xvec, yvec = meshgrid(p, p) # 2D grid x = reshape(xvec, N*N) # 1D array of x y = reshape(yvec, N*N) # 1D array of y ## Compute contents of the Hamiltonian matrix: Hd = 2/a**2 - Phi(x, y, *args) # diagonal terms ox = -0.5/a**2 * exp(1j*a*Ax(x+a/2, y, *args)) # x-step ox[(N-1)::N] = 0.0; ox = ox[:-1] # Dirichlet BCs in x oy = -0.5/a**2 * exp(1j*a*Ay(x, y+a/2, *args)) # y-step oy = oy[:-N] # Dirichlet BCs in y ## Construct the Hamiltonian matrix and solve it: H = diags([Hd, ox, ox.conj(), oy, oy.conj()], [0, 1, -1, N, -N], format='csc', dtype=complex) E, psi = eigsh(H, num, sigma=E0, return_eigenvectors=True) idx = argsort(E) # sort in increasing E E = E[idx] psi = reshape(psi[:,idx], (N, N, num)) ## Grid coordinates suitable for `pcolormesh` pgrid = linspace(-L/2, L/2, N+1) x, y = meshgrid(pgrid, pgrid) return E, psi, x, y """ Explanation: Quantum Mechanics of an Electron in an Electromagnetic Field In this notebook, we will study the energy levels and wavefunctions of an electron in an electromagnetic field. We make the following simplifying assumptions: The problem is two-dimensional and static: the electron moves in the $x$-$y$ plane, and the potentials can vary in $x$ and $y$ but have no $z$ or $t$ dependence. The electron is non-relativistic. $e = m = \hbar = 1$. For this system, the time-independent Schrödinger wave equation takes the following partial differential equation (PDE) form: $$\left{\frac{1}{2}\left[\left(-i\frac{\partial}{\partial x} + A_x\right)^2 + \left(-i\frac{\partial}{\partial y} + A_y\right)^2\right] - \Phi(x,y) \right} \psi(x,y) = E \;\psi(x,y)$$ where: $\Phi(x,y)$ is the electromagnetic scalar potential $A_x(x,y)$ and $A_y(x,y)$ are the $x$ and $y$ components of the vector potential $\psi(x,y)$ is an energy eigenfunction, and $E$ is the corresponding energy Numerical solver A numerical solver for this PDE has been written for you below. The details are beyond the scope of this discussion, and are not required for the exercises below. (It uses a technique called the finite difference method, in which space is discretized into a grid and Taylor expansions are used to convert a PDE into a matrix equation.) Skim through the code below. There's no need to go through it in detail. Then run the code cell and continue to the subsequent discussion. End of explanation """ import numpy as np import matplotlib.pyplot as plt ## Return the electromagnetic scalar potential for a 2D harmonic oscillator, ## evaluated at 2D coordinates x and y (where x and y may be 2D arrays). def Phi_2dwell(x, y, omega1, omega2): return - 0.5 * (omega1**2 * x**2 + omega2**2 * y**2) # Return an array of zeros with the same array shape as x. def zerofield(x, y, omega1, omega_2): return np.zeros(x.shape) """ Explanation: Inputs and outputs of the schrodinger2d function The inputs to the schrodinger2d function that you need to be concerned with are Phi, Ax, Ay, and args. Helper functions For Phi, Ax, and Ay, the caller supplies helper functions. These helper funcitons are responsible for computing the scalar and vector potentials. For args, the caller supplies a tuple, containing additional parameters (if any) to give the helper functions. Each helper function should be a Python function that takes inputs (x, y, ...), where x and y are arrays of $x$ and $y$ coordinates, and the other inputs, denoted by ..., are the parameters specified in args. The helper function must return an array, of the same shape as $x$ and $y$, giving the potential at the specified points. Other inputs The other inputs to schrodinger2d can usually be omitted (i.e., left to their default values). These defaults specify a square computational cell of length L=1.0, with N=50 grid points in each direction. The coordinate origin, $x = y = 0$, is the center of the box. Dirichlet boundary conditions are imposed at the walls of the box. The solver finds the num=30 energy eigenstates whose energies are closest to E0=-100.0 (if the eigenenergies are all positive, this setting finds the 30 lowest-energy solutions). Return values The schrodinger2d function returns three values: E is an array of energy eigenvalues located by the numerical solver, sorted in increasing order. psi is an array containing the corresponding wavefunctions, such that psi[:,:,n] is a 2D array specifying the grid values of the n-th wavefunction. xgrid and ygrid are 2D arrays specifying the $x$ and $y$ grid coordinates, suitable for passing to pcolormesh. Example: 2D harmonic oscillator Consider the following potentials: $$\begin{aligned} \Phi &= - \frac{1}{2} \left(\omega_1^2 x^2 + \omega_2^2 y^2\right) \ A_x &= A_y = 0.\end{aligned}$$ This describes a 2D harmonic oscillator with different spring constants in the $x$ and $y$ direction. The energy spectrum should be $$E_{mn} = \hbar \omega_1 \left(m + \frac{1}{2}\right) + \hbar \omega_2 \left(n + \frac{1}{2}\right), \;\; m, n \in \mathbb{Z}.$$ We implement these potentials by writing the following helper functions: End of explanation """ omega1, omega2 = 50.0, 60.0 # Values of the omega1 and omega2 parameters ## Look carefully at show `schrodinger2d' is called. E, psi, x, y = schrodinger2d(Phi_2dwell, zerofield, zerofield, (omega1, omega2)) ## Plot the energy levels, and compare to the theoretical values. nstates = len(E) for m in range(5): for n in range(5): Eth = omega1*(m+0.5) + omega2*(n+0.5) plt.plot([0, nstates], [Eth, Eth], 'c--') plt.plot(E, 'o') plt.xlim(0, nstates); plt.ylim(0, E[-1]) plt.xlabel('Eigenvalue number') plt.ylabel('E') """ Explanation: Now let's check whether the numerical solver gives the expected spectrum: End of explanation """ plt.subplot(1, 2, 1) plt.axis("equal") plt.pcolor(x, y, abs(psi[:,:,0])**2) plt.subplot(1, 2, 2) plt.axis("equal") plt.pcolormesh(abs(psi[:,:,1])**2) """ Explanation: From the plot produced by the above code, you should see that the numerically obtained eigenenergies (plotted as dots) accurately matches the theoretical predictions (plotted as horizontal dashes). We can also inspect the spatial distributions of the eigenstates: End of explanation """ ## Plot Phi for a particular choice of parameters: V0, R1, R2, d = 1e5, 0.15, 0.4, 0.025 N = 80 coords = np.linspace(-0.5+1./(N+1), 0.5-1./(N+1), N) x, y = np.meshgrid(coords, coords) r = np.sqrt(x**2 + y**2) Phi = - V0 * (2 - np.tanh((r-R1)/d) + np.tanh((r-R2)/d)) grid = np.linspace(-0.5, 0.5, N+1) x, y = np.meshgrid(grid, grid) plt.pcolormesh(x, y, Phi) plt.axis("equal") plt.title("Heat map of $\Phi$") plt.xlabel("x"); plt.ylabel("y") plt.colorbar() """ Explanation: Task 1: Electron in a uniform magnetic field (8 marks) Now consider scalar and vector potentials of the form $$\begin{aligned} \Phi &= - \frac{1}{2} \omega_0^2 (x^2 + y^2) \ A_x &= - B_0 y \ A_y &= 0. \end{aligned}$$ The scalar potential acts as quadratic potential well, similar to the previous example except that it is isotropic. The vector potential generates a uniform out-of-plane magnetic field $\vec{B} = [0, 0, B_0]$ (you can verify this by calculating $\nabla \times \vec{A}$). Investigate: * The energy spectrum of the system for different values of $\omega_0$ and $B_0$ (you should look at "large" and "small" values of both parameters). * How the energy eigenfunctions are spatially distributed. Your answer should consist of text descriptions, accompanied by code to generate the plots supporting your findings. Task 2: Gauge invariance (4 marks) Take the scalar and vector potentials from Task 1, with the parameters fixed at, say, $\omega_0 = 100, B_0 = 1.0$ (you may use different parameters, if you wish). Now consider the gauge field $$\lambda(x,y) = ax + by,$$ where $a$ and $b$ are arbitrary constants. Demonstrate, numerically, that the different choices of $a$ and $b$ do not affect the energy eigenvalues, nor the energy eigenfunctions' probability densities. It is up to you to choose exactly what plots to generate to demonstrate this phenomenon. Task 3: The Aharonov-Bohm Effect (8 marks) Consider the following scalar potential: $$\Phi = - V_0 \left{2 - \tanh\left[\frac{r-R_1}{d}\right] + \tanh\left[\frac{r-R_2}{d}\right]\right}$$ where $r = \sqrt{x^2+y^2}$. This scalar potential generates an annulus of inner radius $R_1$ and outer radius $R_2$. Inside the annulus, the potential is $0$; outside, the potential is $-2V_0$. The scalar potential is plotted below: End of explanation """
jgarciab/wwd2017
class4/hw_3.ipynb
gpl-3.0
print("Figure 1") display(Image(url="http://www.datavis.ca/gallery/images/galvanic-3D.png",width=600)) print("Figure 2") display(Image(url="http://www.econoclass.com/images/statdrivers.gif")) """ Explanation: Assignment 1: Data visualization Explain what do you think that is wrong with the following figures and what kind of plot would you use. There are many correct ways to answer. Figure 1 What do you think this plot shows? answer here - What is wrong with the style? answer here - What is wrong (or can be improved) with the type of plot? answer here - What type of plot would you use and why? answer here Figure 2 What do you think this plot shows? answer here - What is wrong with the message it gives? answer here - What is wrong (or can be improved) with the type of plot? (https://en.wikipedia.org/wiki/Bar_chart) answer here End of explanation """ #Read data pd.read_stata("data/colombia.dta") #Discard the rows with "[No leer] Ambas" #How many people in the income group "Menos de 160.000" want to negociate? -> Our successes #How many people in the income group "Menos de 160.000" want to fight? #How many people are in the income group "Menos de 160.000"? -> Our number of trials #What is the probability that a random person in the group "Menos de 160.000" wants to negociate? -> This is our "p" #How many people in total want to negociate? #How many people in total want to fight? #What is the probability that a random person wants to negociate? -> This is the "p" of the entire population. #Calculate the RR #What's the null hypothesis? #What's the alternative hypothesis? #What's the p-value associated? -> Do the stats #What are the confidence intervals of our p? #What can we say? """ Explanation: Assignment 2: Binomial test Test if the poorest people are more likely to negotiate (df["colpaz1a"] == "Negociación"), when compared with the entire population. There are three options for the variable "colpaz1a": "Negociación", "Uso de la fuerza militar" and "[No leer] Ambas". Please discard the rows with "[No leer] Ambas" before the test. The column with the income is "q10new". The group with the lowest income is "Menos de 160.000" Answer the questions: How many people in the income group "Menos de 160.000" want to negociate? How many people in the income group "Menos de 160.000" want to fight? What is the probability that a random person in the group "Menos de 160.000" wants to negociate? -> This is our "p" How many people in total want to negociate? How many people in total want to fight? What is the probability that a random person wants to negociate? -> This is the "p" of the entire population. Calculate the RR What's the null hypothesis? What's the alternative hypothesis? What's the p-value associated? What are the confidence intervals of our p? What can we say? End of explanation """ #Read data df = pd.read_stata("data/colombia.dta") df = df.loc[df["colpaz1a"] != "[No leer] Ambas"] df = df.loc[df["q10new"] != "Ningún ingreso"] #Discard the rows with "[No leer] Ambas" df = df.dropna(subset=["colpaz1a","q10new"]) df["colpaz1a"].cat.remove_unused_categories() #Can we see a trend in the crosstab? a = pd.crosstab(df["colpaz1a"].astype(str),df["q10new"].astype(str)) #What does the Chi-square test say? import scipy.stats a2,p,b,exp = scipy.stats.chi2_contingency(a) #What are the ratios of observed/expected? print(a2,p,b) a/exp pd.read_csv("../class3/data/world_bank/data.csv") """ Explanation: Assignment 3: Chi-square test Test if there are interactions between income and how likely you are to negociate. There are three options for the variable "colpaz1a", "Negociación", "Uso de la fuerza militar" and "[No leer] Ambas". Please discard the rows with "[No leer] Ambas" before the test. The column with the income is "q10new". Answer the questions: Can we see a trend in the crosstab? What does the Chi-square test say? What are the ratios of observed/expected? End of explanation """ #1. Download your dataset for the quantitative design #2. Explain what type of variables you have #3. Fix the format to convert it into tidy data (Melt/Pivot). #4. Save your dataset into a file (so you don't have to do the other things every time) #5. Describe the data and visualize the relationship between all (or 10 if there are too many) variables with a scatter plot matrix or a correlation matrix #6. Do some other cool plot. """ Explanation: Assignment 4: Read, melt, pivot, groupby Download your dataset for the quantitative design Explain what type of variables you have Fix the format to convert it into tidy data (Melt/Pivot). Save your dataset into a file (so you don't have to do the other things every time) Describe the data and visualize the relationship between all (or 10 if there are too many) variables with a scatter plot matrix or a correlation matrix Do some other cool plot. Note: If your data is already tidy before step 3, perform steps 3 and 4 in this dataset: "data/cities.csv", a dataset with the distances between 11 cities. End of explanation """
Fifth-Cohort-Awesome/NightThree
three_arg.ipynb
mit
MovieTextFile = open("tmdb_5000_movies.csv") # for line in MovieTextFile: # print(line) # not quite right # type(MovieTextFile) """ Explanation: Goal 1 Injest file as pure text End of explanation """ import csv with open("tmdb_5000_movies.csv",encoding="utf8") as f: reader = csv.reader(f) MovieList = list(reader) MovieList[:5] """ Explanation: Import data as a list of lines End of explanation """ import pandas as pd movies = pd.read_csv("tmdb_5000_movies.csv") movieFrame = pd.DataFrame(movies) movieFrame[:5] """ Explanation: Import data as a data frame End of explanation """ #pull out genres array of JSON strings from data frame genres = movieFrame['genres'] # genresFrame = pd.DataFrame(genres) genres[:5] # Pull out list of names for each row of the data frame # Start with testing first row and iterating through JSON string import json genreList = [] genre = json.loads(genres[0]) for i,val in enumerate(genre): genreList.append(genre[i]['name']) genreList # Iterate through indices of genre array to create a list of lists of genre names import json genresAll = [] for k,x in enumerate(genres): genreList = [] genre = json.loads(genres[k]) for i,val in enumerate(genre): genreList.append(genre[i]['name']) genresAll.append(genreList) genresAll[:10] genreSeries['W'] = pd.Series(genresAll,index=movieFrame.index) genreFrame = pd.DataFrame(genreSeries['W'],columns=['GenreList']) genreFrame[:5] genreDummies = genreFrame.GenreList.astype(str).str.strip('[]').str.get_dummies(', ') genreDummies[:10] # append lists as a column at end of dataframe movieGenreFrame = pd.merge(movieFrame,genreFrame,how='inner',left_index=True, right_index=True) movieGenreFrame[:5] wideMovieFrame = pd.merge(movieGenreFrame,genreDummies,how='inner',left_index=True,right_index=True) wideMovieFrame[:5] """ Explanation: Goal 2 End of explanation """ longMovieFrame = pd.melt(wideMovieFrame, id_vars=movieGenreFrame.columns, value_vars=genreDummies.columns, var_name='Genre',value_name="genre_present") longMovieFrame[:10] # test results with 'Avatar' example longMovieFrame[longMovieFrame['title']=='Avatar'] # If only retaining "true" genres longMovieFrameTrimmed = longMovieFrame[longMovieFrame['genre_present']==1] longMovieFrameTrimmed[:5] """ Explanation: Goal 3 End of explanation """
GoogleCloudPlatform/vertex-ai-samples
notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb
apache-2.0
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 -U tensorflow $USER_FLAG -q ! pip3 install -U tensorflow-data-validation $USER_FLAG -q ! pip3 install -U tensorflow-transform $USER_FLAG -q ! pip3 install -U tensorflow-io $USER_FLAG -q ! pip3 install --upgrade google-cloud-aiplatform[tensorboard] $USER_FLAG -q ! pip3 install --upgrade google-cloud-pipeline-components $USER_FLAG -q """ Explanation: E2E ML on GCP: MLOps stage 3 : formalization: get started with Dataflow pipeline components <table align="left"> <td> <a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.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/ai/platform/notebooks/deploy-notebook?download_url=https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.ipynb"> <img src="https://cloud.google.com/ml-engine/images/colab-logo-32px.png" alt="Colab logo"> Colab logo Run in Colab </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/main/notebooks/community/ml_ops/stage3/get_started_with_dataflow_pipeline_components.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> <br/><br/><br/> Overview This tutorial demonstrates how to use Vertex AI for E2E MLOps on Google Cloud in production. This tutorial covers stage 3 : formalization: get started with Dataflow pipeline components. Dataset The dataset used for this tutorial is the GSOD dataset from BigQuery public datasets. The version of the dataset you use only the fields year, month and day to predict the value of mean daily temperature (mean_temp). Objective In this tutorial, you learn how to use prebuilt Google Cloud Pipeline Components for Dataflow. This tutorial uses the following Google Cloud ML services: Vertex AI Pipelines Google Cloud Pipeline Components Dataflow The steps performed include: Build an Apache Beam data pipeline. Encapsulate the Apache Beam data pipeline with a Dataflow component in a Vertex AI pipeline. Execute a Vertex AI pipeline. Installations Install the required packages for executing the notebook. End of explanation """ 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 Once you've installed the additional packages, you need to restart the notebook kernel so it can find the packages. End of explanation """ import os PROJECT_ID = "" if not os.getenv("IS_TESTING"): # Get your Google Cloud project ID from gcloud shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID: ", PROJECT_ID) """ Explanation: 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 and Dataflow API. 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"} """ Explanation: Otherwise, set your project ID here. 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 the timestamp 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 = False if not os.path.exists("/opt/deeplearning/metadata/env_version") and not os.getenv( "DL_ANACONDA_HOME" ): if "google.colab" in sys.modules: IS_COLAB = True 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" into the filter box, and select Vertex 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 """ if not os.path.exists("/opt/deeplearning/metadata/env_version"): if "google.colab" in sys.modules: ! gcloud config set project $PROJECT_ID """ Explanation: If you are using Colab Notebooks, set the project using gcloud config. End of explanation """ BUCKET_URI = "gs://[your-bucket-name]" # @param {type:"string"} if BUCKET_URI == "" or BUCKET_URI is None or BUCKET_URI == "gs://[your-bucket-name]": BUCKET_URI = "gs://" + PROJECT_ID + "aip-" + TIMESTAMP """ Explanation: Create a Cloud Storage bucket The following steps are required, regardless of your notebook environment. When you initialize the Vertex SDK for Python, you specify a Cloud Storage staging bucket. The staging bucket is where all the data associated with your dataset and model resources are retained across sessions. Set the name of your Cloud Storage bucket below. Bucket names must be globally unique across all Google Cloud projects, including those outside of your organization. End of explanation """ ! gsutil mb -l $REGION $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() if 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 If you don't know your service account, try to get your service account using gcloud command by executing the second cell below. 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 Vertex AI Pipelines Run the following commands to grant your service account access to read and write pipeline artifacts in the bucket that you created in the previous step -- you only need to run these once per service account. End of explanation """ import google.cloud.aiplatform as aip from google_cloud_pipeline_components.v1.dataflow import DataflowPythonJobOp from google_cloud_pipeline_components.v1.wait_gcp_resources import \ WaitGcpResourcesOp from kfp import dsl from kfp.v2 import compiler """ Explanation: Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants End of explanation """ aip.init(project=PROJECT_ID, 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 """ %%writefile wc.py # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """A minimalist word-counting workflow that counts words in Shakespeare. This is the first in a series of successively more detailed 'word count' examples. Next, see the wordcount pipeline, then the wordcount_debugging pipeline, for more detailed examples that introduce additional concepts. Concepts: 1. Reading data from text files 2. Specifying 'inline' transforms 3. Counting a PCollection 4. Writing data to Cloud Storage as text files To execute this pipeline locally, first edit the code to specify the output location. Output location could be a local file path or an output prefix on GCS. (Only update the output location marked with the first CHANGE comment.) To execute this pipeline remotely, first edit the code to set your project ID, runner type, the staging location, the temp location, and the output location. The specified GCS bucket(s) must already exist. (Update all the places marked with a CHANGE comment.) Then, run the pipeline as described in the README. It will be deployed and run using the Google Cloud Dataflow Service. No args are required to run the pipeline. You can see the results in your output bucket in the GCS browser. """ from __future__ import absolute_import import argparse import logging import re from past.builtins import unicode import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions def run(argv=None): """Main entry point; defines and runs the wordcount pipeline.""" parser = argparse.ArgumentParser() parser.add_argument('--input', dest='input', default='gs://dataflow-samples/shakespeare/kinglear.txt', help='Input file to process.') parser.add_argument('--output', dest='output', # CHANGE 1/5: The Google Cloud Storage path is required # for outputting the results. default='gs://YOUR_OUTPUT_BUCKET/AND_OUTPUT_PREFIX', help='Output file to write results to.') known_args, pipeline_args = parser.parse_known_args(argv) # pipeline_args.extend([ # # CHANGE 2/5: (OPTIONAL) Change this to DataflowRunner to # # run your pipeline on the Google Cloud Dataflow Service. # '--runner=DirectRunner', # # CHANGE 3/5: Your project ID is required in order to run your pipeline on # # the Google Cloud Dataflow Service. # '--project=SET_YOUR_PROJECT_ID_HERE', # # CHANGE 4/5: Your Google Cloud Storage path is required for staging local # # files. # '--staging_location=gs://YOUR_BUCKET_NAME/AND_STAGING_DIRECTORY', # # CHANGE 5/5: Your Google Cloud Storage path is required for temporary # # files. # '--temp_location=gs://YOUR_BUCKET_NAME/AND_TEMP_DIRECTORY', # '--job_name=your-wordcount-job', # ]) # We use the save_main_session option because one or more DoFn's in this # workflow rely on global context (e.g., a module imported at module level). pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True with beam.Pipeline(options=pipeline_options) as p: # Read the text file[pattern] into a PCollection. lines = p | ReadFromText(known_args.input) # Count the occurrences of each word. counts = ( lines | 'Split' >> (beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x)) .with_output_types(unicode)) | 'PairWithOne' >> beam.Map(lambda x: (x, 1)) | 'GroupAndSum' >> beam.CombinePerKey(sum)) # Format the counts into a PCollection of strings. def format_result(word_count): (word, count) = word_count return '%s: %s' % (word, count) output = counts | 'Format' >> beam.Map(format_result) # Write the output using a "Write" transform that has side effects. # pylint: disable=expression-not-assigned output | WriteToText(known_args.output) if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run() """ Explanation: Write the Apache Beam pipeline module First, you write the Python module for the Dataflow pipeline. Since it is a module, you additional add the if __name__ == '__main__': entry point and use argparse to pass command line arguments to the module. This module implements the Apache Beam word count example. End of explanation """ %%writefile requirements.txt apache-beam future """ Explanation: Write the requirements (installs) for the Apache Beam pipeline module Next, create the requirements.txt file to specify Python modules that are required to be installed for executing the Apache Beam pipeline module -- in this case, apache-beam is required. End of explanation """ GCS_WC_PY = BUCKET_URI + "/wc.py" ! gsutil cp wc.py $GCS_WC_PY GCS_REQUIREMENTS_TXT = BUCKET_URI + "/requirements.txt" ! gsutil cp requirements.txt $GCS_REQUIREMENTS_TXT GCS_WC_OUT = BUCKET_URI + "/wc_out.txt" """ Explanation: Copy python module and requirements file to Cloud Storage Next, you copy the Python module and requirements file to your Cloud Storage bucket. Additional, you set the Cloud Storage location for the output of the Apache Beam word count pipeline. End of explanation """ PIPELINE_ROOT = "{}/pipeline_root/dataflow_wc".format(BUCKET_URI) @dsl.pipeline(name="dataflow-wc", description="Dataflow word count component pipeline") def pipeline( python_file_path: str = GCS_WC_PY, project_id: str = PROJECT_ID, location: str = REGION, staging_dir: str = PIPELINE_ROOT, args: list = ["--output", GCS_WC_OUT, "--runner", "DataflowRunner"], requirements_file_path: str = GCS_REQUIREMENTS_TXT, ): dataflow_python_op = DataflowPythonJobOp( project=project_id, location=location, python_module_path=python_file_path, temp_location=staging_dir, requirements_file_path=requirements_file_path, args=args, ) _ = WaitGcpResourcesOp(gcp_resources=dataflow_python_op.outputs["gcp_resources"]) compiler.Compiler().compile(pipeline_func=pipeline, package_path="dataflow_wc.json") pipeline = aip.PipelineJob( display_name="dataflow_wc", template_path="dataflow_wc.json", pipeline_root=PIPELINE_ROOT, enable_caching=False, ) pipeline.run() ! gsutil cat {GCS_WC_OUT}* | head -n10 ! rm -f dataflow_wc.json wc.py requirements.txt """ Explanation: Create and execute the pipeline job In this example, the DataflowPythonJobOp component takes the following parameters: project_id: The project ID. location: The region. python_module_path: The Cloud Storage location of the Apache Beam pipeline. temp_location: The Cloud Storage temporary file workspace for the Apache Beam pipeline. requirements_file_path: The required Python modules to install. args: The arguments to pass to the Apache Beam pipeline. Learn more about Google Cloud Pipeline Component for Dataflow End of explanation """ pipeline.delete() """ Explanation: Delete a pipeline job After a pipeline job is completed, you can delete the pipeline job with the method delete(). Prior to completion, a pipeline job can be canceled with the method cancel(). End of explanation """ %%writefile split.py import argparse import logging import tensorflow_transform.beam as tft_beam from past.builtins import unicode import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io import WriteToText from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.options.pipeline_options import SetupOptions def run(argv=None): """Main entry point; defines and runs the wordcount pipeline.""" parser = argparse.ArgumentParser() parser.add_argument('--bq_table', dest='bq_table') parser.add_argument('--bucket', dest='bucket') args, pipeline_args = parser.parse_known_args(argv) logging.info("ARGS") logging.info(args) logging.info("PIPELINE ARGS") logging.info(pipeline_args) for i in range(0, len(pipeline_args), 2): if "--temp_location" == pipeline_args[i]: temp_location = pipeline_args[i+1] elif "--project" == pipeline_args[i]: project = pipeline_args[i+1] exported_train = args.bucket + '/exported_data/train' exported_eval = args.bucket + '/exported_data/eval' pipeline_options = PipelineOptions(pipeline_args) pipeline_options.view_as(SetupOptions).save_main_session = True with beam.Pipeline(options=pipeline_options) as pipeline: with tft_beam.Context(temp_location): raw_data_query = "SELECT {0},{1} FROM {2} LIMIT 500".format("CAST(station_number as STRING) AS station_number,year,month,day","mean_temp", args.bq_table) def parse_bq_record(bq_record): """Parses a bq_record to a dictionary.""" output = {} for key in bq_record: output[key] = [bq_record[key]] return output def split_dataset(bq_row, num_partitions, ratio): """Returns a partition number for a given bq_row.""" import json assert num_partitions == len(ratio) bucket = sum(map(ord, json.dumps(bq_row))) % sum(ratio) total = 0 for i, part in enumerate(ratio): total += part if bucket < total: return i return len(ratio) - 1 # Read raw BigQuery data. raw_train_data, raw_eval_data = ( pipeline | "Read Raw Data" >> beam.io.ReadFromBigQuery( query=raw_data_query, project=project, use_standard_sql=True, ) | "Parse Data" >> beam.Map(parse_bq_record) | "Split" >> beam.Partition(split_dataset, 2, ratio=[8, 2]) ) # Write raw train data to GCS . _ = raw_train_data | "Write Raw Train Data" >> beam.io.WriteToText( file_path_prefix=exported_train, file_name_suffix=".csv" ) # Write raw eval data to GCS . _ = raw_eval_data | "Write Raw Eval Data" >> beam.io.WriteToText( file_path_prefix=exported_eval, file_name_suffix=".csv" ) if __name__ == '__main__': logging.getLogger().setLevel(logging.INFO) run() """ Explanation: Write the Apache Beam pipeline module Next, you write the Python module for the Apache Beam pipeline. This module implements the a dataset split task into training and test data, and writes the split dataset as CSV files to a Cloud Storage bucket. In this example, the Python module will recieve some arguments for the pipeline from the command-line, which will be passed by the Dataflow pipeline component. Note: The Dataflow prebuilt component implicitly adds Dataflow-specific command-line arguments, such as project, location, runner, and temp_location. End of explanation """ %%writefile requirements.txt apache-beam tensorflow-transform==1.2.0 future """ Explanation: Write the requirements (installs) for the Apache Beam pipeline module Next, create the requirements.txt file to specify Python modules that are required to be installed for executing the Apache Beam pipeline module -- in this case, apache-beam and tensorflow-transform are required. End of explanation """ %%writefile setup.py import setuptools REQUIRED_PACKAGES = [ 'tensorflow-transform==1.2.0', 'future' ] PACKAGE_NAME = 'my_package' PACKAGE_VERSION = '0.0.1' setuptools.setup( name=PACKAGE_NAME, version=PACKAGE_VERSION, description='Demo for split transformation', install_requires=REQUIRED_PACKAGES, author="cdpe@google.com", packages=setuptools.find_packages() ) """ Explanation: Write the setup.py (installs) for the Dataflow workers Next, create the setup.py file to specify Python modules that are required to be installed for executing the Dataflow workers -- in this case, tensorflow-transform is required. End of explanation """ GCS_SPLIT_PY = BUCKET_URI + "/split.py" ! gsutil cp split.py $GCS_SPLIT_PY GCS_REQUIREMENTS_TXT = BUCKET_URI + "/requirements.txt" ! gsutil cp requirements.txt $GCS_REQUIREMENTS_TXT GCS_SETUP_PY = BUCKET_URI + "/setup.py" ! gsutil cp setup.py $GCS_SETUP_PY """ Explanation: Copy python module and requirements file to Cloud Storage Next, you copy the Python module, requirements and setup file to your Cloud Storage bucket. Additional, you set the Cloud Storage location for the output of the Apache Beam dataset split pipeline. End of explanation """ IMPORT_FILE = "bq://bigquery-public-data.samples.gsod" BQ_TABLE = "bigquery-public-data.samples.gsod" """ Explanation: Location of BigQuery training data. Now set the variable IMPORT_FILE to the location of the data table in BigQuery. End of explanation """ PIPELINE_ROOT = "{}/pipeline_root/dataflow_split".format(BUCKET_URI) @dsl.pipeline(name="dataflow-split", description="Dataflow split dataset") def pipeline( python_file_path: str = GCS_SPLIT_PY, project_id: str = PROJECT_ID, location: str = REGION, staging_dir: str = PIPELINE_ROOT, args: list = [ "--bucket", BUCKET_URI, "--bq_table", BQ_TABLE, "--runner", "DataflowRunner", "--setup_file", GCS_SETUP_PY, ], requirements_file_path: str = GCS_REQUIREMENTS_TXT, ): # DataflowPythonJobOp.component_spec.implementation.container.image = "gcr.io/ml-pipeline/google-cloud-pipeline-components:v0.2.0_dataflow_logs_fix" dataflow_python_op = DataflowPythonJobOp( project=project_id, location=location, python_module_path=python_file_path, temp_location=staging_dir, requirements_file_path=requirements_file_path, args=args, ) _ = WaitGcpResourcesOp(gcp_resources=dataflow_python_op.outputs["gcp_resources"]) compiler.Compiler().compile(pipeline_func=pipeline, package_path="dataflow_split.json") pipeline = aip.PipelineJob( display_name="dataflow_split", template_path="dataflow_split.json", pipeline_root=PIPELINE_ROOT, enable_caching=False, ) pipeline.run() ! gsutil ls {BUCKET_URI}/exported_data ! rm -f dataflow_split.json split.py requirements.txt """ Explanation: Create and execute the pipeline job In this example, the DataflowPythonJobOp component takes the following parameters: project_id: The project ID. location: The region. python_module_path: The Cloud Storage location of the Apache Beam pipeline. temp_location: The Cloud Storage temporary file workspace for the Apache Beam pipeline. requirements_file_path: The required Python modules to install. args: The arguments to pass to the Apache Beam pipeline. Learn more about Google Cloud Pipeline Component for Dataflow Additional, you add --runner=DataflowRunner to the input args, to tell the component to use Dataflow instead of DirectRunner for the Apache Beam job. End of explanation """ pipeline.delete() """ Explanation: Delete a pipeline job After a pipeline job is completed, you can delete the pipeline job with the method delete(). Prior to completion, a pipeline job can be canceled with the method cancel(). End of explanation """ # Warning: Setting this to true will delete everything in your bucket delete_bucket = False if delete_bucket or os.getenv("IS_TESTING"): ! gsutil rm -r $BUCKET_URI """ Explanation: 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: Dataset Cloud Storage Bucket End of explanation """
kdungs/teaching-SMD2-2016
assignments/1.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot') """ Explanation: Übungsblatt 1: Fehlerrechnung Aufgabe 1 Aufgabe 2 Aufgabe 3 End of explanation """ a1, a1_err = 2.0, 0.2 a2, a2_err = 1.0, 0.1 rho = -0.8 """ Explanation: Aufgabe 1 Gegeben sei eine parametrische Funktion $y = f(x)$, $y = 1 + a_1x + a_2x^2$ mit Parametern $a_1 = 2.0 ± 0.2$, $a_2 = 1.0 ± 0.1$ und Korrelationskoeffizient $ρ = −0.8$. End of explanation """
chrismcginlay/crazy-koala
jupyter/12_arrays_one.ipynb
gpl-3.0
amount1=int(input("Please enter amount 1:")) amount2=int(input("Please enter amount 2:")) amount3=int(input("Please enter amount 3:")) total = amount1 + amount2 + amount3 print("The total raised is", total) """ Explanation: Arrays Part 1 In Task 15 (Charity Collection) you probably used three variables for the different amounts of money raised. Run the following code to refresh your memory End of explanation """ length1=int(input("Please enter length 1:")) width1 =int(input("Please enter width 1:")) length2=int(input("Please enter length 2:")) width2 =int(input("Please enter width 2:")) area1 = length1 * width1 area2 = length2 * width2 print("Area 1 is", area1) print("Area 2 is", area2) """ Explanation: In task 16 (Calculate the Area of a Rectangle Part 2) you probably used different variables for the two rectangles. Run the following code to refresh your memory End of explanation """ # Working with Lists # P Thoresen # December 2013 names = ["Fred", "Sue", "Alan", "Mark", "Fiona", "Ian", "Edward", "Ruby", "Sean", "Sarah"] genders = ["M", "F", "M", "M","F", "M", "M", "F", "M", "F"] marks = [23, 54, 23, 76, 36, 35, 86, 25, 56, 87] print(names, genders, marks, sep='\n') #Just to show the arrays are set up properly """ Explanation: This is fine for programs that only need to process a small number of values, but becomes unwieldy with lots of values: ```python3 amount1=int(input("Please enter amount 1:")) amount2=int(input("Please enter amount 2:")) ... amount50=int(input("Please enter amount 50:")) total = amount1 + amount2 + ... + amount50 ``` If you had to write a program to accept 50 inputs like this, you would become quite frustrated. Surely there must be a better way? Of course there is. We can now introduce the idea of arrays which can be used efficiently instead of lots of separate variables. (Arrays in the Python language are technically called lists). Arrays Instead of lots of separate variables, arrays can be used instead. An array is a list of values: python3 names = ["Fred","Anna",...,"Mary"] #an array of strings tests = [45,34,...65] #an array of integers Each vaue can be accessed by its index number, which always starts counting from 0: |index|0|1|...|9| |-|-|-|-|-| |names|"Fred"|"Anna"|...|"Mary"| |tests|45|34|...|65| python3 names[0] #contains "Fred" names[1] #contains "Anna" ...etc. Arrays can usually used with loops to display and process all the data: ```python3 for pupil in range(10): #for each pupil from 0 to 9 print(names[pupil]) #print the name of that pupil total = 0 for pupil in range(10): #for each pupil from 0 to 9 total = total + tests[pupil] #add that pupil’s mark to the total average = total / 10 ``` Strings are actually arrays of characters: |name="fred"|index|0|1|2|3| |-|-|-|-|-|-| | |char|f|r|e|d| Variable Names To avoid confusion when writing programs, use singular and plurals when you name variables: variable name|one or many?|example ---|---|--- name|a single name|eg: name = "fred" age|a single age|eg: age = 14 names|an array of names|eg: names[4] = "sue" ages|an array of lengths|eg: ages[4] = 15 This makes is easier to remember whether a variable holds a single value or a list of values. Arrays in Python Please Run the following code. You can change the names, genders and marks if you want, but be very careful with all the quotes and brackes End of explanation """ print(names[0], marks[0]) print(name[1],marks[1]) print(len(names)) for pupil in range(10): print(pupil) for pupil in range(len(names)): print(pupil) for pupil in range(10): print(names[pupil],marks[pupil], sep=': ') for pupil in range(10): if genders[pupil]=="M": print(names[pupil], "is a boy") else: print(names[pupil], "is a girl") """ Explanation: Next, run each of the following lines of code in turn and examine the output carefully. You should be able to either predict or understand the output produced. End of explanation """ #List each pupil’s name, gender and test mark: #List the names and marks of each pupil, and if they have passed (50 marks or more) or failed: #List the names and marks of all the boys who have passed: #Count how many boys are in the class: #Count how many boys scored 50 or more: """ Explanation: Exercise 5 empty cells are provided below. In each cell, write, and test, commands to: 1. List each pupil’s name, gender and test mark: 2. List the names and marks of each pupil, and if they have passed (50 marks or more) or failed: 3. List the names and marks of all the boys who have passed: 4. Count how many boys are in the class: 5. Count how many boys scored 50 or more: End of explanation """ for pupil in range(10): print(names[pupil],marks[pupil]) """ Explanation: Formatted Output (Tables) Your programs from above should be displaying the correct results, but the output might be untidy: End of explanation """ for pupil in range(10): nicename = format(names[pupil], '10') #format pupil name nicemark = format(marks[pupil], '2') #format pupil mark print(nicename + nicemark) #print formatted data """ Explanation: These data can be displayed neatly using the format() function. You have already used the format() function to display numbers to two decimal points. The longest name is Edward – 6 characters. If all the names are printed out with 8 characters, and all the numbers with 2 characters, then the result will be a table with text left aligned and numbers right-aligned. End of explanation """ for pupil in range(10): print(format(names[pupil], '10') + format(marks[pupil],'2')) """ Explanation: Or more compactly: End of explanation """
tpospisi/FlexCoDE
vignettes/Custom Class.ipynb
gpl-2.0
import flexcode import numpy as np import xgboost as xgb from flexcode.regression_models import XGBoost, CustomModel """ Explanation: This notebook provides an example on how to use a custom class within Flexcode. <br> In order to be compatible, a regression method needs to have a fit and predict method implemented - i.e. model.fit() and model.predict() need to be the functions used for training and predicting respectively. We provide here an example with artifical data. <br> We compare the FlexZBoost (Flexcode with builtin XGBoost) with the custom class of FLexcode when passing XGBoost Regressor. The two should give basically identical results. End of explanation """ def generate_data(n_draws): x = np.random.normal(0, 1, n_draws) z = np.random.normal(x, 1, n_draws) return x, z x_train, z_train = generate_data(5000) x_validation, z_validation = generate_data(5000) x_test, z_test = generate_data(5000) """ Explanation: Data Creation End of explanation """ # Parameterize model model = flexcode.FlexCodeModel(XGBoost, max_basis=31, basis_system="cosine", regression_params={'max_depth': 3, 'learning_rate': 0.5, 'objective': 'reg:linear'}) # Fit and tune model model.fit(x_train, z_train) cdes_predict_xgb, z_grid = model.predict(x_test, n_grid=200) model.__dict__ import pickle pickle.dump(file=open('example.pkl', 'wb'), obj=model, protocol=pickle.HIGHEST_PROTOCOL) model = pickle.load(open('example.pkl', 'rb')) model.__dict__ cdes_predict_xgb, z_grid = model.predict(x_test, n_grid=200) """ Explanation: FlexZBoost End of explanation """ # Parameterize model my_model = xgb.XGBRegressor model_c = flexcode.FlexCodeModel(CustomModel, max_basis=31, basis_system="cosine", regression_params={'max_depth': 3, 'learning_rate': 0.5, 'objective': 'reg:linear'}, custom_model=my_model) # Fit and tune model model_c.fit(x_train, z_train) cdes_predict_custom, z_grid = model_c.predict(x_test, n_grid=200) """ Explanation: Custom Model Our custom model in this case is going to be XGBRegressor. <br> The only difference with the above is that we are going to use the CustomModel class and we are going to pass XGBRegressor as custom_model. After that, everything is exactly as above. <br> Parameters can be passed also in the same way as above. End of explanation """ np.max(np.abs(cdes_predict_custom - cdes_predict_xgb)) """ Explanation: The two conditional density estimates should be the same across the board. <br> We check the maximum difference in absolute value between the two. End of explanation """
pligor/predicting-future-product-prices
04_time_series_prediction/.ipynb_checkpoints/30_price_history_dataset_per_mobile_phone-arima-checkpoint.ipynb
agpl-3.0
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 = np.load(npz_full) dic.keys()[:10] """ Explanation: Actual Run End of explanation """ 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_key = dic.keys()[0] cur_key cur_sku = dic[cur_key][()] cur_sku.keys() train_mat = cur_sku['train'] train_mat.shape target_len inputs = train_mat[:, :-target_len] inputs.shape targets = train_mat[:, -target_len:] targets.shape easy_mode = False score_dic_filepath = data_path + "/arima/scoredic_easy_mode_{}_{}.npy".format(easy_mode, cur_key) 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=easy_mode) #4h 4min 51s / 108 cases => ~= 136 seconds per case ! arr = np.array(list(scoredic.iteritems())) arr.shape #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 """ args = np.argsort(filtered_arr[:, 1]) args filtered_arr[args[:10], 0] %%time with warnings.catch_warnings(): warnings.filterwarnings("ignore") ae = ArimaEstimator(p_auto_regression_order=4, d_integration_level=1, q_moving_average=3, easy_mode=False) print ae.fit(test_ins_vals, test_tars_vals).score(test_ins_vals, test_tars_vals) plt.figure(figsize=(15,7)) plt.plot(ae.preds.flatten(), label='preds') test_tars.plot(label='real') plt.legend() plt.show() """ Explanation: Conclusion If you are training in easy mode then what you get at the end is that the model only cares for the previous value in order to do its predictions and this makes it much easier for everybody but in reality we might not have advantage Trying End of explanation """ from arima.arima_testing import ArimaTesting best_params, target_len, npz_full %%time keys, scores, preds = ArimaTesting.full_testing(best_params=best_params, target_len=target_len, npz_full=npz_full) # render graphs here score_arr = np.array(scores) np.mean(score_arr[np.logical_not(score_arr != score_arr)]) """ Explanation: All tests End of explanation """
google-research/google-research
cell_embedder/CellEmbedder.ipynb
apache-2.0
#@title Default title text # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2018 Google LLC. Licensed under the Apache License, Version 2.0 (the "License"); End of explanation """ !pip install --upgrade tf_slim from google.colab import drive import glob import matplotlib.pyplot as plt import numpy as np import os import PIL.Image import tensorflow.compat.v1 as tf import tf_slim as slim # Get slim inception code # from tf_slim.nets import inception # throws error no attribute 'inception_v4_arg_scope' if not os.path.exists('models/research/slim'): !git clone https://github.com/tensorflow/models/ old_cwd = os.getcwd() os.chdir('models/research/slim') from nets import inception os.chdir(old_cwd) # Download inceptionv4 checkpoint !wget http://download.tensorflow.org/models/inception_v4_2016_09_09.tar.gz !tar -xvzf inception_v4_2016_09_09.tar.gz """ Explanation: Install + Imports End of explanation """ #@title Connect to Drive (Run this cell once) drive.mount('/content/gdrive') # Verify folder exists after adding the shared folder to your drive. !ls gdrive/My\ Drive/cell_embedder_colab #@title Note: Change path to copy images+weights from Drive. (Run once) !cp -R gdrive/My\ Drive/cell_embedder_colab* . """ Explanation: Add path to data and projection weights. NOTE: Data and weights are shared in this folder. Add these to your Google Drive by selecting "Add shortcut to Drive" before running these cells. End of explanation """ DATA_DIR = 'cell_embedder_colab/' # NOTE - You need to set this to the location of the data. IMAGES_DIR = os.path.join(DATA_DIR, 'imgs/fullres_8bit_png_bbbc025') RANDOM_PROJECTION_CKPT = os.path.join( DATA_DIR, 'random_projection/random_projection.ckpt') INCEPTION_V4_CKPT = 'inception_v4.ckpt' # This is downloaded in the installs. #@title Helper functions def load_image(file_path): with PIL.Image.open(file_path) as im: im = np.asarray(im) return im def build_inceptionv4_rand64_tower(inputs, is_training=False): """Builds an inceptionv4 rand64 tower starting from image tensor. The tower consists of an Inception v4 base, and 1 fully connected layer reducing output dim to 64, and a normalization layer. Loss is not included. Args: inputs: An input dictionary mapping key to a tensor of input images i.e. {IMAGE_KEY: 4D tensor of (num, h, w, c)}. is_training: (bool) Specifies if it is training phase. Returns: (tensor) A tensor of embeddings. (dict) A dictionary mapping endpoint layer names to activation tensors. """ with slim.arg_scope(inception.inception_v4_arg_scope()): _, activations = inception.inception_v4(inputs[IMAGE_KEY], num_classes=1001, is_training=is_training) net = activations['PreLogitsFlatten'] with slim.arg_scope([slim.fully_connected], activation_fn=None): net = slim.fully_connected(net, 64, scope='fc0') activations['fc0'] = net net = tf.nn.l2_normalize(net, dim=-1, name='embed_norm') net = tf.reshape(net, [-1, 64]) activations['embed_norm'] = net return net, activations #@title Load Images (sorted by stain names) image_fnames = sorted(glob.glob('{}/*.png'.format(IMAGES_DIR))) print(image_fnames) np_images = [] plt.figure(figsize=(20, 15)) for i, img_fname in enumerate(image_fnames): np_images.append(load_image(img_fname)) plt.subplot(1, len(image_fnames), i+1) plt.imshow(np_images[-1]) np_images = np.array(np_images) np_images = np.expand_dims(np_images, axis=3) print(np_images.shape) NUM_STAINS, IMG_HEIGHT, IMG_WIDTH = np_images.shape[0:3] # The order in which you want the embeddings for each stain. Here embedding for # img Stack00002.png (DAPI) will come first in the embedding. STAIN_ORDER = [2,3,4,0,1] print(NUM_STAINS, IMG_HEIGHT, IMG_WIDTH) #@title Build model and intialize weights. (Run once) IMAGE_KEY = 'images' graph = tf.Graph() with graph.as_default(): images_ph = tf.placeholder(tf.float32, shape=(None, IMG_HEIGHT, IMG_WIDTH, 1)) # Resize to 299, 299. This is the input image size for inception. images_small = tf.image.resize_images( images_ph, [299, 299], method=tf.image.ResizeMethod.AREA) # Adjust pixel brightness to [0, 1] images_small /= 255.0 # Subtract 0.5 and multiply by 2.0 to keep it within [-1, 1] images_small -= 0.5 images_small *= 2.0 # Assert image is in [-1, 1]. Add an epsilon on either bound for edge cases. epsilon = 0.01 assert_min = tf.assert_greater_equal(tf.reduce_min(images_small), -(1 + epsilon)) assert_max = tf.assert_less_equal(tf.reduce_max(images_small), (1 + epsilon)) with tf.control_dependencies([assert_min, assert_max]): images_small = tf.identity(images_small) single_stain_images = tf.tile(images_small, [1, 1, 1, 3]) inputs = {IMAGE_KEY: single_stain_images} embed, _ = build_inceptionv4_rand64_tower(inputs, is_training=False) assignment_inception_map = {} assignment_projection_map = {} for v in slim.get_model_variables(): if v.op.name.startswith('InceptionV4'): assignment_inception_map[v.op.name] = v.op.name else: assignment_projection_map[v.op.name] = v.op.name tf.train.init_from_checkpoint(INCEPTION_V4_CKPT, assignment_inception_map) tf.train.init_from_checkpoint(RANDOM_PROJECTION_CKPT, assignment_projection_map) # We get 1 embedding for each stain. Concatenate the stain embeddings # to get 1 embedding for the entire image. This will be of dimension # size_of_embedding (64) x num_stains. single_stain_embeds = tf.split(embed, NUM_STAINS) stain_concat_embed = tf.concat(single_stain_embeds, 1) sess = tf.Session(graph=graph) saver = tf.train.Saver() init_op = tf.global_variables_initializer() sess.run(init_op) def get_ordered_embeddings(input_imgs, images_ph=images_ph,sess=sess): stain_embeds, concat_embed = sess.run([single_stain_embeds, stain_concat_embed], feed_dict={images_ph: input_imgs}) ordered_tf_embeds = np.concatenate([stain_embeds[i] for i in STAIN_ORDER], axis=1) return ordered_tf_embeds """ Explanation: Load images and build model End of explanation """ embeds = get_ordered_embeddings(np_images) print(embeds[0][:10]) plt.figure(figsize=(30,10)) plt.plot(embeds.T, 'b-o') """ Explanation: Get Embeddings End of explanation """
xdnian/pyml
assignments/solutions/ex03_sample_solution.ipynb
mit
%load_ext watermark %watermark -a '' -u -d -v -p numpy,pandas,matplotlib,scipy,sklearn %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: Assignment 3 - basic classifiers Math practice and coding application for main classifiers introduced in Chapter 3 of the Python machine learning book. Weighting Note that this assignment is more difficult than the previous ones, and thus has a higher weighting 3 and longer duration (3 weeks). Each one of the previous two assignments has a weighting 1. Specifically, the first 3 assignments contribute to your continuous assessment as follows: Assignment weights: $w_1 = 1, w_2 = 1, w_3 = 3$ Assignment grades: $g_1, g_2, g_3$ Weighted average: $\frac{1}{\sum_i w_i} \times \sum_i \left(w_i \times g_i \right)$ Future assignments will be added analogously. RBF kernel (20 points) Show that a Gaussian RBF kernel can be expressed as a dot product: $$ K(\mathbf{x}, \mathbf{y}) = e^\frac{-|\mathbf{x} - \mathbf{y}|^2}{2} = \phi(\mathbf{x})^T \phi(\mathbf{y}) $$ by spelling out the mapping function $\phi$. For simplicity * you can assume both $\mathbf{x}$ and $\mathbf{y}$ are 2D vectors $ x = \begin{pmatrix} x_1 \ x_2 \end{pmatrix} , \; y = \begin{pmatrix} y_1 \ y_2 \end{pmatrix} $ * we use a scalar unit variance here even though the proof can be extended for vectors $\mathbf{x}$ $\mathbf{y}$ and general covariance matrices. Hint: use Taylor series expansion of the exponential function Answer $$ e^\frac{-|\mathbf{x} - \mathbf{y}|^2}{2} = e^{-\frac{|\mathbf{x}|^2}{2} - \frac{|\mathbf{y}|^2}{2} + \mathbf{x}^T \mathbf{y}} = e^{-\frac{|\mathbf{x}|^2}{2}} e^{-\frac{|\mathbf{y}|^2}{2}} e^{\mathbf{x}^T \mathbf{y}} $$ Recall (from calculus) that the Taylor series expansion of the exp function is: $$ e^z = \sum_{k=0}^\infty \frac{z^k}{k!} $$ Thus $$ \begin{align} e^\frac{-|\mathbf{x} - \mathbf{y}|^2}{2} &= \sum_{k=0}^\infty \frac{\left( \mathbf{x}^T \mathbf{y} \right)^k}{k!} e^{-\frac{|\mathbf{x}|^2}{2}} e^{-\frac{|\mathbf{y}|^2}{2}} \ &= \sum_{k=0}^\infty \frac{\left( x_1 y_1 + x_2 y_2 \right)^k}{k!} e^{-\frac{|\mathbf{x}|^2}{2}} e^{-\frac{|\mathbf{y}|^2}{2}} \ &= \sum_{k=0}^\infty \frac{\sum_{\ell = 0}^{k} C_\ell^k (x_1 y_1)^\ell (x_2 y_2)^{k-\ell}}{k!} e^{-\frac{|\mathbf{x}|^2}{2}} e^{-\frac{|\mathbf{y}|^2}{2}} \end{align} $$ From this we can see: $$ \phi(\mathbf{x}) = e^{-\frac{|\mathbf{x}|^2}{2}} \biguplus_{k=0}^\infty \biguplus_{\ell = 0}^{k} \frac{\sqrt{C_\ell^k} x_1^\ell x_2^{k-\ell}}{\sqrt{k!}} $$ , where $\biguplus$ means ordered enumeration of vector components, e.g. $$ \biguplus_{k=0}^2 x_k = \begin{pmatrix} x_0 \ x_1 \ x_2 \end{pmatrix} $$ And $$ \biguplus_{k=0}^2 \biguplus_{\ell=0}^k x_{k\ell} = \begin{pmatrix} x_{00} \ x_{10} \ x_{11} \ x_{20} \ x_{21} \ x_{22} \end{pmatrix} $$ Kernel SVM complexity (10 points) How would the complexity (in terms of number of parameters) of a trained kernel SVM change with the amount of training data, and why? Note that the answer may depend on the specific kernel used as well as the amount of training data. Consider specifically the following types of kernels $K(\mathbf{x}, \mathbf{y})$. * linear: $$ K\left(\mathbf{x}, \mathbf{y}\right) = \mathbf{x}^T \mathbf{y} $$ * polynomial with degree $q$: $$ K\left(\mathbf{x}, \mathbf{y}\right) = (\mathbf{x}^T\mathbf{y} + 1)^q $$ * RBF with distance function $D$: $$ K\left(\mathbf{x}, \mathbf{y} \right) = e^{-\frac{D\left(\mathbf{x}, \mathbf{y} \right)}{2s^2}} $$ Answer Parametric versus non-parametric As a quick recap of the lecture slides, machine learning models lay on a spectrum of being parametric versus non-parametric. Two extreme examples are below. How about SVM with different kernels above? Extreme end of being parametric Linear classifiers such as perceptron has a fixed number of parameters $\mathbf{w}$ regardless of the size of the training data. Extreme end of being non-parametric KNN has no parameters and rely entirely on the training data. One way to look at this is to treat the entire training data as the parameters for KNN. RBF kernel projects to an infinite dimensional output space, so the parameter complexity depends entirely on the amount of training data, i.e. the Gram matrix (see IML Chapter 13) with dimension $N \times N$ where $N$ is the number of training samples: $$ K_{ts} = K(\mathbf{x}^{(t)}, \mathbf{x}^{(s)}) $$ Both linear and polynomial kernels project to a finite dimensional output/mapped space. In particular, the linear kernel remains in the orignal space. Thus, the number of parameters is decided by the dimensionality of the output space. So, Kernel SVM is more non-parametric for RBF kernel but more parametric for linear/polynomial kernels. Gaussian density Bayes (30 points) $$ p\left(\Theta | \mathbf{X}\right) = \frac{p\left(\mathbf{X} | \Theta\right) p\left(\Theta\right)}{p\left(\mathbf{X}\right)} $$ Assume both the likelihood and prior have Gaussian distributions: $$ \begin{align} p(\mathbf{X} | \Theta) &= \frac{1}{(2\pi)^{N/2}\sigma^N} \exp\left(-\frac{\sum_{t=1}^N (\mathbf{x}^{(t)} - \Theta)^2}{2\sigma^2}\right) \ p(\Theta) &= \frac{1}{\sqrt{2\pi}\sigma_0} \exp\left( -\frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right) \end{align} $$ Derive $\Theta$ from the dataset $\mathbf{X}$ via the following methods: ML (maximum likelihood) estimation $$ \Theta_{ML} = argmax_{\Theta} p(\mathbf{X} | \Theta) $$ MAP estimation $$ \begin{align} \Theta_{MAP} &= argmax_{\Theta} p(\Theta | \mathbf{X}) \ &= argmax_{\Theta} p(\mathbf{X} | \Theta) p(\Theta) \end{align} $$ Bayes estimation $$ \begin{align} \Theta_{Bayes} &= E(\Theta | \mathbf{X}) \ &= \int \Theta p(\Theta | \mathbf{X}) d\Theta \end{align} $$ Answer As a common trick, to maximize $\exp(f)\exp(g)$, we can maximize $\log\left(\exp(f)\exp(g)\right) = \log\left(\exp(f+g)\right) = f+g$. ML $$ \begin{align} \Theta_{ML} &= argmax_{\Theta} p(\mathbf{X} | \Theta) \ &= argmax_{\Theta} \log(p(\mathbf{X} | \Theta)) \ &= argmax_{\Theta} \left( -\log\left((2\pi)^{N/2} \sigma^N\right) - \frac{1}{2\sigma^2} \sum_{t=1}^N \left( \mathbf{x}^{(t)} - \Theta \right)^2 \right) \ &= argmin_{\Theta} \sum_{t=1}^N \left( \mathbf{x}^{(t)} - \Theta \right)^2 \end{align} $$ Take derivate $$ 0 = \frac{\partial \sum_{t=1}^N \left( \mathbf{x}^{(t)} - \Theta \right)^2 }{\partial \Theta} = 2 \sum_{t=1}^N \left( \Theta - \mathbf{x}^{(t)} \right) $$ We know $$ \Theta_{ML} =\frac{\sum_{t=1}^N \mathbf{x}^{(t)}}{N} $$ MAP $$ \begin{align} \Theta_{MAP} &= argmax_{\Theta} p(\Theta | \mathbf{X}) \ &= argmax_{\Theta} p(\mathbf{X} | \Theta) p(\Theta) \ &= argmax_{\Theta} \left( \log\left(p(\mathbf{X} | \Theta)\right) + \log\left(p(\Theta)\right) \right) \ &= argmax_{\Theta} \left( -\log\left((2\pi)^{N/2}\sigma^N \right) -\frac{\sum_{t=1}^N \left(\mathbf{x}^{(t)} - \Theta\right)^2}{2\sigma^2} -\log\left(\sqrt{2\pi}\sigma_0\right) -\frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right) \ &= argmin_{\Theta} \left( \frac{1}{2\sigma^2} \sum_{t=1}^N \left( \mathbf{x}^{(t)} - \Theta \right)^2 + \frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right) \end{align} $$ Take derivate: $$ 0 = \frac{\partial \left( \frac{1}{2\sigma^2} \sum_{t=1}^N \left( \mathbf{x}^{(t)} - \Theta \right)^2 + \frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right)} {\partial \Theta} = \frac{1}{\sigma^2} \sum_{t=1}^N \left( \Theta - \mathbf{x}^{(t)} \right) + \frac{1}{\sigma_0^2} \left( \Theta - \mu_0 \right) $$ We have $$ \Theta_{MAP} = \frac{N/\sigma^2}{N/\sigma^2 + 1/\sigma_0^2} \mathbf{m} + \frac{1/\sigma_0^2}{N/\sigma^2 + 1/\sigma_0^2} \mu_0 $$ , where $$ \mathbf{m} = \frac{1}{N} \sum_{t=1}^N \mathbf{x}^{(t)} $$ Alternatively Note that the product of two Gaussians is still a Gaussian: $$ \begin{align} p(\Theta | \mathbf{X}) & = \frac{p(\mathbf{X} | \Theta) p(\Theta)}{p(\mathbf{X})} \ &= \frac{1}{(2\pi)^{N/2}\sigma^N \sqrt{2\pi}\sigma_0 p(\mathbf{X})} \exp\left(-\frac{\sum_{t=1}^N (\mathbf{x}^{(t)} - \Theta)^2}{2\sigma^2}\right) \exp\left( -\frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right) \ &= \frac{1}{(2\pi)^{N/2}\sigma^N \sqrt{2\pi}\sigma_0 p(\mathbf{X})} \exp\left(-\frac{\sum_{t=1}^N (\mathbf{x}^{(t)} - \Theta)^2}{2\sigma^2} -\frac{(\Theta - \mu_0)^2}{2\sigma_0^2} \right) \ &= \frac{1}{(2\pi)^{N/2}\sigma^N \sqrt{2\pi}\sigma_0 p(\mathbf{X})} \exp\left(-\frac{\sum_{t=1}^N \sigma_0^2 (\Theta - \mathbf{x}^{(t)})^2 + \sigma^2 (\Theta - \mu_0)^2}{2(\sigma\sigma_0)^2} \right) \ &= \frac{1}{(2\pi)^{N/2}\sigma^N \sqrt{2\pi}\sigma_0 p(\mathbf{X})} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \left( \left(\Theta - \Theta_{MAP}\right)^2 + \left(-\Theta_{MAP}^2 + \sigma_0^2 \sum_{t=1}^N \left(\mathbf{x}^{(t)}\right)^2 + \sigma^2 -mu_0^2\right) \right) \right) \ &= \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \left(\Theta - \Theta_{MAP}\right)^2 \right) \ \frac{1}{\bigtriangleup} &= \frac{1}{(2\pi)^{N/2}\sigma^N \sqrt{2\pi}\sigma_0 p(\mathbf{X})} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \left(-\Theta_{MAP}^2 + \sigma_0^2 \sum_{t=1}^N \left(\mathbf{x}^{(t)}\right)^2 + \sigma^2 -mu_0^2\right) \right) \end{align} $$ $\bigtriangleup$ is a constant (with $\Theta$), so the mean $\Theta_{MAP}$ will maximize $p(\Theta | \mathbf{X})$. Bayes From the single Gaussian interpretation of $p(\Theta | \mathbf{X})$ above we know: $$ \begin{align} \Theta_{Bayes} &= E(\Theta | \mathbf{X}) \ &= \int \Theta p(\Theta | \mathbf{X}) d\Theta \ &= \int \Theta \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \left(\Theta - \Theta_{MAP}\right)^2 \right) d\Theta \ &= \int \left( \Theta + \Theta_{MAP} \right) \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \Theta^2 \right) d\Theta \ &= \int \Theta \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \Theta^2 \right) d\Theta + \Theta_{MAP} \int \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \Theta^2 \right) d\Theta \end{align} $$ The first term above is an odd symmetric function, so the integral is zero: $$ 0 = \int \Theta \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \Theta^2 \right) d\Theta $$ And the integral part of the second term above is $1$ since the original density function is normalized: $$ 1 = \int \frac{1}{\bigtriangleup} \exp \left( -\frac{N\sigma_0^2 + \sigma^2}{2(\sigma\sigma_0)^2} \Theta^2 \right) d\Theta $$ Thus $\Theta_{Bayes} = \Theta_{MAP}$ Hand-written digit classification (40 points) In the textbook sample code we applied different scikit-learn classifers for the Iris data set. In this exercise, we will apply the same set of classifiers over a different data set: hand-written digits. Please write down the code for different classifiers, choose their hyper-parameters, and compare their performance via the accuracy score as in the Iris dataset. Which classifier(s) perform(s) the best and worst, and why? The classifiers include: * perceptron * logistic regression * SVM * decision tree * random forest * KNN * naive Bayes The dataset is available as part of scikit learn, as follows. End of explanation """ from sklearn.datasets import load_digits digits = load_digits() X = digits.data # training data y = digits.target # training label print(X.shape) print(y.shape) """ Explanation: Load data End of explanation """ import matplotlib.pyplot as plt import pylab as pl num_rows = 4 num_cols = 5 fig, ax = plt.subplots(nrows=num_rows, ncols=num_cols, sharex=True, sharey=True) ax = ax.flatten() for index in range(num_rows*num_cols): img = digits.images[index] label = digits.target[index] ax[index].imshow(img, cmap='Greys', interpolation='nearest') ax[index].set_title('digit ' + str(label)) ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() plt.show() """ Explanation: Visualize data End of explanation """ #Your code comes here """ Explanation: Answer Date Preprocessing Hint: How you divide training and test data set? And apply other techinques we have learned if needed. You could take a look at the Iris data set case in the textbook. End of explanation """ if Version(sklearn_version) < '0.18': from sklearn.cross_validation import train_test_split else: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0) num_training = y_train.shape[0] num_test = y_test.shape[0] print('training: ' + str(num_training) + ', test: ' + str(num_test)) """ Explanation: Data sets: training versus test End of explanation """ from sklearn.preprocessing import StandardScaler scaling_option = 'standard'; if scaling_option == 'standard': sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) else: X_train_std = X_train X_test_std = X_test """ Explanation: Data scaling End of explanation """ from sklearn.metrics import accuracy_score """ Explanation: Accuracy score End of explanation """ from sklearn.linear_model import Perceptron # training ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0) _ = ppn.fit(X_train_std, y_train) # prediction y_pred = ppn.predict(X_test_std) # print('Misclassified samples: %d out of %d' % ((y_test != y_pred).sum(), y_test.shape[0])) print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) """ Explanation: Classifier #1 Perceptron Perceptron End of explanation """ # training from sklearn.linear_model import LogisticRegression lr = LogisticRegression(C=1000.0, random_state=0) _ = lr.fit(X_train_std, y_train) # prediction y_pred = lr.predict(X_test_std) print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) """ Explanation: Classifier #2 Logistic Regression Logistic regression End of explanation """ from sklearn.svm import SVC kernels = ['linear', 'rbf'] for kernel in kernels: svm = SVC(kernel=kernel, C=1.0, random_state=0) # training svm.fit(X_train_std, y_train) # testing y_pred = svm.predict(X_test_std) print('Accuracy for ' + kernel + ' kernel: %.2f' % accuracy_score(y_test, y_pred)) """ Explanation: Classifier #3 SVM SVM End of explanation """ from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy', random_state=1) # training tree.fit(X_train, y_train) # testing y_pred = tree.predict(X_test) print('Accuracy: %2f' % accuracy_score(y_test, y_pred)) """ Explanation: Classifier #4 Decision Tree Decision tree End of explanation """ from sklearn.ensemble import RandomForestClassifier num_estimators = [1, 5, 10, 20, 40] for n_estimators in num_estimators: forest = RandomForestClassifier(criterion='entropy', n_estimators=n_estimators, random_state=1) # training forest.fit(X_train, y_train) # testing y_pred = forest.predict(X_test) print('Accuracy for %d estimators: %2f' % (n_estimators, accuracy_score(y_test, y_pred))) """ Explanation: Classifer #5 Random Forest Random forest End of explanation """ from sklearn.neighbors import KNeighborsClassifier num_neighbors = [1, 5, 10, 20, 100] for n_neighbors in num_neighbors: knn = KNeighborsClassifier(n_neighbors=n_neighbors, p=2, metric='minkowski') # training knn.fit(X_train_std, y_train) # testing y_pred = knn.predict(X_test_std) print('Accuracy for %d neighbors: %2f' % (n_neighbors, accuracy_score(y_test, y_pred))) """ Explanation: Classifier #6 KNN KNN End of explanation """ from sklearn.naive_bayes import GaussianNB gnb = GaussianNB() _ = gnb.fit(X_train_std, y_train) y_pred = gnb.predict(X_test_std) print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) """ Explanation: Classifier #7 Naive Bayes Naive Bayes End of explanation """
Abasyoni/dynet
examples/python/tutorials/RNNs.ipynb
apache-2.0
# we assume that we have the dynet module in your path. # OUTDATED: we also assume that LD_LIBRARY_PATH includes a pointer to where libcnn_shared.so is. from dynet import * """ Explanation: RNNs tutorial End of explanation """ pc = ParameterCollection() NUM_LAYERS=2 INPUT_DIM=50 HIDDEN_DIM=10 builder = LSTMBuilder(NUM_LAYERS, INPUT_DIM, HIDDEN_DIM, pc) # or: # builder = SimpleRNNBuilder(NUM_LAYERS, INPUT_DIM, HIDDEN_DIM, pc) """ Explanation: An LSTM/RNN overview: An (1-layer) RNN can be thought of as a sequence of cells, $h_1,...,h_k$, where $h_i$ indicates the time dimenstion. Each cell $h_i$ has an input $x_i$ and an output $r_i$. In addition to $x_i$, cell $h_i$ receives as input also $r_{i-1}$. In a deep (multi-layer) RNN, we don't have a sequence, but a grid. That is we have several layers of sequences: $h_1^3,...,h_k^3$ $h_1^2,...,h_k^2$ $h_1^1,...h_k^1$, Let $r_i^j$ be the output of cell $h_i^j$. Then: The input to $h_i^1$ is $x_i$ and $r_{i-1}^1$. The input to $h_i^2$ is $r_i^1$ and $r_{i-1}^2$, and so on. The LSTM (RNN) Interface RNN / LSTM / GRU follow the same interface. We have a "builder" which is in charge of creating definining the parameters for the sequence. End of explanation """ s0 = builder.initial_state() x1 = vecInput(INPUT_DIM) s1=s0.add_input(x1) y1 = s1.output() # here, we add x1 to the RNN, and the output we get from the top is y (a HIDEN_DIM-dim vector) y1.npvalue().shape s2=s1.add_input(x1) # we can add another input y2=s2.output() """ Explanation: Note that when we create the builder, it adds the internal RNN parameters to the ParameterCollection. We do not need to care about them, but they will be optimized together with the rest of the network's parameters. End of explanation """ print s2.h() """ Explanation: If our LSTM/RNN was one layer deep, y2 would be equal to the hidden state. However, since it is 2 layers deep, y2 is only the hidden state (= output) of the last layer. If we were to want access to the all the hidden state (the output of both the first and the last layers), we could use the .h() method, which returns a list of expressions, one for each layer: End of explanation """ # create a simple rnn builder rnnbuilder=SimpleRNNBuilder(NUM_LAYERS, INPUT_DIM, HIDDEN_DIM, pc) # initialize a new graph, and a new sequence rs0 = rnnbuilder.initial_state() # add inputs rs1 = rs0.add_input(x1) ry1 = rs1.output() print "all layers:", s1.h() print s1.s() """ Explanation: The same interface that we saw until now for the LSTM, holds also for the Simple RNN: End of explanation """ rnn_h = rs1.h() rnn_s = rs1.s() print "RNN h:", rnn_h print "RNN s:", rnn_s lstm_h = s1.h() lstm_s = s1.s() print "LSTM h:", lstm_h print "LSTM s:", lstm_s """ Explanation: To summarize, when calling .add_input(x) on an RNNState what happens is that the state creates a new RNN/LSTM column, passing it: 1. the state of the current RNN column 2. the input x The state is then returned, and we can call it's output() method to get the output y, which is the output at the top of the column. We can access the outputs of all the layers (not only the last one) using the .h() method of the state. .s() The internal state of the RNN may be more involved than just the outputs $h$. This is the case for the LSTM, that keeps an extra "memory" cell, that is used when calculating $h$, and which is also passed to the next column. To access the entire hidden state, we use the .s() method. The output of .s() differs by the type of RNN being used. For the simple-RNN, it is the same as .h(). For the LSTM, it is more involved. End of explanation """ s2=s1.add_input(x1) s3=s2.add_input(x1) s4=s3.add_input(x1) # let's continue s3 with a new input. s5=s3.add_input(x1) # we now have two different sequences: # s0,s1,s2,s3,s4 # s0,s1,s2,s3,s5 # the two sequences share parameters. assert(s5.prev() == s3) assert(s4.prev() == s3) s6=s3.prev().add_input(x1) # we now have an additional sequence: # s0,s1,s2,s6 s6.h() s6.s() """ Explanation: As we can see, the LSTM has two extra state expressions (one for each hidden layer) before the outputs h. Extra options in the RNN/LSTM interface Stack LSTM The RNN's are shaped as a stack: we can remove the top and continue from the previous state. This is done either by remembering the previous state and continuing it with a new .add_input(), or using we can access the previous state of a given state using the .prev() method of state. Initializing a new sequence with a given state When we call builder.initial_state(), we are assuming the state has random /0 initialization. If we want, we can specify a list of expressions that will serve as the initial state. The expected format is the same as the results of a call to .final_s(). TODO: this is not supported yet. End of explanation """ state = rnnbuilder.initial_state() xs = [x1,x1,x1] states = state.add_inputs(xs) outputs = [s.output() for s in states] hs = [s.h() for s in states] print outputs, hs """ Explanation: Aside: memory efficient transduction The RNNState interface is convenient, and allows for incremental input construction. However, sometimes we know the sequence of inputs in advance, and care only about the sequence of output expressions. In this case, we can use the add_inputs(xs) method, where xs is a list of Expression. End of explanation """ state = rnnbuilder.initial_state() xs = [x1,x1,x1] outputs = state.transduce(xs) print outputs """ Explanation: This is convenient. What if we do not care about .s() and .h(), and do not need to access the previous vectors? In such cases we can use the transduce(xs) method instead of add_inputs(xs). transduce takes in a sequence of Expressions, and returns a sequence of Expressions. As a consequence of not returning RNNStates, trnasduce is much more memory efficient than add_inputs or a series of calls to add_input. End of explanation """ import random from collections import defaultdict from itertools import count import sys LAYERS = 2 INPUT_DIM = 50 HIDDEN_DIM = 50 characters = list("abcdefghijklmnopqrstuvwxyz ") characters.append("<EOS>") int2char = list(characters) char2int = {c:i for i,c in enumerate(characters)} VOCAB_SIZE = len(characters) pc = ParameterCollection() srnn = SimpleRNNBuilder(LAYERS, INPUT_DIM, HIDDEN_DIM, pc) lstm = LSTMBuilder(LAYERS, INPUT_DIM, HIDDEN_DIM, pc) params = {} params["lookup"] = pc.add_lookup_parameters((VOCAB_SIZE, INPUT_DIM)) params["R"] = pc.add_parameters((VOCAB_SIZE, HIDDEN_DIM)) params["bias"] = pc.add_parameters((VOCAB_SIZE)) # return compute loss of RNN for one sentence def do_one_sentence(rnn, sentence): # setup the sentence renew_cg() s0 = rnn.initial_state() R = parameter(params["R"]) bias = parameter(params["bias"]) lookup = params["lookup"] sentence = ["<EOS>"] + list(sentence) + ["<EOS>"] sentence = [char2int[c] for c in sentence] s = s0 loss = [] for char,next_char in zip(sentence,sentence[1:]): s = s.add_input(lookup[char]) probs = softmax(R*s.output() + bias) loss.append( -log(pick(probs,next_char)) ) loss = esum(loss) return loss # generate from model: def generate(rnn): def sample(probs): rnd = random.random() for i,p in enumerate(probs): rnd -= p if rnd <= 0: break return i # setup the sentence renew_cg() s0 = rnn.initial_state() R = parameter(params["R"]) bias = parameter(params["bias"]) lookup = params["lookup"] s = s0.add_input(lookup[char2int["<EOS>"]]) out=[] while True: probs = softmax(R*s.output() + bias) probs = probs.vec_value() next_char = sample(probs) out.append(int2char[next_char]) if out[-1] == "<EOS>": break s = s.add_input(lookup[next_char]) return "".join(out[:-1]) # strip the <EOS> # train, and generate every 5 samples def train(rnn, sentence): trainer = SimpleSGDTrainer(pc) for i in xrange(200): loss = do_one_sentence(rnn, sentence) loss_value = loss.value() loss.backward() trainer.update() if i % 5 == 0: print loss_value, print generate(rnn) """ Explanation: Character-level LSTM Now that we know the basics of RNNs, let's build a character-level LSTM language-model. We have a sequence LSTM that, at each step, gets as input a character, and needs to predict the next character. End of explanation """ sentence = "a quick brown fox jumped over the lazy dog" train(srnn, sentence) sentence = "a quick brown fox jumped over the lazy dog" train(lstm, sentence) """ Explanation: Notice that: 1. We pass the same rnn-builder to do_one_sentence over and over again. We must re-use the same rnn-builder, as this is where the shared parameters are kept. 2. We renew_cg() before each sentence -- because we want to have a new graph (new network) for this sentence. The parameters will be shared through the model and the shared rnn-builder. End of explanation """ train(srnn, "these pretzels are making me thirsty") """ Explanation: The model seem to learn the sentence quite well. Somewhat surprisingly, the Simple-RNN model learn quicker than the LSTM! How can that be? The answer is that we are cheating a bit. The sentence we are trying to learn has each letter-bigram exactly once. This means a simple trigram model can memorize it very well. Try it out with more complex sequences. End of explanation """
ColeLab/informationtransfermapping
TheoreticalResults/.ipynb_checkpoints/ItoEtAl2017_ComputationalModelGroupAnalysis-checkpoint.ipynb
gpl-3.0
import numpy as np import sys sys.path.append('utils/') import os os.environ['OMP_NUM_THREADS'] = str(1) import matplotlib.pyplot as plt % matplotlib inline import scipy.stats as stats import statsmodels.api as sm import multiprocessing as mp import sklearn.preprocessing as preprocessing import sklearn.svm as svm import statsmodels.sandbox.stats.multicomp as mc # Import custom modules import multregressionconnectivity as mreg import model import analysis from matplotlib.colors import Normalize # Code to generate a normalized midpoint for plt.imshow visualization function class MidpointNormalize(Normalize): def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint Normalize.__init__(self, vmin, vmax, clip) def __call__(self, value, clip=None): # I'm ignoring masked values and all kinds of edge cases to make a # simple example... x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1] return np.ma.masked_array(np.interp(value, x, y)) """ Explanation: Computational model for group analysis Demo code for Ito et al., 2017. Generates exact figures from Supplementary Fig. 3, and several comparable figures to Fig. 4. Author: Takuya Ito (takuya.ito@rutgers.edu) Ito T, Kulkarni KR, Schultz DH, Mill RD, Chen RH, Solomyak LI, Cole MW (2017). Cognitive task information is transferred between brain regions via resting-state network topology. bioRxiv. https://doi.org/10.1101/101782 Summary: Reads in data generated from running simulations on a compute cluster (20 simulations/subjects). For each simulated subject, we run a resting-state simulation, a task-state simulation (for topdown hub stimulation), a second task-state simulation (for simultaneous topdown and bottomup network stimulation), and perform the information transfer mapping procedure for each task. Each task consists for 4 different task conditions. Simulations are run using a network with five communities, comprising of a single hub community and four local communities. We employ a firing rate code model, and simulate functional MRI data by convolving the simulated signal with a hemodynamic response function (defined in model.py module). See Supplemental materials/methods for a full description. The model (see Stern et al., 2014) $$ \frac{dx_{i}}{dt} \tau_{i} = -x_{i}(t) + s \hspace{3 pt} \phi \hspace{1 pt} \bigg{(} x_i(t) \bigg{)} + g \bigg{(} \sum_{j\neq i}^{N} W_{ij} \hspace{3 pt} \phi \hspace{1 pt} \bigg{(} x_{j}(t) \bigg{)} \bigg{)} + I_{i}(t)$$ where $x_i$ is the activity of region $i$, $\tau_{i}$ is the time constant for region $i$, $s$ is the recurrent (local) coupling, $g$ is the global coupling parameter, $\phi$ is the bounded transfer function (in this scenario is the hyperbolic tangent), $W_{xy}$ is the synaptic connectivity matrix, and $I$ is the task-stimulation (if any). Simulation description (see Methods for full description) N.B. All simulations were performed separately using the provided modules; data provided are a direct product for running the provided model. This notebook is configured to run analyses in parallel using the multiprocessing module in python. 1.0 Load and visualize synaptic connectivity, resting-state FC 2.0 Compute out-of-network degree centrality 3.0 Load in network-to-network activity flow mapping predictions; perform predicted-to-actual similarity analysis (RSA) 4.0 Seconday analysis: Load in network-to-network activity flow mapping predictions; perform predicted-to-actual similarity analysis (using SVMs) Parameters: global coupling parameter g = 1.0 local coupling parameter s = 1.0 Sampling rate of 10ms Additional notes: Simulation data was generated using the function model.subjectSimulationAndSaveToFile() See help(model.subjectSimulationAndSaveToFile) for more details Simulations were performed on a compute cluster at Rutgers University (NM3 compute cluster) A single subject simulation takes about ~10-12 minutes to complete for model.subjectSimulationAndSaveToFile 0 - Import modules and define essential parameters End of explanation """ # Specify the directory to read in provided data # If data file was unzippd in current working directory this shouldn't need to be changed datadir = 'ItoEtAl2017_Simulations/' # Specify number of CPUs to process on (using multiprocessing module in python) nproc = 10 # Output file to save generated figures (from this notebook) outputdir = './figures/' # default with output in current working directory if not os.path.exists(outputdir): os.makedirs(outputdir) """ Explanation: ESSENTIAL parameters to modify Identify data directory Indicate number of threads to perform analyses (this originally was performed on a large linux servers with > 20 CPUs) End of explanation """ nsubjs = range(0,20) # number of simulations (i.e., subject numbers) nblocks = 20 # number of blocks per task condition #### Define the condition numbers associated with each task # Conditions 1-4 are for top-down stimulation only (i.e., task 1) topdown_only = range(1,5) # Conditions 5-9 are simultaneous top-down (hub-network) and bottom-up (local-network) stimulation (i.e., task 2) topdown_and_bottomup = range(5,9) """ Explanation: Basic simulation parameters End of explanation """ #### Set up subject networks #### # Parameters for subject's networks ncommunities = 5 innetwork_dsity = .35 outnetwork_dsity = .05 hubnetwork_dsity = .20 nodespercommunity = 50 totalnodes = nodespercommunity*ncommunities ########## # Construct structural matrix W = model.generateStructuralNetwork(ncommunities=ncommunities, innetwork_dsity=innetwork_dsity, outnetwork_dsity=outnetwork_dsity, hubnetwork_dsity=hubnetwork_dsity, nodespercommunity=nodespercommunity, showplot=False) # Construct synaptic matrix G = model.generateSynapticNetwork(W, showplot=False) # Define community affiliation vector Ci = np.repeat(np.arange(ncommunities),nodespercommunity) # Plot figure plt.figure() # norm = MidpointNormalize(midpoint=0) plt.imshow(G,origin='lower',interpolation='none') plt.xlabel('Regions') plt.ylabel('Regions') plt.title('Synaptic Weight Matrix', y=1.04, fontsize=18) plt.colorbar() """ Explanation: 1.0 Construct sample network matrix and visualize group FC matrices 1.1 Construct and visualize synaptic matrix for a single sample subject (Fig. 4A) We generate a random synaptic matrix using the model.py module for demonstration End of explanation """ fcmat_pearson = np.zeros((totalnodes,totalnodes,len(nsubjs))) fcmat_multreg = np.zeros((totalnodes,totalnodes,len(nsubjs))) ########## # Load in subject FC data scount = 0 for subj in nsubjs: indir = datadir + '/restfc/' # Load in pearson FC matrix filename1 = 'subj' + str(subj) + '_restfc_pearson.txt' fcmat_pearson[:,:,scount] = np.loadtxt(indir + filename1, delimiter=',') # Loda in multreg FC matrix filename2 = 'subj' + str(subj) + '_restfc_multreg.txt' fcmat_multreg[:,:,scount] = np.loadtxt(indir + filename2, delimiter=',') scount += 1 ########## # Plot group FC averages plt.figure() avg = np.mean(fcmat_pearson,axis=2) np.fill_diagonal(avg,0) plt.imshow(avg ,origin='lower',interpolation='none')#,vmin=0) plt.xlabel('Regions') plt.ylabel('Regions') plt.title('Group Rest FC Matrix\nPearson FC', y=1.04, fontsize=18) plt.colorbar() plt.tight_layout() plt.figure() avg = np.mean(fcmat_multreg,axis=2) np.fill_diagonal(avg,0) plt.imshow(avg ,origin='lower',interpolation='none')#,vmin=-.08,vmax=.08) plt.xlabel('Regions') plt.ylabel('Regions') plt.title('Group Rest FC Matrix\nMultiple Regression FC', y=1.04, fontsize=18) plt.colorbar() plt.tight_layout() """ Explanation: 1.2 Visualize group average resting-state FC from simulated data (analogous to Fig. 4B) Visualize both Pearson FC and multiple linear regression End of explanation """ outofnet_intrinsicFC = np.zeros((ncommunities,len(nsubjs))) indices = np.arange(nodespercommunity*ncommunities) ########## # Calculate average out-of-network degree across subjects scount = 0 for subj in nsubjs: for net in range(0,ncommunities): # if net == hubnet: continue net_ind = np.where(Ci==net)[0] net_ind.shape = (len(net_ind),1) outofnet_ind = np.setxor1d(net_ind,indices) outofnet_ind.shape = (len(outofnet_ind),1) outofnet_intrinsicFC[net,scount] = np.mean(fcmat_multreg[net_ind, outofnet_ind.T, scount]) scount += 1 # Compute average stats fcmean = np.mean(outofnet_intrinsicFC,axis=1) fcerr = np.std(outofnet_intrinsicFC,axis=1)/np.sqrt(len(nsubjs)) ########## # Plot figure fig = plt.bar(range(len(fcmean)), fcmean, yerr=fcerr) # fig = plt.ylim([.09,0.10]) fig = plt.xticks(np.arange(.4,5.4,1.0),['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4'],fontsize=14) fig = plt.ylabel('Multiple Regression FC', fontsize=16) fig = plt.xlabel('Networks', fontsize=16) fig = plt.title("Average Out-Of-Network IntrinsicFC\nSimulated Resting-State Data", fontsize=18, y=1.02) fig = plt.tight_layout() """ Explanation: 2.0 Compute out-of-network intrinsic FC (analogous to Fig. 4D) End of explanation """ # Empty variables for topdown task analysis ite_topdown = np.zeros((ncommunities,ncommunities,len(nsubjs))) # Empty variables for topdown and bottomup task analysis ite_topdownbottomup = np.zeros((ncommunities,ncommunities,len(nsubjs))) ########## # Run predicted-to-actual similarity for every network-to-network configuration (using RSA approach) for i in range(ncommunities): for j in range(ncommunities): if i==j: continue fromnet = i net = j nblocks = nblocks ## First run on topdown only task conditions inputs = [] for subj in nsubjs: inputs.append((subj,net,fromnet,topdown_only,nblocks,Ci,nodespercommunity,datadir)) # Run multiprocessing across subjects pool = mp.Pool(processes=nproc) results_topdown = pool.map_async(analysis.predictedToActualRSA, inputs).get() pool.close() pool.join() ## Second run on topdown and bottomup task conditions inputs = [] for subj in nsubjs: inputs.append((subj,net,fromnet,topdown_and_bottomup,nblocks,Ci,nodespercommunity,datadir)) # Run multiprocessing pool = mp.Pool(processes=nproc) results_topdownbottomup = pool.map_async(analysis.predictedToActualRSA, inputs).get() pool.close() pool.join() ## Get results and store in network X network X subjects matrix scount = 0 for subj in nsubjs: # Obtain topdown task results ite = results_topdown[scount] ite_topdown[i,j,scount] = ite # Obtain topdown and bottom up task results ite = results_topdownbottomup[scount] ite_topdownbottomup[i,j,scount] = ite scount += 1 """ Explanation: 3.0 Run group analysis on network-to-network information transfer mapping output using simulated data (Supplementary Fig. 3A-D) Note: Activity flow mapping procedure (and subsequent data) was generated on the compute cluster. Code that generated data is included in model.py. We demonstrate the 'predicted-to-actual' similarity analysis below. 3.1 Network-to-network information transfer mapping on simulated neural data Region-to-region activity flow mapping is performed already (with provided simulation data); we only perform the predicted-to-actual similarity analysis. Perform for two tasks: (1) topdown only task conditions (stimulation of hub network only); (2) topdown and bottom up task conditions (stimulation of both hub network and local networks). End of explanation """ # Instantiate empty result matrices tmat_topdown = np.zeros((ncommunities,ncommunities)) pmat_topdown = np.ones((ncommunities,ncommunities)) tmat_topdownbottomup = np.zeros((ncommunities,ncommunities)) pmat_topdownbottomup = np.ones((ncommunities,ncommunities)) # Run t-tests for every network-to-network configuration for i in range(ncommunities): for j in range(ncommunities): if i==j: continue ########## ## Run statistical test for first task (topdown only stim) t, p = stats.ttest_1samp(ite_topdown[i,j,:],0) tmat_topdown[i,j] = t # Make p-value one-sided (for one-sided t-test) if t > 0: p = p/2.0 else: p = 1-p/2.0 pmat_topdown[i,j] = p ########## ## Run statistical test for second task (topdown and bottomup stim) t, p = stats.ttest_1samp(ite_topdownbottomup[i,j,:],0) # Make p-value one-sided (for one-sided t-test) tmat_topdownbottomup[i,j] = t if t > 0: p = p/2.0 else: p = 1-p/2.0 pmat_topdownbottomup[i,j] = p ########## # Run FDR correction on p-values (exclude diagonal values) ## TopDown Task qmat_topdown = np.ones((ncommunities,ncommunities)) triu_ind = np.triu_indices(ncommunities,k=1) tril_ind = np.tril_indices(ncommunities,k=-1) all_ps = np.hstack((pmat_topdown[triu_ind],pmat_topdown[tril_ind])) h, all_qs = mc.fdrcorrection0(all_ps) # the first half of all qs belong to triu, second half belongs to tril qmat_topdown[triu_ind] = all_qs[:len(triu_ind[0])] qmat_topdown[tril_ind] = all_qs[len(tril_ind[0]):] binary_mat_topdown = qmat_topdown < .05 ## TopDown and BottomUp Task qmat_topdownbottomup = np.ones((ncommunities,ncommunities)) triu_ind = np.triu_indices(ncommunities,k=1) tril_ind = np.tril_indices(ncommunities,k=-1) all_ps = np.hstack((pmat_topdownbottomup[triu_ind],pmat_topdownbottomup[tril_ind])) h, all_qs = mc.fdrcorrection0(all_ps) # the first half of all qs belong to triu, second half belongs to tril qmat_topdownbottomup[triu_ind] = all_qs[:len(triu_ind[0])] qmat_topdownbottomup[tril_ind] = all_qs[len(tril_ind[0]):] binary_mat_topdownbottomup = qmat_topdownbottomup < .05 ########## # Plot figures for topdown task # (Unthresholded plot) plt.figure(figsize=(12,10)) plt.subplot(121) norm = MidpointNormalize(midpoint=0) plt.imshow(np.mean(ite_topdown,axis=2),norm=norm,origin='lower',interpolation='None',cmap='bwr') plt.title('Network-to-Network ITE (using RSA) (Unthresholded)\nTopDown Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) # (Thresholded plot) plt.subplot(122) threshold_acc = np.multiply(binary_mat_topdown,np.mean(ite_topdown,axis=2)) norm = MidpointNormalize(midpoint=0) plt.imshow(threshold_acc,norm=norm,origin='lower',interpolation='None',cmap='bwr') plt.title('Network-to-Network ITE (using RSA) (Thresholded)\nTopDown Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) plt.tight_layout() plt.savefig(outputdir + 'SFig_CompModel_RSA_topdownOnly.pdf') ########## # Plot figures for topdown and bottomup task # (Unthresholded plot) plt.figure(figsize=(12,10)) ((12,10)) plt.subplot(121) norm = MidpointNormalize(midpoint=0) plt.imshow(np.mean(ite_topdownbottomup,axis=2),origin='lower',interpolation='None',norm=norm,cmap='bwr') plt.title('Network-to-Network ITE (using RSA) (Unthresholded)\nTopDownBottomUp Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) # (Thresholded plot) plt.subplot(122) threshold_acc = np.multiply(binary_mat_topdownbottomup,np.mean(ite_topdownbottomup,axis=2)) norm = MidpointNormalize(midpoint=0) plt.imshow(threshold_acc,origin='lower',interpolation='None',norm=norm,cmap='bwr') plt.title('Network-to-Network ITE (using RSA)(Thresholded)\nTopDownBottomUp Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) plt.tight_layout() plt.savefig(outputdir + 'SFig_CompModel_RSA_topdownbottomup.pdf') """ Explanation: 3.2 Statistical testing on results and plot End of explanation """ # Empty variables for topdown task analysis svm_topdown = np.zeros((ncommunities,ncommunities,len(nsubjs))) # Empty variables for topdown and bottomup task analysis svm_topdownbottomup = np.zeros((ncommunities,ncommunities,len(nsubjs))) ########## # Run predicted-to-actual similarity for every network-to-network configuration (using RSA approach) for i in range(ncommunities): for j in range(ncommunities): if i==j: continue fromnet = i net = j nblocks = nblocks ## First run on topdown only task conditions inputs = [] for subj in nsubjs: inputs.append((subj,net,fromnet,topdown_only,nblocks,Ci,nodespercommunity,datadir)) # Run multiprocessing across subjects pool = mp.Pool(processes=nproc) results_topdown = pool.map_async(analysis.predictedToActualSVM, inputs).get() pool.close() pool.join() ## Second run on topdown and bottomup task conditions inputs = [] for subj in nsubjs: inputs.append((subj,net,fromnet,topdown_and_bottomup,nblocks,Ci,nodespercommunity,datadir)) # Run multiprocessing pool = mp.Pool(processes=nproc) results_topdownbottomup = pool.map_async(analysis.predictedToActualSVM, inputs).get() pool.close() pool.join() ## Get results and store in network X network X subjects matrix scount = 0 for subj in nsubjs: # Obtain topdown task results svm = results_topdown[scount] svm_topdown[i,j,scount] = svm # Obtain topdown and bottom up task results svm = results_topdownbottomup[scount] svm_topdownbottomup[i,j,scount] = svm scount += 1 """ Explanation: 4.0 Run group analysis on network-to-network information transfer mapping output using SVM decoding (as opposed to predicted-to-actual RSA analysis) (Supplementary Fig. 3E-H) 4.1 Network-to-network information transfer mapping on simulated neural data USING SVMs End of explanation """ # Instantiate empty result matrices tmat_topdown_svm = np.zeros((ncommunities,ncommunities)) pmat_topdown_svm = np.ones((ncommunities,ncommunities)) tmat_topdownbottomup_svm = np.zeros((ncommunities,ncommunities)) pmat_topdownbottomup_svm = np.ones((ncommunities,ncommunities)) # Perform accuracy decoding t-test against chance, which is 25% for a 4-way classification chance = .25 for i in range(ncommunities): for j in range(ncommunities): if i==j: continue # Run statistical test for first task (topdown only stim) t, p = stats.ttest_1samp(svm_topdown[i,j,:],chance) tmat_topdown_svm[i,j] = t # Make p-value one-sided (for one-sided t-test) if t > 0: p = p/2.0 else: p = 1-p/2.0 pmat_topdown_svm[i,j] = p # Run statistical test for second task (topdown and bottomup stim) t, p = stats.ttest_1samp(svm_topdownbottomup[i,j,:],chance) tmat_topdownbottomup_svm[i,j] = t # Make p-value one-sided (for one-sided t-test) if t > 0: p = p/2.0 else: p = 1-p/2.0 pmat_topdownbottomup_svm[i,j] = p ## TopDown Tasks # Run FDR correction on p-values (Don't get diagonal values) qmat_topdown_svm = np.ones((ncommunities,ncommunities)) triu_ind = np.triu_indices(ncommunities,k=1) tril_ind = np.tril_indices(ncommunities,k=-1) all_ps = np.hstack((pmat_topdown_svm[triu_ind],pmat_topdown_svm[tril_ind])) h, all_qs = mc.fdrcorrection0(all_ps) # the first half of all qs belong to triu, second half belongs to tril qmat_topdown_svm[triu_ind] = all_qs[:len(triu_ind[0])] qmat_topdown_svm[tril_ind] = all_qs[len(tril_ind[0]):] binary_mat_topdown_svm = qmat_topdown_svm < .05 ## TopDown and BottomUp Tasks # Run FDR correction on p-values (Don't get diagonal values) qmat_topdownbottomup_svm = np.ones((ncommunities,ncommunities)) triu_ind = np.triu_indices(ncommunities,k=1) tril_ind = np.tril_indices(ncommunities,k=-1) all_ps = np.hstack((pmat_topdownbottomup_svm[triu_ind],pmat_topdownbottomup_svm[tril_ind])) h, all_qs = mc.fdrcorrection0(all_ps) # the first half of all qs belong to triu, second half belongs to tril qmat_topdownbottomup_svm[triu_ind] = all_qs[:len(triu_ind[0])] qmat_topdownbottomup_svm[tril_ind] = all_qs[len(tril_ind[0]):] binary_mat_topdownbottomup_svm = qmat_topdownbottomup_svm < .05 #### ## Plot figures for Top Down Task # Unthresholded map plt.figure(figsize=(12,10)) plt.subplot(121) mat = np.mean(svm_topdown,axis=2) norm = MidpointNormalize(midpoint=0) plt.imshow(mat,norm=norm,origin='lower',interpolation='None',cmap='bwr') plt.title('Network-to-Network ITE (using SVMs) (Unthresholded)\nTopDown Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=0.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) plt.tight_layout() plt.savefig(outputdir + 'SFig_CompModel_SVM_topdownOnly_Unthresholded.pdf') # Thresholded map plt.subplot(122) mat = np.mean(svm_topdown,axis=2) mat = np.multiply(binary_mat_topdown_svm,mat) norm = MidpointNormalize(midpoint=0) plt.imshow(mat,norm=norm,origin='lower',interpolation='None',cmap='bwr') plt.title('Network-to-Network ITE (using SVMs) (Thresholded)\nTopDown Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=0.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) plt.tight_layout() plt.savefig(outputdir + 'SFig_CompModel_SVM_topdownOnly.pdf') #### ## Plot figures for Top Down AND Bottom Up Task # Unthresholded map plt.figure(figsize=(12,10)) plt.subplot(121) mat = np.mean(svm_topdownbottomup,axis=2) norm = MidpointNormalize(midpoint=0) plt.imshow(mat,origin='lower',interpolation='None',norm=norm,cmap='bwr') plt.title('Network-to-Network ITE (using SVMs) (Unthresholded)\nTopDownBottomUp Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=0.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) # Thresholded map plt.subplot(122) mat = np.mean(svm_topdownbottomup,axis=2) mat = np.multiply(binary_mat_topdownbottomup_svm,mat) norm = MidpointNormalize(midpoint=0) plt.imshow(mat,origin='lower',interpolation='None',norm=norm,cmap='bwr') plt.title('Network-to-Network ITE (using SVMs) (Thresholded)\nTopDownBottomUp Tasks',fontsize=16, y=1.02) plt.colorbar(fraction=0.046) plt.yticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.xticks(range(ncommunities), ['FlexHub', 'Net1', 'Net2', 'Net3', 'Net4']) plt.ylabel('Network ActFlow FROM',fontsize=15) plt.xlabel('Network ActFlow TO',fontsize=15) plt.tight_layout() plt.savefig(outputdir + 'SFig_CompModel_SVM_topdownbottomup.pdf') """ Explanation: 4.2 Statistical testing on results and plot End of explanation """
johntanz/ROP
.ipynb_checkpoints/Masimo160127-Copy1-checkpoint.ipynb
gpl-2.0
#the usual beginning import pandas as pd import numpy as np from pandas import Series, DataFrame from datetime import datetime, timedelta from pandas import concat #define any string with 'C' as NaN def readD(val): if 'C' in val: return np.nan return val """ Explanation: Masimo Analysis For Pulse Ox. Analysis, make sure the data file is the right .csv format: a) Headings on Row 1 b) Open the csv file through Notepad or TextEdit and delete extra row commas (non-printable characters) c) There are always Dates in Column A and Time in Column B. d) There might be a row that says "Time Gap Present". Delete this row from Notepad or TextEdit End of explanation """ df = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP006PO.csv', parse_dates={'timestamp': ['Date','Time']}, index_col='timestamp', usecols=['Date', 'Time', 'SpO2', 'PR', 'PI', 'Exceptions'], na_values=['0'], converters={'Exceptions': readD} ) #parse_dates tells the read_csv function to combine the date and time column #into one timestamp column and parse it as a timestamp. # pandas is smart enough to know how to parse a date in various formats #index_col sets the timestamp column to be the index. #usecols tells the read_csv function to select only the subset of the columns. #na_values is used to turn 0 into NaN #converters: readD is the dict that means any string with 'C' with be NaN (for PI) #dfclean = df[27:33][df[27:33].loc[:, ['SpO2', 'PR', 'PI', 'Exceptions']].apply(pd.notnull).all(1)] #clean the dataframe to get rid of rows that have NaN for PI purposes df_clean = df[df.loc[:, ['PI', 'Exceptions']].apply(pd.notnull).all(1)] """Pulse ox date/time is 1 mins and 32 seconds faster than phone. Have to correct for it.""" TC = timedelta(minutes=1, seconds=32) """ Explanation: Import File into Python Change File Name! End of explanation """ df_first = df.first_valid_index() #get the first number from index Y = pd.to_datetime(df_first) #convert index to datetime # Y = TIME DATA COLLECTION BEGAN / First data point on CSV # SYNTAX: # datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) W = datetime(2015, 6, 17, 7, 10)+TC # W = first eye drop dtarts X = datetime(2015, 6, 17, 8, 36)+TC # X = ROP Exam Started Z = datetime(2015, 6, 17, 8, 39)+TC # Z = ROP Exam Ended df_last = df.last_valid_index() #get the last number from index Q = pd.to_datetime(df_last) # Q = TIME DATA COLLECTION ENDED / Last Data point on CSV """ Explanation: Set Date and Time of ROP Exam and Eye Drops End of explanation """ avg0PI = df_clean.PI[Y:W].mean() avg0O2 = df.SpO2[Y:W].mean() avg0PR = df.PR[Y:W].mean() print 'Baseline Averages\n', 'PI :\t',avg0PI, '\nSpO2 :\t',avg0O2,'\nPR :\t',avg0PR, #df.std() for standard deviation """ Explanation: Baseline Averages End of explanation """ # Every 5 min Average from start of eye drops to start of exam def perdeltadrop(start, end, delta): rdrop = [] curr = start while curr < end: rdrop.append(curr) curr += delta return rdrop dfdropPI = df_clean.PI[W:W+timedelta(hours=1)] dfdropO2 = df.SpO2[W:W+timedelta(hours=1)] dfdropPR = df.PR[W:W+timedelta(hours=1)] windrop = timedelta(minutes=5)#make the range rdrop = perdeltadrop(W, W+timedelta(hours=1), windrop) avgdropPI = Series(index = rdrop, name = 'PI DurEyeD') avgdropO2 = Series(index = rdrop, name = 'SpO2 DurEyeD') avgdropPR = Series(index = rdrop, name = 'PR DurEyeD') for i in rdrop: avgdropPI[i] = dfdropPI[i:(i+windrop)].mean() avgdropO2[i] = dfdropO2[i:(i+windrop)].mean() avgdropPR[i] = dfdropPR[i:(i+windrop)].mean() resultdrops = concat([avgdropPI, avgdropO2, avgdropPR], axis=1, join='inner') print resultdrops """ Explanation: Average q 5 Min for 1 hour after 1st Eye Drops End of explanation """ #AVERAGE DURING ROP EXAM FOR FIRST FOUR MINUTES def perdelta1(start, end, delta): r1 = [] curr = start while curr < end: r1.append(curr) curr += delta return r1 df1PI = df_clean.PI[X:X+timedelta(minutes=4)] df1O2 = df.SpO2[X:X+timedelta(minutes=4)] df1PR = df.PR[X:X+timedelta(minutes=4)] win1 = timedelta(seconds=10) #any unit of time & make the range r1 = perdelta1(X, X+timedelta(minutes=4), win1) #make the series to store avg1PI = Series(index = r1, name = 'PI DurEx') avg1O2 = Series(index = r1, name = 'SpO2 DurEx') avg1PR = Series(index = r1, name = 'PR DurEX') #average! for i1 in r1: avg1PI[i1] = df1PI[i1:(i1+win1)].mean() avg1O2[i1] = df1O2[i1:(i1+win1)].mean() avg1PR[i1] = df1PR[i1:(i1+win1)].mean() result1 = concat([avg1PI, avg1O2, avg1PR], axis=1, join='inner') print result1 """ Explanation: Average Every 10 Sec During ROP Exam for first 4 minutes End of explanation """ #AVERAGE EVERY 5 MINUTES ONE HOUR AFTER ROP EXAM def perdelta2(start, end, delta): r2 = [] curr = start while curr < end: r2.append(curr) curr += delta return r2 # datetime(year, month, day, hour, etc.) df2PI = df_clean.PI[Z:(Z+timedelta(hours=1))] df2O2 = df.SpO2[Z:(Z+timedelta(hours=1))] df2PR = df.PR[Z:(Z+timedelta(hours=1))] win2 = timedelta(minutes=5) #any unit of time, make the range r2 = perdelta2(Z, (Z+timedelta(hours=1)), win2) #define the average using function #make the series to store avg2PI = Series(index = r2, name = 'PI q5MinHr1') avg2O2 = Series(index = r2, name = 'O2 q5MinHr1') avg2PR = Series(index = r2, name = 'PR q5MinHr1') #average! for i2 in r2: avg2PI[i2] = df2PI[i2:(i2+win2)].mean() avg2O2[i2] = df2O2[i2:(i2+win2)].mean() avg2PR[i2] = df2PR[i2:(i2+win2)].mean() result2 = concat([avg2PI, avg2O2, avg2PR], axis=1, join='inner') print result2 """ Explanation: Average Every 5 Mins Hour 1-2 After ROP Exam End of explanation """ #AVERAGE EVERY 15 MINUTES TWO HOURS AFTER ROP EXAM def perdelta3(start, end, delta): r3 = [] curr = start while curr < end: r3.append(curr) curr += delta return r3 # datetime(year, month, day, hour, etc.) df3PI = df_clean.PI[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))] df3O2 = df.SpO2[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))] df3PR = df.PR[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))] win3 = timedelta(minutes=15) #any unit of time, make the range r3 = perdelta3((Z+timedelta(hours=1)), (Z+timedelta(hours=2)), win3) #make the series to store avg3PI = Series(index = r3, name = 'PI q15MinHr2') avg3O2 = Series(index = r3, name = 'O2 q15MinHr2') avg3PR = Series(index = r3, name = 'PR q15MinHr2') #average! for i3 in r3: avg3PI[i3] = df3PI[i3:(i3+win3)].mean() avg3O2[i3] = df3O2[i3:(i3+win3)].mean() avg3PR[i3] = df3PR[i3:(i3+win3)].mean() result3 = concat([avg3PI, avg3O2, avg3PR], axis=1, join='inner') print result3 """ Explanation: Average Every 15 Mins Hour 2-3 After ROP Exam End of explanation """ #AVERAGE EVERY 30 MINUTES THREE HOURS AFTER ROP EXAM def perdelta4(start, end, delta): r4 = [] curr = start while curr < end: r4.append(curr) curr += delta return r4 # datetime(year, month, day, hour, etc.) df4PI = df_clean.PI[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))] df4O2 = df.SpO2[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))] df4PR = df.PR[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))] win4 = timedelta(minutes=30) #any unit of time, make the range r4 = perdelta4((Z+timedelta(hours=2)), (Z+timedelta(hours=3)), win4) #make the series to store avg4PI = Series(index = r4, name = 'PI q30MinHr3') avg4O2 = Series(index = r4, name = 'O2 q30MinHr3') avg4PR = Series(index = r4, name = 'PR q30MinHr3') #average! for i4 in r4: avg4PI[i4] = df4PI[i4:(i4+win4)].mean() avg4O2[i4] = df4O2[i4:(i4+win4)].mean() avg4PR[i4] = df4PR[i4:(i4+win4)].mean() result4 = concat([avg4PI, avg4O2, avg4PR], axis=1, join='inner') print result4 """ Explanation: Average Every 30 Mins Hour 3-4 After ROP Exam End of explanation """ #AVERAGE EVERY 60 MINUTES 4-24 HOURS AFTER ROP EXAM def perdelta5(start, end, delta): r5 = [] curr = start while curr < end: r5.append(curr) curr += delta return r5 # datetime(year, month, day, hour, etc.) df5PI = df_clean.PI[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))] df5O2 = df.SpO2[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))] df5PR = df.PR[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))] win5 = timedelta(minutes=60) #any unit of time, make the range r5 = perdelta5((Z+timedelta(hours=3)), (Z+timedelta(hours=24)), win5) #make the series to store avg5PI = Series(index = r5, name = 'PI q60MinHr4+') avg5O2 = Series(index = r5, name = 'O2 q60MinHr4+') avg5PR = Series(index = r5, name = 'PR q60MinHr4+') #average! for i5 in r5: avg5PI[i5] = df5PI[i5:(i5+win5)].mean() avg5O2[i5] = df5O2[i5:(i5+win5)].mean() avg5PR[i5] = df5PR[i5:(i5+win5)].mean() result5 = concat([avg5PI, avg5O2, avg5PR], axis=1, join='inner') print result5 """ Explanation: Average Every Hour 4-24 Hours Post ROP Exam End of explanation """ df_O2_pre = df[Y:W] #Find count of these ranges below = 0 # v <=80 middle = 0 #v >= 81 and v<=84 above = 0 #v >=85 and v<=89 ls = [] b_dict = {} m_dict = {} a_dict = {} for i, v in df_O2_pre['SpO2'].iteritems(): if v <= 80: #below block if not ls: ls.append(v) else: if ls[0] >= 81: #if the range before was not below 80 if len(ls) >= 5: #if the range was greater than 10 seconds, set to 5 because data points are every 2 if ls[0] <= 84: #was it in the middle range? m_dict[middle] = ls middle += 1 ls = [v] elif ls[0] >= 85 and ls[0] <=89: #was it in the above range? a_dict[above] = ls above += 1 ls = [v] else: #old list wasn't long enough to count ls = [v] else: #if in the same range ls.append(v) elif v >= 81 and v<= 84: #middle block if not ls: ls.append(v) else: if ls[0] <= 80 or (ls[0]>=85 and ls[0]<= 89): #if not in the middle range if len(ls) >= 5: #if range was greater than 10 seconds if ls[0] <= 80: #was it in the below range? b_dict[below] = ls below += 1 ls = [v] elif ls[0] >= 85 and ls[0] <=89: #was it in the above range? a_dict[above] = ls above += 1 ls = [v] else: #old list wasn't long enough to count ls = [v] else: ls.append(v) elif v >= 85 and v <=89: #above block if not ls: ls.append(v) else: if ls[0] <=84 : #if not in the above range if len(ls) >= 5: #if range was greater than if ls[0] <= 80: #was it in the below range? b_dict[below] = ls below += 1 ls = [v] elif ls[0] >= 81 and ls[0] <=84: #was it in the middle range? m_dict[middle] = ls middle += 1 ls = [v] else: #old list wasn't long enough to count ls = [v] else: ls.append(v) else: #v>90 or something else weird. start the list over ls = [] #final list check if len(ls) >= 5: if ls[0] <= 80: #was it in the below range? b_dict[below] = ls below += 1 ls = [v] elif ls[0] >= 81 and ls[0] <=84: #was it in the middle range? m_dict[middle] = ls middle += 1 ls = [v] elif ls[0] >= 85 and ls[0] <=89: #was it in the above range? a_dict[above] = ls above += 1 b_len = 0.0 for key, val in b_dict.iteritems(): b_len += len(val) m_len = 0.0 for key, val in m_dict.iteritems(): m_len += len(val) a_len = 0.0 for key, val in a_dict.iteritems(): a_len += len(val) #post exam duraiton length analysis df_O2_post = df[Z:Q] #Find count of these ranges below2 = 0 # v <=80 middle2= 0 #v >= 81 and v<=84 above2 = 0 #v >=85 and v<=89 ls2 = [] b_dict2 = {} m_dict2 = {} a_dict2 = {} for i2, v2 in df_O2_post['SpO2'].iteritems(): if v2 <= 80: #below block if not ls2: ls2.append(v2) else: if ls2[0] >= 81: #if the range before was not below 80 if len(ls2) >= 5: #if the range was greater than 10 seconds, set to 5 because data points are every 2 if ls2[0] <= 84: #was it in the middle range? m_dict2[middle2] = ls2 middle2 += 1 ls2 = [v2] elif ls2[0] >= 85 and ls2[0] <=89: #was it in the above range? a_dict2[above2] = ls2 above2 += 1 ls2 = [v2] else: #old list wasn't long enough to count ls2 = [v2] else: #if in the same range ls2.append(v2) elif v2 >= 81 and v2<= 84: #middle block if not ls2: ls2.append(v2) else: if ls2[0] <= 80 or (ls2[0]>=85 and ls2[0]<= 89): #if not in the middle range if len(ls2) >= 5: #if range was greater than 10 seconds if ls2[0] <= 80: #was it in the below range? b_dict2[below2] = ls2 below2 += 1 ls2 = [v2] elif ls2[0] >= 85 and ls2[0] <=89: #was it in the above range? a_dict2[above2] = ls2 above2 += 1 ls2 = [v2] else: #old list wasn't long enough to count ls2 = [v2] else: ls2.append(v2) elif v2 >= 85 and v2 <=89: #above block if not ls2: ls2.append(v2) else: if ls2[0] <=84 : #if not in the above range if len(ls2) >= 5: #if range was greater than if ls2[0] <= 80: #was it in the below range? b_dict2[below2] = ls2 below2 += 1 ls2 = [v2] elif ls2[0] >= 81 and ls2[0] <=84: #was it in the middle range? m_dict2[middle2] = ls2 middle2 += 1 ls2 = [v2] else: #old list wasn't long enough to count ls2 = [v2] else: ls2.append(v2) else: #v2>90 or something else weird. start the list over ls2 = [] #final list check if len(ls2) >= 5: if ls2[0] <= 80: #was it in the below range? b_dict2[below2] = ls2 below2 += 1 ls2= [v2] elif ls2[0] >= 81 and ls2[0] <=84: #was it in the middle range? m_dict2[middle2] = ls2 middle2 += 1 ls2 = [v2] elif ls2[0] >= 85 and ls2[0] <=89: #was it in the above range? a_dict2[above2] = ls2 above2 += 1 b_len2 = 0.0 for key, val2 in b_dict2.iteritems(): b_len2 += len(val2) m_len2 = 0.0 for key, val2 in m_dict2.iteritems(): m_len2 += len(val2) a_len2 = 0.0 for key, val2 in a_dict2.iteritems(): a_len2 += len(val2) #print results from count and min print "Desat Counts for X mins\n" print "Pre Mild Desat (85-89) Count: %s\t" %above, "for %s min" %((a_len*2)/60.) print "Pre Mod Desat (81-84) Count: %s\t" %middle, "for %s min" %((m_len*2)/60.) print "Pre Sev Desat (=< 80) Count: %s\t" %below, "for %s min\n" %((b_len*2)/60.) print "Post Mild Desat (85-89) Count: %s\t" %above2, "for %s min" %((a_len2*2)/60.) print "Post Mod Desat (81-84) Count: %s\t" %middle2, "for %s min" %((m_len2*2)/60.) print "Post Sev Desat (=< 80) Count: %s\t" %below2, "for %s min\n" %((b_len2*2)/60.) print "Data Recording Time!" print '*' * 10 print "Pre-Exam Data Recording Length\t", X - Y # start of exam - first data point print "Post-Exam Data Recording Length\t", Q - Z #last data point - end of exam print "Total Data Recording Length\t", Q - Y #last data point - first data point Pre = ['Pre',(X-Y)] Post = ['Post',(Q-Z)] Total = ['Total',(Q-Y)] RTL = [Pre, Post, Total] PreMild = ['Pre Mild Desats \t',(above), 'for', (a_len*2)/60., 'mins'] PreMod = ['Pre Mod Desats \t',(middle), 'for', (m_len*2)/60., 'mins'] PreSev = ['Pre Sev Desats \t',(below), 'for', (b_len*2)/60., 'mins'] PreDesats = [PreMild, PreMod, PreSev] PostMild = ['Post Mild Desats \t',(above2), 'for', (a_len2*2)/60., 'mins'] PostMod = ['Post Mod Desats \t',(middle2), 'for', (m_len2*2)/60., 'mins'] PostSev = ['Post Sev Desats \t',(below2), 'for', (b_len2*2)/60., 'mins'] PostDesats = [PostMild, PostMod, PostSev] #creating a list for recording time length #did it count check sort correctly? get rid of the ''' if you want to check your values ''' print "Mild check" for key, val in b_dict.iteritems(): print all(i <=80 for i in val) print "Moderate check" for key, val in m_dict.iteritems(): print all(i >= 81 and i<=84 for i in val) print "Severe check" for key, val in a_dict.iteritems(): print all(i >= 85 and i<=89 for i in val) ''' """ Explanation: Mild, Moderate, and Severe Desaturation Events End of explanation """ import csv class excel_tab(csv.excel): delimiter = '\t' csv.register_dialect("excel_tab", excel_tab) with open('ROP006_PO.csv', 'w') as f: #CHANGE CSV FILE NAME writer = csv.writer(f, dialect=excel_tab) writer.writerow(['PI']) writer.writerow([avg0PI]) for i in rdrop: writer.writerow([avgdropPI[i]]) #NEEDS BRACKETS TO MAKE IT SEQUENCE for i in r1: writer.writerow([avg1PI[i]]) for i in r2: writer.writerow([avg2PI[i]]) for i in r3: writer.writerow([avg3PI[i]]) for i in r4: writer.writerow([avg4PI[i]]) for i in r5: writer.writerow([avg5PI[i]]) writer.writerow(['O2']) writer.writerow([avg0O2]) for i in rdrop: writer.writerow([avgdropO2[i]]) for i in r1: writer.writerow([avg1O2[i]]) for i in r2: writer.writerow([avg2O2[i]]) for i in r3: writer.writerow([avg3O2[i]]) for i in r4: writer.writerow([avg4O2[i]]) for i in r5: writer.writerow([avg5O2[i]]) writer.writerow(['PR']) writer.writerow([avg0PR]) for i in rdrop: writer.writerow([avgdropPR[i]]) for i in r1: writer.writerow([avg1PR[i]]) for i in r2: writer.writerow([avg2PR[i]]) for i in r3: writer.writerow([avg3PR[i]]) for i in r4: writer.writerow([avg4PR[i]]) for i in r5: writer.writerow([avg5PR[i]]) writer.writerow(['Data Recording Time Length']) writer.writerows(RTL) writer.writerow(['Pre Desat Counts for X Minutes']) writer.writerows(PreDesats) writer.writerow(['Post Dest Counts for X Minutes']) writer.writerows(PostDesats) """ Explanation: Export to CSV End of explanation """
ES-DOC/esdoc-jupyterhub
notebooks/cmcc/cmip6/models/cmcc-cm2-sr5/land.ipynb
gpl-3.0
# DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cmcc', 'cmcc-cm2-sr5', 'land') """ Explanation: ES-DOC CMIP6 Model Properties - Land MIP Era: CMIP6 Institute: CMCC Source ID: CMCC-CM2-SR5 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 """
azhurb/deep-learning
intro-to-tflearn/TFLearn_Sentiment_Analysis.ipynb
mit
import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical """ Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with Numpy, we'll be using TFLearn, a high-level library built on top of TensorFlow. TFLearn makes it simpler to build networks just by defining the layers. It takes care of most of the details for you. We'll start off by importing all the modules we'll need, then load and prepare the data. End of explanation """ reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) """ Explanation: Preparing the data Following along with Andrew, our goal here is to convert our reviews into word vectors. The word vectors will have elements representing words in the total vocabulary. If the second position represents the word 'the', for each review we'll count up the number of times 'the' appears in the text and set the second position to that count. I'll show you examples as we build the input data from the reviews data. Check out Andrew's notebook and video for more about this. Read the data Use the pandas library to read the reviews and postive/negative labels from comma-separated files. The data we're using has already been preprocessed a bit and we know it uses only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like The, the, and THE, all the same way. End of explanation """ from collections import Counter total_counts = Counter()# bag of words here for idx, review in reviews.iterrows(): total_counts.update(review[0].split(" ")) print("Total words in data set: ", len(total_counts)) """ Explanation: Counting word frequency To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how to do this in Andrew's lesson. Try to implement it here using the Counter class. Exercise: Create the bag of words from the reviews data and assign it to total_counts. The reviews are stores in the reviews Pandas DataFrame. If you want the reviews as a Numpy array, use reviews.values. You can iterate through the rows in the DataFrame with for idx, row in reviews.iterrows(): (documentation). When you break up the reviews into words, use .split(' ') instead of .split() so your results match ours. End of explanation """ vocab = sorted(total_counts, key=total_counts.get, reverse=True)[:10000] print(vocab[:60]) """ Explanation: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in the vocabulary are rarely used so they will have little effect on our predictions. Below, we'll sort vocab by the count value and keep the 10000 most frequent words. End of explanation """ print(vocab[-1], ': ', total_counts[vocab[-1]]) """ Explanation: What's the last word in our vocabulary? We can use this to judge if 10000 is too few. If the last word is pretty common, we probably need to keep more words. End of explanation """ word2idx = {word: idx for idx, word in enumerate(vocab)}## create the word-to-index dictionary here """ Explanation: The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words. Note: When you run, you may see a different word from the one shown above, but it will also have the value 30. That's because there are many words tied for that number of counts, and the Counter class does not guarantee which one will be returned in the case of a tie. Now for each review in the data, we'll make a word vector. First we need to make a mapping of word to index, pretty easy to do with a dictionary comprehension. Exercise: Create a dictionary called word2idx that maps each word in the vocabulary to an index. The first word in vocab has index 0, the second word has index 1, and so on. End of explanation """ def text_to_vector(text): vector = np.zeros(len(vocab), dtype = np.int_) for word in text.split(" "): idx = word2idx.get(word) if idx is not None: vector[idx] += 1 return vector """ Explanation: Text to vector function Now we can write a function that converts a some text to a word vector. The function will take a string of words as input and return a vector with the words counted up. Here's the general algorithm to do this: Initialize the word vector with np.zeros, it should be the length of the vocabulary. Split the input string of text into a list of words with .split(' '). Again, if you call .split() instead, you'll get slightly different results than what we show here. For each word in that list, increment the element in the index associated with that word, which you get from word2idx. Note: Since all words aren't in the vocab dictionary, you'll get a key error if you run into one of those words. You can use the .get method of the word2idx dictionary to specify a default returned value when you make a key error. For example, word2idx.get(word, None) returns None if word doesn't exist in the dictionary. End of explanation """ text_to_vector('The tea is for a party to celebrate ' 'the movie so she has no time for a cake')[:65] """ Explanation: If you do this right, the following code should return ``` text_to_vector('The tea is for a party to celebrate ' 'the movie so she has no time for a cake')[:65] array([0, 1, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]) ``` End of explanation """ #print(len(reviews)) word_vectors = np.zeros((len(reviews), len(vocab)), dtype=np.int_) for ii, (_, text) in enumerate(reviews.iterrows()): word_vectors[ii] = text_to_vector(text[0]) # Printing out the first 5 word vectors word_vectors[:5, :23] """ Explanation: Now, run through our entire review data set and convert each review to a word vector. End of explanation """ Y = (labels=='positive').astype(np.int_) records = len(labels) shuffle = np.arange(records) np.random.shuffle(shuffle) test_fraction = 0.9 train_split, test_split = shuffle[:int(records*test_fraction)], shuffle[int(records*test_fraction):] trainX, trainY = word_vectors[train_split,:], to_categorical(Y.values[train_split], 2) testX, testY = word_vectors[test_split,:], to_categorical(Y.values[test_split], 2) trainY """ Explanation: Train, Validation, Test sets Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. Here we're using the function to_categorical from TFLearn to reshape the target data so that we'll have two output units and can classify with a softmax activation function. We actually won't be creating the validation set here, TFLearn will do that for us later. End of explanation """ # Network building def build_model(): # This resets all parameters and variables, leave this here tf.reset_default_graph() #### Your code #### net = tflearn.input_data([None, 10000]) net = tflearn.fully_connected(net, 100, activation='ReLU') net = tflearn.fully_connected(net, 50, activation='ReLU') net = tflearn.fully_connected(net, 2, activation='softmax') net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') model = tflearn.DNN(net) return model """ Explanation: Building the network TFLearn lets you build the network by defining the layers. Input layer For the input layer, you just need to tell it how many units you have. For example, net = tflearn.input_data([None, 100]) would create a network with 100 input units. The first element in the list, None in this case, sets the batch size. Setting it to None here leaves it at the default batch size. The number of inputs to your network needs to match the size of your data. For this example, we're using 10000 element long vectors to encode our input data, so we need 10000 input units. Adding layers To add new hidden layers, you use net = tflearn.fully_connected(net, n_units, activation='ReLU') This adds a fully connected layer where every unit in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call. It's telling the network to use the output of the previous layer as the input to this layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling net = tflearn.fully_connected(net, n_units). Output layer The last layer you add is used as the output layer. Therefore, you need to set the number of units to match the target data. In this case we are predicting two classes, positive or negative sentiment. You also need to set the activation function so it's appropriate for your model. Again, we're trying to predict if some input data belongs to one of two classes, so we should use softmax. net = tflearn.fully_connected(net, 2, activation='softmax') Training To set how you train the network, use net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') Again, this is passing in the network you've been building. The keywords: optimizer sets the training method, here stochastic gradient descent learning_rate is the learning rate loss determines how the network error is calculated. In this example, with the categorical cross-entropy. Finally you put all this together to create the model with tflearn.DNN(net). So it ends up looking something like net = tflearn.input_data([None, 10]) # Input net = tflearn.fully_connected(net, 5, activation='ReLU') # Hidden net = tflearn.fully_connected(net, 2, activation='softmax') # Output net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') model = tflearn.DNN(net) Exercise: Below in the build_model() function, you'll put together the network using TFLearn. You get to choose how many layers to use, how many hidden units, etc. End of explanation """ model = build_model() """ Explanation: Intializing the model Next we need to call the build_model() function to actually build the model. In my solution I haven't included any arguments to the function, but you can add arguments so you can change parameters in the model if you want. Note: You might get a bunch of warnings here. TFLearn uses a lot of deprecated code in TensorFlow. Hopefully it gets updated to the new TensorFlow version soon. End of explanation """ # Training model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=128, n_epoch=10) """ Explanation: Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Below is the code to fit our the network to our word vectors. You can rerun model.fit to train the network further if you think you can increase the validation accuracy. Remember, all hyperparameter adjustments must be done using the validation set. Only use the test set after you're completely done training the network. End of explanation """ predictions = (np.array(model.predict(testX))[:,0] >= 0.5).astype(np.int_) test_accuracy = np.mean(predictions == testY[:,0], axis=0) print("Test accuracy: ", test_accuracy) """ Explanation: Testing After you're satisified with your hyperparameters, you can run the network on the test set to measure its performance. Remember, only do this after finalizing the hyperparameters. End of explanation """ # Helper function that uses your model to predict sentiment def test_sentence(sentence): positive_prob = model.predict([text_to_vector(sentence.lower())])[0][1] print('Sentence: {}'.format(sentence)) print('P(positive) = {:.3f} :'.format(positive_prob), 'Positive' if positive_prob > 0.5 else 'Negative') sentence = "Moonlight is by far the best movie of 2016." test_sentence(sentence) sentence = "It's amazing anyone could be talented enough to make something this spectacularly awful" test_sentence(sentence) """ Explanation: Try out your own text! End of explanation """
oroszl/szamprob
notebooks/Package01/feladat01.ipynb
gpl-3.0
mondat="A " mondat+="mezőn legelésző " mondat+="bárányok " mondat+="mélyen " mondat+="hallgatnak." print(mondat) """ Explanation: Feladatok Minden feladatot külön notebookba oldj meg! A megoldásnotebook neve tartalmazza a feladat számát! A megoldasok kerüljenek a MEGOLDASOK mappába!<br> Csak azok a feladatok kerülnek elbírálásra amelyek a MEGOLDASOK mappában vannak! A megoldás tartalmazza a megoldandó feladat szövegét a megoldás notebook első markdown cellájában! Kommentekkel illetve markdown cellákkal magyarázd hogy éppen mit csinál az adott kódrészlet!<br> Magyarázat nélkül beküldött feladatok csak fél feladatnak számítanak! 01-komment Tegyél kommentjeleket az alábbi kódcellába úgy, hogy a futtatás végeredményben azt írja ki, hogy A bárányok hallgatnak. Mit jelent a += jel? Fogalmazd meg szavakkal ! End of explanation """ kisbetuk='qwertzuiopasdfghjklyxcvbnm' nagybetuk='QWERTZUIOPASDFGHJKLYXCVBNM' extra='+- %=.~' """ Explanation: 02-egyszerű számolás Hány csillagászati egységet tesz meg a fény egy fertályóra alatt ? A számítás elvégzéséhez definiálj változókat, és végezd el a számítást! 03-karakterlancok és indexelés Az alább definiált három karakterlánc segítségével definiáljunk egy változót, ami a saját keresztnevünket tartalmazza! Az ékezetektől tekintsünk el! Használjunk indexelést elölről és hátulról is! End of explanation """ kicsi=['al',9,'+',42.137,'szoveg',69,1j] """ Explanation: 04-lista manipulálás az alábbi cellában definiált kicsi lista segítségével építs egy olyan listát ami háromszor egymás után fordított sorrendben tartalmazza a kicsi lista elemeit. építs egy olyan listát, ami 6 elemű, az első 5 eleme az eredeti kicsi lista elemei a 6. eleme pedig maga a kicsi lista. End of explanation """ telefon_konyv={'Alonzo Hinton': '(855) 278-2590', 'Cleo Hennings': '(844) 832-0585', 'Daine Ventura': '(833) 832-5081', 'Esther Leeson': '(855) 485-0624', 'Gene Connell': '(811) 973-2926', 'Lashaun Bottorff': '(822) 687-1735', 'Marx Hermann': '(844) 164-8116', 'Nicky Duprey': '(811) 032-6328', 'Piper Subia': '(844) 373-4228', 'Zackary Palomares': '(822) 647-3686'} """ Explanation: 05-szótár kezelés Add hozzá az alábbi telefonkönyvhöz 'Samwise Gamgie' (123) 000-1423 telefonszámát! Nézz utána az interneten, hogyan lehet az alábbi telefonkönyvből kinyerni az összes telefonszámot lista formájában! End of explanation """ tesztelendo=[7,5,0,-2] """ Explanation: 06-logikai Írd meg azokat a logikai kifejezéseket, amelyek a tesztelendo nevű listán leellenőrzik az alábbi kérdéseket: * Van-e a számok között 0? * Nagyobb-e a számok összege hatnál? * Igaz-e, hogy az összes szám pozitív? * Igaz-e, hogy van a számok között negatív? * ☠ Igaz-e, hogy van legalább 2 szám, ami nagyobb, mint 5? ☠ End of explanation """
jbpoline/newpower
peakdistribution/find_peakdistr.ipynb
mit
% matplotlib inline import os import numpy as np import nibabel as nib from nipy.labs.utils.simul_multisubject_fmri_dataset import surrogate_3d_dataset import nipy.algorithms.statistics.rft as rft from __future__ import print_function, division import math import matplotlib.pyplot as plt import palettable.colorbrewer as cb from nipype.interfaces import fsl import pandas as pd import nipy.algorithms.statistics.intvol as intvol from matplotlib import colors import scipy.stats as stats """ Explanation: Find distribution of local maxima in a Gaussian Random Field In this notebook, I try to find the distribution of local maxima in a Gaussian Random Field. I followed several steps to (a) look at the distribution through simulations, (b) apply different possible approaches to find the distribution. It is a draft and a bit a mess of things that might seem logical stuff, but I also wanted to summarise (and see) more or less what is known. 1. Simulate random fields (without activation) and extract local maxima In a first step, I - Simulate a guassian random field using nipype. This field is huge (500x500x500) and therefore memory-intensive to ensure we have lots of local maxima. - Look at the GRF. - Export the GRF to a nifti file. Before saving the data, I make sure all values are positive, because step (d) only extracts local maxima that are above 0. - Extract all local maxima using nipype and fsl cluster. - Look at the table of local maxima and print the total number of peaks. - Look at the distribution of these maxima. Import libraries End of explanation """ smooth_FWHM = 3 smooth_sd = smooth_FWHM/(2*math.sqrt(2*math.log(2))) data = surrogate_3d_dataset(n_subj=1,sk=smooth_sd,shape=(500,500,500),noise_level=1) """ Explanation: Simulate very large RF End of explanation """ plt.figure(figsize=(6,4)) plt.imshow(data[1:20,1:20,1]) plt.colorbar() plt.show() """ Explanation: Show part of the RF (20x20x1) End of explanation """ minimum = data.min() newdata = data - minimum #little trick because fsl.model.Cluster ignores negative values img=nib.Nifti1Image(newdata,np.eye(4)) img.to_filename("files/RF.nii.gz") """ Explanation: Save RF End of explanation """ cl=fsl.model.Cluster() cl.inputs.threshold = 0 cl.inputs.in_file="files/RF.nii.gz" cl.inputs.out_localmax_txt_file="files/locmax.txt" cl.inputs.num_maxima=1000000 cl.inputs.connectivity=26 cl.inputs.terminal_output='none' cl.run() """ Explanation: Run fsl cluster to extract local maxima End of explanation """ peaks = pd.read_csv("files/locmax.txt",sep="\t").drop('Unnamed: 5',1) peaks.Value = peaks.Value + minimum peaks[:5] len(peaks) """ Explanation: Read and print top of file with peaks , print total number of peaks. End of explanation """ col=cb.qualitative.Set1_8.mpl_colors plt.figure(figsize=(6,3)) ax=plt.subplot(111) ax.hist(peaks.Value,40,normed=1,facecolor=col[0],alpha=0.75,lw=0) ax.set_xlim([-1,5]) plt.show() """ Explanation: Plot histogram local maxima End of explanation """ def nulprobdens(exc,peaks): v = exc u = peaks - v f0 = (2+(u+v)**2)*(u+v)*np.exp(-(u+v)**2/2)/(v**2*np.exp(-v**2/2)) return f0 """ Explanation: 2. First approach: analytically derived distribution of local maxima above u a. (Cheng & Schwartzman, 2015) b. RFT Cheng and Schwartzman recently published a paper in which they derive a distribution of local maxima over a certain threshold. They make (like RFT) the assumption that the field is a GRF whose interior is non-empty... A consequence is that we can only compute this when the threshold is high enough to ensure there are only blobs and no holes. We'll take a look how the theoretical distribution performs for lower thresholds. This is their derived distribution: For all local maxima above threshold $v$, extending $u$ above this threshold, For each $t_0 \in T$ and each fixed $u>0$, as $v \rightarrow \infty$, \begin{equation} F_t(u,v) = \frac{(u+v)^{N-1}e^{-(u+v)^2/2}}{v^{N-1}e^{-v^2/2}} \end{equation} Below you can see that the approximation indeed only works well on very high thresholds, and therefore cannot be used to obtain the full distribution of all peaks. We also compare with the random field theory approximation, with u the threshold: \begin{equation} F_t(u,t_0) = u e^{-u(t_0 - u)} \end{equation} Function for pdf of peaks given a certain threshold End of explanation """ def nulprobdensRFT(exc,peaks): f0 = exc*np.exp(-exc*(peaks-exc)) return f0 """ Explanation: Function for pdf of peaks given a certain threshold, RFT End of explanation """ fig,axs=plt.subplots(1,5,figsize=(13,3)) fig.subplots_adjust(hspace = .5, wspace=0.3) axs=axs.ravel() thresholds=[2,2.5,3,3.5,4] bins=np.arange(2,5,0.5) x=np.arange(2,10,0.0001) twocol=cb.qualitative.Paired_10.mpl_colors for i in range(5): thr=thresholds[i] axs[i].hist(peaks.Value[peaks.Value>thr],lw=0,facecolor=twocol[i*2-2],normed=True,bins=np.arange(thr,5,0.1)) axs[i].set_xlim([thr,5]) axs[i].set_ylim([0,3]) xn = x[x>thr] yn = nulprobdens(thr,xn) ynb = nulprobdensRFT(thr,xn) axs[i].plot(xn,yn,color=twocol[i*2-1],lw=3,label="C&S") axs[i].plot(xn,ynb,color=twocol[i*2-1],lw=3,linestyle="--",label="RFT") axs[i].set_title("threshold:"+str(thr)) axs[i].set_xticks(np.arange(thr,5,0.5)) axs[i].set_yticks([1,2]) axs[i].legend(loc="upper right",frameon=False) axs[i].set_xlabel("peak height") axs[i].set_ylabel("density") plt.show() """ Explanation: Compute density function over a range with different excursion thresholds End of explanation """ fig,axs=plt.subplots(1,4,figsize=(13,7)) fig.subplots_adjust(hspace = .1, wspace=0.1) axs=axs.ravel() thresholds=np.arange(0,4,1) cmap = colors.ListedColormap(['white', 'black']) bounds=[0,0.5,1] norm = colors.BoundaryNorm(bounds, cmap.N) for t in range(len(thresholds)): mask = np.zeros(shape=data.shape,dtype=np.intp) mask[data>thresholds[t]]=1 axs[t].imshow(mask[1:200,1:200,20],cmap=cmap,norm=norm) axs[t].set_title("threshold:"+str(thresholds[t])) axs[t].patch.set_visible(False) axs[t].axis('off') """ Explanation: In this figure, we see the observed tail distribution of the local maxima (light colored) in our simulated data. The thick line represents the theoretical distribution of the local maxima above a certain threshold. It is only a good approximation for really high thresholds. RFT works better for lower thresholds. 3. Second approach: what can we use the Euler Characteristic for? The Euler Characteristic is a topological invariant that represents for a certain threshold applied to a certain random field #peaks - #holes. Therefore, again, if the threshold is high enough (there are no holes), it computes the number of peaks. If we compute the EC for a range of thresholds (above a certain threshold), we can construct a pdf of peak heights. It should be noted that the number of peaks is dependent of the smoothness, but this dependency can be taken out by dividing the smoothness by the total volume as a correcting factor. This principle has led to a theoretical approximation of the pdf of peaks, which is closely related to the approach of Cheng \& Schwartzmann. Let's first look at the masks that result from our random field with certain thresholds End of explanation """ EulerDens = [] EulerDensInv = [] urange = np.arange(-4,4,0.3) for t in urange: mask = np.zeros(shape=data.shape,dtype=np.intp) mask[data>t]=1 EulerDens.append(intvol.EC3d(mask)) mask2 = 1-mask EulerDensInv.append(intvol.EC3d(mask2)) sumpeak = [] for t in urange: sumpeak.append(sum(peaks.Value>t)) plt.figure(figsize=(7,5)) plt.plot(urange,EulerDens,color=col[1],lw=3,label="observed Euler Characteristic") plt.plot(urange,EulerDensInv,color=col[2],lw=3,label="observed inverse Euler Characteristic") plt.plot(urange,sumpeak,color=col[3],lw=3,label="Number of peaks") plt.legend(loc="upper right",frameon=False) plt.ylim([-600000,1200000]) plt.show() """ Explanation: Now we'll look at the number of peaks and the Euler Characteristic against the threshold. End of explanation """ smoothnesses = [0,3,6,9] minima = [] for sm in range(len(smoothnesses)): smooth_FWHM = smoothnesses[sm] smooth_sd = smooth_FWHM/(2*math.sqrt(2*math.log(2))) data = surrogate_3d_dataset(n_subj=1,sk=smooth_sd,shape=(500,500,500),noise_level=1) minimum = data.min() newdata = data - minimum #little trick because fsl.model.Cluster ignores negative values minima.append(minimum) img=nib.Nifti1Image(newdata,np.eye(4)) img.to_filename(os.path.join("files/RF_"+str(sm)+".nii.gz")) cl=fsl.model.Cluster() cl.inputs.threshold = 0 cl.inputs.in_file=os.path.join("files/RF_"+str(sm)+".nii.gz") cl.inputs.out_localmax_txt_file=os.path.join("files/locmax_"+str(sm)+".txt") cl.inputs.num_maxima=10000000 cl.inputs.connectivity=26 cl.inputs.terminal_output='none' cl.run() """ Explanation: In this plot we can indeed see that the Euler Characteristic gives the number of peaks, but only above a certain threshold that is high enough. Below these higher thresholds, is gives # peaks - # holes. Is there a way to estimate the number of holes in the presence of peaks using the EC? I don't think so, it's the exact same problem as the number of paeks in the presence of holes? Therefore the Euler Characteristic cannot give us information for lower thresholds. 4. Third approach: peaks as the maximum of something of which we know the distribution? The above procedures use the fact that these fields are (should be) continuous fields. However, what comes out of the scanner is not continuous at all. We make it more continuous by applying a smoothing kernel, which allows to use these processes. However, I wonder, is it possible to look at the peaks simply as the maximum of a sample of a known distribution? Can we look at the random fields as multivariate normal with a correlation structure dependent on the smoothness? Here the smoothness comes into play! How does smoothness affect the distribution of the peaks? First simulate random fields for different smoothnesses. End of explanation """ col=cb.qualitative.Set1_8.mpl_colors+cb.qualitative.Set2_8.mpl_colors plt.figure(figsize=(10,5)) ax=plt.subplot(111) for sm in range(len(smoothnesses)): file = os.path.join("files/RF_"+str(sm)+".nii.gz") tvals = nib.load(file).get_data().astype('float64')+minima[sm] values, base = np.histogram(tvals,100,normed=1) ax.plot(base[:-1],values,label="smoothness: "+str(smoothnesses[sm]),color=col[sm],lw=2) ax.set_xlim([-4,4]) ax.set_ylim([0,0.5]) ax.legend(loc="lower right",frameon=False) ax.set_title("distribution of peak heights for different smoothing kernels (FWHM)") plt.show() """ Explanation: Look at the distribution of the voxels? We simulated the random fields to be a GRF, from a normal distribution. Here you can see that indeed the distribution is normal independent from the smoothness. End of explanation """ all = [] for sm in range(len(smoothnesses)): peaks = pd.read_csv(os.path.join("files/locmax_"+str(sm)+".txt"),sep="\t").drop('Unnamed: 5',1).Value peaks = peaks + minima[sm] all.append(peaks) col=cb.qualitative.Set1_8.mpl_colors+cb.qualitative.Set2_8.mpl_colors plt.figure(figsize=(10,5)) ax=plt.subplot(111) for sm in range(len(smoothnesses)): values, base = np.histogram(all[sm],30,normed=1) ax.plot(base[:-1],values,label="smoothness: "+str(smoothnesses[sm]),color=col[sm],lw=2) ax.set_xlim([-1,5]) ax.set_ylim([0,1.2]) ax.legend(loc="lower right",frameon=False) ax.set_title("distribution of peak heights for different smoothing kernels (FWHM)") plt.show() """ Explanation: So how about the distribution of the maximum of a sample of these distributions? End of explanation """ # random sample smplm = [] for i in range(100000): smpl = np.random.standard_normal((n,)) smplm.append(max(smpl)) # distribution xm = np.arange(-1,5,0.001) ym = n*stats.norm.cdf(xm)**(n-1)*stats.norm.pdf(xm) # histogram twocol=cb.qualitative.Paired_10.mpl_colors plt.figure(figsize=(6,3)) ax=plt.subplot(111) ax.hist(smplm,100,normed=1,facecolor=twocol[0],alpha=0.75,lw=0) ax.plot(xm,ym,color=twocol[1],lw=3) ax.set_xlim([-1,5]) plt.show() """ Explanation: As expected, from a certain smoothness (3 x voxel size), the distribution remains the same. First: the distribution without smoothness! The RF with smoothness 0 should be just normally distributed values without correlation. The peaks with smoothness 0 should be just maxima of a sample of normally distributed values. We know the distribution of a sample with normally distribution values from order statistics: $f_{max}(x) = nF(x)^{n-1}f(x)$ This is to show that the distribution of the maximum of the sample is the right one. Simulate n normally distributed values Take the maximum Compute for a range of values the distribution of the maximum Show histogram of simulated maxima with the pdf on top End of explanation """ n = (500**3)/len(all[1]) n """ Explanation: Now can we just state that the peaks in our unsmoothed random field is the maxima of a sample? First: the sample size is variable! Let's try it on the average sample size, i.e. the average number of voxels per peak. End of explanation """ # distribution of a maximum xm = np.arange(-1,5,0.001) ym = n*stats.norm.cdf(xm)**(n-1)*stats.norm.pdf(xm) # histogram twocol=cb.qualitative.Paired_10.mpl_colors plt.figure(figsize=(6,3)) ax=plt.subplot(111) ax.hist(all[1],100,normed=1,facecolor=twocol[0],alpha=0.75,lw=0) ax.plot(xm,ym,color=twocol[1],lw=3) ax.set_xlim([-1,5]) plt.show() """ Explanation: Show histogram of peaks of uncorrected field with the distribution of maximum of a sample of size n. End of explanation """ # random sample smplmc = [] n = 2 mean = [0,0] r = 0.2 cov = [[1,r],[r,1]] for i in range(100000): smpl = np.random.multivariate_normal(mean,cov,int(n/n)) smplmc.append(np.max(smpl)) # distribution xmc = np.arange(-2,3,0.001) corf = (1-r)/np.sqrt(1-r**2) ymc = n*stats.norm.cdf(corf*xmc)**(n-1)*stats.norm.pdf(xmc) # histogram twocol=cb.qualitative.Paired_10.mpl_colors plt.figure(figsize=(6,3)) ax=plt.subplot(111) ax.hist(smplmc,100,normed=1,facecolor=twocol[2],alpha=0.75,lw=0) ax.plot(xmc,ymc,color=twocol[3],lw=3) ax.set_xlim([-1,5]) plt.show() # random sample smplmc = [] n = 10 mean = np.array([0,0,0,0,0,0,0,0,0,0]) r = 0.5 cov = np.array([[1,r,r,r,r,r,r,r,r,r], [r,1,r,r,r,r,r,r,r,r], [r,r,1,r,r,r,r,r,r,r], [r,r,r,1,r,r,r,r,r,r], [r,r,r,r,1,r,r,r,r,r], [r,r,r,r,r,1,r,r,r,r], [r,r,r,r,r,r,1,r,r,r], [r,r,r,r,r,r,r,1,r,r], [r,r,r,r,r,r,r,r,1,r], [r,r,r,r,r,r,r,r,r,1] ]) for i in range(100): smpl = np.random.multivariate_normal(mean,cov,int(n/n)) smplmc.append(np.max(smpl)) # distribution (just max of gaussian normal) xm = np.arange(-1,5,0.001) corf = (1-r)/np.sqrt(1-r**2) ym = n*stats.norm.cdf(xm)**(n-1)*stats.norm.pdf(xm) # histogram twocol=cb.qualitative.Paired_10.mpl_colors plt.figure(figsize=(6,3)) ax=plt.subplot(111) ax.hist(smplm,100,normed=1,facecolor=twocol[0],alpha=0.75,lw=0) ax.plot(xm,ym,color=twocol[1],lw=3) ax.set_xlim([-1,5]) plt.show() newline """ Explanation: Ok, I'm stuck. The stuff below is the maximum of a sample with correlation. We have the distribution, but if it doesn't work for uncorrelated values, it's not going to work for correlated values. So I leave it here but it's non-informative. End of explanation """
kevinsung/OpenFermion
docs/fqe/tutorials/fqe_vs_openfermion_quadratic_hamiltonians.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2020 The OpenFermion Developers End of explanation """ try: import fqe except ImportError: !pip install fqe --quiet from typing import Union from itertools import product import fqe from fqe.hamiltonians.restricted_hamiltonian import RestrictedHamiltonian import numpy as np import cirq import openfermion as of from openfermion.testing.testing_utils import random_quadratic_hamiltonian from openfermion.ops import QuadraticHamiltonian from openfermion.linalg.givens_rotations import givens_decomposition_square from openfermion.circuits.primitives import optimal_givens_decomposition from scipy.sparse import csc_matrix from scipy.linalg import expm from scipy.special import binom import scipy as sp # set up the number of orbs and a random quadratic Hamiltonian norbs = 4 ikappa = random_quadratic_hamiltonian(norbs, conserves_particle_number=True, real=True, expand_spin=False, seed=2) ikappa_mat = of.get_sparse_operator(of.get_fermion_operator(ikappa), n_qubits=norbs) # set up initial full Hilbert space wavefunction wfn = np.zeros((2**(norbs), 1), dtype=np.complex128) wfn[int("".join([str(x) for x in [1] * (norbs//2) + [0] * (norbs//2)]), 2), 0] = 1 # alpha1-alpha2 Hartree-Fock state # full space unitary time = np.random.random() hamiltonian_evolution = expm(-1j * ikappa_mat * time) # build a FQE operator corresponding to the Hamiltonian evolution fqe_ham = RestrictedHamiltonian((ikappa.n_body_tensors[1, 0],)) assert fqe_ham.quadratic() # initialize the FQE wavefunction [n-elec, sz, norbs] fqe_wfn = fqe.Wavefunction([[norbs // 2, norbs//2, norbs]]) hf_wf = np.zeros((int(binom(norbs, norbs // 2)), 1), dtype=np.complex128) hf_wf[0, 0] = 1 # right most bit is zero orbital. fqe_wfn.set_wfn(strategy='from_data', raw_data={(norbs//2, norbs//2): hf_wf}) fqe_wfn.print_wfn() """ Explanation: FQE vs OpenFermion vs Cirq: Quadratic Hamiltonian Evolution <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://quantumai.google/openfermion/fqe/tutorials/fqe_vs_openfermion_quadratic_hamiltonians"><img src="https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png" />View on QuantumAI</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/quantumlib/OpenFermion/blob/master/docs/fqe/tutorials/fqe_vs_openfermion_quadratic_hamiltonians.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/quantumlib/OpenFermion/blob/master/docs/fqe/tutorials/fqe_vs_openfermion_quadratic_hamiltonians.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/github_logo_1x.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/OpenFermion/docs/fqe/tutorials/fqe_vs_openfermion_quadratic_hamiltonians.ipynb"><img src="https://quantumai.google/site-assets/images/buttons/download_icon_1x.png" />Download notebook</a> </td> </table> This notebook demonstrates how evolve a state under a quadratic Hamiltonian with FQE, Cirq, and OpenFermion. We first generate a random quadratic hamiltonian using OpenFermion. Then we set up a full $2^{n} \times 2^{n}$ operator and a computational basis state corresponding to a Slater determinant with the zero and one indexed alpha spin-orbitals occupied. We then compare the full space time evolutions to the LU-decomposition evolution implemented in FQE. Lastly, we using the optimal_givens_decomposition to implement the quadratic Hamiltonian time evolution in Cirq. The 1-RDMs are compared for correctness. We purposefully picked a high spin state so the spin-summed 1-RDM from FQE is equivalent to the spinless 1-RDM. End of explanation """ # initialize wavefunction [n-elec, sz, norbs] fqe_wfn = fqe.Wavefunction([[norbs // 2, norbs//2, norbs]]) hf_wf = np.zeros((int(binom(norbs, norbs // 2)), 1), dtype=np.complex128) hf_wf[0, 0] = 1 # right most bit is zero orbital. 2-alpha electron HF is 0011. This is the first element of our particle conserved Hilbert space fqe_wfn.set_wfn(strategy='from_data', raw_data={(norbs//2, norbs//2): hf_wf}) fqe_wfn.print_wfn() # OpenFermion indexes from the left as zero. The RHF state is 1100 wfn[int("".join([str(x) for x in [1] * (norbs//2) + [0] * (norbs//2)]), 2), 0] = 1 print("\nHF-Vector-OpenFermion ", bin(int("".join([str(x) for x in [1] * (norbs//2) + [0] * (norbs//2)]), 2))) fqe_wfn.print_wfn() # before fqe_wfn = fqe_wfn.time_evolve(time, fqe_ham) fqe_wfn.print_wfn() # after final_wfn = hamiltonian_evolution @ wfn # Full space time-evolution """ Explanation: Aside The FQE and cirq/OpenFermion have reverse ordering of the occupation number vectors. Give a bitstring representing occupations 01001 one commonly wants to determine the index of the orbitals used in the 2-orbital Slater determinant. In OpenFermion the orbitals used are 1 and 4. In FQE the orbitals used are 0 and 3. The difference is that OpenFermion starts indexing from the left most bit whereas FQE starts indexing from the right most bit. End of explanation """ def get_opdm(wfn: Union[sp.sparse.coo_matrix, sp.sparse.csr_matrix, sp.sparse.csc_matrix], nso: int) -> np.ndarray: """ A slow way to get 1-RDMs from density matrices or states """ if isinstance(wfn, (sp.sparse.coo_matrix, sp.sparse.csc_matrix)): wfn = wfn.tocsr() wfn = wfn.toarray() opdm = np.zeros((nso, nso), dtype=wfn.dtype) a_ops = [ of.get_sparse_operator(of.jordan_wigner(of.FermionOperator(((p, 0)))), n_qubits=nso) for p in range(nso) ] for p, q in product(range(nso), repeat=2): operator = a_ops[p].conj().T @ a_ops[q] if wfn.shape[0] == wfn.shape[1]: # we are working with a density matrix val = np.trace(wfn @ operator) else: val = wfn.conj().transpose() @ operator @ wfn # print((p, q, r, s), val.toarray()[0, 0]) if isinstance(val, (float, complex, int)): opdm[p, q] = val else: opdm[p, q] = val[0, 0] return opdm fqe_opdm = fqe_wfn.rdm('i^ j') # get the FQE-opdm # get the exactly evolved opdm initial_opdm = np.diag([1] * (norbs//2) + [0] * (norbs//2)) u = expm(1j * ikappa.n_body_tensors[1, 0] * time) final_opdm = u @ initial_opdm @ u.conj().T print(final_opdm) print() # contract the wavefunction opdm test_opdm = get_opdm(final_wfn, norbs) print(test_opdm) assert np.allclose(test_opdm.real, final_opdm.real) assert np.allclose(test_opdm.imag, final_opdm.imag) assert np.allclose(final_opdm, fqe_opdm) cirq_wfn = fqe.to_cirq(fqe_wfn).reshape((-1, 1)) cfqe_opdm = get_opdm(cirq_wfn, 2 * norbs) print() print(cfqe_opdm[::2, ::2]) assert np.allclose(final_opdm, cfqe_opdm[::2, ::2]) # cirq evolution qubits = cirq.LineQubit.range(norbs) prep = cirq.Moment([cirq.X.on(qubits[0]), cirq.X.on(qubits[1])]) rotation = cirq.Circuit(optimal_givens_decomposition(qubits, u.conj().copy())) circuit = prep + rotation final_state = circuit.final_state_vector().reshape((-1, 1)) cirq_opdm = get_opdm(final_state, norbs) print() print(cirq_opdm) assert np.allclose(final_opdm, cirq_opdm) """ Explanation: Compare 1-RDMs It is easy to compare the 1-RDMs of the wavefunctions to confirm they are representing the same state. We will compute the 1-RDM for the wfn and fqe_wfn and compare to the opdm computed from fqe.to_cirq. End of explanation """ # Get the basis rotation circuit rotations, diagonal = givens_decomposition_square(u.conj().T) # Reinitialize the wavefunction to Hartree-Fock fqe_wfn = fqe.Wavefunction([[norbs // 2, norbs // 2, norbs]]) hf_wf = np.zeros((int(binom(norbs, norbs // 2)), 1), dtype=np.complex128) hf_wf[0, 0] = 1 # right most bit is zero orbital. fqe_wfn.set_wfn(strategy='from_data', raw_data={(norbs // 2, norbs // 2): hf_wf}) # Iterate through each layer and time evolve by the appropriate fermion operators for layer in rotations: for givens in layer: i, j, theta, phi = givens op = of.FermionOperator(((2 * j, 1), (2 * j, 0)), coefficient=-phi) fqe_wfn = fqe_wfn.time_evolve(1.0, op) op = of.FermionOperator(((2 * i, 1), (2 * j, 0)), coefficient=-1j * theta) + of.FermionOperator(((2 * j, 1), (2 * i, 0)), coefficient=1j * theta) fqe_wfn = fqe_wfn.time_evolve(1.0, op) # evolve the last diagonal phases for idx, final_phase in enumerate(diagonal): if not np.isclose(final_phase, 1.0): op = of.FermionOperator(((2 * idx, 1), (2 * idx, 0)), -np.angle(final_phase)) fqe_wfn = fqe_wfn.time_evolve(1.0, op) # map the wavefunction to a cirq wavefunction and get the opdm crq_wfn = fqe.to_cirq(fqe_wfn).reshape((-1, 1)) crq_opdm = get_opdm(crq_wfn, 2 * norbs) print(crq_opdm[::2, ::2]) # check if it is the same as our other 1-RDMs assert np.allclose(final_opdm, crq_opdm[::2, ::2]) """ Explanation: Givens rotations with FQE We can use the same circuit generated by OpenFermion except apply the Givens rotations to the FQE wavefunction. Each Givens rotation gate sequence is mapped to $$ e^{-i \theta (a_{p}^{\dagger}a_{q} - a_{q}^{\dagger}a_{p})}e^{i \phi a_{p}^{\dagger}a_{p}} $$ which can be applies sequentially to the state. End of explanation """
scikit-optimize/scikit-optimize.github.io
0.7/notebooks/auto_examples/sklearn-gridsearchcv-replacement.ipynb
bsd-3-clause
print(__doc__) import numpy as np """ Explanation: Scikit-learn hyperparameter search wrapper Iaroslav Shcherbatyi, Tim Head and Gilles Louppe. June 2017. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt Introduction This example assumes basic familiarity with scikit-learn &lt;http://scikit-learn.org/stable/index.html&gt;_. Search for parameters of machine learning models that result in best cross-validation performance is necessary in almost all practical cases to get a model with best generalization estimate. A standard approach in scikit-learn is using :obj:sklearn.model_selection.GridSearchCV class, which takes a set of values for every parameter to try, and simply enumerates all combinations of parameter values. The complexity of such search grows exponentially with the addition of new parameters. A more scalable approach is using :obj:sklearn.model_selection.RandomizedSearchCV, which however does not take advantage of the structure of a search space. Scikit-optimize provides a drop-in replacement for :obj:sklearn.model_selection.GridSearchCV, which utilizes Bayesian Optimization where a predictive model referred to as "surrogate" is used to model the search space and utilized to arrive at good parameter values combination as soon as possible. Note: for a manual hyperparameter optimization example, see "Hyperparameter Optimization" notebook. End of explanation """ from skopt import BayesSearchCV from sklearn.datasets import load_digits from sklearn.svm import SVC from sklearn.model_selection import train_test_split X, y = load_digits(10, True) X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=.25, random_state=0) # log-uniform: understand as search over p = exp(x) by varying x opt = BayesSearchCV( SVC(), { 'C': (1e-6, 1e+6, 'log-uniform'), 'gamma': (1e-6, 1e+1, 'log-uniform'), 'degree': (1, 8), # integer valued parameter 'kernel': ['linear', 'poly', 'rbf'], # categorical parameter }, n_iter=32, cv=3 ) opt.fit(X_train, y_train) print("val. score: %s" % opt.best_score_) print("test score: %s" % opt.score(X_test, y_test)) """ Explanation: Minimal example A minimal example of optimizing hyperparameters of SVC (Support Vector machine Classifier) is given below. End of explanation """ from skopt import BayesSearchCV from skopt.space import Real, Categorical, Integer from sklearn.datasets import load_digits from sklearn.svm import LinearSVC, SVC from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split X, y = load_digits(10, True) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # pipeline class is used as estimator to enable # search over different model types pipe = Pipeline([ ('model', SVC()) ]) # single categorical value of 'model' parameter is # sets the model class # We will get ConvergenceWarnings because the problem is not well-conditioned. # But that's fine, this is just an example. linsvc_search = { 'model': [LinearSVC(max_iter=1000)], 'model__C': (1e-6, 1e+6, 'log-uniform'), } # explicit dimension classes can be specified like this svc_search = { 'model': Categorical([SVC()]), 'model__C': Real(1e-6, 1e+6, prior='log-uniform'), 'model__gamma': Real(1e-6, 1e+1, prior='log-uniform'), 'model__degree': Integer(1,8), 'model__kernel': Categorical(['linear', 'poly', 'rbf']), } opt = BayesSearchCV( pipe, [(svc_search, 20), (linsvc_search, 16)], # (parameter space, # of evaluations) cv=3 ) opt.fit(X_train, y_train) print("val. score: %s" % opt.best_score_) print("test score: %s" % opt.score(X_test, y_test)) """ Explanation: Advanced example In practice, one wants to enumerate over multiple predictive model classes, with different search spaces and number of evaluations per class. An example of such search over parameters of Linear SVM, Kernel SVM, and decision trees is given below. End of explanation """ from skopt import BayesSearchCV from sklearn.datasets import load_iris from sklearn.svm import SVC X, y = load_iris(True) searchcv = BayesSearchCV( SVC(gamma='scale'), search_spaces={'C': (0.01, 100.0, 'log-uniform')}, n_iter=10, cv=3 ) # callback handler def on_step(optim_result): score = searchcv.best_score_ print("best score: %s" % score) if score >= 0.98: print('Interrupting!') return True searchcv.fit(X, y, callback=on_step) """ Explanation: Progress monitoring and control using callback argument of fit method It is possible to monitor the progress of :class:BayesSearchCV with an event handler that is called on every step of subspace exploration. For single job mode, this is called on every evaluation of model configuration, and for parallel mode, this is called when n_jobs model configurations are evaluated in parallel. Additionally, exploration can be stopped if the callback returns True. This can be used to stop the exploration early, for instance when the accuracy that you get is sufficiently high. An example usage is shown below. End of explanation """ from skopt import BayesSearchCV from sklearn.datasets import load_iris from sklearn.svm import SVC X, y = load_iris(True) searchcv = BayesSearchCV( SVC(), search_spaces=[ ({'C': (0.1, 1.0)}, 19), # 19 iterations for this subspace {'gamma':(0.1, 1.0)} ], n_iter=23 ) print(searchcv.total_iterations) """ Explanation: Counting total iterations that will be used to explore all subspaces Subspaces in previous examples can further increase in complexity if you add new model subspaces or dimensions for feature extraction pipelines. For monitoring of progress, you would like to know the total number of iterations it will take to explore all subspaces. This can be calculated with total_iterations property, as in the code below. End of explanation """
drivendata/data-science-is-software
notebooks/lectures/4.0-testing.ipynb
mit
from __future__ import print_function import os import numpy as np import pandas as pd PROJ_ROOT = os.path.abspath(os.path.join(os.pardir, os.pardir)) """ Explanation: <table style="width:100%; border: 0px solid black;"> <tr style="width: 100%; border: 0px solid black;"> <td style="width:75%; border: 0px solid black;"> <a href="http://www.drivendata.org"> <img src="https://s3.amazonaws.com/drivendata.org/kif-example/img/dd.png" /> </a> </td> </tr> </table> Data Science is Software Developer #lifehacks for the Jupyter Data Scientist Section 4: Don't let other people break your toys Motivation "Many machine learning algorithms have a curious property: they are robust against bugs. Since they’re designed to deal with noisy data, they can often deal pretty well with noise caused by math mistakes as well. If you make a math mistake in your implementation, the algorithm might still make sensible-looking predictions. This is bad news, not good news. It means bugs are subtle and hard to detect. Your algorithm might work well in some situations, such as small toy datasets you use for validation, and completely fail in other situations — high dimensions, large numbers of training examples, noisy observations, etc." — Roger Gross, "Testing MCMC code, part 1: unit tests", Harvard Intelligent Probabilistic Systems group End of explanation """ data = np.random.normal(0.0, 1.0, 1000000) assert np.mean(data) == 0.0 np.testing.assert_almost_equal(np.mean(data), 0.0, decimal=2) a = np.random.normal(0, 0.0001, 10000) b = np.random.normal(0, 0.0001, 10000) np.testing.assert_array_equal(a, b) np.testing.assert_array_almost_equal(a, b, decimal=3) """ Explanation: numpy.testing Provides useful assertion methods for values that are numerically close and for numpy arrays. End of explanation """ import engarde.decorators as ed test_data = pd.DataFrame({'a': np.random.normal(0, 1, 100), 'b': np.random.normal(0, 1, 100)}) @ed.none_missing() def process(dataframe): dataframe.loc[10, 'a'] = 1.0 return dataframe process(test_data).head() """ Explanation: engarde decorators A new library that lets you practice defensive program--specifically with pandas DataFrame objects. It provides a set of decorators that check the return value of any function that returns a DataFrame and confirms that it conforms to the rules. End of explanation """
LSSTDESC/Twinkles
doc/SLSimDocumentation/strong_lensing_review.ipynb
mit
import numpy as np import matplotlib.pyplot as plt import pandas as pd from astropy.io import fits plt.style.use('ggplot') %matplotlib inline om10_cat = fits.open('../../data/twinkles_lenses_v2.fits')[1].data sprinkled_lens_gals = pd.read_csv('../../data/sprinkled_lens_galaxies_230.txt') sprinkled_agn = pd.read_csv('../../data/sprinkled_agn_230.txt') """ Explanation: Strong Lensing in Twinkles Overview Strong Lensing in Twinkles simulations involves taking existing CATSIM instance catalogs and replacing specific AGN within those catalogs with a Strongly Lensed AGN system. This means adding images of the original AGN and a lens galaxy into the CATSIM instance catalogs. This is done using a piece of code in the Twinkles repository that is known as the sprinkler. This notebook will first discuss the sprinkler and then move onto verifying its outputs in instance catalogs. Sprinkler Code Review The sprinkler code can be found here. It involves a step inserted into the final pass method of the Instance Catalog class that allows manipulation of the array of catalog results to be manipulated before printing out. This step starts with the loading of an OM10 based catalog of strongly lensed AGN systems. The OM10-Twinkles Catalog The catalog we are using started with the set of the 872 rung 4 lenses from the Time Delay Challenge 1 (see discussion in this issue on why these were chosen). However, when looking through this catalog we learned that sizes were missing for the foreground lens galaxies and we have chosen to use CATSIM galaxies to add this information to the catalog as well as an SED for each of these foreground galaxies. This process was completed in this issue. In the process 11 galaxies were unable to be matched adequately to CATSIM galaxies so we end up with a final catalog in Twinkles of 861 galaxies. Selecting Sprinkled Systems The next step after loading the lensing catalog is to go through the instance catalog AGNs one at a time and see if they match a lens system from our OM10-Twinkles catalog. The matching is done by taking the redshift and magnitude of the CATSIM AGN and selecting any available lens systems with a source AGN that has a redshift within 0.1 dex and an LSST magnorm value (magnitude in a simulated filter with one bin at 500nm) within .25 mags. Once the possible matches to a given instance catalog AGN are found there is a chance that it will be replaced that is set by the density parameter in the sprinkler class. In the current Twinkles run it is set at 1.0 so that 198 lens systems are sprinkled into the Twinkles instance catalogs. If the AGN is chosen to be sprinkled then we proceed with the sprinkler and if there are multiple matches from the OM10-Twinkles catalog we randomly choose one to use as we proceed. First, we remove any disc and bulge information for that galaxy from the instance catalog leaving only the AGN data and copy this AGN entry creating 2 or 4 entries in the catalog depending upon the number of images the OM10 system we are sprinkling in has in total. Next we use the OM10 data for each image to shift the location of the AGN in each image to the correct location and adjust the magnitude for each entry depending on the OM10 magnification parameter for each AGN image. At this point we also adjust the time delay for each image with OM10 info and give all the images the same source redshift from the OM10 entry. Once the new entries are ready they are appended to the instance catalog with a new instance catalog id tag that gives us the ID of the Bulge galaxy in the instance catalog to which it is associated and the ID number of the OM10-Twinkles catalog system that is used. The next step is to take the original entry in the instance catalog and add in the information for the foreground lens galaxy. Therefore, in this step the AGN and Disc data for the original galaxy are cleared and the redshift and magnitude for the lens galaxy from the OM10 system is added into the instance catalog. Here we also add in the radius of the lens galaxy and the sed file we want to use (the information added to the original OM10 systems in the process described in the last section). We also add in the OM10 position angles and ellipticities at this point. Once we have gone through this process for all AGN in the instance catalog then we return to the normal instance catalog processing to write the information out to file. Verifying Instance Catalog Output For the sections below I am using the output from an instance catalog created using Twinkles and removing the SNe entries at the bottom. I then split it up into the bulge+disk galaxy entries and the AGNs before only selecting the objects that were sprinkled. We will also load in the OM10-Twinkles catalog of strongly lensed AGN systems for validation purposes. This catalog is where all the lens systems that end up in Twinkles catalogs are stored. Loading datasets End of explanation """ sprinkled_agn[:20] """ Explanation: This file loaded contains extra information to a normal instance catalog output. During the sprinkling process as new id numbers are given to the sprinkled AGN all of their ids are larger than 1e11 while those unsprinkled are not. These larger Ids contain information on the OM10-Twinkles system used in the sprinkler, the image number in that system and the associated lens galaxy. We have previously added columns containing this information to the instance catalog information for the AGN. End of explanation """ x_sep_inst = [] y_sep_inst = [] x_sep_om10 = [] y_sep_om10 = [] for agn_row in range(len(sprinkled_agn)): lens_gal_current = sprinkled_agn['lens_gal_id'][agn_row] twinkles_current = sprinkled_agn['twinkles_id'][agn_row] im_num_current = sprinkled_agn['image_num'][agn_row] om10_current = om10_cat[om10_cat['twinklesId'] == twinkles_current] lens_ra = sprinkled_lens_gals.query('id == %i' % lens_gal_current)['ra'].values[0] lens_dec = sprinkled_lens_gals.query('id == %i' % lens_gal_current)['dec'].values[0] x_sep_inst.append(((sprinkled_agn['ra'][agn_row] - lens_ra)*3600.)*np.cos(np.radians(lens_dec))) y_sep_inst.append((sprinkled_agn['dec'][agn_row] - lens_dec)*3600) x_sep_om10.append(om10_current['XIMG'][0][im_num_current]) y_sep_om10.append(om10_current['YIMG'][0][im_num_current]) fig = plt.figure(figsize=(12, 6)) fig.add_subplot(1,2,1) p1 = plt.hist(100*(np.array(x_sep_inst) - np.array(x_sep_om10))/np.array(x_sep_om10)) plt.xlabel('Percent Difference') plt.title('XIMG (ra)') fig.add_subplot(1,2,2) p2 = plt.hist(100*(np.array(y_sep_inst) - np.array(y_sep_om10))/np.array(y_sep_om10)) plt.xlabel('Percent Difference') plt.title('YIMG (dec)') plt.suptitle('Difference between OM10 separations and Instance Catalog separations between images and lens galaxy') fig = plt.figure(figsize=(12, 6)) fig.add_subplot(1,2,1) p1 = plt.hist((np.array(x_sep_inst) - np.array(x_sep_om10))) plt.xlabel('Difference (arcsec)') plt.title('XIMG (ra)') fig.add_subplot(1,2,2) p2 = plt.hist((np.array(y_sep_inst) - np.array(y_sep_om10))) plt.xlabel('Difference (arcsec)') plt.title('YIMG (dec)') plt.suptitle('Difference between OM10 separations and Instance Catalog separations between images and lens galaxy') plt.tight_layout() plt.subplots_adjust(top=.9) """ Explanation: Validating Image Positions Our first task is to verify that the image locations in the instance catalog are in the correct places when compared to the entries from the OM10 catalog. To do this we will find the relative ra and dec positions for each of the images in a lensed system relative to the lens galaxy from OM10 and compare the instance catalog values to the appropriate OM10 system. End of explanation """ ellip = np.sqrt(1-((sprinkled_lens_gals['minor_axis']**2)/(sprinkled_lens_gals['major_axis']**2))) sprinkled_lens_gals['r_eff'] = sprinkled_lens_gals['major_axis']*np.sqrt(1-ellip) fig = plt.figure(figsize=(18,6)) fig.add_subplot(1,3,1) p1 = plt.hist(sprinkled_lens_gals['mag_norm']) plt.xlabel('MagNorm (mags @ 500 nm)') fig.add_subplot(1,3,2) p2 = plt.hist(sprinkled_lens_gals['redshift']) plt.xlabel('Redshift') fig.add_subplot(1,3,3) p3 = plt.hist(sprinkled_lens_gals['r_eff']) plt.xlabel('R_Eff (arcsec)') """ Explanation: Overall, differences between the instance catalogs and the OM10 inputs seem to be within 0.01 arcseconds. It appears that the positions in the instance catalog are accurate reproductions of the OM10 data they are based upon. Check distributions of Lens galaxies In the next section we will plot the properties of the lens galaxies in the sprinkled data. End of explanation """ #Use only the brightest AGN image in a system for magnitudes and only record the redshift once for each system agn_magnorm = {} agn_redshifts = [] for agn_row in range(len(sprinkled_agn)): lens_gal_current = sprinkled_agn['lens_gal_id'][agn_row] im_num_current = sprinkled_agn['image_num'][agn_row] om10_current = om10_cat[om10_cat['twinklesId'] == twinkles_current] try: current_val = agn_magnorm[str(lens_gal_current)] if sprinkled_agn['mag_norm'][agn_row] < current_val: agn_magnorm[str(lens_gal_current)] = sprinkled_agn['mag_norm'][agn_row] except KeyError: agn_magnorm[str(lens_gal_current)] = sprinkled_agn['mag_norm'][agn_row] agn_redshifts.append(sprinkled_agn['redshift'][agn_row]) fig = plt.figure(figsize=(12,6)) fig.add_subplot(1,2,1) plt.hist(agn_magnorm.values()) plt.title('Magnitude for brightest AGN image in a system') plt.xlabel('MagNorm (mags @ 500 nm)') fig.add_subplot(1,2,2) plt.hist(agn_redshifts) plt.title('Lensed AGN Redshifts') plt.xlabel('Source Redshifts') plt.suptitle('Lensed AGN Properties') plt.tight_layout() plt.subplots_adjust(top=.9) """ Explanation: Check distributions of Lensed AGN Now we plot the properties of the lensed AGN sprinkled into the instance catalogs. End of explanation """ sprinkled_agn_2 = pd.read_csv('../../data/sprinkled_agn_185614.txt') sprinkled_agn_3 = pd.read_csv('../../data/sprinkled_agn_204392.txt') sprinkled_agn['mag_norm_185614'] = sprinkled_agn_2['mag_norm'] sprinkled_agn['mag_norm_204392'] = sprinkled_agn_3['mag_norm'] #Check if the mag_norm value stays the same from the first visit to the second for any AGN image for agn_row in range(len(sprinkled_agn)): if sprinkled_agn['mag_norm'][agn_row] == sprinkled_agn['mag_norm_185614'][agn_row]: print agn_row """ Explanation: Varaibility Validation Finally, we take a look to make sure that the magnitudes for the AGN are not static. We do that by looking at the AGN in two more r band visits from the Twinkles simulation. End of explanation """ fig = plt.figure(figsize=(12,12)) for agn_row in range(10): plt.plot([59580.1, 59825.3, 59857.2], [sprinkled_agn['mag_norm'][agn_row], sprinkled_agn['mag_norm_185614'][agn_row], sprinkled_agn['mag_norm_204392'][agn_row]], marker='+') plt.xlabel('Visit MJD') plt.ylabel('MagNorm (mags @ 500 nm)') plt.title('AGN Image MagNorms for the first three r-band visits for 5 doubly-lensed AGN systems') plt.tight_layout() """ Explanation: As the previous cell shows there are no AGN with the same magnitude from the first visit to the next showing that variability is being calculated for each system. Below we plot a few light curves on the set of three visits. End of explanation """
mne-tools/mne-tools.github.io
0.17/_downloads/9ced5a5fd40c97d018c393deda509609/plot_visualize_raw.ipynb
bsd-3-clause
import os.path as op import numpy as np import mne data_path = op.join(mne.datasets.sample.data_path(), 'MEG', 'sample') raw = mne.io.read_raw_fif(op.join(data_path, 'sample_audvis_raw.fif'), preload=True) raw.set_eeg_reference('average', projection=True) # set EEG average reference """ Explanation: Visualize Raw data End of explanation """ raw.plot(block=True, lowpass=40) """ Explanation: The visualization module (:mod:mne.viz) contains all the plotting functions that work in combination with MNE data structures. Usually the easiest way to use them is to call a method of the data container. All of the plotting method names start with plot. If you're using Ipython console, you can just write raw.plot and ask the interpreter for suggestions with a tab key. To visually inspect your raw data, you can use the python equivalent of mne_browse_raw. End of explanation """ raw.plot(butterfly=True, group_by='position') """ Explanation: The channels are color coded by channel type. Generally MEG channels are colored in different shades of blue, whereas EEG channels are black. The scrollbar on right side of the browser window also tells us that two of the channels are marked as bad. Bad channels are color coded gray. By clicking the lines or channel names on the left, you can mark or unmark a bad channel interactively. You can use +/- keys to adjust the scale (also = works for magnifying the data). Note that the initial scaling factors can be set with parameter scalings. If you don't know the scaling factor for channels, you can automatically set them by passing scalings='auto'. With pageup/pagedown and home/end keys you can adjust the amount of data viewed at once. Drawing annotations You can enter annotation mode by pressing a key. In annotation mode you can mark segments of data (and modify existing annotations) with the left mouse button. You can use the description of any existing annotation or create a new description by typing when the annotation dialog is active. Notice that the description starting with the keyword 'bad' means that the segment will be discarded when epoching the data. Existing annotations can be deleted with the right mouse button. Annotation mode is exited by pressing a again or closing the annotation window. See also :class:mne.Annotations and marking_bad_segments. To see all the interactive features, hit ? key or click help in the lower left corner of the browser window. <div class="alert alert-danger"><h4>Warning</h4><p>Annotations are modified in-place immediately at run-time. Deleted annotations cannot be retrieved after deletion.</p></div> The channels are sorted by channel type by default. You can use the group_by parameter of :func:raw.plot &lt;mne.io.Raw.plot&gt; to group the channels in a different way. group_by='selection' uses the same channel groups as MNE-C's mne_browse_raw (see CACCJEJD). The selections are defined in mne-python/mne/data/mne_analyze.sel and by modifying the channels there, you can define your own selection groups. Notice that this also affects the selections returned by :func:mne.read_selection. By default the selections only work for Neuromag data, but group_by='position' tries to mimic this behavior for any data with sensor positions available. The channels are grouped by sensor positions to 8 evenly sized regions. Notice that for this to work effectively, all the data channels in the channel array must be present. The order parameter allows to customize the order and select a subset of channels for plotting (picks). Here we use the butterfly mode and group the channels by position. To toggle between regular and butterfly modes, press 'b' key when the plotter window is active. Notice that group_by also affects the channel groupings in butterfly mode. End of explanation """ events = mne.read_events(op.join(data_path, 'sample_audvis_raw-eve.fif')) event_id = {'A/L': 1, 'A/R': 2, 'V/L': 3, 'V/R': 4, 'S': 5, 'B': 32} raw.plot(butterfly=True, events=events, event_id=event_id) """ Explanation: We can read events from a file (or extract them from the trigger channel) and pass them as a parameter when calling the method. The events are plotted as vertical lines so you can see how they align with the raw data. We can also pass a corresponding "event_id" to transform the event trigger integers to strings. End of explanation """ raw.plot_sensors(kind='3d', ch_type='mag', ch_groups='position') """ Explanation: We can check where the channels reside with plot_sensors. Notice that this method (along with many other MNE plotting functions) is callable using any MNE data container where the channel information is available. End of explanation """ projs = mne.read_proj(op.join(data_path, 'sample_audvis_eog-proj.fif')) raw.add_proj(projs) raw.plot_projs_topomap() """ Explanation: We used ch_groups='position' to color code the different regions. It uses the same algorithm for dividing the regions as order='position' of :func:raw.plot &lt;mne.io.Raw.plot&gt;. You can also pass a list of picks to color any channel group with different colors. Now let's add some ssp projectors to the raw data. Here we read them from a file and plot them. End of explanation """ projs[0].plot_topomap() """ Explanation: Note that the projections in raw.info['projs'] can be visualized using :meth:raw.plot_projs_topomap &lt;mne.io.Raw.plot_projs_topomap&gt; or calling :func:proj.plot_topomap &lt;mne.Projection.plot_topomap&gt; more examples can be found in sphx_glr_auto_examples_io_plot_read_proj.py End of explanation """ raw.plot() """ Explanation: The first three projectors that we see are the SSP vectors from empty room measurements to compensate for the noise. The fourth one is the average EEG reference. These are already applied to the data and can no longer be removed. The next six are the EOG projections that we added. Every data channel type has two projection vectors each. Let's try the raw browser again. End of explanation """ raw.plot_psd(tmax=np.inf, average=False) """ Explanation: Now click the proj button at the lower right corner of the browser window. A selection dialog should appear, where you can toggle the projectors on and off. Notice that the first four are already applied to the data and toggling them does not change the data. However the newly added projectors modify the data to get rid of the EOG artifacts. Note that toggling the projectors here doesn't actually modify the data. This is purely for visually inspecting the effect. See :func:mne.io.Raw.del_proj to actually remove the projectors. Raw container also lets us easily plot the power spectra over the raw data. Here we plot the data using spatial_colors to map the line colors to channel locations (default in versions >= 0.15.0). Other option is to use the average (default in < 0.15.0). See the API documentation for more info. End of explanation """ layout = mne.channels.read_layout('Vectorview-mag') layout.plot() raw.plot_psd_topo(tmax=30., fmin=5., fmax=60., n_fft=1024, layout=layout) """ Explanation: Plotting channel-wise power spectra is just as easy. The layout is inferred from the data by default when plotting topo plots. This works for most data, but it is also possible to define the layouts by hand. Here we select a layout with only magnetometer channels and plot it. Then we plot the channel wise spectra of first 30 seconds of the data. End of explanation """
numeristical/introspective
examples/SplineCalib_Details.ipynb
mit
import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import ml_insights as mli from sklearn.metrics import roc_auc_score, log_loss ## This is a (rather ugly) function that allows us ## to make piecewise linear functions easily def make_pw_linear_fn(xvals, yvals): def lin_func(x): if type(x)==np.ndarray: return(np.array([lin_func(i) for i in x])) if x<=xvals[0]: return(yvals[0]) elif x>=xvals[-1]: return(yvals[-1]) else: asd=np.max(np.where(x>xv)[0]) return(yv[asd]+((x-xv[asd])*(yv[asd+1]-yv[asd])/(xv[asd+1]-xv[asd]))) return lin_func ## If we specify a set of x_values and y values it returns a function ## that linearly interpolates between them on the domain specified xv = np.array([0,.1,.4,.7,.9,1]) yv = np.array([0,.4,.7,.8,.95,1]) f1 = make_pw_linear_fn(xv,yv) # Here's what the resulting function looks like # We will use this below to represent the "true" calibration function # In other words, when x is our model output, f1(x) will be the # true probability that y=1 given x tvec = np.linspace(0,1,1001) plt.plot(tvec,f1(tvec)) plt.plot(tvec,tvec,'k--') """ Explanation: SplineCalib: The dirty details In this notebook, we dive into the various "knobs" of SplineCalib. While the default settings generally work very well, in some situations the user may want to make some specific adjustments to the spline fitting process. This notebook will walk through several examples where we may want to adjust the default behavior and thereby provide a deeper understanding of the details of how SplineCalib works. End of explanation """ np.random.seed(0) npts = 5000 xvec = np.random.uniform(size =npts) probvec = f1(xvec) yvec = np.random.binomial(n=1, p=probvec) xvec_test = np.random.uniform(size=50000) probvec_test = f1(xvec_test) yvec_test = np.random.binomial(n=1, p=probvec_test) # From this reliability diagram, we see that our scores # are underpredicting the true probability mli.plot_reliability_diagram(yvec,xvec); # We use a SplineCalib with the default settings and fit it to the calibration data sc = mli.SplineCalib() sc.fit(xvec, yvec) # Here is the resulting calibration curve sc.show_calibration_curve() # Here is the calibration curve superimposed on the reliability diagram # We see it fits the data well without being overly wiggly sc.show_calibration_curve() mli.plot_reliability_diagram(yvec,xvec); # Here is the calibration curve compared to the "true" answer # We see it fits well, though it "rounds off" the corners # This is by design, the splines are required to have a continuous # first (and second) derivative sc.show_calibration_curve() plt.plot(tvec, f1(tvec)) # Here we see that the log_loss of our calibrated probabilities # are nearly as good as using the actual "right answer" # and a large improvement over the uncalibrated probabilities (log_loss(yvec_test, xvec_test), log_loss(yvec_test, sc.calibrate(xvec_test)), log_loss(yvec_test, f1(xvec_test))) # Note that the AUROC score does not change. # This will *always* be the case (as long as the calibration curve is increasing) # Because AUROC just depends on the relative ordering of the scores (roc_auc_score(yvec_test, xvec_test), roc_auc_score(yvec_test, sc.calibrate(xvec_test)), roc_auc_score(yvec_test, f1(xvec_test))) """ Explanation: We generate some synthetic data. xvec representes the uncalibrated scores probvec represents the true probability for that score yvec is the binary outcome based on the true probability Given xvec and yvec, we wish to recover an estimate of the function f1 that we defined above which maps scores to true probabilities End of explanation """ # This is a diagnostic tool which shows the cross-validation results # used to choose the best regularization parameter sc.show_spline_reg_plot() sc.best_reg_param, np.log10(sc.best_reg_param) """ Explanation: Section 2: Changing the "reg_param" search SplineCalib uses the sklearn LogisticRegression "under the hood". Spline Calibration works by using a natural spline basis representation and then fitting an L2-regularized Logistic Regression. We use cross-validation to find the best C parameter, where C is the inverse of the lambda parameter you may be familiar with in penalized regression methods. Smaller C means a higher penalty on "wiggliness". By default, SplineCalib looks at 17 equally spaced points (in log10 scale) between -4 and 4. End of explanation """ # Search 51 points between 10**-2 and 10**0 sc1 = mli.SplineCalib(reg_param_vec = np.logspace(-2,0,51)) sc1.fit(xvec, yvec) # Now we explore just the range 1e-2 to 1e0 with more resolution sc1.show_spline_reg_plot() sc1.best_reg_param, np.log10(sc1.best_reg_param) """ Explanation: Above, we see that the best value was found when C=1e-1 or .1. But perhaps there would be an even better value if we searched a finer "grid" of points. In the next cell we will do exactly that. End of explanation """ # We can "focus" our regularization parameter in a narrower range to # try to get a more accurate "best" parameter sc2 = mli.SplineCalib(reg_param_vec = np.logspace(-2,0,51), reg_prec=16 ) sc2.fit(xvec, yvec) sc2.show_spline_reg_plot() sc2.best_reg_param, np.log10(sc2.best_reg_param) # We can see the underlying scores here sc2.reg_param_scores """ Explanation: Why didn't we chooose the minimum value?! By default SplineCalib errs on the side of more regularization and less "wiggly" curves. One way it does this is to round the log_loss values to 4 decimals, and then choose the most regularized variant that achieves the (rounded) minimum. So what we are seeing is that the dotted line achieves a value around .50284, which rounds down to .5028, and nothing else achieves less than .50275. So many values get a rounded score of .5028, and SplineCalib chooses the leftmost (most regularized) one. What if we want the absolute lowest one? We can adjust the number of decimal places we look at using the reg_prec parameter. The default value is 4, but we can make it higher if we wish to. We give an example below. End of explanation """ sc.show_calibration_curve() sc1.show_calibration_curve() sc2.show_calibration_curve() (log_loss(yvec_test, sc.calibrate(xvec_test)), log_loss(yvec_test, sc1.calibrate(xvec_test)), log_loss(yvec_test, sc2.calibrate(xvec_test))) """ Explanation: The differences between the three calibrators is nearly imperceptible... End of explanation """ np.random.seed(0) npts = 100 xvec = np.random.uniform(size =npts) probvec = f1(xvec) yvec = np.random.binomial(n=1, p=probvec) # Here we plot a reliablity diagram with custom bins (10 equally spaced). # Since we have only 100 data points it is hard to see much of a pattern # except that most points seem above the line. plt.figure(figsize=(10,4)) mli.plot_reliability_diagram(yvec,xvec, bins=np.linspace(0,1,11), show_histogram=True); # Try SplineCalib with the default settings sc4 = mli.SplineCalib() sc4.fit(xvec, yvec) # Here is the resulting calibration curve sc4.show_calibration_curve() # The curve does not go to [0,0], let's investigate... sc4.calibrate(np.array([0,1e-16,1e-10,1e-9,1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2])) sc4.logodds_eps, np.min(xvec) """ Explanation: Section 3: The logodds_eps parameter In the next couple of sections, we will imagine that we have only a small set of points from which to learn our calibration. This situation may require us to do some manual tinkering to achieve the best results, though the default should still give a reasonable calibration. End of explanation """ # the smalles value of xvec was .0047, so logodds_eps was set at .001 sc4.logodds_eps, np.min(xvec) # So, all values <=.001 get the same value (.1197) sc4.calibrate(np.array([0,1e-16,1e-10,1e-9,1e-8,1e-7,1e-6,1e-5,1e-4,1e-3,1e-2])) sc5 = mli.SplineCalib(logodds_eps=.0000001) sc5.fit(xvec, yvec) sc5.show_calibration_curve() sc5.logodds_eps, np.min(xvec) sc5.calibrate(np.array([0,1e-16,1e-8,1e-4,1e-3,1e-2])) """ Explanation: What's going on here? Well, it's a bit complicated.... By default, SplineCalib transforms the "incoming" probabilities to log-odds scale before doing the spline basis expansion and subsequent logistic regression. This is generally the "right" thing to do, however, it poses a problem, as 0 and 1 map to -infinity and +infinity respectively. So what should we do? Our solution is to designate a parameter $\epsilon$, and then map everything smaller than $\epsilon$ to $\epsilon$ (and everything larger than ($1-\epsilon$) to ($1-\epsilon$)). There are several justifications for this, but perhaps the most useful is to assume that probabilities are never 0 or 1. And even if, say, a random forest model gives a "probability" of 0 (meaning no trees thought this was a positive case), there is almost certainly some probability that it will indeed be a positive case. So what should be the value of $\epsilon$ or, as we refer to it logodds_eps? By default, SplineCalib will choose a "reasonable" value. It does so based on two principles: 0 should be qualitatively different from the smallest positive value we see in our data set. So if we see a value of .0001 in our training data, logodds_eps should be less than that, so as not to "aggregate" the two different kinds of scores. There should not be a huge gap between where 0 lies after transformation and the next highest value lies. It may be tempting to set logodds_eps at 1e-16, but in practice, this may cause issues since zeros will have high "leverage" in the logistic regression. Thus, by default, SplineCalib uses a heuristic which says, essentially, if the smallest positive value is 1e-4, then set logodds_eps to be 1e-5. (Note: The above principles and reasoning apply analogously to values close to 1, and SplineCalib considers both values close to zero and close to one in choosing logodds_eps) If you wish to override this, you can easily do so by setting logodds_eps manually. End of explanation """ # Negligible difference in performance on the test set (log_loss(yvec_test, sc4.calibrate(xvec_test)), log_loss(yvec_test, sc5.calibrate(xvec_test)) ) """ Explanation: Note, that it is debatable whether or not this behavior is desirable. We have no data for inputs < .0046, so the question is how far we should "extrapolate" and the extent to which we should assume that the true probability approaches 0 as the input goes to zero. End of explanation """ # Take the previous calibration curve and add a unity prior with weight 50 sc6 = mli.SplineCalib(unity_prior=True, unity_prior_weight=25, logodds_eps=.0000001) sc6.fit(xvec, yvec) # We get a warning about lack of convergence. This is usually not a problem, but can # usually be fixed by increasing the number of iterations via "max_iter" sc6 = mli.SplineCalib(unity_prior=True, unity_prior_weight=25, logodds_eps=.0000001, max_iter=5000) sc6.fit(xvec, yvec) # Now increase the weight to 100 sc7 = mli.SplineCalib(unity_prior=True, unity_prior_weight=100, logodds_eps=.0000001, max_iter=5000) sc7.fit(xvec, yvec) # We see that the curve gets closer to the line y=x as we increase the # weight of the unity prior sc5.show_calibration_curve() sc6.show_calibration_curve() sc7.show_calibration_curve() # Adding unity prior of weight 25 slight improves the test set performance in this case # Adding unity priot of weight 100 makes it considerably worse # Recall that our training data was size 100 (log_loss(yvec_test, sc5.calibrate(xvec_test)), log_loss(yvec_test, sc6.calibrate(xvec_test)), log_loss(yvec_test, sc7.calibrate(xvec_test))) """ Explanation: Section 4: The unity_prior Often, when dealing with small calibration training sets, it is useful to use a "unity" prior distribution. This means that, before we see any data, we assume that the input distribution is (relatively) well-calibrated, and we put a "weight" (measured in number of observations) on that belief. In SplineCalib, we control this with the parameters unity_prior, unity_prior_weight, and unity_prior_gridsize. Setting unity_prior to True, will augment the training data with observations along the axis y=x. unity_prior_weight controls the "strength" of the prior, measured in number of observations. unity_prior_gridsize controls the resolution of the augmented points. We deomstrate this below: End of explanation """ # Generate data as before np.random.seed(0) npts = 5000 xvec = np.random.uniform(size =npts) probvec = f1(xvec) yvec = np.random.binomial(n=1, p=probvec) # Filter out 95% of the values where xvec is greater than 0.6 keep_pt = np.random.uniform(size=len(xvec))<.05 mask = (xvec<=.6) | (keep_pt==1) xvec = xvec[mask] yvec = yvec[mask] len(xvec), np.min(xvec), np.max(xvec) # The histogram shows the paucity of data greater than 0.6 plt.figure(figsize=(10,4)) mli.plot_reliability_diagram(yvec, xvec,show_histogram=True); # First, let's try the default SplineCalib parameters sc8 = mli.SplineCalib() sc8.fit(xvec, yvec) sc8.show_calibration_curve() sc8.knot_vec, len(sc8.knot_vec) # Lets try 30 equally spaced knots from 0 to 1 sc9= mli.SplineCalib(knot_sample_size = 0, force_knot_endpts=False, add_knots = np.linspace(0,1,30)) sc9.fit(xvec, yvec) # Looks smoother sc9.show_calibration_curve() sc9.knot_vec, len(sc9.knot_vec) # neglible difference in performance on test set (is slightly worse) # However, gives a more "coherent" curve (log_loss(yvec_test, sc8.calibrate(xvec_test)), log_loss(yvec_test, sc9.calibrate(xvec_test))) # let's force the endpoints, choose 17 additional knots at random # and 11 additional equally spaced knots between 0 and 1 sc10 = mli.SplineCalib(knot_sample_size=19, force_knot_endpts=True, add_knots=np.linspace(0,1,11)) sc10.fit(xvec, yvec) sc10.show_calibration_curve() sc10.knot_vec, len(sc10.knot_vec) (log_loss(yvec_test, sc8.calibrate(xvec_test)), log_loss(yvec_test, sc9.calibrate(xvec_test)), log_loss(yvec_test, sc10.calibrate(xvec_test))) """ Explanation: Section 5: How to choose the knots One key aspect of spline fitting methods is how to choose the "knots". Recall that a natural cubic spline is defined as a different cubic function on each interval, with additional contraints so that the first and second derivatives remain continuous as we cross from one interval to another. The "knots" are the endpoints of the intervals and thereby greatly affect how the spline is fit. The traditional smoothing spline uses all of the observed x-values as knots and relies on the regularization to prevent the spline from becoming too wiggly. However, in practice, using all values adds significantly to the time complexity of the spline-fitting without markedly improving the performance. Consequently, by default, SplineCalib randomly chooses 30 knots, and forces the smallest and largest values to be knots (so technically we choose 28 knots at random from the "interior" values and add in the smallest and largest). We find that this works well in practice. However, we also give the user control in how to choose the knots. Users can increase the size of the randomly sampled knots, force the inclusion of endpoints, and, in fact, force the inclusion of any specified values. This is controlled by the following parameters: knot_sample_size: The size of the random sample of x-values used as knots. If force_knot_endpts is True, the smallest and largest values will be chosen as knots automatically, and knot_sample_size-2 additional knots will be chosen at random from the other values. Default is 30 force_knot_endpts: If True, the smallest and largest input values will automatically be included in the (random) knot sample. If False, this will not be done. Default is True. add_knots: A list or np-array of additional knots to be used. If the user wishes to directly specify knots, they can set knot_sample_size to 0 and give the knots they wish to use in add_knots. To demonstrate some of these features, we create a dataset where values that are greater than 0.6 are rare in the input data. Thus if you rely on purely random selection, this area will be underrepresented in the knots. This may or may not be desirable, depending on other factors. End of explanation """
sonyahanson/assaytools
examples/ipynbs/data-analysis/hsa/analyzing_FLU_hsa_lig1_20150922.ipynb
lgpl-2.1
import numpy as np import matplotlib.pyplot as plt from lxml import etree import pandas as pd import os import matplotlib.cm as cm import seaborn as sns %pylab inline # Get read and position data of each fluorescence reading section def get_wells_from_section(path): reads = path.xpath("*/Well") wellIDs = [read.attrib['Pos'] for read in reads] data = [(float(s.text), r.attrib['Pos']) for r in reads for s in r] datalist = { well : value for (value, well) in data } welllist = [ [ datalist[chr(64 + row) + str(col)] if chr(64 + row) + str(col) in datalist else None for row in range(1,9) ] for col in range(1,13) ] return welllist file_lig1="MI_FLU_hsa_lig1_20150922_150518.xml" file_name = os.path.splitext(file_lig1)[0] label = file_name[0:25] print label root = etree.parse(file_lig1) #find data sections Sections = root.xpath("/*/Section") much = len(Sections) print "****The xml file " + file_lig1 + " has %s data sections:****" % much for sect in Sections: print sect.attrib['Name'] #Work with topread TopRead = root.xpath("/*/Section")[0] welllist = get_wells_from_section(TopRead) df_topread = pd.DataFrame(welllist, columns = ['A - HSA','B - Buffer','C - HSA','D - Buffer', 'E - HSA','F - Buffer','G - HSA','H - Buffer']) df_topread.transpose() # To generate cvs file # df_topread.transpose().to_csv(label + Sections[0].attrib['Name']+ ".csv") """ Explanation: FLUORESCENCE BINDING ASSAY ANALYSIS Experiment date: 2015/09/22 Protein: HSA Fluorescent ligand : dansylamide (lig1) Xml parsing parts adopted from Sonya's assaytools/examples/fluorescence-binding-assay/Src-gefitinib fluorescence simple.ipynb End of explanation """ import numpy as np from scipy import optimize import matplotlib.pyplot as plt %matplotlib inline def model(x,slope,intercept): ''' 1D linear model in the format scipy.optimize.curve_fit expects: ''' return x*slope + intercept # generate some data #X = np.random.rand(1000) #true_slope=1.0 #true_intercept=0.0 #noise = np.random.randn(len(X))*0.1 #Y = model(X,slope=true_slope,intercept=true_intercept) + noise #ligand titration lig1=np.array([200.0000,86.6000,37.5000,16.2000,7.0200, 3.0400, 1.3200, 0.5700, 0.2470, 0.1070, 0.0462, 0.0200]) lig1 # Since I have 4 replicates L=np.concatenate((lig1, lig1, lig1, lig1)) len(L) # Fluorescence read df_topread.loc[:,("B - Buffer", "D - Buffer", "F - Buffer", "H - Buffer")] B=df_topread.loc[:,("B - Buffer")] D=df_topread.loc[:,("D - Buffer")] F=df_topread.loc[:,("F - Buffer")] H=df_topread.loc[:,("H - Buffer")] Y = np.concatenate((B.as_matrix(),D.as_matrix(),F.as_matrix(),H.as_matrix())) (MF,BKG),_ = optimize.curve_fit(model,L,Y) print('MF: {0:.3f}, BKG: {1:.3f}'.format(MF,BKG)) print('y = {0:.3f} * L + {1:.3f}'.format(MF, BKG)) """ Explanation: Calculating Molar Fluorescence (MF) of Free Ligand 1. Maximum likelihood curve-fitting Find the maximum likelihood estimate, $\theta^$, i.e. the curve that minimizes the squared error $\theta^ = \text{argmin} \sum_i |y_i - f_\theta(x_i)|^2$ (assuming i.i.d. Gaussian noise) Y = MF*L + BKG Y: Fluorescence read (Flu unit) L: Total ligand concentration (uM) BKG: background fluorescence without ligand (Flu unit) MF: molar fluorescence of free ligand (Flu unit/ uM) End of explanation """ def model2(x,kd,fr): ''' 1D linear model in the format scipy.optimize.curve_fit expects: ''' # lr =((x+rtot+kd)-((x+rtot+kd)**2-4*x*rtot)**(1/2))/2 # y = bkg + mf*(x - lr) + fr*mf*lr bkg = 86.2 mf = 2.517 rtot = 0.5 return bkg + mf*(x - ((x+rtot+kd)-((x+rtot+kd)**2-4*x*rtot)**(1/2))/2) + fr*mf*(((x+rtot+kd)-((x+rtot+kd)**2-4*x*rtot)**(1/2))/2) # Total HSA concentration (uM) Rtot = 0.5 #Total ligand titration X = L len(X) # Fluorescence read df_topread.loc[:,("A - HSA", "C - HSA", "E - HSA", "G - HSA")] A=df_topread.loc[:,("A - HSA")] C=df_topread.loc[:,("C - HSA")] E=df_topread.loc[:,("E - HSA")] G=df_topread.loc[:,("G - HSA")] Y = np.concatenate((A.as_matrix(),C.as_matrix(),E.as_matrix(),G.as_matrix())) len(Y) (Kd,FR),_ = optimize.curve_fit(model2, X, Y, p0=(5,1)) print('Kd: {0:.3f}, Fr: {1:.3f}'.format(Kd,FR)) """ Explanation: Curve-fitting to binding saturation curve Fluorescence intensity vs added ligand LR= ((X+Rtot+KD)-SQRT((X+Rtot+KD)^2-4XRtot))/2 L= X - LR Y= BKG + MFL + FRMF*LR Constants Rtot: receptor concentration (uM) BKG: background fluorescence without ligand (Flu unit) MF: molar fluorescence of free ligand (Flu unit/ uM) Parameters to fit Kd: dissociation constant (uM) FR: Molar fluorescence ratio of complex to free ligand (unitless) complex flurescence = FRMFLR Experimental data Y: fluorescence measurement X: total ligand concentration L: free ligand concentration End of explanation """
smalladi78/SEF
notebooks/0_DataCleanup-Feb2016.ipynb
unlicense
import pandas as pd import numpy as np import locale import matplotlib.pyplot as plt from bokeh.plotting import figure, show from bokeh.models import ColumnDataSource, HoverTool %matplotlib inline from bokeh.plotting import output_notebook output_notebook() _ = locale.setlocale(locale.LC_ALL, '') thousands_sep = lambda x: locale.format("%.2f", x, grouping=True) #example: print thousands_sep(1234567890.76543) getdate_ym = lambda x: str(x.year) + "_" + str(x.month) getdate_ymd = lambda x: str(x.month) + "/" + str(x.day) + "/" + str(x.year) dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"]) map(getdate_ym, dates) map(getdate_ymd, dates) """ Explanation: Data cleanup This notebook is meant for cleaning up the donation data. The following is a summary of some of the cleanup tasks from this notebook: Load the csv file that has the donors Strip out whitespace from all the columns Fill na with empty strings Change column data types (after examining for correctness) Cleanup amounts column - removed negative (totals to -641910.46 dollars) and zero values Cleanup state codes. Removed donations that are outside of US - about \$30,000 USD Removed donations totaling to 9.5 million dollars that came from anonymous donors (as outliers) If there is no location information or it is inaccurate, move it to a different, move it to a different dataframe Update the city and state names when not present based on the zipcodes dataset. End of explanation """ df = pd.read_csv('in/gifts_Feb2016_2.csv') source_columns = ['donor_id', 'amount_initial', 'donation_date', 'appeal', 'fund', 'city', 'state', 'zipcode_initial', 'charitable', 'sales'] df.columns = source_columns df.info() strip_func = lambda x: x.strip() if isinstance(x, str) else x df = df.applymap(strip_func) """ Explanation: Load csv End of explanation """ df.replace({'appeal': {'0': ''}}, inplace=True) df.appeal.fillna('', inplace=True) df.fund.fillna('', inplace=True) """ Explanation: Address nan column values End of explanation """ df.donation_date = pd.to_datetime(df.donation_date) df.charitable = df.charitable.astype('bool') df['zipcode'] = df.zipcode_initial.str[0:5] fill_zipcode = lambda x: '0'*(5-len(str(x))) + str(x) x1 = pd.DataFrame([[1, '8820'], [2, 8820]], columns=['a','b']) x1.b = x1.b.apply(fill_zipcode) x1 df.zipcode = df.zipcode.apply(fill_zipcode) """ Explanation: Change column types and drop unused columns End of explanation """ ## Ensure that all amounts are dollar figures df[~df.amount_initial.str.startswith('-$') & ~df.amount_initial.str.startswith('$')] ## drop row with invalid data df.drop(df[df.donation_date == '1899-12-31'].index, axis=0, inplace=True) df['amount_cleanup'] = df.amount_initial.str.replace(',', '') df['amount_cleanup'] = df.amount_cleanup.str.replace('$', '') df['amount'] = df.amount_cleanup.astype(float) ## Make sure we did not throw away valid numbers by checking with the original value df[(df.amount == 0)].amount_initial.unique() """ Explanation: Cleanup amounts End of explanation """ # There are some outliers in the data, quite a few of them are recent. _ = plt.scatter(df[df.amount > 5000].amount.values, df[df.amount > 5000].donation_date.values) plt.show() # Fun little thing to try out bokeh (we can hover and detect the culprits) def plot_data(df): dates = map(getdate_ym, pd.DatetimeIndex(df[df.amount > 5000].donation_date)) amounts = map(thousands_sep, df[df.amount > 5000].amount) x = df[df.amount > 5000].donation_date.values y = df[df.amount > 5000].amount.values donor_ids = df[df.amount > 5000].donor_id.values states = df[df.amount > 5000].state.values source = ColumnDataSource( data=dict( x=x, y=y, dates=dates, amounts=amounts, donor_ids=donor_ids, states=states, ) ) hover = HoverTool( tooltips=[ ("date", "@dates"), ("amount", "@amounts"), ("donor", "@donor_ids"), ("states", "@states"), ] ) p = figure(plot_width=400, plot_height=400, title=None, tools=[hover]) p.circle('x', 'y', size=5, source=source) show(p) plot_data(df.query('amount > 5000')) # All the Outliers seem to have the following properties: state == YY and specific donorid. # Plot the remaining data outside of these to check that we caught all the outliers. plot_data(df[~df.index.isin(df.query('state == "YY" and amount > 5000').index)]) # Outlier data df[(df.state == 'YY') & (df.amount >= 45000)] df[(df.state == 'YY') & (df.amount >= 45000)]\ .sort_values(by='amount', ascending=False)\ .head(6)[source_columns]\ .to_csv('out/0/outlier_data.csv') """ Explanation: Outlier data End of explanation """ df.drop(df[(df.state == 'YY') & (df.amount >= 45000)].index, inplace=True) print 'After dropping the anonymous donor, total amounts from the unknown state as a percentage of all amounts is: '\ , thousands_sep(100*df[(df.state == 'YY')].amount.sum()/df.amount.sum()), '%' """ Explanation: Exchanged emails with Anil and confirmed the decision to drop the outlier for the anonymous donor with the 9.5 million dollars. End of explanation """ ## Some funds have zero amounts associated with them. ## They mostly look like costs - expense fees, transaction fees, administrative fees ## Let us examine if we can safely drop them from our analysis df[df.amount_initial == '$0.00'].groupby(['fund', 'appeal'])['donor_id'].count() """ Explanation: Amounts with zero values End of explanation """ df.drop(df[df.amount == 0].index, axis=0, inplace=True) """ Explanation: Dropping rows with zero amounts (after confirmation with SEF office) End of explanation """ ## What is the total amount of the negative? print 'Total negative amount is: ', df[df.amount < 0].amount.sum() # Add if condition to make this re-runnable if df[df.amount < 0].amount.sum() > 0: print 'Amounts grouped by fund and appeal, sorted by most negative amounts' df[df.amount < 0]\ .groupby(['fund', 'appeal'])['amount',]\ .sum()\ .sort_values(by='amount')\ .to_csv('out/0/negative_amounts_sorted.csv') df[df.amount < 0]\ .groupby(['fund', 'appeal'])['amount',]\ .sum()\ .to_csv('out/0/negative_amounts_grouped_by_fund.csv') """ Explanation: Negative amounts End of explanation """ df.drop(df[df.amount < 0].index, axis=0, inplace=True) """ Explanation: Dropping rows with negative amounts (after confirmation with SEF office) End of explanation """ df.info() df.state.unique() ## States imported from http://statetable.com/ states = pd.read_csv('in/state_table.csv') states.rename(columns={'abbreviation': 'state'}, inplace=True) all_states = pd.merge(states, pd.DataFrame(df.state.unique(), columns=['state']), on='state', how='right') invalid_states = all_states[pd.isnull(all_states.id)].state df[df.state.isin(invalid_states)].state.value_counts().sort_index() df[df.state.isin(['56', 'AB', 'BC', 'CF', 'Ca', 'Co', 'HY', 'IO', 'Ny', 'PR', 'UK', 'VI', 'ja'])] %%html <style>table {float:left}</style> """ Explanation: Investigate invalid state codes End of explanation """ state_renames = {'Ny': 'NY', 'IO': 'IA', 'Ca' : 'CA', 'Co' : 'CO', 'CF' : 'FL', 'ja' : 'FL'} df.replace({'state': state_renames}, inplace=True) """ Explanation: Explanation for invalid state codes: State|Count|Action|Explanation| -----|-----|------|-----------| YY|268|None|All these rows are bogus entries (City and Zip are also YYYYs) - about 20% of the donation amount has this ON|62|Remove|This is the state of Ontario, Canada AP|18|Remove|This is data for Hyderabad VI|6|Remove|Virgin Islands PR|5|Remove|Peurto Rico Ny|5|NY|Same as NY - rename Ny as NY 56|1|Remove|This is one donation from Bangalore, Karnataka HY|1|Remove|Hyderabad BC|1|Remove|British Columbia, Canada IO|1|IA|Changed to Iowa - based on city and zip code AB|1|Remove|AB stands for Alberta, Canada Ca|1|CA|Same as California - rename Ca to CA Co|1|CO|Same as Colarado - rename Co to CO CF|1|FL|Changed to Florida based on zip code and city ja|1|FL|Change to FL based on zip code and city UK|1|Remove|London, UK KA|1|Remove|Bangalore, Karnataka End of explanation """ non_usa_states = ['ON', 'AP', 'VI', 'PR', '56', 'HY', 'BC', 'AB', 'UK', 'KA'] print 'Total amount for locations outside USA: ', sum(df[df.state.isin(non_usa_states)].amount) #### Total amount for locations outside USA: 30710.63 df.drop(df[df.state.isin(non_usa_states)].index, axis=0, inplace=True) """ Explanation: Dropping data for non-US locations End of explanation """ print 'Percentage of amount for unknown (YY) state : {:.2f}'.format(100*df[df.state == 'YY'].amount.sum()/df.amount.sum()) print 'Total amount for the unknown state excluding outliers: ', df[(df.state == 'YY') & (df.amount < 45000)].amount.sum() print 'Total amount for the unknown state: ', df[(df.state == 'YY')].amount.sum() print 'Total amount: ', df.amount.sum() """ Explanation: Investigate donations with state of YY End of explanation """ print 'Pecentage of total amount from donations with no location: ', 100*sum(df[(df.city == '') & (df.state == '') & (df.zipcode_initial == '')].amount)/sum(df.amount) noloc_df = df[(df.city == '') & (df.state == '') & (df.zipcode_initial == '')].copy() df = df[~((df.city == '') & (df.state == '') & (df.zipcode_initial == ''))].copy() print df.shape[0] + noloc_df.shape[0] noloc_df = noloc_df.append(df[(df.state == 'YY')]) df = df[~(df.state == 'YY')] # Verify that we transferred all the rows over correctly. This total must match the total from above. print df.shape[0] + noloc_df.shape[0] """ Explanation: We will add these donations to the noloc_df below (which is the donations that have empty strings for the city/state/zipcode. Investigate empty city, state and zip code Pecentage of total amount from donations with no location: 3.087 Moving all the data with no location to a different dataframe. We will investigate the data that does have location information for correctness of location and then merge the no location data back at the end. End of explanation """ noloc_df = noloc_df.append(df[(df.city.str.lower() == 'yyy') | (df.city.str.lower() == 'yyyy')]) df = df[~((df.city.str.lower() == 'yyy') | (df.city.str.lower() == 'yyyy'))] # Verify that we transferred all the rows over correctly. This total must match the total from above. print df.shape[0] + noloc_df.shape[0] """ Explanation: Investigate City in ('YYY','yyy') These entries have invalid location information and will be added to the noloc_df dataframe. End of explanation """ print 'Percentage of total amount for data with City but no state: {:.3f}'.format(100*sum(df[df.state == ''].amount)/sum(df.amount)) df[((df.state == '') & (df.city != ''))][['city','zipcode','amount']].sort_values('city', ascending=True).to_csv('out/0/City_No_State.csv') """ Explanation: Investigate empty state but non-empty city Percentage of total amount for data with City but no state: 0.566 End of explanation """ index = df[(df.donor_id == '-28K0T47RF') & (df.donation_date == '2007-11-30') & (df.city == 'Cupertino')].index df.ix[index,'state'] = 'CA' index = df[(df.donor_id == '9F4812A118') & (df.donation_date == '2012-06-30') & (df.city == 'San Juan')].index df.ix[index,'state'] = 'WA' df.ix[index,'zipcode'] = 98250 # Verified that these remaining entries are for non-US location print 'Total amount for non-USA location: ', df[((df.state == '') & (df.city != ''))].amount.sum() df.drop(df[((df.state == '') & (df.city != ''))].index, inplace=True) """ Explanation: By visually examining the cities for rows that don't have a state, we can see that all the cities are coming from Canada and India and some from other countries (except two entries). So we will correct these two entries and drop all the other rows as they are not relevant to the USA. End of explanation """ print 'Percentage of total amount for data with valid US state, but no city, zipcode: {:.3f}'.format(100*sum(df[(df.city == '') & (df.zipcode_initial == '')].amount)/sum(df.amount)) # Verify that we transferred all the rows over correctly. This total must match the total from above. print df.shape[0] + noloc_df.shape[0] stateonly_df = df[(df.city == '') & (df.zipcode_initial == '')].copy() stateonly_df.state = '' ## Move the rows with just the state over to the noloc_df dataset noloc_df = pd.concat([noloc_df, stateonly_df]) df = df[~((df.city == '') & (df.zipcode_initial == ''))].copy() # Verify that we transferred all the rows over correctly. This total must match the total from above. print df.shape[0] + noloc_df.shape[0] print 100*sum(df[df.city == ''].amount)/sum(df.amount) print len(df[df.city == '']), len(df[df.zipcode_initial == '']) print sum(df[df.city == ''].amount), sum(df[df.zipcode_initial == ''].amount) print sum(df[(df.city == '') & (df.zipcode_initial != '')].amount),\ sum(df[(df.city != '') & (df.zipcode_initial == '')].amount) print sum(df.amount) """ Explanation: Investigate empty city and zipcode but valid US state Percentage of total amount for data with valid US state, but no city, zipcode: 4.509 Most of this amount (1.7 of 1.8 million) is coming from about 600 donors in California. We already know that about California is a major contributor to donations. Although, we can do some analytics based on just the US state using this data, it complicates the analysis that does not substantiate the knowledge gain. Therefore, we are dropping the state column from these rows and moving over this data to the dataset that has no location (the one that we created earlier) to simplify our analysis. End of explanation """ ## Zip codes from ftp://ftp.census.gov/econ2013/CBP_CSV/zbp13totals.zip zipcodes = pd.read_csv('in/zbp13totals.txt', dtype={'zip': object}) zipcodes = zipcodes[['zip', 'city', 'stabbr']] zipcodes = zipcodes.rename(columns = {'zip':'zipcode', 'stabbr': 'state', 'city': 'city'}) zipcodes.city = zipcodes.city.str.title() zipcodes.zipcode = zipcodes.zipcode.astype('str') ## If we know the zip code, we can populate the city by using the zipcodes data df.replace({'city': {'': np.nan}, 'state': {'': np.nan}}, inplace=True) ## Set the index correctly for update to work. Then reset it back. df.set_index(['zipcode'], inplace=True) zipcodes.set_index(['zipcode'], inplace=True) df.update(zipcodes, join='left', overwrite=False, raise_conflict=False) df.reset_index(drop=False, inplace=True) zipcodes.reset_index(drop=False, inplace=True) zipcodesdetail = pd.read_csv('in/zip_code_database.csv') zipcodesdetail = zipcodesdetail[zipcodesdetail.country == 'US'][['zip', 'primary_city', 'county', 'state', 'timezone', 'latitude', 'longitude']] zipcodesdetail = zipcodesdetail.rename(columns = {'zip':'zipcode', 'primary_city': 'city'}) # The zip codes dataset has quite a few missing values. Filling in what we need for now. # If this happens again, search for a different data source!! zipcodesdetail.loc[(zipcodesdetail.city == 'Frisco') & (zipcodesdetail.state == 'TX') & (pd.isnull(zipcodesdetail.county)), 'county'] = 'Denton' # Strip the ' County' portion from the county names def getcounty(county): if pd.isnull(county): return county elif county.endswith(' County'): return county[:-7] else: return county zipcodesdetail.county = zipcodesdetail['county'].apply(getcounty) zipcodesdetail.zipcode = zipcodesdetail.zipcode.apply(fill_zipcode) newcols = np.array(list(set(df.columns).union(zipcodesdetail.columns))) df = pd.merge(df, zipcodesdetail, on=['state', 'city', 'zipcode'], how='inner', suffixes=('_x', ''))[newcols] # For some reason, the data types are being reset. So setting them back to their expected data types. df.donation_date = df.donation_date.apply(pd.to_datetime) df.charitable = df.charitable.apply(bool) df.amount = df.amount.apply(int) """ Explanation: Investigating empty city and empty state with non-empty zip code Since we have the zip code data from the US census data, we can use that to fill in the city and state End of explanation """ all_zipcodes = pd.merge(df, zipcodes, on='zipcode', how='left') all_zipcodes[pd.isnull(all_zipcodes.city_x)].head() ## There seems to be only one row with an invalid zip code. Let's drop it. df.drop(df[df.zipcode_initial.isin(['GU214ND','94000'])].index, axis=0, inplace=True) """ Explanation: Investigate invalid zip codes End of explanation """ print 'No state: count of rows: ', len(df[df.state == ''].amount),\ 'Total amount: ', sum(df[df.state == ''].amount) print 'No zipcode: count of rows: ', len(df[df.zipcode == ''].amount),\ 'Total amount: ', sum(df[df.zipcode == ''].amount) print 'No city: count of rows: ', len(df[df.city == ''].amount),\ 'Total amount: ', sum(df[df.city == ''].amount) # Examining data - top 10 states by amount and number of donors print df.groupby('state')['amount',].sum().sort_values(by='amount', ascending=False)[0:10] print df.groupby('state')['donor_id',].count().sort_values(by='donor_id', ascending=False)[0:10] print noloc_df.state.unique() print noloc_df.city.unique() print noloc_df.zipcode.unique() noloc_df['city'] = '' noloc_df['state'] = '' noloc_df['zipcode'] = '' print df.shape[0] + noloc_df.shape[0] df.shape, noloc_df.shape # The input data has the latest zip code for each donor. So we cannot observe any movement even if there was any since # all donations by a given donor will only have the same exact zipcode. x1 = pd.DataFrame(df.groupby(['donor_id','zipcode']).zipcode.nunique()) x1[x1.zipcode != 1] # The noloc_df and the df with location values have no donors in common - so we cannot use the donor # location information from df to detect the location in noloc_df. set(df.donor_id.values).intersection(noloc_df.donor_id.values) df.rename(columns={'donation_date': 'activity_date'}, inplace=True) df['activity_year'] = df.activity_date.apply(lambda x: x.year) df['activity_month'] = df.activity_date.apply(lambda x: x.month) df['activity_dow'] = df.activity_date.apply(lambda x: x.dayofweek) df['activity_ym'] = df['activity_date'].map(lambda x: 100*x.year + x.month) df['activity_yq'] = df['activity_date'].map(lambda x: 10*x.year + (x.month-1)//3) df['activity_ymd'] = df['activity_date'].map(lambda x: 10000*x.year + 100*x.month + x.day) # Drop the zipcode_initial (for privacy reasons) df.drop('zipcode_initial', axis=1, inplace=True) """ Explanation: Final check on all location data to confirm that we have no rows with empty state, city or location End of explanation """ !mkdir -p out/0 df.to_pickle('out/0/donations.pkl') noloc_df.to_pickle('out/0/donations_noloc.pkl') df[df.donor_id == '_1D50SWTKX'].sort_values(by='activity_date').tail() df.columns df.shape """ Explanation: All done! Let's save our dataframes for the next stage of processing End of explanation """
PAIR-code/ai-explorables
server-side/private-and-fair/MNIST_Generate_UMAP.ipynb
apache-2.0
%%capture !curl -L https://github.com/tensorflow/privacy/releases/download/0.2.3/order.tgz -o order.tgz !tar zxvf order.tgz mnist_priv_train = np.load('data/order_mnist_priv_train.npy') mnist_priv_test = np.load('data/order_mnist_priv_test.npy') mnist_priv_train.shape (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() x_train_orig = x_train x_train.shape """ Explanation: Download data MNIST privacy rankings from Distribution Density, Tails, and Outliers in Machine Learning: Metrics and Applications. End of explanation """ trainList = [] for i, d in enumerate(np.argsort(mnist_priv_train)): trainList.append({ 'priv_order': d, 'y': y_train[i], 'i': i }) df = pd.DataFrame(trainList) top3df = df[df['y'] == 3].sort_values(['priv_order'], ascending=True).head(10) f, axarr = plt.subplots(1, 10) for i, d in enumerate(top3df['i'].to_list()): axarr[i].imshow(x_train[d]) bot3df = df[df['y'] == 3].sort_values(['priv_order'], ascending=False).head(10) f, axarr = plt.subplots(1, 10) for i, d in enumerate(bot3df['i'].to_list()): axarr[i].imshow(x_train[d]) """ Explanation: The top and bottom "3" digits End of explanation """ train, test = tf.keras.datasets.mnist.load_data() train_data, train_labels = train test_data, test_labels = test train_data = np.array(train_data, dtype=np.float32) / 255 test_data = np.array(test_data, dtype=np.float32) / 255 train_data = train_data.reshape(train_data.shape[0], 28, 28, 1) test_data = test_data.reshape(test_data.shape[0], 28, 28, 1) train_labels = np.array(train_labels, dtype=np.int32) test_labels = np.array(test_labels, dtype=np.int32) train_labels = tf.keras.utils.to_categorical(train_labels, num_classes=10) test_labels = tf.keras.utils.to_categorical(test_labels, num_classes=10) model_784 = tf.keras.Sequential([ tf.keras.layers.Conv2D(16, 8, strides=2, padding='same', activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPool2D(2, 1), tf.keras.layers.Conv2D(32, 4, strides=2, padding='valid', activation='relu'), tf.keras.layers.MaxPool2D(2, 1), tf.keras.layers.Flatten(), tf.keras.layers.Dense(28*28, activation='relu', name='embedding_784'), tf.keras.layers.Dense(32, activation='relu', name='embedding_32'), tf.keras.layers.Dense(10, name='logit') ]) model_784.summary() loss = tf.keras.losses.CategoricalCrossentropy( from_logits=True, reduction=tf.losses.Reduction.NONE) model_784.compile(loss=loss, optimizer="adam", metrics=["accuracy"]) model_784.fit( train_data, train_labels, validation_data=(test_data, test_labels), epochs=10, batch_size=250, verbose=2, ) embedding_layer_model_784 = tf.keras.Model( inputs=model_784.input, outputs=model_784.get_layer('embedding_784').output) with tf.compat.v1.Session() as sess: sess.run(tf.compat.v1.global_variables_initializer()) train_embeddings_784 = sess.run(embedding_layer_model_784(train_data)) def umapDigit(digit=0, embeddings=train_embeddings_784, digit_type='', slug='784_'): dfN = df[df['y'] == digit] embeddingsN = embeddings.take(dfN['i'].to_list(), axis=0) reducer = umap.UMAP(random_state=42, min_dist=.05, n_neighbors=8) umap_xy = reducer.fit_transform(embeddingsN) fig, ax = plt.subplots(figsize=(6, 6)) color = dfN['priv_order'] plt.scatter(umap_xy[:, 0], umap_xy[:, 1], c=color, cmap="Spectral", s=3) plt.setp(ax, xticks=[], yticks=[]) plt.title("MNIST " + str(digit) + " - UMAP", fontsize=18) plt.show() rootdir = 'umap-digits/' outpath = rootdir + 'umap_train_' + slug + digit_type + str(digit) + '.npy' with open(outpath, 'w') as outfile: np.save(outfile, umap_xy) for i in range(0, 10): umapDigit(i) """ Explanation: UMAP Embeddings of each training MNIST digit training projected with UMAP. End of explanation """
andreyf/machine-learning-examples
sklearn/sklearn.cross_validation.ipynb
gpl-3.0
from sklearn import cross_validation, datasets import numpy as np """ Explanation: Sklearn sklearn.cross_validation документация: http://scikit-learn.org/stable/modules/cross_validation.html End of explanation """ iris = datasets.load_iris() train_data, test_data, train_labels, test_labels = cross_validation.train_test_split(iris.data, iris.target, test_size = 0.3) #убедимся, что тестовая выборка действительно составляет 0.3 от всех данных float(len(test_labels))/len(iris.data) print 'Размер обучающей выборки: {} объектов \nРазмер тестовой выборки: {} объектов'.format(len(train_data), len(test_data)) print 'Обучающая выборка:\n', train_data[:5] print '\n' print 'Тестовая выборка:\n', test_data[:5] print 'Метки классов на обучающей выборке:\n', train_labels print '\n' print 'Метки классов на тестовой выборке:\n', test_labels """ Explanation: Разовое разбиение данных на обучение и тест с помощью train_test_split End of explanation """ for train_indices, test_indices in cross_validation.KFold(10, n_folds = 5): print train_indices, test_indices for train_indices, test_indices in cross_validation.KFold(10, n_folds = 2, shuffle = True): print train_indices, test_indices for train_indices, test_indices in cross_validation.KFold(10, n_folds = 2, shuffle = True, random_state = 1): print train_indices, test_indices """ Explanation: Стратегии проведения кросс-валидации KFold End of explanation """ target = np.array([0] * 5 + [1] * 5) print target for train_indices, test_indices in cross_validation.StratifiedKFold(target, n_folds = 2, shuffle = True, random_state = 0): print train_indices, test_indices target = np.array([0, 1] * 5) print target for train_indices, test_indices in cross_validation.StratifiedKFold(target, n_folds = 2,shuffle = True): print train_indices, test_indices """ Explanation: StratifiedKFold End of explanation """ for train_indices, test_indices in cross_validation.ShuffleSplit(10, n_iter = 10, test_size = 0.2): print train_indices, test_indices """ Explanation: ShuffleSplit End of explanation """ target = np.array([0] * 5 + [1] * 5) print target for train_indices, test_indices in cross_validation.StratifiedShuffleSplit(target, n_iter = 4, test_size = 0.2): print train_indices, test_indices """ Explanation: StratifiedShuffleSplit End of explanation """ for train_indices, test_index in cross_validation.LeaveOneOut(10): print train_indices, test_index """ Explanation: Leave-One-Out End of explanation """
wobiskai/anomaly-detection-in-Bitcoin
notebooks/Bitcoin Anomaly Analysis.ipynb
apache-2.0
import numpy as np import pandas as pd column_names = ['txn_key', 'from_user', 'to_user', 'date', 'amount'] df = pd.read_csv('../data/bitcoin_uic_data_and_code_20130410/user_edges.txt', names=column_names) df.head() """ Explanation: Load data End of explanation """ df[ df.date < 20110000000000 ].to_csv('../data/subset/user_edges_2010.csv', index=False) df = pd.read_csv('../data/subset/user_edges_2010.csv') df['date'] = pd.to_datetime(df.date, format='%Y-%m-%d %H:%M:%S') df.to_csv('../data/subset/user_edges_2010.csv', index=False) """ Explanation: Select transactions in or before 2010 End of explanation """ import networkx as nx # for features only defined in undirected graph G = nx.from_pandas_dataframe(df, source='from_user', target='to_user', edge_attr=['txn_key', 'amount', 'date'], create_using=nx.Graph() ) # unique links between users G_di = nx.from_pandas_dataframe(df, source='from_user', target='to_user', edge_attr=['txn_key', 'amount', 'date'], create_using=nx.DiGraph() ) # the full graph G_mdi = nx.from_pandas_dataframe(df, source='from_user', target='to_user', edge_attr=['txn_key', 'amount', 'date'], create_using=nx.MultiDiGraph() ) # transaction feature maps count_by_key = df.groupby('txn_key').size() amount_by_key = df.groupby('txn_key').amount.sum() ufrom_by_key = df.groupby('txn_key').from_user.agg(pd.Series.nunique) uto_by_key = df.groupby('txn_key').to_user.agg(pd.Series.nunique) # user feature maps in_txn_count = df.groupby('to_user').size() in_key_count = df.groupby('to_user').txn_key.agg(pd.Series.nunique) out_txn_count = df.groupby('from_user').size() out_key_count = df.groupby('from_user').txn_key.agg(pd.Series.nunique) total_in_txn_amt = df.groupby('to_user').amount.sum() total_out_txn_amt = df.groupby('from_user').amount.sum() avg_in_txn_amt = df.groupby('to_user').amount.mean() avg_out_txn_amt = df.groupby('from_user').amount.mean() from_fst_txn_date = df.groupby('from_user').date.min() df_feat = df.assign( # transaction features count_by_key = df.txn_key.map(count_by_key), amount_by_key = df.txn_key.map(amount_by_key), from_eq_to = df.from_user == df.to_user, ufrom_by_key = df.txn_key.map(ufrom_by_key), uto_by_key = df.txn_key.map(uto_by_key), # transaction date features date_year = df.date.dt.year, date_month = df.date.dt.month, date_day = df.date.dt.day, date_dayofweek = df.date.dt.dayofweek, date_dayofyear = df.date.dt.dayofyear, date_hour = df.date.dt.hour, date_minute = df.date.dt.minute, date_second = df.date.dt.second, # user features from_in_txn_count = df.from_user.map(in_txn_count), from_in_key_count = df.from_user.map(in_key_count), from_out_txn_count = df.from_user.map(out_txn_count), from_out_key_count = df.from_user.map(out_key_count), to_in_txn_count = df.to_user.map(in_txn_count), to_in_key_count = df.to_user.map(in_key_count), to_out_txn_count = df.to_user.map(out_txn_count), to_out_key_count = df.to_user.map(out_key_count), from_total_in_txn_amt = df.from_user.map(total_in_txn_amt), from_total_out_txn_amt = df.from_user.map(total_out_txn_amt), to_total_in_txn_amt = df.to_user.map(total_in_txn_amt), to_total_out_txn_amt = df.to_user.map(total_out_txn_amt), from_avg_in_txn_amt = df.from_user.map(avg_in_txn_amt), from_avg_out_txn_amt = df.from_user.map(avg_out_txn_amt), to_avg_in_txn_amt = df.to_user.map(avg_in_txn_amt), to_avg_out_txn_amt = df.to_user.map(avg_out_txn_amt), from_in_deg = df.from_user.map(G_mdi.in_degree()), from_out_deg = df.from_user.map(G_mdi.out_degree()), from_in_udeg = df.from_user.map(G_di.in_degree()), from_out_udeg = df.from_user.map(G_di.out_degree()), to_in_deg = df.to_user.map(G_mdi.in_degree()), to_out_deg = df.to_user.map(G_mdi.out_degree()), to_in_udeg = df.to_user.map(G_di.in_degree()), to_out_udeg = df.to_user.map(G_di.out_degree()), from_cc = df.from_user.map(nx.clustering(G)), to_cc = df.to_user.map(nx.clustering(G)) ) df_feat.fillna(0, inplace=True) """ Explanation: Transaction Features to use Number of transaction under this key Transaction amount, total amount under this key From equals to? Number of unique from/to under this key Transaction date Year Month Day Day of week Day of year Hour Minute Second From/to in/out (unique) degree From/to clustering coefficient From/to in/out transaction frequency All Within ±12 hours From/to transaction volume All Within ±12 hours From/to first transaction date From/to average in/out transaction amount From/to average time between in/out transactions Build graphs from transaction data - Undirected, directed and multi-directed End of explanation """ from sklearn.ensemble import IsolationForest not_train_cols = ['txn_key', 'from_user', 'to_user', 'date'] X_train = df_feat[ [col for col in df_feat.columns if col not in not_train_cols] ].values clf = IsolationForest(n_estimators=100, contamination=0.01, n_jobs=-1, random_state=42) clf.fit(X_train) clf.threshold_ pred = clf.predict(X_train) anomalies = (pred != 1) """ Explanation: Isolation Forest for anomaly detection End of explanation """ import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(12, 8)) sns.distplot(scores, kde=False) line = plt.vlines(clf.threshold_, 0, 30000, colors='r', linestyles='dotted') line.set_label('Threshold = -0.0948') plt.legend(loc='upper left', fontsize='medium') plt.title('Anomaly Scores returned by Isolation Forest', fontsize=16); """ Explanation: Anomaly Scores End of explanation """ from sklearn.manifold import TSNE tsne = TSNE(n_components=2, #perplexity=50, #n_iter=200, n_iter_without_progress=10, #angle=0.7, random_state=42) X_tsne = tsne.fit_transform(X_train[150000:155000]) %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns outlier = anomalies[150000:155000] plt.figure(figsize=(12,8)) plt.scatter(X_tsne[~outlier][:,0], X_tsne[~outlier][:,1], marker='.', c='b', alpha=.2) plt.scatter(X_tsne[outlier][:,0], X_tsne[outlier][:,1], marker='o', c='r', alpha=1) plt.legend(['Normal Transactions', 'Abnormal Transactions']) plt.title('t-SNE Visualization of Normal Transactions vs Abnormal Transactions', fontsize=16); """ Explanation: Visualizing the Transactions End of explanation """ json_date_format = '%Y-%m-%dT%H:%M:%SZ' # df['date'] = df.date.dt.strftime(json_date_format) for scc in nx.strongly_connected_components(G_di): if len(scc) > 5: intersect = np.intersect1d(list(scc), anomalies_id) if intersect.size > 0: G_sub = G_di.subgraph(scc) #G_sub_json = json_graph.node_link_data(G_sub) #with open('../d3/json/network.json', 'w') as json_file: # json.dump(G_sub_json, json_file) anomalies = (pred != 1) np.concatenate((df[anomalies].from_user, df[anomalies].to_user)) anomalies_pairs = zip(df[anomalies].from_user, df[anomalies].to_user) for i, j in anomalies_pairs: neigh = G_di.neighbors(i) neigh += G_di.neighbors(j) nodes = neigh + [i, j] if len(nodes) > 10 and len(nodes) < 20: G_sub = nx.subgraph(G_di, nodes) from networkx.readwrite import json_graph import json anomalies_pairs = zip(df[anomalies].from_user, df[anomalies].to_user) for e in G_sub.edges_iter(): if e[:2] in anomalies_pairs: G_sub.edge[e[0]][e[1]]['type'] = 'licensing' else: G_sub.edge[e[0]][e[1]]['type'] = 'suit' G_sub_json = json_graph.node_link_data(G_sub) with open('../d3/json/network.json', 'w') as json_file: json.dump(G_sub_json, json_file) G_di = nx.from_pandas_dataframe(df, source='from_user', target='to_user', edge_attr=['txn_key', 'amount', 'date'], create_using=nx.DiGraph() ) from IPython.display import IFrame IFrame('./d3/html/network.html', width=1000, height=500) """ Explanation: D3 Network Visualization End of explanation """
jo-tez/aima-python
learning_apps.ipynb
mit
from learning import * from notebook import * """ Explanation: LEARNING APPLICATIONS In this notebook we will take a look at some indicative applications of machine learning techniques. We will cover content from learning.py, for chapter 18 from Stuart Russel's and Peter Norvig's book Artificial Intelligence: A Modern Approach. Execute the cell below to get started: End of explanation """ train_img, train_lbl, test_img, test_lbl = load_MNIST() """ Explanation: CONTENTS MNIST Handwritten Digits Loading and Visualising Testing MNIST Fashion MNIST HANDWRITTEN DIGITS CLASSIFICATION The MNIST Digits database, available from this page, is a large database of handwritten digits that is commonly used for training and testing/validating in Machine learning. The dataset has 60,000 training images each of size 28x28 pixels with labels and 10,000 testing images of size 28x28 pixels with labels. In this section, we will use this database to compare performances of different learning algorithms. It is estimated that humans have an error rate of about 0.2% on this problem. Let's see how our algorithms perform! NOTE: We will be using external libraries to load and visualize the dataset smoothly (numpy for loading and matplotlib for visualization). You do not need previous experience of the libraries to follow along. Loading MNIST Digits Data Let's start by loading MNIST data into numpy arrays. The function load_MNIST() loads MNIST data from files saved in aima-data/MNIST. It returns four numpy arrays that we are going to use to train and classify hand-written digits in various learning approaches. End of explanation """ print("Training images size:", train_img.shape) print("Training labels size:", train_lbl.shape) print("Testing images size:", test_img.shape) print("Testing labels size:", test_lbl.shape) """ Explanation: Check the shape of these NumPy arrays to make sure we have loaded the database correctly. Each 28x28 pixel image is flattened to a 784x1 array and we should have 60,000 of them in training data. Similarly, we should have 10,000 of those 784x1 arrays in testing data. End of explanation """ # takes 5-10 seconds to execute this show_MNIST(train_lbl, train_img) # takes 5-10 seconds to execute this show_MNIST(test_lbl, test_img) """ Explanation: Visualizing Data To get a better understanding of the dataset, let's visualize some random images for each class from training and testing datasets. End of explanation """ print("Average of all images in training dataset.") show_ave_MNIST(train_lbl, train_img) print("Average of all images in testing dataset.") show_ave_MNIST(test_lbl, test_img) """ Explanation: Let's have a look at the average of all the images of training and testing data. End of explanation """ print(train_img.shape, train_lbl.shape) temp_train_lbl = train_lbl.reshape((60000,1)) training_examples = np.hstack((train_img, temp_train_lbl)) print(training_examples.shape) """ Explanation: Testing Now, let us convert this raw data into DataSet.examples to run our algorithms defined in learning.py. Every image is represented by 784 numbers (28x28 pixels) and we append them with its label or class to make them work with our implementations in learning module. End of explanation """ # takes ~10 seconds to execute this MNIST_DataSet = DataSet(examples=training_examples, distance=manhattan_distance) """ Explanation: Now, we will initialize a DataSet with our training examples, so we can use it in our algorithms. End of explanation """ pL = PluralityLearner(MNIST_DataSet) print(pL(177)) %matplotlib inline print("Actual class of test image:", test_lbl[177]) plt.imshow(test_img[177].reshape((28,28))) """ Explanation: Moving forward we can use MNIST_DataSet to test our algorithms. Plurality Learner The Plurality Learner always returns the class with the most training samples. In this case, 1. End of explanation """ # takes ~45 Secs. to execute this nBD = NaiveBayesLearner(MNIST_DataSet, continuous = False) print(nBD(test_img[0])) """ Explanation: It is obvious that this Learner is not very efficient. In fact, it will guess correctly in only 1135/10000 of the samples, roughly 10%. It is very fast though, so it might have its use as a quick first guess. Naive-Bayes The Naive-Bayes classifier is an improvement over the Plurality Learner. It is much more accurate, but a lot slower. End of explanation """ %matplotlib inline print("Actual class of test image:", test_lbl[0]) plt.imshow(test_img[0].reshape((28,28))) """ Explanation: To make sure that the output we got is correct, let's plot that image along with its label. End of explanation """ # takes ~20 Secs. to execute this kNN = NearestNeighborLearner(MNIST_DataSet, k=3) print(kNN(test_img[211])) """ Explanation: k-Nearest Neighbors We will now try to classify a random image from the dataset using the kNN classifier. End of explanation """ %matplotlib inline print("Actual class of test image:", test_lbl[211]) plt.imshow(test_img[211].reshape((28,28))) """ Explanation: To make sure that the output we got is correct, let's plot that image along with its label. End of explanation """ train_img, train_lbl, test_img, test_lbl = load_MNIST(fashion=True) """ Explanation: Hurray! We've got it correct. Don't worry if our algorithm predicted a wrong class. With this techinique we have only ~97% accuracy on this dataset. MNIST FASHION Another dataset in the same format is MNIST Fashion. This dataset, instead of digits contains types of apparel (t-shirts, trousers and others). As with the Digits dataset, it is split into training and testing images, with labels from 0 to 9 for each of the ten types of apparel present in the dataset. The below table shows what each label means: | Label | Description | | ----- | ----------- | | 0 | T-shirt/top | | 1 | Trouser | | 2 | Pullover | | 3 | Dress | | 4 | Coat | | 5 | Sandal | | 6 | Shirt | | 7 | Sneaker | | 8 | Bag | | 9 | Ankle boot | Since both the MNIST datasets follow the same format, the code we wrote for loading and visualizing the Digits dataset will work for Fashion too! The only difference is that we have to let the functions know which dataset we're using, with the fashion argument. Let's start by loading the training and testing images: End of explanation """ # takes 5-10 seconds to execute this show_MNIST(train_lbl, train_img, fashion=True) # takes 5-10 seconds to execute this show_MNIST(test_lbl, test_img, fashion=True) """ Explanation: Visualizing Data Let's visualize some random images for each class, both for the training and testing sections: End of explanation """ print("Average of all images in training dataset.") show_ave_MNIST(train_lbl, train_img, fashion=True) print("Average of all images in testing dataset.") show_ave_MNIST(test_lbl, test_img, fashion=True) """ Explanation: Let's now see how many times each class appears in the training and testing data: End of explanation """ temp_train_lbl = train_lbl.reshape((60000,1)) training_examples = np.hstack((train_img, temp_train_lbl)) # takes ~10 seconds to execute this MNIST_DataSet = DataSet(examples=training_examples, distance=manhattan_distance) """ Explanation: Unlike Digits, in Fashion all items appear the same number of times. Testing We will now begin testing our algorithms on Fashion. First, we need to convert the dataset into the learning-compatible Dataset class: End of explanation """ pL = PluralityLearner(MNIST_DataSet) print(pL(177)) %matplotlib inline print("Actual class of test image:", test_lbl[177]) plt.imshow(test_img[177].reshape((28,28))) """ Explanation: Plurality Learner The Plurality Learner always returns the class with the most training samples. In this case, 9. End of explanation """ # takes ~45 Secs. to execute this nBD = NaiveBayesLearner(MNIST_DataSet, continuous = False) print(nBD(test_img[24])) """ Explanation: Naive-Bayes The Naive-Bayes classifier is an improvement over the Plurality Learner. It is much more accurate, but a lot slower. End of explanation """ %matplotlib inline print("Actual class of test image:", test_lbl[24]) plt.imshow(test_img[24].reshape((28,28))) """ Explanation: Let's check if we got the right output. End of explanation """ # takes ~20 Secs. to execute this kNN = NearestNeighborLearner(MNIST_DataSet, k=3) print(kNN(test_img[211])) """ Explanation: K-Nearest Neighbors With the dataset in hand, we will first test how the kNN algorithm performs: End of explanation """ %matplotlib inline print("Actual class of test image:", test_lbl[211]) plt.imshow(test_img[211].reshape((28,28))) """ Explanation: The output is 1, which means the item at index 211 is a trouser. Let's see if the prediction is correct: End of explanation """
unoebauer/public-astro-tools
jupyter/wind_tutorial.ipynb
mit
mstar = 52.5 # mass; if no astropy units are provided, the calculators will assume units of solar masses lstar = 1e6 # luminosity; if no astropy units are provided, the calculators will assume units of solar luminosities teff = 4.2e4 # effective temperature; if no astropy units are provided, the calculators will assume kelvin sigma = 0.3 # reference electron scattering cross section; if no astropy untis are provided, cm^2/g is assumed gamma = 0.502 # Eddington factor with respect to electron scattering """ Explanation: Wind Structure Calculator This Python module provides a number of simple calculators with which the structure of line-driven winds can be determined following different analytic approaches. In the following, we briefly demonstrate the usage of these calculators at the example of the well-studies O-star zeta-Puppis. Setting the stellar Parameters These parameters describe the basic properties of the star. These are adopted from Noebauer & Sim 2015, tables 2 and 3. End of explanation """ alpha = 0.595 k = 0.381 """ Explanation: CAK force multiplier paramters. Again these are adopted from Noebauer & Sim 2015, table 3 End of explanation """ x = np.logspace(-3, 3, 1024) + 1. """ Explanation: The grid for dimensional radii (i.e. r/Rstar) for which the wind velocity and density will be later determined End of explanation """ wind_cak75 = ws.WindStructureCak75(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sigma=sigma, k=k, alpha=alpha) wind_fa86 = ws.WindStructureFa86(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sigma=sigma, k=k, alpha=alpha) wind_kppa89 = ws.WindStructureKppa89(mstar=mstar, lstar=lstar, teff=teff, gamma=gamma, sigma=sigma, k=k, alpha=alpha) winds = [wind_cak75, wind_fa86, wind_kppa89] labels = ["CAK75", "FA86", "KPPA89"] linestyles = ["solid", "dashed", "dashdot"] """ Explanation: Setting up the calculators WindStructureCak75: wind structure based on the seminal work by Castor, Abbott and Klein 1975; the central star is assumed to be a point source WindStructureFa86: wind structure based on fits to the numerical results obtained by Friend and Abbott 1986; only the influence of the finite extent of the central star is taken into account WindStructureKppa89: wind structure based on the approximate analytic description by Kudritzki, Pauldrach, Puls and Abbbott 1989; the finite extent of the central star is taken into account Note: in all wind structure calculators it is assumed that the ionization state is frozen-in, i.e. constant throughout the wind. End of explanation """ print(" | vterm [km/s] | Mdot [solMass/yr] ") print("==========================================") for wind, label in zip(winds, labels): print("{:6s} | {:7.2f} | {:.4e}".format(label, wind.vterm.value, wind.mdot.value)) """ Explanation: Calculating the mass-loss rates End of explanation """ plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x, wind.v(x), ls=ls, label=label) plt.legend(frameon=False, loc="lower right") plt.xlabel(r"$r/R_{\star}$") plt.ylabel(r"$v$ [km/s]") plt.xlim([0.8, 1e1]) """ Explanation: Determining and visualizing the wind structure Let's first have a look at the wind velocity in absolute terms as predicted by the different descriptions of the wind structure. End of explanation """ plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x - 1., wind.v(x) / wind.vterm, ls=ls, label=label) plt.xscale("log") plt.xlim([1e-3, 1e3]) plt.ylim([0, 1]) plt.legend(loc="upper left", frameon=False) plt.xlabel(r"$r/R_{\star} - 1$") plt.ylabel(r"$v/v_{\infty}$") """ Explanation: The following illustration compares how fast the terminal wind speed is reached in the various wind descriptions End of explanation """ plt.figure() for wind, label, ls in zip(winds, labels, linestyles): plt.plot(x, wind.rho(x), ls=ls, label=label) plt.yscale("log") plt.ylim([1e-15, 1e-10]) plt.xlim([0.8, 10]) plt.xlabel(r"$r/R_{\star}$") plt.ylabel(r"$\rho$ $[\mathrm{g\,cm^{-3}}]$") plt.legend(loc="upper right", frameon=False) """ Explanation: Finally, we have a look at the predicted wind density: End of explanation """
claudiuskerth/PhDthesis
Data_analysis/SNP-indel-calling/dadi/dadiExercises/First_Steps_with_dadi.ipynb
mit
sys.path.insert(0, '/home/claudius/Downloads/dadi') sys.path """ Explanation: I have cloned the $\delta$a$\delta$i repository into '/home/claudius/Downloads/dadi' and have compiled the code. Now I need to add that directory to the PYTHONPATH variable: End of explanation """ import dadi dir(dadi) import pylab %matplotlib inline x = pylab.linspace(0, 4*pylab.pi, 1000) pylab.plot(x, pylab.sin(x), '-r') %%sh # this allows me to execute a shell command ls """ Explanation: Now, I should be able to import $\delta$a$\delta$i End of explanation """ fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format') fs_ery """ Explanation: I have turned the 1D folded SFS's from realSFS into $\delta$d$\delta$i format by hand according to the description in section 3.1 of the manual. I have left out the masking line from the input file. End of explanation """ # number of segregating sites fs_ery.data[1:].sum() """ Explanation: $\delta$a$\delta$i is detecting that the spectrum is folded (as given in the input file), but it is also automatically masking the 0th and 18th count category. This is a not a good behaviour. End of explanation """ fs_ery.pi() """ Explanation: Single population statistics $\pi$ End of explanation """ fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False) """ Explanation: I have next added a masking line to the input file, setting it to '1' for the first position, i. e. the 0-count category. End of explanation """ fs_ery """ Explanation: $\delta$a$\delta$i is issuing the following message when executing the above command: WARNING:Spectrum_mod:Creating Spectrum with data_folded = True, but mask is not True for all entries which are nonsensical for a folded Spectrum. End of explanation """ fs_ery.pi() """ Explanation: I do not understand this warning from $\delta$a$\delta$i. The 18-count category is sensical for a folded spectrum with even sample size, so should not be masked. Anyway, I do not understand why $\delta$a$\delta$i is so reluctant to keep all positions, including the non-variable one. End of explanation """ # Calcualting pi with the formula from Wakeley2009 n = 36 # 36 sequences sampled from 18 diploid individuals pi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n/2+1)] ) * 2.0 / (n*(n-1)))/pylab.sum(fs_ery.data) # note fs_ery.data gets the whole fs_ery list, including masked entries pi_Wakeley """ Explanation: The function that returns $\pi$ produces the same output with or without the last count category masked ?! I think that is because even if the last count class (966.62...) is masked, it is still included in the calculation of $\pi$. However, there is no obvious unmasking in the pi function. Strange! There are (at least) two formulas that allow the calculation of $\pi$ from a folded sample allele frequency spectrum. One is given in Wakeley2009, p.16, equation (1.4): $$ \pi = \frac{1}{n \choose 2} \sum_{i=1}^{n/2} i(n-i)\eta_{i} $$ Here, $n$ is the number of sequences and $\eta_{i}$ is the SNP count in the i'th minor sample allele frequency class. The other formula is on p. 45 in Gillespie "Population Genetics - A concise guide": $$ \hat{\pi} = \frac{n}{n-1} \sum_{i=1}^{S_{n}} 2 \hat{p_{i}}(1-\hat{p_{i}}) $$ This is the formula that $\delta$a$\delta$i's pi function uses, with the modification that it multiplies each $\hat{p_{i}}$ by the count in the i'th class of the SFS, i. e. the sum is not over all SNP's but over all SNP frequency classes. End of explanation """ fs_ery.mask fs_ery.data # gets all data, including the masked one # Calculating pi with the formula from Gillespie: n = 18 p = pylab.arange(0, n+1)/float(n) p # Calculating pi with the formula from Gillespie: n / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) """ Explanation: This is the value of $\pi_{site}$ that I calculated previously and included in the first draft of the thesis. End of explanation """ # the sample size (n) that dadi stores in this spectrum object and uses as n in the pi function fs_ery.sample_sizes[0] # what is the total number of sites in the spectrum pylab.sum(fs_ery.data) """ Explanation: This is the same as the output of dadi's pi function on the same SFS. End of explanation """ # pi per site n / (n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data) """ Explanation: So, 1.6 million sites went into the ery spectrum. End of explanation """ # with correct small sample size correction 2 * n / (2* n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data) # Calculating pi with the formula from Gillespie: n = 18 p = pylab.arange(0, n+1)/float(n) p = p/2 # with a folded spectrum, we are summing over minor allele freqs only pi_Gillespie = 2*n / (2*n-1.0) * 2 * pylab.sum(fs_ery * p*(1-p)) / pylab.sum(fs_ery.data) pi_Gillespie pi_Wakeley - pi_Gillespie """ Explanation: Apart from the incorrect small sample size correction by $\delta$a$\delta$i in case of folded spectra ($n$ refers to sampled sequences, not individuals), Gillespie's formula leads to a much higher estimate of $\pi_{site}$ than Wakeley's. Why is that? End of explanation """ fs_ery.folded """ Explanation: As can be seen from the insignificant difference (must be due to numerical inaccuracies) between the $\pi_{Wakeley}$ and the $\pi_{Gillespie}$ estimates, they are equivalent with the calculation for folded spectra given above as well as the correct small sample size correction. Beware: $\delta$a$\delta$i does not handle folded spectra correctly. It should be a relatively easy to fix the pi function to work correctly with folded spectra. Care should be taken to also correctly handle uneven sample sizes. End of explanation """ fs_par = dadi.Spectrum.from_file('PAR.FOLDED.sfs.dadi_format') pylab.plot(fs_ery, 'r', label='ery') pylab.plot(fs_par, 'g', label='par') pylab.legend() """ Explanation: I think for now it would be best to import unfolded spectra from realSFS and fold them if necessary in dadi. End of explanation """ from scipy.optimize import least_squares def model(theta, eta, n): """ theta: scaled population mutation rate parameter [scalar] eta: the folded 1D spectrum, including 0-count cat. [list] n: number of sampled gene copies, i. e. 2*num_ind [scalar] returns a numpy array """ i = pylab.arange(1, eta.size) delta = pylab.where(i == n-i, 1, 0) return theta * 1/i + 1/(n-i) / (1 + delta) ?pylab.where # test i = pylab.arange(1, 19) n = 36 print i == n-i # print pylab.where(i == n-i, 1, 0) # get a theta estimate from pi: theta = pi_Wakeley * fs_ery.data.sum() print theta # print len(fs_ery) # model(theta, fs_ery, 36) def fun(theta, eta, n): """ return residuals between model and data """ return model(theta, eta, n) - eta[1:] def jac(theta, eta, n, test=False): """ creates a Jacobian matrix """ J = pylab.empty((eta.size-1, theta.size)) i = pylab.arange(1, eta.size, dtype=float) delta = pylab.where(i == n-i, 1, 0) num = 1/i + 1/(n-i) den = 1 + delta if test: print i print num print den J[:,0] = num / den return J # test jac(theta, fs_ery, 36, test=True) # starting value theta0 = theta # pi_Wakeley from above # sum over unmasked entries, i. e. without 0-count category, i. e. returns number of variable sites fs_ery.sum() # optimize res = least_squares(fun, x0=theta0, jac=jac, bounds=(0,fs_ery.sum()), kwargs={'eta': fs_ery, 'n': 36}, verbose=1) res.success ?least_squares print res.x print theta pylab.rcParams['figure.figsize'] = [12.0, 8.0] import matplotlib.pyplot as plt plt.rcParams['font.size'] = 14.0 i = range(1, len(fs_ery)) eta_model = model(res.x, eta=fs_ery, n=36) # get predicted values with optimal theta plt.plot(i, fs_ery[1:], "bo", label="data from ery") # plot observed spectrum ymax = max( fs_ery[1:].max(), eta_model.max() ) plt.axis([0, 19, 0, ymax*1.1]) # set axis range plt.xlabel("minor allele frequency (i)") plt.ylabel(r'$\eta_i$', fontsize='large', rotation='horizontal') plt.title("folded SFS of ery") plt.plot(i, eta_model, "go-", label="\nneutral model" + "\n" + r'$\theta_{opt} = $' + str(round(res.x, 1)) ) # plot model prediction with optimal theta plt.legend() """ Explanation: ML estimate of $\theta$ from 1D folded spectrum I am trying to fit eq. 4.21 of Wakeley2009 to the oberseved 1D folded spectra. $$ E[\eta_i] = \theta \frac{\frac{1}{i} + \frac{1}{n-i}}{1+\delta_{i,n-i}} \qquad 1 \le i \le \big[n/2\big] $$ Each frequency class, $\eta_i$, provides an estimate of $\theta$. However, I would like to find the value of $\theta$ that minimizes the deviation of the above equation from all observed counts $\eta_i$. I am following the example given here: https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#example-of-solving-a-fitting-problem $$ \frac{\delta E}{\delta \theta} = \frac{\frac{1}{i} + \frac{1}{n-i}}{1+\delta_{i,n-i}} \qquad 1 \le i \le \big[n/2\big] $$ I have just one parameter to optimize. End of explanation """ #?plt.ylabel #print plt.rcParams fs_ery[1:].max() #?pylab os.getcwd() %%sh ls """ Explanation: The counts in each frequency class should be Poisson distributed with rate equal to $E[\eta_i]$ as given above. The lowest frequency class has the highest rate and therefore also the highest variance End of explanation """ def plot_folded_sfs(filename, n, pop = ''): # read in spectrum from file data = open(filename, 'r') sfs = pylab.array( data.readline().split(), dtype=float ) data.close() # should close connection to file #return sfs # get starting value for theta from Watterson's theta S = sfs[1:].sum() T_total = sum([1.0/i for i in range(1, n)]) # onhe half the expected total length of the genealogy theta0 = S / T_total # see eq. 4.7 in Wakeley2009 # optimize res = least_squares(fun, x0=theta0, jac=jac, bounds=(0, sfs.sum()), kwargs={'eta': sfs, 'n': 36}, verbose=1) #print "Optimal theta per site is {0:.4f}".format(res.x[0]/sfs.sum()) #print res.x[0]/sfs.sum() #return theta0, res # plot plt.rcParams['font.size'] = 14.0 i = range(1, len(sfs)) eta_model = model(res.x, eta=sfs, n=36) # get predicted values with optimal theta plt.plot(i, sfs[1:], "rs", label="data of " + pop) # plot observed spectrum ymax = max( sfs[1:].max(), eta_model.max() ) plt.axis([0, 19, 0, ymax*1.1]) # set axis range plt.xlabel("minor allele frequency (i)") plt.ylabel(r'$\eta_i$', fontsize='large', rotation='horizontal') plt.title("folded SFS") plt.text(5, 10000, r"Optimal neutral $\theta$ per site is {0:.4f}".format(res.x[0]/sfs.sum())) plt.plot(i, eta_model, "go-", label="\nneutral model" + "\n" + r'$\theta_{opt} = $' + str(round(res.x, 1)) ) # plot model prediction with optimal theta plt.legend() plot_folded_sfs('PAR.FOLDED.sfs', n=36, pop='par') plot_folded_sfs('ERY.FOLDED.sfs', n=36, pop='ery') """ Explanation: The following function will take the file name of a file containing the flat 1D folded frequency spectrum of one population and plots it together with the best fitting neutral expectation. End of explanation """ from scipy.optimize import minimize_scalar ?minimize_scalar # define cost function def f(theta, eta, n): """ return sum of squared deviations between model and data """ return sum( (model(theta, eta, n) - eta[1:])**2 ) # see above for definition of the 'model' function """ Explanation: Univariate function minimizers or 1D scalar minimisation Since I only have one value to optimize, I can use a slightly simpler approach than used above: End of explanation """ theta = pylab.arange(0, fs_ery.data[1:].sum()) # specify range of theta cost = [f(t, fs_ery.data, 36) for t in theta] plt.plot(theta, cost, 'b-', label='ery') plt.xlabel(r'$\theta$') plt.ylabel('cost') plt.title("cost function for ery") plt.legend(loc='best') ?plt.legend """ Explanation: It would be interesting to know whether the cost function is convex or not. End of explanation """ res = minimize_scalar(f, bounds = (0, fs_ery.data[1:].sum()), method = 'bounded', args = (fs_ery.data, 36)) res # number of segregating sites fs_par.data[1:].sum() res = minimize_scalar(f, bounds = (0, fs_par.data[1:].sum()), method = 'bounded', args = (fs_par.data, 36)) res """ Explanation: Within the specified bounds (the observed $\theta$, i. e. derived from the data, cannot lie outside these bounds), the cost function is convex. This is therefore an easy optimisation problem. See here for more details. End of explanation """ from sympy import * x0 , x1 = symbols('x0 x1') init_printing(use_unicode=True) diff(0.5*(1-x0)**2 + (x1-x0**2)**2, x0) diff(0.5*(1-x0)**2 + (x1-x0**2)**2, x1) """ Explanation: The fitted values of $\theta$ are similar to the ones obtained above with the least_squares function. The estimates for ery deviate more than for par. End of explanation """ from scipy.optimize import curve_fit """ Explanation: Wow! Sympy is a replacement for Mathematica. There is also Sage, which may include even more functionality. End of explanation """ ?curve_fit def model(i, theta): """ i: indpendent variable, here minor SNP frequency classes theta: scaled population mutation rate parameter [scalar] returns a numpy array """ n = len(i) delta = pylab.where(i == n-i, 1, 0) return theta * 1/i + 1/(n-i) / (1 + delta) i = pylab.arange(1, fs_ery.size) popt, pcov = curve_fit(model, i, fs_ery.data[1:]) # optimal theta print popt perr = pylab.sqrt(pcov) perr print str(int(popt[0] - 1.96*perr[0])) + ' < ' + str(int(popt[0])) + ' < ' + str(int(popt[0] + 1.96*perr[0])) popt, pcov = curve_fit(model, i, fs_par.data[1:]) perr = pylab.sqrt(pcov) print str(int(popt[0] - 1.96*perr[0])) + ' < ' + str(int(popt[0])) + ' < ' + str(int(popt[0] + 1.96*perr[0])) """ Explanation: Curve_fit is another function that can be used for optimization. End of explanation """ %pwd % ll ! cat ERY.FOLDED.sfs.dadi_format fs_ery = dadi.Spectrum.from_file('ERY.FOLDED.sfs.dadi_format', mask_corners=False) fs_ery fs_ery.pop_ids = ['ery'] # get a Poisson sample from the observed spectrum fs_ery_param_boot = fs_ery.sample() fs_ery_param_boot fs_ery_param_boot.data %psource fs_ery.sample """ Explanation: I am not sure whether these standard errors (perr) are correct. It may be that it is assumed that errors are normally distributed, which they are not exactly in this case. They should be close to Poisson distributed (see Fu1995), which should be fairly similar to normal with such high expected values as here. If the standard errors are correct, then the large overlap of the 95% confidence intervals would indicate that the data do not provide significant support for a difference in $\theta$ between par and ery. Parametric bootstrap from the observed SFS End of explanation """ fs_ery_param_boot = pylab.array([fs_ery.sample() for i in range(100)]) # get the first 3 boostrap samples from the doubleton class fs_ery_param_boot[:3, 2] """ Explanation: There must be a way to get more than one bootstrap sample per call. End of explanation """ # read in the flattened 2D SFS EryPar_unfolded_2dsfs = dadi.Spectrum.from_file('EryPar.unfolded.2dsfs.dadi_format', mask_corners=True) # check dimension len(EryPar_unfolded_2dsfs[0,]) EryPar_unfolded_2dsfs.sample_sizes # add population labels EryPar_unfolded_2dsfs.pop_ids = ["ery", "par"] EryPar_unfolded_2dsfs.pop_ids """ Explanation: It would be good to get the 5% and 95% quantiles from the bootstrap samples of each frequency class and add those intervals to the plot of the observed frequency spectrum and the fitted neutral spectrum. This would require to find a quantile function and to find out how to add lines to a plot with matplotlib. It would also be good to use the predicted counts from the neutral model above with the fitted $\theta$ as parameters for the bootstrap with sample() and add 95% confidence intervals to the predicted neutral SFS. I have done this in R instead (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd) Using unfolded spectra I edited the 2D SFS created for estimating $F_{ST}$ by realSFS. I have convinced myself that realSFS outputs a flattened 2D matrix as expected by $\delta$a$\delta$i's Spectrum.from_file function (see section 3.1 of the manual with my comments). Note, that in the manual, "samples" stands for number of allele copies, so that the correct specification of dimensions for this 2D unfolded SFS of 18 diploid individuals in each of 2 populations is 37 x 37. End of explanation """ # marginalise over par to get 1D SFS for ery fs_ery = EryPar_unfolded_2dsfs.marginalize([1]) # note the argument is an array with dimensions, one can marginalise over more than one dimension at the same time, # but that is only interesting for 3-dimensional spectra, which I don't have here fs_ery # marginalise over ery to get 1D SFS for par fs_par = EryPar_unfolded_2dsfs.marginalize([0]) fs_par """ Explanation: Marginalizing $\delta$a$\delta$i offers a function to get the marginal spectra from multidimensional spectra. Note, that this marginalisation is nothing fancy. In R it would be taking either the rowSums or the colSums of the matrix. End of explanation """ # plot 1D spectra for each population pylab.plot(fs_par, 'g', label="par") pylab.plot(fs_ery, 'r', label="ery") pylab.legend() """ Explanation: Note, that these marginalised 1D SFS's are not identical to the 1D SFS estimated directly with realSFS. This is because, for the estimation of the 2D SFS, realSFS has only taken sites that had data from at least 9 individuals in each population (see assembly.sh, lines 1423 onwards). The SFS's of par and ery had conspicuous shape differences. It would therefore be good to plot them to see, whether the above commands have done the correct thing. End of explanation """ fs_ery.pi() / pylab.sum(fs_ery.data) fs_ery.data n = 36 # 36 sequences sampled from 18 diploid individuals pi_Wakeley = (sum( [i*(n-i)*fs_ery[i] for i in range(1, n)] ) * 2.0 / (n*(n-1))) pi_Wakeley = pi_Wakeley / pylab.sum(fs_ery.data) pi_Wakeley """ Explanation: These marginal unfolded spectra look similar in shape to the 1D folded spectra of each subspecies (see above). End of explanation """ fs_par.pi() / pylab.sum(fs_par.data) pylab.sum(fs_par.data) pylab.sum(EryPar_unfolded_2dsfs.data) """ Explanation: $\delta$a$\delta$i's pi function seems to calculate the correct value of $\pi$ for this unfolded spectrum. However, it is worrying that $\pi$ from this marginal spectrum is about 20 times larger than the one calculated from the directly estimated 1D folded spectrum (see above the $\pi$ calculated from the folded 1D spectrum). End of explanation """ # from dadi's marginalise function: fs_ery.data sfs2d = EryPar_unfolded_2dsfs.copy() # this should get the marginal spectrum for ery ery_mar = [pylab.sum(sfs2d.data[i]) for i in range(0, len(sfs2d))] ery_mar # this should get the marginal spectrum for ery and then take the sum over it sum([pylab.sum(sfs2d.data[i]) for i in range(0, len(sfs2d))]) # look what happens if I include masking sum([pylab.sum(sfs2d[i]) for i in range(0, len(sfs2d))]) fs_ery.data - ery_mar """ Explanation: <font color="red">The sum over the marginalised 1D spectra should be the same as the sum over the 2D spectrum !</font> End of explanation """ sfs2d[0] pylab.sum(sfs2d[0]) # from dadi's marginalise function: fs_ery.data # dividing by the correct number of sites to get pi per site: fs_ery.pi() / pylab.sum(sfs2d.data) """ Explanation: So, during the marginalisation the masking of data in the fixed categories (0, 36) is the problem, producing incorrectly marginalised counts in those masked categories. This is shown in the following: End of explanation """ fs_par.pi() / pylab.sum(sfs2d.data) """ Explanation: This is very close to the estimate of $\pi$ derived from the folded 1D spectrum of ery! (see above) End of explanation """ fs_ery.Watterson_theta() / pylab.sum(sfs2d.data) fs_ery.Tajima_D() fs_par.Tajima_D() """ Explanation: This is also nicely close to the estimate of $\pi_{site}$ of par from its folded 1D spectrum. Tajima's D End of explanation """ n = 36 pi_Wakeley = (sum( [i*(n-i)*fs_ery.data[i] for i in range(1, n+1)] ) * 2.0 / (n*(n-1))) #/ pylab.sum(sfs2d.data) pi_Wakeley # number of segregating sites # this sums over all unmasked positions in the array pylab.sum(fs_ery) fs_ery.S() S = pylab.sum(fs_ery) theta_Watterson = S / pylab.sum(1.0 / (pylab.arange(1, n))) theta_Watterson # normalizing constant, see page 45 in Gillespie a1 = pylab.sum(1.0 / pylab.arange(1, n)) #print a1 a2 = pylab.sum(1.0 / pylab.arange(1, n)**2.0) #print a2 b1 = (n+1.0)/(3.0*(n-1)) #print b1 b2 = 2.0*(n**2 + n + 3)/(9.0*n*(n-1)) #print b2 c1 = b1 - (1.0/a1) #print c1 c2 = b2 - (n+2.0)/(a1*n) + a2/a1**2 #print c2 C = ((c1/a1)*S + (c2/(a1**2.0 + a2))*S*(S-1)) C = C**(1/2.0) ery_Tajimas_D = (pi_Wakeley - theta_Watterson) / C print '{0:.6f}'.format(ery_Tajimas_D) ery_Tajimas_D - fs_ery.Tajima_D() """ Explanation: Now, I am calculating Tajima's D from the ery marginal spectrum by hand in order to check whether $\delta$a$\delta$i is doing the right thing. End of explanation """ fs_par.Tajima_D() """ Explanation: $\delta$a$\delta$i seems to do the right thing. Note, that the estimate of Tajima's D from this marginal spectrum of ery is slightly different from the estimate derived from the folded 1D spectrum of ery (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd). The folded 1D spectrum resulted in a Tajima's D estimate of $\sim$0.05, i. e. a difference of almost 0.1. Again, the 2D spectrum is based on only those sites for which there were at least 9 individiuals with data in both populations, whereas the 1D folded spectrum of ery included all sites for which there were 9 ery individuals with data (see line 1571 onwards in assembly.sh). End of explanation """ EryPar_unfolded_2dsfs.S() """ Explanation: My estimate from the folded 1D spectrum of par was -0.6142268 (see /data3/claudius/Big_Data/ANGSD/SFS/SFS.Rmd). Multi-population statistics End of explanation """ EryPar_unfolded_2dsfs.Fst() """ Explanation: The 2D spectrum contains counts from 60k sites that are variable in par or ery or both. End of explanation """ %psource EryPar_unfolded_2dsfs.scramble_pop_ids # plot the scrambled 2D SFS dadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs.scramble_pop_ids(), vmin=1) """ Explanation: This estimate of $F_{ST}$ according to Weir and Cockerham (1984) is well below the estimate of $\sim$0.3 from ANGSD according to Bhatia/Hudson (2013). Note, however, that this estimate showed a positive bias of around 0.025 in 100 permutations of population labels of individuals. Taking the positive bias into account, both estimates of $F_{ST}$ are quite similar. The following function scramble_pop_ids should generate a 2D SFS with counts as if individuals were assigned to populations randomly. Theoretically, the $F_{ST}$ calculated from this SFS should be 0. End of explanation """ # get Fst for scrambled SFS EryPar_unfolded_2dsfs.scramble_pop_ids().Fst() """ Explanation: So, this is how the 2D SFS would look like if ery and par were not genetically differentiated. End of explanation """ # folding EryPar_folded_2dsfs = EryPar_unfolded_2dsfs.fold() EryPar_folded_2dsfs EryPar_folded_2dsfs.mask """ Explanation: The $F_{ST}$ from the scrambled SFS is much lower than the $F_{ST}$ of the observed SFS. That should mean that there is significant population structure. However, the $F_{ST}$ from the scrambled SFS is not 0. I don't know why that is. End of explanation """ dadi.Plotting.plot_single_2d_sfs(EryPar_unfolded_2dsfs, vmin=1) dadi.Plotting.plot_single_2d_sfs(EryPar_folded_2dsfs, vmin=1) """ Explanation: Plotting End of explanation """ # unfolded spectrum from marginalisation of 2D unfolded spectrum fs_ery len(fs_ery) fs_ery.fold() """ Explanation: The folded 2D spectrum is not a minor allele frequency spectrum as are the 1D folded spectra of ery and par. This is because an allele that is minor in one population can be the major allele in the other. What is not counted are the alleles that are major in both populations, i. e. the upper right corner. For the 2D spectrum to make sense it is crucial that allele frequencies are polarised the same way in both populations, either with an outgroup sequence or arbitrarily with respect to the reference sequence (as I did here). How to fold a 1D spectrum End of explanation """ fs_ery_folded = fs_ery.copy() # make a copy of the UNfolded spectrum n = len(fs_ery)-1 for i in range(len(fs_ery)): fs_ery_folded[i] += fs_ery[n-i] if i == n/2.0: fs_ery_folded[i] /= 2 fs_ery_folded[0:19] isinstance(fs_ery_folded, pylab.ndarray) mask = [True] mask.extend([False] * 18) mask.extend([True] * 18) print mask print sum(mask) mask = [True] * 37 for i in range(len(mask)): if i > 0 and i < 19: mask[i] = False print mask print sum(mask) """ Explanation: Let's use the formula (1.2) from Wakeley2009 to fold the 1D spectrum manually: $$ \eta_{i} = \frac{\zeta_{i} + \zeta_{n-i}}{1 + \delta_{i, n-i}} \qquad 1 \le i \le [n/2] $$ $n$ is the number of gene copies sampled, i. e. haploid sample size. $[n/2]$ is the largest integer less than or equal to n/2 (to handle uneven sample sizes). $\zeta_{i}$ are the unfolded frequencies and $\delta_{i, n-i}$ is Kronecker's $\delta$ which is 1 if $i = n-i$ and zero otherwise (to avoid counting the unfolded n/2 frequency class twice with even sample sizes). End of explanation """ mask = [[True], [False] * 18, [True] * 18] print mask print [elem for a in mask for elem in a] """ Explanation: Here is how to flatten an array of arrays with list comprehension: End of explanation """ fs_ery_folded.mask = mask fs_ery_folded.folded = True fs_ery_folded - fs_ery.fold() """ Explanation: Set new mask for the folded spectrum: End of explanation """ EryPar_unfolded_2dsfs.sample_sizes EryPar_unfolded_2dsfs._total_per_entry() # copy the unfolded 2D spectrum for folding import copy sfs2d_folded = copy.deepcopy(EryPar_unfolded_2dsfs) n = len(sfs2d_folded)-1 m = len(sfs2d_folded[0])-1 for i in range(n+1): for j in range(m+1): sfs2d_folded[i,j] += sfs2d_folded[n-i, m-j] if i == n/2.0 and j == m/2.0: sfs2d_folded[i,j] /= 2 mask = sfs2d_folded._total_per_entry() > (n+m)/2 mask sfs2d_folded.mask = mask sfs2d_folded.fold = True dadi.Plotting.plot_single_2d_sfs(sfs2d_folded, vmin=1) """ Explanation: The fold() function works correctly for 1D spectra, at least. How about 2D spectra? $$ \eta_{i,j} = \frac{\zeta_{i,j} + \zeta_{n-i, m-j}}{1 + \delta_{i, n-i; j, m-j}} \qquad 1 \le i+j \le \Big[\frac{n+m}{2}\Big] $$ End of explanation """ # copy the unfolded 2D spectrum for folding import copy sfs2d_unfolded = copy.deepcopy(EryPar_unfolded_2dsfs) total_samples = pylab.sum(sfs2d_unfolded.sample_sizes) total_samples total_per_entry = dadi.Spectrum(sfs2d_unfolded._total_per_entry(), pop_ids=['ery', 'par']) #total_per_entry.pop_ids = ['ery', 'par'] dadi.Plotting.plot_single_2d_sfs(total_per_entry, vmin=1) total_per_entry = sfs2d_unfolded._total_per_entry() total_per_entry where_folded_out = total_per_entry > total_samples/2 where_folded_out original_mask = sfs2d_unfolded.mask original_mask pylab.logical_or([True, False, True], [False, False, True]) # get the number of elements along each axis sfs2d_unfolded.shape [slice(None, None, -1) for i in sfs2d_unfolded.shape] matrix = pylab.array([ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ]) reverse_slice = [slice(None, None, -1) for i in matrix.shape] reverse_slice matrix[reverse_slice] matrix[::-1,::-1] """ Explanation: I am going to go through every step in the fold function of dadi: End of explanation """ final_mask = pylab.logical_or(original_mask, dadi.Numerics.reverse_array(original_mask)) final_mask """ Explanation: With the variable length list of slice objects, one can generalise the reverse of arrays with any dimensions. End of explanation """ ?pylab.where pylab.where(matrix < 6, matrix, 0) # this takes the part of the spectrum that is non-sensical if the derived allele is not known # and sets the rest to 0 print pylab.where(where_folded_out, sfs2d_unfolded, 0) # let's plot the bit of the spectrum that we are going to fold onto the rest: dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(pylab.where(where_folded_out, sfs2d_unfolded, 0)), vmin=1) # now let's reverse this 2D array, i. e. last row first and last element of each row first: _reversed = dadi.Numerics.reverse_array(pylab.where(where_folded_out, sfs2d_unfolded, 0)) _reversed dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(_reversed), vmin=1) """ Explanation: Here, folding doesn't mask new cells. End of explanation """ # This shall now be added to the original unfolded 2D spectrum. sfs2d_folded = pylab.ma.masked_array(sfs2d_unfolded.data + _reversed) dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(sfs2d_folded), vmin=1) sfs2d_folded.data sfs2d_folded.data[where_folded_out] = 0 sfs2d_folded.data dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(sfs2d_folded), vmin=1) sfs2d_folded.shape where_ambiguous = (total_per_entry == total_samples/2.0) where_ambiguous """ Explanation: The transformation we have done with the upper-right diagonal 2D array above should be identical to projecting it across a vertical center line (creating an upper left triangular matrix) and then projecting it across a horizontal center line (creating the final lower left triangular matrix). Note, that this is not like mirroring the upper-right triangular 2D array across the 36-36 diagonal! End of explanation """ # this extracts the diagonal values from the UNfolded spectrum and sets the rest to 0 ambiguous = pylab.where(where_ambiguous, sfs2d_unfolded, 0) dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(ambiguous), vmin=1) """ Explanation: SNP's with joint frequencies in the True cells are counted twice at the moment due to the folding and the fact that the sample sizes are even. End of explanation """ reversed_ambiguous = dadi.Numerics.reverse_array(ambiguous) dadi.Plotting.plot_single_2d_sfs(dadi.Spectrum(reversed_ambiguous), vmin=1) """ Explanation: These are the values in the diagonal before folding. End of explanation """ a = -1.0*ambiguous + 0.5*ambiguous + 0.5*reversed_ambiguous b = -0.5*ambiguous + 0.5*reversed_ambiguous a == b sfs2d_folded += -0.5*ambiguous + 0.5*reversed_ambiguous final_mask = pylab.logical_or(final_mask, where_folded_out) final_mask sfs2d_folded = dadi.Spectrum(sfs2d_folded, mask=final_mask, data_folded=True, pop_ids=['ery', 'par']) pylab.rcParams['figure.figsize'] = [12.0, 8.0] dadi.Plotting.plot_single_2d_sfs(sfs2d_folded, vmin=1) """ Explanation: These are the values that got added to the diagonal during folding. Comparing with the previous plot, one can see for instance that the value in the (0, 36) class got added to the value in the (36, 0) class and vice versa. The two frequency classes are equivalent, since it is arbitrary which allele we call minor in the total sample (of 72 gene copies). These SNP's are therefore counted twice. End of explanation """
goujou/LAPM
notebooks/Century.ipynb
mit
from sympy import * from LAPM import * from LAPM.linear_autonomous_pool_model import LinearAutonomousPoolModel """ Explanation: Ages and transit time distribution from Century This notebook shows how to use the LAPM package to compute system level metrics for the Century model. End of explanation """ B=Matrix([[-2.927714, 0, 0, 0, 0, 0, 0.000000], [0, -14.560, 0, 0, 0, 0, 0], [0, 0, -3.6211195, 0, 0, 0, 0], [0, 0, 0, -18.20, 0, 0, 0], [1.449218, 6.552, 1.4665534, 8.19, -3.731, 0.082992, 0.003042], [0.204940, 0, 0.2534784, 0, 2.193828, -0.1976, 0], [0, 0, 0, 0, 0.014924, 0.005928, -0.006760]]) u=Matrix(7,1,[3.58800, 18.97804, 4.68, 24.75396, 0, 0, 0]) M=LinearAutonomousPoolModel(u, B, True) M.A_expected_value """ Explanation: In the second line above, we imported also the linear_autonomous_pool_model module which contains most of the functions required for the examples in this notebook. We will create now a compartmental representation of Century using the original parameter values described in Parton et al. (1987). End of explanation """ M.A_quantile(0.5) # Median (50% quantile) of the system age distribution M.T_expected_value #Mean transit time M.T_quantile(0.95) # Median (50% quantile) of the transit time distribution M.a_expected_value # Mean age vector of individual pools M.a_quantile(0.95) # 95% quantile of individual pools M.a_quantile(0.05) # 5% quantiles of individual pools """ Explanation: Other useful system diagnostics are: End of explanation """
opencobra/cobrapy
documentation_builder/media.ipynb
gpl-2.0
from cobra.io import load_model model = load_model("textbook") model.medium """ Explanation: Growth media The availability of nutrients has a major impact on metabolic fluxes and cobrapy provides some helpers to manage the exchanges between the external environment and your metabolic model. In experimental settings the "environment" is usually constituted by the growth medium, ergo the concentrations of all metabolites and co-factors available to the modeled organism. However, constraint-based metabolic models only consider fluxes. Thus, you can not simply use concentrations since fluxes have the unit mmol / [gDW h] (concentration per gram dry weight of cells and hour). Also, you are setting an upper bound for the particular import flux and not the flux itself. There are some crude approximations. For instance, if you supply 1 mol of glucose every 24h to 1 gram of bacteria you might set the upper exchange flux for glucose to 1 mol / [1 gDW * 24 h] since that is the nominal maximum that can be imported. There is no guarantee however that glucose will be consumed with that flux. Thus, the preferred data for exchange fluxes are direct flux measurements as the ones obtained from timecourse exa-metabolome measurements for instance. So how does that look in COBRApy? The current growth medium of a model is managed by the medium attribute. End of explanation """ medium = model.medium medium["EX_o2_e"] = 0.0 model.medium = medium model.medium """ Explanation: This will return a dictionary that contains the upper flux bounds for all active exchange fluxes (the ones having non-zero flux bounds). Right now we see that we have enabled aerobic growth. You can modify a growth medium of a model by assigning a dictionary to model.medium that maps exchange reactions to their respective upper import bounds. For now let us enforce anaerobic growth by shutting off the oxygen import. End of explanation """ model.slim_optimize() """ Explanation: As we can see oxygen import is now removed from the list of active exchanges and we can verify that this also leads to a lower growth rate. End of explanation """ model.medium["EX_co2_e"] = 0.0 model.medium """ Explanation: There is a small trap here. model.medium can not be assigned to directly. So the following will not work: End of explanation """ medium = model.medium medium["EX_co2_e"] = 0.0 model.medium = medium model.medium # now it worked """ Explanation: As you can see EX_co2_e is not set to zero. This is because model.medium is just a copy of the current exchange fluxes. Assigning to it directly with model.medium[...] = ... will not change the model. You have to assign an entire dictionary with the changed import flux upper bounds: End of explanation """ model = load_model("textbook") with model: medium = model.medium medium["EX_o2_e"] = 0.0 model.medium = medium print(model.slim_optimize()) print(model.slim_optimize()) model.medium """ Explanation: Setting the growth medium also connects to the context manager, so you can set a specific growth medium in a reversible manner. End of explanation """ from cobra.medium import minimal_medium max_growth = model.slim_optimize() minimal_medium(model, max_growth) """ Explanation: So the medium change is only applied within the with block and reverted automatically. Minimal media In some cases you might be interested in the smallest growth medium that can maintain a specific growth rate, the so called "minimal medium". For this we provide the function minimal_medium which by default obtains the medium with the lowest total import flux. This function needs two arguments: the model and the minimum growth rate (or other objective) the model has to achieve. End of explanation """ minimal_medium(model, 0.1, minimize_components=True) """ Explanation: So we see that growth is actually limited by glucose import. Alternatively you might be interested in a minimal medium with the smallest number of active imports. This can be achieved by using the minimize_components argument (note that this uses a MIP formulation and will therefore be much slower). End of explanation """ minimal_medium(model, 0.8, minimize_components=8, open_exchanges=True) """ Explanation: When minimizing the number of import fluxes there may be many alternative solutions. To obtain several of those you can also pass a positive integer to minimize_components which will give you at most that many alternative solutions. Let us try that with our model and also use the open_exchanges argument which will assign a large upper bound to all import reactions in the model. The return type will be a pandas.DataFrame. End of explanation """ ecoli = load_model("iJO1366") ecoli.exchanges[0:5] """ Explanation: So there are 4 alternative solutions in total. One aerobic and three anaerobic ones using different carbon sources. Boundary reactions Apart from exchange reactions there are other types of boundary reactions such as demand or sink reactions. cobrapy uses various heuristics to identify those and they can be accessed by using the appropriate attribute. For exchange reactions: End of explanation """ ecoli.demands """ Explanation: For demand reactions: End of explanation """ ecoli.sinks """ Explanation: For sink reactions: End of explanation """ ecoli.boundary[0:10] """ Explanation: All boundary reactions (any reaction that consumes or introduces mass into the system) can be obtained with the boundary attribute: End of explanation """
blakeflei/IntroScientificPythonWithJupyter
07 - Some Basic Statistics.ipynb
bsd-3-clause
from numpy.random import normal,rand import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats %matplotlib inline """ Explanation: Some Basic Statistics This module will cover the calculation of some basic statistical parameters using numpy and scipy, starting with a 'by hand' or from textbook formulas and using built-in functions. By the end of this file you should have seen simple examples of: 1. Mean, standard deviation, and variance 2. Confidence intervals 3. One-way analysis of variance (ANOVA) 4. Student's t-test 5. F-test 6. Coefficient of determination 7. Pearson's correlation coefficient 8. Probability Distribution Functions (PDFs) Further Reading: https://docs.scipy.org/doc/scipy/reference/stats.html https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html https://github.com/scipy/scipy/blob/master/scipy/stats/stats.py http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm http://www.physics.csbsju.edu/stats/t-test.html https://onlinecourses.science.psu.edu/stat501/node/255 http://originlab.com/doc/Origin-Help/ANOVA-CRD http://hamelg.blogspot.com/2015/11/python-for-data-analysis-part-22.html End of explanation """ # Generate some continuous data: nums = normal(2, 3, 1000) # function of mean (mu), std (sigma), and size (n) """ Explanation: Mean, Standard Deviation, and Variance These all give an initial sense of the distribution of a group of samples - the average value (mean) and how spread out they are (standard deviation and variance). Keep in mind that the variance is the square of the standard deviation. End of explanation """ mean = (1/len(nums))*np.sum(nums) print('The mean is: %g' % mean) stdev = np.sqrt(1/len(nums) * np.sum((nums - mean)**2)) print('The standard deviation (all samples, or the population) is: %g' % stdev) stdev = np.sqrt(1/(len(nums)-1) * np.sum((nums - mean)**2)) print('The unbiased standard deviation (a group of samples, or a subset of the population) is: %g' % stdev) var = (1/len(nums)) * np.sum((nums - mean)**2) print('The variance is: %g' % var) """ Explanation: Mean: $\mu = \frac{1}{n}\sum_{i=1}^{n} x_i$ Standard deviation Root of the average squared deviation from the mean (entire population): $\sigma = \sqrt{\frac{1}{n}\sum_{i=1}^{n} (x_i-\mu)^2}$ Root of the average squared deviation from the mean (subset of population): $\sigma = \sqrt{\frac{1}{n-1}\sum_{i=1}^{n} (x_i-\mu)^2}$ Variance Average squared deviation from mean: $\sigma^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i-\mu)^2$ We can do these calculations manually: End of explanation """ mean = np.mean(nums) print('The mean is: %g' % mean) stdev = np.std(nums) print('The standard deviation (all samples, or the population) is: %g' \ % stdev) stdev = np.std(nums, ddof=1) print('The standard deviation (a group of samples, or a subset of the population) is: %g' % stdev) var = np.var(nums) print('The variance is: %g' % var) """ Explanation: Or by using built-in functions: End of explanation """ # Start with normally distributed group of samples grp1 = normal(100, 5, 10000) # Compute the standard error of the mean grp1_avg = np.mean(grp1) grp1_std = np.std(grp1, ddof=1) standard_err = grp1_std/np.sqrt(np.size(grp1)) # Determine the critical probability that corresponds to 1/2 of the # 95% confidence interval (see Distributions) conf_int = 0.95 dof = len(grp1)-1 # We use the degrees of freedom of n-1 because it's # a sample of the population T_val = stats.t.ppf(1-(1-conf_int)/2, dof) # Use the percent point # function (inverse of the # CDF, more on this later) # The average value, reported with 95% confidence is: conf_int = standard_err*T_val lower_int = grp1_avg - conf_int upper_int = grp1_avg + conf_int print("The value is {0:.3g} ± {1:.3g} (95% confidence interval)" \ .format(grp1_avg, conf_int)) print("or a range of {0:.6g} to {0:.6g}".format(lower_int,upper_int)) """ Explanation: Confidence Intervals How sure are we that the measurements we've taken encompass the population mean, rather than just the mean of the sample group (assuming it is a subset of the population mean)? Confidence invervals define bounds on the certainty of a reported value. Starting with a normally distributed group of random samples, we want to state with a known amount of confidence (i.e. 95% confidence) that the reported interval will contain the population mean. We report: $\mu \pm \sigma_m T$ where: $\mu$ is the mean value $T$ is the critical probability (t-value) $\sigma_m = \frac{\sigma}{\sqrt{n}}$ is the standard error of the mean $\sigma$ is the standard deviation $n$ is the number of samples Notes: - Technically, it is not correct to state that mean has a 95% chance of being within the confidence inverval (using 95% confidence as an example). The mean is a number, not a probability. **A confidence interval of 95% means that the confidence interval, if repeated with many different groups of samples, would encompass the population mean 95% of the time.** This is a slight distinction: it's not that there is a 95% chance that the value is within that particular confidence interval - it's a statement that the confidence interval, if repeated, would trend towards encompassing the population mean 95% of the time. Assuming the group of samples is a subset and not the entire population, critical probability (t-value) is determined from the t-distribution instead of the normal distribution. This is more accurate for lower sampling because it takes into account the degrees of freedom. Keep in mind the t- and the normal distributions converge for large sampling. For more information about determining the critical probability (t-value) from a percentage (i.e. 95%), see the 'Confidence Intervals from a Distribution Perspective' section near the end of this notebook. End of explanation """ dof = len(grp1)-1 mean = np.mean(grp1) std_err = stats.sem(grp1) #sem = standard error (of the) mean lower_int, upper_int = stats.t.interval(\ 0.95, dof, loc=mean, scale=std_err) print("A range of {0:.6g} to {0:.6g}".format(lower_int, upper_int)) """ Explanation: We can also use the built in function for determining the 95% confidence interval: End of explanation """ from scipy.stats import ttest_ind, ttest_rel # Three groups of data, but one of these is not like the others. grp1 = normal(45, 23, 5) grp2 = normal(45, 23, 5) grp3 = normal(10, 12, 5) """ Explanation: One-Way Analysis of Variance (ANOVA) How could we determine multiple groups of samples are from the same population or from different populations? One-way analysis assumes a single factor (independent variable) affects the mean value of the group. Keep in mind that the samples should be independent and interval or ratio data (i.e. not categorical). Two groups: Student's T-test The goal of the Student's t-test is to determine if two groups of samples are from the same population or different populations. This comes up frequently when we want to determine if the data we're collected somehow differs from another data set (i.e. we've observed something change (before/after populations), or observe something different from what someone else claims). To do this, first calculate a t-value, and use this t-value (to sample the t-distribution) to determine a measure of how similar the two groups of samples are. This is known as a p-value. The p-value represents the probability that the difference between the groups of samples is observed purely by chance. A p-value below some threshold (i.e. 0.05) means there is a significant difference between the groups of samples. Increasing t-values (increasingly different groups) lead to p-value decreases (decreasing chances that the samples are from the same distribution). Often, this is described in terms of the null hypothesis, or that there is 'null difference' between the two groups of samples. In other words, can the null hypothesis (there is no difference between the two populations) be rejected? The goal is to determine if any difference is due to sampling, experimental, etc. error or if the means really are different. This is intended for normally distributed, continuous distributions. Fun fact: the 'student' is actually William S. Gossett, a brewmaster who worked at the Guinness brewery. End of explanation """ # Get some initial info about the three groups grp1_siz = float(grp1.size) grp1_dof = grp1_siz - 1 grp1_avg = np.sum(grp1)/grp1_siz grp1_var = 1/(grp1_dof)* np.sum((grp1 - grp1_avg)**2) grp2_siz = float(grp2.size) grp2_dof = grp2_siz - 1 grp2_avg = np.sum(grp2)/grp2_siz grp2_var = 1/(grp2_dof)* np.sum((grp2 - grp2_avg)**2) grp3_siz = float(np.size(grp3)) grp3_avg = np.sum(grp3)/grp3_siz grp3_dof = grp3_siz - 1 grp3_var = 1/(grp3_dof)* np.sum((grp3 - grp3_avg)**2) """ Explanation: Equal sample sizes, equal variances $t = \frac{\bar{X}1 - \bar{X}_2}{s{pool}\sqrt{\frac{2}{n}}}$ where: $s_{pool}$ = pooled variance $s_{pool} = \sqrt{\frac{s_1^2 + s_2^2}{2}}$ $n$ is the number of samples $\bar{X}$ is the expectation value (if equal weights, average) $s_1^2 = \frac{1}{n-1} \sum^{n}_{1} (x_i-\bar{X})^2$ Equal or unequal sample sizes, equal variances $t = \frac{\bar{X}1 - \bar{X}_2}{s{pool}\sqrt{\frac{1}{n_1} + \frac{1}{n_2}}}$ where: $s_{pool} = \sqrt{\frac{(n_1 -1) s_1^2 + (n_2 -1) s_2^2}{n_1 + n_2 -1}}$ Equal or unequal sample sizes, unequal variances $t = \frac{\bar{X}1 - \bar{X}_2}{s\delta}$ where: $s_\delta = \sqrt{\frac{s_1^2}{n_1} + \frac{s_2^2}{n_2}}$ The p-values can be calculated by integrating the Student's t-distribution cumulative density fuction (CDF) directly - more information is provided in the Distributions section. Alternatively, tables of precalculated CDF values (Z-tables) may be used when calculating CDF isn't practical but aren't discussed here. Below, the survival function (stats.t(degFreedom).sf, or '1 - CDF') is used to sample the t-distribution. End of explanation """ # Equal sample size, assumed equal variance: pooled_var = np.sqrt( (grp1_var + grp2_var)/2 ) t = (grp1_avg - grp2_avg)/(pooled_var*np.sqrt(2/grp1_siz)) # Calculate p-value: degFreedom = (grp1_var/grp1_siz + grp2_var/grp2_siz)**2/ \ ((grp1_var/grp1_siz)**2/grp1_dof + (grp2_var/grp2_siz)**2/grp2_dof) p = 2*stats.t(degFreedom).sf(np.abs(t)) # we want 2x the area under the curve, # from neg infinity to the neg t value print(" t = {0:g} p = {1:g}".format(t, p)) """ Explanation: Calculate the Student's t- and p-values: End of explanation """ # Equal or unequal sample size, assumed equal variance: pooled_var = np.sqrt( (grp1_dof*grp1_var+grp2_dof*grp2_var)/ \ (grp1_siz+grp2_siz-2) ) t = (grp1_avg - grp2_avg)/ \ (pooled_var*np.sqrt(1/grp1_siz + 1/grp2_siz)) # Calculate p-value: degFreedom = (grp1_var/grp1_siz + grp2_var/grp2_siz)**2/ \ ((grp1_var/grp1_siz)**2/grp1_dof + (grp2_var/grp2_siz)**2/grp2_dof) p = 2*stats.t(degFreedom).sf(np.abs(t)) print(" t = {0:g} p = {1:g}".format(t, p)) """ Explanation: The p-value between groups 1 and 2 is greater than our value of 0.05, so we cannot reject the null hypothesis, and assume these are from the same population. End of explanation """ # Equal or unequal sample size, assumed unequal variance: var = np.sqrt( grp1_var/grp1_siz + grp3_var/grp3_siz ) t = (grp1_avg - grp3_avg)/var # Calculate p-value: degFreedom = (grp1_var/grp1_siz + grp3_var/grp3_siz)**2/ \ ((grp1_var/grp1_siz)**2/grp1_dof + (grp3_var/grp3_siz)**2/grp3_dof) p = 2*stats.t(degFreedom).sf(np.abs(t)) print(" t = {0:g} p = {1:g}".format(t, p)) """ Explanation: The p-value between groups 1 and 2 is still greater than our value of 0.05, so we cannot reject the null hypothesis, and assume these are from the same population. End of explanation """ # Equal sample size, assumed equal variance: t, p = ttest_rel(grp1, grp2) print("ttest_rel eq_var: t = %g p = %g" % (t, p)) # Equal or unequal sample size, assumed equal variance: t, p = ttest_ind(grp1, grp2, equal_var=True) print("ttest_ind eq_var: t = %g p = %g" % (t, p)) # Note that the first and second t-tests converge as sampling # approaches infinity. # Equal or unequal sample size, assumed unequal variance: t, p = ttest_ind(grp1, grp3, equal_var=False) print("ttest_ind uneq_var: t = %g p = %g" % (t, p)) """ Explanation: The p-value between groups 1 and 3 is still greater than our value of 0.05, but is much closer. We can't strictly reject the null hypothesis, but it's worth a closer look. Do we really have enough samples to draw conclusions? Or use built-in functions: End of explanation """ grp1 = normal(45, 23, 500) grp2 = normal(45, 23, 500) grp3 = normal(10, 12, 500) """ Explanation: If the p-value is smaller than some threshold (i.e. 0.01 or 0.05, etc.) then the null hypothesis can be rejected. The two groups of samples have different means! Note that the first and second tests converge as sampling approaches infinity. The goal of the Student's t-test is to determine if two groups of samples are from the same population or different populations. This comes up frequently when we want to determine if the data we're collected somehow differs from another data set (i.e. we've observed something change (before/after populations), or observe something different from what someone else claims). To do this, first calculate a t-value, and use this t-value (to sample the t-distribution) to determine a measure of how similar the two groups of samples are. This is known as a p-value. The p-value represents the probability that the difference between the groups of samples is observed purely by chance. A p-value below some threshold (i.e. 0.05) means there is a significant difference between the groups of samples. Increasing t-values (increasingly different groups) lead to p-value decreases (decreasing chances that the samples are from the same distribution). Often, this is described in terms of the null hypothesis, or that there is 'null difference' between the two groups of samples. In other words, can the null hypothesis (there is no difference between the two populations) be rejected? The goal is to determine if any difference is due to sampling, experimental, etc. error or if the means really are different. This is intended for normally distributed, continuous distributions. Fun fact: the 'student' is actually William S. Gossett, a brewmaster who worked at the Guinness brewery. >2 Groups: One-way ANOVA F-test statistic The F-test can be thought of as the generalized form of the t-test for multiple groups of samples. A popular use of the F-test is to determine if one group of samples is from a different population than all other groups (i.e. one vs many), or if all are from the same population. While there are several different F-tests, the focus here is on a test to determine if the means of a given set of normally distributed values are equal. To do this, first calculate a F-statistic, and use this F-statistic (to sample the F-distribution) to find the chance that all of the groups of samples are from the same population. Like with T-tests above, we call this sample the p-value. The p-value represents the chance that the difference between the groups of samples is observed purely by chance. A p-value below some threshold (i.e. 0.05) means that there is a significant difference between the groups of samples. Here, the F-statistic is the ratio of variation between sample means to the variation within the samples. Increasing F-statistics lead to decreasing the p-values (decreasing chances that the samples are from the same distribution). Often, this is described in terms of the null hypothesis, or the hypothesis that there is null difference between the groups of samples. In other words, can the null hypothesis (all groups are from the same population) be rejected? The goal is to determine if the differencs are due to sampling, experimental, etc. error or if the means really are different. This is intended for normally distributed, continuous distributions. End of explanation """ all_grps = [grp1, grp2, grp3] # Use some vectorization to simplify # code num_grps = float(len(all_grps)) alldata = np.concatenate(all_grps) alldata_avg = np.mean(alldata) alldata_siz = np.size(alldata) bgv = 0 for a in all_grps: bgv += (np.size(a) * (np.mean(a)-alldata_avg)**2)/(num_grps-1) wgv = 0 for a in all_grps: for i in a: wgv += (i - np.mean(a))**2/(alldata_siz - num_grps) f_stat = bgv/wgv prob = stats.f(num_grps-1, alldata_siz-num_grps).sf(np.abs(f_stat)) print('F-statistic is %g p is %g' % (f_stat, prob)) f, p = stats.f_oneway(grp1,grp2,grp3) print('F-statistic is %g p is %g' % (f, p)) """ Explanation: Here, we use: $F_{stat} = \frac{\text{between set variability}}{\text{within set variability}}$ where: between set variability = $\sum^{K}{i=1} \frac{n_i(\bar{X_i} -\bar{X})^2}{K - 1}$ within set variability = $\sum^{K}{i=1} \sum^{n_i}{j=1} \frac{(X{ij} -\bar{X_i})^2}{N - K}$ and: $\bar{X}$ is the mean of all data $\bar{X_i}$ is the mean of set $i$ $K$ is the number of sets $N$ is the overall sample size End of explanation """ from scipy.optimize import curve_fit # Create arbitrary function x_vals = np.arange(0, 100) y_vals = x_vals**2 + normal(0, 3000, np.size(x_vals)) # Fit and create fit line def func(x_vals, B, C): return x_vals**B + C opt, cov = curve_fit(func, x_vals, y_vals) x_fitted = np.linspace(0, max(x_vals), 100) y_fitted = func(x_fitted, *opt) # Show fit plt.scatter(x_vals, y_vals) plt.plot(x_fitted, y_fitted, color='red') plt.show() """ Explanation: Coefficient of Determination ($R^2$) The coefficient of determination is a measure of how closely one group of samples (i.e. measured) follows another (i.e. a model). This is accomplished via the proportion of total variation of outcomes explained by the model. End of explanation """ y_avg = np.mean(y_vals) y_fit = func(x_vals, *opt) SSregr = np.sum( (y_fit - y_avg )**2 ) SSerror = np.sum( (y_vals - y_fit )**2 ) SStotal = np.sum( (y_vals - y_avg )**2 ) Rsq = SSregr/SStotal print('R squared is: %g' % Rsq) """ Explanation: Compute by hand: $R^2 = \frac{SS_{regr}}{SS_{total}}$ where: $SS$ = "sum of squares" ${rgr}$ = "regression" $SS{regr} = \sum^{n}{1} (\hat{x_i}-\bar{X})^2$ $SS{total} = \sum^{n}_{1} (x_i-\bar{X})^2$ and: $\hat{x_i}$ is the fitted value $\bar{X}$ is the average value of X $x_i$ is the measured value of x End of explanation """ from scipy.stats import pearsonr grp1 = list(range(0, 5)) grp2 = grp1+normal(0, 1, np.size(grp1)) plt.scatter(grp1, grp1) plt.scatter(grp1, grp2) plt.show() """ Explanation: Pearson's correlation coefficient For two sets of data, how correlated are the two, on a scale of -1 to 1? A p-value for the Pearson's correlation coefficient can also be determined, indicating the probability of an uncorrelated system producing data that has a Pearson correlation at least as extreme (as with everything, it's not reliable for small groups of samples). Keep in mind that the correlation coefficient is defined for data sets of the same size. End of explanation """ grp1_siz = float(np.size(grp1)) grp1_avg = np.sum(grp1)/grp1_siz grp1_std = np.sqrt((1/grp1_siz) * np.sum((grp1 - grp1_avg)**2)) grp2_siz = float(np.size(grp2)) grp2_avg = np.sum(grp2)/grp2_siz grp2_std = np.sqrt((1/grp2_siz) * np.sum((grp2 - grp2_avg)**2)) dof = grp1_siz - 2 # Note that the size of the two samples must be the same pearson_r = np.sum( 1/grp1_siz*(grp1 - grp1_avg)*(grp2 - grp2_avg) ) / \ (grp1_std * grp2_std) t_conv = pearson_r/np.sqrt( (1 - pearson_r**2)/(grp1_siz - 2) ) # convert to student's t value p = 2*stats.t(dof).sf(np.abs(t_conv)) # survival function of the t-dist print("pearson_r = %g p = %g" % (pearson_r, p)) """ Explanation: Again we can do this by hand, noting that $\rho$ is different from $p$: $\rho = \frac{ \sum^{n}_{1} (1/n) (X_1 - \bar{X}_1) (X_2 - \bar{X}_2)}{s_1^2 s_2^2}$ The p value can be determined by converting $\rho$ to a student's t and then determining the area under the distribution function: $t_{conv} = \frac{\rho}{\sqrt{( 1-\rho^2) / (n-2)}} $ End of explanation """ r,p = pearsonr(grp1, grp2) print("pearson_r = %g p = %g" % (r, p)) """ Explanation: We have a very high Pearson's correlation coefficient (highly correlated) with a low p-value (can reject null hypothsis that it's due purely due to chance). Howeever, we don't have many samples, so it's not a robust conclusion. Or use built-in functions: End of explanation """ num_samples = 10000 span = 10 # How wide to plot and bin rand_gen = normal(0, 1, num_samples) # Generate num_sample numbers bins = np.linspace(-span/2, span/2, num=100) histogram = np.histogram(rand_gen, bins); # Use histogram to get the # distribution X = histogram[1][:-1] Y = histogram[0] plt.scatter(X,Y, label="Sample Frequency") plt.legend(loc='best') plt.title('Scatter Plot') plt.show() """ Explanation: Distributions Distribution functions can be thought of as the probability of measuring a particular sample value. To get a better picture of how frequently a type of randomly distributed variable should be measured in theory, we can use the analytical distribution function. For example, perhaps the most well known distribution is the Gaussian, Normal, or Bell-Curve distribution. This is determined from a set of gaussian distributed random numbers. We can generate a lot of these numbers and plot the frequency of each number within a set of 'bins': End of explanation """ Y_pdf = stats.norm.pdf(X) # PDF function applied to the # X values conv_factor = len(X)/(float(span) * float(num_samples)) # Use a normalization factor to # demonstrate the two are # overlapped plt.scatter(X,Y*conv_factor, label="Sample Frequency") plt.plot(X,Y_pdf, color='red', label="Prob. Dist. Func.") plt.legend(loc='best') plt.show() """ Explanation: The probability distribution function (PDF) is a function that represents the probability of obtaining a particular value for a population that follows that particular distribution. Using a conversion factor, it's clear that the two overlap: End of explanation """ X_dof = np.size(X) - 1 Y_pdf = stats.norm.pdf(X) Y_cdf = stats.norm.cdf(X) plt.plot(X,Y_pdf, color='red', label="Prob. Dist. Func.") plt.plot(X,Y_cdf, color='blue', label="Cumul. Dist. Func.") plt.legend(loc='best') plt.show() """ Explanation: A common use of distributions is to determine the chance of measuring a value of at least some amount. Instead of looking at the probability of obtaining exactly a value, we can ask: what is the probability of obtaining something at least as large? All we need is the integration of the PDF, known as the cumulative distribution function (CDF), as we're really looking for the area under the PDF up to a certain point. Continuing our example: End of explanation """ stats.norm.cdf(2) """ Explanation: For those that are wondering, the CDF is actually less than the PDF at a certain point because both scaled but in different ways - the CDF is scaled such that it's maximum value is one but the PDF is such that the area beneath it is one. For more information, look into the integral of the PDF. We use the CDF to determine the percent chance of obtaining something at least as large, i.e. what is the percent chance of getting at least 2? End of explanation """ dof = np.size(X) - 1 Y_t_pdf = stats.t(dof).pdf(X) Y_t_cdf = stats.t(dof).cdf(X) plt.plot(X, Y_t_pdf, color='red', label="Prob. Dist. Func.") plt.plot(X, Y_t_cdf, color='blue', label="Cumul. Dist. Func.") plt.legend(loc='best') plt.show() """ Explanation: PDF of Student's t-distribution This doesn't seem that interesting until we consider the distributions used in the ANOVA analysis above. Here we use the Student's t-distribution, which is extremely similar to the normal distribution except that it incorporates the fact that we often use a subset of the population (and thus degrees of freedom = n-1): End of explanation """ t = -1.47254 # Use a specified t-value # Use CDF to determine probabilities left_prob = stats.t(dof).cdf(-np.abs(t)) right_prob = stats.t(dof).sf(np.abs(t)) # The survival function is 1-CDF between_prob = 1-(left_prob+right_prob) # Plot t-distribution, highlighting the different plot areas left_ind = X <= -np.abs(t) right_ind = X >= np.abs(t) between_ind = (X > -np.abs(t)) & ( X < np.abs(t)) plt.fill_between(X[left_ind],stats.t(dof).pdf(X[left_ind]), facecolor='red') plt.fill_between(X[right_ind],stats.t(dof).pdf(X[right_ind]), facecolor='red') plt.fill_between(X[between_ind],stats.t(dof).pdf(X[between_ind]),facecolor='deepskyblue') # Label the plot areas plt.text(x=1.7*t,y=0.04, s='%0.3g' % left_prob) plt.text(x=-0.4,y=0.1,s='%0.3g' % between_prob) plt.text(x=1.1*-t,y=0.04, s='%0.3g' % right_prob) plt.show() """ Explanation: Let's say our t-value is: -1.47254. A note about two-tailed tests: We're interested if we can reject the null hypothesis, or if the populations are the same. The t-value can be positive or negative (depending on the two means) but we're only interested only if it is different (not only + or only - difference, but both). To determine the p-value, we sample from both sides of the distribution, and this is known as a two-tailed test. For the p-value of the t-test (two-tailed), we're concerned with getting the the value under both sides of the distribution. Here we're ignoring the sign of the t-value and treating it as a negative value for a zero-mean t-distribution probability distribution function. For the two-tailed p-value on a t-test: End of explanation """ p = 2*stats.t(dof).sf(np.abs(t)) print("%g" % p) """ Explanation: The two-tailed test (i.e. including both sides) is simply 2x the value of the area of one of the sides: End of explanation """ conf_int = 0.95 # Use a specified confidence interval # (i.e. % of total CDF area) # We use the t-distribution in lieu of the normal distribution because # the samples are a subset of the population the inverse of the CDF # for the normal distribution is known as the percent point function t_value = stats.t.ppf(1-(1-conf_int)/2,dof) # Use CDF to check that probabilities are correct left_prob = stats.t.cdf(-t_value, dof) right_prob = stats.t.sf(t_value, dof) # The survival function is 1-CDF between_prob = 1-(left_prob+right_prob) # Plot T distribution, highlighting the different plot areas left_ind = X <= -t_value right_ind = X >= t_value between_ind = (X > -t_value) & ( X < t_value) plt.fill_between(X[left_ind],stats.t.pdf(X[left_ind],dof), facecolor='deepskyblue') plt.fill_between(X[right_ind],stats.t.pdf(X[right_ind],dof), facecolor='deepskyblue') plt.fill_between(X[between_ind],stats.t.pdf(X[between_ind],dof),facecolor='red') # Label the plot areas plt.text(x=2.2*t,y=0.04, s='%0.3g' % left_prob) plt.text(x=-0.4,y=0.1,s='%0.3g' % between_prob) plt.text(x=1.6*-t,y=0.04, s='%0.3g' % right_prob) plt.show() print("The t_value that can be used in the 95 percent confidence interval is: %0.6g" % T_val) """ Explanation: Confidence Intervals from a Distribution Perspective This is where the critical probability (t-value) for the confidence interval comes from. Working backwards, we're interested the value of the probability distribution function that, when sampled, encompasses $\frac{1}{2}$ of the confidence interval (i.e. 95%) area under the function. To do so, 1/2 of the confidence interval on each side of the distribution is removed, and the corresponding t-value is determined. End of explanation """
gschivley/ERCOT_power
Prediction model/Prediction models - XGBoost.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import os from xgboost import XGBRegressor from sklearn.linear_model import LinearRegression from sklearn.svm import SVR, LinearSVR from sklearn.model_selection import GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.ensemble import GradientBoostingRegressor from sklearn.model_selection import validation_curve, learning_curve """ Explanation: Prediction model End of explanation """ path = '../Final report' X_fn = 'x.csv' y_fn = 'y.csv' X_path = os.path.join(path, X_fn) y_path = os.path.join(path, y_fn) X = pd.read_csv(X_path) y = pd.read_csv(y_path) X.head() """ Explanation: Import data Might still need to clean up the files some after import End of explanation """ for fuel in ['All coal', 'Lignite', 'Subbituminous']: X.loc[:,fuel] = X.loc[:,fuel].values/X.loc[:,'NG Price ($/mcf)'].values X.drop('NG Price ($/mcf)', axis=1, inplace=True) """ Explanation: Make fuel price a ratio of the coal price to the natural gas price End of explanation """ cluster_ids = X['cluster'].unique() for cluster in cluster_ids: X['cluster_{}'.format(cluster)] = np.eye(len(cluster_ids))[X['cluster'],cluster] X.head() X.tail() """ Explanation: One-hot encoding of the cluster variable I'm trying to make this easy for using with different numbers of clusters End of explanation """ free_cap_dict = {} for cluster in range(6): free_cap_dict[cluster] = X.loc[X['cluster'] == cluster, ['DATETIME', 'nameplate_capacity', 'GROSS LOAD (MW)']] col_name = 'cluster_' + str(cluster) + ' free capacity' free_cap_dict[cluster].loc[:,col_name] = (free_cap_dict[cluster].loc[:,'nameplate_capacity'].values - free_cap_dict[cluster].loc[:,'GROSS LOAD (MW)'].values) free_cap_dict[0].head() for cluster in range(6): col_name = 'cluster_' + str(cluster) + ' free capacity' X = pd.merge(X, free_cap_dict[cluster].loc[:,['DATETIME', col_name]], on='DATETIME') X.head(n=10) for idx in X.index: datetime = X.loc[idx, 'DATETIME'] for cluster in range(6): col_name = 'cluster_' + cluster + ' free capacity' X.loc[idx, col_name] = y.tail() """ Explanation: Add free capacity of every group for that hour. Turns out that this doesn't help prediction. It actually makes prediction much worse... End of explanation """ X_cols = ['nameplate_capacity', 'GROSS LOAD (MW)', 'ERCOT Load, MW', 'Total Wind Installed, MW', 'Total Wind Output, MW', 'Net Load Change (MW)', 'All coal', 'Lignite', 'Subbituminous'] X_cluster_cols = ['cluster_{}'.format(cluster) for cluster in cluster_ids] # X_cluster_free_cols = ['cluster_{} free capacity'.format(cluster) for cluster in cluster_ids] X_clean = X.loc[:,X_cols+X_cluster_cols]#+X_cluster_free_cols] X_clean.fillna(0, inplace=True) y_clean = y.loc[:,'Gen Change (MW)'] y_clean.fillna(0, inplace=True) print X_clean.shape print y_clean.shape X_clean.head() """ Explanation: Drop unnecessary columns and replace nan's with 0 End of explanation """ X_train = X_clean.loc[(X['Year']<2012),:] y_train = y_clean.loc[(X['Year']<2012)] X_va = X_clean.loc[X['Year'].isin([2012, 2013]),:] y_va = y_clean.loc[X['Year'].isin([2012, 2013])] X_test = X_clean.loc[X['Year']>2013,:] y_test = y_clean.loc[X['Year']>2013] """ Explanation: Split into training, validation, testing End of explanation """ X_train_scaled = StandardScaler().fit_transform(X_train) X_va_scaled = StandardScaler().fit_transform(X_va) X_test_scaled = StandardScaler().fit_transform(X_test) """ Explanation: Need scaled versions of the X data for some of the models End of explanation """ print X_train_scaled.shape, y_train.shape print X_va_scaled.shape, y_va.shape print X_test_scaled.shape, y_test.shape """ Explanation: Check size of all arrays End of explanation """ lm = LinearRegression() lm.fit(X_train_scaled, y_train) lm.score(X_va_scaled, y_va) y_pr = lm.predict(X_va_scaled) y_va.values.shape, y_pr.shape, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values.shape y_lm_resids = pd.DataFrame(dict(zip(['Gen Change (MW)', 'y_pr', 'cluster'], [y_va.values, y_pr, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values]))) # y_lm_resids['y_pr'] = y_pr # y_lm_resids['cluster'] = X.loc[:,'cluster'] y_lm_resids.head() y_lm_resids.loc[:,'residuals'] = y_lm_resids.loc[:,'y_pr'] - y_lm_resids.loc[:,'Gen Change (MW)'] g = sns.FacetGrid(y_lm_resids, hue='cluster', col='cluster', col_wrap=3) g.map(plt.scatter, 'Gen Change (MW)', 'residuals') g.add_legend() """ Explanation: Linear Regression (OLS) End of explanation """ from xgboost import XGBRegressor """ Explanation: XGBoost End of explanation """ param_values = [25, 100, 250, 350] train_scores, valid_scores = validation_curve(XGBRegressor(), X_train, y_train, "n_estimators", param_values, n_jobs=-1, verbose=3) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.title("Validation Curve with XGBoost", size=15) plt.xlabel("n_estimators", size=15) plt.ylabel("Score", size=15) plt.ylim(0.0, 1.1) lw = 2 plt.plot(param_values, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_values, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.plot(param_values, valid_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_values, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") plt.savefig('XGBoost n_estimators validation curve.pdf', bbox_inches='tight') """ Explanation: Validation curve for n_estimators End of explanation """ param_values = [1,3,5,9,15] train_scores, valid_scores = validation_curve(XGBRegressor(n_estimators=250), X_train, y_train, "max_depth", param_values, n_jobs=-1, verbose=3) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.title("Validation Curve with XGBoost", size=15) plt.xlabel("max_depth", size=15) plt.ylabel("Score", size=15) plt.ylim(0.0, 1.1) lw = 2 plt.plot(param_values, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_values, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.plot(param_values, valid_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_values, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") plt.savefig('XGBoost max_depth validation curve.pdf', bbox_inches='tight') """ Explanation: Validation curve for n_estimators End of explanation """ param_values = np.logspace(-5, 1, 7) train_scores, valid_scores = validation_curve(XGBRegressor(n_estimators=250), X_train, y_train, "reg_alpha", param_values, n_jobs=-1, verbose=3) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.title("Validation Curve with XGBoost") plt.xlabel("reg_alpha") plt.ylabel("Score") plt.ylim(0.0, 1.1) lw = 2 plt.semilogx(param_values, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(param_values, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.semilogx(param_values, valid_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(param_values, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") """ Explanation: Validation curve for reg_alpha End of explanation """ param_values = [1,3,5,9,15] train_sizes, train_scores, valid_scores = learning_curve(XGBRegressor(n_estimators=250), X_train, y_train, n_jobs=-1, verbose=3) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) valid_scores_mean = np.mean(valid_scores, axis=1) valid_scores_std = np.std(valid_scores, axis=1) plt.title("Learning Curve with XGBoost", size=15) plt.xlabel("Sample size", size=15) plt.ylabel("Score", size=15) plt.ylim(0.0, 1.1) lw = 2 plt.plot(train_sizes, train_scores_mean, label="Training score", color="darkorange", lw=lw) plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.2, color="darkorange", lw=lw) plt.plot(train_sizes, valid_scores_mean, label="Cross-validation score", color="navy", lw=lw) plt.fill_between(train_sizes, valid_scores_mean - valid_scores_std, valid_scores_mean + valid_scores_std, alpha=0.2, color="navy", lw=lw) plt.legend(loc="best") plt.savefig('XGBoost learning curve.pdf', bbox_inches='tight') xgbr = XGBRegressor(n_estimators=250) xgbr.fit(X_train, y_train) y_pr = xgbr.predict(X_va) y_xgbr_resids = pd.DataFrame(dict(zip(['Gen Change (MW)', 'y_pr', 'cluster'], [y_va.values, y_pr, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values]))) y_xgbr_resids.loc[:,'residuals'] = y_xgbr_resids.loc[:,'y_pr'] - y_xgbr_resids.loc[:,'Gen Change (MW)'] plt.scatter() with sns.axes_style('whitegrid'): g = sns.FacetGrid(y_xgbr_resids, hue='cluster', col='cluster', col_wrap=3) g.map(plt.scatter, 'y_pr', 'residuals', s=5, alpha=.3) g.set_xlabels(size=15) g.set_ylabels(size=15) plt.savefig('XGBR residuals.pdf') model = XGBRegressor() subsample = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0] param_grid = dict(subsample=subsample) grid_search = GridSearchCV(model, param_grid, n_jobs=-1, verbose=3) result = grid_search.fit(X_train_scaled, y_train) result.cv_results_ model = XGBRegressor() colsample_bytree = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0] param_grid = dict(colsample_bytree=colsample_bytree) grid_search = GridSearchCV(model, param_grid, n_jobs=-1, verbose=3) result = grid_search.fit(X_train_scaled, y_train) result.cv_results_ model = XGBRegressor() colsample_bylevel = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 1.0] param_grid = dict(colsample_bylevel=colsample_bylevel) grid_search = GridSearchCV(model, param_grid, n_jobs=-1, verbose=3) result = grid_search.fit(X_train_scaled, y_train) result.cv_results_ model = XGBRegressor() max_depth = [3, 6, 9] n_estimators = [100, 250, 500] reg_alpha = [1e-5, 1e-3, 0.1] reg_lambda = [1e-3, 0.1, 1] param_grid = dict(max_depth=max_depth, n_estimators=n_estimators, reg_alpha=reg_alpha, reg_lambda=reg_lambda) grid_search = GridSearchCV(model, param_grid, n_jobs=-1, verbose=2) result = grid_search.fit(X_train_scaled, y_train) import cPickle as pickle pickle.dump((grid_search, result), open( "xgb gridsearch and results.pkl", "wb" ) ) result.cv_results_ result.best_estimator_ grid_search.score(X_va_scaled, y_va) """ Explanation: Learning curve for n_estimators=250 and max_depth=3 End of explanation """ xgb = XGBRegressor(n_estimators=250, reg_alpha=0.1) xgb.fit(X_train, y_train) xgb.score(X_va, y_va) y_pr = xgb.predict(X_va) y_xgb_resids = pd.DataFrame(dict(zip(['Gen Change (MW)', 'y_pr', 'cluster'], [y_va.values, y_pr, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values]))) y_xgb_resids.loc[:,'residuals'] = y_xgb_resids.loc[:,'y_pr'] - y_xgb_resids.loc[:,'Gen Change (MW)'] g = sns.FacetGrid(y_xgb_resids, hue='cluster', col='cluster', col_wrap=3) g.map(plt.scatter, 'y_pr', 'residuals') g.add_legend() y_xgb_resids.describe() """ Explanation: Try XGBoost on non-scaled data Turns out this works better End of explanation """ X_train.columns X_train_ratio = X_train.copy() X_va_ratio = X_va.copy() for fuel in ['All coal', 'Lignite', 'Subbituminous']: X_train_ratio.loc[:,fuel] = X_train_ratio.loc[:,fuel].values/X_train_ratio.loc[:,'NG Price ($/mcf)'].values X_va_ratio.loc[:,fuel] = X_va.loc[:,fuel]/X_va.loc[:,'NG Price ($/mcf)'] X_train_ratio.drop('NG Price ($/mcf)', axis=1, inplace=True) X_va_ratio.drop('NG Price ($/mcf)', axis=1, inplace=True) X_train.head() X_train_ratio.head() xgb_ratio = XGBRegressor(n_estimators=250, reg_alpha=0.1) xgb_ratio.fit(X_train_ratio, y_train) xgb_ratio.score(X_va_ratio, y_va) y_pr = xgb_ratio.predict(X_va_ratio) y_xgb_resids = pd.DataFrame(dict(zip(['Gen Change (MW)', 'y_pr', 'cluster'], [y_va.values, y_pr, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values]))) y_xgb_resids.loc[:,'residuals'] = y_xgb_resids.loc[:,'y_pr'] - y_xgb_resids.loc[:,'Gen Change (MW)'] g = sns.FacetGrid(y_xgb_resids, hue='cluster', col='cluster', col_wrap=3) g.map(plt.scatter, 'y_pr', 'residuals') g.add_legend() y_xgb_resids.describe() from xgboost import plot_importance plot_importance(xgb_ratio) """ Explanation: Try ratio of fuel prices End of explanation """ lm = LinearRegression(normalize=True) lm.fit(X_train_ratio, y_train) lm.score(X_va_ratio, y_va) y_pr = lm.predict(X_va_scaled) y_va.values.shape, y_pr.shape, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values.shape y_lm_resids = pd.DataFrame(dict(zip(['Gen Change (MW)', 'y_pr', 'cluster'], [y_va.values, y_pr, X.loc[X['Year'].isin([2012, 2013]),'cluster'].values]))) # y_lm_resids['y_pr'] = y_pr # y_lm_resids['cluster'] = X.loc[:,'cluster'] y_lm_resids.head() y_lm_resids.loc[:,'residuals'] = y_lm_resids.loc[:,'y_pr'] - y_lm_resids.loc[:,'Gen Change (MW)'] g = sns.FacetGrid(y_lm_resids, hue='cluster', col='cluster', col_wrap=3) g.map(plt.scatter, 'Gen Change (MW)', 'residuals') g.add_legend() """ Explanation: Linear Regression (OLS) with ratio of fuel prices Slight improvement from first OLS try, but still nowhere near as good as gradient boosting End of explanation """
GoogleCloudPlatform/training-data-analyst
courses/machine_learning/deepdive2/production_ml/solutions/custom_model_training.ipynb
apache-2.0
USER_FLAG = "--user" !pip3 install {USER_FLAG} google-cloud-aiplatform==1.7.0 --upgrade !pip3 install {USER_FLAG} kfp==1.8.9 google-cloud-pipeline-components==0.2.0 """ Explanation: Running custom model training on Vertex AI Pipelines In this lab, you will learn how to run a custom model training job using the Kubeflow Pipelines SDK on Vertex AI Pipelines. Learning objectives Use the Kubeflow Pipelines SDK to build scalable ML pipelines. Create and containerize a custom Scikit-learn model training job that uses Vertex AI managed datasets. Run a batch prediction job within Vertex AI Pipelines. Use pre-built components, which are provided through the google_cloud_pipeline_components library, to interact with Vertex AI services. Vertex AI Pipelines setup There are a few additional libraries you'll need to install in order to use Vertex AI Pipelines: Kubeflow Pipelines: This is the SDK you'll be using to build your pipeline. Vertex AI Pipelines supports running pipelines built with both Kubeflow Pipelines or TFX. Google Cloud Pipeline Components: This library provides pre-built components that make it easier to interact with Vertex AI services from your pipeline steps. Each learning objective will correspond to a #TODO in the student lab notebook -- try to complete that notebook first before reviewing this solution notebook. To install both of the services to be used in this notebook, first set the user flag in the notebook cell: End of explanation """ 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: You may see some warning messages in the install output. After installing these packages you'll need to restart the kernel: End of explanation """ # TODO 1: Check for the KFP SDK version !python3 -c "import kfp; print('KFP SDK version: {}'.format(kfp.__version__))" !python3 -c "import google_cloud_pipeline_components; print('google_cloud_pipeline_components version: {}'.format(google_cloud_pipeline_components.__version__))" """ Explanation: Finally, check that you have correctly installed the packages. The KFP SDK version should be >=1.8: End of explanation """ import os 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: Set your project ID and bucket Throughout this notebook, you'll reference your Cloud project ID and the bucket you created earlier. Next you'll create variables for each of those. If you don't know your project ID you may be able to get it by running the following: End of explanation """ if PROJECT_ID == "" or PROJECT_ID is None: PROJECT_ID = "your-project-id" # @param {type:"string"} """ Explanation: Otherwise, set it here: End of explanation """ BUCKET_NAME="gs://" + PROJECT_ID + "-bucket" !echo {BUCKET_NAME} """ Explanation: Then create a variable to store your bucket name. If you created it in this lab, the following will work. Otherwise, you'll need to set this manually: End of explanation """ from kfp.v2 import compiler, dsl from kfp.v2.dsl import pipeline from google.cloud import aiplatform from google_cloud_pipeline_components import aiplatform as gcc_aip """ Explanation: Import libraries Add the following to import the libraries you'll be using throughout this notebook: End of explanation """ PATH=%env PATH %env PATH={PATH}:/home/jupyter/.local/bin REGION="us-central1" PIPELINE_ROOT = f"{BUCKET_NAME}/pipeline_root/" PIPELINE_ROOT """ Explanation: Define constants The last thing you need to do before building your pipeline is define some constant variables. PIPELINE_ROOT is the Cloud Storage path where the artifacts created by your pipeline will be written. You're using us-central1 as the region here, but if you used a different region when you created your bucket, update the REGION variable in the code below: End of explanation """ !mkdir traincontainer !touch traincontainer/Dockerfile !mkdir traincontainer/trainer !touch traincontainer/trainer/train.py """ Explanation: After running the code above, you should see the root directory for your pipeline printed. This is the Cloud Storage location where the artifacts from your pipeline will be written. It will be in the format of gs://YOUR-BUCKET-NAME/pipeline_root/ Configuring a custom model training job Before you set up your pipeline, you need to write the code for your custom model training job. To train the model, you'll use the UCI Machine Learning Dry beans dataset, from: KOKLU, M. and OZKAN, I.A., (2020), "Multiclass Classification of Dry Beans Using Computer Vision and Machine Learning Techniques."In Computers and Electronics in Agriculture, 174, 105507. DOI. Your first pipeline step will create a managed dataset in Vertex AI using a BigQuery table that contains a version of this beans data. The dataset will be passed as input to your training job. In your training code, you'll have access to environment variable to access this managed dataset. Here's how you'll set up your custom training job: Write a Scikit-learn DecisionTreeClassifier model to classify bean types in your data. Package the training code in a Docker container and push it to Container Registry From there, you'll be able to start a Vertex AI Training job directly from your pipeline. Let's get started! Define your training code in a Docker container Run the following to set up a directory where you'll add your containerized code: End of explanation """ %%writefile traincontainer/Dockerfile FROM gcr.io/deeplearning-platform-release/sklearn-cpu.0-23 WORKDIR / # Copies the trainer code to the docker image. COPY trainer /trainer RUN pip install sklearn google-cloud-bigquery joblib pandas google-cloud-storage # Sets up the entry point to invoke the trainer. ENTRYPOINT ["python", "-m", "trainer.train"] """ Explanation: After running those commands, you should see a directory called traincontainer/ created on the left (you may need to click the refresh icon to see it). You'll see the following in your traincontainer/ directory: + Dockerfile + trainer/ + train.py Your first step in containerizing your code is to create a Dockerfile. In your Dockerfile you'll include all the commands needed to run your image. It'll install all the libraries you're using and set up the entry point for your training code. Run the following to create a Dockerfile file locally in your notebook: End of explanation """ %%writefile traincontainer/trainer/train.py from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import roc_curve from sklearn.model_selection import train_test_split from google.cloud import bigquery from google.cloud import storage from joblib import dump import os import pandas as pd bqclient = bigquery.Client() storage_client = storage.Client() def download_table(bq_table_uri: str): prefix = "bq://" if bq_table_uri.startswith(prefix): bq_table_uri = bq_table_uri[len(prefix):] table = bigquery.TableReference.from_string(bq_table_uri) rows = bqclient.list_rows( table, ) return rows.to_dataframe(create_bqstorage_client=False) # These environment variables are from Vertex AI managed datasets training_data_uri = os.environ["AIP_TRAINING_DATA_URI"] test_data_uri = os.environ["AIP_TEST_DATA_URI"] # Download data into Pandas DataFrames, split into train / test df = download_table(training_data_uri) test_df = download_table(test_data_uri) labels = df.pop("Class").tolist() data = df.values.tolist() test_labels = test_df.pop("Class").tolist() test_data = test_df.values.tolist() # TODO 2: Define and train the Scikit model skmodel = DecisionTreeClassifier() skmodel.fit(data, labels) score = skmodel.score(test_data, test_labels) print('accuracy is:',score) # Save the model to a local file dump(skmodel, "model.joblib") # Upload the saved model file to GCS bucket = storage_client.get_bucket("YOUR_GCS_BUCKET") model_directory = os.environ["AIP_MODEL_DIR"] storage_path = os.path.join(model_directory, "model.joblib") blob = storage.blob.Blob.from_string(storage_path, client=storage_client) blob.upload_from_filename("model.joblib") """ Explanation: Run the following to create train.py file. This retrieves the data from your managed dataset, puts it into a Pandas DataFrame, trains a Scikit-learn model, and uploads the trained model to Cloud Storage: End of explanation """ BUCKET = BUCKET_NAME[5:] # Trim the 'gs://' before adding to train script !sed -i -r 's@YOUR_GCS_BUCKET@'"$BUCKET"'@' traincontainer/trainer/train.py """ Explanation: Run the following to replace YOUR_GCS_BUCKET from the script above with the name of your Cloud Storage bucket: End of explanation """ !PROJECT_ID=$(gcloud config get-value project) !IMAGE_URI="gcr.io/YOUR_PROJECT_ID/scikit:v1" """ Explanation: You can also do this manually if you'd prefer. If you do, make sure not to include the gs:// in your bucket name when you update the script. Now your training code is in a Docker container and you're ready to run training in the Cloud. Push container to Container Registry With your training code complete, you're ready to push this to Google Container Registry. Later when you configure the training component of your pipeline, you'll point Vertex AI Pipelines at this container. Replace YOUR_PROJECT_ID with your PROJECT_ID in the IMAGE_URI. End of explanation """ !docker build ./traincontainer -t gcr.io/YOUR_PROJECT_ID/scikit:v1 """ Explanation: Again, replace YOUR_PROJECT_ID with your PROJECT_ID and build your container by running the following: End of explanation """ !docker push gcr.io/$PROJECT_ID/scikit:v1 """ Explanation: Finally, push the container to Container Registry: End of explanation """ %%writefile batch_examples.csv Area,Perimeter,MajorAxisLength,MinorAxisLength,AspectRation,Eccentricity,ConvexArea,EquivDiameter,Extent,Solidity,roundness,Compactness,ShapeFactor1,ShapeFactor2,ShapeFactor3,ShapeFactor4 23288,558.113,207.567738,143.085693,1.450653336,0.7244336162,23545,172.1952453,0.8045881703,0.9890847314,0.9395021523,0.8295857874,0.008913077034,0.002604069884,0.6882125787,0.9983578734 23689,575.638,205.9678003,146.7475015,1.403552348,0.7016945718,24018,173.6714472,0.7652721693,0.9863019402,0.8983750474,0.8431970773,0.00869465998,0.002711119968,0.7109813112,0.9978994889 23727,559.503,189.7993849,159.3717704,1.190922235,0.5430731512,24021,173.8106863,0.8037601626,0.9877607094,0.952462433,0.9157600082,0.007999299741,0.003470231343,0.8386163926,0.9987269085 31158,641.105,212.0669751,187.1929601,1.132879009,0.4699241567,31474,199.1773023,0.7813134733,0.989959967,0.9526231013,0.9392188582,0.0068061806,0.003267009878,0.8821320637,0.9993488983 32514,649.012,221.4454899,187.1344232,1.183349841,0.5346736437,32843,203.4652564,0.7849831,0.9899826447,0.9700068737,0.9188051492,0.00681077351,0.002994124691,0.8442029022,0.9989873701 33078,659.456,235.5600775,178.9312328,1.316483846,0.6503915309,33333,205.2223615,0.7877214708,0.9923499235,0.9558229607,0.8712102818,0.007121351881,0.002530662194,0.7590073551,0.9992209221 33680,683.09,256.203255,167.9334938,1.525623324,0.7552213942,34019,207.081404,0.80680321,0.9900349805,0.9070392732,0.8082699962,0.007606985006,0.002002710402,0.6533003868,0.9966903078 33954,716.75,277.3684803,156.3563259,1.773951126,0.825970469,34420,207.9220419,0.7994819873,0.9864613597,0.8305492781,0.7496238998,0.008168948587,0.001591181142,0.5619359911,0.996846984 36322,719.437,272.0582306,170.8914975,1.591993952,0.7780978465,36717,215.0502424,0.7718560075,0.9892420405,0.8818487005,0.7904566678,0.007490177594,0.001803782407,0.6248217437,0.9947124371 36675,742.917,285.8908964,166.8819538,1.713132487,0.8119506999,37613,216.0927123,0.7788277766,0.9750618137,0.8350248381,0.7558572692,0.0077952528,0.001569528272,0.5713202115,0.9787472145 37454,772.679,297.6274753,162.1493177,1.835514817,0.8385619338,38113,218.3756257,0.8016695205,0.9827093118,0.7883332637,0.7337213257,0.007946480356,0.001420623993,0.5383469838,0.9881438654 37789,766.378,313.5680678,154.3409867,2.031657789,0.8704771226,38251,219.3500608,0.7805870567,0.9879218844,0.8085170916,0.6995293312,0.008297866252,0.001225659709,0.4893412853,0.9941740339 47883,873.536,327.9986493,186.5201272,1.758516115,0.822571799,48753,246.9140116,0.7584464543,0.9821549443,0.7885506623,0.7527897207,0.006850002074,0.00135695419,0.5666923636,0.9965376533 49777,861.277,300.7570338,211.6168613,1.42123379,0.7105823885,50590,251.7499649,0.8019106536,0.9839296304,0.843243269,0.8370542883,0.00604208839,0.001829706116,0.7006598815,0.9958014989 49882,891.505,357.1890036,179.8346914,1.986207449,0.8640114945,51042,252.0153467,0.7260210171,0.9772736178,0.7886896753,0.7055518063,0.007160679276,0.001094585314,0.4978033513,0.9887407248 53249,919.923,325.3866286,208.9174205,1.557489212,0.7666552108,54195,260.3818974,0.6966846347,0.9825445152,0.7907120655,0.8002231025,0.00611066177,0.001545654241,0.6403570138,0.9973491406 61129,964.969,369.3481688,210.9473449,1.750902193,0.8208567513,61796,278.9836198,0.7501135067,0.9892064211,0.8249553283,0.7553404711,0.006042110436,0.001213219664,0.5705392272,0.9989583843 61918,960.372,353.1381442,224.0962377,1.575832543,0.7728529173,62627,280.7782864,0.7539207091,0.9886790043,0.8436218213,0.7950947556,0.005703319619,0.00140599258,0.6321756704,0.9962029945 141953,1402.05,524.2311633,346.3974998,1.513380332,0.7505863011,143704,425.1354762,0.7147107987,0.9878152313,0.9074598849,0.8109694843,0.003692991084,0.0009853172185,0.6576715044,0.9953071199 145285,1440.991,524.9567463,353.0769977,1.486805285,0.7400216694,146709,430.0960442,0.7860466375,0.9902937107,0.8792413513,0.8192980608,0.003613289371,0.001004269363,0.6712493125,0.9980170255 146153,1476.383,526.1933264,356.528288,1.475881001,0.7354662103,149267,431.3789276,0.7319360978,0.9791380546,0.8425962592,0.8198107159,0.003600290972,0.001003163512,0.6720896099,0.991924286 """ Explanation: Navigate to the Container Registry section of your Cloud console to verify your container is there. Configuring a batch prediction job The last step of your pipeline will run a batch prediction job. For this to work, you need to provide a CSV file in Cloud Storage that contains the examples you want to get predictions on. You'll create this CSV file in your notebook and copy it to Cloud Storage using the gsutil command line tool. Copying batch prediction examples to Cloud Storage The following file contains 3 examples from each class in your beans dataset. The example below doesn't include the Class column since that is what your model will be predicting. Run the following to create this CSV file locally in your notebook: End of explanation """ !gsutil cp batch_examples.csv $BUCKET_NAME """ Explanation: Then, copy the file to your Cloud Storage bucket: End of explanation """ @pipeline(name="automl-beans-custom", pipeline_root=PIPELINE_ROOT) def pipeline( bq_source: str = "bq://sara-vertex-demos.beans_demo.large_dataset", bucket: str = BUCKET_NAME, project: str = PROJECT_ID, gcp_region: str = REGION, bq_dest: str = "", container_uri: str = "", batch_destination: str = "" ): dataset_create_op = gcc_aip.TabularDatasetCreateOp( display_name="tabular-beans-dataset", bq_source=bq_source, project=project, location=gcp_region ) training_op = gcc_aip.CustomContainerTrainingJobRunOp( display_name="pipeline-beans-custom-train", container_uri=container_uri, project=project, location=gcp_region, dataset=dataset_create_op.outputs["dataset"], staging_bucket=bucket, training_fraction_split=0.8, validation_fraction_split=0.1, test_fraction_split=0.1, bigquery_destination=bq_dest, model_serving_container_image_uri="us-docker.pkg.dev/vertex-ai/prediction/sklearn-cpu.0-24:latest", model_display_name="scikit-beans-model-pipeline", machine_type="n1-standard-4", ) batch_predict_op = gcc_aip.ModelBatchPredictOp( project=project, location=gcp_region, job_display_name="beans-batch-predict", model=training_op.outputs["model"], gcs_source_uris=["{0}/batch_examples.csv".format(BUCKET_NAME)], instances_format="csv", gcs_destination_output_uri_prefix=batch_destination, machine_type="n1-standard-4" ) """ Explanation: You'll reference this file in the next step when you define your pipeline. Building a pipeline with pre-built components Now that your training code is in the cloud, you're ready to call it from your pipeline. The pipeline you'll define will use three pre-built components from the google_cloud_pipeline_components library you installed earlier. These predefined components simplify the code you need to write to set up your pipeline, and will allow us to use Vertex AI services like model training and batch prediction. If you can't find a pre-built component for the task you want to accomplish, you can define your own Python-based custom components. To see an example, check out this codelab. Here's what your three-step pipeline will do: Create a managed dataset in Vertex AI. Run a training job on Vertex AI using the custom container you set up. Run a batch prediction job on your trained Scikit-learn classification model. Define your pipeline Because you're using pre-built components, you can set up your entire pipeline in the pipeline definition. End of explanation """ compiler.Compiler().compile( pipeline_func=pipeline, package_path="custom_train_pipeline.json" ) """ Explanation: Compile and run the pipeline With your pipeline defined, you're ready to compile it. The following will generate a JSON file that you'll use to run the pipeline: End of explanation """ from datetime import datetime TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S") """ Explanation: Next, create a TIMESTAMP variable. You'll use this in your job ID: End of explanation """ pipeline_job = aiplatform.PipelineJob( display_name="custom-train-pipeline", template_path="custom_train_pipeline.json", job_id="custom-train-pipeline-{0}".format(TIMESTAMP), parameter_values={ "project": PROJECT_ID, "bucket": BUCKET_NAME, "bq_dest": "bq://{0}".format(PROJECT_ID), "container_uri": "gcr.io/{0}/scikit:v1".format(PROJECT_ID), "batch_destination": "{0}/batchpredresults".format(BUCKET_NAME) }, enable_caching=True, ) """ Explanation: Then define your pipeline job, passing in a few project-specific parameters: End of explanation """ # TODO 3: Run the job pipeline_job.submit() """ Explanation: Finally, run the job to create a new pipeline execution: End of explanation """
CDIPS-AI-2017/pensieve
Notebooks/image_search_query.ipynb
apache-2.0
import os import json import requests from requests_oauthlib import OAuth1 def get_secret(service): """Access local store to load secrets.""" local = os.getcwd() root = os.path.sep.join(local.split(os.path.sep)[:3]) secret_pth = os.path.join(root, '.ssh', '{}.json'.format(service)) return secret_pth def load_secret(service): """Load secrets from a local store. Args: server: str defining server Returns: dict: storing key: value secrets """ pth = get_secret(service) secret = json.load(open(pth)) return secret BING_API_KEY = load_secret('bing') NP_API_KEY, NP_API_SECRET = load_secret('noun_project') def search_bing_for_image(query): """ Perform a Bing image search. Args: query: Image search query Returns: results: List of urls from results """ search_params = {'q': query, 'mkt': 'en-us', 'safeSearch': 'strict'} auth = {'Ocp-Apim-Subscription-Key': BING_API_KEY} url = 'https://api.cognitive.microsoft.com/bing/v5.0/images/search' r = requests.get(url, params=search_params, headers=auth) results = r.json()['value'] urls = [result['contentUrl'] for result in results] return urls def search_np_for_image(query): """ Perform a Noun Project image search. Args: query: Image search query Returns: results: List of image result JSON dicts """ auth = OAuth1(NP_API_KEY, NP_API_SECRET) endpoint = 'http://api.thenounproject.com/icons/{}'.format(query) params = {'limit_to_public_domain': 1, 'limit': 5} response = requests.get(endpoint, params=params, auth=auth) urls = [icon['preview_url'] for icon in response.json()['icons']] return urls print(search_np_for_image('magic')[:3]) print(search_bing_for_image('magic')[:3]) """ Explanation: Extracting image search queries from text Mems that get sent to Proxi should have an image associated with them. Human players should have an easy enough time finding images that represent, but when we have nothing but a chunk of text to go on, this is more difficult. What words are important? Do important words build clear, unambiguous queries? Interacting with image search APIs First things first: I need a way to search the internet for images. I'll be using a combination of the Noun Project API, along with the Bing Image Search API. I considered using Google's Custom Image Search, but the daily limits (100 searches/day) were a little low for my use. Here are some quick functions to format the GET requests for Bing and the Noun Project. End of explanation """ from PIL import Image import matplotlib.pyplot as plt import urllib %matplotlib inline def view_urls(urls): """Display the images found at the provided urls""" for i, url in enumerate(urls): resp = requests.get(url) dat = urllib.request.urlopen(resp.url) img = Image.open(dat) plt.imshow(img) plt.axis('off') plt.show() view_urls(search_bing_for_image('magic')[:3]) view_urls(search_np_for_image('magic')[:3]) """ Explanation: For quick prototyping, I wrote another function to display an image from its URL. End of explanation """ import pensieve book1 = pensieve.Doc('../../corpus/book1.txt', doc_id=1) from pprint import pprint from numpy.random import randint rand = randint(len(book1.paragraphs)) print(book1.paragraphs[rand].text) pprint(book1.paragraphs[rand].words) """ Explanation: Finding important words My teammates and I have done a lot of work these past few weeks extracting the names of people, places, things, activities, and moods from text. This work has been incorporated into a Python package, Pensieve. I'll load up the package and take a look at the words that were extracted from the paragraphs in Harry Potter and the Sorcerer's Stone. End of explanation """ import textacy import networkx as nx graph = textacy.network.terms_to_semantic_network(book1.paragraphs[400].spacy_doc) print(book1.paragraphs[400].text) textacy.viz.draw_semantic_network(graph); """ Explanation: It is nice that the objects and verbs are extracted, but there are too many to just throw into one search query. In order to find the most, let's play around with some features in textacy that can give some sort of importance ordering to the words in the paragraph. Most of these features effectively implement different vertex importance sorting algorithms on a semantic network, so a nice place to start might be at the semantic network itself End of explanation """ print(book1.paragraphs[400].text) textacy.keyterms.textrank(book1.paragraphs[400].spacy_doc) """ Explanation: First, we'll look at textacy.keyterms.textrank. This implements the TextRank algorithm, which iteratively computes a score for each vertex in the graph that roughly corresponds to the number of vertices connected to that vertex. End of explanation """ print(book1.paragraphs[654].text) textacy.keyterms.textrank(book1.paragraphs[654].spacy_doc) """ Explanation: This seems to work pretty well! I suppose in this example, I may have chosen "study", but "plant" still makes sense. Let's look at another paragraph to see what happens. End of explanation """ print(book1.paragraphs[400].text) textacy.keyterms.sgrank(book1.paragraphs[400].spacy_doc) print(book1.paragraphs[654].text) textacy.keyterms.sgrank(book1.paragraphs[654].spacy_doc) """ Explanation: We may run into trouble when the most important nodes are character names. An image search with the query "ron" or even "ron harry potter" is unlikely to give us good results. More on this later... What about other algorithms? Let's try SGRank. This algorithm improves upon TextRank by getting rid of unlikely keyword candidates and performing multiple rankings. It is also capable of outputting multiple word phrases. End of explanation """ print(book1.paragraphs[400].text) textacy.keyterms.key_terms_from_semantic_network(book1.paragraphs[400].spacy_doc, ranking_algo='divrank') print(book1.paragraphs[654].text) textacy.keyterms.key_terms_from_semantic_network(book1.paragraphs[654].spacy_doc, ranking_algo='divrank') """ Explanation: Now this may end up being a little too specific for our purposes. "gryffindor common room" would be a great result for this image, but "dumpy little witch" is not as good... DivRank attempts to provide a ranking that balances node centrality with node diversity. Let's see how that fares. End of explanation """ def build_query(par): """ Use TextRank to find the most important words that aren't character names. """ keyterms = textacy.keyterms.textrank(par.spacy_doc) for keyterm, rank in keyterms: if keyterm.title() not in par.doc.words['people']: return keyterm return None par = book1.paragraphs[randint(len(book1.paragraphs))] print(par.text) build_query(par) """ Explanation: We seem to be getting pretty consistent results between DivRank and TextRank. For simplicity, I'm settling on TextRank. Building the queries Removing character names If the most important node in the semantic network is a character's name, we are unlikely to get decent image search results. The quickest way around this is to move down the ranking until we find a term that isn't a named character. Pensieve collects a list of all of the people named in a document, so this is simple to implement. End of explanation """ def submit_query(query): """ Decide which search engine to use based on the part of speech of the query """ doc = textacy.Doc(query, lang='en') try: urls = search_np_for_image(query) except Exception as e: urls = search_bing_for_image(query) return urls par = book1.paragraphs[400] print(par.text) query = build_query(par) print(query) urls = submit_query(query) view_urls(urls[:1]) """ Explanation: Deciding which search engine to use We'll probably get good enough results by trying the Noun Project first and using Bing for everything else. End of explanation """
bspalding/research_public
advanced_sample_analyses/Tesla-and-Oil-(Short).ipynb
apache-2.0
# Import libraries from matplotlib import pyplot from pykalman import KalmanFilter import numpy import scipy import time import datetime # Initialize a Kalman Filter. # Using kf to filter does not change the values of kf, so we don't need to ever reinitialize it. kf = KalmanFilter(transition_matrices = [1], observation_matrices = [1], initial_state_mean = 0, initial_state_covariance = 1, observation_covariance=1, transition_covariance=.01) # helper functions # for converting dates to a plottable form def convert_date(mydate): # return time.mktime(datetime.datetime.strptime(mydate, "%Y-%m-%d").timetuple()) return datetime.datetime.strptime(mydate, "%Y-%m-%d") # for grabbing dates and prices for a relevant equity def get_data(equity_name,trading_start,trading_end='2015-07-20'): # using today as a default arg. stock_data = get_pricing(equity_name, start_date = trading_start, end_date = trading_end, fields = ['close_price'], frequency = 'daily') stock_data['date'] = stock_data.index # drop nans. For whatever reason, nans were causing the kf to return a nan array. stock_data = stock_data.dropna() # the dates are just those on which the prices were recorded dates = stock_data['date'] dates = [convert_date(str(x)[:10]) for x in dates] prices = stock_data['close_price'] return dates, prices # TSLA started trading on Jun-29-2010. dates_tsla, scores_tsla = get_data('TSLA','2010-06-29') # Apply Kalman filter to get a rolling average scores_tsla_means, _ = kf.filter(scores_tsla.values) """ Explanation: Tesla and Gasoline By John Loeber Notebook released under the Creative Commons Attribution 4.0 License. Introduction Is the stock price of Tesla Motors (TSLA) linked to the price of gasoline? Some people think that cheap gasoline incentivizes the purchase of gas-fuelled cars, lowering demand for Teslas, thus causing a drop in TSLA stock price. I try to find out whether that is true: I investigate the relationship between the price of TSLA and the price of UGA, an ETF tracking the price of gasoline. Conclusion The price of <strong>TSLA roughly follows the price of gasoline, with a lag of about 50 business days.</strong> However, statistical correlations show only very weak results, which is likely due to two reasons: 1. The price of TSLA is not only impacted by gas -- there are other factors: earnings reports, rumours, etc. They cause occasional (smaller) movements in TSLA that are not related to the price of gas. 2. The lag is not necessarily constant -- there's no reason why the offset should always be 50 business days. Sometimes TSLA may take longer to respond, and at other times it may respond more quickly. This makes it hard to fit the time-series to each other in a way that yields a strong correlation. Going Further Use the result, that TSLA roughly follows the price of gasoline with a lag of about 50 business days, to construct a trading strategy. It will be worthwhile to write an algorithm to attempt to trade on this pattern. To expand further upon this project: - Test against crude oil and energy ETFs to search for other signals in the data. - Query the Quantopian Fundamentals and use quarterly sales/revenue data to see how these details correspond to the price of gasoline. - Consider commodity prices from NYMEX or other potentially more informative datasets. Have questions? Post to the community or send us an email: feedback@quantopian.com. Investigation I'll use Kalman filters to obtain moving averages, both of TSLA and of the ETFs. I overlay these moving average plots and look for relationships between the two (using both the obtained moving averages and the raw data). End of explanation """ # Use a scatterplot instead of a line plot because a line plot would be far too noisy. pyplot.scatter(dates_tsla,scores_tsla,c='gray',label='TSLA Price') pyplot.plot(dates_tsla,scores_tsla_means, c='red', label='TSLA MA') pyplot.ylabel('TSLA Price') pyplot.xlabel('Date') pyplot.ylim([0,300]) pyplot.legend(loc=2) pyplot.show() """ Explanation: I'll plot the daily TSLA price and its Kalman-filtered moving average on it, simply to get a feel for the data. End of explanation """ # Get UGA data and apply the Kalman filter to get a moving average. dates_uga, scores_uga = get_data('UGA','2013-06-01') scores_uga_means, _ = kf.filter(scores_uga.values) # Get TSLA for June 2013 onwards, and apply the Kalman Filter. dates_tsla2, scores_tsla2 = get_data('TSLA','2013-06-01') scores_tsla_means2, _ = kf.filter(scores_tsla2.values) """ Explanation: This plot raises an important consideration: in 2012, Tesla debuted the Model S and delivered 2650 vehicles. It was only midway through 2013 that Tesla rose to prominence, having dramatically increased their production output. Thus, the period between 2010 and mid-2013 is likely misleading/irrelevant. In this investigation, I will concentrate on data from June 2013 onwards. UGA UGA is the ETF tracking the price of gasoline. End of explanation """ _, ax1 = pyplot.subplots() ax1.plot(dates_tsla2,scores_tsla_means2, c='red', label='TSLA MA') pyplot.xlabel('Date') pyplot.ylabel('TSLA Price MA') pyplot.legend(loc=2) # twinx allows us to use the same plot ax2 = ax1.twinx() ax2.plot(dates_uga, scores_uga_means, c='black', label='UGA Price MA') pyplot.ylabel('UGA Price MA') pyplot.legend(loc=3) pyplot.show() """ Explanation: We'll now plot the TSLA price (moving average) and the UGA price (moving average). End of explanation """ def find_offset(ts1,ts2,window): """ Finds the offset between two equal-length timeseries that maximizies correlation. Window is # of days by which we want to left- or right-shift. N.B. You'll have to adjust the function for negative correlations.""" l = len(ts1) if l!=len(ts2): raise Exception("Error! Timeseries lengths not equal!") max_i_spearman = -1000 max_spearman = -1000 spear_offsets = [] # we try all possible offsets from -window to +window. # we record the spearman correlation for each offset. for i in range(window,0,-1): series1 = ts1[i:] series2 = ts2[:l-i] # spearmanr is a correlation test spear = scipy.stats.spearmanr(series1,series2)[0] spear_offsets.append(spear) if spear > max_spearman: # update best correlation max_spearman = spear max_i_spearman = -i for i in range(0,window): series1 = ts1[:l-i] series2 = ts2[i:] spear = scipy.stats.spearmanr(series1,series2)[0] spear_offsets.append(spear) if spear > max_spearman: max_spearman = spear max_i_spearman = i print "Max Spearman:", max_spearman, " At offset: ", max_i_spearman pyplot.plot(range(-window,window),spear_offsets, c='green', label='Spearman Correlation') pyplot.xlabel('Offset Size (Number of Business Days)') pyplot.ylabel('Spearman Correlation') pyplot.legend(loc=3) pyplot.show() print "Kalman-Filtered Smoothed Data" find_offset(scores_tsla_means2,scores_uga_means,200) print "Raw Data" find_offset(scores_tsla2,scores_uga,150) """ Explanation: You can immediately see a strong, though perhaps lagged correspondence. If you line up the most prominent peaks and troughs in prices, you can see that the two time-series appear to correlate strongly, albeit with a lag of what looks like about two or three months. We'll use a function to find the lag that maximizes correlation. End of explanation """ # plotting formalities for 126-day offset d = 126 cseries1 = scores_tsla_means2[d:] cseries2 = scores_uga_means[:len(scores_tsla_means2)-d] r = range(len(cseries1)) _, ax1 = pyplot.subplots() ax1.plot(r, cseries1, c='red', label='TSLA MA') pyplot.xlabel('Number of Business Days Elapsed') pyplot.ylabel('TSLA Price MA') pyplot.legend(loc=2) ax2 = ax1.twinx() ax2.plot(r, cseries2, c='black', label='UGA Price MA') pyplot.ylabel('UGA Price MA') pyplot.legend(loc=4) pyplot.title("-126 Day Offset") pyplot.show() # plotting for 50-day offset d = 50 cseries1 = scores_tsla_means2[d:] cseries2 = scores_uga_means[:len(scores_tsla_means2)-d] r = range(len(cseries1)) _, ax1 = pyplot.subplots() ax1.plot(r, cseries1, c='red', label='TSLA MA') pyplot.xlabel('Number of Business Days Elapsed') pyplot.ylabel('TSLA Price MA') pyplot.legend(loc=2) ax2 = ax1.twinx() ax2.plot(r, cseries2, c='black', label='UGA Price MA') pyplot.ylabel('UGA Price MA') pyplot.legend(loc=4) pyplot.title("-50 Day Offset") pyplot.show() """ Explanation: These plots are not promising at all! I want to find a strong positive correlation between TSLA and UGA, but neither in the smoothed nor in the raw data is there a strong, positive correlation. However, I did find that negative offsets of 126 and 50 days are correlation-maximizing, so we'll take a look at the smoothed data with these offsets. End of explanation """ print scipy.stats.spearmanr(scores_tsla_means2[d:][250:],scores_uga_means[:len(scores_tsla_means2)-d][250:]) """ Explanation: It is my opinion that the 50-day offset is a better fit. Not only do the 50-day plots visually appear to correspond more strongly (we can line up all major movements), it is also more plausible that gas price leads Tesla by 50 business days, rather than by 120 business days. However, looking at the 50-day plot, it is nonetheless surprising that the Spearman correlation is so low: End of explanation """
keras-team/autokeras
docs/ipynb/text_regression.ipynb
apache-2.0
dataset = tf.keras.utils.get_file( fname="aclImdb.tar.gz", origin="http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz", extract=True, ) # set path to dataset IMDB_DATADIR = os.path.join(os.path.dirname(dataset), "aclImdb") classes = ["pos", "neg"] train_data = load_files( os.path.join(IMDB_DATADIR, "train"), shuffle=True, categories=classes ) test_data = load_files( os.path.join(IMDB_DATADIR, "test"), shuffle=False, categories=classes ) x_train = np.array(train_data.data) y_train = np.array(train_data.target) x_test = np.array(test_data.data) y_test = np.array(test_data.target) print(x_train.shape) # (25000,) print(y_train.shape) # (25000, 1) print(x_train[0][:50]) # <START> this film was just brilliant casting <UNK> """ Explanation: To make this tutorial easy to follow, we just treat IMDB dataset as a regression dataset. It means we will treat prediction targets of IMDB dataset, which are 0s and 1s as numerical values, so that they can be directly used as the regression targets. A Simple Example The first step is to prepare your data. Here we use the IMDB dataset as an example. End of explanation """ # Initialize the text regressor. reg = ak.TextRegressor(overwrite=True, max_trials=1) # It tries 10 different models. # Feed the text regressor with training data. reg.fit(x_train, y_train, epochs=2) # Predict with the best model. predicted_y = reg.predict(x_test) # Evaluate the best model with testing data. print(reg.evaluate(x_test, y_test)) """ Explanation: The second step is to run the TextRegressor. As a quick demo, we set epochs to 2. You can also leave the epochs unspecified for an adaptive number of epochs. End of explanation """ reg.fit( x_train, y_train, # Split the training data and use the last 15% as validation data. validation_split=0.15, ) """ Explanation: Validation Data By default, AutoKeras use the last 20% of training data as validation data. As shown in the example below, you can use validation_split to specify the percentage. End of explanation """ split = 5000 x_val = x_train[split:] y_val = y_train[split:] x_train = x_train[:split] y_train = y_train[:split] reg.fit( x_train, y_train, epochs=2, # Use your own validation set. validation_data=(x_val, y_val), ) """ Explanation: You can also use your own validation set instead of splitting it from the training data with validation_data. End of explanation """ input_node = ak.TextInput() output_node = ak.TextBlock(block_type="ngram")(input_node) output_node = ak.RegressionHead()(output_node) reg = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=1 ) reg.fit(x_train, y_train, epochs=2) """ Explanation: Customized Search Space For advanced users, you may customize your search space by using AutoModel instead of TextRegressor. You can configure the TextBlock for some high-level configurations, e.g., vectorizer for the type of text vectorization method to use. You can use 'sequence', which uses TextToInteSequence to convert the words to integers and use Embedding for embedding the integer sequences, or you can use 'ngram', which uses TextToNgramVector to vectorize the sentences. You can also do not specify these arguments, which would leave the different choices to be tuned automatically. See the following example for detail. End of explanation """ input_node = ak.TextInput() output_node = ak.TextToIntSequence()(input_node) output_node = ak.Embedding()(output_node) # Use separable Conv layers in Keras. output_node = ak.ConvBlock(separable=True)(output_node) output_node = ak.RegressionHead()(output_node) reg = ak.AutoModel( inputs=input_node, outputs=output_node, overwrite=True, max_trials=1 ) reg.fit(x_train, y_train, epochs=2) """ Explanation: The usage of AutoModel is similar to the functional API of Keras. Basically, you are building a graph, whose edges are blocks and the nodes are intermediate outputs of blocks. To add an edge from input_node to output_node with output_node = ak.[some_block]([block_args])(input_node). You can even also use more fine grained blocks to customize the search space even further. See the following example. End of explanation """ train_set = tf.data.Dataset.from_tensor_slices(((x_train,), (y_train,))).batch(32) test_set = tf.data.Dataset.from_tensor_slices(((x_test,), (y_test,))).batch(32) reg = ak.TextRegressor(overwrite=True, max_trials=2) # Feed the tensorflow Dataset to the regressor. reg.fit(train_set, epochs=2) # Predict with the best model. predicted_y = reg.predict(test_set) # Evaluate the best model with testing data. print(reg.evaluate(test_set)) """ Explanation: Data Format The AutoKeras TextRegressor is quite flexible for the data format. For the text, the input data should be one-dimensional For the regression targets, it should be a vector of numerical values. AutoKeras accepts numpy.ndarray. We also support using tf.data.Dataset format for the training data. End of explanation """
danielmcd/hacks
marketpatterns/TestNotebook.ipynb
gpl-3.0
import calendar import datetime import numpy import os.path import pickle from random import randrange, random, shuffle import sys import time import math import nupic from nupic.encoders import ScalarEncoder, MultiEncoder from nupic.bindings.algorithms import SpatialPooler as SP from nupic.research.TP10X2 import TP10X2 as TP """ Explanation: The Chicken Overlord End of explanation """ C = [1, 1, 1, 0, 0, 0, 0, 0, 0] B = [0, 0, 0, 1, 1, 1, 0, 0, 0] A = [0, 0, 0, 0, 0, 0, 1, 1, 1] n = 10 w = 3 #inputs = [[0] * (i*w) + [1] *w + [0] * ((n - i - 1) * w) for i in range (0, n)] enc = ScalarEncoder(w=5, minval=0, maxval=10, radius=1.25, periodic=True, name="encoder", forced=True) for d in range(0, 10): print str(enc.encode(d)) inputs = [enc.encode(i) for i in range(10)] """ Explanation: <img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This stuff imports stuff. End of explanation """ tp = TP(numberOfCols=40, cellsPerColumn=7.9, initialPerm=0.5, connectedPerm=0.5, minThreshold=10, newSynapseCount=10, permanenceInc=0.1, permanenceDec=0.01, activationThreshold=1, globalDecay=0, burnIn=1, checkSynapseConsistency=False, pamLength=7) """ Explanation: <img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This stuff is the stuff the Temporal Pooler thing is learning to recognize. End of explanation """ input_array = numpy.zeros(40, dtype="int32") tp.reset() for i, pattern in enumerate(inputs*1): input_array[:] = pattern tp.compute(input_array, enableLearn=True, computeInfOutput=True) tp.printStates() """ Explanation: <img src="http://www.designofsignage.com/application/symbol/hands/image/600x600/hand-point-up-2.jpg" width="40px" height="40px" align="left"/> This is the Temporal Pooler thing. End of explanation """
alepoydes/introduction-to-numerical-simulation
practice/Not so elementary elementary functions.ipynb
mit
y=np.linspace(-2,3,100) x=np.exp(y) plt.plot(x,y) plt.xlabel('$x$') plt.ylabel('$y=\ln x$') plt.show() """ Explanation: Вычисление элементарных функций Вычисление значения функции на данном аргументе является одной из важнейших задач численных методов. Несмотря на то, что вы уже огромное число раз вычисляли значения функций на практике, вам вряд ли приходилось самостоятельно реализовывать вычисление функций, не сводящихся к композиции элементарных. Действительно, калькуляторы, стандартные библиотеки, математические пакеты и т.п. позволяют вам легко и зачастую с произвольной точностью вычислять значение широко известных функций. Однако иногда вычисление элементраных функций приходится реализовывать самостоятельно, например, если вы пытаетесь добиться более высокой производительности, улучшить точность, эффективно распараллелить вычисления, используете среду/оборудование, для которого нет математических библиотек и т.п. Алгоритмы вычисления элементарных функций сами по себе поучительны, так как учат нас избегать типичных ошибок расчетов на компьютере, подсказывают, как реализовать вычисления неэлементарных функций, а также позволяют рассмотреть нам некоторые методы, которые полностью проявляют свою мощь в более сложных задачах. В этой лабораторной работе мы рассмотрим задачу вычисления натурального логарифма $y=\ln x$. Функция выбрана достаточно произвольно, подобных оразом можно вычислить и другие элементарные функции. Сразу стоит обратить внимание, что используемые методы достаточно универсальны, но не являются самыми быстрыми. Элементарные свойства. Редукция аргумента. По-определению, натуральным логарифмом называется функция, обратная к экспоненте, т.е. $y=\ln x$ тогда и только тогда, когда $x=e^y$. Поэтому если мы можем вычислять показательную функцию, то легко построить график логарифмической функции, нужно просто поменять переменные местами. End of explanation """ plt.semilogx(x,y) plt.xlabel('$x$') plt.ylabel('$y=\ln x$') plt.show() """ Explanation: Для графического представления данных часто используется логарифмическая шкала, на которой находищиеся на одном расстоянии точки отличаются в одно и то же число раз. График логарифма в логарифмической шкале по аргументу $x$ выглядит как прямая линия. End of explanation """ x=np.logspace(0,10,100) y=np.log(x) plt.semilogx(x,y) plt.semilogx(1/x,-y) plt.xlabel('$x$') plt.ylabel('$y=\ln x$') plt.show() """ Explanation: Лоагрифм преобразует умножение в сложение: $$\ln (xy)=\ln x+\ln y.$$ а возведение в степень в умножение $$\ln x^a=a\ln x.$$ Это свойство, например, может быть использовано для вычисления произвольных вещественных степеней: $$a^x=\exp(\ln a^x)=\exp(a\ln x).$$ Это свойство можно применить и для того, чтобы выразить значения логарифма в одних точках, через значения в других, избежав вычислений значений в неудобных точках. Например, воспользовавшись свойством $$\ln \frac1x=-\ln x,$$ можно вычислять значения логарифма на всей области определения, реализовав вычисление логарифма только на интервале $(0,1]$ или от $[1,\infty)$. Этот подход называется редукцией аргумента, и ипользуется при вычислении почти всех функций. End of explanation """ x0=np.logspace(-5,5,1000,dtype=np.double) epsilon=np.finfo(np.double).eps best_precision=(epsilon/2)*np.abs(1./np.log(x0)) plt.loglog(x0,best_precision, '-k') plt.loglog(x0,np.full(x0.shape, epsilon), '--r') plt.xlabel("$Аргумент$") plt.ylabel("$Относительная\,погрешность$") plt.legend(["$Минимальная\,погр.$","$Машинная\,погр.$"]) plt.show() """ Explanation: Задание 1. Выполните редукцию аргумента логарифма так, чтобы всегда получать значения из интервала $[1,1+\epsilon)$, где $\epsilon$ - маленькое положительное число. Каким свойством предпочтительнее воспользоваться $\ln x^2=2\ln x$ или $\ln \frac{x}{2}=\ln x-\ln 2$? Результат даже точного вычислении логарифма имеет погрешность равную произведению погрешности аргумента на число обусловленности. Число обусловленности можно найти по формуле: $$\kappa(x)=\frac{|x(\ln x)'|}{|ln x|}=\frac{|x/x|}{|\ln x|}=\frac{1}{|\ln x|}.$$ Так как погрешность аргумента всегда не привосходит, но может достигать половины машинной точности, то лучшая реализация вычисления логарфима будет иметь следующую точность: End of explanation """ def relative_error(x0,x): return np.abs(x0-x)/np.abs(x0) def log_teylor_series(x, N=5): a=x-1 a_k=a # x в степени k. Сначала k=1 y=a # Значене логарифма, пока для k=1. for k in range(2,N): # сумма по степеням a_k=-a_k*a # последовательно увеличиваем степень и учитываем множитель со знаком y=y+a_k/k return y x=np.logspace(-5,1,1001) y0=np.log(x) y=log_teylor_series(x) plt.loglog(x,relative_error(y0,y),'-k') plt.loglog(x0,best_precision,'--r') plt.xlabel('$x$') plt.ylabel('$(y-y_0)/y_0$') plt.legend(["$Достигнутая\;погр.$", "$Минимальная\;погр.$"],loc=5) plt.show() """ Explanation: Формально при $x=1$ число обусловленности равно бесконечности (так как значение функции равно $0$), однако этот пик очень узкий, так что почти всюду значения могут быть найдены с машинной точностью, кроме узкого Разложение в степенной ряд Из математического анализа нам известно, что для $|x|<1$ справедливо разложение логарифма в ряд: $$\ln (1+a)=\sum_{k=1}^\infty (-1)^{n+1}a^k/k=x-x^2/2+x^3/3+\ldots.$$ Так как правая часть содержит только арифметические операции, то возникает соблазн использовать частичную сумму этого ряда для приближенного вычисления логарифма. Первое препятствие на этом пути - это сходимость ряда только на малом интервале, т.е. таким способом могут быть получены только значения $\ln x$ для $x\in(0,2)$. Вторая сложность заключается в том, что частичная сумма $S_N$ из $N$ членов ряда $$S_N=\sum_{k=1}^N (-1)^{n+1}{a^k}/k$$ дает только часть суммы, а остаток ряда $$R_N=\sum_{k=N+1}^\infty (-1)^{n+1}{a^k}/k$$ быстро увеличивается, если значения $a$ увеличиваются по модулю. Вычислим численно относительную погрешность отбрасывания остатка ряда. End of explanation """ # Узлы итерполяции N=5 xn=1+1./(1+np.arange(N)) yn=np.log(xn) # Тестовые точки x=np.linspace(1+1e-10,2,1000) y=np.log(x) # Многочлен лагранжа import scipy.interpolate L=scipy.interpolate.lagrange(xn,yn) yl=L(x) plt.plot(x,y,'-k') plt.plot(xn,yn,'.b') plt.plot(x,yl,'-r') plt.xlabel("$x$") plt.ylabel("$y=\ln x$") plt.show() plt.semilogy(x,relative_error(y,yl)) plt.xlabel("$Аргумент$") plt.ylabel("$Относительная\;погрешность$") plt.show() """ Explanation: Формула Эйлера дает аккуратное приближение функции только рядом с точкой разложения (в даном случае $x=1$), что мы и наблюдаем в эксперименте. Наибольшую точность мы получили возле $x=1$, что противоречит нашей оценке через числа обусловленности. Однако нужно принимать во внимание, что мы сравнивали нашу реализацию со встроенной, которая не дает (и не может дать) абсолютно правильный ответ. Точность вычислений можно увеличить, добавляя слагаемые в частичную сумму. Сколько слагаемых нужно взять, чтобы достигнуть желаемой точности? Распространено заблуждение, что суммировать нужно до тех пор, пока последнее добавленное слагаемое не станет меньше желаемой точности. Вообще говоря это не так. Чтобы получить верную оценку погрешности отбрасывания остатка ряда, нужно оценить весь остаток ряда, а не только последнее слагаемое. Для оценки остатка ряда можно воспользоваться формулой Лагранжа для остаточного члена: $$R_N=\frac{a^{N+1}}{(N+1)!}\frac{d^{N+1}f(a\theta)}{da^{N+1}},$$ где как и выше $a=x-1$, а $\theta$ лежит на интервале $[0,1]$. Задание 2. Найдите количество слагаемых в частичной сумме, достаточное для получения значения логарифма с заданной точностью. Реализуйте вычисления логарифма через сумму с заданной точностью. Какую максимальную точность удается достичь? Аппроксимация многочленами При вычислении логарифма через частичную суммы мы по сути приближали логарифм многочленами. Многочлен Тейлора давал хорошее приближение функции и нескольких производных, но только в одной точке. Мы же сейчас интересуемся только значением функции, но хотели бы иметь хорошую точность приближения на целом интервале. Для достижения этой цели многочлены Тейлора подходят плохо, однако можно воспользоваться многочленами Лагранжа, Чебышева и т.п., или можно попытаться минимизировать непосредственно ошибку прилижения на отрезке, варьируя коэффициенты многочлена. В качестве примера мы рассмотрим построение интерполяционного многочлена Лагранжа. Этот многочлен будет точно совпадать с приближаемой функцией в $N+1$ узле, где $N$~-- степень многочлена, а между узлами мы надеямся, что погрешность не будет слишком силько расти. Зафиксируем несколько значений $x_n=1+1/(n+1)$, $n=0..N$, из интервала $[1,2]$ и вычислим в них точные значения логарифма в этих точках $y_n=\ln(x_n)$. Тогда интерполяционный многочлен имеет вид: $$L(x)=\sum_{n=0}^{N}\prod_{k\neq n} \frac{x-x_k}{x_n-x}.$$ End of explanation """ def log_newton(x, N=10): y=1 # начальное приближение for j in range(N): y=y-1+x/np.exp(y) return y x=np.logspace(-3,3,1000) y0=np.log(x) y=log_newton(x) plt.loglog(x,relative_error(y0,y),'-k') plt.xlabel("$Аргумент$") plt.ylabel("$Относительная\;погрешность$") plt.show() """ Explanation: Как мы видим, погрешность стремится к нулю в узлах интерполяции, между узлами ошибка не растет выше некоторой величины, т.е. с точки зрения вычисления функции этот приближение гораздо лучше. Задание 3. Как следует из графика ошибки, предложенный выбор узлов $x_n$ плох. Подумайте, как лучше расположить узлы интерполяции? Воспользуйтесь формулой приведения $$x=\frac{1+2u/3}{1-2u/3},$$ позволяющей преобразовать интервал $x\in[1/5,5]$ в интервал $u\in[-1,1]$. Будет ли разложение по степеням $u$ предпочтительнее разложения по степеням $a=x-1$? Составьте интерполяционный многочлен Лагранжа от переменной $u$ с узлами в нулях многочлена Чебышева: $$u_n=\cos\frac{\pi(n+1/2)}{N+1},\quad n=0..N.$$ Сравните точности аппроксимации с узлами в $x_n$ и в $u_n$. Задание A (повышенная сложность). Найдите многочлен данной степени $N$, дающий наименьшую погрешность приближения логарифма на интервале $[1/5,5]$. Задание B (повышенная сложность). Постройте разложение логарифма на интервале $[1/5,5]$ по многочленам Чебышева от переменной $u$ методом Ланцоша. Итерационный метод Для нахождения $y$, такого что $y=\ln x$, можно численно решить уравнение $x=e^y$, что может оказаться проще, чем считать логарифм напрямую. Для решения уравнения воспользуемся методом Ньютона. Перепишем уравнение в виде $F(y)=e^y-x=0$, т.е. будем искать нули функции $F$. Пусть у нас есть начальное приближение для $y=y_0$. Приблизим функцию $F$ рядом с $y_0$ с помощью касательной, т.е. $F(y)\approx F'(y_0)(y-y_0)+F(y_0)$. Если функция $F$ близка к линейной (что верно, если $y_0$ близко к нулю функции), то точки пересечения функции и касательной с осью абсцисс близки. Составим уравнение на ноль касательной: $$F'(y_0)(y-y_0)+F(y_0)=0,$$ следовательно следующим приближением выберем $$y=y_0-\frac{F(y_0)}{F'(y_0)}.$$ Итерации по методу Ньютона определены следующей рекуррентной формулой: $$y_{n+1}=y_n-\frac{F(y_n)}{F'(y_n)}.$$ Подставляя явный вид функции $F$, получаем $$y_{n+1}=y_n-\frac{e^{y_n}-x}{e^{y_n}}=y_n-1+xe^{-y_n}.$$ Точное значение логарифма есть предел последовательности $y_n$ при $n\to\infty$. Приближенное значение логарифма можно получить сделав несколько итераций. При выполнении ряда условий метод Ньютона имеет квадратичную скорость сходимости, т.е. $$|y_n-y^|<\alpha|y_{n-1}-y^|^2,$$ где $y^*=\lim_{n\to\infty} y_n$ - точное значение логарифма, и $\alpha\in(0,1]$ - некоторая константа. Неформально выражаясь, квадратичная сходимость означает удвоение числа значащих цифр на каждой итерации. End of explanation """ B=8 # число используемых для составления таблицы бит мантиссы table=np.log((np.arange(0,2**B, dtype=np.double)+0.5)/(2**B)) log2=np.log(2) def log_table(x): M,E=np.frexp(x) return log2*E+table[(M*2**B).astype(np.int)] x=np.logspace(-10,10,1000) y0=np.log(x) y=log_table(x) plt.loglog(x,relative_error(y0,y),'-k') plt.xlabel("$Аргумент$") plt.ylabel("$Относительная\;погрешность$") plt.show() """ Explanation: Задание 4. Начальное приближение в вышеприведенном алгоритме выбрано очень грубо, предложите лучшее приближение. Оцените число итераций, необходимое для получения лучшей возможной точности. Реализуйте метод Ньютона для найденного числа итераций. Удалось ли получить машиную точность? Почему? Почему при использовании 1 в качестве начального приближения итерации расходятся для $x$ заметно отличающихся от 1? Вычисление с помощью таблиц Число с плавающей запятой представляется в виде $M\cdot 2^E$, где $M$ - мантисса, а $E$ - экспонента. Согласно основному свойству логарифма $$\ln (M\cdot 2^E)=E\ln 2+\ln M,$$ где константу $\ln 2$ можно предварительно вычислить и сохранить, экспонента представляет собой данное нам целое число, единственно что нам остается вычислить - это логарифм мантиссы. Так как мантисса всегда лежит в интервале $(-1,1)$, а с учетом области определения логарима, в интервале $(0,1)$, то мы можем приближенно найти значение $\ln M$ как сохраненное в таблице значение логарифма в ближайшей к $M$ точке. Для составления таблицы удобно отбросить все биты мантиссы, кроме нескольких старших, перебрать все их возможные значения и вычислить логарифм этих значений. End of explanation """
Unidata/unidata-python-workshop
notebooks/MetPy_Advanced/QG Analysis.ipynb
mit
from datetime import datetime import cartopy.crs as ccrs import cartopy.feature as cfeature import numpy as np from scipy.ndimage import gaussian_filter from siphon.catalog import TDSCatalog from siphon.ncss import NCSS import matplotlib.pyplot as plt import metpy.calc as mpcalc import metpy.constants as mpconstants from metpy.units import units import xarray as xr """ Explanation: <a name="top"></a> <div style="width:1000 px"> <div style="float:right; width:98 px; height:98px;"> <img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;"> </div> <h1>Advanced MetPy: Quasi-Geostrophic Analysis</h1> <div style="clear:both"></div> </div> <hr style="height:2px;"> Overview: Teaching: 30 minutes Exercises: 45 minutes Objectives <a href="#download">Download NARR output from TDS</a> <a href="#interpolation">Calculate QG-Omega Forcing Terms</a> <a href="#ascent">Create a four-panel plot of QG Forcings</a> This is a tutorial demonstrates common analyses for Synoptic Meteorology courses with use of Unidata tools, specifically MetPy and Siphon. In this tutorial we will cover accessing, calculating, and plotting model output. Let's investigate The Storm of the Century, although it would easy to change which case you wanted (please feel free to do so). Reanalysis Output: NARR 00 UTC 13 March 1993 Data from Reanalysis on pressure surfaces: Geopotential Heights Temperature u-wind component v-wind component Calculations: Laplacian of Temperature Advection Differential Vorticity Advection Wind Speed End of explanation """ # Case Study Date year = 1993 month = 3 day = 13 hour = 0 dt = datetime(year, month, day, hour) """ Explanation: <a name="download"></a> Downloading NARR Output Lets investigate what specific NARR output is available to work with from NCEI. https://www.ncdc.noaa.gov/data-access/model-data/model-datasets/north-american-regional-reanalysis-narr We specifically want to look for data that has "TDS" data access, since that is short for a THREDDS server data access point. There are a total of four different GFS datasets that we could potentially use. Choosing our data source Let's go ahead and use the NARR Analysis data to investigate the past case we identified (The Storm of the Century). https://www.ncei.noaa.gov/thredds/catalog/narr-a-files/199303/19930313/catalog.html?dataset=narr-a-files/199303/19930313/narr-a_221_19930313_0000_000.grb And we will use a python package called Siphon to read this data through the NetCDFSubset (NetCDFServer) link. https://www.ncei.noaa.gov/thredds/ncss/grid/narr-a-files/199303/19930313/narr-a_221_19930313_0000_000.grb/dataset.html First we can set out date using the datetime module End of explanation """ # Read NARR Data from THREDDS server base_url = 'https://www.ncei.noaa.gov/thredds/catalog/narr-a-files/' # Programmatically generate the URL to the day of data we want cat = TDSCatalog(f'{base_url}{dt:%Y%m}/{dt:%Y%m%d}/catalog.xml') # Have Siphon find the appropriate dataset ds = cat.datasets.filter_time_nearest(dt) # Download data using the NetCDF Subset Service ncss = ds.subset() query = ncss.query().lonlat_box(north=60, south=18, east=300, west=225) query.time(dt).variables('Geopotential_height_isobaric', 'Temperature_isobaric', 'u-component_of_wind_isobaric', 'v-component_of_wind_isobaric').add_lonlat().accept('netcdf') data = ncss.get_data(query) # Open data with xarray, and parse it with MetPy ds = xr.open_dataset(xr.backends.NetCDF4DataStore(data)).metpy.parse_cf() ds # Back up in case of bad internet connection. # Uncomment the following line to read local netCDF file of NARR data # ds = xr.open_dataset('../../data/NARR_19930313_0000.nc').metpy.parse_cf() """ Explanation: Next, we set up access to request subsets of data from the model. This uses the NetCDF Subset Service (NCSS) to make requests from the GRIB collection and get results in netCDF format. End of explanation """ # This is the time we're using vtime = ds.Temperature_isobaric.metpy.time[0] # Grab lat/lon values from file as unit arrays lats = ds.lat.metpy.unit_array lons = ds.lon.metpy.unit_array # Calculate distance between grid points # will need for computations later dx, dy = mpcalc.lat_lon_grid_deltas(lons, lats) # Grabbing data for specific variable contained in file (as a unit array) # 700 hPa Geopotential Heights hght_700 = ds.Geopotential_height_isobaric.metpy.sel(vertical=700 * units.hPa, time=vtime) # Equivalent form needed if there is a dash in name of variable # (e.g., 'u-component_of_wind_isobaric') # hght_700 = ds['Geopotential_height_isobaric'].metpy.sel(vertical=700 * units.hPa, time=vtime) # 700 hPa Temperature tmpk_700 = ds.Temperature_isobaric.metpy.sel(vertical=700 * units.hPa, time=vtime) # 700 hPa u-component_of_wind uwnd_700 = ds['u-component_of_wind_isobaric'].metpy.sel(vertical=700 * units.hPa, time=vtime) # 700 hPa v-component_of_wind vwnd_700 = ds['v-component_of_wind_isobaric'].metpy.sel(vertical=700 * units.hPa, time=vtime) """ Explanation: Subset Pressure Levels Using xarray gives great funtionality for selecting pieces of your dataset to use within your script/program. MetPy also includes helpers for unit- and coordinate-aware selection and getting unit arrays from xarray DataArrays. End of explanation """ # 500 hPa Geopotential Height # 500 hPa u-component_of_wind # 500 hPa v-component_of_wind # 900 hPa u-component_of_wind # 900 hPa v-component_of_wind """ Explanation: Exercise Write the code to access the remaining necessary pieces of data from our file to calculate the QG Omega forcing terms valid at 700 hPa. Data variables desired: * hght_500: 500-hPa Geopotential_height_isobaric * uwnd_500: 500-hPa u-component_of_wind_isobaric * vwnd_500: 500-hPa v-component_of_wind_isobaric * uwnd_900: 900-hPa u-component_of_wind_isobaric * vwnd_900: 900-hPa v-component_of_wind_isobaric End of explanation """ # %load solutions/QG_data.py """ Explanation: Solution End of explanation """ # Set constant values that will be needed in computations # Set default static stability value sigma = 2.0e-6 * units('m^2 Pa^-2 s^-2') # Set f-plane at typical synoptic f0 value f0 = 1e-4 * units('s^-1') # Use dry gas constant from MetPy constants Rd = mpconstants.Rd # Smooth Heights # For calculation purposes we want to smooth our variables # a little to get to the "synoptic values" from higher # resolution datasets # Number of repetitions of smoothing function n_reps = 50 # Apply the 9-point smoother hght_700s = mpcalc.smooth_n_point(hght_700, 9, n_reps) hght_500s = mpcalc.smooth_n_point(hght_500, 9, n_reps) tmpk_700s = mpcalc.smooth_n_point(tmpk_700, 9, n_reps) tmpc_700s = tmpk_700s.to('degC') uwnd_700s = mpcalc.smooth_n_point(uwnd_700, 9, n_reps) vwnd_700s = mpcalc.smooth_n_point(vwnd_700, 9, n_reps) uwnd_500s = mpcalc.smooth_n_point(uwnd_500, 9, n_reps) vwnd_500s = mpcalc.smooth_n_point(vwnd_500, 9, n_reps) uwnd_900s = mpcalc.smooth_n_point(uwnd_900, 9, n_reps) vwnd_900s = mpcalc.smooth_n_point(vwnd_900, 9, n_reps) """ Explanation: QG Omega Forcing Terms Here is the QG Omega equation from Bluesetein (1992; Eq. 5.6.11) with the two primary forcing terms on the right hand side of this equation. $$\left(\nabla_p ^2 + \frac{f^2}{\sigma}\frac{\partial ^2}{\partial p^2}\right)\omega = \frac{f_o}{\sigma}\frac{\partial}{\partial p}\left[\vec{V_g} \cdot \nabla_p \left(\zeta_g + f \right)\right] + \frac{R}{\sigma p} \nabla_p ^2 \left[\vec{V_g} \cdot \nabla_p T \right]$$ We want to write code that will calculate the differential vorticity advection term (the first term on the r.h.s.) and the laplacian of the temperature advection. We will compute these terms so that they are valid at 700 hPa. Need to set constants for static stability, f0, and Rd. End of explanation """ # Absolute Vorticity Calculation avor_900 = mpcalc.absolute_vorticity(uwnd_900s, vwnd_900s, dx, dy, lats) avor_500 = mpcalc.absolute_vorticity(uwnd_500s, vwnd_500s, dx, dy, lats) # Advection of Absolute Vorticity vortadv_900 = mpcalc.advection(avor_900, (uwnd_900s, vwnd_900s), (dx, dy)).to_base_units() vortadv_500 = mpcalc.advection(avor_500, (uwnd_500s, vwnd_500s), (dx, dy)).to_base_units() # Differential Vorticity Advection between two levels diff_avor = ((vortadv_900 - vortadv_500)/(400 * units.hPa)).to_base_units() # Calculation of final differential vorticity advection term term_A = (-f0 / sigma * diff_avor).to_base_units() print(term_A.units) """ Explanation: Compute Term A - Differential Vorticity Advection Need to compute: 1. absolute vorticity at two levels (e.g., 500 and 900 hPa) 2. absolute vorticity advection at same two levels 3. centered finite-difference between two levels (e.g., valid at 700 hPa) 4. apply constants to calculate value of full term End of explanation """ # Temperature Advection # Laplacian of Temperature Advection # Calculation of final Laplacian of Temperature Advection term """ Explanation: Exercise Compute Term B - Laplacian of Temperature Advection Need to compute: 1. Temperature advection at 700 hPa (tadv_700) 2. Laplacian of Temp Adv. at 700 hPa (lap_tadv_700) 3. final term B with appropriate constants (term_B) For information on how to calculate a Laplacian using MetPy, see the documentation on this function. End of explanation """ # %load solutions/term_B_calc.py """ Explanation: Solution End of explanation """ # Set some contour intervals for various parameters # CINT 500 hPa Heights clev_hght_500 = np.arange(0, 7000, 60) # CINT 700 hPa Heights clev_hght_700 = np.arange(0, 7000, 30) # CINT 700 hPa Temps clev_tmpc_700 = np.arange(-40, 40, 5) # CINT Omega terms clev_omega = np.arange(-20, 21, 2) # Set some projections for our data (Plate Carree) # and output maps (Lambert Conformal) # Data projection; NARR Data is Earth Relative dataproj = ccrs.PlateCarree() # Plot projection # The look you want for the view, LambertConformal for mid-latitude view plotproj = ccrs.LambertConformal(central_longitude=-100., central_latitude=40., standard_parallels=[30, 60]) """ Explanation: Four Panel Plot Upper-left Panel: 700-hPa Geopotential Heights, Temperature, and Winds Upper-right Panel: 500-hPa Geopotential Heights, Absolute Vorticity, and Winds Lower-left Panel: Term B (Laplacian of Temperature Advection) Lower-right Panel: Term A (Laplacian of differential Vorticity Advection) End of explanation """ # Set figure size fig=plt.figure(1, figsize=(24.5,17.)) # Format the valid time vtime_str = str(vtime.dt.strftime('%Y-%m-%d %H%MZ').values) # Upper-Left Panel ax=plt.subplot(221, projection=plotproj) ax.set_extent([-125., -73, 25., 50.],ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE, linewidth=0.5) ax.add_feature(cfeature.STATES, linewidth=0.5) # Contour #1 cs = ax.contour(lons, lats, hght_700, clev_hght_700,colors='k', linewidths=1.5, linestyles='solid', transform=dataproj) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=3, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour #2 cs2 = ax.contour(lons, lats, tmpc_700s, clev_tmpc_700, colors='grey', linewidths=1.0, linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=3, fmt='%d', rightside_up=True, use_clabeltext=True) # Colorfill cf = ax.contourf(lons, lats, tadv_700*10**4, np.arange(-10,10.1,0.5), cmap=plt.cm.bwr, extend='both', transform=dataproj) plt.colorbar(cf, orientation='horizontal', pad=0.0, aspect=50, extendrect=True) # Vector ax.barbs(lons.m, lats.m, uwnd_700s.to('kts').m, vwnd_700s.to('kts').m, regrid_shape=15, transform=dataproj) # Titles plt.title('700-hPa Geopotential Heights (m), Temperature (C),\n' 'Winds (kts), and Temp Adv. ($*10^4$ C/s)',loc='left') plt.title('VALID: ' + vtime_str, loc='right') # Upper-Right Panel ax=plt.subplot(222, projection=plotproj) ax.set_extent([-125., -73, 25., 50.],ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE, linewidth=0.5) ax.add_feature(cfeature.STATES, linewidth=0.5) # Contour #1 clev500 = np.arange(0,7000,60) cs = ax.contour(lons, lats, hght_500, clev500, colors='k', linewidths=1.5, linestyles='solid', transform=dataproj) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=3, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour #2 cs2 = ax.contour(lons, lats, avor_500*10**5, np.arange(-40, 50, 3),colors='grey', linewidths=1.0, linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=3, fmt='%d', rightside_up=True, use_clabeltext=True) # Colorfill cf = ax.contourf(lons, lats, vortadv_500*10**8, np.arange(-2, 2.2, 0.2), cmap=plt.cm.BrBG, extend='both', transform=dataproj) plt.colorbar(cf, orientation='horizontal', pad=0.0, aspect=50, extendrect=True) # Vector ax.barbs(lons.m, lats.m, uwnd_500s.to('kts').m, vwnd_500s.to('kts').m, regrid_shape=15, transform=dataproj) # Titles plt.title('500-hPa Geopotential Heights (m), Winds (kt), and\n' 'Absolute Vorticity Advection ($*10^{8}$ 1/s^2)',loc='left') plt.title('VALID: ' + vtime_str, loc='right') # Lower-Left Panel ax=plt.subplot(223, projection=plotproj) ax.set_extent([-125., -73, 25., 50.],ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE, linewidth=0.5) ax.add_feature(cfeature.STATES, linewidth=0.5) # Contour #1 cs = ax.contour(lons, lats, hght_700s, clev_hght_700, colors='k', linewidths=1.5, linestyles='solid', transform=dataproj) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=3, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour #2 cs2 = ax.contour(lons, lats, tmpc_700s, clev_tmpc_700, colors='grey', linewidths=1.0, transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=3, fmt='%d', rightside_up=True, use_clabeltext=True) # Colorfill cf = ax.contourf(lons, lats, term_B*10**12, clev_omega, cmap=plt.cm.RdYlBu_r, extend='both', transform=dataproj) plt.colorbar(cf, orientation='horizontal', pad=0.0, aspect=50, extendrect=True) # Vector ax.barbs(lons.m, lats.m, uwnd_700s.to('kts').m, vwnd_700s.to('kts').m, regrid_shape=15, transform=dataproj) # Titles plt.title('700-hPa Geopotential Heights (m), Winds (kt), and\n' 'Term B QG Omega ($*10^{12}$ kg m$^{-3}$ s$^{-3}$)',loc='left') plt.title('VALID: ' + vtime_str, loc='right') # # Lower-Right Panel ax=plt.subplot(224, projection=plotproj) ax.set_extent([-125., -73, 25., 50.],ccrs.PlateCarree()) ax.add_feature(cfeature.COASTLINE, linewidth=0.5) ax.add_feature(cfeature.STATES, linewidth=0.5) # Contour #1 cs = ax.contour(lons, lats, hght_500s, clev500, colors='k', linewidths=1.5, linestyles='solid', transform=dataproj) plt.clabel(cs, fontsize=10, inline=1, inline_spacing=3, fmt='%i', rightside_up=True, use_clabeltext=True) # Contour #2 cs2 = ax.contour(lons, lats, avor_500*10**5, np.arange(-40, 50, 3), colors='grey', linewidths=1.0, linestyles='dotted', transform=dataproj) plt.clabel(cs2, fontsize=10, inline=1, inline_spacing=3, fmt='%d', rightside_up=True, use_clabeltext=True) # Colorfill cf = ax.contourf(lons, lats, term_A*10**12, clev_omega, cmap=plt.cm.RdYlBu_r, extend='both', transform=dataproj) plt.colorbar(cf, orientation='horizontal', pad=0.0, aspect=50, extendrect=True) # Vector ax.barbs(lons.m, lats.m, uwnd_500s.to('kt').m, vwnd_500s.to('kt').m, regrid_shape=15, transform=dataproj) # Titles plt.title('500-hPa Geopotential Heights (m), Winds (kt), and\n' 'Term A QG Omega ($*10^{12}$ kg m$^{-3}$ s$^{-3}$)',loc='left') plt.title('VALID: ' + vtime_str, loc='right') plt.show() """ Explanation: Start 4-panel Figure End of explanation """ # %load solutions/qg_omega_total_fig.py """ Explanation: Exercise Plot the combined QG Omega forcing terms (term_A + term_B) in a single panel BONUS: Compute a difference map of Term A and Term B and plot Solution End of explanation """
fccoelho/Curso_Blockchain
assignments/Edwards-curve signature/Lisk.ipynb
lgpl-3.0
from hashlib import sha256 import json import ed25519 """ Explanation: <img src="https://cdn-images-1.medium.com/max/1200/1*cCHDhDD093-nE5lFTRGMDA.png" width="100px" align="left"> Understanding Lisk's Transactions Signing Scheme Flávio Codeço Coelho End of explanation """ passphrase = b"witch collapse practice feed shame open despair creek road again ice least" H = sha256(passphrase) H.hexdigest() H.digest() """ Explanation: EdDSA EdDSA is a variant of Schnorr signatures. Lisk uses ed25519 to sign off transactions. EdDSA is based on Edwards elliptic curves over a finite field: $$E(\mathbb{F}_q)$$ where q is a large prime number, $$q=2^{255}-19$$ Creating a key pair Based on Lisk documentation about key pairs, we start from a BIP-39 passphrase: End of explanation """ sk = ed25519.SigningKey(H.digest()) sk.to_bytes() """ Explanation: First the private key: End of explanation """ vk = sk.get_verifying_key() vk.to_bytes() """ Explanation: then the public: End of explanation """ tx = { "type": 0, "amount": 128, "senderPublicKey": "Public key of the sender", "timestamp": "<Timestamp>", "recipientId": "<Id of the recipient>", "signature": "<Signature of the data block>", "id": "<txid>", "fee": 10000000, "senderId": "<Id of the sender>", } txJSON = json.dumps(tx) txJSON """ Explanation: Signing a transaction Let $tx$ be a fund transfer transaction (type 0 in lisk): End of explanation """ Htx = sha256(txJSON.encode('ascii')) Htx.digest() """ Explanation: Let $H_{tx}$ be the SHA256 hash of the transaction block. End of explanation """ sig = sk.sign(Htx.digest(), encoding='hex') sig """ Explanation: Lisk then signs $H_{tx}$ using the sender keys: End of explanation """ tx['signature'] = sig.decode('ascii') tx2JSON = json.dumps(tx) tx """ Explanation: Adding the signature to the transaction The signature is then added to the datablock. Ed25519 signatures are not malleable, meaning that for the same private key and message (Tx), there is only one valid signature. End of explanation """ Itx = sha256(tx2JSON.encode('ascii')) sig2 = sk.sign(Itx.digest(), encoding='hex') sig2 """ Explanation: Second signature If a second signature is enabled for the sender's account, the transaction can receive a second signature. Let $I_{tx}$ be the SHA256 hash of the transaction block appended with the first signature. Again we will sign $I_{tx}$ instead of the transaction block. End of explanation """ vk.verify(sig2,Itx.digest(),encoding='hex') """ Explanation: Verifying End of explanation """
hpparvi/PyTransit
notebooks/contamination/example_1a.ipynb
gpl-2.0
%pylab inline import sys from corner import corner sys.path.append('.') from src.mocklc import MockLC, SimulationSetup from src.blendlpf import MockLPF import src.plotting as pl """ Explanation: Contamination example 1a No contamination and uninformative priors on orbital parameters Hannu Parviainen<br> Instituto de Astrofísica de Canarias Last modified: 15.7.2019 Here we use the pytransit.contamination module to estimate the true planet to star radius ratio robustly using multicolour photometry in the presence of possible flux contamination from an unresolved source in the photometry aperture, as detailed in Parviainen et al. 2019 (submitted). This can be used in the validation of transiting planet candidates, where, e.g., blended eclipsing binaries are a significant source of false positives. Light curves: We don't use real data here, but create simulated multicolour photometry lightcurves using the MockLC class found in src.mocklc. The code is the same that was used for the simulations in Parviainen et al. (2019). Log posterior function: The log posterior function is defined by MockLPF class found in src.blendlpf.MockLPF. The class inherits pytransit.lpf.PhysContLPF and overrides the _init_instrument method to define the instrument and the contamination model (amongst other things to make running a variety of simulations smooth). Parametrisation: As discussed in the paper, the contamination is parametrised by the apparent area ratio ($k_\mathrm{True}^2$), true area ratio ($k_\mathrm{App}^2$), and the effective temperatures of the host and contaminant stars. The apparent area ratio defines how deep the transit is in a single single passband and can be wavelength dependent (if the host and contaminant are of different spectral type), while the true area ratio stands for the unblended true geometric planet-star area ratio. The true radius ratio ($k_\mathrm{True}$) is the main quantity of interest in transiting planet candidate validation), since it together with a stellar radius estimate gives the true absolute planetary radius. End of explanation """ lc = MockLC(SimulationSetup('M', 0.1, 0.0, 0.0, 'short_transit', cteff=5500)) lc.create(wnsigma=[0.001, 0.001, 0.001, 0.001], rnsigma=0.00001, rntscale=0.5, nights=1); lc.plot(); """ Explanation: Create a mock light curve End of explanation """ lpf = MockLPF('Example_1', lc) lpf.print_parameters(columns=2) """ Explanation: Initialize the log posterior function End of explanation """ lpf.optimize_global(1000) lpf.plot_light_curves() """ Explanation: Optimize End of explanation """ lpf.sample_mcmc(5000, reset=True, repeats=2) """ Explanation: Estimate the posterior The contamination parameter space is a bit difficult to sample (especially if the signal to noise ratio is low), so the sampling should be continued at least for 10000 iterations. End of explanation """ df = lpf.posterior_samples() pl.joint_radius_ratio_plot(df, fw=13, clim=(0.099, 0.12), htelim=(3570, 3630), ctelim=(2400,3800), blim=(0, 0.5), rlim=(3.8, 5.2)); pl.joint_contamination_plot(df, fw=13, clim=(0, 0.4), htelim=(3570, 3630), ctelim=(2400,3800), blim=(0, 0.5), rlim=(3.8, 5.2)); """ Explanation: Analysis We plot the main results below. It is clear that a single good-quality four-colour light curve still allows for contamination from a source of similar spectral type as the host star. However, in this example, the maximum allowed level of contamination is not sufficient to take the transiting object out of the planetary regime. Also, the joint posterior plots clearly show that any significant contamination must come from a source of a similar spectral type as the host. Combining this information with prior knowledge about the probability of having such a system without colour variations can be used in probabilistic planet candidate validation. Plot the basic joint posterior End of explanation """ pl.marginal_radius_ratio_plot(df, bins=60, klim=(0.097, 0.12), figsize=(7,5)); """ Explanation: Plot the apparent and true radius ratio posteriors End of explanation """ corner(df.iloc[:,2:-3]); """ Explanation: Make a corner plot to have a good overview to the posterior space End of explanation """
buds-lab/the-building-data-genome-project
notebooks/00_Meta Data Exploration.ipynb
mit
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import os %matplotlib inline repos_path = "/Users/nus/temporal-features-for-nonres-buildings-library/" meta = pd.read_csv(os.path.join(repos_path,"data/raw/meta_open_withclassificationobjectives.csv"), index_col='uid', parse_dates=["datastart","dataend"], dayfirst=True) meta.info() sns.set_style("whitegrid") """ Explanation: Meta Data Exploration Clayton Miller -- miller.clayton@gmail.com This notebook gives an overview of the buildings in this study End of explanation """ meta.primaryspaceusage.value_counts() meta.usagecategory.value_counts() meta.info()#[['industry','timezone']].head() meta.head() df = pd.pivot_table(meta.reset_index(), index='timezone', columns='subindustry', values='uid', aggfunc='count') df # crashes = sns.load_dataset("car_crashes").sort_values("total", ascending=False) location = pd.DataFrame(meta.timezone.value_counts()).reset_index() location def createbarchart(df, column, ylabel, color, filelabel): # Initialize the matplotlib figure #sns.set_context('poster', font_scale=1) location = pd.DataFrame(df[column].value_counts()).reset_index() f, ax = plt.subplots(figsize=(9, 5)) sns.set_color_codes("pastel") sns.barplot(x=column, y="index", data=location[:15], color=color) # Add a legend and informative axis label ax.legend(ncol=2, loc="lower right", frameon=True) ax.set(ylabel=ylabel, xlabel="Number of Buildings") sns.despine(left=True, bottom=True) plt.subplots_adjust(left=0.3) plt.tight_layout() plt.savefig(os.path.join(repos_path,"reports/figures/metadataoverview/"+filelabel+".png")) location[:15] meta["string_starttime"] = meta.datastart.apply(lambda x: str(x.date())) sns.set_context("paper", font_scale=2) createbarchart(meta, "string_starttime", "Data Starting Time", "m","starttimesbar") #sns.set_style("white") createbarchart(meta, "timezone", "Time Zones", "b","timezonesbar") createbarchart(meta, "industry", "Industry", "r", "bar_industry") createbarchart(meta, "subindustry", "Sub-Industry", "g","bar_subindustry") createbarchart(meta, "primaryspaceusage", "Primary Use", "y", "bar_primaryspaceuse") """ Explanation: Create Bar Charts Use: http://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html End of explanation """ import numpy as np # Simple data to display in various forms x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) # row and column sharing f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row') ax1.plot(x, y) ax1.set_title('Sharing x per column, y per row') ax2.scatter(x, y) ax3.scatter(x, 2 * y ** 2 - 1, color='r') ax4.plot(x, 2 * y ** 2 - 1, color='r') sns.set_color_codes("pastel") sns.set_context(font_scale=1) import matplotlib.gridspec as gridspec plt.figure(figsize=(18,10)) gs = gridspec.GridSpec(2, 8) #f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2, figsize=(20, 9))# # ax = plt.subplot2grid((2,2),(0, 0)) location = pd.DataFrame(meta["timezone"].value_counts()).reset_index() ax1 = plt.subplot(gs[0,0:4]) ax1 = sns.barplot(x="timezone", y="index", data=location[:15], color="b") ax1.legend(ncol=2, loc="lower right", frameon=True) ax1.set(ylabel="Time Zones", xlabel="Number of Buildings") location = pd.DataFrame(meta["industry"].value_counts()).reset_index() ax2 = plt.subplot(gs[0,4:]) ax2 = sns.barplot(x="industry", y="index", data=location[:15], color="g") ax2.legend(ncol=2, loc="lower right", frameon=True) ax2.set(ylabel="Industry", xlabel="Number of Buildings") location = pd.DataFrame(meta["subindustry"].value_counts()).reset_index() ax3 = plt.subplot(gs[1,0:4]) ax3 = sns.barplot(x="subindustry", y="index", data=location[:15], color="r") ax3.legend(ncol=2, loc="lower right", frameon=True) ax3.set(ylabel="Sub-Industry", xlabel="Number of Buildings") location = pd.DataFrame(meta["primaryspaceusage"].value_counts()).reset_index() ax4 = plt.subplot(gs[1,4:]) ax4 = sns.barplot(x="primaryspaceusage", y="index", data=location[:15], color="y") ax4.legend(ncol=2, loc="lower right", frameon=True) ax4.set(ylabel="Primary Use", xlabel="Number of Buildings") sns.despine(left=True, bottom=True) plt.subplots_adjust(left=0.3) plt.tight_layout() plt.savefig(os.path.join(repos_path,"reports/figures/metadataoverview/allbars.pdf")) """ Explanation: Create 4 bar charts in a set of panels End of explanation """
magenta/magenta-demos
jupyter-notebooks/NSynth.ipynb
apache-2.0
import os import numpy as np import matplotlib.pyplot as plt from magenta.models.nsynth import utils from magenta.models.nsynth.wavenet import fastgen from IPython.display import Audio %matplotlib inline %config InlineBackend.figure_format = 'jpg' """ Explanation: Exploring Neural Audio Synthesis with NSynth Parag Mital There is a lot to explore with NSynth. This notebook explores just a taste of what's possible including how to encode and decode, timestretch, and interpolate sounds. Also check out the blog post for more examples including two compositions created with Ableton Live. If you are interested in learning more, checkout my online course on Kadenze where we talk about Magenta and NSynth in more depth. Part 1: Encoding and Decoding We'll walkthrough using the source code to encode and decode some audio. This is the most basic thing we can do with NSynth, and it will take at least about 6 minutes per 1 second of audio to perform on a GPU, though this will get faster! I'll first show you how to encode some audio. This is basically saying, here is some audio, now put it into the trained model. It's like the encoding of an MP3 file. It takes some raw audio, and represents it using some really reduced down representation of the raw audio. NSynth works similarly, but we can actually mess with the encoding to do some awesome stuff. You can for instance, mix it with other encodings, or slow it down, or speed it up. You can potentially even remove parts of it, mix many different encodings together, and hopefully just explore ideas yet to be thought of. After you've created your encoding, you have to just generate, or decode it, just like what an audio player does to an MP3 file. First, to install Magenta, follow their setup guide here: https://github.com/tensorflow/magenta#installation - then import some packages: End of explanation """ # from https://www.freesound.org/people/MustardPlug/sounds/395058/ fname = '395058__mustardplug__breakbeat-hiphop-a4-4bar-96bpm.wav' sr = 16000 audio = utils.load_audio(fname, sample_length=40000, sr=sr) sample_length = audio.shape[0] print('{} samples, {} seconds'.format(sample_length, sample_length / float(sr))) """ Explanation: Now we'll load up a sound I downloaded from freesound.org. The utils.load_audio method will resample this to the required sample rate of 16000. I'll load in 40000 samples of this beat which should end up being a pretty good loop: End of explanation """ %time encoding = fastgen.encode(audio, 'model.ckpt-200000', sample_length) """ Explanation: Encoding We'll now encode some audio using the pre-trained NSynth model (download from: http://download.magenta.tensorflow.org/models/nsynth/wavenet-ckpt.tar). This is pretty fast, and takes about 3 seconds per 1 second of audio on my NVidia 1080 GPU. This will give us a 125 x 16 dimension encoding for every 4 seconds of audio which we can then decode, or resynthesize. We'll try a few things, including just leaving it alone and reconstructing it as is. But then we'll also try some fun transformations of the encoding and see what's possible from there. ```help(fastgen.encode) Help on function encode in module magenta.models.nsynth.wavenet.fastgen: encode(wav_data, checkpoint_path, sample_length=64000) Generate an array of embeddings from an array of audio. Args: wav_data: Numpy array [batch_size, sample_length] checkpoint_path: Location of the pretrained model. sample_length: The total length of the final wave file, padded with 0s. Returns: encoding: a [mb, 125, 16] encoding (for 64000 sample audio file). ``` End of explanation """ print(encoding.shape) """ Explanation: This returns a 3-dimensional tensor representing the encoding of the audio. The first dimension of the encoding represents the batch dimension. We could have passed in many audio files at once and the process would be much faster. For now we've just passed in one audio file. End of explanation """ np.save(fname + '.npy', encoding) """ Explanation: We'll also save the encoding so that we can use it again later: End of explanation """ fig, axs = plt.subplots(2, 1, figsize=(10, 5)) axs[0].plot(audio); axs[0].set_title('Audio Signal') axs[1].plot(encoding[0]); axs[1].set_title('NSynth Encoding') """ Explanation: Let's take a look at the encoding of this audio file. Think of these as 16 channels of sounds all mixed together (though with a lot of caveats): End of explanation """ %time fastgen.synthesize(encoding, save_paths=['gen_' + fname], samples_per_save=sample_length) """ Explanation: You should be able to pretty clearly see a sort of beat like pattern in both the signal and the encoding. Decoding Now we can decode the encodings as is. This is the process that takes awhile, though it used to be so long that you wouldn't even dare trying it. There is still plenty of room for improvement and I'm sure it will get faster very soon. ``` help(fastgen.synthesize) Help on function synthesize in module magenta.models.nsynth.wavenet.fastgen: synthesize(encodings, save_paths, checkpoint_path='model.ckpt-200000', samples_per_save=1000) Synthesize audio from an array of embeddings. Args: encodings: Numpy array with shape [batch_size, time, dim]. save_paths: Iterable of output file names. checkpoint_path: Location of the pretrained model. [model.ckpt-200000] samples_per_save: Save files after every amount of generated samples. ``` End of explanation """ sr = 16000 synthesis = utils.load_audio('gen_' + fname, sample_length=sample_length, sr=sr) """ Explanation: After it's done synthesizing, we can see that takes about 6 minutes per 1 second of audio on a non-optimized version of Tensorflow for GPU on an NVidia 1080 GPU. We can speed things up considerably if we want to do multiple encodings at a time. We'll see that in just a moment. Let's first listen to the synthesized audio: End of explanation """ def load_encoding(fname, sample_length=None, sr=16000, ckpt='model.ckpt-200000'): audio = utils.load_audio(fname, sample_length=sample_length, sr=sr) encoding = fastgen.encode(audio, ckpt, sample_length) return audio, encoding # from https://www.freesound.org/people/maurolupo/sounds/213259/ fname = '213259__maurolupo__girl-sings-laa.wav' sample_length = 32000 audio, encoding = load_encoding(fname, sample_length) fastgen.synthesize( encoding, save_paths=['gen_' + fname], samples_per_save=sample_length) synthesis = utils.load_audio('gen_' + fname, sample_length=sample_length, sr=sr) """ Explanation: Listening to the audio, the sounds are definitely different. NSynth seems to apply a sort of gobbly low-pass that also really doesn't know what to do with the high frequencies. It is really quite hard to describe, but that is what is so interesting about it. It has a recognizable, characteristic sound. Let's try another one. I'll put the whole workflow for synthesis in two cells, and we can listen to another synthesis of a vocalist singing, "Laaaa": End of explanation """ # use image interpolation to stretch the encoding: (pip install scikit-image) try: from skimage.transform import resize except ImportError: !pip install scikit-image from skimage.transform import resize """ Explanation: Aside from the quality of the reconstruction, what we're really after is what is possible with such a model. Let's look at two examples now. Part 2: Timestretching Let's try something more fun. We'll stretch the encodings a bit and see what it sounds like. If you were to try and stretch audio directly, you'd hear a pitch shift. There are some other ways of stretching audio without shifting pitch, like granular synthesis. But it turns out that NSynth can also timestretch. Let's see how. First we'll use image interpolation to help stretch the encodings. End of explanation """ def timestretch(encodings, factor): min_encoding, max_encoding = encoding.min(), encoding.max() encodings_norm = (encodings - min_encoding) / (max_encoding - min_encoding) timestretches = [] for encoding_i in encodings_norm: stretched = resize(encoding_i, (int(encoding_i.shape[0] * factor), encoding_i.shape[1]), mode='reflect') stretched = (stretched * (max_encoding - min_encoding)) + min_encoding timestretches.append(stretched) return np.array(timestretches) # from https://www.freesound.org/people/MustardPlug/sounds/395058/ fname = '395058__mustardplug__breakbeat-hiphop-a4-4bar-96bpm.wav' sample_length = 40000 audio, encoding = load_encoding(fname, sample_length) """ Explanation: Here's a utility function to help you stretch your own encoding. It uses skimage.transform and will retain the range of values. Images typically only have a range of 0-1, but the encodings aren't actually images so we'll keep track of their min/max in order to stretch them like images. End of explanation """ audio = utils.load_audio('gen_slower_' + fname, sample_length=None, sr=sr) Audio(audio, rate=sr) encoding_slower = timestretch(encoding, 1.5) encoding_faster = timestretch(encoding, 0.5) """ Explanation: Now let's stretch the encodings with a few different factors: End of explanation """ fig, axs = plt.subplots(3, 1, figsize=(10, 7), sharex=True, sharey=True) axs[0].plot(encoding[0]); axs[0].set_title('Encoding (Normal Speed)') axs[1].plot(encoding_faster[0]); axs[1].set_title('Encoding (Faster))') axs[2].plot(encoding_slower[0]); axs[2].set_title('Encoding (Slower)') """ Explanation: Basically we've made a slower and faster version of the amen break's encodings. The original encoding is shown in black: End of explanation """ fastgen.synthesize(encoding_faster, save_paths=['gen_faster_' + fname]) fastgen.synthesize(encoding_slower, save_paths=['gen_slower_' + fname]) """ Explanation: Now let's decode them: End of explanation """ sample_length = 80000 # from https://www.freesound.org/people/MustardPlug/sounds/395058/ aud1, enc1 = load_encoding('395058__mustardplug__breakbeat-hiphop-a4-4bar-96bpm.wav', sample_length) # from https://www.freesound.org/people/xserra/sounds/176098/ aud2, enc2 = load_encoding('176098__xserra__cello-cant-dels-ocells.wav', sample_length) """ Explanation: It seems to work pretty well and retains the pitch and timbre of the original sound. We could even quickly layer the sounds just by adding them. You might want to do this in a program like Logic or Ableton Live instead and explore more possiblities of these sounds! Part 3: Interpolating Sounds Now let's try something more experimental. NSynth released plenty of great examples of what happens when you mix the embeddings of different sounds: https://magenta.tensorflow.org/nsynth-instrument - we're going to do the same but now with our own sounds! First let's load some encodings: End of explanation """ enc_mix = (enc1 + enc2) / 2.0 fig, axs = plt.subplots(3, 1, figsize=(10, 7)) axs[0].plot(enc1[0]); axs[0].set_title('Encoding 1') axs[1].plot(enc2[0]); axs[1].set_title('Encoding 2') axs[2].plot(enc_mix[0]); axs[2].set_title('Average') fastgen.synthesize(enc_mix, save_paths='mix.wav') """ Explanation: Now we'll mix the two audio signals together. But this is unlike adding the two signals together in a Ableton or simply hearing both sounds at the same time. Instead, we're averaging the representation of their timbres, tonality, change over time, and resulting audio signal. This is way more powerful than a simple averaging. End of explanation """ def fade(encoding, mode='in'): length = encoding.shape[1] fadein = (0.5 * (1.0 - np.cos(3.1415 * np.arange(length) / float(length)))).reshape(1, -1, 1) if mode == 'in': return fadein * encoding else: return (1.0 - fadein) * encoding fig, axs = plt.subplots(3, 1, figsize=(10, 7)) axs[0].plot(enc1[0]); axs[0].set_title('Original Encoding') axs[1].plot(fade(enc1, 'in')[0]); axs[1].set_title('Fade In') axs[2].plot(fade(enc1, 'out')[0]); axs[2].set_title('Fade Out') """ Explanation: As another example of what's possible with interpolation of embeddings, we'll try crossfading between the two embeddings. To do this, we'll write a utility function which will use a hanning window to apply a fade in or out to the embeddings matrix: End of explanation """ def crossfade(encoding1, encoding2): return fade(encoding1, 'out') + fade(encoding2, 'in') fig, axs = plt.subplots(3, 1, figsize=(10, 7)) axs[0].plot(enc1[0]); axs[0].set_title('Encoding 1') axs[1].plot(enc2[0]); axs[1].set_title('Encoding 2') axs[2].plot(crossfade(enc1, enc2)[0]); axs[2].set_title('Crossfade') """ Explanation: Now we can cross fade two different encodings by adding their repsective fade ins and out: End of explanation """ fastgen.synthesize(crossfade(enc1, enc2), save_paths=['crossfade.wav']) """ Explanation: Now let's synthesize the resulting encodings: End of explanation """
fja05680/pinkfish
examples/225.weight-by-portfolio/strategy.ipynb
mit
import datetime import matplotlib.pyplot as plt import pandas as pd import pinkfish as pf import strategy # Format price data. pd.options.display.float_format = '{:0.2f}'.format %matplotlib inline # Set size of inline plots. '''note: rcParams can't be in same cell as import matplotlib or %matplotlib inline %matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure %matplotlib inline: only draw static images in the notebook ''' plt.rcParams["figure.figsize"] = (10, 7) """ Explanation: Weight By Portfolio Strategy Basic buy and hold that allows weighting by user specified weights, Equal, Sharpe Ratio, Annual Returns, Std Dev, Vola, or DS Vola. Rebalance is yearly, monthly, weekly, or daily. Option to sell all shares of an investment is regime turns negative. End of explanation """ # Symbol Lists. SP500_Sectors = \ {'XLB': None, 'XLE': None, 'XLF': None, 'XLI': None, 'XLK': None, 'XLP': None, 'XLU': None, 'XLV': None, 'XLY': None} Mixed_Asset_Classes = \ {'IWB': None, 'SPY': None, 'VGK': None, 'IEV': None, 'EWJ': None, 'EPP': None, 'IEF': None, 'SHY': None, 'GLD': None} FANG_Stocks = \ {'FB': None, 'AMZN': None, 'NFLX': None, 'GOOG': None} Stocks_Bonds_Gold = \ {'SPY': None, 'QQQ': None, 'TLT': None, 'GLD': None} Stocks_Bonds = \ {'SPY': 0.50, 'AGG': 0.50} # Pick one of the above. weights = Stocks_Bonds_Gold symbols = list(weights) capital = 100_000 start = datetime.datetime(*pf.ALPHA_BEGIN) #start = datetime.datetime(*pf.SP500_BEGIN) end = datetime.datetime.now() weight_by_choices = ('equal', 'sharpe', 'ret', 'sd', 'vola', 'ds_vola') rebalance_choices = ('yearly', 'monthly', 'weekly', 'daily') options = { 'use_adj' : True, 'use_cache' : True, 'margin' : 1, 'weights' : weights, 'weight_by' : 'vola', 'rebalance' : 'monthly', 'use_regime_filter' : False } """ Explanation: Some global data End of explanation """ s = strategy.Strategy(symbols, capital, start, end, options=options) s.run() """ Explanation: Run Strategy End of explanation """ s.rlog.head() s.tlog.tail() s.dbal.tail() """ Explanation: View log DataFrames: raw trade log, trade log, and daily balance. End of explanation """ pf.print_full(s.stats) """ Explanation: Generate strategy stats - display all available stats. End of explanation """ symbols_no_weights = [k for k,v in weights.items() if v is None] symbols_weights = {k:v for k,v in weights.items() if v is not None} remaining_weight = 1 - sum(symbols_weights.values()) weights_ = weights.copy() for symbol in symbols_no_weights: weights_[symbol] = (1 / len(symbols_no_weights)) * remaining_weight totals = s.portfolio.performance_per_symbol(weights=weights_) totals corr_df = s.portfolio.correlation_map(s.ts) corr_df """ Explanation: View Performance by Symbol End of explanation """ benchmark = pf.Benchmark('SPY', s.capital, s.start, s.end, use_adj=True) benchmark.run() """ Explanation: Run Benchmark, Retrieve benchmark logs, and Generate benchmark stats. End of explanation """ pf.plot_equity_curve(s.dbal, benchmark=benchmark.dbal) """ Explanation: Plot Equity Curves: Strategy vs Benchmark End of explanation """ df = pf.plot_bar_graph(s.stats, benchmark.stats) df """ Explanation: Bar Graph: Strategy vs Benchmark End of explanation """ kelly = pf.kelly_criterion(s.stats, benchmark.stats) kelly """ Explanation: Analysis: Kelly Criterian End of explanation """
tpin3694/tpin3694.github.io
python/set_the_color_of_a_matplotlib.ipynb
mit
%matplotlib inline import numpy as np import matplotlib.pyplot as plt """ Explanation: Title: Set The Color Of A Matplotlib Plot Slug: set_the_color_of_a_matplotlib Summary: Set The Color Of A Matplotlib Plot Date: 2016-05-01 12:00 Category: Python Tags: Data Visualization Authors: Chris Albon Import numpy and matplotlib.pyplot End of explanation """ n = 100 r = 2 * np.random.rand(n) theta = 2 * np.pi * np.random.rand(n) area = 200 * r**2 * np.random.rand(n) colors = theta """ Explanation: Create some simulated data. End of explanation """ c = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.RdYlGn) c1 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.Blues) c2 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.BrBG) c3 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.Greens) c4 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.RdGy) c5 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.YlOrRd) c6 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.autumn) c7 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.binary) c8 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.gist_earth) c9 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.gist_heat) c10 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.hot) c11 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.spring) c12 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.summer) c12 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.winter) c13 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.bone) c14 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.cool) c15 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.YlGn) c16 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.RdBu) c17 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.PuOr) c18 = plt.scatter(theta, r, c=colors, s=area, cmap=plt.cm.Oranges) """ Explanation: Create a scatterplot using the a colormap. Full list of colormaps: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps End of explanation """
hparik11/Deep-Learning-Nanodegree-Foundation-Repository
Project2/image-classification/dlnd_image_classification.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' # Use Floyd's cifar-10 dataset if present floyd_cifar10_location = '/input/cifar-10/python.tar.gz' if isfile(floyd_cifar10_location): tar_gz_path = floyd_cifar10_location else: tar_gz_path = 'cifar-10-python.tar.gz' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(tar_gz_path): with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar: urlretrieve( 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', tar_gz_path, pbar.hook) if not isdir(cifar10_dataset_folder_path): with tarfile.open(tar_gz_path) as tar: tar.extractall() tar.close() tests.test_folder_path(cifar10_dataset_folder_path) """ Explanation: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images. Get the Data Run the following cell to download the CIFAR-10 dataset for python. End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 5 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) """ Explanation: Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog * horse * ship * truck Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch. Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions. End of explanation """ def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ # TODO: Implement Function x_prime = map(lambda x1: 0.1 + ((x1*(0.9-0.1))/(255)), x) return np.array(list(x_prime)) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_normalize(normalize) """ Explanation: Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. End of explanation """ def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ # TODO: Implement Function # one_hot_encoded_labels = np.zeros((len(x), max(x)+1)) # one_hot_encoded_labels[np.arange(len(x)),x] = 1 # return one_hot_encoded_labels return np.eye(10)[x] """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_one_hot_encode(one_hot_encode) """ Explanation: One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function. Hint: Don't reinvent the wheel. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode) """ Explanation: Randomize Data As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save it Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb')) """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return tf.placeholder(dtype=tf.float32, shape=[None, image_shape[0], image_shape[1], image_shape[2]], name="x") def neural_net_label_input(n_classes): """ Return a Tensor for a batch of label input : n_classes: Number of classes : return: Tensor for label input. """ # TODO: Implement Function return tf.placeholder(dtype=tf.float32, shape=[None, n_classes], name="y") def neural_net_keep_prob_input(): """ Return a Tensor for keep probability : return: Tensor for keep probability. """ # TODO: Implement Function return tf.placeholder(dtype=tf.float32, name="keep_prob") """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tf.reset_default_graph() tests.test_nn_image_inputs(neural_net_image_input) tests.test_nn_label_inputs(neural_net_label_input) tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input) """ Explanation: Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project. Note: If you're finding it hard to dedicate enough time for this course each week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages to build each layer, except the layers you build in the "Convolutional and Max Pooling Layer" section. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup. However, if you would like to get the most out of this course, try to solve all the problems without using anything from the TF Layers packages. You can still use classes from other packages that happen to have the same name as ones you find in TF Layers! For example, instead of using the TF Layers version of the conv2d class, tf.layers.conv2d, you would want to use the TF Neural Network version of conv2d, tf.nn.conv2d. Let's begin! Input The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions * Implement neural_net_image_input * Return a TF Placeholder * Set the shape using image_shape with batch size set to None. * Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_label_input * Return a TF Placeholder * Set the shape using n_classes with batch size set to None. * Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_keep_prob_input * Return a TF Placeholder for dropout keep probability. * Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder. These names will be used at the end of the project to load your saved model. Note: None for shapes in TensorFlow allow for a dynamic size. End of explanation """ def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # TODO: Implement Function # print(x_tensor.shape) # print(conv_ksize) # print(conv_num_outputs) color_channels = x_tensor.shape[3].value weights = tf.Variable(tf.truncated_normal([conv_ksize[0], conv_ksize[1], color_channels, conv_num_outputs], mean=0, stddev=0.1)) biases = tf.Variable(tf.zeros(conv_num_outputs)) layer = tf.nn.conv2d(x_tensor, weights, strides=[1, conv_strides[0], conv_strides[1], 1], padding='SAME') layer = tf.add(layer, biases) layer = tf.nn.relu(layer) layer = tf.nn.max_pool(layer, ksize=[1, pool_ksize[0], pool_ksize[1], 1], strides=[1, pool_strides[0], pool_strides[1], 1], padding='SAME') return layer """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_con_pool(conv2d_maxpool) """ Explanation: Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor using weight and conv_strides. * We recommend you use same padding, but you're welcome to use any padding. * Add bias * Add a nonlinear activation to the convolution. * Apply Max Pooling using pool_ksize and pool_strides. * We recommend you use same padding, but you're welcome to use any padding. Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer, but you can still use TensorFlow's Neural Network package. You may still use the shortcut option for all the other layers. End of explanation """ def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function # print(x_tensor) return tf.contrib.layers.flatten(x_tensor) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_flatten(flatten) """ Explanation: Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function #Step 1: create the weights and bias size = x_tensor.shape[1].value weights = tf.Variable(tf.truncated_normal([size, num_outputs], mean=0, stddev=0.1)) bias = tf.Variable(tf.zeros(num_outputs)) #Step 2: apply matmul layer = tf.matmul(x_tensor, weights) #Step 3: add bias layer = tf.nn.bias_add(layer, bias) #Step 4: apply relu layer = tf.nn.relu(layer) return layer # return tf.layers.dense(flatten(x_tensor), num_outputs, activation=tf.nn.relu) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_fully_conn(fully_conn) """ Explanation: Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. End of explanation """ def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function #Step 1: create the weights and bias size = x_tensor.shape[1].value weights = tf.Variable(tf.truncated_normal([size, num_outputs], mean=0, stddev=0.1)) bias = tf.Variable(tf.zeros(num_outputs)) #Step 2: apply matmul layer = tf.matmul(x_tensor, weights) #Step 3: add bias layer = tf.nn.bias_add(layer, bias) return layer # return tf.layers.dense(flatten(x_tensor), num_outputs) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_output(output) """ Explanation: Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Activation, softmax, or cross entropy should not be applied to this. End of explanation """ def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ conv_ksize = [5, 5] conv_strides = [1, 1] pool_ksize = [2, 2] pool_strides = [1, 1] # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers # Play around with different number of outputs, kernel size and stride # Function Definition from Above: # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides) layer_1 = conv2d_maxpool(x, 16, conv_ksize, conv_strides, pool_ksize, pool_strides) layer_2 = conv2d_maxpool(layer_1, 32, conv_ksize, conv_strides, pool_ksize, pool_strides) layer_3 = conv2d_maxpool(layer_2, 64, conv_ksize, conv_strides, pool_ksize, pool_strides) # TODO: Apply a Flatten Layer # Function Definition from Above: # flatten(x_tensor) flat_layer = flatten(layer_3) # TODO: Apply 1, 2, or 3 Fully Connected Layers # Play around with different number of outputs # Function Definition from Above: # fully_conn(x_tensor, num_outputs) fully_connected = fully_conn(flat_layer, 64) fully_connected = tf.nn.dropout(fully_connected, keep_prob) # TODO: Apply an Output Layer # Set this to the number of classes # Function Definition from Above: # output(x_tensor, num_outputs) output_layer = output(fully_connected, 10) # TODO: return output return output_layer """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ ############################## ## Build the Neural Network ## ############################## # Remove previous weights, bias, inputs, etc.. tf.reset_default_graph() # Inputs x = neural_net_image_input((32, 32, 3)) y = neural_net_label_input(10) keep_prob = neural_net_keep_prob_input() # Model logits = conv_net(x, keep_prob) # Name logits Tensor, so that is can be loaded from disk after training logits = tf.identity(logits, name='logits') # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tests.test_conv_net(conv_net) """ Explanation: Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Fully Connected Layers Apply an Output Layer Return the output Apply TensorFlow's Dropout to one or more layers in the model using keep_prob. End of explanation """ def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data """ # TODO: Implement Function session.run(optimizer, feed_dict={ x: feature_batch, y: label_batch, keep_prob: keep_probability}) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_train_nn(train_neural_network) """ Explanation: Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be called for each batch, so tf.global_variables_initializer() has already been called. Note: Nothing needs to be returned. This function is only optimizing the neural network. End of explanation """ def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy: TensorFlow accuracy function """ # TODO: Implement Function loss = session.run(cost, feed_dict={x: feature_batch, y: label_batch, keep_prob: 1.0}) validation_accuracy = session.run(accuracy, feed_dict={x: valid_features, y: valid_labels, keep_prob: 1.0}) print('Loss: {:>10.4f} Validation Accuracy: {:.6f}'.format(loss, validation_accuracy)) """ Explanation: Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. End of explanation """ # TODO: Tune Parameters epochs = 20 batch_size = 64 keep_probability = 0.8 """ Explanation: Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the probability of keeping a node using dropout End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) """ Explanation: Train on a Single CIFAR-10 Batch Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) """ Explanation: Fully Train the Model Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_classification' n_samples = 4 top_n_predictions = 3 def test_model(): """ Test the saved model against the test dataset """ test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb')) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(save_model_path + '.meta') loader.restore(sess, save_model_path) # Get Tensors from loaded model loaded_x = loaded_graph.get_tensor_by_name('x:0') loaded_y = loaded_graph.get_tensor_by_name('y:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_logits = loaded_graph.get_tensor_by_name('logits:0') loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0') # Get accuracy in batches for memory limitations test_batch_acc_total = 0 test_batch_count = 0 for test_feature_batch, test_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size): test_batch_acc_total += sess.run( loaded_acc, feed_dict={loaded_x: test_feature_batch, loaded_y: test_label_batch, loaded_keep_prob: 1.0}) test_batch_count += 1 print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count)) # Print Random Samples random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples))) random_test_predictions = sess.run( tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions), feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0}) helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions) test_model() """ Explanation: Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. End of explanation """
borja876/Thinkful-DataScience-Borja
Evolution+of+GDP+and+Household+Electrcity+Consumption.ipynb
mit
import numpy as np import pandas as pd import scipy import matplotlib.pyplot as plt from scipy.stats import ttest_ind from scipy import stats import itertools %matplotlib inline w = pd.read_csv('https://raw.githubusercontent.com/borja876/Thinkful-DataScience-Borja/master/Electricity%20Consumption.csv') x = pd.read_csv('https://raw.githubusercontent.com/borja876/Thinkful-DataScience-Borja/master/GDP%20current%20prices.csv') y = pd.read_csv('https://raw.githubusercontent.com/borja876/Thinkful-DataScience-Borja/master/Population.csv') df = pd.DataFrame(w) df1 = pd.DataFrame(x) df2 = pd.DataFrame(y) """ Explanation: Capston Project: Analytic Report & Research Proposal Evolution of GPD and Household Electricy Consumption 2000-2014 End of explanation """ #Cleanse Data Frame Electricity Consumption: #Delete rows without countries, rename columns and take out those that are not used #Zeros are identified to see their potential impact on the data set and further results dfa= df[:3206] dfb= dfa.rename(columns={'Country or Area': 'Country', 'Quantity': 'Household Consumption (GWh)'}) dfc = dfb.drop(["Quantity Footnotes", "Unit", "Commodity - Transaction"], axis=1) dfc['Year'] = dfc['Year'].astype(int) #dfc.loc[dfc['Household Consumption (GWh)'] == 0] #Cleanse Data Frame GDP Current Prices (USD): #Cleanse Data Frame Electricity Consumption: #Delete rows without countries, rename columns and take out those that are not used #Zeros are identified to see their potential impact on the data set and further results dfd= df1[:3322] dfe= dfd.rename(columns={'Country or Area': 'Country', 'Value': 'GDP Current Prices (USD)'}) dfg = dfe.drop('Value Footnotes', axis=1) dfg['Year'] = dfg['Year'].astype(int) #dfg.loc[dfg['GDP Current Prices (USD)'] == 0] #Cleanse Data Frame Population: #Take out rows without countries #Rename columns #Clean columns taking out those that are not used dfh= df2[:3522] dfi= dfh.rename(columns={'Country or Area': 'Country', 'Value': 'Population'}) dfj = dfi.drop('Value Footnotes', axis=1) dfj['Year'] = dfj['Year'].astype(int) #dfj.loc[dfj['Population'] == 0] #Merge data into a single dataset #Cleanse new dataset result = dfc.merge(dfg, left_on=["Country","Year"], right_on=["Country","Year"], how='outer') result = result.merge(dfj, left_on=["Country","Year"], right_on=["Country","Year"], how='outer') result = result.dropna() #Rescale & rename variables in the new data set to GDP Current Prices (Million USD) & Population (Thousands) result['GDP Current Prices (Million USD)']=result['GDP Current Prices (USD)']/1000000 result['Population (Thousands)']=result['Population']/1000 #Drop redundant columns after merging the data sets result = result.drop('GDP Current Prices (USD)',1) result = result.drop('Population',1) result= result.rename(columns={'GDP Current Prices (USD)': 'GDP Current Prices (Million USD)', 'Population': 'Population (Thousands)'}) #Use population as a common ground to standardise GDP and household consumption to standardise both variables result['Standard GDP Current Prices (USD)'] =(result['GDP Current Prices (Million USD)']*1000)/result['Population (Thousands)'] result['Standard Household Consumption (kWh)'] = (result['Household Consumption (GWh)']*1000)/result['Population (Thousands)'] """ Explanation: Data sets description The purpose of this report is to analyze the evolution of the household electricity market and GDP per continent in the period 2000-2014. This will show how different economic cycles have affected both variables and the potential correlation between them. Furthermore, in a per continent basis, the both variables will be scrutinized to depict the similarities and differences between continents that will show the relationship between them. Three data sets have been imported from United Nations (from now onwards UN) database. The data sets contain global information for the time span 2000-2014 regarding: Electricity consumption for the household market (GhW). In this dataset, the UN has estimated values for some countries (ex-colonies of the UK) based on their April-March consumption. This estimation has been done up until 2004 yearly electricity consumption was standardized following the natural year and not the fiscal year. Electricity consumption in Iraq in 2014 has a null value, as it was not reported due to the war that started in 2015. GDP per country in current USD. From all the data sets available, measuring GDP the one measuring it in current USD has been chosen to avoid the impact of the different base years across countries when calculating the base of the deflation year and to avoid the use of different exchange rates across countries during the time span under analysis. Population. In this case, the population has been converted into (Thousands) as a unit to make the standardized GDP and electricity consumption significant. This variable shows the net population at the end of the year considering births, deaths and declared migration. The three of them are significant because, although different data sets containing this information exist, only this institution (UN) gathers them. They are consistent in terms of the methods used to gather this information and credible due to the institution that is providing them. The three variables can be compared against each other reducing the bias that may exist in the data due to different data gathering technics used across countries. Electricity consumption and GDP are two metrics that measure the wealth and wellbeing of a country. Its evolution during years can not only show where economy has experienced a slowdown and lose of welfare. The chosen time span neutralizes the effect of the disappearance of the USSR which reduces the distortion of the obtained results. Furthermore, the evolution of these two variables before the year 2000 has not representative when predicting the future evolution of wealth and wellbeing of a country/continent or/and its economic slowdown. The main reason being that the way in which the information is gathered in both cases has changed at a macroeconomic level and base years have been adjusted in all countries to the year 2000. Both variables, Electricity and GDP, have been analyzed after standardizing them considering the Population as the common factor. Additionally, they have been rescaled to kWh (electricity consumption) and (Million USD) to make them comparable. Household electricity consumption per individual and GDP per individual at current prices are better proxies of the welfare of the country and scaling issues disappear. End of explanation """ #Import list of countries per continent from external data set and clean the columns that will not be used. countries = pd.read_json('https://raw.githubusercontent.com/borja876/Thinkful-DataScience-Borja/master/countries.txt') countries =countries.drop (['capital','code','timezones'],1) #Merge both data sets for have a complete working data set result = result.merge(countries, left_on=["Country"], right_on=["name"], how='inner') result = result.drop('name',1) result = result.rename(columns={'continent': 'Continent'}) """ Explanation: A list of countries per continent has been imported from a different source (https://gist.github.com/pamelafox/986163). The use of this list aims to group by continent the information provided by the UN at a country level. This has risen additional difficulties due to the use different names between sources for several countries, for example: Russian Federation vs. Russia, Netherlands vs. The Netherlands, etc. Moreover, some countries have been identified in the original data set that are not included in the original list. This have been added to the list for the completeness. The aim of this addition is to have all continents accurately represented. America has been split into North and South America to have a detailed view of the evolution of both regions independently and to avoid distortion. The final continents used are: Africa Oceania North America South America Europe Asia End of explanation """ result.head() """ Explanation: After checking that all countries considered by the UN are captured in the eternal list of countries used to group them by continent the final data set is created. The following table shows the first five rows of the final data set that will be used for the purpose of this report: End of explanation """ summary = result.describe().astype(int) summary.drop('Year',1) v = result.var() v1 = pd.DataFrame(v, columns=['Var']) w=result.skew() w1 = pd.DataFrame(w, columns=['Skew']) ww=result.kurt() ww1 = pd.DataFrame(ww, columns=['kurt']) df55 = v1.assign(Skew=w1.values, Kurt=ww1.values) df56=df55.transpose() frames = [summary, df56] summaryb = pd.concat(frames).drop('Year',1) summaryb """ Explanation: The following summary statistics have been conducted. In the table below, it can be seen the difference between extreme values for all variables, ranging from zero/tens to millions for electricity consumption and GDP. Once standardized variances continue to be high. This recommends the use of the median instead of the mean to avoid the effect of these extreme values. These extreme values come from United States (North America) which is equivalent to the whole Europe and Iraq (min) as zero for 2014. The values of Skewness and Kurtosis show that variables cannot be following a normal distribution. End of explanation """ print(ttest_ind(result['Household Consumption (GWh)'], result['GDP Current Prices (Million USD)'], equal_var=False)) print(ttest_ind(result['Standard Household Consumption (kWh)'], result['Standard GDP Current Prices (USD)'], equal_var=False)) """ Explanation: A t test has been conducted showing that the difference in means between both the standard electricity consumption and the standard GDP are truly because the populations are different and not due to variability. As both original variables are representing different populations, the standardised ones follow the same principle (as it can deducted from the obtained p values). End of explanation """ # Making two variables. norm = np.random.normal(0, 1, 2404) norm.sort() a = result.sort_values('Household Consumption (GWh)',ascending=True) b = result.sort_values('GDP Current Prices (Million USD)',ascending=True) c = result.sort_values('Population (Thousands)',ascending=True) d = result.sort_values('Standard GDP Current Prices (USD)',ascending=True) e = result.sort_values('Standard Household Consumption (kWh)',ascending=True) #Checking that variables are not normally distributed plt.figure(figsize=(20, 5)) plt.subplot(1, 5, 1) plt.plot(norm,a['Household Consumption (GWh)'], "o") plt.title('Household Consumption (GWh') plt.subplot(1, 5, 2) plt.plot(norm,b['GDP Current Prices (Million USD)'], "o") plt.title('GDP Current Prices (Million USD)') plt.subplot(1, 5, 3) plt.plot(norm,c['Population (Thousands)'], "o") plt.title('Population (Thousands)') plt.subplot(1, 5, 4) plt.plot(norm,d['Standard GDP Current Prices (USD)'], "o") plt.title('Standard GDP Current Prices (USD p. Capita)') plt.subplot(1, 5, 5) plt.plot(norm,e['Standard Household Consumption (kWh)'], "o") plt.title('Household Consumption (kWh) p. Capita') plt.tight_layout() plt.show() """ Explanation: A closer look at each of the variables confirms what was anticipated by the Skewness and Kurtosis coefficients. When each of the variables is compared against a normal distribution, none of them follow this kind of distribution. End of explanation """ #Histograms plt.figure(figsize=(20, 5)) plt.subplot(1, 5, 1) plt.xlabel("GDP Current Prices (Million USD)") plt.ylabel("Frequency") plt.hist(result['GDP Current Prices (Million USD)'], bins= 5000 ,facecolor='green', alpha=0.5) plt.axis([0, 150000, 0, 650]) plt.title('GDP Current Prices (Million USD)') plt.subplot(1, 5, 2) plt.xlabel("Household Consumption (GWh)") plt.ylabel("Frequency") plt.hist(result['Household Consumption (GWh)'], bins=5000 ,facecolor='blue', alpha=0.5) plt.axis([0, 13000, 0, 650]) plt.title('Household Consumption (GWh') plt.subplot(1, 5, 3) plt.xlabel("Population (Thousands)") plt.ylabel("Frequency") plt.hist(result['Population (Thousands)'], bins=5000 ,facecolor='red', alpha=0.5) plt.axis([0, 25000, 0, 650]) plt.title('Population (Thousands)') plt.subplot(1, 5, 4) plt.xlabel("Standard GDP Current Prices") plt.ylabel("Frequency") plt.hist(result['Standard GDP Current Prices (USD)'], bins=100 ,facecolor='red', alpha=0.5) plt.axis([0, 120000, 0, 600]) plt.title('USD') plt.subplot(1, 5, 5) plt.xlabel("Standard Household Consumption") plt.ylabel("Frequency") plt.hist(result['Standard Household Consumption (kWh)'], bins=100 ,facecolor='red', alpha=0.5) plt.axis([0, 9000, 0, 600]) plt.title('Population (Thousands)') plt.tight_layout() plt.show() """ Explanation: From the histograms below, it can be seen that the distribution of values is asymmetric, having a high concentration of values in the lower end and a long tail which shows the dispersion of values (with very low frequencies of occurrence). The standardized variables follow the same pattern in terms of frequency of occurrence between lower and higher values. End of explanation """ #Calculate the correlation matrix result.corr() """ Explanation: Question 1: Is there a relationship between GDP and Household consumption? Is it the same across continents? When comparing the data sets without grouping the data into continents, the correlation matrix below shows that there is no correlation between years GDP and Electricity consumption, hence there is no inflation effect on the variables. There is a strnger correlation between the standard GDP and the years due to the impact of population. The table below highlights the positive and strong relationship between electricity consumption and GDP. Furthermore, it evidences the relationship between our standardized variables: both vary in the same direction but at a lower rate due to the impact in the variable “Population” used to standardize them. It also evidences the positive relationship between population and electricity consumption. As expected, it shows that only half of the increase is due to an increase in population leaving the other half unexplained. End of explanation """ #Plot standard household consumption and standard GDP grouped by continents result2=result.groupby(['Continent']).median() result3 = result2.sort_values(['Standard Household Consumption (kWh)']) plt.figure(figsize=(20, 7)) plt.subplot(1, 2, 1) result3['Standard Household Consumption (kWh)'].plot(kind='bar', color='red') plt.ylabel('kWh') plt.title('Standard Household Consumption per Continent') plt.subplot(1, 2, 2) result3['Standard GDP Current Prices (USD)'].plot(kind='bar', color='blue') plt.ylabel('Million USD') plt.title('Standard GDP Current Prices per Continent') plt.tight_layout() plt.show() """ Explanation: For a more granular inspection of the data, median from the standardized variables will be used based on the initial findings regarding the disparity of values in the original data sets. Furthermore, and due to the representativeness of the standardized values, analysis per continent will be based on them, only using the unstandardized values when additional conclusions can be obtained. The following charts show the values per continent of the standardized variables. The table shows that there is a significant difference in values between continents, both in the standard household consumption and in the GDP. End of explanation """ #Box-plot result1=result.groupby(['Continent','Year']).median() result1[['Standard Household Consumption (kWh)','Standard GDP Current Prices (USD)']].boxplot(figsize=(26, 10)) """ Explanation: The following box plot shows the summary statistics describing the values per continent of each of the variables. It can be appreciated that variance is lower in the case of the standard household consumption compared to the standard GDP. The min value in terms of standard GDP is much lower thant the percentil 25 while in the case of the electricity consumption values are more compact. End of explanation """ #Scatter plot showing the correlation between standardised values C = result1.index.levels[0] colors = itertools.cycle(["r", "b", "g", 'purple','yellow','brown']) plt.figure(figsize=(20, 5)) for cont in C : graph = result1.loc[cont] plt.scatter(x=graph['Standard Household Consumption (kWh)'], y=graph['Standard GDP Current Prices (USD)'], color = next(colors), marker= 'o', label = cont) plt.ylabel('USD') plt.xlabel('kWh') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) plt.show() """ Explanation: When analyzing the correlation between standard household consumption and standard GDP, North & South America and Asia show a higher correlation than the rest of the continents. In the case of Europe, values are more scattered in the higher end of the graph due to a higher standard GDP. It can be concluded that the correlation between both variables although exists in all continents, vaires varies between continents in terms of its strength. End of explanation """ #Plot correlation between unstandardised variables to undertand the source of correlation C = result1.index.levels[0] colors = itertools.cycle(["r", "b", "g", 'purple','yellow','brown']) plt.figure(figsize=(20, 5)) plt.subplot(1, 3, 1) for cont in C : graph = result1.loc[cont] plt.scatter(x=graph['Population (Thousands)'], y=graph['Household Consumption (GWh)'], color = next(colors), marker = 'o', s = 50, label=cont) plt.ylabel('GWh') plt.xlabel('Population (Thousands)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) #plt.ylim([20000, 160000]) #plt.title('Electricity consumption') #plt.show() plt.subplot(1, 3, 2) for cont in C : graph = result1.loc[cont] plt.scatter(x=graph['Population (Thousands)'], y=graph['GDP Current Prices (Million USD)'], color = next(colors),marker = 'x', s = 50, label=cont) plt.ylabel('Million USD') plt.xlabel('Population (Thousands)') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) plt.subplot(1, 3, 3) for cont in C : graph = result1.loc[cont] plt.scatter(x=graph['Household Consumption (GWh)'], y=graph['GDP Current Prices (Million USD)'], color = next(colors),marker = 'x', s = 50, label=cont) plt.ylabel('Household Consumption (GWh)') plt.xlabel('Million USD') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) plt.tight_layout() plt.show() """ Explanation: Further investigation depicts how the relationship of each of the raw variables (Household Consumption (GWh) and GDP) that form each of the standard variables differ. Additionally, within continents, it can be seen that the relationship between both consumption and GDP vs population behave in a similar way. Especially notorious is the case of Africa, that shows how both GDP and electricity consumption grow with population. In this case although it could be infer due to the characteristics of its economy that the correlation between both is closer to 1, it can be seen how the slope is steeper than the unit due to the contribution of other factors to both variables. End of explanation """ #Plot time series showing the evolution of the standardised variables C = result1.index.levels[0] colors = itertools.cycle(["r", "b", "g", 'purple','yellow','brown']) plt.figure(figsize=(20, 5)) plt.subplot(1, 2, 1) for cont in C : graph = result1.loc[cont] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-", label = cont) plt.ylabel('kWh') plt.xlabel('Year') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) plt.subplot(1, 2, 2) for cont in C : graph = result1.loc[cont] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-", label = cont) plt.ylabel('USD') plt.xlabel('Year') plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=3, mode="expand", borderaxespad=0.) plt.tight_layout() plt.show() """ Explanation: As it can be seen from the graphs above, each continent follows a different pattern in terms of standard electricity consumption and standard GDP against population. Hence detailed analysis show how each continent behaves in a different way although initially, when considering global data, the relationship between both variables was high and positive. Question 2: How has the economic welfare of countries evolved from the year 2000? From the graphs below it can be seen that standard electricity consumption and standard GDP is higher in Europe than in the rest of the continents. In all cases both variables experience an increase during the period and except for Europe the increase seems to be smoother in the rest of the continents. From an electricity consumption perspective, the graph depicts how the economic downturns of 2008 affected the welfare of the population. It also shows how up until that year, when natural gas was considered an alternative cheaper solution for household heating systems, the population was relying on its use. The rest of the continents were more conservative in the use of electricity for household needs. It can be seen how there is a strong decrease in electricity consumption in 2002 and 2004 both in Asia and North America. The first change in slope can be seen in Asia in 2002 (due to the economic downturn that the country experienced that year). This decrease impacts North America in 2004 as part of its knock on effect. On the flipside, Europe slightly decreases its rate of increase but still increases the electricity consumption up until 2008. The economic Africa´s growth, in the lower-end is mainly due to the penetration of new electricity infrastructure during this period. From a GDP perspective, the graph shows the deep impact that the 2008 economic downturn had in Europe. Although hiking up until then, the loss by 2014 was considerable in relative terms. For the rest of the continents, the 2002 economic downturn can be observed. It is worth mentioning the economic acceleration that Asia has experimented during the period. Starting at a lower point than Oceania, it grows surpassing Oceania after 2006 and continues to grow at a higher rate than the rest of the continents. A similar growth is driven by South America but for different reasons. In this case it is not mainly the growth of the GDP but the decrease in population due to the crisis experienced by Argentina at the beginning of the century. End of explanation """ #Plot 6 graphs showing the evolution of standard GDP per continent C = result1.index.levels[0] colors = itertools.cycle(["r", "b", "g", 'purple','yellow','brown']) plt.figure(figsize=(26, 10)) plt.subplot(2, 6, 1) graph = result1.loc['Africa'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('Africa: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.subplot(2, 6, 2) graph = result1.loc['Oceania'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('Oceania: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.subplot(2, 6, 3) graph = result1.loc['South America'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('South America: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.subplot(2, 6, 4) graph = result1.loc['Europe'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('Europe: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.subplot(2, 6, 5) graph = result1.loc['Asia'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('Asia: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.subplot(2, 6, 6) graph = result1.loc['North America'] plt.plot(graph.index, graph['Standard GDP Current Prices (USD)'], color = next(colors), linestyle = "-") plt.ylabel('USD') plt.xlabel('Year') plt.title('North America: Standard GDP Current Prices') plt.xlim([2000, 2014]) plt.tight_layout() plt.show() """ Explanation: Question 3: What was the behavior of each continent during this period? All six continents have increased their wealth during the period 2000-2014. Europe and America have more than doubled their GDP per capita while the rest of the continents have multiplied by 3 except for Asia that has multiplied its GDP by 7. All continents show a flat or declining GDP during the period 2002-2004, being the case of Asia the most significant. All except for Europe and South America have experienced a slight decrease in its GDP due to the economic crisis if compared to Europe. It can be seen that Europe was one of the continents that was experiencing higher growth but also higher decline due to the crisis. In the case of America, periods of growth and slowdown have been alternating every two years. Europe has been the continent that has experienced the highest economic downturn during the period. Although it was one of the highest growing ones up until 2008, the economic downturn has significantly reduced the GDP per capita up until more than USD10,000. End of explanation """ #Plot six graphs showing the evolution of standard electricity consumption per continent C = result1.index.levels[0] colors = itertools.cycle(["r", "b", "g", 'purple','yellow','brown']) plt.figure(figsize=(26, 10)) plt.subplot(2, 6, 1) graph = result1.loc['Africa'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('kWh') plt.xlabel('Year') plt.title('Africa: Household Consumption') plt.xlim([2000, 2014]) plt.subplot(2, 6, 2) graph = result1.loc['Oceania'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('kWh') plt.xlabel('Year') plt.title('Oceania: Household Consumption') plt.xlim([2000, 2014]) plt.ylim([180, 240]) plt.subplot(2, 6, 3) graph = result1.loc['South America'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('x10 kWh') plt.xlabel('Year') plt.title('South America: Household Consumption') plt.xlim([2000, 2014]) plt.subplot(2, 6, 4) graph = result1.loc['Europe'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('kWh') plt.xlabel('Year') plt.title('Europe: Household Consumption') plt.xlim([2000, 2014]) plt.subplot(2, 6, 5) graph = result1.loc['Asia'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('kWh') plt.xlabel('Year') plt.title('Asia: Household Consumption') plt.xlim([2000, 2014]) plt.subplot(2, 6, 6) graph = result1.loc['North America'] plt.plot(graph.index, graph['Standard Household Consumption (kWh)'], color = next(colors), linestyle = "-") plt.ylabel('kWh') plt.xlabel('Year') plt.title('North America: Household Consumption') plt.xlim([2000, 2014]) plt.tight_layout() plt.show() """ Explanation: Electricity consumption per household decreases in all continents between 2002 ad 2004. This is due to two main reasons. The increase of electricity prices correlated to and oil prices basket at that time and the economic slowdown that took place in that period. Although it shows an increase in all six continents, the behavior during the period under analysis is significantly different: In Africa, electricity consumption decreases in 2004 and steadily increases during the period. After 2004 every 2 years Africa experiences a contraction in consumption followed by an increase that compensates and surpasses in absolute terms the contraction. Compared to the rest of the continents it seems too have the steepest slope only comparable to South America. This can be mainly because of the penetration of electricity infrastructure in the continent and its low starting point in terms of standard electricity consumption. In Australia there is a decrease in consumption in 2002 and after a continuous increase up unitl 2008, it stabilizes around the value achieve in 2014. This is mainly due to the environmental and demand management regulation introduced in the country in 2006 added to the economic downturn that affected Australia in 2008. In South America, there is a steady increase in electricity consumption due to the emigration after the recession at the beginning of the century. In North America and Europe, electricity consumption growth is similar to Europe. In both there is a decrease in 2002-2004 due to the economic downturn in the case of Europe and to the introduction of natural gas and regulation giving positive incentives to the use of it in heating systems. Additionally, in North America the deregulation of household production makes the impact in this country higher than in Europe. In both, the main responsible for the 2008 decrease in electricity consumption is the real estate crisis that affected Europe more than America but it had its consequences in both. In Asia, electricity consumption has followed an increasing path during the period. After the 2002-2004 stagnation in terms of consumption, the increase experienced by this region has been uneven. It has followed a pattern of two years of growth and one year of decrease. During the growth periods, it has increased its household consumption roughly 100 kWh per capita. During the declining periods, consumption has fall one quarter of its increase. End of explanation """
ChadFulton/statsmodels
examples/notebooks/markov_autoregression.ipynb
bsd-3-clause
%matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import requests from io import BytesIO # NBER recessions from pandas_datareader.data import DataReader from datetime import datetime usrec = DataReader('USREC', 'fred', start=datetime(1947, 1, 1), end=datetime(2013, 4, 1)) """ Explanation: Markov switching autoregression models This notebook provides an example of the use of Markov switching models in Statsmodels to replicate a number of results presented in Kim and Nelson (1999). It applies the Hamilton (1989) filter the Kim (1994) smoother. This is tested against the Markov-switching models from E-views 8, which can be found at http://www.eviews.com/EViews8/ev8ecswitch_n.html#MarkovAR or the Markov-switching models of Stata 14 which can be found at http://www.stata.com/manuals14/tsmswitch.pdf. End of explanation """ # Get the RGNP data to replicate Hamilton dta = pd.read_stata('https://www.stata-press.com/data/r14/rgnp.dta').iloc[1:] dta.index = pd.DatetimeIndex(dta.date, freq='QS') dta_hamilton = dta.rgnp # Plot the data dta_hamilton.plot(title='Growth rate of Real GNP', figsize=(12,3)) # Fit the model mod_hamilton = sm.tsa.MarkovAutoregression(dta_hamilton, k_regimes=2, order=4, switching_ar=False) res_hamilton = mod_hamilton.fit() res_hamilton.summary() """ Explanation: Hamilton (1989) switching model of GNP This replicates Hamilton's (1989) seminal paper introducing Markov-switching models. The model is an autoregressive model of order 4 in which the mean of the process switches between two regimes. It can be written: $$ y_t = \mu_{S_t} + \phi_1 (y_{t-1} - \mu_{S_{t-1}}) + \phi_2 (y_{t-2} - \mu_{S_{t-2}}) + \phi_3 (y_{t-3} - \mu_{S_{t-3}}) + \phi_4 (y_{t-4} - \mu_{S_{t-4}}) + \varepsilon_t $$ Each period, the regime transitions according to the following matrix of transition probabilities: $$ P(S_t = s_t | S_{t-1} = s_{t-1}) = \begin{bmatrix} p_{00} & p_{10} \ p_{01} & p_{11} \end{bmatrix} $$ where $p_{ij}$ is the probability of transitioning from regime $i$, to regime $j$. The model class is MarkovAutoregression in the time-series part of Statsmodels. In order to create the model, we must specify the number of regimes with k_regimes=2, and the order of the autoregression with order=4. The default model also includes switching autoregressive coefficients, so here we also need to specify switching_ar=False to avoid that. After creation, the model is fit via maximum likelihood estimation. Under the hood, good starting parameters are found using a number of steps of the expectation maximization (EM) algorithm, and a quasi-Newton (BFGS) algorithm is applied to quickly find the maximum. End of explanation """ fig, axes = plt.subplots(2, figsize=(7,7)) ax = axes[0] ax.plot(res_hamilton.filtered_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec['USREC'].values, color='k', alpha=0.1) ax.set_xlim(dta_hamilton.index[4], dta_hamilton.index[-1]) ax.set(title='Filtered probability of recession') ax = axes[1] ax.plot(res_hamilton.smoothed_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec['USREC'].values, color='k', alpha=0.1) ax.set_xlim(dta_hamilton.index[4], dta_hamilton.index[-1]) ax.set(title='Smoothed probability of recession') fig.tight_layout() """ Explanation: We plot the filtered and smoothed probabilities of a recession. Filtered refers to an estimate of the probability at time $t$ based on data up to and including time $t$ (but excluding time $t+1, ..., T$). Smoothed refers to an estimate of the probability at time $t$ using all the data in the sample. For reference, the shaded periods represent the NBER recessions. End of explanation """ print(res_hamilton.expected_durations) """ Explanation: From the estimated transition matrix we can calculate the expected duration of a recession versus an expansion. End of explanation """ # Get the dataset ew_excs = requests.get('http://econ.korea.ac.kr/~cjkim/MARKOV/data/ew_excs.prn').content raw = pd.read_table(BytesIO(ew_excs), header=None, skipfooter=1, engine='python') raw.index = pd.date_range('1926-01-01', '1995-12-01', freq='MS') dta_kns = raw.loc[:'1986'] - raw.loc[:'1986'].mean() # Plot the dataset dta_kns[0].plot(title='Excess returns', figsize=(12, 3)) # Fit the model mod_kns = sm.tsa.MarkovRegression(dta_kns, k_regimes=3, trend='nc', switching_variance=True) res_kns = mod_kns.fit() res_kns.summary() """ Explanation: In this case, it is expected that a recession will last about one year (4 quarters) and an expansion about two and a half years. Kim, Nelson, and Startz (1998) Three-state Variance Switching This model demonstrates estimation with regime heteroskedasticity (switching of variances) and no mean effect. The dataset can be reached at http://econ.korea.ac.kr/~cjkim/MARKOV/data/ew_excs.prn. The model in question is: $$ \begin{align} y_t & = \varepsilon_t \ \varepsilon_t & \sim N(0, \sigma_{S_t}^2) \end{align} $$ Since there is no autoregressive component, this model can be fit using the MarkovRegression class. Since there is no mean effect, we specify trend='nc'. There are hypotheized to be three regimes for the switching variances, so we specify k_regimes=3 and switching_variance=True (by default, the variance is assumed to be the same across regimes). End of explanation """ fig, axes = plt.subplots(3, figsize=(10,7)) ax = axes[0] ax.plot(res_kns.smoothed_marginal_probabilities[0]) ax.set(title='Smoothed probability of a low-variance regime for stock returns') ax = axes[1] ax.plot(res_kns.smoothed_marginal_probabilities[1]) ax.set(title='Smoothed probability of a medium-variance regime for stock returns') ax = axes[2] ax.plot(res_kns.smoothed_marginal_probabilities[2]) ax.set(title='Smoothed probability of a high-variance regime for stock returns') fig.tight_layout() """ Explanation: Below we plot the probabilities of being in each of the regimes; only in a few periods is a high-variance regime probable. End of explanation """ # Get the dataset filardo = requests.get('http://econ.korea.ac.kr/~cjkim/MARKOV/data/filardo.prn').content dta_filardo = pd.read_table(BytesIO(filardo), sep=' +', header=None, skipfooter=1, engine='python') dta_filardo.columns = ['month', 'ip', 'leading'] dta_filardo.index = pd.date_range('1948-01-01', '1991-04-01', freq='MS') dta_filardo['dlip'] = np.log(dta_filardo['ip']).diff()*100 # Deflated pre-1960 observations by ratio of std. devs. # See hmt_tvp.opt or Filardo (1994) p. 302 std_ratio = dta_filardo['dlip']['1960-01-01':].std() / dta_filardo['dlip'][:'1959-12-01'].std() dta_filardo['dlip'][:'1959-12-01'] = dta_filardo['dlip'][:'1959-12-01'] * std_ratio dta_filardo['dlleading'] = np.log(dta_filardo['leading']).diff()*100 dta_filardo['dmdlleading'] = dta_filardo['dlleading'] - dta_filardo['dlleading'].mean() # Plot the data dta_filardo['dlip'].plot(title='Standardized growth rate of industrial production', figsize=(13,3)) plt.figure() dta_filardo['dmdlleading'].plot(title='Leading indicator', figsize=(13,3)); """ Explanation: Filardo (1994) Time-Varying Transition Probabilities This model demonstrates estimation with time-varying transition probabilities. The dataset can be reached at http://econ.korea.ac.kr/~cjkim/MARKOV/data/filardo.prn. In the above models we have assumed that the transition probabilities are constant across time. Here we allow the probabilities to change with the state of the economy. Otherwise, the model is the same Markov autoregression of Hamilton (1989). Each period, the regime now transitions according to the following matrix of time-varying transition probabilities: $$ P(S_t = s_t | S_{t-1} = s_{t-1}) = \begin{bmatrix} p_{00,t} & p_{10,t} \ p_{01,t} & p_{11,t} \end{bmatrix} $$ where $p_{ij,t}$ is the probability of transitioning from regime $i$, to regime $j$ in period $t$, and is defined to be: $$ p_{ij,t} = \frac{\exp{ x_{t-1}' \beta_{ij} }}{1 + \exp{ x_{t-1}' \beta_{ij} }} $$ Instead of estimating the transition probabilities as part of maximum likelihood, the regression coefficients $\beta_{ij}$ are estimated. These coefficients relate the transition probabilities to a vector of pre-determined or exogenous regressors $x_{t-1}$. End of explanation """ mod_filardo = sm.tsa.MarkovAutoregression( dta_filardo.iloc[2:]['dlip'], k_regimes=2, order=4, switching_ar=False, exog_tvtp=sm.add_constant(dta_filardo.iloc[1:-1]['dmdlleading'])) np.random.seed(12345) res_filardo = mod_filardo.fit(search_reps=20) res_filardo.summary() """ Explanation: The time-varying transition probabilities are specified by the exog_tvtp parameter. Here we demonstrate another feature of model fitting - the use of a random search for MLE starting parameters. Because Markov switching models are often characterized by many local maxima of the likelihood function, performing an initial optimization step can be helpful to find the best parameters. Below, we specify that 20 random perturbations from the starting parameter vector are examined and the best one used as the actual starting parameters. Because of the random nature of the search, we seed the random number generator beforehand to allow replication of the result. End of explanation """ fig, ax = plt.subplots(figsize=(12,3)) ax.plot(res_filardo.smoothed_marginal_probabilities[0]) ax.fill_between(usrec.index, 0, 1, where=usrec['USREC'].values, color='gray', alpha=0.2) ax.set_xlim(dta_filardo.index[6], dta_filardo.index[-1]) ax.set(title='Smoothed probability of a low-production state'); """ Explanation: Below we plot the smoothed probability of the economy operating in a low-production state, and again include the NBER recessions for comparison. End of explanation """ res_filardo.expected_durations[0].plot( title='Expected duration of a low-production state', figsize=(12,3)); """ Explanation: Using the time-varying transition probabilities, we can see how the expected duration of a low-production state changes over time: End of explanation """
roatienza/Deep-Learning-Experiments
versions/2022/autoencoder/python/ae_pytorch_demo.ipynb
mit
import torch import torchvision import wandb import time from torch import nn from einops import rearrange from argparse import ArgumentParser from pytorch_lightning import LightningModule, Trainer, Callback from pytorch_lightning.loggers import WandbLogger from torch.optim import Adam from torch.optim.lr_scheduler import CosineAnnealingLR """ Explanation: AutoEncoder PyTorch Demo using MNIST In this demo, we build a simple autoencoder using PyTorch. A separate encoder and decoder are built. The encoder is trained to encode the input data into a latent space. The decoder is trained to reconstruct the input data from the latent space. This demo also shows how to use an autoencoder to remove noise from images. End of explanation """ class Encoder(nn.Module): def __init__(self, n_features=1, kernel_size=3, n_filters=16, feature_dim=16): super().__init__() self.conv1 = nn.Conv2d(n_features, n_filters, kernel_size=kernel_size, stride=2) self.conv2 = nn.Conv2d(n_filters, n_filters*2, kernel_size=kernel_size, stride=2) self.conv3 = nn.Conv2d(n_filters*2, n_filters*4, kernel_size=kernel_size, stride=2) self.fc1 = nn.Linear(256, feature_dim) def forward(self, x): y = nn.ReLU()(self.conv1(x)) y = nn.ReLU()(self.conv2(y)) y = nn.ReLU()(self.conv3(y)) y = rearrange(y, 'b c h w -> b (c h w)') y = self.fc1(y) return y # use this to get the correct input shape for fc1. encoder = Encoder(n_features=1) x = torch.Tensor(1, 1, 28, 28) h = encoder(x) print("h.shape:", h.shape) """ Explanation: CNN Encoder using PyTorch We use 3 CNN layers to encode the input image. We use stride of 2 to reduce the feature map size. The last MLP layer resizes the flattened feature map to the target latent vector size, feature_dim. End of explanation """ class Decoder(nn.Module): def __init__(self, kernel_size=3, n_filters=64, feature_dim=16, output_size=28, output_channels=1): super().__init__() self.init_size = output_size // 2**2 - 1 self.fc1 = nn.Linear(feature_dim, self.init_size**2 * n_filters) # output size of conv2dtranspose is (h-1)*2 + 1 + (kernel_size - 1) self.conv1 = nn.ConvTranspose2d(n_filters, n_filters//2, kernel_size=kernel_size, stride=2) self.conv2 = nn.ConvTranspose2d(n_filters//2, n_filters//4, kernel_size=kernel_size, stride=2) self.conv3 = nn.ConvTranspose2d(n_filters//4, output_channels, kernel_size=kernel_size-1) def forward(self, x): B, _ = x.shape y = self.fc1(x) y = rearrange(y, 'b (c h w) -> b c h w', b=B, h=self.init_size, w=self.init_size) y = nn.ReLU()(self.conv1(y)) y = nn.ReLU()(self.conv2(y)) y = nn.Sigmoid()(self.conv3(y)) return y decoder = Decoder() x_tilde = decoder(h) print("x_tilde.shape:", x_tilde.shape) """ Explanation: CNN Decoder using PyTorch A decoder is used to reconstruct the input image. The decoder is trained to reconstruct the input data from the latent space. The architecture is similar to the encoder but inverted. A latent vector is resized using an MLP layer so that it is suitable for a convolutional layer. We use strided tranposed convolutional layers to upsample the feature map until the desired image size is reached. The last activation layer is a sigmoid to ensure the output is in the range [0, 1]. End of explanation """ def noise_collate_fn(batch): x, _ = zip(*batch) x = torch.stack(x, dim=0) # mean=0.5, std=0.5 normal noise noise = torch.normal(0.5, 0.5, size=x.shape) xn = x + noise xn = torch.clamp(xn, 0, 1) return xn, x def clean_collate_fn(batch): x, _ = zip(*batch) x = torch.stack(x, dim=0) return x, x class LitAEMNISTModel(LightningModule): def __init__(self, feature_dim=16, lr=0.001, batch_size=64, num_workers=4, max_epochs=30, denoise=False, **kwargs): super().__init__() self.save_hyperparameters() self.encoder = Encoder(feature_dim=feature_dim) self.decoder = Decoder(feature_dim=feature_dim) self.loss = nn.MSELoss() self.denoise = denoise def forward(self, x): h = self.encoder(x) x_tilde = self.decoder(h) return x_tilde # this is called during fit() def training_step(self, batch, batch_idx): x_in, x = batch x_tilde = self.forward(x_in) loss = self.loss(x_tilde, x) return {"loss": loss} # calls to self.log() are recorded in wandb def training_epoch_end(self, outputs): avg_loss = torch.stack([x["loss"] for x in outputs]).mean() self.log("train_loss", avg_loss, on_epoch=True) # this is called at the end of an epoch def test_step(self, batch, batch_idx): x_in, x = batch x_tilde = self.forward(x_in) loss = self.loss(x_tilde, x) return {"x_in" : x_in, "x_tilde" : x_tilde, "test_loss" : loss,} # this is called at the end of all epochs def test_epoch_end(self, outputs): avg_loss = torch.stack([x["test_loss"] for x in outputs]).mean() self.log("test_loss", avg_loss, on_epoch=True, prog_bar=True) # validation is the same as test def validation_step(self, batch, batch_idx): return self.test_step(batch, batch_idx) def validation_epoch_end(self, outputs): return self.test_epoch_end(outputs) # we use Adam optimizer def configure_optimizers(self): optimizer = Adam(self.parameters(), lr=self.hparams.lr) # this decays the learning rate to 0 after max_epochs using cosine annealing scheduler = CosineAnnealingLR(optimizer, T_max=self.hparams.max_epochs) return [optimizer], [scheduler] # this is called after model instatiation to initiliaze the datasets and dataloaders def setup(self, stage=None): self.train_dataloader() self.test_dataloader() # build train and test dataloaders using MNIST dataset # we use simple ToTensor transform def train_dataloader(self): collate_fn = noise_collate_fn if self.denoise else clean_collate_fn return torch.utils.data.DataLoader( torchvision.datasets.MNIST( "./data", train=True, download=True, transform=torchvision.transforms.ToTensor() ), batch_size=self.hparams.batch_size, shuffle=True, num_workers=self.hparams.num_workers, pin_memory=True, collate_fn=collate_fn ) def test_dataloader(self): collate_fn = noise_collate_fn if self.denoise else clean_collate_fn return torch.utils.data.DataLoader( torchvision.datasets.MNIST( "./data", train=False, download=True, transform=torchvision.transforms.ToTensor() ), batch_size=self.hparams.batch_size, shuffle=False, num_workers=self.hparams.num_workers, pin_memory=True, collate_fn=collate_fn ) def val_dataloader(self): return self.test_dataloader() """ Explanation: PyTorch Lightning AutoEncoder An autoencoder is simply an encoder and a decoder. The encoder extracts the feature vector from the input image. The decoder reconstructs the input image from the feature vector. The feature vector is the compressed representation of the input image. Our PL module can also perform denoising. Below, we also present the collate function for clean and noisy images. To generate noisy images, we apply a Gaussian noise with mean of 0.5 and a standard deviation of 0.5. End of explanation """ def get_args(): parser = ArgumentParser(description="PyTorch Lightning AE MNIST Example") parser.add_argument("--max-epochs", type=int, default=30, help="num epochs") parser.add_argument("--batch-size", type=int, default=64, help="batch size") parser.add_argument("--lr", type=float, default=0.001, help="learning rate") parser.add_argument("--feature-dim", type=int, default=2, help="ae feature dimension") # if denoise is true parser.add_argument("--denoise", action="store_true", help="train a denoising AE") parser.add_argument("--devices", default=1) parser.add_argument("--accelerator", default='gpu') parser.add_argument("--num-workers", type=int, default=4, help="num workers") args = parser.parse_args("") return args """ Explanation: Arguments The arguments are as in our previous examples. The only new argument is feature_dim. This is the size of the latent vector. To use the denoising autoencoder, we also need to set denoise to True. End of explanation """ class WandbCallback(Callback): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): # process first 10 images of the first batch if batch_idx == 0: x, _ = batch n = 10 outputs = outputs["x_tilde"] columns = ['image'] if pl_module.denoise: columns += ['denoised'] key = "mnist-ae-denoising" else: columns += ["reconstruction"] key = "mnist-ae-reconstruction" data = [[wandb.Image(x_i), wandb.Image(x_tilde_i)] for x_i, x_tilde_i in list(zip(x[:n], outputs[:n]))] wandb_logger.log_table(key=key, columns=columns, data=data) """ Explanation: Weights and Biases Callback The callback logs train and validation metrics to wandb. It also logs sample predictions. This is similar to our WandbCallback example for MNIST. End of explanation """ if __name__ == "__main__": args = get_args() ae = LitAEMNISTModel(feature_dim=args.feature_dim, lr=args.lr, batch_size=args.batch_size, num_workers=args.num_workers, denoise=args.denoise, max_epochs=args.max_epochs) ae.setup() wandb_logger = WandbLogger(project="ae-mnist") start_time = time.time() trainer = Trainer(accelerator=args.accelerator, devices=args.devices, max_epochs=args.max_epochs, logger=wandb_logger, callbacks=[WandbCallback()]) trainer.fit(ae) elapsed_time = time.time() - start_time print("Elapsed time: {}".format(elapsed_time)) wandb.finish() # decoder as a generative model import matplotlib.pyplot as plt decoder = ae.decoder decoder.eval() with torch.no_grad(): # generate a tensor of random noise with size 1, feature_dim x_in = torch.randn(1, args.feature_dim) x_tilde = decoder.forward(x_in) plt.imshow(x_tilde[0].detach().numpy().reshape(28, 28), cmap="gray") plt.axis('off') plt.show() """ Explanation: Training an AE We train the autoencoder on the MNIST dataset. For simple reconstruction, the input image is also the target image. For denoising, the input is the noisy image while the target is the clean image. The results can be viewed on wandb. End of explanation """
google-aai/sc17
cats/step_0_to_0.ipynb
apache-2.0
print('Hello world!') """ Explanation: Let's Get Started With Data Science, World! Author(s): kozyr@google.com Reviewer(s): nrh@google.com It's a beautiful day and we can do all kinds of pretty things. Here are some little examples to get you started. Print: ...something End of explanation """ import numpy as np n = 20 intercept = -10 slope = 5 noise = 10 error = np.random.normal(0, noise, 20) x = np.array(range(n)) y = intercept + slope * x + error print(x) print(np.round(y, 2)) """ Explanation: Numpy: make some noise! numpy is the essential package for working with numbers. Simulate some noise and make a straight line. End of explanation """ import pandas as pd df = pd.DataFrame({'feature': x, 'label': y}) print(df) """ Explanation: Pandas: not just for chewing bamboo pandas is the essential package for working with dataframes. Make a convenient dataframe for using our feature to predict our label. End of explanation """ import seaborn as sns %matplotlib inline sns.regplot(x='feature', y='label', data=df) %matplotlib inline sns.distplot(error, axlabel='residuals') %matplotlib inline sns.jointplot(x='feature', y='label', data=df) """ Explanation: Seaborn: pretty plotting A picture is worth a thousand numbers. seaborn puts some glamour in your plotting style. End of explanation """ import tensorflow as tf c = tf.constant('Hello, world!') with tf.Session() as sess: print sess.run(c) """ Explanation: TensorFlow: built for speed tensorflow is the essential package for training neural networks efficiently at scale. In order to be efficient at scale, it only runs when it's required to. Let's ask it to greet us... End of explanation """ from tensorflow.python.client import device_lib def get_devices(): devices = device_lib.list_local_devices() return [x.name for x in devices] print(get_devices()) """ Explanation: Finally, let's greet our tensorflow supported devices! Say hello to our CPU, and our GPU if we invited it to the party! End of explanation """
joshnsolomon/phys202-2015-work
assignments/assignment05/MatplotlibEx03.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np """ Explanation: Matplotlib Exercise 3 Imports End of explanation """ def well2d(x, y, nx, ny, L=1.0): """Compute the 2d quantum well wave function.""" xcoord, ycoord = np.meshgrid(x,y) xpor = np.sin((nx*np.pi*xcoord)/L) ypor = np.sin((ny*np.pi*ycoord)/L) psi = (2/L)*xpor*ypor return psi print(well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1)) psi = well2d(np.linspace(0,1,10), np.linspace(0,1,10), 1, 1) assert len(psi)==10 assert psi.shape==(10,10) """ Explanation: Contour plots of 2d wavefunctions The wavefunction of a 2d quantum well is: $$ \psi_{n_x,n_y}(x,y) = \frac{2}{L} \sin{\left( \frac{n_x \pi x}{L} \right)} \sin{\left( \frac{n_y \pi y}{L} \right)} $$ This is a scalar field and $n_x$ and $n_y$ are quantum numbers that measure the level of excitation in the x and y directions. $L$ is the size of the well. Define a function well2d that computes this wavefunction for values of x and y that are NumPy arrays. End of explanation """ psi = well2d(np.linspace(0,1,100),np.linspace(0,1,100),3,2,1.0) plt.figure(figsize=(10,7)) plt.contourf(np.linspace(0,1,100),np.linspace(0,1,100),psi,cmap='gist_rainbow') plt.xlim(0,1) plt.ylim(0,1) plt.colorbar() assert True # use this cell for grading the contour plot """ Explanation: The contour, contourf, pcolor and pcolormesh functions of Matplotlib can be used for effective visualizations of 2d scalar fields. Use the Matplotlib documentation to learn how to use these functions along with the numpy.meshgrid function to visualize the above wavefunction: Use $n_x=3$, $n_y=2$ and $L=0$. Use the limits $[0,1]$ for the x and y axis. Customize your plot to make it effective and beautiful. Use a non-default colormap. Add a colorbar to you visualization. First make a plot using one of the contour functions: End of explanation """ plt.figure(figsize=(10,7)) plt.pcolor(np.linspace(0,1,100),np.linspace(0,1,100),psi,cmap='rainbow') plt.xlim(0,1) plt.ylim(0,1) plt.colorbar() assert True # use this cell for grading the pcolor plot """ Explanation: Next make a visualization using one of the pcolor functions: End of explanation """
ogaway/Matching-Market
matching.ipynb
gpl-3.0
# coding: UTF-8 %matplotlib inline from matching import * from matching_simu import * """ Explanation: Matching Market Table of Contents ・One-to-One Matching ・Many-to-One Matching ・Modeling Simulation Import a class, Matching() from matching.py. End of explanation """ prop_prefs = [[1, 0, 2], [0, 1, 2], [0, 1, 2]] resp_prefs = [[0, 2, 1], [1, 0, 2], [1, 0, 2]] M1 = Matching(prop_prefs, resp_prefs) prop_matched, resp_matched = M1.DA() prop_matched resp_matched M1.summary() M1.graph() """ Explanation: One-to-One Matching 1) Deffered Acceptance Based on this wiki. End of explanation """ prop_matched, resp_matched = M1.TTC() prop_matched resp_matched M1.summary() M1.graph() """ Explanation: 2) Top Trading Cycle Initial settings are the same as the above. End of explanation """ prop_matched, resp_matched = M1.BS() prop_matched resp_matched M1.summary() M1.graph() """ Explanation: 3) The Boston Public Schools System Initial settings are the same as the above. End of explanation """ prop_prefs = [[1, 2, 0], [2, 0, 1], [2, 1, 0], [2, 0, 1]] resp_prefs = [[3, 2, 1, 0], [2, 1, 3, 0], [0, 1, 3, 2]] caps = [1, 2, 2] M2 = Matching(prop_prefs, resp_prefs, caps) """ Explanation: Many-to-One Matching Assume that the number of students is 4, that of laboratories is 3 and each laboratory has a capacity. End of explanation """ prop_matched, resp_matched, indptr = M2.DA() prop_matched resp_matched indptr M2.summary() M2.graph() """ Explanation: 1) Deffered Acceptance End of explanation """ prop_matched, resp_matched, indptr = M2.TTC() prop_matched resp_matched indptr M2.summary() M2.graph() """ Explanation: 2) Top Trading Cycle Initial settings are the same as the above. End of explanation """ prop_matched, resp_matched, indptr = M2.BS() prop_matched resp_matched indptr M2.graph() """ Explanation: 3) The Boston Public Schools System Initial settings are the same as the above. End of explanation """ caps_list = [5, 7, 9, 11, 13, 15] aves_DA = simulate(caps_list, 'DA') aves_TTC = simulate(caps_list, 'TTC') aves_BS = simulate(caps_list, 'BS') aves_DA aves_TTC aves_BS plt.plot(caps_list, aves_DA, label="DA") plt.plot(caps_list, aves_TTC, label="TTC") plt.plot(caps_list, aves_BS, label="BS") plt.title('Compare the mechanisms') plt.xlim(5, 15) plt.ylim(1, 5) plt.xlabel('Capacity') plt.ylabel('Average Rank') plt.legend(loc=1) plt.show() """ Explanation: Modeling Simulation Utility Function for the i-th student is given as follows. $U_{i} = \alpha CV_{j} + (1-\alpha) PV_{ij}$ $CV_{j}$ means a common value to the j-th laboratory. $PV_{ij}$ means the i-th student's private value to the j-th laboratory. These are uniformly distributed over [0, 1). $\alpha$ is a parameter, default set is 0.8. Suppose that the preferences of the students are decided by this utility function, and the number of students is 100, that of laboratories is 20. Simulate 3000 times at each capacity and return an average rank. End of explanation """
sud218/ml-graphlab-boilerplate
notebooks/01 - Getting started with GraphLab and SFrame.ipynb
mit
import graphlab as gl """ Explanation: Fire up GraphLab create End of explanation """ sf = gl.SFrame('data/people-example.csv') """ Explanation: Load a tabular dataset SFrame is a tabular, column-mutable dataframe object that can scale to big data. The data in SFrame is stored column-wise, and is stored on persistent storage (e.g. disk) to avoid being constrained by memory size. Each column in an SFrame is a size-immutable SArray, but SFrames are mutable in that columns can be added and subtracted with ease. An SFrame essentially acts as an ordered dict of SArrays. End of explanation """ sf # we can view first few lines of the table sf.head() sf.tail() """ Explanation: SFrame basics End of explanation """ sf['Country'] sf['age'].mean() """ Explanation: Inspect Dataset End of explanation """ sf sf['Full Name'] = sf['First Name'] + ' ' + sf['Last Name'] sf """ Explanation: Creating new columns End of explanation """ sf['Country'] def transform_country(country): return 'United States' if country == 'USA' else country transform_country('USA') transform_country('India') sf['Country'] = sf['Country'].apply(transform_country) sf """ Explanation: Apply Function for Data transformation End of explanation """
hpcarcher/2015-12-14-Portsmouth-students
ScientificPython/L02-numpy/L02_NumPy.ipynb
gpl-2.0
# calculate pi import numpy as np # N : number of iterations def calc_pi(N): x = np.random.ranf(N); y = np.random.ranf(N); r = np.sqrt(x*x + y*y); c=r[ r <= 1.0 ] return 4*float((c.size))/float(N) # time the results pts = 6; N = np.logspace(1,8,num=pts); result = np.zeros(pts); count = 0; for n in N: result = %timeit -o -n1 calc_pi(n) result[count] = result.best count += 1 # and save results to file np.savetxt('calcpi_timings.txt', np.c_[N,results], fmt='%1.4e %1.6e'); """ Explanation: <hr style="border: solid 1px red; margin-bottom: -1% "> NumPy <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; background-color:transparent;"> <hr style="border: solid 1px red; margin-top: 1.5% "> Kevin Stratford &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<a style="color: blue">kevin@epcc.ed.ac.uk</a><br> Emmanouil Farsarakis &nbsp; &nbsp; <a style="color: blue">farsarakis@epcc.ed.ac.uk</a><br><br> Other course authors: <br> Neelofer Banglawala <br> Andy Turner <br> Arno Proeme <br> <hr style="border: solid 1px red; margin-bottom: 2% "> &nbsp;<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> <img src="reusematerial.png"; style="float: center; width: 90"; > <hr style="border: solid 1px red; margin-bottom: 2% "> &nbsp;<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: 1%; "> <div align="center" style="float: center; color: blue;"> www.archer.ac.uk <br><br> support@archer.ac.uk </div> <div> <img src="epsrclogo.png"; style="float: left; width: 35%; margin-left: 20%; margin-top: 2% "> <img src="nerclogo.png"; style="float: left; width: 25%; margin-left: 5%"> </div> <br><br> <br><br> <div> <img src="craylogo.png"; style="float: left; width: 30%; margin-left: 10%; margin-top: 6% "> <img src="epcclogo.png"; style="float: left; width: 30%; margin-left: 5%; margin-top: 6% " > <img src="ediunilogo.png"; style="float: left; width: 20%; margin-left: 5%; margin-top: 2% " > </div> <br> <br> <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Introducing NumPy <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> Core Python provides lists Lists are slow for many numerical algorithms NumPy provides fast precompiled functions for numerical routines: multidimensional arrays : faster than lists matrices and linear algebra operations random number generation Fourier transforms and much more... https://www.numpy.org/ <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Calculating $\pi$ <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> <img src="montecarlo.png"; style="float: right; width: 40%; margin-right: 2%; margin-top: 0%; margin-bottom: -1%"> If we know the area $A$ of square length $R$, and the area $Q$ of the quarter circle with radius $R$, we can calculate $\pi$ : $ Q/A = \pi R^2/ 4 R^2 $, so $ \pi = 4\,Q/A $ <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Calculating $\pi$ : monte carlo method <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> We can use the <i>monte carlo</i> method to determine areas $A$ and $Q$ and approximate $\pi$. For $N$ iterations randomly generate the coordinates $(x,\,y)$, where $0 \leq \,x,\, y <R$ <br> Calculate distance $ r = x^2 + y^2 $. Check if $(x,\,y)$ lies within radius of circle<br> Check if $ r $ lies within radius $R$ of circle i.e. if $r \leq R $ <br> if yes, add to count for approximating area of circle<br> The numerical approximation of $\pi$ is then : 4 * (count/$N$) <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Calculating $\pi$ : a solution <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> End of explanation """ # import numpy as alias np import numpy as np # create a 1d array with a list a = np.array( [-1,0,1] ); a """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Creating arrays &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # use arrays to create arrays b = np.array( a ); b # use numpy functions to create arrays # arange for arrays, range for lists! a = np.arange( -2, 6, 2 ); a """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Creating arrays &nbsp; II<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # between start, stop, sample step points a = np.linspace(-10, 10, 5); a; # Ex: can you guess these functions do? b = np.zeros(3); print b c = np.ones(3); print c # Ex++: what does this do? Check documentation! h = np.hstack( (a, a, a), 0 ); print h """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Creating arrays &nbsp; III <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # array characteristics such as: print a print a.ndim # dimensions print a.shape # shape print a.size # size print a.dtype # data type # can choose data type a = np.array( [1,2,3], np.int16 ); a.dtype """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Array characteristics <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # multi-dimensional arrays e.g. 2d array or matrix # e.g. list of lists mat = np.array( [[1,2,3], [4,5,6]]); print mat; print mat.size; mat.shape # join arrays along first axis (0) d = np.r_[np.array([1,2,3]), 0, 0, [4,5,6]]; print d; d.shape """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Multi-dimensional arrays &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # join arrays along second axis (1) d = np.c_[np.array([1,2,3]), [4,5,6]]; print d; d.shape # Ex: use r_, c_ with nd (n>1) arrays # Ex: can you guess the shape of these arrays? h = np.array( [1,2,3,4,5,6] ); i = np.array( [[1,1],[2,2],[3,3],[4,4],[5,5],[6,6]] ); j = np.array( [[[1],[2],[3],[4],[5],[6]]] ); k = np.array( [[[[1],[2],[3],[4],[5],[6]]]] ); """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Multi-dimensional arrays &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # reshape 1d arrays into nd arrays original matrix unaffected mat = np.arange(6); print mat print mat.reshape( (3, 2) ) print mat; print mat.size; print mat.shape # can also use the shape, this modifies the original array a = np.zeros(10); print a a.shape = (2,5) print a; print a.shape; """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Reshaping arrays &nbsp; I<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # Ex: what do flatten() and ravel()? # use online documentation, or '?' mat2 = mat.flatten() mat2 = mat.ravel() # Ex: split a martix? Change the cuts and axis values # need help?: np.split? cuts=2; np.split(mat, cuts, axis=0) """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Reshaping arrays &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # Ex: can you guess what these functions do? # np.copyto(b, a); # v = np.vstack( (arr2d, arr2d) ); print v; v.ndim; # c0 = np.concatenate( (arr2d, arr2d), axis=0); c0; # c1 = np.concatenate(( mat, mat ), axis=1); print "c1:", c1; # Ex++: other functions to explore # # stack(arrays[, axis]) # tile(A, reps) # repeat(a, repeats[, axis]) # unique(ar[, return_index, return_inverse, ...]) # trim_zeros(filt[, trim]), fill(scalar) # xv, yv = meshgrid(x,y) """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Functions for you to explore <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # basic indexing and slicing we know from lists a = np.arange(8); print a a[3] # a[start:stop:step] --> [start, stop every step) print a[0:7:2] print a[0::2] # negative indices are valid! # last element index is -1 print a[2:-3:2] """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Accessing arrays &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # basic indexing of a 2d array : take care of each dimension nd = np.arange(12).reshape((4,3)); print nd; print nd[2,2]; print nd[2][2]; # get corner elements 0,2,9,11 print nd[0:4:3, 0:3:2] # Ex: get elements 7,8,10,11 that make up the bottom right corner nd = np.arange(12).reshape((4,3)); print nd; nd[2:4, 1:3] """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Accessing arrays &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # slices are views (like references) # on an array, can change elements nd[2:4, 1:3] = -1; nd # assign slice to a variable to prevent this s = nd[2:4, 1:3]; print nd; s = -1; nd """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Slices and copies &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # Care - simple assignment between arrays # creates references! nd = np.arange(12).reshape((4,3)) md = nd md[3] = 1000 print nd # avoid this by creating distinct copies # using copy() nd = np.arange(12).reshape((4,3)) md = nd.copy() md[3] = 999 print nd """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Slices and copies &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # advanced or fancy indexing lets you do more p = np.array( [[0,1,2], [3,4,5], [6,7,8], [9,10,11]] ); print p rows = [0,0,3,3]; cols = [0,2,0,2]; print p[rows, cols] # Ex: what will this slice look like? m = np.array( [[0,-1,4,20,99], [-3,-5,6,7,-10]] ); print m[[0,1,1,1], [1,0,1,4]]; """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Fancy indexing &nbsp; I<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # can use conditionals in indexing # m = np.array([[0,-1,4,20,99],[-3,-5,6,7,-10]]); m[ m < 0 ] # Ex: can you guess what this does? query: np.sum? y = np.array([[0, 1], [1, 1], [2, 2]]); rowsum = y.sum(1); y[rowsum <= 2, :] # Ex: and this? a = np.arange(10); mask = np.ones(len(a), dtype = bool); mask[[0,2,4]] = False; print mask result = a[mask]; result # Ex: r=np.array([[0,1,2],[3,4,5]]); xp = np.array( [[[1,11],[2,22],[3,33]], [[4,44],[5,55],[6,66]]] ); xp[slice(1), slice(1,3,None), slice(1)]; xp[:1, 1:3:, :1]; print xp[[1,1,1],[1,2,1],[0,1,0]] """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Fancy indexing &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # add an element with insert a = np.arange(6).reshape([2,3]); print a np.append(a, np.ones([2,3]), axis=0) # inserting an array of elements np.insert(a, 1, -10, axis=0) # can use delete, or a boolean mask, to delete array elements a = np.arange(10) np.delete(a, [0,2,4], axis=0) """ Explanation: &nbsp; <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Manipulating arrays <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # vectorization allows element-wise operations (no for loop!) a = np.arange(10).reshape([2,5]); b = np.arange(10).reshape([2,5]); -0.1*a a*b a/(b+1) #.astype(float) """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Vectorization &nbsp; I<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # random floats a = np.random.ranf(10); a # create random 2d int array a = np.random.randint(0, high=5, size=25).reshape(5,5); print a; # generate sample from normal distribution # (mean=0, standard deviation=1) s = np.random.standard_normal((5,5)); s; # Ex: what other ways are there to generate random numbers? # What other distributions can you sample? """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Random number generation <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # easy way to save data to text file pts = 5; x = np.arange(pts); y = np.random.random(pts); # format specifiers: d = int, f = float, e = scientific np.savetxt('savedata.txt', np.c_[x,y], header = 'DATA', footer = 'END', fmt = '%d %1.4f') !cat savedata.txt # One could do ... # p = np.loadtxt('savedata.txt') # ...but much more flexibility with genfromtext p = np.genfromtxt('savedata.txt', skip_header=2, skip_footer=1); p # Ex++: what do numpy.save, numpy.load do ? """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; File IO <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # calculate pi using polynomials # import Polynomial class from numpy.polynomial import Polynomial as poly; num = 100000; denominator = np.arange(num); denominator[3::4] *= -1 # every other odd coefficient is -ve numerator = np.ones(denominator.size); # avoid dividing by zero, drop first element denominator almost = numerator[1:]/denominator[1:]; # make even coefficients zero almost[1::2] = 0 # add back zero coefficient coeffs = np.r_[0,almost]; p = poly(coeffs); 4*p(1) # pi approximation """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Polynomials &nbsp; I<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> Can represent polynomials with the numpy class Polynomial from <i>numpy.polynomial.polynomial</i>. Polynomial([a, b, c, d, e]) is equivalent to $p(x) = a\,+\,b\,x \,+\,c\,x^2\,+\,d\,x^3\,+\,e\,x^4$. <br> For example: Polynomial([1,2,3]) is equivalent to $p(x) = 1\,+\,2\,x \,+\,3\,x^2$ Polynomial([0,1,0,2,0,3]) is equivalent to $p(x) = x \,+\,2\,x^3\,+\,3\,x^5 $ <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Polynomials &nbsp; II<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> Can carry out arithmetic operations on polynomials, as well integrate and differentiate them. Can also use the <i>polynomial</i> package to find a least-squares fit to data. <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Polynomials : calculating $\pi$ &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> The Taylor series expansion for the trigonometric function $\arctan(y)$ is :<br> &nbsp; &nbsp; &nbsp; $\arctan ( y) \, = \,y - \frac{y^3}{3} + \frac{y^5}{5} - \frac{y^7}{7} + \dots $ Now, $\arctan(1) = \frac{\pi}{4} $, so ... &nbsp; &nbsp; &nbsp;$ \pi = 4 \, \big( - \frac{1}{3} + \frac{1}{5} - \frac{1}{7} + ... \big) $ We can represent the series expansion using a numpy Polynomial, with coefficients: <br> $p(x)$ = [0, &nbsp; 1, &nbsp; 0, &nbsp; -1/3, &nbsp; 0, &nbsp; 1/5, &nbsp; 0, &nbsp; -1/7,...], and use it to approximate $\pi$. <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Polynomials : calculating $\pi$ &nbsp; II <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """ # accessing a 2d array nd = np.arange(100).reshape((10,10)) # accessing element of 2d array %timeit -n10000000 -r3 nd[5][5] %timeit -n10000000 -r3 nd[(5,5)] # Ex: multiplying two vectors x=np.arange(10E7) %timeit -n1 -r10 x*x %timeit -n1 -r10 x**2 # Ex++: from the linear algebra package %timeit -n1 -r10 np.dot(x,x) """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Performance &nbsp; I <img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> Python has a convenient timing function called <i><b>timeit</b></i>. Can use this to measure the execution time of small code snippets. To use timeit function import module timeit and use <i><b>timeit.timeit</b></i> or use magic command <b>%timeit</b> in an IPython shell <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Performance &nbsp; II<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> By default, <i>timeit</i>: Takes the best time out of 3 repeat tests (-r) takes the average time for a number of iterations (-n) per repeat In an IPython shell: <i>%timeit &nbsp; <b>-n</b>&lt;iterations&gt; &nbsp; &nbsp;<b>-r</b>&lt;repeats&gt; &nbsp; &nbsp;&lt;code&gt;</i> query %timeit? for more information https://docs.python.org/2/library/timeit.html <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Performance : experiments &nbsp; I<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> Here are some timeit experiments for you to run. End of explanation """ import numpy as np # Ex: range functions and iterating in for loops size = int(1E6); %timeit for x in range(size): x ** 2 # faster than range for very large arrays? %timeit for x in xrange(size): x ** 2 %timeit for x in np.arange(size): x ** 2 %timeit np.arange(size) ** 2 # Ex: look at the calculating pi code # Make sure you understand it. Time the code. """ Explanation: <hr style="border: solid 1px red; margin-bottom: 2% "> [NumPy] &nbsp; Performance : experiments &nbsp; II<img src="headerlogos.png"; style="float: right; width: 25%; margin-right: -1%; margin-top: 0%; margin-bottom: -1%"> <hr style="border: solid 1px red; margin-bottom: -1%; "> &nbsp; End of explanation """
adityaka/misc_scripts
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/03_01/Begin/.ipynb_checkpoints/Creating Series-checkpoint.ipynb
bsd-3-clause
import pandas as pd import numpy as np """ Explanation: Series Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html End of explanation """ my_simple_series = pd.Series(np.random.randn(5), index=['a', 'b', 'c', 'd', 'e']) my_simple_series my_simple_series.index """ Explanation: Create series from NumPy array number of labels in 'index' must be the same as the number of elements in array End of explanation """ Access a series like a NumPy array """ Explanation: Create series from NumPy array, without explicit index End of explanation """ my_dictionary = {'a' : 45., 'b' : -19.5, 'c' : 4444} my_second_series = pd.Series(my_dictionary) my_second_series Access a series like a dictionary """ Explanation: Create series from Python dictionary End of explanation """ pd.Series(my_dictionary, index=['b', 'c', 'd', 'a']) unknown = my_second_series.get('f') type(unknown) """ Explanation: note order in display; same as order in "index" note NaN End of explanation """ pd.Series(5., index=['a', 'b', 'c', 'd', 'e']) """ Explanation: Create series from scalar If data is a scalar value, an index must be provided. The value will be repeated to match the length of index End of explanation """
esa-as/2016-ml-contest
HouMath/Face_classification_HouMath_XGB_03.ipynb
apache-2.0
%matplotlib inline import pandas as pd from pandas.tools.plotting import scatter_matrix import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns import matplotlib.colors as colors import xgboost as xgb import numpy as np from sklearn.metrics import confusion_matrix, f1_score, accuracy_score from classification_utilities import display_cm, display_adj_cm from sklearn.model_selection import GridSearchCV from sklearn.model_selection import validation_curve from sklearn.datasets import load_svmlight_files from sklearn.model_selection import StratifiedKFold from sklearn.datasets import make_classification from xgboost.sklearn import XGBClassifier from scipy.sparse import vstack seed = 123 np.random.seed(seed) import pandas as pd filename = './facies_vectors.csv' training_data = pd.read_csv(filename) training_data.head(10) training_data['Well Name'] = training_data['Well Name'].astype('category') training_data['Formation'] = training_data['Formation'].astype('category') training_data.info() training_data.describe() facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00','#1B4F72', '#2E86C1', '#AED6F1', '#A569BD', '#196F3D'] facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS','WS', 'D','PS', 'BS'] facies_counts = training_data['Facies'].value_counts().sort_index() facies_counts.index = facies_labels facies_counts.plot(kind='bar',color=facies_colors,title='Distribution of Training Data by Facies') sns.heatmap(training_data.corr(), vmax=1.0, square=True) """ Explanation: In this notebook, we mainly utilize extreme gradient boost to improve the prediction model originially proposed in TLE 2016 November machine learning tuotrial. Extreme gradient boost can be viewed as an enhanced version of gradient boost by using a more regularized model formalization to control over-fitting, and XGB usually performs better. Applications of XGB can be found in many Kaggle competitions. Some recommended tutorrials can be found Our work will be orginized in the follwing order: •Background •Exploratory Data Analysis •Data Prepration and Model Selection •Final Results Background The dataset we will use comes from a class excercise from The University of Kansas on Neural Networks and Fuzzy Systems. This exercise is based on a consortium project to use machine learning techniques to create a reservoir model of the largest gas fields in North America, the Hugoton and Panoma Fields. For more info on the origin of the data, see Bohling and Dubois (2003) and Dubois et al. (2007). The dataset we will use is log data from nine wells that have been labeled with a facies type based on oberservation of core. We will use this log data to train a classifier to predict facies types. This data is from the Council Grove gas reservoir in Southwest Kansas. The Panoma Council Grove Field is predominantly a carbonate gas reservoir encompassing 2700 square miles in Southwestern Kansas. This dataset is from nine wells (with 4149 examples), consisting of a set of seven predictor variables and a rock facies (class) for each example vector and validation (test) data (830 examples from two wells) having the same seven predictor variables in the feature vector. Facies are based on examination of cores from nine wells taken vertically at half-foot intervals. Predictor variables include five from wireline log measurements and two geologic constraining variables that are derived from geologic knowledge. These are essentially continuous variables sampled at a half-foot sample rate. The seven predictor variables are: •Five wire line log curves include gamma ray (GR), resistivity logging (ILD_log10), photoelectric effect (PE), neutron-density porosity difference and average neutron-density porosity (DeltaPHI and PHIND). Note, some wells do not have PE. •Two geologic constraining variables: nonmarine-marine indicator (NM_M) and relative position (RELPOS) The nine discrete facies (classes of rocks) are: 1.Nonmarine sandstone 2.Nonmarine coarse siltstone 3.Nonmarine fine siltstone 4.Marine siltstone and shale 5.Mudstone (limestone) 6.Wackestone (limestone) 7.Dolomite 8.Packstone-grainstone (limestone) 9.Phylloid-algal bafflestone (limestone) These facies aren't discrete, and gradually blend into one another. Some have neighboring facies that are rather close. Mislabeling within these neighboring facies can be expected to occur. The following table lists the facies, their abbreviated labels and their approximate neighbors. Facies/ Label/ Adjacent Facies 1 SS 2 2 CSiS 1,3 3 FSiS 2 4 SiSh 5 5 MS 4,6 6 WS 5,7 7 D 6,8 8 PS 6,7,9 9 BS 7,8 Exprolatory Data Analysis After the background intorduction, we start to import the pandas library for some basic data analysis and manipulation. The matplotblib and seaborn are imported for data vislization. End of explanation """ import xgboost as xgb X_train = training_data.drop(['Facies', 'Well Name','Formation','Depth'], axis = 1 ) Y_train = training_data['Facies' ] - 1 dtrain = xgb.DMatrix(X_train, Y_train) train = X_train.copy() train['Facies']=Y_train train.head() """ Explanation: Data Preparation and Model Selection Now we are ready to test the XGB approach, and will use confusion matrix and f1_score, which were imported, as metric for classification, as well as GridSearchCV, which is an excellent tool for parameter optimization. End of explanation """ def accuracy(conf): total_correct = 0. nb_classes = conf.shape[0] for i in np.arange(0,nb_classes): total_correct += conf[i][i] acc = total_correct/sum(sum(conf)) return acc adjacent_facies = np.array([[1], [0,2], [1], [4], [3,5], [4,6,7], [5,7], [5,6,8], [6,7]]) def accuracy_adjacent(conf, adjacent_facies): nb_classes = conf.shape[0] total_correct = 0. for i in np.arange(0,nb_classes): total_correct += conf[i][i] for j in adjacent_facies[i]: total_correct += conf[i][j] return total_correct / sum(sum(conf)) target='Facies' """ Explanation: The accuracy function and accuracy_adjacent function are defined in the following to quatify the prediction correctness. End of explanation """ def modelfit(alg, dtrain, features, useTrainCV=True, cv_fold=10,early_stopping_rounds = 50): if useTrainCV: xgb_param = alg.get_xgb_params() xgb_param['num_class']=9 xgtrain = xgb.DMatrix(train[features].values,label = train[target].values) cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round= alg.get_params()['n_estimators'],nfold=cv_fold, metrics='merror',early_stopping_rounds = early_stopping_rounds) alg.set_params(n_estimators=cvresult.shape[0]) #Fit the algorithm on the data alg.fit(dtrain[features], dtrain[target],eval_metric='merror') #Predict training set: dtrain_prediction = alg.predict(dtrain[features]) dtrain_predprob = alg.predict_proba(dtrain[features])[:,1] #Pring model report print ("\nModel Report") print ("Accuracy : %.4g" % accuracy_score(dtrain[target], dtrain_prediction)) print ("F1 score (Train) : %f" % f1_score(dtrain[target], dtrain_prediction,average='weighted')) feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False) feat_imp.plot(kind='bar',title='Feature Importances') plt.ylabel('Feature Importance Score') features =[x for x in X_train.columns] features """ Explanation: Before processing further, we define a functin which will help us create XGBoost models and perform cross-validation. End of explanation """ from xgboost import XGBClassifier xgb1 = XGBClassifier( learning_rate = 0.1, n_estimators=1000, max_depth=5, min_child_weight=1, gamma = 0, subsample=0.8, colsample_bytree=0.8, objective='multi:softmax', nthread =4, seed = 123, ) modelfit(xgb1, train, features) xgb1 """ Explanation: General Approach for Parameter Tuning We are going to preform the steps as follows: 1.Choose a relatively high learning rate, e.g., 0.1. Usually somewhere between 0.05 and 0.3 should work for different problems. 2.Determine the optimum number of tress for this learning rate.XGBoost has a very usefull function called as "cv" which performs cross-validation at each boosting iteration and thus returns the optimum number of tress required. 3.Tune tree-based parameters(max_depth, min_child_weight, gamma, subsample, colsample_bytree) for decided learning rate and number of trees. 4.Tune regularization parameters(lambda, alpha) for xgboost which can help reduce model complexity and enhance performance. 5.Lower the learning rate and decide the optimal parameters. Step 1:Fix learning rate and number of estimators for tuning tree-based parameters In order to decide on boosting parameters, we need to set some initial values of other parameters. Lets take the following values: 1.max_depth = 5 2.min_child_weight = 1 3.gamma = 0 4.subsample, colsample_bytree = 0.8 : This is a commonly used used start value. 5.scale_pos_weight = 1 Please note that all the above are just initial estimates and will be tuned later. Lets take the default learning rate of 0.1 here and check the optimum number of trees using cv function of xgboost. The function defined above will do it for us. End of explanation """ from sklearn.model_selection import GridSearchCV param_test1={ 'max_depth':range(3,10,2), 'min_child_weight':range(1,6,2) } gs1 = GridSearchCV(xgb1,param_grid=param_test1, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs1.fit(train[features],train[target]) gs1.grid_scores_, gs1.best_params_,gs1.best_score_ param_test2={ 'max_depth':[8,9,10], 'min_child_weight':[1,2] } gs2 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=5, min_child_weight=1, n_estimators=290, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.8),param_grid=param_test2, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs2.fit(train[features],train[target]) gs2.grid_scores_, gs2.best_params_,gs2.best_score_ gs2.best_estimator_ """ Explanation: Step 2: Tune max_depth and min_child_weight End of explanation """ param_test3={ 'gamma':[i/10.0 for i in range(0,5)] } gs3 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, n_estimators=370, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.8),param_grid=param_test3, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs3.fit(train[features],train[target]) gs3.grid_scores_, gs3.best_params_,gs3.best_score_ xgb2 = XGBClassifier( learning_rate = 0.1, n_estimators=1000, max_depth=9, min_child_weight=1, gamma = 0.2, subsample=0.8, colsample_bytree=0.8, objective='multi:softmax', nthread =4, scale_pos_weight=1, seed = seed, ) modelfit(xgb2,train,features) xgb2 """ Explanation: Step 3: Tune gamma End of explanation """ param_test4={ 'subsample':[i/10.0 for i in range(6,10)], 'colsample_bytree':[i/10.0 for i in range(6,10)] } gs4 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, n_estimators=236, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.8),param_grid=param_test4, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs4.fit(train[features],train[target]) gs4.grid_scores_, gs4.best_params_,gs4.best_score_ param_test4b={ 'subsample':[i/10.0 for i in range(5,7)], } gs4b = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, n_estimators=236, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.8),param_grid=param_test4b, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs4b.fit(train[features],train[target]) gs4b.grid_scores_, gs4b.best_params_,gs4b.best_score_ """ Explanation: Step 4:Tune subsample and colsample_bytree End of explanation """ param_test5={ 'reg_alpha':[1e-5, 1e-2, 0.1, 1, 100] } gs5 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, n_estimators=236, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.6),param_grid=param_test5, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs5.fit(train[features],train[target]) gs5.grid_scores_, gs5.best_params_,gs5.best_score_ param_test6={ 'reg_alpha':[0, 0.001, 0.005, 0.01, 0.05] } gs6 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, n_estimators=236, nthread=4, objective='multi:softprob', reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=123,subsample=0.6),param_grid=param_test6, scoring='accuracy', n_jobs=4,iid=False, cv=5) gs6.fit(train[features],train[target]) gs6.grid_scores_, gs6.best_params_,gs6.best_score_ xgb3 = XGBClassifier( learning_rate = 0.1, n_estimators=1000, max_depth=9, min_child_weight=1, gamma = 0.2, subsample=0.6, colsample_bytree=0.8, reg_alpha=0.05, objective='multi:softmax', nthread =4, scale_pos_weight=1, seed = seed, ) modelfit(xgb3,train,features) xgb3 model = XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9, min_child_weight=1, missing=None, n_estimators=122, nthread=4, objective='multi:softprob', reg_alpha=0.05, reg_lambda=1, scale_pos_weight=1, seed=123, silent=True, subsample=0.6) model.fit(X_train, Y_train) xgb.plot_importance(model) """ Explanation: Step 5: Tuning Regularization Parameters End of explanation """ xgb4 = XGBClassifier( learning_rate = 0.01, n_estimators=5000, max_depth=9, min_child_weight=1, gamma = 0.2, subsample=0.6, colsample_bytree=0.8, reg_alpha=0.05, objective='multi:softmax', nthread =4, scale_pos_weight=1, seed = seed, ) modelfit(xgb4,train,features) xgb4 """ Explanation: Step 6: Reducing Learning Rate End of explanation """ # Load data filename = './facies_vectors.csv' data = pd.read_csv(filename) # Change to category data type data['Well Name'] = data['Well Name'].astype('category') data['Formation'] = data['Formation'].astype('category') # Leave one well out for cross validation well_names = data['Well Name'].unique() f1=[] for i in range(len(well_names)): # Split data for training and testing X_train = data.drop(['Facies', 'Formation','Depth'], axis = 1 ) Y_train = data['Facies' ] - 1 train_X = X_train[X_train['Well Name'] != well_names[i] ] train_Y = Y_train[X_train['Well Name'] != well_names[i] ] test_X = X_train[X_train['Well Name'] == well_names[i] ] test_Y = Y_train[X_train['Well Name'] == well_names[i] ] train_X = train_X.drop(['Well Name'], axis = 1 ) test_X = test_X.drop(['Well Name'], axis = 1 ) # Final recommended model based on the extensive parameters search model_final = XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.01, max_delta_step=0, max_depth=9, min_child_weight=1, missing=None, n_estimators=432, nthread=4, objective='multi:softmax', reg_alpha=0.05, reg_lambda=1, scale_pos_weight=1, seed=123, silent=1, subsample=0.6) # Train the model based on training data model_final.fit( train_X , train_Y , eval_metric = 'merror' ) # Predict on the test set predictions = model_final.predict(test_X) # Print report print ("\n------------------------------------------------------") print ("Validation on the leaving out well " + well_names[i]) conf = confusion_matrix( test_Y, predictions, labels = np.arange(9) ) print ("\nModel Report") print ("-Accuracy: %.6f" % ( accuracy(conf) )) print ("-Adjacent Accuracy: %.6f" % ( accuracy_adjacent(conf, adjacent_facies) )) print ("-F1 Score: %.6f" % ( f1_score ( test_Y , predictions , labels = np.arange(9), average = 'weighted' ) )) f1.append(f1_score ( test_Y , predictions , labels = np.arange(9), average = 'weighted' )) facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS', 'WS', 'D','PS', 'BS'] print ("\nConfusion Matrix Results") from classification_utilities import display_cm, display_adj_cm display_cm(conf, facies_labels,display_metrics=True, hide_zeros=True) print ("\n------------------------------------------------------") print ("Final Results") print ("-Average F1 Score: %6f" % (sum(f1)/(1.0*len(f1)))) """ Explanation: Cross Validation Next we use our tuned final model to do cross validation on the training data set. One of the wells will be used as test data and the rest will be the training data. Each iteration, a different well is chosen. End of explanation """ # Load data filename = './facies_vectors.csv' data = pd.read_csv(filename) # Change to category data type data['Well Name'] = data['Well Name'].astype('category') data['Formation'] = data['Formation'].astype('category') # Split data for training and testing X_train_all = data.drop(['Facies', 'Formation','Depth'], axis = 1 ) Y_train_all = data['Facies' ] - 1 X_train_all = X_train_all.drop(['Well Name'], axis = 1) # Final recommended model based on the extensive parameters search model_final = XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=0.8, gamma=0.2, learning_rate=0.01, max_delta_step=0, max_depth=9, min_child_weight=1, missing=None, n_estimators=432, nthread=4, objective='multi:softmax', reg_alpha=0.05, reg_lambda=1, scale_pos_weight=1, seed=123, silent=1, subsample=0.6) # Train the model based on training data model_final.fit(X_train_all , Y_train_all , eval_metric = 'merror' ) # Leave one well out for cross validation well_names = data['Well Name'].unique() f1=[] for i in range(len(well_names)): X_train = data.drop(['Facies', 'Formation','Depth'], axis = 1 ) Y_train = data['Facies' ] - 1 train_X = X_train[X_train['Well Name'] != well_names[i] ] train_Y = Y_train[X_train['Well Name'] != well_names[i] ] test_X = X_train[X_train['Well Name'] == well_names[i] ] test_Y = Y_train[X_train['Well Name'] == well_names[i] ] train_X = train_X.drop(['Well Name'], axis = 1 ) test_X = test_X.drop(['Well Name'], axis = 1 ) #print(test_Y) predictions = model_final.predict(test_X) # Print report print ("\n------------------------------------------------------") print ("Validation on the leaving out well " + well_names[i]) conf = confusion_matrix( test_Y, predictions, labels = np.arange(9) ) print ("\nModel Report") print ("-Accuracy: %.6f" % ( accuracy(conf) )) print ("-Adjacent Accuracy: %.6f" % ( accuracy_adjacent(conf, adjacent_facies) )) print ("-F1 Score: %.6f" % ( f1_score ( test_Y , predictions , labels = np.arange(9), average = 'weighted' ) )) f1.append(f1_score ( test_Y , predictions , labels = np.arange(9), average = 'weighted' )) facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS', 'WS', 'D','PS', 'BS'] print ("\nConfusion Matrix Results") from classification_utilities import display_cm, display_adj_cm display_cm(conf, facies_labels,display_metrics=True, hide_zeros=True) print ("\n------------------------------------------------------") print ("Final Results") print ("-Average F1 Score: %6f" % (sum(f1)/(1.0*len(f1)))) """ Explanation: Model from all data set End of explanation """ # Load test data test_data = pd.read_csv('validation_data_nofacies.csv') test_data['Well Name'] = test_data['Well Name'].astype('category') X_test = test_data.drop(['Formation', 'Well Name', 'Depth'], axis=1) # Predict facies of unclassified data Y_predicted = model_final.predict(X_test) test_data['Facies'] = Y_predicted + 1 # Store the prediction test_data.to_csv('Prediction3.csv') test_data """ Explanation: Use final model to predict the given test data set End of explanation """
NAU-CFL/Python_Learning_Source
reference_notebooks/Notes-06.ipynb
mit
fruit = "pinapple" letter = fruit[1] """ Explanation: Strings String is a Sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: End of explanation """ print(letter) """ Explanation: The second statement selects character number 1 from fruit and assigns it to letter. The expression in brackets is called an index. The index indicates which character in the sequence you want (hence the name). End of explanation """ letter = fruit[0] print(letter) """ Explanation: For most people, the first letter of 'pinapple' is p, not i. But for computer scientists, the index is an offset from the beginning of the string, and the offset of the first letter is zero. End of explanation """ letter = fruit[1.5] """ Explanation: So b is the 0th letter (“zero-eth”) of 'pinapple', a is the 1th letter (“one-eth”), and n is the 2th d(“two-eth”) letter. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get: End of explanation """ fruit = 'banana' len(fruit) """ Explanation: The len function The len is a built-in function that returns the number of characters in a string: End of explanation """ length = len(fruit) fruit[length] fruit[length-1] """ Explanation: If you try to get the last letter in variable fruit, you should use n-1 for last item as in indexing, otherwise you will get an index out of range error. End of explanation """ fruit = 'pinapple' index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 """ Explanation: Alternatively, you can use negative indices, which count backward from the end of the string. The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on. Traversal with a for loop We usually process string one character at a time to make most out of the computations. Going from the first character to the last one is called traversal. We can write a traversal using while loop but it's not really efficient in terms of time spend on writing the code: End of explanation """ for char in fruit: print(char) """ Explanation: This loop traverses the string and displays each letter on a line by itself. The loop condition is index &lt; len(fruit), so when index is equal to the length of the string, the condition is false, and the body of the loop is not executed. The last character accessed is the one with the index len(fruit)-1, which is the last character in the string. Try Yourself! Exercise: Write a function that takes a string as an argument and displays the letters backward, one per line. Another and more pythonic way of writing traversal is with for loops: End of explanation """ prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: print(letter + suffix) """ Explanation: Each time through the loop, the next character in the string is assigned to the variable char. The loop continues until no characters are left. The following example shows how to use concatenation (string addition) and a for loop to generate an abecedarian series (that is, in alphabetical order). In Robert McCloskey’s book MakeWay for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack, and Quack. This loop outputs these names in order: End of explanation """ s = 'Monty Python' print(s[0:5]) print(s[6:12]) """ Explanation: Of course, that’s not quite right because “Ouack” and “Quack” are misspelled. Try Yourself! Exercise: Modify the program to fix this error. String Slices A segment of a string is called a slice. Selecting a slice is similar to selecting a character: End of explanation """ fruit = 'banana' fruit[:3] fruit[3:] """ Explanation: The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. This behavior is counterintuitive, but it might help to imagine the indices pointing between the characters. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string: End of explanation """ fruit = 'banana' fruit[3:3] """ Explanation: If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: End of explanation """ greeting = 'Hello, world!' greeting[0] = 'J' """ Explanation: An empty string contains no characters and has length 0, but other than that, it is the same as any other string. Try Yourself! Exercise: Given that fruit is a string, what does fruit[:] mean? Strings are immutable It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example: End of explanation """ greeting = 'Hello, world!' new_greeting = 'J' + greeting[1:] print(new_greeting) """ Explanation: The “object” in this case is the string and the “item” is the character you tried to assign. For now, an object is the same thing as a value, but we will refine that definition later. An item is one of the values in a sequence. The reason for the error is that strings are immutable, which means you can’t change an existing string. The best you can do is create a new string that is a variation on the original. This example concatenates a new first letter onto a slice of greeting. It has no effect on the original string: End of explanation """ word = 'banana' word.upper() """ Explanation: Searching What does the following function do? Python def find(word, letter): index = 0 while index &lt; len(word): if word[index] == letter: return index index = index + 1 return -1 In a sense, find is the opposite of the [] operator. Instead of taking an index and extracting the corresponding character, it takes a character and finds the index where that character appears. If the character is not found, the function returns -1. This is the first example we have seen of a return statement inside a loop. If word[index] == letter, the function breaks out of the loop and returns immediately. If the character doesn’t appear in the string, the program exits the loop normally and returns -1. This pattern of computation—traversing a sequence and returning when we find what we are looking for—is called a search. Try Yourself! Exercise: Modify find so that it has a third parameter, the index in word where it should start looking. Looping and Counting The following program counts the number of times the letter a appears in a string: Python word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print(count) This program demonstrates another pattern of computation called a counter. The variable count is initialized to 0 and then incremented each time an a is found. When the loop exits, count contains the result—the total number of a’s. Try Yourself! Exercise1: Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments. Exercise2: Rewrite this function so that instead of traversing the string, it uses the three-parameter version of find from the previous section. String Methods A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For example, the method upper takes a string and returns a new string with all uppercase letters: Instead of the function syntax upper(word), it uses the method syntax word.upper(). End of explanation """ word = 'banana' word.find('a') """ Explanation: This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument. A method call is called an invocation; in this case, we would say that we are invoking upper on the word. As it turns out, there is a string method named find that is remarkably similar to the function we wrote: End of explanation """ word.find('na') """ Explanation: In this example, we invoke find on word and pass the letter we are looking for as a parameter. Actually, the find method is more general than our function; it can find substrings, not just characters: End of explanation """ word.find('na', 3) """ Explanation: It can take as a second argument the index where it should start: End of explanation """ name = 'bob' name.find('b', 1, 2) """ Explanation: And as a third argument the index where it should stop: End of explanation """ 'a' in 'Banana' 'seed' in 'banana' """ Explanation: This search fails because b does not appear in the index range from 1 to 2 (not including 2). Try Yourself! Exercise1: There is a string method called count that is similar to the function in the previous exercise. Read the documentation of this method and write an invocation that counts the number of as in 'banana'. The in Operator The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second: End of explanation """ def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) in_both("apples", "oranges") """ Explanation: For example, the following function prints all the letters from word1 that also appear in word2: Python def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) With well-chosen variable names, Python sometimes reads like English. You could read this loop, “for (each) letter in (the first) word, if (the) letter (appears) in (the second) word, print (the) letter.” Here’s what you get if you compare apples and oranges: End of explanation """ if word == 'banana': print('All right, bananas.') """ Explanation: String Comparison The relational operators work on strings. To see if two strings are equal: End of explanation """ if word < 'banana': print('Your word,' + word + ', comes before banana.') elif word > 'banana': print('Your word,' + word + ', comes after banana.') else: print('All right, bananas.') """ Explanation: Other relational operations are useful for putting words in alphabetical order: End of explanation """
simkovic/simkovic.github.io
_ipynb/Skewed Distributions-Overview.ipynb
mit
%pylab inline from scipy import stats np.random.seed(3) from IPython.display import Image import warnings warnings.filterwarnings('ignore') from urllib import urlopen Image(url='http://tiny.cc/tpiaox') """ Explanation: The Trouble with Response Times Recently, I wanted to analyse response times from a visual search task. For me the standard approach of feeding measurements with highly skewed distributions and censored values into Anova is not acceptable. Unfortunately, I found little guidance on how to conduct a Gelman style analysis (Gelman & Shalizie, 2013). There are no instances of say Gamma regression or Weibull regression in BDA or in Gelman & Hill (2007). I took a look at the Bayesian Survival Analysis by Ibrahim, Chen & Sinha (2005). This book treats the relevant models. It presents an overview of the literature, but gives little guidance on how to select an appropriate model. Besides Survival Times are not exactly response times and the lessons from survival analysis may not be applicable here. I did a little research on the Internet and in the psychological literature. I thought it may be useful to share what I learned. This is the first post in series. It gives an overview of the most popular models and the theory and motivation behind them. End of explanation """ for d in range(1,5): plt.figure() f=urlopen('http://tiny.cc/iriaox'%d) D=np.loadtxt(f) y=D[D[:,3]<35,6] y=y[y<30] x=np.linspace(0,30,31) plt.hist(y,bins=x,normed=True,color='c',edgecolor='w'); plt.grid(b=False,axis='x') mlest=stats.lognorm.fit(y) x=np.linspace(0,30,101) plt.plot(x,stats.lognorm.pdf(x,mlest[0],mlest[1],mlest[2])); plt.xlabel('Response Time (Seconds)') plt.ylabel('pdf'); plt.title('subject %d'%d) """ Explanation: Two distributions with positive and negative skew are shown above. They occur frequently in psychological research. The prime example are response times or solution times with positive skew. These arise in experiments where subject hits a key and terminates the trial as soon as he makes a decision. As an example consider the distribution of reaction times from four subjects from one of my studies. The subject was asked to hit a key as soon as he detected a pair of chasing rings among twelve other randomly moving distractors. End of explanation """ ms= range(-10,5,2) for m in ms: x=np.arange(0,10,0.1) y=stats.norm.pdf(x,m,3) y/=y.sum() plt.plot(x,y) plt.legend(ms); """ Explanation: The distributions for fours subjects displayed above are similar in some aspects but vary in other aspects. We are looking for a simple model which would capture the diversity and complexity of the data. The black curve shows one such proposal. Notable feature of these distributions is that response times can only have positive values. This provides a constraint on the shape of the distribution. You can envision a normal distribution which is pushed against the vertical line at $x=0$. However as the probability mass hits the wall it pushed back and acumulates on the positive side. Or we can just cut away the negative values. The result looks like this? End of explanation """ ms= np.linspace(0,0.3,11) for m in ms: x=np.arange(0,20) y=m*np.power(1-m,x) plt.plot(x,y,'o-') plt.legend(ms); """ Explanation: This is a naive approach. The truncated gaussian makes a sharp jump at $x=0$. In the distribution from our subjects we do not see such a jump. The solution times peak around 6-7 seconds and the distribtion goes towards $p(x=0)=0$ in continuous fashion. To obtain better candidates we now explore processes that give rise to skewed distributions in a systematic way. Geometric distribution We start really simple with a discrete distribution. Subject makes a decision at discrete time steps $t=1,2,3,\dots$. At each step the subject solves the task with probability $\beta$. What is the probability that he solves the task at step $\tau$? It is the product of the probabilities at each decision step. The subject has solved the task at step $t$ (with probability $\beta$) and failed to solve the task at all previous steps (with probability $1-\beta$ at each step). Hence $p(t=\tau)=\beta (1-\beta)^{\tau-1}$. This distribution is called geometric. It looks like this End of explanation """ ms= np.linspace(0,0.5,9) for m in ms: x=np.arange(0.1,5,0.1) y=m*np.exp(-m*x) plt.plot(x,y) plt.legend(np.round(ms,2)); """ Explanation: Exponential distribution There are two features that we don't like about the geometric distribution. First the distribution always peeks at $x=0$. We would like to obtain distributions that have mode somewhere $x>0$. Second, the measured reaction times are continuous. Let's get rid of the second problem,first. We derive the continuous analogue of geometric distribution. With no discrete steps we need to think about $\alpha$ as a rate. $\alpha$ then gives the number of decisions per a unit of time. If $\beta=0.8$ per second then $\beta=0.4$ per half of a second and $\beta=60\cdot 0.8 = 48$ per minute. Now consider a case of geometric distribution with $t=6$ and $\beta=0.2$. Then $p(t=6)=0.2 \cdot (0.8)^{5}= 0.655$. We have 5 time steps at which no decision was made. We split each of them into halves. We now have ten time steps where no decision was made. Each time step now has length 0.5 and probability of no decision at each of these steps is $0.8/2=0.4$. Such modification doesn't change $t=0.5\cdot 10 = 1 \cdot5$. However it alters $p(t=6)=0.2 \cdot (0.4)^{10}= 0.0001$. (Why do we choose $0.8/2=0.4$ instead of $\sqrt{0.8}=0.89$? This is because we want to hold the number of non-decision events constant at 5 irrespective of the number of bins. With $0.4$ we distribute 5 non-decisions across 10 bins. With $\sqrt{0.8}$ we would distribute 10 non-decisions across 10 bins.) We can generalize the process of division. The probability of no decision per reduced bin is $\frac{\tau (1-\beta)}{n}$, where $n$ is the number of bins. Then the probability of $\tau$ steps over the reduced bins is $\beta \left(\frac{\tau (1-\beta)}{n}\right)^{n}$ We obtain the exponential distribution by making the bins infinitely small. $$\lim_{n \to \infty} \beta \left(\frac{\tau (1-\beta)}{n}\right)^{n} =\beta e^{-\beta\tau} $$ Here is what the exponential pdf looks like for various parameter values. End of explanation """ b=1.6;a=3 h=stats.expon.rvs(b,size=[10000,a]).sum(1)-a x=np.arange(0,20,0.2) y=stats.erlang.pdf(x-x[1],a,b) plt.hist(h,bins=x,normed=True,color='c',edgecolor='c'); plt.plot(x,y,lw=2) plt.xlim([x[0],x[-1]]); plt.grid(b=False,axis='x') """ Explanation: Gamma distribution Next we would like to obtain distribution that is also capable of curves with mode away from $x=0$. The general strategy for obtaining more flexible distribution is to build a mixture of the simpler ones. In our case we conceive the following process. In order to reach a decision multiple serial stages of the same exponential process need to finish. We draw $\alpha$ samples from an exponential distribution with decision rate $\beta$ and sum them to obtain the total decision time. End of explanation """ x=np.arange(0,30,0.1) for h in [0.8,1.6]: plt.figure() mm=[1,2,4,8,16] for m in mm: plt.plot(x,stats.gamma.pdf(x,a=h,scale=m, loc=5)) plt.legend(1/np.array(mm,dtype='float'),title='beta') plt.title('alpha=%.1f'%h) plt.figure() mm=[0.8,1,1.5,2,3] for m in mm: plt.plot(x,stats.gamma.pdf(x,a=m,scale=3, loc=5)) plt.legend(mm,title='alpha'); plt.title('beta=1/3'); """ Explanation: The resulting distribution is called Erlang distribution. An example of Erlang with $\beta=1.6$ and $\alpha=3$ is depicted above along with the results of a simulation of the underlying multistage proces. For our purposes however Gamma distribution will be more useful. Gamma is a cousin of Erlang. The only difference is that the number of bins $\alpha$ is continuous in Gamma while it is discrete in Erlang. Erlang has the following PDF $$p(t;\beta,\alpha)=\frac{\beta^\alpha}{(\alpha-1)!} t^{\alpha-1} e^{-\beta t}$$ Gamma distribution has PDF. $$p(t;\beta,\alpha)=\frac{ \beta^\alpha}{\Gamma(\alpha)} t^{\alpha-1} e^{-\beta t}$$ The last term is the common heritage from their exponential ancestor. The middle term arises from the combinatorics of summing exponentially distributed variables and is the same for both distributions. The distributions differ only in terms of the normalizing constant. Let's see what Gamma can do. We look how the distribution changes for different parameter values. End of explanation """ for i in range(2): a=[1.6,0.4][i] plt.subplot(2,2,i*2+1) if i==0: plt.title('(beta*t)^alpha');plt.ylabel('alpha>1') else: plt.ylabel('alpha<1') x=np.arange(0,30,0.1) plt.plot(x,np.power(x,a)) plt.subplot(2,2,i*2+2) if i==0: plt.title('pdf') plt.plot(x,a*np.power(x,a)*np.exp(-np.power(x,a))) """ Explanation: We see curves with mode at $x>0$. These are similar to the reponse times from our human subjects. At the same time with Gamma we can create the exponential-like distributions with mode at $x=0$. Although not present in the data for our for subjects, these also do occur in psychological research, for instance in fast detection tasks. Weibull Distribution Gamma distribution is already fine for the purpose of our data set. However, there are further options which can make difference with other datasets. Let's look at these. To do so let's go one step back to the exponential distribution and ask if there is another way to extend it. We chose rate $\beta$ that evolves exponentially the response time. The PDF of Weibull distribution is given by $$\alpha\beta\left(\beta t\right)^{\alpha-1}e^{-(\beta t)^{\alpha}}$$ Parameter $\alpha$ is the new stuff. $\alpha$ is a positive real parameter. The term $(\beta t)^{\alpha}$ is crucial here. If $\alpha>1$ then this term explodes and Weibull loses its tail and the positive skew. On the other hand if $\alpha<1$ then the term increases only slowly and Weibull has a fat tail. (If $\alpha=1$ we obtain exponential distribution.) End of explanation """ x=np.arange(0,30,0.1) for h in [0.8,1.6]: plt.figure() mm=[1,2,4,8,16] for m in mm: plt.plot(x,stats.weibull_min.pdf(x,h,scale=m, loc=5)) plt.legend(1/np.array(mm,dtype='float'),title='beta'); plt.title('alpha=%.1f'%h); plt.figure() mm=[1,1.5,2,3,5] for m in mm: plt.plot(x,stats.weibull_min.pdf(x,m,scale=3, loc=5)) plt.legend(mm,title='alpha'); plt.title('beta=1/3'); """ Explanation: We now do gymnastics. The graphs show that by proper choice of $\alpha$ we can obtain a distribution that is almost symmetric. This is something that Gamma can't do. End of explanation """ from scipy.special import erf def exgausspdf(x,mu=0,sigma=1,beta=1): ''' mu - mean of gaussain sigma - sd of gaussian beta - rate of the exponential distribution ''' a=(1-erf((mu+beta*np.square(sigma)-x)/(np.sqrt(2)*sigma))) return beta/2.*np.exp(beta*(2*mu+beta*np.square(sigma)-2*x)/2.)*a x=np.arange(0,30,0.1) plt.figure() mm=[2,4,6,8,10] for m in mm: plt.plot(x,exgausspdf(x,mu=m,sigma=1,beta=0.25)) plt.legend(mm,title='mu'); plt.title('sigma=1,beta=1/4'); plt.figure() mm=[0,0.25,0.5,1,2,4] for m in mm: plt.plot(x,exgausspdf(x,mu=5,sigma=m,beta=0.25)) plt.legend(mm,title='sigma'); plt.title('mu=5,beta=1/4'); plt.figure() mm=[0.25,0.5,1,2,4] for m in mm: plt.plot(x,exgausspdf(x,mu=5,sigma=1,beta=m)) plt.legend(mm,title='beta'); plt.title('mu=5,sigma=1'); """ Explanation: ExGaussian Distribution We now go back to the exponential distribution and explicitly start with the goal of obtaining a distribution that covers the skew range between the exponential distribution and the normal distribution. The most straightforward way to do this is to build a mixture of two variables $Z=X+Y$ where $X \sim \mathcal{N}(\mu,\sigma)$ and $Y \sim \mathrm{Expon}(\beta)$. Then $Z \sim \mathrm{ExGauss}(\mu,\sigma,\beta)$. It's PDF is given by $$f(x;\mu,\sigma,\beta) = \frac{\beta}{2} \exp\left(\frac{\beta}{2} \left(2 \mu + \beta \sigma^2 - 2 x\right)\right) \operatorname{erfc} \left(\frac{\mu + \beta \sigma^2 - x}{ \sqrt{2} \sigma}\right)$$ End of explanation """ x=np.arange(0,30,0.1) for m in np.arange(1,5,0.4): plt.plot(x,stats.lognorm.pdf(x,1,loc=0,scale=np.exp(m))) plt.legend(np.arange(1,5,0.2),title='mu') plt.title('sigma=1'); plt.figure() for m in np.arange(0.5,1.4,0.1): plt.plot(x,stats.lognorm.pdf(x,m,loc=0,scale=np.exp(2))) plt.legend(np.arange(0.5,1.4,0.1),title='sigma') plt.title('mu=2'); """ Explanation: The effect of parameters on the shape of distribution can be intuited from their respective role as parameters of the gaussian and exponential distribution. $\beta$ and $\sigma$ control the respective contribution of the exponential and gaussian component. As $\sigma \to 0$ Exgaussian reduces to shifted exponential. Exgaussian has three parameters which offers more modeling flexibility than the distributions we reviewed so far. Lognormal Distribution Above we have concentrated on the flexibility afforded the probability distribution of the model. Lognormal Distribution is popular due to its easy use, quick fitting and rather straightforward interpretation of its parameters. $Y$ has lognormal distribution if $X\sim \mathbf{N}(\mu,\sigma)$ and $Y=\log(X)$, where $\mu$ and $\sigma$ are the familiar mean and standard deviation. End of explanation """
michaelgat/Udacity_DL
image-classification/dlnd_image_classification_MG.ipynb
mit
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import problem_unittests as tests import tarfile cifar10_dataset_folder_path = 'cifar-10-batches-py' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile('cifar-10-python.tar.gz'): with DLProgress(unit='B', unit_scale=True, miniters=1, desc='CIFAR-10 Dataset') as pbar: urlretrieve( 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz', 'cifar-10-python.tar.gz', pbar.hook) if not isdir(cifar10_dataset_folder_path): with tarfile.open('cifar-10-python.tar.gz') as tar: tar.extractall() tar.close() tests.test_folder_path(cifar10_dataset_folder_path) """ Explanation: Image Classification In this project, you'll classify images from the CIFAR-10 dataset. The dataset consists of airplanes, dogs, cats, and other objects. You'll preprocess the images, then train a convolutional neural network on all the samples. The images need to be normalized and the labels need to be one-hot encoded. You'll get to apply what you learned and build a convolutional, max pooling, dropout, and fully connected layers. At the end, you'll get to see your neural network's predictions on the sample images. Get the Data Run the following cell to download the CIFAR-10 dataset for python. End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 50 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) """ Explanation: Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog * horse * ship * truck Understanding a dataset is part of making predictions on the data. Play around with the code cell below by changing the batch_id and sample_id. The batch_id is the id for a batch (1-5). The sample_id is the id for a image and label pair in the batch. Ask yourself "What are all possible labels?", "What is the range of values for the image data?", "Are the labels in order or random?". Answers to questions like these will help you preprocess the data and end up with better predictions. End of explanation """ def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ return x / 255 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_normalize(normalize) """ Explanation: Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. End of explanation """ def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ return np.eye(10)[x] # Our own implementation of one hot logic. # return np.array([one_hot_encode_helper(label) for label in x]) one_hot_map = {} def one_hot_encode_helper(x): if x in one_hot_map: return one_hot_map[x] result = np.zeros(10) result[x] = 0 one_hot_map[x] = result return result """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_one_hot_encode(one_hot_encode) """ Explanation: One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 to 9. The one-hot encoding function should return the same encoding for each value between each call to one_hot_encode. Make sure to save the map of encodings outside the function. Hint: Don't reinvent the wheel. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(cifar10_dataset_folder_path, normalize, one_hot_encode) """ Explanation: Randomize Data As you saw from exploring the data above, the order of the samples are randomized. It doesn't hurt to randomize it again, but you don't need to for this dataset. Preprocess all the data and save it Running the code cell below will preprocess all the CIFAR-10 data and save it to file. The code below also uses 10% of the training data for validation. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ import pickle import problem_unittests as tests import helper # Load the Preprocessed Validation data valid_features, valid_labels = pickle.load(open('preprocess_validation.p', mode='rb')) """ Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation """ import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a bach of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return tf.placeholder(tf.float32, [None, image_shape[0],image_shape[1],image_shape[2]], name='x') def neural_net_label_input(n_classes): """ Return a Tensor for a batch of label input : n_classes: Number of classes : return: Tensor for label input. """ # TODO: Implement Function return tf.placeholder(tf.float32, [None, n_classes], name='y') def neural_net_keep_prob_input(): """ Return a Tensor for keep probability : return: Tensor for keep probability. """ # TODO: Implement Function return tf.placeholder(tf.float32, name='keep_prob') """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tf.reset_default_graph() tests.test_nn_image_inputs(neural_net_image_input) tests.test_nn_label_inputs(neural_net_label_input) tests.test_nn_keep_prob_inputs(neural_net_keep_prob_input) """ Explanation: Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittests before you submit your project. If you're finding it hard to dedicate enough time for this course a week, we've provided a small shortcut to this part of the project. In the next couple of problems, you'll have the option to use TensorFlow Layers or TensorFlow Layers (contrib) to build each layer, except "Convolutional & Max Pooling" layer. TF Layers is similar to Keras's and TFLearn's abstraction to layers, so it's easy to pickup. If you would like to get the most of this course, try to solve all the problems without TF Layers. Let's begin! Input The neural network needs to read the image data, one-hot encoded labels, and dropout keep probability. Implement the following functions * Implement neural_net_image_input * Return a TF Placeholder * Set the shape using image_shape with batch size set to None. * Name the TensorFlow placeholder "x" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_label_input * Return a TF Placeholder * Set the shape using n_classes with batch size set to None. * Name the TensorFlow placeholder "y" using the TensorFlow name parameter in the TF Placeholder. * Implement neural_net_keep_prob_input * Return a TF Placeholder for dropout keep probability. * Name the TensorFlow placeholder "keep_prob" using the TensorFlow name parameter in the TF Placeholder. These names will be used at the end of the project to load your saved model. Note: None for shapes in TensorFlow allow for a dynamic size. End of explanation """ def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_strides: Stride 2-D Tuple for convolution :param pool_ksize: kernal size 2-D Tuple for pool :param pool_strides: Stride 2-D Tuple for pool : return: A tensor that represents convolution and max pooling of x_tensor """ # TODO: Implement Function weight = tf.Variable(tf.random_normal([conv_ksize[0], conv_ksize[1], x_tensor.get_shape().as_list()[-1], conv_num_outputs], stddev=0.1)) bias = tf.Variable(tf.zeros(conv_num_outputs, dtype=tf.float32)) conv_layer = tf.nn.conv2d(x_tensor, weight, strides=[1, conv_strides[0], conv_strides[1], 1], padding='SAME') conv_layer = tf.nn.bias_add(conv_layer, bias) conv_layer = tf.nn.relu(conv_layer) conv_layer = tf.nn.max_pool(conv_layer, ksize=[1, pool_ksize[0], pool_ksize[1], 1], strides=[1, pool_strides[0], pool_strides[1], 1], padding='SAME') return conv_layer """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_con_pool(conv2d_maxpool) """ Explanation: Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor using weight and conv_strides. * We recommend you use same padding, but you're welcome to use any padding. * Add bias * Add a nonlinear activation to the convolution. * Apply Max Pooling using pool_ksize and pool_strides. * We recommend you use same padding, but you're welcome to use any padding. Note: You can't use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. You're free to use any TensorFlow package for all the other layers. End of explanation """ def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function # return tf.contrib.layers.flatten(x_tensor) flattened_size = x_tensor.shape[1] * x_tensor.shape[2] * x_tensor.shape[3] return tf.reshape(x_tensor, [-1, flattened_size.value]) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_flatten(flatten) """ Explanation: Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. End of explanation """ def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function # return tf.contrib.layers.fully_connected(x_tensor, num_outputs=num_outputs) num_features = x_tensor.shape[1].value weights = tf.Variable(tf.random_normal([num_features, num_outputs], stddev=0.1)) biases = tf.Variable(tf.zeros([num_outputs])) fc = tf.add(tf.matmul(x_tensor, weights), biases) fc = tf.nn.relu(fc) return fc """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_fully_conn(fully_conn) """ Explanation: Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. End of explanation """ def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """ # TODO: Implement Function # return tf.contrib.layers.fully_connected(x_tensor, num_outputs=num_outputs) num_features = x_tensor.shape[1].value weights = tf.Variable(tf.random_normal([num_features, num_outputs], stddev=0.1)) biases = tf.Variable(tf.zeros([num_outputs])) output_layer = tf.add(tf.matmul(x_tensor, weights), biases) # output_layer = tf.nn.softmax(output_layer) return output_layer """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_output(output) """ Explanation: Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). You can use TensorFlow Layers or TensorFlow Layers (contrib) for this layer. Note: Activation, softmax, or cross entropy shouldn't be applied to this. End of explanation """ def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers # Play around with different number of outputs, kernel size and stride # Function Definition from Above: # conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides) x = conv2d_maxpool(x, 8, (4, 4), (1, 1), (2, 2), (2, 2)) x = conv2d_maxpool(x, 16, (4, 4), (1, 1), (2, 2), (2, 2)) x = conv2d_maxpool(x, 32, (4, 4), (1, 1), (2, 2), (2, 2)) # TODO: Apply a Flatten Layer # Function Definition from Above: # flatten(x_tensor) x = flatten(x) # TODO: Apply 1, 2, or 3 Fully Connected Layers # Play around with different number of outputs # Function Definition from Above: # fully_conn(x_tensor, num_outputs) x = fully_conn(x, 1024) x = tf.nn.dropout(x, keep_prob=keep_prob) x = fully_conn(x, 1024) x = tf.nn.dropout(x, keep_prob=keep_prob) # TODO: Apply an Output Layer # Set this to the number of classes # Function Definition from Above: # output(x_tensor, num_outputs) x = output(x, 10) # TODO: return output return x """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ ############################## ## Build the Neural Network ## ############################## # Remove previous weights, bias, inputs, etc.. tf.reset_default_graph() # Inputs x = neural_net_image_input((32, 32, 3)) y = neural_net_label_input(10) keep_prob = neural_net_keep_prob_input() # Model logits = conv_net(x, keep_prob) # Name logits Tensor, so that is can be loaded from disk after training logits = tf.identity(logits, name='logits') # Loss and Optimizer cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y)) optimizer = tf.train.AdamOptimizer().minimize(cost) # Accuracy correct_pred = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32), name='accuracy') tests.test_conv_net(conv_net) """ Explanation: Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Fully Connected Layers Apply an Output Layer Return the output Apply TensorFlow's Dropout to one or more layers in the model using keep_prob. End of explanation """ def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data """ # TODO: Implement Function session.run(optimizer, feed_dict={x:feature_batch, y:label_batch, keep_prob:keep_probability}) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ tests.test_train_nn(train_neural_network) """ Explanation: Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be called for each batch, so tf.global_variables_initializer() has already been called. Note: Nothing needs to be returned. This function is only optimizing the neural network. End of explanation """ def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy: TensorFlow accuracy function """ # TODO: Implement Function loss = session.run(cost, feed_dict={x:feature_batch, y:label_batch, keep_prob:1.0}) acc = session.run(accuracy, feed_dict={x:valid_features, y:valid_labels, keep_prob:1.0}) print('Loss={0} ValidationAccuracy={1}'.format(loss, acc)) # print("ValidationAccuracy={0}".format(acc)) """ Explanation: Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. End of explanation """ # TODO: Tune Parameters epochs = 35 batch_size = 2048 keep_probability = 0.9 """ Explanation: Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the probability of keeping a node using dropout End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ print('Checking the Training on a Single Batch...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): batch_i = 1 for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) """ Explanation: Train on a Single CIFAR-10 Batch Instead of training the neural network on all the CIFAR-10 batches of data, let's use a single batch. This should save time while you iterate on the model to get a better accuracy. Once the final validation accuracy is 50% or greater, run the model on all the data in the next section. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ save_model_path = './image_classification' print('Training...') with tf.Session() as sess: # Initializing the variables sess.run(tf.global_variables_initializer()) # Training cycle for epoch in range(epochs): # Loop over all batches n_batches = 5 for batch_i in range(1, n_batches + 1): for batch_features, batch_labels in helper.load_preprocess_training_batch(batch_i, batch_size): train_neural_network(sess, optimizer, keep_probability, batch_features, batch_labels) print('Epoch {:>2}, CIFAR-10 Batch {}: '.format(epoch + 1, batch_i), end='') print_stats(sess, batch_features, batch_labels, cost, accuracy) # Save Model saver = tf.train.Saver() save_path = saver.save(sess, save_model_path) """ Explanation: Fully Train the Model Now that you got a good accuracy with a single CIFAR-10 batch, try it with all five batches. End of explanation """ """ DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_classification' n_samples = 4 top_n_predictions = 3 def test_model(): """ Test the saved model against the test dataset """ test_features, test_labels = pickle.load(open('preprocess_test.p', mode='rb')) loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load model loader = tf.train.import_meta_graph(save_model_path + '.meta') loader.restore(sess, save_model_path) # Get Tensors from loaded model loaded_x = loaded_graph.get_tensor_by_name('x:0') loaded_y = loaded_graph.get_tensor_by_name('y:0') loaded_keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') loaded_logits = loaded_graph.get_tensor_by_name('logits:0') loaded_acc = loaded_graph.get_tensor_by_name('accuracy:0') # Get accuracy in batches for memory limitations test_batch_acc_total = 0 test_batch_count = 0 for train_feature_batch, train_label_batch in helper.batch_features_labels(test_features, test_labels, batch_size): test_batch_acc_total += sess.run( loaded_acc, feed_dict={loaded_x: train_feature_batch, loaded_y: train_label_batch, loaded_keep_prob: 1.0}) test_batch_count += 1 print('Testing Accuracy: {}\n'.format(test_batch_acc_total/test_batch_count)) # Print Random Samples random_test_features, random_test_labels = tuple(zip(*random.sample(list(zip(test_features, test_labels)), n_samples))) random_test_predictions = sess.run( tf.nn.top_k(tf.nn.softmax(loaded_logits), top_n_predictions), feed_dict={loaded_x: random_test_features, loaded_y: random_test_labels, loaded_keep_prob: 1.0}) helper.display_image_predictions(random_test_features, random_test_labels, random_test_predictions) test_model() """ Explanation: Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters. End of explanation """
tpin3694/tpin3694.github.io
machine-learning/pipelines_with_parameter_optimization.ipynb
mit
# Import required packages import numpy as np from sklearn import linear_model, decomposition, datasets from sklearn.pipeline import Pipeline from sklearn.model_selection import GridSearchCV, cross_val_score from sklearn.preprocessing import StandardScaler """ Explanation: Title: Pipelines With Parameter Optimization Slug: pipelines_with_parameter_optimization Summary: Pipelines with parameter optimization using scikit-learn. Date: 2016-12-01 12:00 Category: Machine Learning Tags: Model Selection Authors: Chris Albon Preliminaries End of explanation """ # Load the breast cancer data dataset = datasets.load_breast_cancer() # Create X from the dataset's features X = dataset.data # Create y from the dataset's output y = dataset.target """ Explanation: Load Data End of explanation """ # Create an scaler object sc = StandardScaler() # Create a pca object pca = decomposition.PCA() # Create a logistic regression object with an L2 penalty logistic = linear_model.LogisticRegression() # Create a pipeline of three steps. First, standardize the data. # Second, tranform the data with PCA. # Third, train a logistic regression on the data. pipe = Pipeline(steps=[('sc', sc), ('pca', pca), ('logistic', logistic)]) """ Explanation: Create Pipelines End of explanation """ # Create a list of a sequence of integers from 1 to 30 (the number of features in X + 1) n_components = list(range(1,X.shape[1]+1,1)) # Create a list of values of the regularization parameter C = np.logspace(-4, 4, 50) # Create a list of options for the regularization penalty penalty = ['l1', 'l2'] # Create a dictionary of all the parameter options # Note has you can access the parameters of steps of a pipeline by using '__’ parameters = dict(pca__n_components=n_components, logistic__C=C, logistic__penalty=penalty) """ Explanation: Create Parameter Space End of explanation """ # Create a grid search object clf = GridSearchCV(pipe, parameters) # Fit the grid search clf.fit(X, y) # View The Best Parameters print('Best Penalty:', clf.best_estimator_.get_params()['logistic__penalty']) print('Best C:', clf.best_estimator_.get_params()['logistic__C']) print('Best Number Of Components:', clf.best_estimator_.get_params()['pca__n_components']) """ Explanation: Conduct Parameter Optmization With Pipeline End of explanation """ # Fit the grid search using 3-Fold cross validation cross_val_score(clf, X, y) """ Explanation: Use Cross Validation To Evaluate Model End of explanation """
amadeuspzs/travelTime
travelTime.ipynb
mit
import urllib, json, time """ Explanation: travelTime Source realtime travel data from Google Maps End of explanation """ apiKey="" if not apiKey: print "Enter your API key for traffic data!" exit(1) """ Explanation: Enter your Google Maps Directions API key below: End of explanation """ origin="Empire State Building, NY" destination="One World Trade Center, NY" """ Explanation: Enter your origin and destination: End of explanation """ params = urllib.urlencode( {'origin': origin, 'destination': destination, 'mode': 'driving', 'key': apiKey, 'departure_time':'now'}) url = "https://maps.googleapis.com/maps/api/directions/json?%s" % params timestamp = int(time.time()) # capture when the request is made try: response = urllib.urlopen(url) except IOError, e: print e if response.getcode() == 200: data = json.loads(response.read()) else: print "Error %s" % response.getcode() exit(1) """ Explanation: Try to grab realtime traffic from Google: End of explanation """ if 'error_message' in data: print data['error_message'] exit(1) if not 'routes' in data or len(data['routes']) < 1: print "Route data not returned. Check locations?" exit(1) elif not 'duration_in_traffic' in data['routes'][0]['legs'][0]: print "Traffic data not returned" exit(1) else: print "%s,%s" % (timestamp, data['routes'][0]['legs'][0]['duration_in_traffic']['value']) """ Explanation: Process response data End of explanation """
hanhanwu/Hanhan_Data_Science_Practice
sequencial_analysis/CPT_poem_generator.ipynb
mit
from CPT import * import pandas as pd sample_poem = open('sample_sonnets.txt').read().lower().replace('\n', '') # smaller data sample all_poem = open('sonnets.txt').read().lower().replace('\n', '') # larger data sample def generate_char_seq(whole_str, n): """ Generate a dataframe, each row contains a sequence with length n. Next sequence is 1 character of the previous sequence. param: whole_str: original text in string format param: n: the length of each sequence return: a dataframe that contains all the sequences. """ dct = {} idx = 0 # the index of the dataframe, the key of each key-value in the dictionary for i in range(len(whole_str)-n): sub_str = whole_str[i:i+n] dct[idx] = {} for j in range(n): dct[idx][j] = sub_str[j] idx += 1 df = pd.DataFrame(dct) return df """ Explanation: CPT Poem Generator How to use CPT In your terminal, type git clone https://github.com/NeerajSarwan/CPT.git to download CPT If you don't have git, download and install it. After download CPT, type cd CPT to enter into the folder You code should be created under this file, so that you can run the code below. Python CPT open source: https://github.com/NeerajSarwan/CPT/blob/master/CPT.py Poem Generation Methods with CPT Character based poem generation Word based poem generation To compare with LSTM poem generator: https://github.com/hanhanwu/Hanhan_Data_Science_Practice/blob/master/sequencial_analysis/try_poem_generator.ipynb Download the sonnets text from : https://github.com/pranjal52/text_generators/blob/master/sonnets.txt End of explanation """ # I'm using 410 character sequence to train train_seq_len = 410 training_df = generate_char_seq(sample_poem, train_seq_len).T training_df.head() # The testing data will use 20 characters, and I only choose 7 seperate rows from all sequences. ## The poem output will try to predict characters based on the 20 characters in each row, 7 rows in total test_seq_len = 20 all_testing_df = generate_char_seq(sample_poem, test_seq_len).T testing_df = all_testing_df.iloc[[77, 99, 177, 199, 277, 299, 410],:] testing_df.head() # This python open source has a bit weird model input requirement, so I will use its own functions to load the data. training_df.to_csv("train.csv", index=False) testing_df.to_csv("test.csv") model = CPT() train, test = model.load_files("train.csv", "test.csv") model.train(train) predict_len = 10 predictions = model.predict(train,test,test_seq_len,predict_len) predictions """ Explanation: Method 1 Part 1 - Character Based Poem Generator (Smaller Sample Data) End of explanation """ for i in range(testing_df.shape[0]): all_char_lst = testing_df.iloc[i].tolist() all_char_lst.append(' ') all_char_lst.extend(predictions[i]) print(''.join(all_char_lst)) """ Explanation: Generate the poem End of explanation """ # I'm using 410 character sequence to train train_seq_len = 410 training_df = generate_char_seq(all_poem, train_seq_len).T training_df.head() # The testing data will use 30 characters, and I only choose 10 seperate rows from all sequences. ## The poem output will try to predict characters based on the 20 characters in each row, 10 rows in total test_seq_len = 30 all_testing_df = generate_char_seq(all_poem, test_seq_len).T testing_df = all_testing_df.iloc[[1,2,3,4,5,77, 99, 177, 199, 277, 299, 410],:] testing_df.head() training_df.to_csv("all_train.csv", index=False) testing_df.to_csv("all_test.csv") model = CPT() train, test = model.load_files("all_train.csv", "all_test.csv") model.train(train) predict_len = 10 # predict the next 10 characters predictions = model.predict(train,test,test_seq_len,predict_len) """ Explanation: Obseravtion The data size is very smaller here. But comparing with LSTM poem generation, CPT is much much faster, and the output is more descent than LSTM results. Method 1 Part 2 - Character Based Poem Generator (Larger Sample Data) End of explanation """ for i in range(testing_df.shape[0]): all_char_lst = testing_df.iloc[i].tolist() all_char_lst.append(' ') all_char_lst.extend(predictions[i]) print(''.join(all_char_lst)) """ Explanation: Generate the poem End of explanation """ all_words = all_poem.split() print(len(all_words)) # With selected sequence length to train train_seq_len = 1000 training_df = generate_char_seq(all_words, train_seq_len).T training_df.head() # The testing data will use 20 words, and I only choose 10 seperate rows from all sequences. ## The poem output will try to predict characters based on the 20 characters in each row, 10 rows in total test_seq_len = 20 output_poem_rows = 10 all_testing_df = generate_char_seq(all_words, test_seq_len).T selected_row_idx_lst = [train_seq_len*i for i in range(output_poem_rows)] testing_df = all_testing_df.iloc[selected_row_idx_lst,:] testing_df.head() training_df.to_csv("all_train_words.csv", index=False) testing_df.to_csv("all_test_words.csv") model = CPT() train, test = model.load_files("all_train_words.csv", "all_test_words.csv") model.train(train) predict_len = 10 # predict the next 10 words predictions = model.predict(train,test,test_seq_len,predict_len) """ Explanation: Observations At the very beginning, I tried to generate poem with selected 7 rows, each row uses 20 characters to predict the next 10 characters. It gave exactly the same output as smaller data sample output. This may indicate that, when the selected testing data is very very small and tend to be unique in the training data, smaller data inout is enough to get the results. Then I changed to 12 rows, each row uses 30 characters to predict the next 10 character. The first 5 rows came from continuous rows, which means the next row is 1 character shift from its previous row. If you check their put, although cannot say accurate, but the 5 rows has similar prediction. I think CPT can be more accurate when there are repeated sub-sequences appeared in the training data, because the algorithm behind CPT is prediction tree + inverted index + lookup table, similar to FP-growth in transaction prediction, more repeat more accurate. Method 2 - Word Based Poem Generation End of explanation """ for i in range(testing_df.shape[0]): all_char_lst = testing_df.iloc[i].tolist() all_char_lst.extend(predictions[i]) print(' '.join(all_char_lst)) """ Explanation: Generate the poem End of explanation """
steinam/teacher
jup_notebooks/data-science-ipython-notebooks-master/scipy/effect_size.ipynb
mit
from __future__ import print_function, division import numpy import scipy.stats import matplotlib.pyplot as pyplot from IPython.html.widgets import interact, fixed from IPython.html import widgets # seed the random number generator so we all get the same results numpy.random.seed(17) # some nice colors from http://colorbrewer2.org/ COLOR1 = '#7fc97f' COLOR2 = '#beaed4' COLOR3 = '#fdc086' COLOR4 = '#ffff99' COLOR5 = '#386cb0' %matplotlib inline """ Explanation: Effect Size Credits: Forked from CompStats by Allen Downey. License: Creative Commons Attribution 4.0 International. End of explanation """ mu1, sig1 = 178, 7.7 male_height = scipy.stats.norm(mu1, sig1) mu2, sig2 = 163, 7.3 female_height = scipy.stats.norm(mu2, sig2) """ Explanation: To explore statistics that quantify effect size, we'll look at the difference in height between men and women. I used data from the Behavioral Risk Factor Surveillance System (BRFSS) to estimate the mean and standard deviation of height in cm for adult women and men in the U.S. I'll use scipy.stats.norm to represent the distributions. The result is an rv object (which stands for random variable). End of explanation """ def eval_pdf(rv, num=4): mean, std = rv.mean(), rv.std() xs = numpy.linspace(mean - num*std, mean + num*std, 100) ys = rv.pdf(xs) return xs, ys """ Explanation: The following function evaluates the normal (Gaussian) probability density function (PDF) within 4 standard deviations of the mean. It takes and rv object and returns a pair of NumPy arrays. End of explanation """ xs, ys = eval_pdf(male_height) pyplot.plot(xs, ys, label='male', linewidth=4, color=COLOR2) xs, ys = eval_pdf(female_height) pyplot.plot(xs, ys, label='female', linewidth=4, color=COLOR3) pyplot.xlabel('height (cm)') None """ Explanation: Here's what the two distributions look like. End of explanation """ male_sample = male_height.rvs(1000) female_sample = female_height.rvs(1000) """ Explanation: Let's assume for now that those are the true distributions for the population. Of course, in real life we never observe the true population distribution. We generally have to work with a random sample. I'll use rvs to generate random samples from the population distributions. Note that these are totally random, totally representative samples, with no measurement error! End of explanation """ mean1, std1 = male_sample.mean(), male_sample.std() mean1, std1 """ Explanation: Both samples are NumPy arrays. Now we can compute sample statistics like the mean and standard deviation. End of explanation """ mean2, std2 = female_sample.mean(), female_sample.std() mean2, std2 """ Explanation: The sample mean is close to the population mean, but not exact, as expected. End of explanation """ difference_in_means = male_sample.mean() - female_sample.mean() difference_in_means # in cm """ Explanation: And the results are similar for the female sample. Now, there are many ways to describe the magnitude of the difference between these distributions. An obvious one is the difference in the means: End of explanation """ # Exercise: what is the relative difference in means, expressed as a percentage? relative_difference = difference_in_means / male_sample.mean() relative_difference * 100 # percent """ Explanation: On average, men are 14--15 centimeters taller. For some applications, that would be a good way to describe the difference, but there are a few problems: Without knowing more about the distributions (like the standard deviations) it's hard to interpret whether a difference like 15 cm is a lot or not. The magnitude of the difference depends on the units of measure, making it hard to compare across different studies. There are a number of ways to quantify the difference between distributions. A simple option is to express the difference as a percentage of the mean. End of explanation """ relative_difference = difference_in_means / female_sample.mean() relative_difference * 100 # percent """ Explanation: But a problem with relative differences is that you have to choose which mean to express them relative to. End of explanation """ simple_thresh = (mean1 + mean2) / 2 simple_thresh """ Explanation: Part Two An alternative way to express the difference between distributions is to see how much they overlap. To define overlap, we choose a threshold between the two means. The simple threshold is the midpoint between the means: End of explanation """ thresh = (std1 * mean2 + std2 * mean1) / (std1 + std2) thresh """ Explanation: A better, but slightly more complicated threshold is the place where the PDFs cross. End of explanation """ male_below_thresh = sum(male_sample < thresh) male_below_thresh """ Explanation: In this example, there's not much difference between the two thresholds. Now we can count how many men are below the threshold: End of explanation """ female_above_thresh = sum(female_sample > thresh) female_above_thresh """ Explanation: And how many women are above it: End of explanation """ overlap = male_below_thresh / len(male_sample) + female_above_thresh / len(female_sample) overlap """ Explanation: The "overlap" is the total area under the curves that ends up on the wrong side of the threshold. End of explanation """ misclassification_rate = overlap / 2 misclassification_rate """ Explanation: Or in more practical terms, you might report the fraction of people who would be misclassified if you tried to use height to guess sex: End of explanation """ # Exercise: suppose I choose a man and a woman at random. # What is the probability that the man is taller? sum(x > y for x, y in zip(male_sample, female_sample)) / len(male_sample) """ Explanation: Another way to quantify the difference between distributions is what's called "probability of superiority", which is a problematic term, but in this context it's the probability that a randomly-chosen man is taller than a randomly-chosen woman. End of explanation """ def CohenEffectSize(group1, group2): """Compute Cohen's d. group1: Series or NumPy array group2: Series or NumPy array returns: float """ diff = group1.mean() - group2.mean() n1, n2 = len(group1), len(group2) var1 = group1.var() var2 = group2.var() pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2) d = diff / numpy.sqrt(pooled_var) return d """ Explanation: Overlap (or misclassification rate) and "probability of superiority" have two good properties: As probabilities, they don't depend on units of measure, so they are comparable between studies. They are expressed in operational terms, so a reader has a sense of what practical effect the difference makes. There is one other common way to express the difference between distributions. Cohen's $d$ is the difference in means, standardized by dividing by the standard deviation. Here's a function that computes it: End of explanation """ CohenEffectSize(male_sample, female_sample) """ Explanation: Computing the denominator is a little complicated; in fact, people have proposed several ways to do it. This implementation uses the "pooled standard deviation", which is a weighted average of the standard deviations of the two groups. And here's the result for the difference in height between men and women. End of explanation """ def overlap_superiority(control, treatment, n=1000): """Estimates overlap and superiority based on a sample. control: scipy.stats rv object treatment: scipy.stats rv object n: sample size """ control_sample = control.rvs(n) treatment_sample = treatment.rvs(n) thresh = (control.mean() + treatment.mean()) / 2 control_above = sum(control_sample > thresh) treatment_below = sum(treatment_sample < thresh) overlap = (control_above + treatment_below) / n superiority = sum(x > y for x, y in zip(treatment_sample, control_sample)) / n return overlap, superiority """ Explanation: Most people don't have a good sense of how big $d=1.9$ is, so let's make a visualization to get calibrated. Here's a function that encapsulates the code we already saw for computing overlap and probability of superiority. End of explanation """ def plot_pdfs(cohen_d=2): """Plot PDFs for distributions that differ by some number of stds. cohen_d: number of standard deviations between the means """ control = scipy.stats.norm(0, 1) treatment = scipy.stats.norm(cohen_d, 1) xs, ys = eval_pdf(control) pyplot.fill_between(xs, ys, label='control', color=COLOR3, alpha=0.7) xs, ys = eval_pdf(treatment) pyplot.fill_between(xs, ys, label='treatment', color=COLOR2, alpha=0.7) o, s = overlap_superiority(control, treatment) print('overlap', o) print('superiority', s) """ Explanation: Here's the function that takes Cohen's $d$, plots normal distributions with the given effect size, and prints their overlap and superiority. End of explanation """ plot_pdfs(2) """ Explanation: Here's an example that demonstrates the function: End of explanation """ slider = widgets.FloatSliderWidget(min=0, max=4, value=2) interact(plot_pdfs, cohen_d=slider) None """ Explanation: And an interactive widget you can use to visualize what different values of $d$ mean: End of explanation """
phanrahan/magmathon
notebooks/tutorial/coreir/TFF.ipynb
mit
import magma as m from mantle import DFF class TFF(m.Circuit): io = m.IO(O=m.Out(m.Bit)) + m.ClockIO() # instance a dff to hold the state of the toggle flip-flop - this needs to be done first dff = DFF() # compute the next state as the not of the old state ff.O io.O <= dff(~dff.O) def tff(): return TFF()() """ Explanation: DFF and TFF (Toggle Flip-Flop) In this example we create a toggle flip-flop (TFF) from a d-flip-flop (DFF). In Magma, finite state machines can be constructed by composing combinational logic with flop-flops register primitives. End of explanation """ from fault import PythonTester tester = PythonTester(TFF, TFF.CLK) tester.eval() val = tester.peek(TFF.O) assert val == False for i in range(10): val = not val tester.step() # toggle clock - now High assert val == tester.peek(TFF.O) tester.step() # toggle clock - now Low assert val == tester.peek(TFF.O) print("Success!") """ Explanation: Test using the python simulator. End of explanation """ m.compile("build/TFF", TFF, inline=True) %cat build/TFF.v %cat build/TFF.json !coreir -i build/TFF.json -p instancecount """ Explanation: Generate Verilog Generate verilog with coreir. End of explanation """ import fault tester = fault.Tester(TFF, TFF.CLK) for i in range(5): tester.step(2) tester.print("TFF.O=%d\n", TFF.O) tester.compile_and_run("verilator", disp_type='realtime') """ Explanation: Here's an example of testing using fault's staged Tester class and the verilator simulator. End of explanation """
probml/pyprobml
notebooks/misc/linreg_sklearn.ipynb
mit
# 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/linreg/linreg_sklearn.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Linear regression <a class="anchor" id="linreg"></a> In this section, we illustrate how to perform linear regression using scikit-learn. Install necessary libraries End of explanation """ from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression from sklearn.preprocessing import MinMaxScaler import sklearn.metrics from sklearn.metrics import mean_squared_error as mse def make_1dregression_data(n=21): np.random.seed(0) xtrain = np.linspace(0.0, 20, n) xtest = np.arange(0.0, 20, 0.1) sigma2 = 4 w = np.array([-1.5, 1 / 9.0]) fun = lambda x: w[0] * x + w[1] * np.square(x) ytrain = fun(xtrain) + np.random.normal(0, 1, xtrain.shape) * np.sqrt(sigma2) ytest = fun(xtest) + np.random.normal(0, 1, xtest.shape) * np.sqrt(sigma2) return xtrain, ytrain, xtest, ytest xtrain, ytrain, xtest, ytest = make_1dregression_data(n=21) # Rescaling data scaler = MinMaxScaler(feature_range=(-1, 1)) Xtrain = scaler.fit_transform(xtrain.reshape(-1, 1)) Xtest = scaler.transform(xtest.reshape(-1, 1)) degs = np.arange(1, 21, 1) ndegs = np.max(degs) mse_train = np.empty(ndegs) mse_test = np.empty(ndegs) ytest_pred_stored = np.empty(ndegs, dtype=np.ndarray) ytrain_pred_stored = np.empty(ndegs, dtype=np.ndarray) for deg in degs: model = LinearRegression() poly_features = PolynomialFeatures(degree=deg, include_bias=False) Xtrain_poly = poly_features.fit_transform(Xtrain) model.fit(Xtrain_poly, ytrain) ytrain_pred = model.predict(Xtrain_poly) ytrain_pred_stored[deg - 1] = ytrain_pred Xtest_poly = poly_features.transform(Xtest) ytest_pred = model.predict(Xtest_poly) mse_train[deg - 1] = mse(ytrain_pred, ytrain) mse_test[deg - 1] = mse(ytest_pred, ytest) ytest_pred_stored[deg - 1] = ytest_pred # Plot MSE vs degree fig, ax = plt.subplots() mask = degs <= 15 ax.plot(degs[mask], mse_test[mask], color="r", marker="x", label="test") ax.plot(degs[mask], mse_train[mask], color="b", marker="s", label="train") ax.legend(loc="upper right", shadow=True) plt.xlabel("degree") plt.ylabel("mse") # save_fig('polyfitVsDegree.pdf') plt.show() # Plot fitted functions chosen_degs = [1, 2, 14, 20] fig, axes = plt.subplots(2, 2, figsize=(10, 7)) axes = axes.reshape(-1) for i, deg in enumerate(chosen_degs): # fig, ax = plt.subplots() ax = axes[i] ax.scatter(xtrain, ytrain) ax.plot(xtest, ytest_pred_stored[deg - 1]) ax.set_ylim((-10, 15)) ax.set_title("degree {}".format(deg)) # save_fig('polyfitDegree{}.pdf'.format(deg)) plt.show() # Plot residuals chosen_degs = [1, 2, 14, 20] fig, axes = plt.subplots(2, 2, figsize=(10, 7)) axes = axes.reshape(-1) for i, deg in enumerate(chosen_degs): # fig, ax = plt.subplots(figsize=(3,2)) ax = axes[i] ypred = ytrain_pred_stored[deg - 1] residuals = ytrain - ypred ax.plot(ypred, residuals, "o") ax.set_title("degree {}".format(deg)) # save_fig('polyfitDegree{}Residuals.pdf'.format(deg)) plt.show() # Plot fit vs actual chosen_degs = [1, 2, 14, 20] fig, axes = plt.subplots(2, 2, figsize=(10, 7)) axes = axes.reshape(-1) for i, deg in enumerate(chosen_degs): for train in [True, False]: if train: ytrue = ytrain ypred = ytrain_pred_stored[deg - 1] dataset = "Train" else: ytrue = ytest ypred = ytest_pred_stored[deg - 1] dataset = "Test" # fig, ax = plt.subplots() ax = axes[i] ax.scatter(ytrue, ypred) ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3") ax.set_xlabel("true y") ax.set_ylabel("predicted y") r2 = sklearn.metrics.r2_score(ytrue, ypred) ax.set_title("degree {}. R2 on {} = {:0.3f}".format(deg, dataset, r2)) # save_fig('polyfitDegree{}FitVsActual{}.pdf'.format(deg, dataset)) plt.show() """ Explanation: Linear regression in 1d <a class="anchor" id="linreg-1d"></a> 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) Xscaled = scaler.transform(X_train) # equivalent to Xscaled = scaler.fit_transform(X_train) # Fit model linreg = lm.LinearRegression() linreg.fit(Xscaled, y_train) # Extract parameters coef = np.append(linreg.coef_, linreg.intercept_) names = np.append(boston.feature_names, "intercept") print(names) print(coef) # Assess fit on test set Xtest_scaled = scaler.transform(X_test) ypred = linreg.predict(Xtest_scaled) plt.figure() plt.scatter(y_test, ypred) plt.xlabel("true price") plt.ylabel("predicted price") mse = sklearn.metrics.mean_squared_error(y_test, ypred) plt.title("Boston housing, rmse {:.2f}".format(np.sqrt(mse))) xs = np.linspace(min(y), max(y), 100) plt.plot(xs, xs, "-") # save_fig("boston-housing-predict.pdf") plt.show() """ Explanation: Linear regression for boston housing <a class="anchor" id="linreg-boston"></a> End of explanation """ from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import Ridge from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error as mse xtrain, ytrain, xtest, ytest = make_1dregression_data(n=21) # Rescaling data scaler = MinMaxScaler(feature_range=(-1, 1)) Xtrain = scaler.fit_transform(xtrain.reshape(-1, 1)) Xtest = scaler.transform(xtest.reshape(-1, 1)) deg = 14 alphas = np.logspace(-10, 1.3, 10) nalphas = len(alphas) mse_train = np.empty(nalphas) mse_test = np.empty(nalphas) ytest_pred_stored = dict() for i, alpha in enumerate(alphas): model = Ridge(alpha=alpha, fit_intercept=False) poly_features = PolynomialFeatures(degree=deg, include_bias=False) Xtrain_poly = poly_features.fit_transform(Xtrain) model.fit(Xtrain_poly, ytrain) ytrain_pred = model.predict(Xtrain_poly) Xtest_poly = poly_features.transform(Xtest) ytest_pred = model.predict(Xtest_poly) mse_train[i] = mse(ytrain_pred, ytrain) mse_test[i] = mse(ytest_pred, ytest) ytest_pred_stored[alpha] = ytest_pred # Plot MSE vs degree fig, ax = plt.subplots() mask = [True] * nalphas ax.plot(alphas[mask], mse_test[mask], color="r", marker="x", label="test") ax.plot(alphas[mask], mse_train[mask], color="b", marker="s", label="train") ax.set_xscale("log") ax.legend(loc="upper right", shadow=True) plt.xlabel("L2 regularizer") plt.ylabel("mse") # save_fig('polyfitVsRidge.pdf') plt.show() # Plot fitted functions chosen_alphas = alphas[[0, 5, 8]] for i, alpha in enumerate(chosen_alphas): fig, ax = plt.subplots() ax.scatter(xtrain, ytrain) ax.plot(xtest, ytest_pred_stored[alpha]) plt.title("L2 regularizer {:0.5f}".format(alpha)) # save_fig('polyfitRidge{}.pdf'.format(i)) plt.show() """ Explanation: Ridge regression <a class="anchor" id="ridge"></a> In this section, we illustrate how to perform ridge regression using scikit-learn. End of explanation """
Hvass-Labs/TensorFlow-Tutorials
01_Simple_Linear_Model.ipynb
mit
%matplotlib inline import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix # Use TensorFlow v.2 with this old v.1 code. # E.g. placeholder variables and sessions have changed in TF2. import tensorflow.compat.v1 as tf tf.disable_v2_behavior() """ Explanation: TensorFlow Tutorial #01 Simple Linear Model by Magnus Erik Hvass Pedersen / GitHub / Videos on YouTube Introduction This tutorial demonstrates the basic workflow of using TensorFlow with a simple linear model. After loading the so-called MNIST data-set with images of hand-written digits, we define and optimize a simple mathematical model in TensorFlow. The results are then plotted and discussed. You should be familiar with basic linear algebra, Python and the Jupyter Notebook editor. It also helps if you have a basic understanding of Machine Learning and classification. TensorFlow 2 This tutorial was developed using TensorFlow v.1 back in the year 2016. There have been significant API changes in TensorFlow v.2. This tutorial uses TF2 in "v.1 compatibility mode", which is still useful for learning how TensorFlow works, but you would have to implement it slightly differently in TF2 (see Tutorial 03C on the Keras API). It would be too big a job for me to keep updating these tutorials every time Google's engineers update the TensorFlow API, so this tutorial may eventually stop working. Imports End of explanation """ tf.__version__ """ Explanation: This was developed using Python 3.6 (Anaconda) and TensorFlow version: End of explanation """ from mnist import MNIST data = MNIST(data_dir="data/MNIST/") """ Explanation: Load Data The MNIST data-set is about 12 MB and will be downloaded automatically if it is not located in the given path. End of explanation """ print("Size of:") print("- Training-set:\t\t{}".format(data.num_train)) print("- Validation-set:\t{}".format(data.num_val)) print("- Test-set:\t\t{}".format(data.num_test)) """ Explanation: The MNIST data-set has now been loaded and consists of 70.000 images and class-numbers for the images. The data-set is split into 3 mutually exclusive sub-sets. We will only use the training and test-sets in this tutorial. End of explanation """ # The images are stored in one-dimensional arrays of this length. img_size_flat = data.img_size_flat # Tuple with height and width of images used to reshape arrays. img_shape = data.img_shape # Number of classes, one class for each of 10 digits. num_classes = data.num_classes """ Explanation: Copy some of the data-dimensions for convenience. End of explanation """ data.y_test[0:5, :] """ Explanation: One-Hot Encoding The output-data is loaded as both integer class-numbers and so-called One-Hot encoded arrays. This means the class-numbers have been converted from a single integer to a vector whose length equals the number of possible classes. All elements of the vector are zero except for the $i$'th element which is 1 and means the class is $i$. For example, the One-Hot encoded labels for the first 5 images in the test-set are: End of explanation """ data.y_test_cls[0:5] """ Explanation: We also need the classes as integers for various comparisons and performance measures. These can be found from the One-Hot encoded arrays by taking the index of the highest element using the np.argmax() function. But this has already been done for us when the data-set was loaded, so we can see the class-number for the first five images in the test-set. Compare these to the One-Hot encoded arrays above. End of explanation """ def plot_images(images, cls_true, cls_pred=None): assert len(images) == len(cls_true) == 9 # Create figure with 3x3 sub-plots. fig, axes = plt.subplots(3, 3) fig.subplots_adjust(hspace=0.3, wspace=0.3) for i, ax in enumerate(axes.flat): # Plot image. ax.imshow(images[i].reshape(img_shape), cmap='binary') # Show true and predicted classes. if cls_pred is None: xlabel = "True: {0}".format(cls_true[i]) else: xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i]) ax.set_xlabel(xlabel) # Remove ticks from the plot. ax.set_xticks([]) ax.set_yticks([]) # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show() """ Explanation: Helper-function for plotting images Function used to plot 9 images in a 3x3 grid, and writing the true and predicted classes below each image. End of explanation """ # Get the first images from the test-set. images = data.x_test[0:9] # Get the true classes for those images. cls_true = data.y_test_cls[0:9] # Plot the images and labels using our helper-function above. plot_images(images=images, cls_true=cls_true) """ Explanation: Plot a few images to see if data is correct End of explanation """ x = tf.placeholder(tf.float32, [None, img_size_flat]) """ Explanation: TensorFlow Graph The entire purpose of TensorFlow is to have a so-called computational graph that can be executed much more efficiently than if the same calculations were to be performed directly in Python. TensorFlow can be more efficient than NumPy because TensorFlow knows the entire computation graph that must be executed, while NumPy only knows the computation of a single mathematical operation at a time. TensorFlow can also automatically calculate the gradients that are needed to optimize the variables of the graph so as to make the model perform better. This is because the graph is a combination of simple mathematical expressions so the gradient of the entire graph can be calculated using the chain-rule for derivatives. TensorFlow can also take advantage of multi-core CPUs as well as GPUs - and Google has even built special chips just for TensorFlow which are called TPUs (Tensor Processing Units) that are even faster than GPUs. A TensorFlow graph consists of the following parts which will be detailed below: Placeholder variables used to feed input into the graph. Model variables that are going to be optimized so as to make the model perform better. The model which is essentially just a mathematical function that calculates some output given the input in the placeholder variables and the model variables. A cost measure that can be used to guide the optimization of the variables. An optimization method which updates the variables of the model. In addition, the TensorFlow graph may also contain various debugging statements e.g. for logging data to be displayed using TensorBoard, which is not covered in this tutorial. Placeholder variables Placeholder variables serve as the input to the graph that we may change each time we execute the graph. We call this feeding the placeholder variables and it is demonstrated further below. First we define the placeholder variable for the input images. This allows us to change the images that are input to the TensorFlow graph. This is a so-called tensor, which just means that it is a multi-dimensional vector or matrix. The data-type is set to float32 and the shape is set to [None, img_size_flat], where None means that the tensor may hold an arbitrary number of images with each image being a vector of length img_size_flat. End of explanation """ y_true = tf.placeholder(tf.float32, [None, num_classes]) """ Explanation: Next we have the placeholder variable for the true labels associated with the images that were input in the placeholder variable x. The shape of this placeholder variable is [None, num_classes] which means it may hold an arbitrary number of labels and each label is a vector of length num_classes which is 10 in this case. End of explanation """ y_true_cls = tf.placeholder(tf.int64, [None]) """ Explanation: Finally we have the placeholder variable for the true class of each image in the placeholder variable x. These are integers and the dimensionality of this placeholder variable is set to [None] which means the placeholder variable is a one-dimensional vector of arbitrary length. End of explanation """ weights = tf.Variable(tf.zeros([img_size_flat, num_classes])) """ Explanation: Variables to be optimized Apart from the placeholder variables that were defined above and which serve as feeding input data into the model, there are also some model variables that must be changed by TensorFlow so as to make the model perform better on the training data. The first variable that must be optimized is called weights and is defined here as a TensorFlow variable that must be initialized with zeros and whose shape is [img_size_flat, num_classes], so it is a 2-dimensional tensor (or matrix) with img_size_flat rows and num_classes columns. End of explanation """ biases = tf.Variable(tf.zeros([num_classes])) """ Explanation: The second variable that must be optimized is called biases and is defined as a 1-dimensional tensor (or vector) of length num_classes. End of explanation """ logits = tf.matmul(x, weights) + biases """ Explanation: Model This simple mathematical model multiplies the images in the placeholder variable x with the weights and then adds the biases. The result is a matrix of shape [num_images, num_classes] because x has shape [num_images, img_size_flat] and weights has shape [img_size_flat, num_classes], so the multiplication of those two matrices is a matrix with shape [num_images, num_classes] and then the biases vector is added to each row of that matrix. Note that the name logits is typical TensorFlow terminology, but other people may call the variable something else. End of explanation """ y_pred = tf.nn.softmax(logits) """ Explanation: Now logits is a matrix with num_images rows and num_classes columns, where the element of the $i$'th row and $j$'th column is an estimate of how likely the $i$'th input image is to be of the $j$'th class. However, these estimates are a bit rough and difficult to interpret because the numbers may be very small or large, so we want to normalize them so that each row of the logits matrix sums to one, and each element is limited between zero and one. This is calculated using the so-called softmax function and the result is stored in y_pred. End of explanation """ y_pred_cls = tf.argmax(y_pred, axis=1) """ Explanation: The predicted class can be calculated from the y_pred matrix by taking the index of the largest element in each row. End of explanation """ cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y_true) """ Explanation: Cost-function to be optimized To make the model better at classifying the input images, we must somehow change the variables for weights and biases. To do this we first need to know how well the model currently performs by comparing the predicted output of the model y_pred to the desired output y_true. The cross-entropy is a performance measure used in classification. The cross-entropy is a continuous function that is always positive and if the predicted output of the model exactly matches the desired output then the cross-entropy equals zero. The goal of optimization is therefore to minimize the cross-entropy so it gets as close to zero as possible by changing the weights and biases of the model. TensorFlow has a built-in function for calculating the cross-entropy. Note that it uses the values of the logits because it also calculates the softmax internally. End of explanation """ cost = tf.reduce_mean(cross_entropy) """ Explanation: We have now calculated the cross-entropy for each of the image classifications so we have a measure of how well the model performs on each image individually. But in order to use the cross-entropy to guide the optimization of the model's variables we need a single scalar value, so we simply take the average of the cross-entropy for all the image classifications. End of explanation """ optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5).minimize(cost) """ Explanation: Optimization method Now that we have a cost measure that must be minimized, we can then create an optimizer. In this case it is the basic form of Gradient Descent where the step-size is set to 0.5. Note that optimization is not performed at this point. In fact, nothing is calculated at all, we just add the optimizer-object to the TensorFlow graph for later execution. End of explanation """ correct_prediction = tf.equal(y_pred_cls, y_true_cls) """ Explanation: Performance measures We need a few more performance measures to display the progress to the user. This is a vector of booleans whether the predicted class equals the true class of each image. End of explanation """ accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) """ Explanation: This calculates the classification accuracy by first type-casting the vector of booleans to floats, so that False becomes 0 and True becomes 1, and then calculating the average of these numbers. End of explanation """ session = tf.Session() """ Explanation: TensorFlow Run Create TensorFlow session Once the TensorFlow graph has been created, we have to create a TensorFlow session which is used to execute the graph. End of explanation """ session.run(tf.global_variables_initializer()) """ Explanation: Initialize variables The variables for weights and biases must be initialized before we start optimizing them. End of explanation """ batch_size = 100 """ Explanation: Helper-function to perform optimization iterations There are 55.000 images in the training-set. It takes a long time to calculate the gradient of the model using all these images. We therefore use Stochastic Gradient Descent which only uses a small batch of images in each iteration of the optimizer. End of explanation """ def optimize(num_iterations): for i in range(num_iterations): # Get a batch of training examples. # x_batch now holds a batch of images and # y_true_batch are the true labels for those images. x_batch, y_true_batch, _ = data.random_batch(batch_size=batch_size) # Put the batch into a dict with the proper names # for placeholder variables in the TensorFlow graph. # Note that the placeholder for y_true_cls is not set # because it is not used during training. feed_dict_train = {x: x_batch, y_true: y_true_batch} # Run the optimizer using this batch of training data. # TensorFlow assigns the variables in feed_dict_train # to the placeholder variables and then runs the optimizer. session.run(optimizer, feed_dict=feed_dict_train) """ Explanation: Function for performing a number of optimization iterations so as to gradually improve the weights and biases of the model. In each iteration, a new batch of data is selected from the training-set and then TensorFlow executes the optimizer using those training samples. End of explanation """ feed_dict_test = {x: data.x_test, y_true: data.y_test, y_true_cls: data.y_test_cls} """ Explanation: Helper-functions to show performance Dict with the test-set data to be used as input to the TensorFlow graph. Note that we must use the correct names for the placeholder variables in the TensorFlow graph. End of explanation """ def print_accuracy(): # Use TensorFlow to compute the accuracy. acc = session.run(accuracy, feed_dict=feed_dict_test) # Print the accuracy. print("Accuracy on test-set: {0:.1%}".format(acc)) """ Explanation: Function for printing the classification accuracy on the test-set. End of explanation """ def print_confusion_matrix(): # Get the true classifications for the test-set. cls_true = data.y_test_cls # Get the predicted classifications for the test-set. cls_pred = session.run(y_pred_cls, feed_dict=feed_dict_test) # Get the confusion matrix using sklearn. cm = confusion_matrix(y_true=cls_true, y_pred=cls_pred) # Print the confusion matrix as text. print(cm) # Plot the confusion matrix as an image. plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues) # Make various adjustments to the plot. plt.tight_layout() plt.colorbar() tick_marks = np.arange(num_classes) plt.xticks(tick_marks, range(num_classes)) plt.yticks(tick_marks, range(num_classes)) plt.xlabel('Predicted') plt.ylabel('True') # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show() """ Explanation: Function for printing and plotting the confusion matrix using scikit-learn. End of explanation """ def plot_example_errors(): # Use TensorFlow to get a list of boolean values # whether each test-image has been correctly classified, # and a list for the predicted class of each image. correct, cls_pred = session.run([correct_prediction, y_pred_cls], feed_dict=feed_dict_test) # Negate the boolean array. incorrect = (correct == False) # Get the images from the test-set that have been # incorrectly classified. images = data.x_test[incorrect] # Get the predicted classes for those images. cls_pred = cls_pred[incorrect] # Get the true classes for those images. cls_true = data.y_test_cls[incorrect] # Plot the first 9 images. plot_images(images=images[0:9], cls_true=cls_true[0:9], cls_pred=cls_pred[0:9]) """ Explanation: Function for plotting examples of images from the test-set that have been mis-classified. End of explanation """ def plot_weights(): # Get the values for the weights from the TensorFlow variable. w = session.run(weights) # Get the lowest and highest values for the weights. # This is used to correct the colour intensity across # the images so they can be compared with each other. w_min = np.min(w) w_max = np.max(w) # Create figure with 3x4 sub-plots, # where the last 2 sub-plots are unused. fig, axes = plt.subplots(3, 4) fig.subplots_adjust(hspace=0.3, wspace=0.3) for i, ax in enumerate(axes.flat): # Only use the weights for the first 10 sub-plots. if i<10: # Get the weights for the i'th digit and reshape it. # Note that w.shape == (img_size_flat, 10) image = w[:, i].reshape(img_shape) # Set the label for the sub-plot. ax.set_xlabel("Weights: {0}".format(i)) # Plot the image. ax.imshow(image, vmin=w_min, vmax=w_max, cmap='seismic') # Remove ticks from each sub-plot. ax.set_xticks([]) ax.set_yticks([]) # Ensure the plot is shown correctly with multiple plots # in a single Notebook cell. plt.show() """ Explanation: Helper-function to plot the model weights Function for plotting the weights of the model. 10 images are plotted, one for each digit that the model is trained to recognize. End of explanation """ print_accuracy() plot_example_errors() """ Explanation: Performance before any optimization The accuracy on the test-set is 9.8%. This is because the model has only been initialized and not optimized at all, so it always predicts that the image shows a zero digit, as demonstrated in the plot below, and it turns out that 9.8% of the images in the test-set happens to be zero digits. End of explanation """ optimize(num_iterations=1) print_accuracy() plot_example_errors() """ Explanation: Performance after 1 optimization iteration Already after a single optimization iteration, the model has increased its accuracy on the test-set significantly. End of explanation """ plot_weights() """ Explanation: The weights can also be plotted as shown below. Positive weights are red and negative weights are blue. These weights can be intuitively understood as image-filters. For example, the weights used to determine if an image shows a zero-digit have a positive reaction (red) to an image of a circle, and have a negative reaction (blue) to images with content in the centre of the circle. Similarly, the weights used to determine if an image shows a one-digit react positively (red) to a vertical line in the centre of the image, and react negatively (blue) to images with content surrounding that line. Note that the weights mostly look like the digits they're supposed to recognize. This is because only one optimization iteration has been performed so the weights are only trained on 100 images. After training on several thousand images, the weights become more difficult to interpret because they have to recognize many variations of how digits can be written. End of explanation """ # We have already performed 1 iteration. optimize(num_iterations=9) print_accuracy() plot_example_errors() plot_weights() """ Explanation: Performance after 10 optimization iterations End of explanation """ # We have already performed 10 iterations. optimize(num_iterations=990) print_accuracy() plot_example_errors() """ Explanation: Performance after 1000 optimization iterations After 1000 optimization iterations, the model only mis-classifies about one in ten images. As demonstrated below, some of the mis-classifications are justified because the images are very hard to determine with certainty even for humans, while others are quite obvious and should have been classified correctly by a good model. But this simple model cannot reach much better performance and more complex models are therefore needed. End of explanation """ plot_weights() """ Explanation: The model has now been trained for 1000 optimization iterations, with each iteration using 100 images from the training-set. Because of the great variety of the images, the weights have now become difficult to interpret and we may doubt whether the model truly understands how digits are composed from lines, or whether the model has just memorized many different variations of pixels. End of explanation """ print_confusion_matrix() """ Explanation: We can also print and plot the so-called confusion matrix which lets us see more details about the mis-classifications. For example, it shows that images actually depicting a 5 have sometimes been mis-classified as all other possible digits, but mostly as 6 or 8. End of explanation """ # This has been commented out in case you want to modify and experiment # with the Notebook without having to restart it. # session.close() """ Explanation: We are now done using TensorFlow, so we close the session to release its resources. End of explanation """
adrn/gary
docs/examples/Arbitrary-density-SCF.ipynb
mit
# Some imports we'll need later: # Third-party import astropy.units as u import matplotlib.pyplot as plt import numpy as np %matplotlib inline # Custom import gala.coordinates as gc import gala.dynamics as gd import gala.integrate as gi import gala.potential as gp from gala.units import galactic from gala.potential.scf import compute_coeffs, compute_coeffs_discrete """ Explanation: Compute an SCF representation of an arbitrary density distribution Basis function expansions are a useful tool for computing gravitational potentials and forces from an arbitrary density function that may not have an analytic solution to Poisson's equation. They are also useful for generating smoothed or compressed representations of gravitational potentials from discrete particle distributions. For astronomical density distributions, a useful expansion technique is the Self-Consistent Field (SCF) method, as initially developed by Hernquist & Ostriker (1992). In this method, using the notation of Lowing et al. 2011, the density and potential functions are expressed as: $$ \rho(r, \phi, \theta) = \sum_{l=0}^{l_{\rm max}} \sum_{m=0}^{l} \sum_{n=0}^{n_{\rm max}} Y_{lm}(\theta) \, \rho_{nl}(r) \, \left[S_{nlm}\,\cos(m\phi) + T_{nlm}\,\sin(m\phi) \right] \ \Phi(r, \phi, \theta) = \sum_{l=0}^{l_{\rm max}} \sum_{m=0}^{l} \sum_{n=0}^{n_{\rm max}} Y_{lm}(\theta) \, \Phi_{nl}(r) \, \left[S_{nlm}\,\cos(m\phi) + T_{nlm}\,\sin(m\phi) \right] $$ where $Y_{lm}(\theta)$ are the usual spherical harmonics, $\rho_{nlm}(r)$ and $\Phi_{nlm}(r)$ are bi-orthogonal radial basis functions, and $S_{nlm}$ and $T_{nlm}$ are expansion coefficients, which need to be computed from a given density function. In this notebook, we'll estimate low-order expansion coefficients for an analytic density distribution (written as a Python function). End of explanation """ def density_func(x, y, z): r = np.sqrt(x**2 + y**2 + z**2) return 1 / (r**1.8 * (1 + r)**2.7) """ Explanation: SCF representation of an analytic density distribution Custom spherical density function For this example, we'll assume that we want a potential representation of the spherical density function: $$ \rho(r) = \frac{1}{r^{1.8} \, (1 + r)^{2.7}} $$ Let's start by writing a density function that takes a single set of Cartesian coordinates (x, y, z) and returns the (scalar) value of the density at that location: End of explanation """ hern = gp.HernquistPotential(m=1, c=1) x = np.logspace(-1, 1, 128) plt.plot(x, density_func(x, 0, 0), marker='', label='custom density') # need a 3D grid for the potentials in Gala xyz = np.zeros((3, len(x))) xyz[0] = x plt.plot(x, hern.density(xyz), marker='', label='Hernquist') plt.xscale('log') plt.yscale('log') plt.xlabel('$r$') plt.ylabel(r'$\rho(r)$') plt.legend(loc='best'); """ Explanation: Let's visualize this density function. For comparison, let's also over-plot the Hernquist density distribution. The SCF expansion uses the Hernquist density for radial basis functions, so the similarity of the density we want to represent and the Hernquist function gives us a sense of how many radial terms we will need in the expansion: End of explanation """ (S, Serr), _ = compute_coeffs(density_func, nmax=10, lmax=0, M=1., r_s=1., S_only=True) """ Explanation: These functions are not too different, implying that we probably don't need too many radial expansion terms in order to well represent the density/potential from this custom function. As an arbitrary number, let's choose to compute radial terms up to and including $n = 10$. In this case, because the density we want to represent is spherical, we don't need any $l, m$ terms, so we set lmax=0. We can also neglect the sin() terms of the expansion ($T_{nlm}$): End of explanation """ pot = gp.SCFPotential(m=1., r_s=1, Snlm=S) """ Explanation: The above variable S will contain the expansion coefficients, and the variable Serr will contain an estimate of the error in this coefficient value. Let's now construct an SCFPotential object with the coefficients we just computed: End of explanation """ x = np.logspace(-1, 1, 128) plt.plot(x, density_func(x, 0, 0), marker='', label='custom density') # need a 3D grid for the potentials in Gala xyz = np.zeros((3, len(x))) xyz[0] = x plt.plot(x, pot.density(xyz), marker='', label='SCF density') plt.xscale('log') plt.yscale('log') plt.xlabel('$r$') plt.ylabel(r'$\rho(r)$') plt.legend(loc='best'); """ Explanation: Now let's visualize the SCF estimated density with the true density: End of explanation """ def density_func_flat(x, y, z, q): r = np.sqrt(x**2 + y**2 + (z / q)**2) return 1 / (r * (1 + r)**3) / (2*np.pi) """ Explanation: This does a pretty good job of capturing the radial fall-off of our custom density function, but you may want to iterate a bit to satisfy your own constraints. For example, you may want the density to be represented with a less than 1% deviation over some range of radii, or whatever. As a second example, let's now try a custom axisymmetric density distribution: Custom axisymmetric density function For this example, we'll assume that we want a potential representation of the flattened Hernquist density function: $$ \rho(R, z) = \frac{1}{r \, (1 + r)^{3}}\ r^2 = R^2 + \frac{z^2}{q^2} $$ where $q$ is the flattening, which we'll set to $q=0.6$. Let's again start by writing a density function that takes a single set of Cartesian coordinates (x, y, z) and returns the (scalar) value of the density at that location: End of explanation """ x = np.logspace(-1, 1, 128) xyz = np.zeros((3, len(x))) xyz[0] = x xyz[2] = x for q in np.arange(0.6, 1+1e-3, 0.2): plt.plot(x, density_func_flat(xyz[0], 0., xyz[2], q), marker='', label='custom density: q={0}'.format(q)) plt.plot(x, hern.density(xyz), marker='', ls='--', label='Hernquist') plt.xscale('log') plt.yscale('log') plt.xlabel('$r$') plt.ylabel(r'$\rho(r)$') plt.legend(loc='best'); """ Explanation: Let's compute the density along a diagonal line for a few different flattenings and again compare to the non-flattened Hernquist profile: End of explanation """ q = 0.6 (S_flat, Serr_flat), _ = compute_coeffs(density_func_flat, nmax=4, lmax=6, args=(q, ), M=1., r_s=1., S_only=True, skip_m=True, progress=True) pot_flat = gp.SCFPotential(m=1., r_s=1, Snlm=S_flat) x = np.logspace(-1, 1, 128) xyz = np.zeros((3, len(x))) xyz[0] = x xyz[2] = x plt.plot(x, density_func_flat(xyz[0], xyz[1], xyz[2], q), marker='', label='true density q={0}'.format(q)) plt.plot(x, pot_flat.density(xyz), marker='', ls='--', label='SCF density') plt.xscale('log') plt.yscale('log') plt.xlabel('$r$') plt.ylabel(r'$\rho(r)$') plt.legend(loc='best'); """ Explanation: Because this is an axisymmetric density distribution, we need to also compute $l$ terms in the expansion, so we set lmax=6, but we can skip the $m$ terms using skip_m=True. Because this computes more coefficients, we might want to see the progress in real time - if you install the Python package tqdm and pass progress=True, it will also display a progress bar: End of explanation """ grid = np.linspace(-8, 8, 128) fig, axes = plt.subplots(1, 2, figsize=(10, 5), sharex=True, sharey=True) _ = pot_flat.plot_contours((grid, grid, 0), ax=axes[0]) axes[0].set_xlabel('$x$') axes[0].set_ylabel('$y$') _ = pot_flat.plot_contours((grid, 0, grid), ax=axes[1]) axes[1].set_xlabel('$x$') axes[1].set_ylabel('$z$') for ax in axes: ax.set_aspect('equal') """ Explanation: The SCF potential object acts like any other gala.potential object, meaning we can, e.g., plot density or potential contours: End of explanation """ w0 = gd.PhaseSpacePosition(pos=[3.5, 0, 1], vel=[0, 0.4, 0.05]) orbit_flat = pot_flat.integrate_orbit(w0, dt=1., n_steps=5000) _ = orbit_flat.plot() """ Explanation: And numerically integrate orbits by passing in initial conditions and integration parameters: End of explanation """
PMEAL/OpenPNM
examples/tutorials/network/random_networks_based_on_delaunay_and_voronoi_tessellations.ipynb
mit
import openpnm as op import matplotlib.pyplot as plt pn = op.network.DelaunayVoronoiDual(points=100, shape=[1, 1, 1]) print(pn) """ Explanation: Delaunay and Voronoi Tessalation Generate Random Networks Based on Delaunay Triangulations, Voronoi Tessellations, or Both A random network offers several advantages over the traditional Cubic arrangement: the topology is more 'natural' looking, and a wider pore size distribution can be achieved since pores are not constrained by the lattice spacing. Random networks can be tricky to generate however, since the connectivity between pores is difficult to determine or define. One surprisingly simple option is to use Delaunay triangulation to connect base points (which become pore centers) that are randomly distributed in space. The Voronoi tessellation is a complementary graph that arises directly from the Delaunay graph which also connects essentially randomly distributed points in space into a network. OpenPNM offers both of these types of network, plus the ability to create a network containing both including interconnections between Delaunay and Voronoi networks via the DelaunayVoronoiDual class. In fact, creating the dual, interconnected network is the starting point, and any unwanted elements can be easily trimmed. End of explanation """ Ts = pn.throats(['voronoi', 'boundary'], mode='and') op.topotools.plot_connections(network=pn, throats=Ts) """ Explanation: The above line of code is deceptively simple. The returned network (pn) contains a fully connected Delaunay network, its complementary Voronoi network, and interconnecting throats (or bonds) between each Delaunay pore (node) and its neighboring Voronoi pores. Such a highly complex network would be useful for modeling pore phase transport (i.e. diffusion) on one network (i.e. Delaunay), solid phase transport (i.e. heat transfer) on the other network (i.e. Voronoi), and exchange of a species (i.e. heat) between the solid and void phases via the interconnecting bonds. Each pore and throat is labelled accordingly (i.e. 'pore.delaunay', 'throat.voronoi'), and the interconnecting throats are labelled 'throat.interconnect'. Moreover, pores and throats lying on the surface of the network are labelled 'surface'. A quick visualization of this network can be accomplished using OpenPNM's built-in graphing tool. The following shows only the Voronoi connections that lie on the surface of the cube: End of explanation """ fig, ax = plt.subplots() Ts = pn.throats(['voronoi', 'boundary'], mode='and') op.topotools.plot_connections(network=pn, throats=Ts, alpha=0.5, ax=ax) Ts = pn.throats(['voronoi', 'internal'], mode='and') op.topotools.plot_connections(network=pn, throats=Ts, c='g', ax=ax) Ts = pn.throats(['voronoi', 'surface'], mode='and') op.topotools.plot_connections(network=pn, throats=Ts, c='r', ax=ax) """ Explanation: One central feature of these networks are the flat boundaries, which are essential when performing transport calculations since they provide well-defined control surfaces for calculating flux. This flat surfaces are accomplished by reflecting the base points across each face prior to performing the tessellations. Plotting the internal Voronoi throats with a different color gives a good idea of the topology: End of explanation """ Ps = pn.pores(['voronoi']) op.topotools.trim(network=pn, pores=Ps) Ts = pn.throats(['surface']) op.topotools.trim(network=pn, throats=Ts) # NBVAL_IGNORE_OUTPUT op.topotools.plot_connections(network=pn) """ Explanation: The green lines are internal connections, and red lines are connections between internal notes and boundary nodes. Delaunay Network As the name suggests, the VoronoiDelaunayDual contains both the Delaunay triangulation and the Voronoi tessellation within the same topology. It is simple to delete one network (or the other) by trimming all of the other network's pores, which also removes all connected throats including the interconnections: End of explanation """ cyl = op.network.DelaunayVoronoiDual(points=200, shape=[2, 5]) op.topotools.plot_connections(network = cyl, throats=cyl.throats('boundary')) sph = op.network.DelaunayVoronoiDual(points=500, shape=[2]) op.topotools.plot_connections(network = sph, throats=sph.throats('surface')) """ Explanation: Create Random Networks of Spherical or Cylindrical Shape Many porous materials come in spherical or cylindrical shapes, such as catalyst pellets. The DelaunayVoronoiDual Network class can produce these geometries by specifying the domain_size in cylindrical [r, z] or spherical [r] coordinates: End of explanation """ Ps = sph.pores('voronoi') Ts = sph.throats('voronoi') geom = op.geometry.GenericGeometry(network=sph, pores=Ps, throats=Ts) mod = op.models.geometry.pore_size.largest_sphere geom.add_model(propname='pore.diameter', model=mod) mod = op.models.geometry.throat_length.ctc geom.add_model(propname='throat.length', model=mod) mod = op.models.geometry.throat_size.from_neighbor_pores geom.add_model(propname='throat.diameter', model=mod) geom.show_hist(['pore.diameter', 'throat.length', 'throat.diameter']) """ Explanation: Note that the cylindrical and spherical networks don't look very nice when too few points are used, so at least about 200 is recommended. Assign Pore Sizes to the Random Network With pore centers randomly distributed in space it becomes challenging to know what pore size to assign to each location. Assigning pores that are too large results in overlaps, which makes it impossible to properly account for porosity and transport lengths. OpenPNM includes a Geometry model called largest_sphere that solves this problem. Let's assign the largest possible pore size to each Voronoi node in the sph network just created: End of explanation """
mne-tools/mne-tools.github.io
dev/_downloads/87ced9add160fc358769ef662f31e446/45_projectors_background.ipynb
bsd-3-clause
import os import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa from scipy.linalg import svd import mne def setup_3d_axes(): ax = plt.axes(projection='3d') ax.view_init(azim=-105, elev=20) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_xlim(-1, 5) ax.set_ylim(-1, 5) ax.set_zlim(0, 5) return ax """ Explanation: Background on projectors and projections This tutorial provides background information on projectors and Signal Space Projection (SSP), and covers loading and saving projectors, adding and removing projectors from Raw objects, the difference between "applied" and "unapplied" projectors, and at what stages MNE-Python applies projectors automatically. We'll start by importing the Python modules we need; we'll also define a short function to make it easier to make several plots that look similar: End of explanation """ ax = setup_3d_axes() # plot the vector (3, 2, 5) origin = np.zeros((3, 1)) point = np.array([[3, 2, 5]]).T vector = np.hstack([origin, point]) ax.plot(*vector, color='k') ax.plot(*point, color='k', marker='o') # project the vector onto the x,y plane and plot it xy_projection_matrix = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]) projected_point = xy_projection_matrix @ point projected_vector = xy_projection_matrix @ vector ax.plot(*projected_vector, color='C0') ax.plot(*projected_point, color='C0', marker='o') # add dashed arrow showing projection arrow_coords = np.concatenate([point, projected_point - point]).flatten() ax.quiver3D(*arrow_coords, length=0.96, arrow_length_ratio=0.1, color='C1', linewidth=1, linestyle='dashed') """ Explanation: What is a projection? In the most basic terms, a projection is an operation that converts one set of points into another set of points, where repeating the projection operation on the resulting points has no effect. To give a simple geometric example, imagine the point $(3, 2, 5)$ in 3-dimensional space. A projection of that point onto the $x, y$ plane looks a lot like a shadow cast by that point if the sun were directly above it: End of explanation """ trigger_effect = np.array([[3, -1, 1]]).T """ Explanation: <div class="alert alert-info"><h4>Note</h4><p>The ``@`` symbol indicates matrix multiplication on NumPy arrays, and was introduced in Python 3.5 / NumPy 1.10. The notation ``plot(*point)`` uses Python `argument expansion`_ to "unpack" the elements of ``point`` into separate positional arguments to the function. In other words, ``plot(*point)`` expands to ``plot(3, 2, 5)``.</p></div> Notice that we used matrix multiplication to compute the projection of our point $(3, 2, 5)$onto the $x, y$ plane: \begin{align}\left[ \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix} \right] \left[ \begin{matrix} 3 \ 2 \ 5 \end{matrix} \right] = \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align} ...and that applying the projection again to the result just gives back the result again: \begin{align}\left[ \begin{matrix} 1 & 0 & 0 \ 0 & 1 & 0 \ 0 & 0 & 0 \end{matrix} \right] \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right] = \left[ \begin{matrix} 3 \ 2 \ 0 \end{matrix} \right]\end{align} From an information perspective, this projection has taken the point $x, y, z$ and removed the information about how far in the $z$ direction our point was located; all we know now is its position in the $x, y$ plane. Moreover, applying our projection matrix to any point in $x, y, z$ space will reduce it to a corresponding point on the $x, y$ plane. The term for this is a subspace: the projection matrix projects points in the original space into a subspace of lower dimension than the original. The reason our subspace is the $x,y$ plane (instead of, say, the $y,z$ plane) is a direct result of the particular values in our projection matrix. Example: projection as noise reduction Another way to describe this "loss of information" or "projection into a subspace" is to say that projection reduces the rank (or "degrees of freedom") of the measurement — here, from 3 dimensions down to 2. On the other hand, if you know that measurement component in the $z$ direction is just noise due to your measurement method, and all you care about are the $x$ and $y$ components, then projecting your 3-dimensional measurement into the $x, y$ plane could be seen as a form of noise reduction. Of course, it would be very lucky indeed if all the measurement noise were concentrated in the $z$ direction; you could just discard the $z$ component without bothering to construct a projection matrix or do the matrix multiplication. Suppose instead that in order to take that measurement you had to pull a trigger on a measurement device, and the act of pulling the trigger causes the device to move a little. If you measure how trigger-pulling affects measurement device position, you could then "correct" your real measurements to "project out" the effect of the trigger pulling. Here we'll suppose that the average effect of the trigger is to move the measurement device by $(3, -1, 1)$: End of explanation """ # compute the plane orthogonal to trigger_effect x, y = np.meshgrid(np.linspace(-1, 5, 61), np.linspace(-1, 5, 61)) A, B, C = trigger_effect z = (-A * x - B * y) / C # cut off the plane below z=0 (just to make the plot nicer) mask = np.where(z >= 0) x = x[mask] y = y[mask] z = z[mask] """ Explanation: Knowing that, we can compute a plane that is orthogonal to the effect of the trigger (using the fact that a plane through the origin has equation $Ax + By + Cz = 0$ given a normal vector $(A, B, C)$), and project our real measurements onto that plane. End of explanation """ # compute the projection matrix U, S, V = svd(trigger_effect, full_matrices=False) trigger_projection_matrix = np.eye(3) - U @ U.T # project the vector onto the orthogonal plane projected_point = trigger_projection_matrix @ point projected_vector = trigger_projection_matrix @ vector # plot the trigger effect and its orthogonal plane ax = setup_3d_axes() ax.plot_trisurf(x, y, z, color='C2', shade=False, alpha=0.25) ax.quiver3D(*np.concatenate([origin, trigger_effect]).flatten(), arrow_length_ratio=0.1, color='C2', alpha=0.5) # plot the original vector ax.plot(*vector, color='k') ax.plot(*point, color='k', marker='o') offset = np.full((3, 1), 0.1) ax.text(*(point + offset).flat, '({}, {}, {})'.format(*point.flat), color='k') # plot the projected vector ax.plot(*projected_vector, color='C0') ax.plot(*projected_point, color='C0', marker='o') offset = np.full((3, 1), -0.2) ax.text(*(projected_point + offset).flat, '({}, {}, {})'.format(*np.round(projected_point.flat, 2)), color='C0', horizontalalignment='right') # add dashed arrow showing projection arrow_coords = np.concatenate([point, projected_point - point]).flatten() ax.quiver3D(*arrow_coords, length=0.96, arrow_length_ratio=0.1, color='C1', linewidth=1, linestyle='dashed') """ Explanation: Computing the projection matrix from the trigger_effect vector is done using singular value decomposition (SVD); interested readers may consult the internet or a linear algebra textbook for details on this method. With the projection matrix in place, we can project our original vector $(3, 2, 5)$ to remove the effect of the trigger, and then plot it: End of explanation """ sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) raw.crop(tmax=60).load_data() """ Explanation: Just as before, the projection matrix will map any point in $x, y, z$ space onto that plane, and once a point has been projected onto that plane, applying the projection again will have no effect. For that reason, it should be clear that although the projected points vary in all three $x$, $y$, and $z$ directions, the set of projected points have only two effective dimensions (i.e., they are constrained to a plane). .. sidebar:: Terminology In MNE-Python, the matrix used to project a raw signal into a subspace is usually called a :term:`projector` or a *projection operator* — these terms are interchangeable with the term *projection matrix* used above. Projections of EEG or MEG signals work in very much the same way: the point $x, y, z$ corresponds to the value of each sensor at a single time point, and the projection matrix varies depending on what aspects of the signal (i.e., what kind of noise) you are trying to project out. The only real difference is that instead of a single 3-dimensional point $(x, y, z)$ you're dealing with a time series of $N$-dimensional "points" (one at each sampling time), where $N$ is usually in the tens or hundreds (depending on how many sensors your EEG/MEG system has). Fortunately, because projection is a matrix operation, it can be done very quickly even on signals with hundreds of dimensions and tens of thousands of time points. Signal-space projection (SSP) We mentioned above that the projection matrix will vary depending on what kind of noise you are trying to project away. Signal-space projection (SSP) :footcite:UusitaloIlmoniemi1997 is a way of estimating what that projection matrix should be, by comparing measurements with and without the signal of interest. For example, you can take additional "empty room" measurements that record activity at the sensors when no subject is present. By looking at the spatial pattern of activity across MEG sensors in an empty room measurement, you can create one or more $N$-dimensional vector(s) giving the "direction(s)" of environmental noise in sensor space (analogous to the vector for "effect of the trigger" in our example above). SSP is also often used for removing heartbeat and eye movement artifacts — in those cases, instead of empty room recordings the direction of the noise is estimated by detecting the artifacts, extracting epochs around them, and averaging. See tut-artifact-ssp for examples. Once you know the noise vectors, you can create a hyperplane that is orthogonal to them, and construct a projection matrix to project your experimental recordings onto that hyperplane. In that way, the component of your measurements associated with environmental noise can be removed. Again, it should be clear that the projection reduces the dimensionality of your data — you'll still have the same number of sensor signals, but they won't all be linearly independent — but typically there are tens or hundreds of sensors and the noise subspace that you are eliminating has only 3-5 dimensions, so the loss of degrees of freedom is usually not problematic. Projectors in MNE-Python In our example data, SSP &lt;ssp-tutorial&gt; has already been performed using empty room recordings, but the :term:projectors &lt;projector&gt; are stored alongside the raw data and have not been applied yet (or, synonymously, the projectors are not active yet). Here we'll load the sample data &lt;sample-dataset&gt; and crop it to 60 seconds; you can see the projectors in the output of :func:~mne.io.read_raw_fif below: End of explanation """ print(raw.info['projs']) """ Explanation: In MNE-Python, the environmental noise vectors are computed using principal component analysis, usually abbreviated "PCA", which is why the SSP projectors usually have names like "PCA-v1". (Incidentally, since the process of performing PCA uses singular value decomposition under the hood, it is also common to see phrases like "projectors were computed using SVD" in published papers.) The projectors are stored in the projs field of raw.info: End of explanation """ first_projector = raw.info['projs'][0] print(first_projector) print(first_projector.keys()) """ Explanation: raw.info['projs'] is an ordinary Python :class:list of :class:~mne.Projection objects, so you can access individual projectors by indexing into it. The :class:~mne.Projection object itself is similar to a Python :class:dict, so you can use its .keys() method to see what fields it contains (normally you don't need to access its properties directly, but you can if necessary): End of explanation """ print(raw.proj) print(first_projector['active']) """ Explanation: The :class:~mne.io.Raw, :class:~mne.Epochs, and :class:~mne.Evoked objects all have a boolean :attr:~mne.io.Raw.proj attribute that indicates whether there are any unapplied / inactive projectors stored in the object. In other words, the :attr:~mne.io.Raw.proj attribute is True if at least one :term:projector is present and all of them are active. In addition, each individual projector also has a boolean active field: End of explanation """ mags = raw.copy().crop(tmax=2).pick_types(meg='mag') for proj in (False, True): with mne.viz.use_browser_backend('matplotlib'): fig = mags.plot(butterfly=True, proj=proj) fig.subplots_adjust(top=0.9) fig.suptitle('proj={}'.format(proj), size='xx-large', weight='bold') """ Explanation: Computing projectors In MNE-Python, SSP vectors can be computed using general purpose functions :func:mne.compute_proj_raw, :func:mne.compute_proj_epochs, and :func:mne.compute_proj_evoked. The general assumption these functions make is that the data passed contains raw data, epochs or averages of the artifact you want to repair via projection. In practice this typically involves continuous raw data of empty room recordings or averaged ECG or EOG artifacts. A second set of high-level convenience functions is provided to compute projection vectors for typical use cases. This includes :func:mne.preprocessing.compute_proj_ecg and :func:mne.preprocessing.compute_proj_eog for computing the ECG and EOG related artifact components, respectively; see tut-artifact-ssp for examples of these uses. For computing the EEG reference signal as a projector, the function :func:mne.set_eeg_reference can be used; see tut-set-eeg-ref for more information. <div class="alert alert-danger"><h4>Warning</h4><p>It is best to compute projectors only on channels that will be used (e.g., excluding bad channels). This ensures that projection vectors will remain ortho-normalized and that they properly capture the activity of interest.</p></div> Visualizing the effect of projectors You can see the effect the projectors are having on the measured signal by comparing plots with and without the projectors applied. By default, raw.plot() will apply the projectors in the background before plotting (without modifying the :class:~mne.io.Raw object); you can control this with the boolean proj parameter as shown below, or you can turn them on and off interactively with the projectors interface, accessed via the :kbd:Proj button in the lower right corner of the plot window. Here we'll look at just the magnetometers, and a 2-second sample from the beginning of the file. End of explanation """ ecg_proj_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_ecg-proj.fif') ecg_projs = mne.read_proj(ecg_proj_file) print(ecg_projs) """ Explanation: Additional ways of visualizing projectors are covered in the tutorial tut-artifact-ssp. Loading and saving projectors SSP can be used for other types of signal cleaning besides just reduction of environmental noise. You probably noticed two large deflections in the magnetometer signals in the previous plot that were not removed by the empty-room projectors — those are artifacts of the subject's heartbeat. SSP can be used to remove those artifacts as well. The sample data includes projectors for heartbeat noise reduction that were saved in a separate file from the raw data, which can be loaded with the :func:mne.read_proj function: End of explanation """ raw.add_proj(ecg_projs) """ Explanation: There is a corresponding :func:mne.write_proj function that can be used to save projectors to disk in .fif format: python3 mne.write_proj('heartbeat-proj.fif', ecg_projs) <div class="alert alert-info"><h4>Note</h4><p>By convention, MNE-Python expects projectors to be saved with a filename ending in ``-proj.fif`` (or ``-proj.fif.gz``), and will issue a warning if you forgo this recommendation.</p></div> Adding and removing projectors Above, when we printed the ecg_projs list that we loaded from a file, it showed two projectors for gradiometers (the first two, marked "planar"), two for magnetometers (the middle two, marked "axial"), and two for EEG sensors (the last two, marked "eeg"). We can add them to the :class:~mne.io.Raw object using the :meth:~mne.io.Raw.add_proj method: End of explanation """ mags_ecg = raw.copy().crop(tmax=2).pick_types(meg='mag') for data, title in zip([mags, mags_ecg], ['Without', 'With']): with mne.viz.use_browser_backend('matplotlib'): fig = data.plot(butterfly=True, proj=True) fig.subplots_adjust(top=0.9) fig.suptitle('{} ECG projector'.format(title), size='xx-large', weight='bold') """ Explanation: To remove projectors, there is a corresponding method :meth:~mne.io.Raw.del_proj that will remove projectors based on their index within the raw.info['projs'] list. For the special case of replacing the existing projectors with new ones, use raw.add_proj(ecg_projs, remove_existing=True). To see how the ECG projectors affect the measured signal, we can once again plot the data with and without the projectors applied (though remember that the :meth:~mne.io.Raw.plot method only temporarily applies the projectors for visualization, and does not permanently change the underlying data). We'll compare the mags variable we created above, which had only the empty room SSP projectors, to the data with both empty room and ECG projectors: End of explanation """
mmaelicke/scikit-gstat
tutorials/05_binning.ipynb
mit
import skgstat as skg import numpy as np import pandas as pd from imageio import imread import plotly.graph_objects as go from plotly.offline import init_notebook_mode, iplot from plotly.subplots import make_subplots skg.plotting.backend('plotly') init_notebook_mode() """ Explanation: 5 - Lag classes This tutorial focuses the estimation of lag classes. It is one of the most important, maybe the most important step for estimating variograms. Usually, lag class generation, or binning, is not really focused in geostatistical literature. The main reason is, that usually, the same method is used. A user-set amount of equidistant lag classes is formed with 0 as lower bound and maxlag as upper bound. Maxlag is often set to the median or 60% percentile of all pairwise separating distances. In SciKit-GStat this is also the default behavior, but only one of dozen of different implemented methods. Thus, we want to shed some light onto the other methods here. SciKit-GStat implements methods of two different kinds. The first kind are the methods, that take a fixed N, the number of lag classes, accessible through the Variogram.n_lags property. These methods are ['even', 'uniform', 'kmeans', 'ward']. The other kind is often used in histogram estimation and will apply a (simple) rule to figure out a suitable N themself. Using one of these methods will overwrite the Variogram.n_lags property. THese methods are: ['sturges', 'scott', 'fd', 'sqrt', 'doane']. End of explanation """ N = 80 pan = skg.data.pancake_field().get('sample') coords, vals = skg.data.pancake(N=80, seed=1312).get('sample') fig = make_subplots(1,2,shared_xaxes=True, shared_yaxes=True) fig.add_trace( go.Scatter(x=coords[:,0], y=coords[:,1], mode='markers', marker=dict(color=vals,cmin=0, cmax=255), name='samples'), row=1, col=1 ) fig.add_trace(go.Heatmap(z=pan, name='field'), row=1, col=2) fig.update_layout(width=900, height=450, template='plotly_white') iplot(fig) """ Explanation: 5.1 Sample data Loads a data sample and draws n_samples from the field. For sampling the field, random samples from a gamma distribution with a fairly high scale are drawn, to ensure there are some outliers in the samle. The values are then re-scaled to the shape of the random field and the values are extracted from it. You can use either of the next two cell to work either on the pancake or the Meuse dataset. End of explanation """ coords, vals = skg.data.meuse().get('sample') vals = vals.flatten() fig = go.Figure(go.Scatter(x=coords[:,0], y=coords[:,1], mode='markers', marker=dict(color=vals), name='samples')) fig.update_layout(width=450, height=450, template='plotly_white') iplot(fig) """ Explanation: Uncomment this cell to work on the pancake: End of explanation """ N = 15 # use a nugget V = skg.Variogram(coords, vals, n_lags=N, use_nugget=True) """ Explanation: 5.2 Lag class binning - fixed N Apply different lag class binning methods and visualize their histograms. In this section, the distance matrix between all point pair combinations (NxN) is binned using each method. The plots visualize the histrogram of the distance matrix of the variogram, not the variogram lag classes themselves. End of explanation """ # apply binning bins, _ = skg.binning.even_width_lags(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'even'}~~binning$") ) iplot(fig) """ Explanation: 5.2.1 default 'even' lag classes The default binning method will find N equidistant bins. This is the default behavior and used in almost all geostatistical publications. It should not be used without a maxlag (like done in the plot below). End of explanation """ # apply binning bins, _ = skg.binning.uniform_count_lags(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'uniform'}~~binning$") ) iplot(fig) """ Explanation: 5.2.2 'uniform' lag classes The histogram of the uniform method will adjust the lag class widths to have the same sample size for each lag class. This can be used, when there must not be any empty lag classes on small data samples, or comparable sample sizes are desireable for the semi-variance estimator. End of explanation """ # apply binning bins, _ = skg.binning.kmeans(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'K-Means'}~~binning$") ) iplot(fig) """ Explanation: 5.2.3 'kmeans' lag classes The distance matrix is clustered by a K-Means algorithm. The centroids, are taken as a good guess for lag class centers. Each lag class is then formed by taking half the distance to each sorted neighboring centroid as a bound. This will most likely result in non-equidistant lag classes. One important note about K-Means clustering is, that it is not a deterministic method, as the starting points for clustering are taken randomly. Thus, the decision was made to seed the random start values. Therefore, the K-Means implementation in SciKit-GStat is deterministic and will always return the same lag classes for the same distance matrix. End of explanation """ # apply binning bins, _ = skg.binning.ward(V.distance, N, None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'ward'}~~binning$") ) iplot(fig) """ Explanation: 5.2.4 'ward' lag classes The other clustering algorithm is a hierarchical clustering algorithm. This algorithm groups values together based on their similarity, which is expressed by Ward's criterion. Agglomerative algorithms work iteratively and deterministic, as at first iteration each value forms a cluster on its own. Each cluster is then merged with the most similar other cluster, one at a time, until all clusters are merged, or the clustering is interrupted. Here, the clustering is interrupted as soon as the specified number of lag classes is reached. The lag classes are then formed similar to the K-Means method, either by taking the cluster mean or median as center. Ward's criterion defines the one other cluster as the closest, that results in the smallest intra-cluster variance for the merged clusters. The main downside is the processing speed. You will see a significant difference for 'ward' and should not use it on medium and large datasets. End of explanation """ # apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'sturges', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'sturges'}~~binning~~%d~classes$" % n) ) iplot(fig) """ Explanation: 5.3 Lag class binning - adjustable N 5.3.1 'sturges' lag classes Sturge's rule is well known and pretty straightforward. It's the default method for histograms in R. The number of equidistant lag classes is defined like: $$ n =log_2 (x + 1) $$ Sturge's rule works good for small, normal distributed datasets. End of explanation """ # apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'scott', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'scott'}~~binning~~%d~classes$" % n) ) iplot(fig) """ Explanation: 5.3.2 'scott' lag classes Scott's rule is another quite popular approach to estimate histograms. The rule is defined like: $$ h = \sigma \frac{24 * \sqrt{\pi}}{x}^{\frac{1}{3}} $$ Other than Sturge's rule, it will estimate the lag class width from the sample size standard deviation. Thus, it is also quite sensitive to outliers. End of explanation """ # apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'sqrt', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'sqrt'}~~binning~~%d~classes$" % n) ) iplot(fig) """ Explanation: 5.3.3 'sqrt' lag classes The only advantage of this method is its speed. The number of lag classes is simply defined like: $$ n = \sqrt{x} $$ Thus, it's usually not really a good choice, unless you have a lot of samples. End of explanation """ # apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'fd', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'fd'}~~binning~~%d~classes$" % n) ) iplot(fig) """ Explanation: 5.3.4 'fd' lag classes The Freedman-Diaconis estimator can be used to derive the number of lag classes again from an optimal lag class width like: $$ h = 2\frac{IQR}{x^{1/3}} $$ As it is based on the interquartile range (IQR), it is very robust to outlier. That makes it a suitable method to estimate lag classes on non-normal distance matrices. On the other side it usually over-estimates the $n$ for small datasets. Thus it should only be used on medium to small datasets. End of explanation """ # apply binning bins, n = skg.binning.auto_derived_lags(V.distance, 'doane', None) # get the histogram count, _ = np.histogram(V.distance, bins=bins) fig = go.Figure( go.Bar(x=bins, y=count), layout=dict(template='plotly_white', title=r"$\texttt{'doane'}~~binning~~%d~classes$" % n) ) iplot(fig) """ Explanation: 5.3.5 'doane' lag classes Doane's rule is an extension to Sturge's rule that takes the skewness of the distance matrix into account. It was found to be a very reasonable choice on most datasets where the other estimators didn't yield good results. It is defined like: $$ \begin{split} n = 1 + \log_{2}(s) + \log_2\left(1 + \frac{|g|}{k}\right) \ g = E\left[\left(\frac{x - \mu_g}{\sigma}\right)^3\right]\ k = \sqrt{\frac{6(s - 2)}{(s + 1)(s + 3)}} \end{split} $$ End of explanation """ # use a exponential model V.set_model('spherical') # set the maxlag V.maxlag = 'median' """ Explanation: 5.4 Variograms The following section will give an overview on the influence of the chosen binning method on the resulting variogram. All parameters will be the same for all variograms, so any change is due to the lag class binning. The variogram will use a maximum lag of 200 to get rid of the very thin last bins at large distances. The maxlag is very close to the effective range of the variogram, thus you can only see differences in sill. But the variogram fitting is not at the focus of this tutorial. You can also change the parameter and fit a more suitable spatial model End of explanation """ # set the new binning method V.bin_func = 'even' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.1 'even' lag classes End of explanation """ # set the new binning method V.bin_func = 'uniform' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.2 'uniform' lag classes End of explanation """ # set the new binning method V.bin_func = 'kmeans' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.3 'kmeans' lag classes End of explanation """ # set the new binning method V.bin_func = 'ward' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.4 'ward' lag classes End of explanation """ # set the new binning method V.bin_func = 'sturges' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.5 'sturges' lag classes End of explanation """ # set the new binning method V.bin_func = 'scott' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.6 'scott' lag classes End of explanation """ # set the new binning method V.bin_func = 'fd' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.7 'fd' lag classes End of explanation """ # set the new binning method V.bin_func = 'sqrt' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.8 'sqrt' lag classes End of explanation """ # set the new binning method V.bin_func = 'doane' # plot fig = V.plot(show=False) print(f'"{V._bin_func_name}" adjusted {V.n_lags} lag classes - range: {np.round(V.cof[0], 1)} sill: {np.round(V.cof[1], 1)}') fig.update_layout(template='plotly_white') iplot(fig) """ Explanation: 5.4.9 'doane' lag classes End of explanation """
lizardsystem/lizard-connector
Example_EN.ipynb
gpl-3.0
result = cli.timeseries.get(uuid="867b166a-fa39-457d-a9e9-4bcb2ff04f61") result.metadata """ Explanation: The connection with Lizard is made. Above all endpoints are shown Now we collect the metadata for a first timeseries with uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61: End of explanation """ queryparams = { "end":1518631200000, "start":946681200000, "window":"month" } result = cli.timeseries.get(uuid="867b166a-fa39-457d-a9e9-4bcb2ff04f61", **queryparams) result.metadata """ Explanation: Download of timeseries with uuid 867b166a-fa39-457d-a9e9-4bcb2ff04f61 From December 31st 1999 untill Februari 14th 2018. This is the metadata: End of explanation """ result.data[0] """ Explanation: And this is the data: End of explanation """ location__uuid = result.metadata['location__uuid'][0] metadata_multiple, events_multiple = cli.timeseries.get(location__uuid=location__uuid, **queryparams) columns = [x for x in metadata_multiple.columns if "observation_type" in x or "uuid" in x] metadata_multiple[columns] """ Explanation: Now we can search for other timeseries based on the metadata. We are going to look at the correlation between precipitation, evaporation and windspeed. First the observation type metadata: End of explanation """ indexed_events = [e.set_index('timestamp') for e in events_multiple if 'timestamp' in e.columns] first = max([indexed.index[0] for indexed in indexed_events]) last = min([indexed.index[-1] for indexed in indexed_events]) print(first, last) indexed_events_ranged = [e[first:last] for e in indexed_events] [e.shape for e in indexed_events_ranged] """ Explanation: The data has different lengths. We cannot correlate the data unless we slice the data. Here we make sure the data is of the same length. Because one of our queryparameters was {"window":"month"} we already resampled the data. End of explanation """ observation_types = metadata_multiple['observation_type__parameter'].tolist() max_weerdata = pd.DataFrame({observation_type: events['max'] for observation_type, events in zip(observation_types, indexed_events_ranged)}) max_weerdata """ Explanation: We can see the data has the same length. Now we select the max for the different timeseries: End of explanation """ max_weerdata.corr() """ Explanation: At last a correlation is easily calculated because of pandas: End of explanation """
cesarcontre/Simulacion2017
Modulo3/.ipynb_checkpoints/Clase23_Repaso1(Mod.3)-checkpoint.ipynb
mit
# Librería de cálculo simbólico import sympy as sym # Para imprimir en formato TeX from sympy import init_printing; init_printing(use_latex='mathjax') """ Explanation: Repaso (Módulo 3) El tema principal en este módulo fue optimización. Al finalizar este módulo, se espera que ustedes tengan las siguientes competencias - Realizar optimizaciones de funciones escalares en un dominio dado usando sympy. - Dado un problema de programación lineal, llevarlo a la forma que vimos en clase y resolverlo. - Ajustar curvas a conjuntos de puntos dados. - Diseñar clasificadores binarios con regresión logística para conjuntos de datos linealmente separables. Ejemplo 1. Optimización de funciones escalares usando sympy En clase vimos cómo optimizar funciones escalares dado un invervalo cerrado finito utilizando sympy. Ustedes, además, realizaron una tarea donde hicieron una función genérica para optimizar cualquier función dada. Recordamos en este ejemplo como optimizar este tipo de funciones. 1.1 Obtener el máximo y el mínimo absoluto de la función $$f(x)=2x^4-16x^3+32x^2+5$$ en el intervalo $[-1, 4.5]$. Graficar la función en este intervalo, junto con el punto donde ocurre el máximo (en color rojo) y el punto donde ocurre el mínimo (en color azul). Les recuerdo nada más como imprimir en formato LaTeX. End of explanation """ import numpy as np import matplotlib.pyplot as plt %matplotlib inline """ Explanation: ¿Qué más librerías necesitamos? End of explanation """ def f(x): return 2*x**4-16*x**3+32*x**2+5 sym.var('x', real = True) f(x) """ Explanation: ¿Qué más sigue? - Declarar variable y función. End of explanation """ df = sym.diff(f(x), x) xc = sym.solve(df, x) xc """ Explanation: Sacar derivada e igualar a cero. End of explanation """ f(-1), f(4.5), f(xc[0]), f(xc[1]), f(xc[2]) """ Explanation: Evaluar en los extremos y en los puntos críticos. End of explanation """ xnum = np.linspace(-1, 4.5, 100) plt.figure(figsize=(8,6)) plt.plot(xnum, f(xnum), 'k', lw = 2, label = '$y=f(x)$') plt.plot([-1], [f(-1)], '*r', ms = 10, label = '$max_{-1\leq x\leq 4.5}f(x)=55$') plt.plot([xc[0], xc[2]], [f(xc[0]), f(xc[2])], '*b', ms = 10, label = '$min_{-1\leq x\leq 4.5}f(x)=5$') plt.legend(loc='best') plt.xlabel('$x$') plt.ylabel('$y$') plt.show() """ Explanation: El más grande es el máximo absoluto y el más pequeño es el mínimo absoluto. Gráfico. End of explanation """ def A(theta): return (1+sym.sin(theta))*sym.cos(theta) sym.var('theta', real = True) A(theta) """ Explanation: 1.2 Encontrar el ángulo $\theta$ que maximiza el área de un trapecio isósceles cuya base menor y segmentos laterales miden exactamente una unidad. Graficar la función área respecto al ángulo $\theta$ en el intervalo donde tiene sentido, junto con el punto donde ocurre el máximo (en color rojo). Declarar variable y función. End of explanation """ dA = sym.diff(A(theta), theta) dA thetac = sym.solve(dA, theta) thetac """ Explanation: Sacar derivada e igualar a cero. End of explanation """ A(0), A(thetac[1]), A(np.pi/2) """ Explanation: Evaluar en los extremos y en los puntos críticos. End of explanation """ thetanum = np.linspace(0, np.pi/2, 100) Anum = sym.lambdify([theta], A(theta), 'numpy') plt.figure(figsize=(8,6)) plt.plot(thetanum, Anum(thetanum), 'k', lw = 2, label = '$y=A(\theta)$') plt.plot([thetac[1]], [A(thetac[1])], '*r', ms = 10, label = '$max_{0\leq x\leq \pi/2}A(\theta)$') plt.legend(loc='best') plt.xlabel('$\theta$') plt.ylabel('$y$') plt.show() """ Explanation: El más grande es el máximo absoluto. End of explanation """ f = -np.arange(1, 5) A = np.array([[4, 3, 2, 1], [-1, -1, -1, -1]]) A = np.concatenate((A, -np.eye(4)), axis = 0) b = np.array([10, -1, 0, 0, 0, 0]) Aeq = np.array([[1, 0, -1, 2]]) beq = np.array([2]) import pyomo_utilities x, obj = pyomo_utilities.linprog(f, A, b, Aeq, beq) x obj = -obj + 5 obj """ Explanation: Ejemplo 2. Programación lineal En clase vimos cómo llevar los problemas de programación lineal a la forma \begin{equation} \begin{array}{ll} \min_{\boldsymbol{x}} & \boldsymbol{f}^T\boldsymbol{x} \ \text{s. a. } & \boldsymbol{A}{eq}\boldsymbol{x}=\boldsymbol{b}{eq} \ & \boldsymbol{A}\boldsymbol{x}\leq\boldsymbol{b}. \end{array} \end{equation} Además, aprendimos a resolver los problemas en esta forma con la función linprog del paquete pyomo_utilities.py, proporcionando únicamente los parámetros $\boldsymbol{f}$, $\boldsymbol{A}$ y $\boldsymbol{b}$ ($\boldsymbol{A}{eq}$ y $\boldsymbol{b}{eq}$, de ser necesario). 2.1 Maximizar la función $x_1+2x_2+3x_3+4x_4+5$ sujeta a las restricciones $4x_1+3x_2+2x_3+x_4\leq10$, $x_1−x_3+2x_4=2$, $x_1+x_2+x_3+x_4\geq1$, $x_1\geq0$, $x_2\geq0$, $x_3\geq0$, $x_4\geq0$. End of explanation """ import pandas as pd df = pd.DataFrame(columns=['Energia', 'Proteina', 'Calcio', 'Precio', 'Limite_diario'], index=['Avena', 'Pollo', 'Huevos', 'Leche', 'Pastel', 'Frijoles_cerdo']) df.loc[:,'Energia']=[110, 205, 160, 160, 420, 260] df.loc[:,'Proteina']=[4, 32, 13, 8, 4, 14] df.loc[:,'Calcio']=[2, 12, 54, 285, 22, 80] df.loc[:,'Precio']=[3, 24, 13, 9, 20, 19] df.loc[:,'Limite_diario']=[4, 3, 2, 8, 2, 2] df """ Explanation: 2.2 Una dieta ideal debe satisfacer (o posiblemente, exceder) ciertos requerimientos nutricionales básicos al menor costo posible, ser variada y buena al paladar. ¿Cómo podemos formular dicha dieta? Suponga que solo tenemos acceso a las siguientes comidas: End of explanation """ f = np.array(df.loc[:,'Precio']) A = -np.array([df.loc[:,'Energia'], df.loc[:,'Proteina'], df.loc[:,'Calcio']]) A = np.concatenate((A, np.eye(6)), axis = 0) A = np.concatenate((A, -np.eye(6)), axis = 0) b = np.array([-2000, -55, -800]) b = np.concatenate((b, df.loc[:,'Limite_diario'])) b = np.concatenate((b, np.zeros((6,)))) x, obj = pyomo_utilities.linprog(f, A, b) x obj """ Explanation: Luego de consultar expertos en nutrición tenemos que una dieta satisfactoria tiene por lo menos $2000$ kcal de energía, $55$ g de proteina, y $800$ mg de calcio. Para imponer la variedad se ha decidido limitar el número de porciones diarias de cada una de las comidas como se indica en la tabla. End of explanation """ data_file = 'forest_mex.csv' data = pd.read_csv(data_file, header = None) x = data.iloc[:, 0].values y = data.iloc[:, 1].values plt.figure() plt.plot(x, y) plt.show() beta1 = pyomo_utilities.curve_polyfit(x, y, 1) beta2 = pyomo_utilities.curve_polyfit(x, y, 2) beta3 = pyomo_utilities.curve_polyfit(x, y, 3) yhat1 = beta1.dot(np.array([x**i for i in range(2)])) yhat2 = beta2.dot(np.array([x**i for i in range(3)])) yhat3 = beta3.dot(np.array([x**i for i in range(4)])) plt.figure(figsize = (8,6)) plt.plot(x, y, '*b', label = 'datos reales') plt.plot(x, yhat1, '-r', label = 'ajuste 1') plt.plot(x, yhat2, '-g', label = 'ajuste 2') plt.plot(x, yhat3, '-k', label = 'ajuste 3') plt.legend(loc = 'best') plt.xlabel('$x$') plt.ylabel('$y$') plt.show() ems = [] ems.append(sum((y-yhat1)**2)) ems.append(sum((y-yhat2)**2)) ems.append(sum((y-yhat3)**2)) plt.figure(figsize = (8,6)) plt.plot(np.arange(3)+1, ems, '*b') plt.xlabel('$n$') plt.ylabel('$e_{ms}(n)$') plt.show() """ Explanation: Ejemplo 3. Ajuste de curvas El archivo forest_mex.csv contiene información histórica anual del porcentaje de área forestal de México. La primer columna corresponde a los años y la segunda corresponde al porcentaje de área forestal. Tomado de: https://data.worldbank.org/indicator/AG.LND.FRST.ZS?view=chart. Usando los años como variable independiente $x$ y el porcentaje de área forestal como variable dependiente $y$, ajustar polinomios de grado 1 hasta grado 3. Mostrar en un solo gráfico los datos de porcentaje de área forestal contra los años, y los polinomios ajustados. Graficar el error cuadrático acumulado contra el número de términos. ¿Cuál es el polinomio que mejor se ajusta? Con los polinomios ajustados en el punto anterior, estime el año en que México quedará sin area forestal (suponiendo que todo sigue igual). End of explanation """ sym.var('a', real = True) Af1 = beta1[0]+beta1[1]*a Af2 = beta2[0]+beta2[1]*a+beta2[2]*a**2 Af3 = beta3[0]+beta3[1]*a+beta3[2]*a**2+beta3[3]*a**3 Af1, Af2, Af3 a1 = sym.solve(Af1, a) a2 = sym.solve(Af2, a) a3 = sym.solve(Af3, a) a1 a2 a3 """ Explanation: El polinomio que mejor se ajusta es el cúbico. End of explanation """ X = 10*np.random.random((100, 2)) Y = (X[:, 1] > X[:, 0]**2)*1 plt.figure(figsize = (8,6)) plt.scatter(X[:,0], X[:,1], c=Y) plt.show() Xe = X[0:80, :] Ye = Y[0:80] B = pyomo_utilities.logreg_clas(Xe, Ye) """ Explanation: Ejemplo 4. Clasificador binario Hasta ahora hemos visto como diseñar clasificadores binarios dados un conjunto de entrenamiento. Sin embargo, no le hemos dado uso. Después del diseño de un clasificador, lo que sigue es entregarle datos de entrada y que él los clasifique. Para los datos de la tarea de clasificación binaria, diseñaremos un clasificador binario por regresión logística lineal utilizando únicamente los primeros 80 datos. Luego, usaremos el clasificador diseñado para clasificar a los 20 datos restantes. ¿Cuántos datos se clasifican bien? ¿Cuántos mal? End of explanation """
GoogleCloudPlatform/python-docs-samples
notebooks/tutorials/storage/Storage command-line tool.ipynb
apache-2.0
!gsutil help """ Explanation: Storage command-line tool The Google Cloud SDK provides a set of commands for working with data stored in Cloud Storage. This notebook introduces several gsutil commands for interacting with Cloud Storage. Note that shell commands in a notebook must be prepended with a !. List available commands The gsutil command can be used to perform a wide array of tasks. Run the help command to view a list of available commands: End of explanation """ # Replace the string below with a unique name for the new bucket bucket_name = "your-new-bucket" """ Explanation: Create a storage bucket Buckets are the basic containers that hold your data. Everything that you store in Cloud Storage must be contained in a bucket. You can use buckets to organize your data and control access to your data. Start by defining a globally unique name. For more information about naming buckets, see Bucket name requirements. End of explanation """ !gsutil mb gs://{bucket_name}/ """ Explanation: NOTE: In the examples below, the bucket_name and project_id variables are referenced in the commands using {} and $. If you want to avoid creating and using variables, replace these interpolated variables with literal values and remove the {} and $ characters. Next, create the new bucket with the gsutil mb command: End of explanation """ # Replace the string below with your project ID project_id = "your-project-id" !gsutil ls -p $project_id """ Explanation: List buckets in a project Replace 'your-project-id' in the cell below with your project ID and run the cell to list the storage buckets in your project. End of explanation """ !gsutil ls -L -b gs://{bucket_name}/ """ Explanation: The response should look like the following: gs://your-new-bucket/ Get bucket metadata The next cell shows how to get information on metadata of your Cloud Storage buckets. To learn more about specific bucket properties, see Bucket locations and Storage classes. End of explanation """ !gsutil cp resources/us-states.txt gs://{bucket_name}/ """ Explanation: The response should look like the following: gs://your-new-bucket/ : Storage class: MULTI_REGIONAL Location constraint: US ... Upload a local file to a bucket Objects are the individual pieces of data that you store in Cloud Storage. Objects are referred to as "blobs" in the Python client library. There is no limit on the number of objects that you can create in a bucket. An object's name is treated as a piece of object metadata in Cloud Storage. Object names can contain any combination of Unicode characters (UTF-8 encoded) and must be less than 1024 bytes in length. For more information, including how to rename an object, see the Object name requirements. End of explanation """ !gsutil ls -r gs://{bucket_name}/** """ Explanation: List blobs in a bucket End of explanation """ !gsutil ls -L gs://{bucket_name}/us-states.txt """ Explanation: The response should look like the following: gs://your-new-bucket/us-states.txt Get a blob and display metadata See Viewing and editing object metadata for more information about object metadata. End of explanation """ !gsutil cp gs://{bucket_name}/us-states.txt resources/downloaded-us-states.txt """ Explanation: The response should look like the following: gs://your-new-bucket/us-states.txt: Creation time: Fri, 08 Feb 2019 05:23:28 GMT Update time: Fri, 08 Feb 2019 05:23:28 GMT Storage class: STANDARD Content-Language: en Content-Length: 637 Content-Type: text/plain ... Download a blob to a local directory End of explanation """ !gsutil rm gs://{bucket_name}/us-states.txt """ Explanation: Cleaning up Delete a blob End of explanation """ !gsutil rm -r gs://{bucket_name}/ """ Explanation: Delete a bucket The following command deletes all objects in the bucket before deleting the bucket itself. End of explanation """
fotis007/python_intermediate
Python_2_8.ipynb
gpl-3.0
from sklearn import datasets iris = datasets.load_iris() digits = datasets.load_digits() iris.data[10] iris.target print(digits.data) digits.target digits.images[0] from sklearn import svm clf = svm.SVC(gamma=0.001, C=100.) clf.fit(digits.data[:-1], digits.target[:-1]) clf.predict(digits.data[-1]) from sklearn import svm from sklearn import datasets clf = svm.SVC() iris = datasets.load_iris() X, y = iris.data, iris.target clf.fit(X, y) import pickle s = pickle.dumps(clf) clf2 = pickle.loads(s) clf2.predict(X[0]) y[0] from sklearn.externals import joblib joblib.dump(clf, 'filename.pkl') clf = joblib.load('filename.pkl') """ Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Datenanalyse-4:-Maschinelles-Lernen" data-toc-modified-id="Datenanalyse-4:-Maschinelles-Lernen-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Datenanalyse 4: Maschinelles Lernen</a></div><div class="lev1 toc-item"><a href="#An-introduction-to-machine-learning-with-scikit-learn" data-toc-modified-id="An-introduction-to-machine-learning-with-scikit-learn-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>An introduction to machine learning with scikit-learn</a></div><div class="lev1 toc-item"><a href="#A-tutorial-on-statistical-learning-for-scientific-data-processing" data-toc-modified-id="A-tutorial-on-statistical-learning-for-scientific-data-processing-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>A tutorial on statistical-learning for scientific data processing</a></div><div class="lev3 toc-item"><a href="#Nearest-Neighbour" data-toc-modified-id="Nearest-Neighbour-301"><span class="toc-item-num">3.0.1&nbsp;&nbsp;</span>Nearest Neighbour</a></div><div class="lev3 toc-item"><a href="#Model-selection" data-toc-modified-id="Model-selection-302"><span class="toc-item-num">3.0.2&nbsp;&nbsp;</span>Model selection</a></div><div class="lev3 toc-item"><a href="#Unsupervised-Clustering" data-toc-modified-id="Unsupervised-Clustering-303"><span class="toc-item-num">3.0.3&nbsp;&nbsp;</span>Unsupervised Clustering</a></div><div class="lev2 toc-item"><a href="#Maschinelles-Lernen-mit-Text" data-toc-modified-id="Maschinelles-Lernen-mit-Text-31"><span class="toc-item-num">3.1&nbsp;&nbsp;</span>Maschinelles Lernen mit Text</a></div> ## Datenanalyse 4: Maschinelles Lernen Das Folgende sind Ausschnitte aus dem <a href="http://scikit-learn.org/stable/tutorial/index.html">Tutorial für scikit-learn</a>. ## An introduction to machine learning with scikit-learn End of explanation """ from sklearn import datasets iris = datasets.load_iris() data = iris.data data.shape digits = datasets.load_digits() digits.images.shape import pylab as pl pl.imshow(digits.images[-1], cmap=pl.cm.gray_r) pl.show() data = digits.images.reshape((digits.images.shape[0], -1)) """ Explanation: A tutorial on statistical-learning for scientific data processing End of explanation """ import numpy as np from sklearn import datasets iris = datasets.load_iris() iris_X = iris.data iris_y = iris.target np.unique(iris_y) # Split iris data in train and test data # A random permutation, to split the data randomly np.random.seed(0) indices = np.random.permutation(len(iris_X)) iris_X_train = iris_X[indices[:-10]] iris_y_train = iris_y[indices[:-10]] iris_X_test = iris_X[indices[-10:]] iris_y_test = iris_y[indices[-10:]] # Create and fit a nearest-neighbor classifier from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier() knn.fit(iris_X_train, iris_y_train) knn.predict(iris_X_test) iris_y_test diabetes = datasets.load_diabetes() diabetes_X_train = diabetes.data[:-20] diabetes_X_test = diabetes.data[-20:] diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] from sklearn import linear_model regr = linear_model.LinearRegression() regr.fit(diabetes_X_train, diabetes_y_train) print(regr.coef_) np.mean((regr.predict(diabetes_X_test)-diabetes_y_test)**2) regr.score(diabetes_X_test, diabetes_y_test) X = np.c_[ .5, 1].T y = [.5, 1] test = np.c_[ 0, 2].T regr = linear_model.LinearRegression() import pylab as pl pl.figure() np.random.seed(0) for _ in range(6): this_X = .1*np.random.normal(size=(2, 1)) + X regr.fit(this_X, y) pl.plot(test, regr.predict(test)) pl.scatter(this_X, y, s=3) pl.show() regr = linear_model.Ridge(alpha=.1) pl.figure() np.random.seed(0) for _ in range(6): this_X = .1*np.random.normal(size=(2, 1)) + X regr.fit(this_X, y) pl.plot(test, regr.predict(test)) pl.scatter(this_X, y, s=3) pl.show() alphas = np.logspace(-4, -1, 6) from __future__ import print_function print([regr.set_params(alpha=alpha ).fit(diabetes_X_train, diabetes_y_train, ).score(diabetes_X_test, diabetes_y_test) for alpha in alphas]) regr = linear_model.Lasso() scores = [regr.set_params(alpha=alpha ).fit(diabetes_X_train, diabetes_y_train ).score(diabetes_X_test, diabetes_y_test) for alpha in alphas] best_alpha = alphas[scores.index(max(scores))] regr.alpha = best_alpha regr.fit(diabetes_X_train, diabetes_y_train) print(regr.coef_) logistic = linear_model.LogisticRegression(C=1e5) logistic.fit(iris_X_train, iris_y_train) from sklearn import svm svc = svm.SVC(kernel='linear') svc.fit(iris_X_train, iris_y_train) svc = svm.SVC(kernel='rbf') """ Explanation: Nearest Neighbour End of explanation """ from sklearn import datasets, svm digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target svc = svm.SVC(C=1, kernel='linear') svc.fit(X_digits[:-100], y_digits[:-100]).score(X_digits[-100:], y_digits[-100:]) import numpy as np X_folds = np.array_split(X_digits, 3) y_folds = np.array_split(y_digits, 3) scores = list() for k in range(3): # We use 'list' to copy, in order to 'pop' later on X_train = list(X_folds) X_test = X_train.pop(k) X_train = np.concatenate(X_train) y_train = list(y_folds) y_test = y_train.pop(k) y_train = np.concatenate(y_train) scores.append(svc.fit(X_train, y_train).score(X_test, y_test)) print(scores) from sklearn import cross_validation k_fold = cross_validation.KFold(n=6, n_folds=3) for train_indices, test_indices in k_fold: print('Train: %s | test: %s' % (train_indices, test_indices)) >>> kfold = cross_validation.KFold(len(X_digits), n_folds=3) >>> [svc.fit(X_digits[train], y_digits[train]).score(X_digits[test], y_digits[test]) ... for train, test in kfold] cross_validation.cross_val_score(svc, X_digits, y_digits, cv=kfold, n_jobs=-1) >>> from sklearn.grid_search import GridSearchCV >>> gammas = np.logspace(-6, -1, 10) >>> clf = GridSearchCV(estimator=svc, param_grid=dict(gamma=gammas), ... n_jobs=-1) >>> clf.fit(X_digits[:1000], y_digits[:1000]) >>> clf.best_score_ clf.best_estimator_.gamma == 1e-6 >>> # Prediction performance on test set is not as good as on train set >>> clf.score(X_digits[1000:], y_digits[1000:]) cross_validation.cross_val_score(clf, X_digits, y_digits) >>> from sklearn import linear_model, datasets >>> lasso = linear_model.LassoCV() >>> diabetes = datasets.load_diabetes() >>> X_diabetes = diabetes.data >>> y_diabetes = diabetes.target >>> lasso.fit(X_diabetes, y_diabetes) >>> # The estimator chose automatically its lambda: >>> lasso.alpha_ """ Explanation: Model selection End of explanation """ >>> from sklearn import cluster, datasets >>> iris = datasets.load_iris() >>> X_iris = iris.data >>> y_iris = iris.target >>> k_means = cluster.KMeans(n_clusters=3) >>> k_means.fit(X_iris) print(k_means.labels_[::10]) print(y_iris[::10]) >>> import scipy as sp >>> try: ... lena = sp.lena() ... except AttributeError: ... from scipy import misc ... lena = misc.lena() >>> X = lena.reshape((-1, 1)) # We need an (n_sample, n_feature) array >>> k_means = cluster.KMeans(n_clusters=5, n_init=1) >>> k_means.fit(X) >>> values = k_means.cluster_centers_.squeeze() >>> labels = k_means.labels_ >>> lena_compressed = np.choose(labels, values) >>> lena_compressed.shape = lena.shape from sklearn.feature_extraction.image import grid_to_graph from sklearn.cluster import AgglomerativeClustering ############################################################################### # Generate data lena = sp.misc.lena() # Downsample the image by a factor of 4 lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2] X = np.reshape(lena, (-1, 1)) ############################################################################### # Define the structure A of the data. Pixels connected to their neighbors. connectivity = grid_to_graph(*lena.shape) ############################################################################### # Compute clustering print("Compute structured hierarchical clustering...") n_clusters = 15 # number of regions ward = AgglomerativeClustering(n_clusters=n_clusters, linkage='ward', connectivity=connectivity).fit(X) label = np.reshape(ward.labels_, lena.shape) print("Number of pixels: ", label.size) print("Number of clusters: ", np.unique(label).size) >>> digits = datasets.load_digits() >>> images = digits.images >>> X = np.reshape(images, (len(images), -1)) >>> connectivity = grid_to_graph(*images[0].shape) >>> agglo = cluster.FeatureAgglomeration(connectivity=connectivity, ... n_clusters=32) >>> agglo.fit(X) >>> X_reduced = agglo.transform(X) >>> X_approx = agglo.inverse_transform(X_reduced) >>> images_approx = np.reshape(X_approx, images.shape) >>> # Create a signal with only 2 useful dimensions >>> x1 = np.random.normal(size=100) >>> x2 = np.random.normal(size=100) >>> x3 = x1 + x2 >>> X = np.c_[x1, x2, x3] >>> from sklearn import decomposition >>> pca = decomposition.PCA() >>> pca.fit(X) print(pca.explained_variance_) # As we can see, only the 2 first components are useful >>> pca.n_components = 2 >>> X_reduced = pca.fit_transform(X) >>> X_reduced.shape >>> # Generate sample data >>> time = np.linspace(0, 10, 2000) >>> s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal >>> s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal >>> S = np.c_[s1, s2] >>> S += 0.2 * np.random.normal(size=S.shape) # Add noise >>> S /= S.std(axis=0) # Standardize data >>> # Mix data >>> A = np.array([[1, 1], [0.5, 2]]) # Mixing matrix >>> X = np.dot(S, A.T) # Generate observations >>> # Compute ICA >>> ica = decomposition.FastICA() >>> S_ = ica.fit_transform(X) # Get the estimated sources >>> A_ = ica.mixing_.T >>> np.allclose(X, np.dot(S_, A_) + ica.mean_) """ Explanation: Unsupervised Clustering End of explanation """ categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med'] from sklearn.datasets import fetch_20newsgroups twenty_train = fetch_20newsgroups(subset='train', categories=categories, shuffle=True, random_state=42) twenty_train.target_names len(twenty_train.data) len(twenty_train.filenames) print(twenty_train.target_names[twenty_train.target[0]]) twenty_train.target[:10] for t in twenty_train.target[:10]: print(twenty_train.target_names[t]) from sklearn.feature_extraction.text import CountVectorizer count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(twenty_train.data) X_train_counts.shape count_vect.vocabulary_.get(u'algorithm') from sklearn.feature_extraction.text import TfidfTransformer tfidf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts) X_train_tf = tfidf_transformer.transform(X_train_counts) X_train_tf.shape from sklearn.naive_bayes import MultinomialNB clf = MultinomialNB().fit(X_train_tf, twenty_train.target) docs_new = ['God is love', 'OpenGL on the GPU is fast'] X_new_counts = count_vect.transform(docs_new) X_new_tfidf = tfidf_transformer.transform(X_new_counts) predicted = clf.predict(X_new_tfidf) for doc, category in zip(docs_new, predicted): print('%r => %s' % (doc, twenty_train.target_names[category])) from sklearn.pipeline import Pipeline text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', MultinomialNB()),]) text_clf = text_clf.fit(twenty_train.data, twenty_train.target) import numpy as np twenty_test = fetch_20newsgroups(subset='test', categories=categories, shuffle=True, random_state=42) docs_test = twenty_test.data predicted = text_clf.predict(docs_test) np.mean(predicted == twenty_test.target) from sklearn.linear_model import SGDClassifier text_clf = Pipeline([('vect', CountVectorizer()), ('tfidf', TfidfTransformer()), ('clf', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-3, n_iter=5)),]) _ = text_clf.fit(twenty_train.data, twenty_train.target) predicted = text_clf.predict(docs_test) np.mean(predicted == twenty_test.target) from sklearn import metrics print(metrics.classification_report(twenty_test.target, predicted, target_names=twenty_test.target_names)) from sklearn.grid_search import GridSearchCV parameters = {'vect__ngram_range': [(1, 1), (1, 2)], 'tfidf__use_idf': (True, False), 'clf__alpha': (1e-2, 1e-3),} gs_clf = GridSearchCV(text_clf, parameters, n_jobs=-1) gs_clf = gs_clf.fit(twenty_train.data[:400], twenty_train.target[:400]) twenty_train.target_names[gs_clf.predict(['God is love'])] best_parameters, score, _ = max(gs_clf.grid_scores_, key=lambda x: x[1]) for param_name in sorted(parameters.keys()): print("%s: %r" % (param_name, best_parameters[param_name])) score """ Explanation: Maschinelles Lernen mit Text End of explanation """
google/pikov
python/samples/2_connect.ipynb
apache-2.0
names = {} for node in graph: for edge in node: if edge.guid == "169a81aefca74e92b45e3fa03c7021df": value = node[edge].value if value in names: raise ValueError('name: "{}" defined twice'.format(value)) names[value] = node names["ctor"] def name_to_guid(name): if name not in names: return None node = names[name] if not hasattr(node, "guid"): return None return node.guid """ Explanation: Build names mapping To make it a little easier to check that I'm using the correct guids, construct a mapping from names back to guid. Note: this adds a constraint that no two nodes have the same name, which should not be enforced for general semantic graphs. End of explanation """ from pikov.sprite import Bitmap, Clip, Frame, FrameList, Resource, Transition """ Explanation: Pikov Classes These classes are the core resources used in defining a "Pikov" file. Note: ideally these classes could be derived from the graph itself, but I don't (yet) encode type or field information in the pikov.json semantic graph. End of explanation """ resource = Resource(graph, guid=name_to_guid("spritesheet")) spritesheet = [] for row in range(16): for column in range(16): sprite_number = row * 16 + column bitmap_name = "bitmap[{}]".format(sprite_number) bitmap = Bitmap(graph, guid=name_to_guid(bitmap_name)) spritesheet.append(bitmap) """ Explanation: Gamekitty Create instances of the Pikov classes to define a concrete Pikov graph, based on my "gamekitty" animations. Load the spritesheet In the previous notebook, we chopped the spritesheet into bitmaps. Find those and save them to an array so that they can be indexed as they were in the original PICO-8 gamekitty doodle. End of explanation """ def find_nodes(graph, ctor, cls): nodes = set() # TODO: With graph formats that have indexes, there should be a faster way. for node in graph: if node[names["ctor"]] == ctor: node = cls(graph, guid=node.guid) nodes.add(node) return nodes def find_frames(graph): return find_nodes(graph, names["frame"], Frame) def find_transitions(graph): return find_nodes(graph, names["transition"], Transition) def find_absorbing_frames(graph): transitions = find_transitions(graph) target_frames = set() source_frames = set() for transition in transitions: target_frames.add(transition.target.guid) source_frames.add(transition.source.guid) return target_frames - source_frames # In but not out. Dead end! MICROS_12_FPS = int(1e6 / 12) # 12 frames per second MICROS_24_FPS = int(1e6 / 24) def connect_frames(graph, transition_name, source, target): transition = Transition(graph, guid=name_to_guid(transition_name)) transition.name = transition_name transition.source = source transition.target = target return transition sit = Clip(graph, guid=name_to_guid("clip[sit]")) sit sit_to_stand = Clip(graph, guid=name_to_guid("clip[sit_to_stand]")) sit_to_stand stand_waggle= Clip(graph, guid=name_to_guid("clip[stand_waggle]")) stand_waggle connect_frames( graph, "transitions[sit_to_stand, stand_waggle]", sit_to_stand[-1], stand_waggle[0]) stand_to_sit = Clip(graph, guid=name_to_guid("clip[stand_to_sit]")) stand_to_sit connect_frames( graph, "transitions[stand_waggle, stand_to_sit]", stand_waggle[-1], stand_to_sit[0]) connect_frames( graph, "transitions[stand_to_sit, sit]", stand_to_sit[-1], sit[0]) sit_paw = Clip(graph, guid=name_to_guid("clip[sit_paw]")) sit_paw connect_frames( graph, "transitions[sit_paw, sit]", sit_paw[-1], sit[0]) connect_frames( graph, "transitions[sit, sit_paw]", sit[-1], sit_paw[0]) sit_to_crouch = Clip(graph, guid=name_to_guid("clip[sit_to_crouch]")) connect_frames( graph, "transitions[sit, sit_to_crouch]", sit[-1], sit_to_crouch[0]) crouch = Clip(graph, guid=name_to_guid("clip[crouch]")) connect_frames( graph, "transitions[sit_to_crouch, crouch]", sit_to_crouch[-1], crouch[0]) crouch_to_sit = Clip(graph, guid=name_to_guid("clip[crouch_to_sit]")) connect_frames( graph, "transitions[crouch_to_sit, sit]", crouch[-1], crouch_to_sit[0]) connect_frames( graph, "transitions[crouch_to_sit, sit]", crouch_to_sit[-1], sit[0]) find_absorbing_frames(graph) graph.save() """ Explanation: Create frames for each "clip" Each animation is defined in terms of sprite numbers. Sometimes a clip should loop, but sometimes it's only used as a transition between looping clips. End of explanation """
tensorflow/docs-l10n
site/ja/agents/tutorials/7_SAC_minitaur_tutorial.ipynb
apache-2.0
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Explanation: Copyright 2021 The TF-Agents Authors. End of explanation """ !sudo apt-get update !sudo apt-get install -y xvfb ffmpeg !pip install 'imageio==2.4.0' !pip install matplotlib !pip install tf-agents[reverb] !pip install pybullet """ Explanation: Actor-Learner APIを使用したSAC minitaur <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/agents/tutorials/7_SAC_minitaur_tutorial"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/agents/tutorials/7_SAC_minitaur_tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a> </td> <td><a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/agents/tutorials/7_SAC_minitaur_tutorial.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a></td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/agents/tutorials/7_SAC_minitaur_tutorial.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a> </td> </table> 前書き ここでは、Minitaur 環境で Soft Actor Critic エージェントをトレーニングする方法を紹介します。 DQN Colab にすでに精通されている場合は、馴染みやすいと思います。主な違いは次のとおりです。 エージェントを DQN から SAC に変更します。 Minitaur(CartPole よりもはるかに複雑な環境)環境でのトレーニング。Minitaur 環境は、四足歩行ロボットが前進するようにトレーニングすることを目的としています。 分散型強化学習のための TF-Agent Actor-Learner API を使用します。 API は、経験再生バッファーと変数コンテナ(パラメータサーバー)を使用した分散データ収集と、複数のデバイスにわたる分散トレーニングの両方をサポートしています。API は非常にシンプルでモジュール化されています。再生バッファーと可変コンテナには Reverb、GPU と TPU での分散トレーニングには TF DistributionStrategy API が使用されます。 以下の依存関係をインストールしていない場合は、実行します。 End of explanation """ import base64 import imageio import IPython import matplotlib.pyplot as plt import os import reverb import tempfile import PIL.Image import tensorflow as tf from tf_agents.agents.ddpg import critic_network from tf_agents.agents.sac import sac_agent from tf_agents.agents.sac import tanh_normal_projection_network from tf_agents.environments import suite_pybullet from tf_agents.metrics import py_metrics from tf_agents.networks import actor_distribution_network from tf_agents.policies import greedy_policy from tf_agents.policies import py_tf_eager_policy from tf_agents.policies import random_py_policy from tf_agents.replay_buffers import reverb_replay_buffer from tf_agents.replay_buffers import reverb_utils from tf_agents.train import actor from tf_agents.train import learner from tf_agents.train import triggers from tf_agents.train.utils import spec_utils from tf_agents.train.utils import strategy_utils from tf_agents.train.utils import train_utils tempdir = tempfile.gettempdir() """ Explanation: セットアップ まず、必要なさまざまなツールをインポートします。 End of explanation """ env_name = "MinitaurBulletEnv-v0" # @param {type:"string"} # Use "num_iterations = 1e6" for better results (2 hrs) # 1e5 is just so this doesn't take too long (1 hr) num_iterations = 100000 # @param {type:"integer"} initial_collect_steps = 10000 # @param {type:"integer"} collect_steps_per_iteration = 1 # @param {type:"integer"} replay_buffer_capacity = 10000 # @param {type:"integer"} batch_size = 256 # @param {type:"integer"} critic_learning_rate = 3e-4 # @param {type:"number"} actor_learning_rate = 3e-4 # @param {type:"number"} alpha_learning_rate = 3e-4 # @param {type:"number"} target_update_tau = 0.005 # @param {type:"number"} target_update_period = 1 # @param {type:"number"} gamma = 0.99 # @param {type:"number"} reward_scale_factor = 1.0 # @param {type:"number"} actor_fc_layer_params = (256, 256) critic_joint_fc_layer_params = (256, 256) log_interval = 5000 # @param {type:"integer"} num_eval_episodes = 20 # @param {type:"integer"} eval_interval = 10000 # @param {type:"integer"} policy_save_interval = 5000 # @param {type:"integer"} """ Explanation: ハイパーパラメータ End of explanation """ env = suite_pybullet.load(env_name) env.reset() PIL.Image.fromarray(env.render()) """ Explanation: 環境変数 RL の環境は、解決しようとしているタスクまたは問題を表しています。標準環境は、suitesを使用して TF-Agent で簡単に作成できます。OpenAI Gym、Atari、DM Control などのソースから環境を読み込むためのさまざまなsuitesが用意されています。これには、文字列の環境名が与えられます。 では、PybulletスイートからMinituar環境を読み込みましょう。 End of explanation """ print('Observation Spec:') print(env.time_step_spec().observation) print('Action Spec:') print(env.action_spec()) """ Explanation: この環境での目標は、エージェントがMinitaurロボットを制御し、可能な限り速く前進させられるようにポリシーをトレーニングすることです。エピソードには1000ステップあり、リターンはエピソード全体の報酬の合計になります。 環境が観察として提供する情報を見てみましょう。ポリシーは観察を使用して行動を生成します。 End of explanation """ collect_env = suite_pybullet.load(env_name) eval_env = suite_pybullet.load(env_name) """ Explanation: 観測はかなり複雑で、すべてのモーターの角度、速度、トルクを表す 28 個の値を受け取ります。それに対して環境は行動に関する [-1, 1] 間の値を 8 個受け取ることを期待します。これらの値は望ましいモーター角度です。 通常、2つの環境を作成します。1つ目はトレーニング中にデータを収集するため、もう2つ目は評価のための環境です。環境は純粋なpythonで記述され、Actor Learner APIが直接使用するnumpy配列を使用します。 End of explanation """ use_gpu = True #@param {type:"boolean"} strategy = strategy_utils.get_strategy(tpu=False, use_gpu=use_gpu) """ Explanation: 分散ストラテジー DistributionStrategy APIでは、データの並列処理を使用して、複数のGPUやTPUなどの複数のデバイス間でトレーニングステップの計算を実行できます。トレーニングステップは以下のとおりです。 トレーニングデータのバッチを受けとる デバイス間で分割する 前進ステップを計算する 損失のMEANを集計して計算する 後退ステップを計算し、勾配変数の更新を実行する TF-Agent Learner API と DistributionStrategy API を使用すると、以下のトレーニングロジックを変更せずに、トレーニングステップの実行を GPU(MirroredStrategy を使用)からTPU(TPUStrategyを使用)に簡単に切り替えることができます。 GPUを有効にする GPU で実行する場合は、まずノートブックで GPU を有効にする必要があります。 [編集]→[ノートブック設定]に移動します [ハードウェアアクセラレータ]ドロップダウンから GPU を選択します ストラテジーの選択 strategy_utilsを使用してストラテジーを生成します。 内部的に、パラメータを渡します。 use_gpu = Falseはtf.distribute.get_strategy()を返します。 この場合、CPU を使用します。 use_gpu = Trueはtf.distribute.MirroredStrategy()を返します。この場合、1 台のマシンのTensorFlowにより認識されるすべての GPU を使用します。 End of explanation """ observation_spec, action_spec, time_step_spec = ( spec_utils.get_tensor_specs(collect_env)) with strategy.scope(): critic_net = critic_network.CriticNetwork( (observation_spec, action_spec), observation_fc_layer_params=None, action_fc_layer_params=None, joint_fc_layer_params=critic_joint_fc_layer_params, kernel_initializer='glorot_uniform', last_kernel_initializer='glorot_uniform') """ Explanation: 以下に示すように、すべての変数とエージェントはstrategy.scope()の下に作成する必要があります。 エージェント SAC エージェントを作成するには、まず、トレーニングするネットワークを作成する必要があります。SAC は actor-critic エージェントなので、2 つのネットワークを必要とします。 critic は、Q(s,a) の値を推定します。つまり、入力として観測と行動を受け取り、状態に対して行動がどのくらい効果的であるかを推定します。 End of explanation """ with strategy.scope(): actor_net = actor_distribution_network.ActorDistributionNetwork( observation_spec, action_spec, fc_layer_params=actor_fc_layer_params, continuous_projection_net=( tanh_normal_projection_network.TanhNormalProjectionNetwork)) """ Explanation: このcriticを使用して、actorネットワークをトレーニングします。これにより、与えられた観察に対する行動を生成できます。 ActorNetworkは、tanh-squashed MultivariateNormalDiag 分布のパラメータを予測します。行動を生成する必要がある場合は常に、その時点の観測を条件としてこの分布がサンプリングされます。 End of explanation """ with strategy.scope(): train_step = train_utils.create_train_step() tf_agent = sac_agent.SacAgent( time_step_spec, action_spec, actor_network=actor_net, critic_network=critic_net, actor_optimizer=tf.keras.optimizers.Adam( learning_rate=actor_learning_rate), critic_optimizer=tf.keras.optimizers.Adam( learning_rate=critic_learning_rate), alpha_optimizer=tf.keras.optimizers.Adam( learning_rate=alpha_learning_rate), target_update_tau=target_update_tau, target_update_period=target_update_period, td_errors_loss_fn=tf.math.squared_difference, gamma=gamma, reward_scale_factor=reward_scale_factor, train_step_counter=train_step) tf_agent.initialize() """ Explanation: これらのネットワークを使用して、エージェントをインスタンス化できます。 End of explanation """ table_name = 'uniform_table' table = reverb.Table( table_name, max_size=replay_buffer_capacity, sampler=reverb.selectors.Uniform(), remover=reverb.selectors.Fifo(), rate_limiter=reverb.rate_limiters.MinSize(1)) reverb_server = reverb.Server([table]) """ Explanation: 再生バッファ 環境から収集されたデータを追跡するためには Reverb を使用します。Reverb は、Deepmind により開発された効率的かつ拡張可能で使いやすい再生システムです。これは、Actor により収集され、トレーニング中に Learner により消費される経験データを格納します。 このチュートリアルでは、max_sizeよりも重要ではありませんが、非同期収集とトレーニングを使用する分散設定では、2〜1000 の samples_per_insert を使用して、rate_limiters.SampleToInsertRatioを試すことをお勧めします。以下に例を示します。 rate_limiter=reverb.rate_limiters.SampleToInsertRatio(samples_per_insert=3.0, min_size_to_sample=3, error_buffer=3.0) End of explanation """ reverb_replay = reverb_replay_buffer.ReverbReplayBuffer( tf_agent.collect_data_spec, sequence_length=2, table_name=table_name, local_server=reverb_server) """ Explanation: 再生バッファは、格納されるテンソルを記述する仕様を使用して構築されます。これは、tf_agent.collect_data_specを使用してエージェントから取得できます。 SAC エージェントは損失を計算するためにその時点と次の両方の観測を必要とするため、sequence_length=2を設定します。 End of explanation """ dataset = reverb_replay.as_dataset( sample_batch_size=batch_size, num_steps=2).prefetch(50) experience_dataset_fn = lambda: dataset """ Explanation: 次に、Reverb再生バッファーからTensorFlowデータセットを生成します。これをLearnerに渡して、トレーニングの体験をサンプリングします。 End of explanation """ tf_eval_policy = tf_agent.policy eval_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_eval_policy, use_tf_function=True) tf_collect_policy = tf_agent.collect_policy collect_policy = py_tf_eager_policy.PyTFEagerPolicy( tf_collect_policy, use_tf_function=True) """ Explanation: ポリシー TF-Agent では、ポリシーは RL のポリシーの標準的な概念を表します。time_stepが指定されると、行動または行動の分布が生成されます。主なメソッドはpolicy_step = policy.step(time_step)で、policy_stepは、名前付きのタプルPolicyStep(action, state, info)です。policy_step.actionは、環境に適用されるactionで、stateは、ステートフル(RNN)ポリシーの状態を表し、infoには行動のログ確率などの補助情報が含まれる場合があります。 エージェントには 2 つのポリシーが含まれています。 agent.policy — 評価と導入に使用される主なポリシー。 agent.collect_policy — データ収集に使用される補助的なポリシー。 End of explanation """ random_policy = random_py_policy.RandomPyPolicy( collect_env.time_step_spec(), collect_env.action_spec()) """ Explanation: ポリシーはエージェントとは無関係に作成できます。たとえば、tf_agents.policies.random_tf_policyを使用して、各<code>time_step</code>の行動をランダムに選択するポリシーを作成できます。 End of explanation """ rb_observer = reverb_utils.ReverbAddTrajectoryObserver( reverb_replay.py_client, table_name, sequence_length=2, stride_length=1) """ Explanation: アクター Actorは、ポリシーと環境の間の相互作用を管理します。 Actorコンポーネントには、環境のインスタンス(py_environmentとして)とポリシー変数のコピーが含まれています。 ポリシー変数のローカル値が指定されると、各Actorワーカーは、一連のデータ収集ステップを実行します。 変数の更新は、actor.run()を呼び出す前に、トレーニングスクリプトの変数コンテナクライアントインスタンスを使用して明示的に行われます。 観測された経験は、各データ収集ステップで再生バッファーに書き込まれます。 Actor がデータ収集ステップを実行すると、状態、行動、報酬)のTrajectoryをオブザーバーに渡し、オブザーバーはそれらをキャッシュして Reverb 再生システムに書き込みます。 stride_length=1なので、フレーム [(t0,t1) (t1,t2) (t2,t3), ...] の Trajectory を保存します。 End of explanation """ initial_collect_actor = actor.Actor( collect_env, random_policy, train_step, steps_per_run=initial_collect_steps, observers=[rb_observer]) initial_collect_actor.run() """ Explanation: ランダムなポリシーで Actor を作成し、再生バッファーをシードする経験を収集します。 End of explanation """ env_step_metric = py_metrics.EnvironmentSteps() collect_actor = actor.Actor( collect_env, collect_policy, train_step, steps_per_run=1, metrics=actor.collect_metrics(10), summary_dir=os.path.join(tempdir, learner.TRAIN_DIR), observers=[rb_observer, env_step_metric]) """ Explanation: 収集ポリシーを使用して Actor をインスタンス化し、トレーニング中にさらに経験を収集します。 End of explanation """ eval_actor = actor.Actor( eval_env, eval_policy, train_step, episodes_per_run=num_eval_episodes, metrics=actor.eval_metrics(num_eval_episodes), summary_dir=os.path.join(tempdir, 'eval'), ) """ Explanation: トレーニング中にポリシーを評価するために使用される Actor を作成します。後でメトリックを記録するためにactor.eval_metrics(num_eval_episodes)を渡します。 End of explanation """ saved_model_dir = os.path.join(tempdir, learner.POLICY_SAVED_MODEL_DIR) # Triggers to save the agent's policy checkpoints. learning_triggers = [ triggers.PolicySavedModelTrigger( saved_model_dir, tf_agent, train_step, interval=policy_save_interval), triggers.StepPerSecondLogTrigger(train_step, interval=1000), ] agent_learner = learner.Learner( tempdir, train_step, tf_agent, experience_dataset_fn, triggers=learning_triggers, strategy=strategy) """ Explanation: 学習者 Learner コンポーネントにはエージェントが含まれており、再生バッファーからの経験データを使用して、ポリシー変数への勾配ステップの更新を実行します。1 つ以上のトレーニングステップの後、Learner は新しい一連の変数値を変数コンテナにプッシュできます。 End of explanation """ def get_eval_metrics(): eval_actor.run() results = {} for metric in eval_actor.metrics: results[metric.name] = metric.result() return results metrics = get_eval_metrics() def log_eval_metrics(step, metrics): eval_results = (', ').join( '{} = {:.6f}'.format(name, result) for name, result in metrics.items()) print('step = {0}: {1}'.format(step, eval_results)) log_eval_metrics(0, metrics) """ Explanation: 指標と評価 上記のactor.eval_metricsでevalアクターをインスタンス化しました。これにより、ポリシー評価中に最も一般的に使用されるメトリックが作成されます。 平均リターン。 リターンは、エピソードの環境でポリシーを実行しているときに得られる報酬の合計であり、通常、これをいくつかのエピソードで平均します。 エピソードの長さの平均。 Actorを実行して、これらのメトリクスを生成します。 End of explanation """ #@test {"skip": true} try: %%time except: pass # Reset the train step tf_agent.train_step_counter.assign(0) # Evaluate the agent's policy once before training. avg_return = get_eval_metrics()["AverageReturn"] returns = [avg_return] for _ in range(num_iterations): # Training. collect_actor.run() loss_info = agent_learner.run(iterations=1) # Evaluating. step = agent_learner.train_step_numpy if eval_interval and step % eval_interval == 0: metrics = get_eval_metrics() log_eval_metrics(step, metrics) returns.append(metrics["AverageReturn"]) if log_interval and step % log_interval == 0: print('step = {0}: loss = {1}'.format(step, loss_info.loss.numpy())) rb_observer.close() reverb_server.stop() """ Explanation: さまざまなメトリクスの他の標準実装については、metrics moduleをご覧ください。 エージェントのトレーニング トレーニングループには、環境からのデータ収集とエージェントのネットワークの最適化の両方が含まれます。途中で、エージェントのポリシーを時々評価して、状況を確認します。 End of explanation """ #@test {"skip": true} steps = range(0, num_iterations + 1, eval_interval) plt.plot(steps, returns) plt.ylabel('Average Return') plt.xlabel('Step') plt.ylim() """ Explanation: 可視化 プロット エージェントのパフォーマンスを確認するために、平均利得とグローバルステップをプロットできます。Minitaurでは、報酬関数は、Minitaur が 1000 ステップで歩く距離に基づいており、エネルギー消費にペナルティを課します。 End of explanation """ def embed_mp4(filename): """Embeds an mp4 file in the notebook.""" video = open(filename,'rb').read() b64 = base64.b64encode(video) tag = ''' <video width="640" height="480" controls> <source src="data:video/mp4;base64,{0}" type="video/mp4"> Your browser does not support the video tag. </video>'''.format(b64.decode()) return IPython.display.HTML(tag) """ Explanation: ビデオ 各ステップで環境をレンダリングすると、エージェントのパフォーマンスを可視化できます。その前に、この Colab に動画を埋め込む関数を作成しましょう。 End of explanation """ num_episodes = 3 video_filename = 'sac_minitaur.mp4' with imageio.get_writer(video_filename, fps=60) as video: for _ in range(num_episodes): time_step = eval_env.reset() video.append_data(eval_env.render()) while not time_step.is_last(): action_step = eval_actor.policy.action(time_step) time_step = eval_env.step(action_step.action) video.append_data(eval_env.render()) embed_mp4(video_filename) """ Explanation: 次のコードは、いくつかのエピソードに渡るエージェントのポリシーを可視化します。 End of explanation """
rahulremanan/python_tutorial
Machine_Vision/02_Object_Prediction/notebook/prediction_cats_dogs.ipynb
mit
import sys import argparse import numpy as np import requests import matplotlib matplotlib.use('Agg') import os import time import json import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import tqdm from io import BytesIO from PIL import Image from keras.preprocessing import image from keras.applications.inception_v3 import preprocess_input from keras.models import model_from_json from keras import backend as K from keras.models import Model from keras.layers import UpSampling2D, Conv2D from keras.preprocessing import image #from keras.applications.inception_resnet_v2 import preprocess_input def generate_timestamp(): timestring = time.strftime("%Y_%m_%d-%H_%M_%S") print ("Time stamp generated: "+timestring) return timestring def is_valid_file(parser, arg): if not os.path.isfile(arg): parser.error("The file %s does not exist ..." % arg) else: return arg def is_valid_dir(parser, arg): if not os.path.isdir(arg): parser.error("The folder %s does not exist ..." % arg) else: return arg """ Explanation: Explainable deep-learning -- Visualizing deep neural networks Author: Dr. Rahul Remanan CEO and Chief Imagination Officer, Moad Computer Launch this notebook in Google CoLab This is a skeletal frame work for building better explainable deep-learning. In this notebook, using the Kaggle Dogs vs Cats Redux, Kernels Edition dataset. Import dependencies End of explanation """ def load_prediction_model(args): try: print (args.config_file[0]) with open(args.config_file[0]) as json_file: model_json = json_file.read() model = model_from_json(model_json) except: print ("Please specify a model configuration file ...") sys.exit(1) try: model.load_weights(args.weights_file[0]) print ("Loaded model weights from: " + str(args.weights_file[0])) except: print ("Error loading model weights ...") sys.exit(1) try: print (args.labels_file[0]) with open(args.labels_file[0]) as json_file: labels = json.load(json_file) print ("Loaded labels from: " + str(args.labels_file[0])) except: print ("No labels loaded ...") sys.exit(1) return model, labels """ Explanation: Function to load the model for generating predictions End of explanation """ def predict(model, img, target_size): print ("Running prediction model on the image file ...") if img.size != target_size: img = img.resize(target_size) _x_ = image.img_to_array(img) _x_ = np.expand_dims(_x_, axis=0) _x_ = preprocess_input(_x_) preds = model.predict(_x_) probabilities = model.predict(_x_, batch_size=1).flatten() prediction = labels[np.argmax(probabilities)] return preds[0], prediction """ Explanation: Function to generate predictions End of explanation """ def plot_preds(image, preds, labels, timestr): output_loc = args.output_dir[0] output_file_preds = os.path.join(output_loc+"//preds_out_"+timestr+".png") fig = plt.figure() plt.axis('on') labels = labels plt.barh([0, 1], preds, alpha=0.5) plt.yticks([0, 1], labels) plt.xlabel('Probability') plt.xlim(0,1.01) plt.tight_layout() fig.savefig(output_file_preds, dpi=fig.dpi) """ Explanation: Function to plot prediction accuracy End of explanation """ import types args=types.SimpleNamespace() args.config_file = ['./trained_cats_dogs.config'] args.weights_file = ['./trained_cats_dogs_epochs30_weights.model'] args.labels_file = ['./trained_labels.json'] args.output_dir = ['./'] args.image = ['./cat_01.jpg'] args.image_url = ['https://github.com/rahulremanan/python_tutorial/raw/master/Machine_Vision/02_Object_Prediction/test_images/dog_01.jpg'] """ Explanation: Initialize parameters for generating predictions End of explanation """ ! wget https://raw.githubusercontent.com/rahulremanan/python_tutorial/master/Machine_Vision/02_Object_Prediction/test_images/cat_01.jpg -O cat_01.jpg ! wget https://raw.githubusercontent.com/rahulremanan/python_tutorial/master/Machine_Vision/02_Object_Prediction/model/trained_cats_dogs.config -O trained_cats_dogs.config ! wget https://raw.githubusercontent.com/rahulremanan/python_tutorial/master/Machine_Vision/02_Object_Prediction/model/trained_labels.json -O trained_labels.json ! wget https://media.githubusercontent.com/media/rahulremanan/python_tutorial/master/Machine_Vision/02_Object_Prediction/model/trained_cats_dogs_epochs30_weights.model -O trained_cats_dogs_epochs30_weights.model """ Explanation: Download model weights, configuration, classification labels and example images End of explanation """ model, labels = load_prediction_model(args) """ Explanation: Load the trained deep learning model and load model weights End of explanation """ from keras.utils import plot_model import pydot import graphviz # apt-get install -y graphviz libgraphviz-dev && pip3 install pydot graphviz from IPython.display import SVG from keras.utils.vis_utils import model_to_dot output_dir = './' plot_model(model, to_file= output_dir + '/model_summary_plot.png') SVG(model_to_dot(model).create(prog='dot', format='svg')) """ Explanation: Visualizing the model architecture -- Inception version 3 End of explanation """ target_size = (299, 299) """ Explanation: Specify input size for the image to generate predictions End of explanation """ from IPython.display import Image as PyImage from IPython.core.display import HTML PyImage(args.image[0]) if args.image is not None: img = Image.open(args.image[0]) preds = predict(model, img, target_size) print (preds[1] + "\t" + "\t".join(map(lambda x: "%.2f" % x, preds[0]))) print (str(preds[1])) timestr = generate_timestamp() plot_preds(img, preds[0], labels, timestr) image_path_pred1 = os.path.join('./preds_out_'+timestr+'.png') PyImage(image_path_pred1) """ Explanation: Generating predictions and plotting classification accuracy Test image 1 Visualize input image End of explanation """ PyImage(url = args.image_url[0]) if args.image_url is not None: response = requests.get(args.image_url[0]) img = Image.open(BytesIO(response.content)) preds = predict(model, img, target_size) print (preds[1] + "\t" + "\t".join(map(lambda x: "%.2f" % x, preds[0]))) print (str(preds[1])) timestr = generate_timestamp() plot_preds(img, preds[0], labels, timestr) image_path_pred2 = os.path.join('./preds_out_'+timestr+'.png') PyImage(image_path_pred2) def class_activation_map(INPUT_IMG_FILE=None, PRE_PROCESSOR=None, LABEL_DECODER=None, MODEL=None, LABELS=None, IM_WIDTH=299, IM_HEIGHT=299, CONV_LAYER='conv_7b', URL_MODE=False, FILE_MODE=False, EVAL_STEPS=1, HEATMAP_SHAPE=[8,8], BENCHMARK=True): if INPUT_IMG_FILE == None: print ('No input file specified to generate predictions ...') return if URL_MODE: response = requests.get(INPUT_IMG_FILE) img = Image.open(BytesIO(response.content)) img = img.resize((IM_WIDTH, IM_HEIGHT)) elif FILE_MODE: img = INPUT_IMG_FILE else: img = image.load_img(INPUT_IMG_FILE, target_size=(IM_WIDTH, IM_HEIGHT)) x = img if not FILE_MODE: x = image.img_to_array(img) x = np.expand_dims(x, axis=0) if PRE_PROCESSOR !=None: preprocess_input = PRE_PROCESSOR x = preprocess_input(x) model = MODEL if model == None: print ('No input model specified to generate predictions ...') return labels = LABELS heatmaps = [] heatmap_sum = np.empty(HEATMAP_SHAPE, float) last_conv_layer = model.get_layer(CONV_LAYER) feature_size = tensor_featureSizeExtractor(last_conv_layer) model_input = model.input model_output = model.output last_conv_layer_out = last_conv_layer.output iterate_input = [] pred_labels = [] out_labels = [] probabilities = np.empty((0,len(labels)), float) for step in (range(EVAL_STEPS)): startTime = time.time() preds = model.predict(x, batch_size=1) preds_endTime = time.time() probability = preds.flatten() probabilities = np.append(probabilities, np.array([probability]), axis=0) if labels !=None: pred_label = labels[np.argmax(probability)] pred_labels.append(pred_label) out_labels.append(pred_label) print('PREDICTION: {}'.format(pred_label)) print('ACCURACY: {}'.format(preds[0])) del pred_label elif LABEL_DECODER !=None: pred_label = pd.DataFrame(LABEL_DECODER(preds, top=3)[0],columns=['col1','category','probability']).iloc[:,1:] pred_labels.append(pred_label.loc[0,'category']) out_labels.append(pred_label.loc[0,'category']) print('PREDICTION:',pred_label.loc[0,'category']) del pred_label else: print ('No labels will be generated ...') pred_labels = set(pred_labels) pred_labels = list(pred_labels) argmax = np.argmax(probability) heatmap_startTime = time.time() output = model_output[:, argmax] model_endTime = time.time() grads = K.gradients(output, last_conv_layer_out)[0] pooled_grads = K.mean(grads, axis=(0, 1, 2)) iterate = K.function([model_input], [pooled_grads, last_conv_layer_out[0]]) pooled_grads_value, conv_layer_output_value = iterate([x]) grad_endTime = time.time() for i in range(feature_size): conv_layer_output_value[:,:,i] *= pooled_grads_value[i] iter_endTime = time.time() heatmap = np.mean(conv_layer_output_value, axis=-1) heatmap = np.maximum(heatmap, 0) heatmap /= np.max(heatmap) heatmap_endTime = time.time() try: heatmap_sum = np.add(heatmap_sum, heatmap) heatmaps.append(heatmap) if EVAL_STEPS >1: del probability del heatmap del output del grads del pooled_grads del iterate del pooled_grads_value del conv_layer_output_value except: print ('Failed updating heatmaps ...') endTime = time.time() predsTime = preds_endTime - startTime gradsTime = grad_endTime - model_endTime iterTime = iter_endTime - grad_endTime heatmapTime = heatmap_endTime - heatmap_startTime executionTime = endTime - startTime model_outputTime = model_endTime - heatmap_startTime if BENCHMARK: print ('Heatmap generation time: {} seconds ...'. format(heatmapTime)) print ('Gradient generation time: {} seconds ...'.format(gradsTime)) print ('Iteration loop execution time: {} seconds ...'.format(iterTime)) print ('Model output generation time: {} seconds'.format(model_outputTime)) print ('Prediction generation time: {} seconds ...'.format(predsTime)) print ('Completed processing {} out of {} steps in {} seconds ...'.format(int(step+1), int(EVAL_STEPS), float(executionTime))) if EVAL_STEPS >1: mean_heatmap = heatmap_sum/EVAL_STEPS else: mean_heatmap = heatmap mean = np.matrix.mean(np.asmatrix(probabilities), axis=0) stdev = np.matrix.std(np.asmatrix(probabilities), axis=0) accuracy = np.matrix.tolist(mean)[0][np.argmax(mean)] uncertainty = np.matrix.tolist(stdev)[0][np.argmax(mean)] return [mean_heatmap, accuracy, uncertainty, pred_labels, heatmaps, out_labels, probabilities] labels_json='./trained_labels.json' with open(labels_json) as json_file: labels = json.load(json_file) print (labels) PRE_PROCESSOR = preprocess_input MODEL = model INPUT_IMG_FILE = './cat_01.jpg' LABELS= labels %matplotlib inline img=mpimg.imread(INPUT_IMG_FILE) plt.imshow(img) import tensorflow as tf def tensor_featureSizeExtractor(last_conv_layer): if len(last_conv_layer.output.get_shape().as_list()) == 4: feature_size = last_conv_layer.output.get_shape().as_list()[3] return feature_size else: return 'Received tensor shape: {} instead of expected shape: 4'.format(len(last_conv_layer.output.get_shape().as_list())) def heatmap_overlay(INPUT_IMG_FILE, HEATMAP, THRESHOLD=0.8): img = cv2.imread(INPUT_IMG_FILE) heatmap = cv2.resize(HEATMAP, (img.shape[1], img.shape[0])) heatmap = np.uint8(255 * heatmap) heatmap = cv2.applyColorMap(heatmap, cv2.COLORMAP_JET) hif = THRESHOLD superimposed_img = heatmap * hif + img return [superimposed_img, heatmap] output = class_activation_map(INPUT_IMG_FILE=INPUT_IMG_FILE, PRE_PROCESSOR=PRE_PROCESSOR, MODEL=MODEL, LABELS=LABELS, IM_WIDTH=299, IM_HEIGHT=299, CONV_LAYER='mixed10') HEATMAP = output[0] plt.matshow(HEATMAP) plt.show() print (output[3]) heatmap_output = heatmap_overlay(INPUT_IMG_FILE, HEATMAP, THRESHOLD=0.8) superimposed_img = heatmap_output[0] output_file = './class_activation_map.jpeg' cv2.imwrite(output_file, superimposed_img) img=mpimg.imread(output_file) plt.imshow(img) """ Explanation: Test image 2 End of explanation """
AllenDowney/ThinkBayes2
soln/gss_grass.ipynb
mit
# 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 import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/code/soln/utils.py from utils import set_pyplot_params set_pyplot_params() """ Explanation: Logistic regression 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 """ # Load the data file import os datafile = 'gss_eda.hdf5' if not os.path.exists(datafile): !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/data/gss_eda.hdf5 """ Explanation: Generational Changes As a second example of logistic regression, we'll use data from the General Social Survey (GSS) to describe generational changes in support for legalization of marijuana. Since 1972 the GSS has surveyed a representative sample of adults in the U.S., asking about issues like "national spending priorities, crime and punishment, intergroup relations, and confidence in institutions". I have selected a subset of the GSS data, resampled it to correct for stratified sampling, and made the results available in an HDF file. The following cell downloads the data. End of explanation """ gss = pd.read_hdf(datafile, 'gss') gss.shape """ Explanation: We can use Pandas to load the data. End of explanation """ gss['grass'].value_counts(dropna=False) """ Explanation: The result is a DataFrame with one row for each respondent and one column for each variable. The primary variable we'll explore is grass, which encodes each respondent's answer to this question (details here): "Do you think the use of marijuana should be made legal or not?" This question was asked during most years of the survey starting in 1973, so it provides a useful view of changes in attitudes over almost 50 years. Here are is the distributions of responses: End of explanation """ gss['cohort'].describe() """ Explanation: The value 1.0 represents "yes"; 2.0 represents "no"; NaN represents peope who were not asked the question and a small number of respondents who did not respond or said "I don't know". To explore generational changes in the responses, we will look at the level of support for legalization as a function of birth year, which is encoded in a variable called cohort. Here's a summary of this variable. End of explanation """ valid = gss.dropna(subset=['grass', 'cohort']).copy() valid.shape """ Explanation: The oldest GSS respondent was born in 1883; the youngest was born in 2000. Before we analyze this data, I will select the subset of respondents with valid data for grass and cohort: End of explanation """ valid['y'] = valid['grass'].replace(2, 0) valid['y'].value_counts() """ Explanation: There are about 37,000 respondents with the data we need. I'll recode the values of grass so 1 means yes and 0 means no. End of explanation """ data = valid.groupby('cohort')['y'].agg(['sum', 'count']) data """ Explanation: Now, for this problem, I'm going to represent the data in a different format. Rather than one row for each respondent, I am going to group the respondents by birth year and record the number of respondents in each group, count, and the number who support legalization, sum. End of explanation """ def plot_data(data): """Plot the fraction of yes responses. data: DataFrame with columns `sum` and `count` """ fraction = data['sum'] / data['count'] plt.plot(data.index, fraction, 'o', label='GSS data', color='C0', alpha=0.4) decorate(xlabel='Year of birth', ylabel='Percent in favor', title='Support for legal marijuana vs cohort') plot_data(data) """ Explanation: Here's what the results look like: End of explanation """ offset = valid['cohort'].mean() valid['x'] = valid['cohort'] - offset """ Explanation: There is a strong relationship between birth year and support for legalization. People born before 1920 are the least likely to say "yes"; people born after 1990 are the most likely. There are substantial departures from the long-term trend for people born in the 1950s and late 1960s. If you want to conjecture about the causes, it might help to think about what was happening when each group turned 18. People born in 1950 turned 18 during the counterculture of the 1960s. People born in the late 1960s turned 18 during the "Just Say No" era of the War on Drugs and the peak in the AIDS epidemic in the U.S. Point estimates I'll use StatsModels again to generate point estimates for the slope and intercept of a logistic model. As we did with the previous problem, I'll center the values of the explanatory variable so the mean is 0. End of explanation """ import statsmodels.formula.api as smf formula = 'y ~ x' results = smf.logit(formula, data=valid).fit(disp=0) results.params """ Explanation: Here are the results from StatsModels. End of explanation """ inter = results.params['Intercept'] slope = results.params['x'] """ Explanation: To visualize the results, I'll use these parameters to estimate the probability of support in each cohort. End of explanation """ data['x'] = data.index - offset data.head() """ Explanation: I'll shift the birth years in data by offset. End of explanation """ probs = expit(inter + slope * data['x']) probs.head() """ Explanation: And use expit to compute the probabilities. End of explanation """ probs.plot(label='Logistic model', color='C1') plot_data(data) """ Explanation: Here's what the model looks like with the data. End of explanation """ from scipy.stats import binom ks = data['sum'] ns = data['count'] likes = binom.pmf(ks, ns, probs) likes.shape """ Explanation: With these parameters, the model captures the long term trend in the data. Computing likelihoods Before we do the Bayesian update, let's compute the probability of the data with the estimated parameters. From the data, we know how many people there are in each group and how many of them support legalization. From the model, we have an estimate for the probability of support in each group. So we can use the binomial distribution to compute the probability of the data given the estimated probabilities. End of explanation """ likes.prod() """ Explanation: For each group likes contains the probability of the outcome, k, given the group size, n, and the estimated probability, p. The likelihood of the data is the product of these likelihoods: End of explanation """ import sys sys.float_info.min_exp """ Explanation: This likelihood is very small, for two reasons: The dataset is large, which means that there are many possible outcomes, so the probability of any particular outcome is small. The data deviate substantially from the model, so the probability of this particular outcome is small. In theory, it's not a problem if the likelihood of the data is small. We might not get a model that fits the data perfectly, but we'll get the parameters that come as close as possible. However, in practice small likelihoods can be problematic. With floating-point numbers, the smallest positive number we can represent is about 1e-1021. End of explanation """ qs = np.linspace(-0.95, -0.75, num=51) prior_inter = make_uniform(qs, 'Intercept') qs = np.linspace(0.025, 0.035, num=51) prior_slope = make_uniform(qs, 'Slope') """ Explanation: Any number smaller than that "underflows"; that is, it gets rounded down to 0. When that happens, we lose the ability to distinguish between parameters that make the model fit the data or not. In the worst case, if all likelihoods underflow, all probabilities in the posterior distribution would be 0. In this example, the likelihoods are big enough that we can still do a Bayesian update, so we'll do that next. Then I will demonstrate a trick we can use to avoid underflow: computing likelihoods under a log transformation. The update I'll use uniform priors for the parameters, with locations centered around the point estimates. End of explanation """ joint = make_joint(prior_inter, prior_slope) joint.head() """ Explanation: I'll make a joint prior. End of explanation """ joint_pmf = Pmf(joint.stack()) joint_pmf.head() """ Explanation: And stack it into a Pmf with a two-column index. End of explanation """ likelihood = joint_pmf.copy() xs = data['x'] ks = data['sum'] ns = data['count'] for slope, inter in joint_pmf.index: ps = expit(inter + slope * xs) likes = binom.pmf(ks, ns, ps) likelihood[slope, inter] = likes.prod() """ Explanation: Here's the update, using the binomial distribution to compute the likelihood of the data in each group. End of explanation """ likelihood.sum() """ Explanation: Again, the likelihoods are small. End of explanation """ posterior_pmf = joint_pmf * likelihood posterior_pmf.normalize() """ Explanation: But we can do the update in the usual way. End of explanation """ joint_posterior = posterior_pmf.unstack() plot_contour(joint_posterior) decorate(title='Joint posterior distribution') """ Explanation: And there are enough non-zero elements to get a useful posterior distribution. Here's what it looks like. End of explanation """ print(posterior_pmf.max_prob()) print(results.params.values[::-1]) """ Explanation: We can confirm that the parameters with maximum posterior probability are consistent with the point estimates. End of explanation """ marginal_inter = marginal(joint_posterior, 0) marginal_slope = marginal(joint_posterior, 1) marginal_inter.mean(), marginal_slope.mean() """ Explanation: Here are the means of the marginal distributions. End of explanation """ marginal_probs = transform(marginal_inter, expit) """ Explanation: Recall that the intercept indicates the log odds of the hypothesis at x=0. To make the distribution of intercepts easier to interpret, I'll use expit to transform the values to probabilities. End of explanation """ marginal_probs.plot(color='C4') decorate(xlabel='Probability at x=0', ylabel='PDF', title='Posterior distribution of intercept in terms of probability') """ Explanation: And here's what it looks like. End of explanation """ marginal_probs.mean(), offset """ Explanation: The mean of this distribution is about 24%, which is the predicted probability of supporting legalization for someone born around 1949. End of explanation """ marginal_lr = transform(marginal_inter, np.exp) """ Explanation: The estimated slope is the log of the likelihood ratio for each additional year of birth. To interpret slopes as likelihood ratios, we can use np.exp to transform the values in the posterior distribution. End of explanation """ marginal_lr.plot(color='C2') decorate(xlabel='Likelihood ratio of each additional year', ylabel='PDF', title='Posterior distribution of slope in terms of likelihood ratio') """ Explanation: And here's what it looks like. End of explanation """ marginal_lr.mean() """ Explanation: The mean of this distribution is about 0.43, which indicates that each additional year is evidence that the respondent will say "yes", with a a likelihood ratio (or Bayes factor) of 0.43. End of explanation """ log_likelihood = joint_pmf.copy() for slope, inter in joint_pmf.index: ps = expit(inter + slope * xs) log_likes = binom.logpmf(ks, ns, ps) log_likelihood[slope, inter] = log_likes.sum() """ Explanation: Later we will use the joint posterior distribution to generate predictions, but first I'll show how to compute likelihoods under a log transform. Log Likelihood Because of the problem of underflow, many likelihood computations are done under a log transform. That's why the distributions in SciPy, including binom, provide functions to compute logarithms of PMFs and PDFs. Here's a loop that uses binom.logpmf to compute the log likelihood of the data for each pair of parameters in joint_pmf: End of explanation """ log_likelihood.min(), log_likelihood.max() """ Explanation: log_likes is an array that contains the logarithms of the binomial PMFs for each group. The sum of these logarithms is the log of their product, which is the log-likelihood of the data. Since the likelihoods are small, their logarithms are negative. The smallest (most negative) is about -610; the largest (least negative) is about -480. End of explanation """ shifted = log_likelihood - log_likelihood.max() likelihood2 = np.exp(shifted) """ Explanation: So the log likelihoods are comfortably with the range we can represent with floating-point numbers. However, before we can do the update, we have to convert the logarithms back to a linear scale. To do that while minimizing underflow, I am going to shift the logs up toward zero. Adding a constant to the log_likelihood is the same as multiplying a constant by likelihood. We can do that without affecting the results because we have to normalize the posterior probabilities, so the multiplicative constant gets normalized away. End of explanation """ shifted.min(), shifted.max() """ Explanation: After subtracting away the largest element in log_likelihood, the range of values in the result is from -127 to 0. End of explanation """ likelihood2.min(), likelihood2.max() """ Explanation: So the range of likelihoods is from near 0 to 1. End of explanation """ posterior_pmf2 = joint_pmf * likelihood2 posterior_pmf2.normalize() """ Explanation: Now we can use them as likelihoods in a Bayesian update. End of explanation """ joint_posterior2 = posterior_pmf2.unstack() marginal2_inter = marginal(joint_posterior2, 0) marginal2_slope = marginal(joint_posterior2, 1) print(marginal2_inter.mean(), marginal2_slope.mean()) """ Explanation: To confirm that we get the same results using likelihoods or log-likelihoods, I'll compute the mean of the marginal posterior distributions: End of explanation """ print(marginal_inter.mean(), marginal_slope.mean()) """ Explanation: And compare them to what we got using (non-log) likelihoods. End of explanation """ np.random.seed(42) sample = posterior_pmf.sample(101) """ Explanation: They are the same except for small differences due to floating-point approximation. In this example, we can compute the posterior distribution either way, using likelihoods or log likelihoods. But if there were more data, the likelihoods would underflow and it would be necessary to use log likelihoods. Making predictions As we did with the previous example, we can use the posterior distribution of the parameters to generate predictions, which we can use to see whether the model fits the data and to extrapolate beyond the data. I'll start with a sample from the posterior distribution. End of explanation """ xs = np.arange(1880, 2021) - offset """ Explanation: And a range of xs that extends 20 years past the observed data. End of explanation """ ps = np.empty((len(sample), len(xs))) for i, (slope, inter) in enumerate(sample): ps[i] = expit(inter + slope * xs) ps.shape """ Explanation: We can use the sampled parameters to predict probabilities for each group. End of explanation """ not_small = (data['count'] >= 20) counts = data.loc[not_small, 'count'] counts.describe() """ Explanation: But that only accounts for uncertainty about the parameters. We also have to account for variability in the size of the groups. Here's the distribution of group size, dropping the groups smaller than 20. End of explanation """ ns = np.random.choice(counts, len(xs), replace=True) ns[:10] """ Explanation: To simulate variation in group size, I'll use np.random.choice to resample the group sizes; that is, I'll draw from counts a sample with the same length as xs, sampling with replacement. End of explanation """ pred = np.empty((len(sample), len(xs))) for i, (slope, inter) in enumerate(sample): ps = expit(inter + slope * xs) ns = np.random.choice(counts, len(xs), replace=True) ks = binom(ns, ps).rvs(len(xs)) pred[i] = ks / ns pred.shape """ Explanation: Even if we know how many people are in each group and their probability of saying "yes", there is still uncertainty in the outcome. We can use the binomial distribution to simulate this (final) source of uncertainty. Putting it all together, the following loop combines these sources of uncertainty to generate predictive distributions for each group. End of explanation """ low, median, high = np.percentile(pred, [5, 50, 95], axis=0) median.shape """ Explanation: The result is an array with one row for each pair of parameters in the sample and one column for each value in xs. Now we can use np.percentile to compute percentiles in each column. End of explanation """ plt.fill_between(xs+offset, low, high, color='C1', alpha=0.2) plt.plot(xs+offset, median, label='Logistic model', color='C1') plot_data(data) """ Explanation: And use them to plot a 90% credible interval for the predictions. End of explanation """
charlesll/RamPy
examples/Baseline_and_Centroid_determination.ipynb
gpl-2.0
%matplotlib inline import numpy as np np.random.seed(42) # fixing the seed import matplotlib import matplotlib.pyplot as plt import rampy as rp import scipy """ Explanation: Centroid measurement Author: Charles Le Losq This notebook illustrates the use of the rampy.centroid() function to measure the centroid of a peak. End of explanation """ x = np.arange(0,600,1.0) nb_samples = 100 # number of samples in our dataset # partial spectra S_1 = scipy.stats.norm.pdf(x,loc=300.,scale=40.) S_2 = scipy.stats.norm.pdf(x,loc=400,scale=20) S_true = np.vstack((S_1,S_2)) print("Number of samples:"+str(nb_samples)) print("Shape of partial spectra matrix:"+str(S_true.shape)) # concentrations C_ = np.random.rand(nb_samples) #60 samples with random concentrations between 0 and 1 C_true = np.vstack((C_,(1-C_))).T print("Shape of concentration matrix:"+str(C_true.shape)) # background E_ = 1e-8*x**2 true_sig = np.dot(C_true,S_true) Obs = np.dot(C_true,S_true) + E_ + np.random.randn(nb_samples,len(x))*1e-4 # norm is a class which, when called, can normalize data into the # [0.0, 1.0] interval. norm = matplotlib.colors.Normalize( vmin=np.min(C_), vmax=np.max(C_)) # choose a colormap c_m = matplotlib.cm.jet # create a ScalarMappable and initialize a data structure s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm) s_m.set_array([]) # plotting spectra # calling the ScalarMappable that was initialised with c_m and norm for i in range(C_.shape[0]): plt.plot(x, Obs[i,:].T, color=s_m.to_rgba(C_[i])) # we plot the colorbar, using again our # ScalarMappable c_bar = plt.colorbar(s_m) c_bar.set_label(r"C_") plt.xlabel('X') plt.ylabel('Y') plt.show() """ Explanation: Problem definition The rampy.centroid function will calculate the centroid of the signal you provide to it. In this case, we have a combination of two Gaussian peaks with some noise. This example is that used in the Machine Learning Regression notebook. The example signals $D_{i,j}$ are generated from a linear combination of two Gaussian peaks $S_{k,j}$, and are affected by a constant background $\epsilon_{i,j}$: $$ D_{i,j} = C_{i,k} \times S_{k,j} + \epsilon_{i,j}$$ We thus will remove the background, then calculate the centroid, and plot it against $C_{i,k}$ which is known in the present case. End of explanation """ Obs_corr = np.ones(Obs.shape) print(Obs_corr.shape) """ Explanation: Baseline fit We will use the rampy.baseline function with a polynomial form. We first create the array to store baseline-corrected spectra End of explanation """ ROI = np.array([[0.,100.],[500.,600.]]) print(ROI) """ Explanation: We define regions of interest ROI where the baseline will fit the signals. From the previous figure, this is clear that it should be between 0 and 100, and 500 and 600. End of explanation """ for i in range(nb_samples): sig_corr, bas_, = rp.baseline(x,Obs[i,:].T,ROI,method="poly",polynomial_order=2) Obs_corr[i,:] = sig_corr.reshape(1,-1) # plotting spectra # calling the ScalarMappable that was initialised with c_m and norm plt.figure(figsize=(8,4)) plt.subplot(1,2,1) for i in range(C_.shape[0]): plt.plot(x, Obs[i,:].T, color=s_m.to_rgba(C_[i]), alpha=0.3) plt.plot(x,bas_,"k-",linewidth=4.0,label="baseline") # we plot the colorbar, using again our # ScalarMappable c_bar = plt.colorbar(s_m) c_bar.set_label(r"C_") plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.title("A) Baseline fit") plt.subplot(1,2,2) for i in range(C_.shape[0]): plt.plot(x, Obs_corr[i,:].T, color=s_m.to_rgba(C_[i]), alpha=0.3) c_bar = plt.colorbar(s_m) c_bar.set_label(r"C_") plt.xlabel('X') plt.ylabel('Y') plt.title("B) Corrected spectra") plt.show() plt.tight_layout() """ Explanation: Then we loop to save the baseline corrected data in this array. End of explanation """ x_array = np.ones((len(x),nb_samples)) for i in range(nb_samples): x_array[:,i] = x centroids_no_smooth = rp.centroid(x_array,Obs_corr.T) centroids_smooth = rp.centroid(x_array,Obs_corr.T,smoothing=True) centroids_true_sig = rp.centroid(x_array,true_sig.T,smoothing=True) """ Explanation: Centroid determination Now we can calculate the centroid of the signal. rampy.centroid calculates it as centroid = np.sum(y_/np.sum(y_)*x) It accepts arrays of spectrum, organised as n points by m samples. Smoothing can be done if wanted, by indicating smoothing = True. We will compare both in the following code. A tweak is to prepare an array fo x with the same shape as y, and the good x values in each columns. Furthermore, do not forget that arrays should be provided as n points by m samples. So use .T if needed to transpose your array. We need it below! End of explanation """ plt.figure() plt.plot(C_,centroids_true_sig,"r-",markersize=3.,label="true values") plt.plot(C_,centroids_no_smooth,"k.",markersize=5., label="non-smoothed centroids") plt.plot(C_,centroids_smooth,"b+",markersize=3., label="smoothed centroids") plt.xlabel("Fraction C_") plt.ylabel("Signal centroid") plt.legend() """ Explanation: Now we can plot the centroids against the chemical ratio C_ for instance. End of explanation """
pastephens/pysal
pysal/contrib/spint/notebooks/Vec_SA_Test.ipynb
bsd-3-clause
dest_A_rand_I = [] dest_B_rand_I = [] dest_A_rand_p = [] dest_B_rand_p = [] for i in range(1000): phi = np.random.uniform(0,np.pi*2, 50).reshape((-1,1)) num = np.arange(0,50).reshape((-1,1)) OX = np.random.randint(0,500, 50).reshape((-1,1)) OY = np.random.randint(0,500, 50).reshape((-1,1)) DX = np.cos(phi)*(np.random.randint(0,500, 50)).reshape((-1,1)) DY = np.sin(phi)*np.random.randint(0,500, 50).reshape((-1,1)) vecs = np.hstack([num, OX, OY, DX, DY]) dests = vecs[:, 3:5] wd = DistanceBand(dests, threshold=9999, alpha=-1.5, binary=False) vmd = VecMoran(vecs, wd, focus='destination', rand='A', permutations=999) dest_A_rand_I.append(vmd.I) dest_A_rand_p.append(vmd.p_z_sim) vmd = VecMoran(vecs, wd, focus='destination', rand='B', permutations=999) dest_B_rand_I.append(vmd.I) dest_B_rand_p.append(vmd.p_z_sim) X,Y,U,V = zip(*vecs[:,1:]) plt.subplot(111) for x in range(0,len(vecs[:,1])): plt.arrow(X[x], #x1 Y[x], # y1 U[x]-X[x], # x2 - x1 V[x]-Y[x], # y2 - y1 fc="k", ec="k", head_width=0.05, head_length=0.1) plt.xlim([-510,550]) plt.ylim([-510,550]) plt.title('Example of 50 random vectors') plt.show() """ Explanation: Demonstrating the vector-based Moran's I statistic for spatial autocorrelation and the associated proposed randomization techniques for generating psuedo p-values - Technique A: Randomly select one vector among the N observed vectors and assign its origin (destination) to the origin (destination) point of another observed vector. This is equivlanet to geometrically translating both the original origin and the original destination by the coordinates of the new origin (destination) point, which preserves the direction and magnitude of the original vector. Using this technique it is possible to generate new vectors that are outside the bounding box of the original set of vectors, thererby violating any potential study area boundaries. - Technique B: For each vector among the N observed vectors, reassign its origin (destination) point to the destination (origin) from another randomly selected vector from the N observed vectors. This does does not preserve distance or magnitude, though it does ensure that all new vectors remain within the bounding box of the of the original vectors Generate 1000 random datasets of 50 vectors, then calculate the vector Moran's I from the destination perspective (VMD) and a psuedo p value (based on 99 permutations) using randomization technique A and randomization technique B for each of the 1000 datasets. End of explanation """ dest_A_cons_I = [] dest_B_cons_I = [] dest_A_cons_p = [] dest_B_cons_p = [] for i in range(1000): phi = np.random.uniform(0,np.pi*2, 50).reshape((-1,1)) num = np.arange(0,50).reshape((-1,1)) OX = np.random.randint(450,500, 50).reshape((-1,1)) OY = np.random.randint(450,500, 50).reshape((-1,1)) DX = np.cos(phi)*(np.random.randint(450,500, 50)).reshape((-1,1)) DY = np.sin(phi)*np.random.randint(450,500, 50).reshape((-1,1)) vecs = np.hstack([num, OX, OY, DX, DY]) dests = vecs[:, 3:5] wd = DistanceBand(dests, threshold=9999, alpha=-1.5, binary=False) vmd = VecMoran(vecs, wd, focus='destination', rand='A', permutations=999) dest_A_cons_I.append(vmd.I) dest_A_cons_p.append(vmd.p_z_sim) vmd = VecMoran(vecs, wd, focus='destination', rand='B', permutations=999) dest_B_cons_I.append(vmd.I) dest_B_cons_p.append(vmd.p_z_sim) X,Y,U,V = zip(*vecs[:,1:]) plt.subplot(111) for x in range(0,len(vecs[:,1])): plt.arrow(X[x], #x1 Y[x], # y1 U[x]-X[x], # x2 - x1 V[x]-Y[x], # y2 - y1 fc="k", ec="k", head_width=0.05, head_length=0.1) plt.xlim([-510,550]) plt.ylim([-510,550]) plt.title('Example of 50 random vectors with constrained origins') plt.show() #Method A random plt.hist(dest_A_rand_I, bins = 25) plt.title('Distribution of VMD I values from random vectors - Method A') plt.show() plt.hist(dest_A_rand_p, bins = 25) plt.title('Distribution of p values from random vectors - Method A') plt.show() #Method A constricted plt.hist(dest_A_cons_I, bins=25) plt.title('Distribution of VMD I values from constrained vectors - Method A') plt.show() plt.hist(dest_A_cons_p, bins=25) plt.title('Distribution of p values from constrained vectors - Method A') plt.show() #Method B random plt.hist(dest_B_rand_I, bins=25) plt.title('Distribution of VMD I values from random vectors - Method B') plt.show() plt.hist(dest_B_rand_p, bins=25) plt.title('Distribution of p values from random vectors - Method B') plt.show() #Method B constricted plt.hist(dest_B_cons_I, bins=25) plt.title('Distribution of VMD I values from constrained vectors - Method B') plt.show() plt.hist(dest_B_cons_p, bins=25) plt.title('Distribution of p values from constrained vectors - Method B') plt.show() print 'a' """ Explanation: Generate 1000 random datasets of 50 vectors with constrained origins (to induce positive spatial autocorrrlation), then calculate the vector Moran's I from the destination perspective (VMD) and a psuedo p value (based on 99 permutations) using randomization technique A and randomization technique B for each of the 1000 datasets. End of explanation """
ljo/collatex-tutorial
unit5/Custom sort.ipynb
gpl-3.0
import re """ Explanation: Defining a custom sort for a complex value We need to sort data that is partially numeric and partially alphabetic, in this case the line numbers 1, 4008, 4008a, 4009, and 9. We can’t sort them numerically because the 'a' isn’t numeric. And we can’t sort them alphabetically because the numbers that begin with '4' (4008, 4008a, 4009) would all sort before '9'. We resolve the problem by writing a custom sort function that separates the values into leading numeric and optional trailing alphabetic parts. We then sort numerically by the numeric part, and break ties by subsorting alphabetically on the alphabetic part. We’ll use a regular expression to parse our line number into two parts, so we load the regex library: End of explanation """ lines = ['4008','4008a','4009','1','9'] sorted(lines) """ Explanation: We initialize a lines list of strings and demonstrate how the default alphabetic sort gives the wrong results: End of explanation """ sorted(lines,key=int) # this raises an error """ Explanation: In Python 3, the key parameter specifies a function that should be applied to the list items before sorting them. If we use int to convert each of the string values to an integer so that we can perform a numerical sort, we raise an error because the 'a' can’t be converted to an integer: End of explanation """ linenoRegex = re.compile('(\d+)(.*)') def splitId(id): """Splits @id value like 4008a into parts, for sorting""" results = linenoRegex.match(id).groups() return (int(results[0]),results[1]) """ Explanation: We create our own sort function, for which we define linenoRegex, which includes two capture groups, both of which are strings by default. The first captures all digits from the beginning of the line number value. The second captures anything after the numbers. The regex splits the input into a tuple that contains the two values as strings, and we convert the first value to an integer before we return it. For example, the input value '4008a' will return (4008,'a'), where the '4008' is an integer and the 'a' is a string. End of explanation """ sorted(lines,key=splitId) """ Explanation: If we now specify our splitId function as the value of the key parameter in the sorted() function, the values will be split into two parts before sorting. Tuples are sorted part by part from start to finish, so we don’t have to tell the function explicitly how to sort once we’ve defined the two parts of our tuple: End of explanation """
marko911/deep-learning
embeddings/Skip-Gram_word2vec.ipynb
mit
import time import numpy as np import tensorflow as tf import utils """ Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like translations. Readings Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material. A really good conceptual overview of word2vec from Chris McCormick First word2vec paper from Mikolov et al. NIPS paper with improvements for word2vec also from Mikolov et al. An implementation of word2vec from Thushan Ganegedara TensorFlow word2vec tutorial Word embeddings When you're dealing with language and words, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram. <img src="assets/word2vec_architectures.png" width="500"> In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts. First up, importing packages. End of explanation """ from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(dataset_filename): with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset_name) as pbar: urlretrieve( 'http://mattmahoney.net/dc/text8.zip', dataset_filename, pbar.hook) if not isdir(dataset_folder_path): with zipfile.ZipFile(dataset_filename) as zip_ref: zip_ref.extractall(dataset_folder_path) with open('data/text8') as f: text = f.read() """ Explanation: Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. Then you can extract it and delete the archive file to save storage space. End of explanation """ words = utils.preprocess(text) print(words[:30]) print("Total words: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) """ Explanation: Preprocessing Here I'm fixing up the text to make training easier. This comes from the utils module I wrote. The preprocess function coverts any punctuation into tokens, so a period is changed to &lt;PERIOD&gt;. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it. End of explanation """ vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] """ Explanation: And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list int_words. End of explanation """ ## Your code here train_words = # The final subsampled word list """ Explanation: Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by $$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$ where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset. I'm going to leave this up to you as an exercise. This is more of a programming challenge, than about deep learning specifically. But, being able to prepare your data for your network is an important skill to have. Check out my solution to see how I did it. Exercise: Implement subsampling for the words in int_words. That is, go through int_words and discard each word given the probablility $P(w_i)$ shown above. Note that $P(w_i)$ is the probability that a word is discarded. Assign the subsampled data to train_words. End of explanation """ def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' # Your code here return """ Explanation: Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From Mikolov et al.: "Since the more distant words are usually less related to the current word than those close to it, we give less weight to the distant words by sampling less from those words in our training examples... If we choose $C = 5$, for each training word we will select randomly a number $R$ in range $< 1; C >$, and then use $R$ words from history and $R$ words from the future of the current word as correct labels." Exercise: Implement a function get_target that receives a list of words, an index, and a window size, then returns a list of words in the window around the index. Make sure to use the algorithm described above, where you choose a random number of words from the window. End of explanation """ def get_batches(words, batch_size, window_size=5): ''' Create a generator of word batches as a tuple (inputs, targets) ''' n_batches = len(words)//batch_size # only full batches words = words[:n_batches*batch_size] for idx in range(0, len(words), batch_size): x, y = [], [] batch = words[idx:idx+batch_size] for ii in range(len(batch)): batch_x = batch[ii] batch_y = get_target(batch, ii, window_size) y.extend(batch_y) x.extend([batch_x]*len(batch_y)) yield x, y """ Explanation: Here's a function that returns batches for our network. The idea is that it grabs batch_size words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory. End of explanation """ train_graph = tf.Graph() with train_graph.as_default(): inputs = labels = """ Explanation: Building the graph From Chris McCormick's blog, we can see the general structure of our network. The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden layer weight matrix to find efficient representations for our words. This weight matrix is usually called the embedding matrix or embedding look-up table. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset. I'm going to have you build the graph in stages now. First off, creating the inputs and labels placeholders like normal. Exercise: Assign inputs and labels using tf.placeholder. We're going to be passing in integers, so set the data types to tf.int32. The batches we're passing in will have varying sizes, so set the batch sizes to [None]. To make things work later, you'll need to set the second dimension of labels to None or 1. End of explanation """ n_vocab = len(int_to_vocab) n_embedding = # Number of embedding features with train_graph.as_default(): embedding = # create embedding weight matrix here embed = # use tf.nn.embedding_lookup to get the hidden layer output """ Explanation: Embedding The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix: You don't actually need to do the matrix multiplication, you just need to select the row in the embedding matrix that corresponds to the input word. Then, the embedding matrix becomes a lookup table, you're looking up a vector the size of the hidden layer that represents the input word. <img src="assets/word2vec_weight_matrix_lookup_table.png" width=500> Exercise: Tensorflow provides a convenient function tf.nn.embedding_lookup that does this lookup for us. You pass in the embedding matrix and a tensor of integers, then it returns rows in the matrix corresponding to those integers. Below, set the number of embedding features you'll use (200 is a good start), create the embedding matrix variable, and use tf.nn.embedding_lookup to get the embedding tensors. For the embedding matrix, I suggest you initialize it with a uniform random numbers between -1 and 1 using tf.random_uniform. This TensorFlow tutorial will help if you get stuck. End of explanation """ # Number of negative labels to sample n_sampled = 100 with train_graph.as_default(): softmax_w = # create softmax weight matrix here softmax_b = # create softmax biases here # Calculate the loss using negative sampling loss = tf.nn.sampled_softmax_loss cost = tf.reduce_mean(loss) optimizer = tf.train.AdamOptimizer().minimize(cost) """ Explanation: Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called "negative sampling". Tensorflow has a convenient function to do this, tf.nn.sampled_softmax_loss. Exercise: Below, create weights and biases for the softmax layer. Then, use tf.nn.sampled_softmax_loss to calculate the loss. Be sure to read the documentation to figure out how it works. End of explanation """ with train_graph.as_default(): ## From Thushan Ganegedara's implementation valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent valid_examples = np.array(random.sample(range(valid_window), valid_size//2)) valid_examples = np.append(valid_examples, random.sample(range(1000,1000+valid_window), valid_size//2)) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # We use the cosine distance: norm = tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keep_dims=True)) normalized_embedding = embedding / norm valid_embedding = tf.nn.embedding_lookup(normalized_embedding, valid_dataset) similarity = tf.matmul(valid_embedding, tf.transpose(normalized_embedding)) # If the checkpoints directory doesn't exist: !mkdir checkpoints """ Explanation: Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. End of explanation """ epochs = 10 batch_size = 1000 window_size = 10 with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: iteration = 1 loss = 0 sess.run(tf.global_variables_initializer()) for e in range(1, epochs+1): batches = get_batches(train_words, batch_size, window_size) start = time.time() for x, y in batches: feed = {inputs: x, labels: np.array(y)[:, None]} train_loss, _ = sess.run([cost, optimizer], feed_dict=feed) loss += train_loss if iteration % 100 == 0: end = time.time() print("Epoch {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Avg. Training loss: {:.4f}".format(loss/100), "{:.4f} sec/batch".format((end-start)/100)) loss = 0 start = time.time() if iteration % 1000 == 0: ## From Thushan Ganegedara's implementation # note that this is expensive (~20% slowdown if computed every 500 steps) sim = similarity.eval() for i in range(valid_size): valid_word = int_to_vocab[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k+1] log = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = int_to_vocab[nearest[k]] log = '%s %s,' % (log, close_word) print(log) iteration += 1 save_path = saver.save(sess, "checkpoints/text8.ckpt") embed_mat = sess.run(normalized_embedding) """ Explanation: Training Below is the code to train the network. Every 100 batches it reports the training loss. Every 1000 batches, it'll print out the validation words. End of explanation """ with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) embed_mat = sess.run(embedding) """ Explanation: Restore the trained network if you need to: End of explanation """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from sklearn.manifold import TSNE viz_words = 500 tsne = TSNE() embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :]) fig, ax = plt.subplots(figsize=(14, 14)) for idx in range(viz_words): plt.scatter(*embed_tsne[idx, :], color='steelblue') plt.annotate(int_to_vocab[idx], (embed_tsne[idx, 0], embed_tsne[idx, 1]), alpha=0.7) """ Explanation: Visualizing the word vectors Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out this post from Christopher Olah to learn more about T-SNE and other ways to visualize high-dimensional data. End of explanation """