text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
## debugging ``` #define localfile system import os if not 'nb_dir' in globals(): nb_dir = os.getcwd() print(nb_dir) os.chdir('..') %load_ext autoreload %autoreload 2 import pandas as pd from class_file_clerk import * df = pd.DataFrame({"a":[1,2,3],"b":[1,2,3]}).set_index('a') df.loc[1,'b'] = 4 try: d.loc["banana",'b'] = 7 except Exception: print('a not found in Zoom data.') d3 = df dse = df email_col = 'b' #TODO: if a student had a Zoom name that isn't present anymore, check to see if their email is still present. # If it is, update their Zoom name e = 4 n = 'bananas' try: d3.loc[n,email_col] = e except Exception: # d3.query() print(f'Warning, {n} at {e} was not found in Zoom data.') df1 = pd.DataFrame({"a":[1,2,3],"b":[1,2,3]}).set_index('a') df2 = pd.DataFrame({"a":[1,2,3],"b":[4,1,6]}).set_index('a') df1.where(df1>df2, df2) ``` # keep max when students go to more than 1 discussion ``` zoom_dir = 'data/input/from_Zoom/' skiprows = 2 time_col = 'Total Duration (Minutes)' os.chdir(f"{nb_dir}/..") email_col = 'User Email' name_col = 'Name (Original Name)' ################### #import attendence spreadsheet print('inputted attendance files:') att_fns = get_zoom_fn_list(zoom_dir) print(att_fns) d = pd.concat([pd.read_csv(fn, skiprows=skiprows, index_col=None) for fn in att_fns], sort=False) d = d[d.index>0]#drop the TA in charge of discussion (assumed to be at index position 0) d.reindex(); # lst = att_fns # # fn = lst.pop() # d = pd.read_csv(lst.pop(), skiprows=skiprows) # while lst is not []: # tmp = pd.read_csv(lst.pop(), skiprows=skiprows) # d = d.where(d[time_col]>tmp[time_col], tmp) # d.query(f"{name_col} == 'Katada Siraj'") name = 'Katada Siraj' #take the max time per student name_lst = list(set(d[name_col].values)) tmp = pd.concat([d[d[name_col]== name].sort_values(time_col,ascending=False).head(1) for name in name_lst]) sum(tmp[time_col]>35) ``` # dev todo: make student email dictionary not add a duplicate row if the same name is already present. # test case load (new) student roster ``` nb_dir # os.chdir(nb_dir) # get_roster_fn(roster_dir=f'{nb_dir}/../data/input/from_Student_Roster/') roster_dir=f'{nb_dir}/../data/input/from_Student_Roster/' os.chdir(roster_dir) f'{nb_dir}/../data/input/from_Student_Roster/' data_dir = f"{nb_dir}/../data/input/" # data_dir = 'data' os.chdir(data_dir) get_roster_fn(roster_dir=f'{nb_dir}/../data/input/from_Student_Roster/') assert(get_roster_fn(roster_dir=f'{nb_dir}/../data/input/from_Student_Roster/') is not None) fn = "my_ta_list.csv" # assert(get_sections() is not None) assert(get_ta(fn =f'{nb_dir}/../data/input/'+fn) is not None) print_state() my_sections = list(get_sections()['Sec ID'].values) roster_fn = get_roster_fn() my_tutors = list(get_ta()['email'].values) df = get_my_students(roster_fn=roster_fn, my_sections = my_sections, my_tutors = my_tutors, skiprows = 14) ```
github_jupyter
# Step 16 Combine Knowledge graphs ![](images/method.png) |**[Overview](#Overview)** |**[Installation](#Installation)||**[Prior-steps](#Prior-steps)**|**[How-to-use](#How-to-use)**|**[Next-steps](#Next-steps)**|**[Postscript](#Postscript)**|**[Acknowledgements](#Acknowledgments)| # Overview We now have several knowledge graphs each representing the business domain or portfolio differently. - step 13: a KG based on the topic modelling of the whole library - Step 14 : a comparator KG based on best practice - in this case a key paper. - Step 15: a KG based on keywords from the whole library We do the following: 1. combine the KGs 2. rationalise labels 3. look for patterns across nodes 4. boost patterns that make sense to stakeholders through relabelling 5. find slices through the KG that will make sense to particular stakeholders 6. add a flag for each slice so that the slice can be quickly shown 7. query the graph to output project artefacts for the dominant slice # Installation Check installation has been made, as per the [READme](https://github.com/lawrencerowland/Data-Model-for-Project-Frameworks/blob/master/Project-frameworks-by-using-NLP-with-Python-libraries/README.md) # Prior-steps One or more KGs can feed into this. The minimum would be 1 KG. This minimum would require either: ## Step 14 for a KG from an expert / stakeholder discussion/whiteboard session / paper *or* ## Step 6, 7 and 8 for a KG from keywords First find keywords <img src="images/Keywords-for-whole-library.png" width="45%"> Then select useful keyword relationships <img src="images/graph-schema-2.png" width="30%"> <img src="images/knowledge-graph-2.png" width="30%"> Add back in lower-scoring keywords <img src="images/Keyword-graph-3.png" width="60%"> *or* ## Step 5,8,9,12,13 for a KG from topic models. The LDA Topic algorithm is applied to the document library, via a Continuous Bag of Words transformation, and a TFIDF transformation. # How-to-use ## Combine graphs Open one of the three graphs in Neo4j. Then add the other two. These can be added either by: - graphml import - copying in the cypher code This depends on how the models were saved. Examples of both types of saving are in previous steps. ***the three graphs pulled in together*** ![3-graphs-together-1.png](images/3-graphs-together-1.png) We can query the model to ask what is the higher level schema reflected by this graph. i.e. what is the implied relationship between the various node labels. Use CALL db.schema() The result looks like this. ![](images/Combined_graph_schema.png) ## Label the graph Rationalise the graph, as a team where possible - Look for useful clusters - combine duplicate concepts - relabel concepts (e.g. in this case, topics is no longer a useful label) - lose direct relationships where there already is an indirect relationship In this case, we have lost the Topics group, whilst retaining most of the keyords. The structure of Success criteria, and project services and Site were more powerful. We have also retained the key division between two topics -so that our project services have shaken out either into a Supply-chain/ Management type services, or into more Technical and Operationally focussed project services. A rough sequence of implementing Success criteria helped in turn to order the Project Services, although some of the dependencies are not strong ones - but rather introduced to allow for easy comprehension. For each label we settle on, we look at the relationships within the group, and relationships with each other group, one at a time. Where useful sub-clusters are identified, we either create a new label, or we add a property for this label. For example the Requirements label is given a type property, which takes one of the following values: attribute or artefact. One useful method is to pull up one or two label groups only, and to arrange them in logical order within group. Cross-relationships can be seen. For large groups, it can be useful to use all four sides of the screen to arrange different nodes. ### Determine useful views (subgraphs) Views can be generated for specific purposes and stakeholders. ### OUTPUT 1 Work-breakdown view A project-management view focusses on tasks needed. Each node was reviewed, and given a boolean property as to whether the node was (or implied a task). For those which are tasks - another property was added, which described that task. When a cypher query is run to find only these tasks- then this becomes a work breakdown structure, which shows class relationships, and dependencies between tasks. - The view can be grouped by Success Factor. - Or it can be grouped by task, and showing predecessors or successors This can be used as a first draft of the Work Breakdown Structure in creating the project plan. **Work-breakdown of tasks, here ordered by Success factors** ![](images/combined_graph_WBS_linear_view.png) ### OUTPUT 2: Document view In just the same way, we identify which nodes are also associated with a project document. We add a boolean property flagging this, and we also add a node property for these nodes which is a document description. The image below shows all the documents. It is the result of running a query for all nodes where the boolean property is 1. The way the documents are spread out below shows how the user interacts with query results, moving nodes around, looking for project-like patterns. In this particular case, the user has identified a meaningful pattern by pulling apart the documents into four clusters: 1. high level definitions 2. site specific 3. design and system descriptions 4. stakeholder and controls documents. If desired, new labels can be added to capture meaningful clusters like this. We have not done this, as there are already enough labels to make sense of the project. This can be used : - as the basis for a Document Management plan, and for establishing Document Configuration Mgt - as Outputs attached to related tasks in the project plan - to contribute to the Stakeholder Mgt plan, in terms of who seems what - to confirm the natural order of development, in terms of what should be seen and reviewed first. ![](images/project_data_items-4way-view.png) ### OUTPUT 3: Project feature view (data-model ) This exercise has highlighted a number of features relevant to successful DeCom projects within an ONR environment. *What* What attributes should be recorded and tracked for each work-package? *Where* They will be captured in project records. These records may be in: - a spreadsheet - a project folder - a project database - an Enterprise Project Management tool - a cloud EPM tool Some of these feature will appear in project reports and dashboards. *Why* These features are key element of the data model for the project, to represent the special characteristics of projects in this business domain. If unnecessary features are captured, they will not be used to guide the project, and will be a waste of money and a distraction. *How* 1. These are taken from the graph database by running a query asking for every requirement or site-element that is directly related to any of the Project services. 2. This produces Column 1, from which we define the relevant work-package characteristic we should know throughout the project (see Column 2) *With what else?* These features are often added to features from standard project data models .i.e. scope, schedule, cost etc. This will normally come from the project framework that has been chosen and the Enterprise Project Management system which is being used. *How to use* Some or all of the below: 1. refine Project Data model and show and agree as a schema 2. confirm how Project Data will be managed in accord with this model 3. Set up / update the database which will be used for the project - so that it has this schema - this is likely to be a relational database - it might be an EPM or cloud EPM system that can be tailored to switch on the right data fields - it might just be a spreadsheet. 4. Update what fields will be controlled and/or reported on as a subset of the data model properties. ### OUTPUT 4: strategy -view The strategy view is determined by the following: - the documents and libraries used as input - the experts consulted to craft any other input knowledge graphs - the stakeholders with whom one works through this process. The strategy view can be created with different hierarchies to reflect the perspective of the stakeholder consuming that strategy view. For example, we have chosen to show the strategy in the following hierarchy: 1. requirements 2. Success-factors 3. project-services 4. site For example, other structures here could have: 1. site elements at highest level (waste/ facility etc) 2. success factors at highest level These would all be more helpful for different audiences. This approach has done the thinking via the clustering and labelling process. Another alternative does not start from one label or another. Instead it starts from the node that reflects the most important concept to a particular user, and uses that as an organising concept. From this node, one can then run a query that asks for nodes within a certain number of hops from that node. All nodes reached on the first hop then can be the highest level of a Strategy Table of Contents. *** Example showing a TOC based on 2 hops from node 'Clarify Waste routes'*** ![](images/2-hop-view-partial-for-waste-routes.png) *** Using the Strategy TOC in the project*** The TOC can be exported as: - a tree graph (using rawgraphs.io or similar) - a CSV file Accordingly it can be used as one or all of the following: 1. a TOC in a text or Word document 2. a diagram showing the hierarchy 3. a folder structure, by using text2folders or similar 4. a table with links to each place /module in the hierarchy ***A Strength of the knowledge graph for Strategy views*** All views are retained in one overall knowledge graph. Let us say that we create: 1. one Strategy TOC for finance with Financial reqts at top level 2. another Strategy TOC for Ops Directors starting from site 3. A third Strategy TOC starting from Success Factors for the project team Each of these users can be given their own TOC, and only ever need to see the project in this way. Meantime, we retain the full knowledge graph in the graph database, and then use it to populate project and workpackage details in more detail. We maintain it in Neo4j. As we maintain it, we can at any time print out an updated Strategy view or TOC that reflects an update of the original view requested by each user. This can be done by adding a boolean property for each view. Each node and relationship show 1 or 0 depending on whether they are represented in that particular view. ### Getting to the strategy views In the course of arriving at suitable views, it can be helpful to pull around the nodes into different clusters or levels, and to see how well this appeals to the User, and how many of the relationships effectively disappear into the simplification of nodes being at the same level. This is in the spirit of Herb Simon's Architecture of Complexity paper. for example this was an interim step: It is too complex for a stakeholder as it is, but is a useful waymark. ![](images/strategic-view.png) to make the strategy view easy to generate: - a series of Optional Match queries were run. - This generates some null results. The null results are not a problem, but we used them as a prompt to xxx - viewed the schema CALL apoc.meta.graph - we simplified the instances which were unncessarily complicating schema , using the apoc.refactor.invert(r), (i.e. where the eponymous direction was not giving helpful information) - there were one or two nodes that were not linked to many other nodes, and so were not appearing on a simple Optional match which slices through the graph one way. We added appropriate relationships so that the Optional Match picked them up. - where there were nulls,in this case where some Project services did not link to a a Success factor, we added an "Other success factor" node, for ease of reading. MATCH (p:project_task) OPTIONAL MATCH (k:Key_factor)-->(p:project_task) OPTIONAL MATCH (k:Key_factor)-->(p:project_task)-->(s:site) OPTIONAL MATCH (r:requirement)-->(k:Key_factor)-->(p:project_task) OPTIONAL MATCH (r:requirement)-->(k:Key_factor)-->(p:project_task)-->(s:site) RETURN r.name,k.name,p.name,s.name ORDER BY r.name, k.name # Next-steps Implement the Outputs in project controls
github_jupyter
The goal of this notebook: 1. Utilize a statistic (derived from a hypothesis test) to measure change within each polarization of a time series of SAR images. 2. Use threshold determined from a pair to determine change throughout a time series of L-band imagery. ``` import rasterio import numpy from pathlib import Path import matplotlib.pyplot as plt import numpy as np from astropy.convolution import convolve from tqdm import tqdm import matplotlib.patches as mpatches import geopandas as gpd from rscube import (get_geopandas_features_from_array, filter_binary_array_by_min_size, scale_img, polygonize_array_to_shapefile ) ``` # Setup Paths to Data ``` DATA_DIR = Path(f'data/') DATA_DIR.exists() hh_paths = sorted(list(DATA_DIR.glob('*/*hh*.tif'))) hv_paths = sorted(list(DATA_DIR.glob('*/*hv*.tif'))) vv_paths = sorted(list(DATA_DIR.glob('*/*vv*.tif'))) hv_paths CHANGE_DIR = Path('out/change_maps') CHANGE_DIR.mkdir(exist_ok=True, parents=True) ``` This will be a trehold associated with each polarization. We can save this if we want to continue such a threshold for the time series in this area. ``` if 'THRESHOLD_DICT' not in locals(): # keys = 'hh', 'hv', 'vv' # values = threshold associated with the change statistics THRESHOLD_DICT = {} THRESHOLD_DICT ``` # Polarization ``` POL = 'hv' ``` # Read Tifs ``` with rasterio.open(hv_paths[0]) as ds: profile = ds.profile def read_arr(path): with rasterio.open(path) as ds: arr = (ds.read(1)) return arr hv_ts = list(map(read_arr, hv_paths)) hh_ts = list(map(read_arr, hh_paths)) vv_ts = list(map(read_arr, vv_paths)) ``` # Change Statistic and Inspection We use a patch change detector elaborated in this [paper](https://www.researchgate.net/publication/229390532_How_to_Compare_Noisy_Patches_Patch_Similarity_Beyond_Gaussian_Noise) and simply add this metric channel by channel. $$ s_{p} = \log\left(\frac{xy}{(x + y)^2} \right) $$ where $x$ and $y$ are the backscatter values for a given polarization $p$ at a pixel for different times. We compute $s_p$ within a patch using a convolution. ``` PATCH_SIZE = 7 def get_change_statistic(img_0, img_1, patch_size=PATCH_SIZE, mask=None): X_0 = np.clip(img_0, 1e-3, 1) X_1 = np.clip(img_1, 1e-3, 1) glr = np.log(X_0 * X_1 / (X_0 + X_1)**2) if mask is not None: glr[mask] = np.nan kernel = np.ones((patch_size, patch_size)) change_statistic = convolve(glr, kernel, boundary='extend', nan_treatment='interpolate', normalize_kernel=True, preserve_nan=True) return change_statistic ``` We need a basic water mask, which we obtain via the HV image. ``` # Ignore the nodata areas and low db (specifically below -22) mask = np.isnan(hv_ts[0]) | (10 * np.log10(hv_ts[0]) < -22) # Remove small land areas from water mask = 1 - filter_binary_array_by_min_size(1 - mask.astype(int), 140).astype(bool) # Remove small water areas from land mask = filter_binary_array_by_min_size(mask.astype(int), 140).astype(bool) plt.imshow(mask, interpolation='none') p = profile.copy() p['dtype'] = 'uint8' p['nodata'] = None with rasterio.open('out/hv_mask.tif', 'w', **p) as ds: ds.write(mask.astype(np.uint8), 1) IND_0 = 0 IND_1 = 2 def get_ts(pol): if pol == 'hh': ts = hh_ts elif pol == 'hv': ts = hv_ts elif pol == 'vv': ts = vv_ts else: raise ValueError('choose hh, hv, vv') return ts ts = get_ts(POL) change_statistic = get_change_statistic(ts[IND_0], ts[IND_1], mask = mask ) plt.figure(figsize=(10, 10)) plt.imshow(change_statistic, interpolation='none') sy = np.s_[1_000:2_000] sx = np.s_[4000:5000] plt.figure(figsize=(10, 10)) plt.imshow(change_statistic[sy, sx], interpolation='none') plt.colorbar() PERCENTILE = 15 T = np.nanpercentile(change_statistic, PERCENTILE) data_mask = ~np.isnan(change_statistic) C = np.zeros(change_statistic.shape) C[data_mask] = (change_statistic[data_mask] < T) plt.imshow(C, interpolation=None) plt.figure(figsize=(10, 10)) plt.imshow(C[sy, sx], interpolation='none') SIZE = PATCH_SIZE**2 def morphological_filter(img): return filter_binary_array_by_min_size(img, SIZE) plt.figure(figsize=(10, 10)) C = morphological_filter(C) plt.imshow(morphological_filter(C), interpolation='none') plt.figure(figsize=(10, 10)) plt.imshow(C[sy, sx], interpolation='none') THRESHOLD_DICT[POL] = T DEST_DIR = (CHANGE_DIR/'_test_pairs') DEST_DIR.mkdir(exist_ok = True, parents=True) polygonize_array_to_shapefile(C, profile, DEST_DIR/f'{POL}_{IND_0}_{IND_1}', mask=~(C.astype(bool))) ``` # Inspecting Change Across the Time Series ``` n = len(ts) pol_thresh = THRESHOLD_DICT[POL] change_statistic_ts = [get_change_statistic(ts[i], ts[i + 1], mask=mask) for i in tqdm(range(n-1))] ``` Let's make sure the histogram roughly is well behaved across pairs. ``` for cs in change_statistic_ts: plt.figure(figsize=(5, 3)) data = (cs[~np.isnan(cs)]) plt.hist(data, bins=50) plt.title(f'median$=${np.median(data):1.2f}') ``` We now apply the threshold and morphological filter to get a change map. ``` def change_determination(change_statistic): data_mask = ~np.isnan(change_statistic) C = np.zeros(change_statistic.shape) C[data_mask] = (change_statistic[data_mask] < pol_thresh) C = morphological_filter(C) return C change_ts = list(map(change_determination, tqdm(change_statistic_ts))) ``` Let's check the results for different indices. ``` plt.figure(figsize=(10, 10)) plt.imshow(change_ts[0][sy, sx], interpolation='none') plt.figure(figsize=(10, 10)) plt.imshow(change_ts[1][sy, sx], interpolation='none') plt.figure(figsize=(10, 10)) plt.imshow(change_ts[2][sy, sx], interpolation='none') ``` ## Save Each Change Map We are going to create a dictionary in which each the `index in the time series + 1 --> date`. It's based on the name convention of how we named the images. Note strings are also lists in python so we can grab the pieces of the string name that are relevant. ``` def format_date(date_str): return f'{date_str[0:4]}-{date_str[4:6]}-{date_str[6:]}' date_dict = {(k + 1): format_date(str(path.name)[14:22]) for (k, path) in enumerate(hv_paths[1:])} date_dict[0] = 'No Change' date_dict ``` Now, we will write a shapefile for each pair as well as saving a binary image (tif file) of the same results. ``` DEST_DIR = (CHANGE_DIR/POL) DEST_DIR.mkdir(exist_ok = True, parents=True) TIF_DIR = DEST_DIR/'tifs' TIF_DIR.mkdir(exist_ok = True, parents=True) p = profile.copy() p['dtype'] = 'uint8' p['nodata'] = None def write_pairwise_changes(k): C = change_ts[k] date_str = date_dict[k+1] dest_path_shp = DEST_DIR/f'{POL}_{k}_{date_str}' dest_path_tif = TIF_DIR/f'{POL}_{k}_{date_str}.tif' polygonize_array_to_shapefile(C, p, dest_path_shp, mask=~(C.astype(bool))) with rasterio.open(dest_path_tif, 'w', **p) as ds: ds.write(C.astype(np.uint8), 1) return dest_path_shp, dest_path_tif list(map(write_pairwise_changes, tqdm(range(n-1)))) ``` ## Combine Pairwise Changes into Single Change Map We'll set each change map to an integer corresponding to it's `index + 1` in the time series. ``` change_map = np.zeros(change_ts[0].shape) for k in range(len(change_ts)): ind = change_ts[k].astype(bool) change_map[ind] = (change_ts[k][ind] * (k + 1)) fig, ax = plt.subplots(figsize=(10, 10)) cmap='tab20c' im = ax.imshow(change_map, cmap=cmap, interpolation='none') values = range(0, len(change_ts) + 1) colors = [im.cmap(im.norm(value)) for value in values] patches = [mpatches.Patch(color=colors[i], label=f'{date_dict[i]}') for i in range(len(values)) ] plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=15) plt.axis('off') fig, ax = plt.subplots(figsize=(10, 10)) im = ax.imshow(change_map[sy, sx], cmap=cmap, interpolation='none') plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=15) plt.axis('off') p = profile.copy() p['dtype'] = 'uint8' p['nodata'] = 0 with rasterio.open(DEST_DIR/f'{POL}_change_map_combined.tif', 'w', **p) as ds: ds.write(change_map.astype(np.uint8), 1) ``` ## Save Combined Change Map as shapefile ``` m = np.zeros(change_map.shape, dtype=bool) features = get_geopandas_features_from_array(change_map.astype(np.uint8), profile['transform'], mask=(change_map==0)) df = gpd.GeoDataFrame.from_features(features, crs=profile['crs']) df.label = df.label.astype('int') df.head() def date_trans(label): return date_dict[label] df['date'] = df.label.map(date_trans) df.head() fig, ax = plt.subplots(figsize=(10, 10)) df.plot(column='date', ax=ax, legend=True) df.to_file(DEST_DIR/f'{POL}_change_map_combined_shp') ```
github_jupyter
## Small introduction to Numpy ## Fast, faster, NumPy <img src="images/numpy.png" width=200 align=right /> Numpy allows us to run mathematical operations over calculations in a efficiant manner. Numpy provides several advantages for python user: - powerful n-dimensional arrays - advanced functions - can integrate C/C++ and Fortran code - efficient linear algebra, random number generation and Fourier transformation ### Vectorization When looping over an list or an array, there’s a lot of overhead involved. Vectorized operations in NumPy delegate the looping internally to highly optimized C and Fortran functions. Let's test the speed of numpy and create an array consisting of True and False. Assume we want to count how many times we have a transition from True to False or the other way round. First we will use a classic Python loop ``` import numpy as np np.random.seed(123) x = np.random.choice([False, True], size=100000) def transitions(x): count = 0 for i, j in zip(x[:-1], x[1:]): if j and not i: count += 1 return count #transitions(x) %timeit transitions(x) ``` Now can try the same with numpy ``` %timeit np.count_nonzero(x[:-1] < x[1:]) ``` ## Numpy arrays The core class is the numpy ndarray (n-dimensional array). We can initialize a numpy array from nested Python lists. #### Differences Between Python Lists and Numpy Arrays - All elements in a numpy arrays must be the same data type - Numpy arrays support arithmetic and other mathematical operations that run on each element of the array - Numpy arrays can store data along multiple dimensions. This makes numpy arrays a very efficient data structure for large datasets. This first example below shows how to generate different numpy arrays. For numpy arrays, brackets ```[]``` are used to assign and identify the dimensions of the numpy arrays. First we want to create a 1-dimensional array. ``` avg_precip = np.array([0.70, 0.75, 1.85, 1.90, 1.20, 0.9]) print(avg_precip) ``` In order to create a 2-dimensional array, we need to specify two sets of brackets ```[]```, the outer set that defines the entire array structure and inner sets that define the rows of the individual arrays. ``` min_max_temp_monthly = np.array([ [-2.11, -2.34, 1.40, 4.22, 9.34, 12.65, 14.26, 14.33, 11.19, 6.03, 2.33, 0.12], [3.00, 4.00, 9.33, 13.45, 19.72, 22.94, 24.99, 24.03, 19.28, 13.44, 7.03, 4.33] ]) print(min_max_temp_monthly) ``` Of course we can create as many dimensions we want ``` # 3-dimensional array multi_array = np.array([[[1,2,3,4], [5,6,7,8], [9,10,11,12],[13,14,15,16]],[[17,18,19,20], [21,22,23,24], [25,26,27,28],[30,31,32,33]]]) multi_array ``` Numpy also has some in-built functions to create certain types of numpy arrays. ``` a = np.zeros((2,2)) # Create an array of all zeros print(a) # Prints "[[ 0. 0.] # [ 0. 0.]]" b = np.ones((1,2)) # Create an array of all ones print(b) # Prints "[[ 1. 1.]]" c = np.full((2,2), 7) # Create a constant array print(c) # Prints "[[ 7. 7.] # [ 7. 7.]]" d = np.eye(2) # Create a 2x2 identity matrix print(d) # Prints "[[ 1. 0.] # [ 0. 1.]]" e = np.random.random((2,2)) # Create an array filled with random values print(e) # Might print "[[ 0.91940167 0.08143941] # [ 0.68744134 0.87236687]]" f = np.linspace(1, 15, 3) # The linspace() function returns numbers evenly spaced over a specified intervals. print(f) # Say we want 3 evenly spaced points from 1 to 15, we can easily use this. # linspace() takes the third argument as the number of datapoints to be created g= np.arange(3,10) # Lists the natural numbers from 3 to 9, as the number in the second position is excluded print(g) ``` Let's import some real world data into numpy.You can easily create new numpy arrays by importing numeric data from text files using the ```np.genfromtxt``` function from numpy. To start, let’s have a look at the top few lines of our data file. ``` f= open("../Data/non-spatial/climate-wue/monthly_climate_wuerzburg_18810101_20201231.txt",'r') fl =f.readlines() for x in fl: print(x) f.close() ``` Lets import the data into numpy and see what are we dealing with. Therefore we can use the ```np.genfromtxt()``` function ``` station_data = np.genfromtxt('../Data/non-spatial/climate-wue/monthly_climate_wuerzburg_18810101_20201231.txt', skip_header=1, delimiter = ';' ) print(station_data) ``` We can now start to work with the data. First let us have look at our data ``` print(type(station_data)) print(station_data.shape) print(station_data.dtype) ``` Okay we can see that we now have created a numpy array with 1680 rows and 17 columns. The data are floating point values with 64-bit precision. ### Working with numpy data - Index and slicing <img src="images/anatomyarray.png" width=800 /> Accessing single values in a 1-dimensional numpy array is straight forward. Always remember that indexing starts with 0. ``` avg_precip = np.array([0.70, 0.75, 1.85, 1.90, 1.20, 0.9]) avg_precip[0] avg_precip[3] ``` In case of our station data we are dealing with a 2-dimensional datset. So if we want to access one value we just need one index for each dimsension ``` station_data[0,0] ``` Similar to Python lists, numpy arrays can be sliced ``` station_data[:5,0] station_data[:5,:2] ``` Let's use this technique to slice our data up into different columns and creating new variables with the column data. The idea is to cut our 2D data into 3 separate columns that will be easier to work with. We will use following columns MESS_DATUM_BEGINN (start of measurement), MO_TN (Monthly mean of the air temperature minimum), MO_TX(Monthly mean of the air temperature maximum) ``` date = station_data[:, 1] temp_max = station_data[:, 8] temp_min = station_data[:, 9] ``` Now we can already start to do some basic calculations.Useful methods include mean(), min(), max(), and std(). ``` print(date.min()) print(date.max()) ``` Okay we now know that we have measurements from January 1881 until December 2020. Let's calculate the mean monthly maximum ``` print(temp_max.mean()) ``` Ooops! This seems wrong. Let's have a look at our data again ``` temp_max ``` We can see that we have a lot of values with -999. These are no data values. In order to make correct calculations we first have to clean our dataset. First, we need to identify a useful test for identifying missing data. We could could convert the data to integer values everywhere and test for values being equal to -999, but there’s an even easier option. Since we know all of our data are dates or temperatures, we can simply look for numbers below -998 to identify missing data ``` data_mask = (station_data < -998) station_data[data_mask] = np.nan station_data date = station_data[:, 1] temp_max = station_data[:, 8] temp_min = station_data[:, 9] temp_max.mean() ``` In the last example we can see that min() and the max() function returned nan. If we just want to get our min and max value we could use the nanmin()/nanmax() function in numpy ``` np.nanmin(temp_max) np.nanmax(temp_max) ``` But let's assume we want to get rid of the nan values. First of all we can count all missing values in our tavg array. To do this, we’ll need two new NumPy function, called np.count_nonzero() and np.isnan(). ``` print("Number of missing dates:", np.count_nonzero(np.isnan(temp_min))) ``` Now we now the number of nan values in the tavg array. Let's remove them ``` clean_data = ~np.isnan(temp_min) temp_min_clean = temp_min[clean_data ] temp_min_clean ``` And of course we can use the same mask to clean also the other arrays ``` clean_date = date[clean_data] temp_max_clean = temp_max[clean_data] temp_max_clean ``` Of course we can use always matplotlib to visualize our data ``` import matplotlib.pylab as plt plt.plot(temp_max_clean) ``` OK, now let’s use a range of dates to find the average maximum temperature for one year. In this case, let’s go for 2010. ``` temp_min_2010 = temp_min_clean[(clean_date >= 20100101) & (clean_date <= 20101231)] temp_min_2010.mean() ``` Next we want to calculate average monthly temperatures. Therefor we first need to convert our dates to strings ``` date_clean_str = (clean_date.astype(int)).astype(str) date_clean_str ``` Now we can only extract the year of our dates ``` year = [datenow[0:4] for datenow in date_clean_str] year = np.array(year) year ``` ...now we do the same for month and day ``` month = [datenow[4:6] for datenow in date_clean_str] month = np.array(month) day = [datenow[6:8] for datenow in date_clean_str] day = np.array(day) ``` Let’s take 2010 again as our example and find the average temperatures for each month in 2010 ``` means_2010 = np.zeros(12) index = 0 for month_now in np.unique(month): means_2010[index] = temp_min_clean[(month == month_now) & (year == '2010')].mean() index = index + 1 print(means_2010) temp_mean = np.zeros(temp_min_clean.shape) for i, temp in enumerate(temp_min_clean): temp_mean[i] = (temp_min_clean[i] + temp_max_clean[i]) / 2 temp_mean ``` Fortunatly we don't need a loop to make element-wise calculations. ``` arr = np.arange(1,21) # Numbers from 1 to 20 arr arr * arr # Multiplies each element by itself arr - arr # Subtracts each element from itself arr + arr # Adds each element to itself arr / arr # Divides each element by itself temp_mean = (temp_min_clean + temp_max_clean) / 2 temp_mean ``` You can also use the functions provided by numpy itself ``` x = np.array([[1,2,3,4],[5,6,7,8]]) y = np.array([[7,8,9,10],[11,12,13,14]]) # Elementwise sum np.add(x, y) # Elementwise difference np.subtract(x, y) # Elementwise product np.multiply(x, y) # Elementwise division np.divide(x, y) # Elementwise square root np.sqrt(x) temp_mean = np.divide(np.add(temp_min_clean, temp_max_clean), 2) temp_mean ``` ### Using functions This makes it quite easy for us to do math with numpy. For example we could convert our temperature from Celsius to Fahrenheit ``` mean_clean_F = 1.8 * temp_mean + 32 mean_clean_F ```
github_jupyter
``` #!/usr/bin/env python # -*- coding: utf-8 -*- #!python3 import tweepy, time, sys, json, requests, random def check_neotoma(): ## This function call to neotoma, reads a text file, compares the two ## and then returns all the 'new' records to a different text file. # inputs: # 1. text file: old_results.json # 2. text file: to_print.json # 3. json call: neotoma with open('old_results.json', 'r') as old_file: old_calls = json.loads(old_file.read()) with open('to_print.json', 'r') as print_file: to_print = json.loads(print_file.read()) neotoma = requests.get("http://ceiwin10.cei.psu.edu/NDB/RecentUploads?months=1") inp_json = json.loads(neotoma.text)['data'] def get_datasets(x): did = [] for y in x: did.append(y["DatasetID"]) return did neo_datasets = get_datasets(inp_json) old_datasets = get_datasets(old_calls) new_datasets = get_datasets(to_print) # So this works # We now have the numeric dataset IDs for the most recent month of # new files to neotoma (neo_datasets), all the ones we've already tweeted # (old_datasets) and all the ones in our queue (new_datasets). # # The next thing we want to do is to remove all the neo_datasets that # are in old_datasets and then remove all the new_datasets that are # in neo_datasets, append neo_datasets to new_datasets (if new_datasets # has a length > 0) and then dump new_datasets. # # Old datasets gets re-written when the tweets go out. # remove all the neo_datasets: for i in range(len(neo_datasets)-1, 0, -1): if neo_datasets[i] in old_datasets: del inp_json[i] # This now gives us a pared down version of inp_json # Now we need to make sure to add any of the to_print to neo_dataset. # We do this by cycling through new_datasets. Any dataset number that # is not in old_datasets or neo_datasets gets added to the beginning of # the new list. This way it is always the first called up when twitter # posts: for i in range(0, len(new_datasets)-1): if new_datasets[i] not in old_datasets and new_datasets[i] not in neo_datasets: inp_json.insert(0,to_print[i]) # Now write out to file. Old file doesn't get changed until the # twitter app is run. with open('to_print.json', 'w') as print_file: json.dump(inp_json, print_file) def post_tweet(): CONSUMER_KEY = 'jou6H9DZLPzw6f3aSIY7wzC6n' CONSUMER_SECRET = 'eum3NCrtrVC1tFsGvEj0GuqsxwQCWFfN8nmgcbMyA5xdmQhSdU' ACCESS_KEY = '3184480124-AHNgg72lXKYEuOjyzh5WKzBMkBBejpKIX9OxKpX' ACCESS_SECRET = 'GAmE6PX3ulj61tluwXA6jUKcPJwoCNToCg5JrJS8BbA3U' auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) api = tweepy.API(auth) print('Twitter authenticated \n') # Read in the printable tweets: with open('to_print.json', 'r') as print_file: to_print = json.loads(print_file.read()) with open('old_results.json', 'r') as print_file: old_files = json.loads(print_file.read()) print('Files opened\n') # Now loop through the records: while len(to_print) > 0: weblink = 'http://apps.neotomadb.org/Explorer/?datasetid=' + str(to_print[0]["DatasetID"]) line = 'Neotoma welcomes another ' + to_print[0]["DatabaseName"] + ' dataset: ' + to_print[0]["SiteName"] + " from " + to_print[0]["Investigator"] + " " + weblink if len(line) > 170: line = 'Neotoma welcomes another dataset: ' + to_print[0]["SiteName"] + " from " + to_print[0]["Investigator"] + " " + weblink print('%s' % line) if random.randint(0,30) == 10: line = 'This is a twitter bot for the Neotoma Paleoecological Database, letting you know what\'s new. http://neotomadb.org managed by @sjgoring' api.update_status(status=line) else: api.update_status(status=line) # Add the tweeted site to `old_files` and then delete it from the to_print. old_files.append(to_print[0]) del to_print[0] with open('to_print.json', 'w') as print_file: json.dump(to_print, print_file) with open('old_results.json', 'w') as print_file: json.dump(old_files, print_file) time.sleep(600) # Tweet every 10 minutes. if len(to_print) < 5: check_neotoma() post_tweet() import tweepy, time, sys, json, requests, random ```
github_jupyter
# Time Series Prediction **Objectives** 1. Build a linear, DNN and CNN model in keras to predict stock market behavior. 2. Build a simple RNN model and a multi-layer RNN model in keras. 3. Combine RNN and CNN architecture to create a keras model to predict stock market behavior. In this lab we will build a custom Keras model to predict stock market behavior using the stock market dataset we created in the previous labs. We'll start with a linear, DNN and CNN model Since the features of our model are sequential in nature, we'll next look at how to build various RNN models in keras. We'll start with a simple RNN model and then see how to create a multi-layer RNN in keras. We'll also see how to combine features of 1-dimensional CNNs with a typical RNN architecture. We will be exploring a lot of different model types in this notebook. To keep track of your results, record the accuracy on the validation set in the table here. In machine learning there are rarely any "one-size-fits-all" so feel free to test out different hyperparameters (e.g. train steps, regularization, learning rates, optimizers, batch size) for each of the models. Keep track of your model performance in the chart below. | Model | Validation Accuracy | |----------|:---------------:| | Baseline | 0.295 | | Linear | -- | | DNN | -- | | 1-d CNN | -- | | simple RNN | -- | | multi-layer RNN | -- | | RNN using CNN features | -- | | CNN using RNN features | -- | ## Load necessary libraries and set up environment variables ``` import os import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from google.cloud import bigquery from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential from tensorflow.keras.layers import (Dense, DenseFeatures, Conv1D, MaxPool1D, Reshape, RNN, LSTM, GRU, Bidirectional) from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint from tensorflow.keras.optimizers import Adam # To plot pretty figures %matplotlib inline mpl.rc('axes', labelsize=14) mpl.rc('xtick', labelsize=12) mpl.rc('ytick', labelsize=12) # For reproducible results. from numpy.random import seed seed(1) tf.random.set_seed(2) PROJECT = "your-gcp-project-here" # REPLACE WITH YOUR PROJECT NAME BUCKET = "your-gcp-bucket-here" # REPLACE WITH YOUR BUCKET REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 %env PROJECT = PROJECT BUCKET = BUCKET REGION = REGION ``` ## Explore time series data We'll start by pulling a small sample of the time series data from Big Query and write some helper functions to clean up the data for modeling. We'll use the data from the `percent_change_sp500` table in BigQuery. The `close_values_prior_260` column contains the close values for any given stock for the previous 260 days. ``` %%time bq = bigquery.Client(project=PROJECT) bq_query = ''' #standardSQL SELECT symbol, Date, direction, close_values_prior_260 FROM `stock_market.eps_percent_change_sp500` LIMIT 100 ''' df_stock_raw = bq.query(bq_query).to_dataframe() df_stock_raw.head() ``` The function `clean_data` below does three things: 1. First, we'll remove any inf or NA values 2. Next, we parse the `Date` field to read it as a string. 3. Lastly, we convert the label `direction` into a numeric quantity, mapping 'DOWN' to 0, 'STAY' to 1 and 'UP' to 2. ``` def clean_data(input_df): """Cleans data to prepare for training. Args: input_df: Pandas dataframe. Returns: Pandas dataframe. """ df = input_df.copy() # TF doesn't accept datetimes in DataFrame. df['Date'] = pd.to_datetime(df['Date'], errors='coerce') df['Date'] = df['Date'].dt.strftime('%Y-%m-%d') # TF requires numeric label. df['direction_numeric'] = df['direction'].apply(lambda x: {'DOWN': 0, 'STAY': 1, 'UP': 2}[x]) return df df_stock = clean_data(df_stock_raw) df_stock.head() ``` ## Read data and preprocessing Before we begin modeling, we'll preprocess our features by scaling to the z-score. This will ensure that the range of the feature values being fed to the model are comparable and should help with convergence during gradient descent. ``` STOCK_HISTORY_COLUMN = 'close_values_prior_260' COL_NAMES = ['day_' + str(day) for day in range(0, 260)] LABEL = 'direction_numeric' def _scale_features(df): """z-scale feature columns of Pandas dataframe. Args: features: Pandas dataframe. Returns: Pandas dataframe with each column standardized according to the values in that column. """ avg = df.mean() std = df.std() return (df - avg) / std def create_features(df, label_name): """Create modeling features and label from Pandas dataframe. Args: df: Pandas dataframe. label_name: str, the column name of the label. Returns: Pandas dataframe """ # Expand 1 column containing a list of close prices to 260 columns. time_series_features = df[STOCK_HISTORY_COLUMN].apply(pd.Series) # Rename columns. time_series_features.columns = COL_NAMES time_series_features = _scale_features(time_series_features) # Concat time series features with static features and label. label_column = df[LABEL] return pd.concat([time_series_features, label_column], axis=1) df_features = create_features(df_stock, LABEL) df_features.head() ``` Let's plot a few examples and see that the preprocessing steps were implemented correctly. ``` ix_to_plot = [0, 1, 9, 5] fig, ax = plt.subplots(1, 1, figsize=(15, 8)) for ix in ix_to_plot: label = df_features['direction_numeric'].iloc[ix] example = df_features[COL_NAMES].iloc[ix] ax = example.plot(label=label, ax=ax) ax.set_ylabel('scaled price') ax.set_xlabel('prior days') ax.legend() ``` ### Make train-eval-test split Next, we'll make repeatable splits for our train/validation/test datasets and save these datasets to local csv files. The query below will take a subsample of the entire dataset and then create a 70-15-15 split for the train/validation/test sets. ``` def _create_split(phase): """Create string to produce train/valid/test splits for a SQL query. Args: phase: str, either TRAIN, VALID, or TEST. Returns: String. """ floor, ceiling = '2002-11-01', '2010-07-01' if phase == 'VALID': floor, ceiling = '2010-07-01', '2011-09-01' elif phase == 'TEST': floor, ceiling = '2011-09-01', '2012-11-30' return ''' WHERE Date >= '{0}' AND Date < '{1}' '''.format(floor, ceiling) def create_query(phase): """Create SQL query to create train/valid/test splits on subsample. Args: phase: str, either TRAIN, VALID, or TEST. sample_size: str, amount of data to take for subsample. Returns: String. """ basequery = """ #standardSQL SELECT symbol, Date, direction, close_values_prior_260 FROM `stock_market.eps_percent_change_sp500` """ return basequery + _create_split(phase) bq = bigquery.Client(project=PROJECT) for phase in ['TRAIN', 'VALID', 'TEST']: # 1. Create query string query_string = create_query(phase) # 2. Load results into DataFrame df = bq.query(query_string).to_dataframe() # 3. Clean, preprocess dataframe df = clean_data(df) df = create_features(df, label_name='direction_numeric') # 3. Write DataFrame to CSV if not os.path.exists('../data'): os.mkdir('../data') df.to_csv('../data/stock-{}.csv'.format(phase.lower()), index_label=False, index=False) print("Wrote {} lines to {}".format( len(df), '../data/stock-{}.csv'.format(phase.lower()))) ls -la ../data ``` ## Modeling For experimentation purposes, we'll train various models using data we can fit in memory using the `.csv` files we created above. ``` N_TIME_STEPS = 260 N_LABELS = 3 Xtrain = pd.read_csv('../data/stock-train.csv') Xvalid = pd.read_csv('../data/stock-valid.csv') ytrain = Xtrain.pop(LABEL) yvalid = Xvalid.pop(LABEL) ytrain_categorical = to_categorical(ytrain.values) yvalid_categorical = to_categorical(yvalid.values) ``` To monitor training progress and compare evaluation metrics for different models, we'll use the function below to plot metrics captured from the training job such as training and validation loss or accuracy. ``` def plot_curves(train_data, val_data, label='Accuracy'): """Plot training and validation metrics on single axis. Args: train_data: list, metrics obtrained from training data. val_data: list, metrics obtained from validation data. label: str, title and label for plot. Returns: Matplotlib plot. """ plt.plot(np.arange(len(train_data)) + 0.5, train_data, "b.-", label="Training " + label) plt.plot(np.arange(len(val_data)) + 1, val_data, "r.-", label="Validation " + label) plt.gca().xaxis.set_major_locator(mpl.ticker.MaxNLocator(integer=True)) plt.legend(fontsize=14) plt.xlabel("Epochs") plt.ylabel(label) plt.grid(True) ``` ### Baseline Before we begin modeling in keras, let's create a benchmark using a simple heuristic. Let's see what kind of accuracy we would get on the validation set if we predict the majority class of the training set. ``` sum(yvalid == ytrain.value_counts().idxmax()) / yvalid.shape[0] ``` Ok. So just naively guessing the most common outcome `UP` will give about 29.5% accuracy on the validation set. ### Linear model We'll start with a simple linear model, mapping our sequential input to a single fully dense layer. ``` # TODO 1a model = Sequential() model.add(Dense(units=N_LABELS, activation='softmax', kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=30, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') ``` The accuracy seems to level out pretty quickly. To report the accuracy, we'll average the accuracy on the validation set across the last few epochs of training. ``` np.mean(history.history['val_accuracy'][-5:]) ``` ### Deep Neural Network The linear model is an improvement on our naive benchmark. Perhaps we can do better with a more complicated model. Next, we'll create a deep neural network with keras. We'll experiment with a two layer DNN here but feel free to try a more complex model or add any other additional techniques to try an improve your performance. ``` # TODO 1b dnn_hidden_units = [16, 8] model = Sequential() for layer in dnn_hidden_units: model.add(Dense(units=layer, activation="relu")) model.add(Dense(units=N_LABELS, activation="softmax", kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=10, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` ### Convolutional Neural Network The DNN does slightly better. Let's see how a convolutional neural network performs. A 1-dimensional convolutional can be useful for extracting features from sequential data or deriving features from shorter, fixed-length segments of the data set. Check out the documentation for how to implement a [Conv1d in Tensorflow](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv1D). Max pooling is a downsampling strategy commonly used in conjunction with convolutional neural networks. Next, we'll build a CNN model in keras using the `Conv1D` to create convolution layers and `MaxPool1D` to perform max pooling before passing to a fully connected dense layer. ``` # TODO 1c model = Sequential() # Convolutional layer model.add(Reshape(target_shape=[N_TIME_STEPS, 1])) model.add(Conv1D(filters=5, kernel_size=5, strides=2, padding="valid", input_shape=[None, 1])) model.add(MaxPool1D(pool_size=2, strides=None, padding='valid')) # Flatten the result and pass through DNN. model.add(tf.keras.layers.Flatten()) model.add(Dense(units=N_TIME_STEPS//4, activation="relu")) model.add(Dense(units=N_LABELS, activation="softmax", kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.compile(optimizer=Adam(lr=0.01), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=10, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` ### Recurrent Neural Network RNNs are particularly well-suited for learning sequential data. They retain state information from one iteration to the next by feeding the output from one cell as input for the next step. In the cell below, we'll build a RNN model in keras. The final state of the RNN is captured and then passed through a fully connected layer to produce a prediction. ``` # TODO 2a model = Sequential() # Reshape inputs to pass through RNN layer. model.add(Reshape(target_shape=[N_TIME_STEPS, 1])) model.add(LSTM(N_TIME_STEPS // 8, activation='relu', return_sequences=False)) model.add(Dense(units=N_LABELS, activation='softmax', kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) # Create the model. model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=40, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` ### Multi-layer RNN Next, we'll build multi-layer RNN. Just as multiple layers of a deep neural network allow for more complicated features to be learned during training, additional RNN layers can potentially learn complex features in sequential data. For a multi-layer RNN the output of the first RNN layer is fed as the input into the next RNN layer. ``` # TODO 2b rnn_hidden_units = [N_TIME_STEPS // 16, N_TIME_STEPS // 32] model = Sequential() # Reshape inputs to pass through RNN layer. model.add(Reshape(target_shape=[N_TIME_STEPS, 1])) for layer in rnn_hidden_units[:-1]: model.add(GRU(units=layer, activation='relu', return_sequences=True)) model.add(GRU(units=rnn_hidden_units[-1], return_sequences=False)) model.add(Dense(units=N_LABELS, activation="softmax", kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=50, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` ### Combining CNN and RNN architecture Finally, we'll look at some model architectures which combine aspects of both convolutional and recurrant networks. For example, we can use a 1-dimensional convolution layer to process our sequences and create features which are then passed to a RNN model before prediction. ``` # TODO 3a model = Sequential() # Reshape inputs for convolutional layer model.add(Reshape(target_shape=[N_TIME_STEPS, 1])) model.add(Conv1D(filters=20, kernel_size=4, strides=2, padding="valid", input_shape=[None, 1])) model.add(MaxPool1D(pool_size=2, strides=None, padding='valid')) model.add(LSTM(units=N_TIME_STEPS//2, return_sequences=False, kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.add(Dense(units=N_LABELS, activation="softmax")) model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=30, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` We can also try building a hybrid model which uses a 1-dimensional CNN to create features from the outputs of an RNN. ``` # TODO 3b rnn_hidden_units = [N_TIME_STEPS // 32, N_TIME_STEPS // 64] model = Sequential() # Reshape inputs and pass through RNN layer. model.add(Reshape(target_shape=[N_TIME_STEPS, 1])) for layer in rnn_hidden_units: model.add(LSTM(layer, return_sequences=True)) # Apply 1d convolution to RNN outputs. model.add(Conv1D(filters=5, kernel_size=3, strides=2, padding="valid")) model.add(MaxPool1D(pool_size=4, strides=None, padding='valid')) # Flatten the convolution output and pass through DNN. model.add(tf.keras.layers.Flatten()) model.add(Dense(units=N_TIME_STEPS // 32, activation="relu", kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.add(Dense(units=N_LABELS, activation="softmax", kernel_regularizer=tf.keras.regularizers.l1(l=0.1))) model.compile(optimizer=Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) history = model.fit(x=Xtrain.values, y=ytrain_categorical, batch_size=Xtrain.shape[0], validation_data=(Xvalid.values, yvalid_categorical), epochs=80, verbose=0) plot_curves(history.history['loss'], history.history['val_loss'], label='Loss') plot_curves(history.history['accuracy'], history.history['val_accuracy'], label='Accuracy') np.mean(history.history['val_accuracy'][-5:]) ``` ## Extra Credit 1. The `eps_percent_change_sp500` table also has static features for each example. Namely, the engineered features we created in the previous labs with aggregated information capturing the `MAX`, `MIN`, `AVG` and `STD` across the last 5 days, 20 days and 260 days (e.g. `close_MIN_prior_5_days`, `close_MIN_prior_20_days`, `close_MIN_prior_260_days`, etc.). Try building a model which incorporates these features in addition to the sequence features we used above. Does this improve performance? 2. The `eps_percent_change_sp500` table also contains a `surprise` feature which captures information about the earnings per share. Try building a model which uses the `surprise` feature in addition to the sequence features we used above. Does this improve performance? Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License
github_jupyter
## Part 1: Import Networks from Statoil Files This example explains how to use the OpenPNM.Utilies.IO.Statoil class to import a network produced by the Maximal Ball network extraction code developed by Martin Blunt's group at Imperial College London. The code is available from him upon request, but they offer a small library of pre-extracted networks on their [website](https://www.imperial.ac.uk/engineering/departments/earth-science/research/research-groups/perm/research/pore-scale-modelling/micro-ct-images-and-networks/). ``` import scipy as sp import openpnm as op ``` The following assumes that the folder containing the 'dat' files is in a directory called 'fixtures' in the same directory as this script. You can also enter a full path to the files. ``` from pathlib import Path path = Path('../fixtures/ICL-Sandstone(Berea)/') project = op.io.Statoil.load(path=path, prefix='Berea') pn = project.network pn.name = 'berea' ``` This import class extracts all the information contained in the 'Statoil' files, such as sizes, locations and connectivity. Note that the ``io`` classes return a ``project`` object, and the network itself can be accessed using the ``network`` attribute. The following printout display which information was contained in the file: ``` print(pn) ``` At this point, the network can be visualized in Paraview. A suitable '.vtp' file can be created with: ``` project.export_data(filename='imported_statoil') ``` The resulting network is shown below: ![](http://i.imgur.com/771T36M.png) ### Clean up network topology Although it's not clear in the network image, there are a number of isolated and disconnected pores in the network. These are either naturally part of the sandstone, or artifacts of the Maximal Ball algorithm. In any event, these must be removed before proceeding since they cause problems for the matrix solver. The easiest way to find these is to use the ```check_network_health``` function on the network object. This will return a dictionary with several key attributes, including a list of which pores are isolated. These can then be trimmed using the ``trim`` function in the ``topotools`` module. ``` print('Number of pores before trimming: ', pn.Np) h = pn.check_network_health() op.topotools.trim(network=pn, pores=h['trim_pores']) print('Number of pores after trimming: ', pn.Np) ``` ### Dealing with Inlet and Outlet Pores When importing Statoil networks, OpenPNM must perform some 'optimizations' to make the network compatible. The main problem is that the original network contains a large number of throats connecting actual internal pores to fictitious 'reservoir' pores. OpenPNM strips away all these throats since 'headless throats' break the graph theory representation. OpenPNM then labels the real internal pores as either 'inlet' or 'outlet' if they were connected to one of these fictitious reservoirs. It is fairly simple to add a new pores to each end of the domain and stitch tehm to the internal pores labelled 'inlet' and 'outlet', but this introduces a subsequent complication that the new pores don't have any geometry properties. For this example, we will not add boundary pores, but just the pores on the inlet and outlet faces. ## Part 2: Calculating Permeability of the Network ### Setup Geometry, Phase, and Physics Objects In OpenPNM 2+ it is optional to define Geometry and Physics objects (These are really only necessary for simulations with diverse geometrical properties in different regions, resulting in different physical processes in each region, such as multiscale networks for instance). It is still necessary to define **Phase** objects: ``` water = op.phases.Water(network=pn) ``` ### Apply Pore-Scale Models We must add the hagen-poiseuille model for calculating the conductance. In OpenPNM 2+ it is possible to add Physics models to Phase objects, which is often simpler than than applying the same model to multiple Physics. ``` water.add_model(propname='throat.hydraulic_conductance', model=op.models.physics.hydraulic_conductance.valvatne_blunt) ``` Recall that boundary pores and throats had no geometrical properties associated with them, so the hydraulic conductances of boundary throats will be undefined (filled with NaNs): ``` print(water['throat.hydraulic_conductance']) ``` ### Run StokesFlow Algorithm Finally, we can create a **StokesFlow** object to run some fluid flow simulations: ``` flow = op.algorithms.StokesFlow(network=pn, phase=water) flow.set_value_BC(pores=pn.pores('inlets'), values=200000) flow.set_value_BC(pores=pn.pores('outlets'), values=100000) flow.run() ``` The resulting pressure field can be visualized in Paraview, giving the following: ![](https://i.imgur.com/AIK6FbJ.png) ### Determination of Permeability Coefficient The way to calculate K is the determine each of the values in Darcy's law manually and solve for K, such that $$ K = \frac{Q\mu L} {\Delta P A} $$ ``` # Get the average value of the fluid viscosity mu = sp.mean(water['pore.viscosity']) # Specify a pressure difference (in Pa) delta_P = 100000 # Using the rate method of the StokesFlow algorithm Q = sp.absolute(flow.rate(pores=pn.pores('inlets'))) # Because we know the inlets and outlets are at x=0 and x=X Lx = sp.amax(pn['pore.coords'][:, 0]) - sp.amin(pn['pore.coords'][:, 0]) A = Lx*Lx # Since the network is cubic Lx = Ly = Lz K = Q*mu*Lx/(delta_P*A) print(K) ```
github_jupyter
<img src="Frame.png" width="320"> # Reference frames Objects can be created in reference frames in order to share the same drawing order priority and the same coordinate system. Objects in a reference frame - Have $(x,y)$ coordinates determined by the frame geometry. - Can change geometry all at once by changing the frame geometry. - Can change visibility all at once by changing the visibility of the frame. - Can be forgotten all at once by either forgetting or resetting the frame. - Are drawn all at once in the drawing order of the frame -- objects drawn after the frame will be "on top" of the frame elements. Frame geometry does not effect the styling for elements in the frame including - Line styling. - Circle radius. - Rectangle and image width, height, dx, dy, and degrees rotation. - Polygon rotation. - Text font and alignment. Some special object types are adjusted more closely to the frame - A `frame_circle` has its radius automatically adjusted to reflect the maximum frame distortion. - A `frame_rect` is essentially converted to a polygon with all vertices determined by the frame geometry. Below we create the `adorn` function to draw example objects on a frame and show how these objects are effected by differently configured frame geometries. ``` from jp_doodle import dual_canvas from IPython.display import display points = [[50,0], [40,-20], [40,-40], [30,-60], [30,-50], [10,-40], [20,-30], [20,-20], [30,-10], [0,0]] def adorn(frame, frame_name): def text_at(x, y, content): frame.text(x=x, y=y, text=content, color="black", background="white", align="center", valign="center") frame.circle(x=50, y=25, r=25, color="#339") frame.frame_circle(x=75, y=75, r=25, color="#539") frame.rect(x=-50, y=25, h=30, w=50, color="#369") frame.frame_rect(x=-75, y=75, h=30, w=50, color="#93a") # This local image reference works in "classic" notebook, but not in Jupyter Lab. mandrill_url = "../mandrill.png" frame.name_image_url("mandrill", mandrill_url) frame.named_image(image_name="mandrill", x=-90, y=-90, w=79, h=70) frame.polygon(points=points, lineWidth=5, color="#4fa", fill=False) # add some labels for clarity text_at(50, 25, "circle") text_at(75, 75, "frame_circle") text_at(-25, 40, "rect") text_at(-50, 90, "frame_rect") cfg = {"color":"salmon"} frame.lower_left_axes(-100, -100, 100, 100, max_tick_count=4, tick_text_config=cfg, tick_line_config=cfg) text_at(0, -120, frame_name) no_frame = dual_canvas.DualCanvasWidget(width=420, height=420) display(no_frame) adorn(no_frame, "Not a frame") no_frame.fit(None, 20) # Display the objects "outside" of any frame: slanted = dual_canvas.SnapshotCanvas("Frame.png", width=420, height=420) slanted.display_all() # The vector frame factory provides the most general frame parameters. slanted_frame = slanted.vector_frame( x_vector={"x":1, "y":-0.3}, y_vector={"x":1, "y":1}, xy_offset={"x":1100, "y":1200} ) adorn(slanted_frame, "Slanted") slanted.fit() slanted.lower_left_axes() slanted.fit(None, 20) ``` Above note that the positions of the objects change, but the styling of the objects is not changed by the frame geometry except for the `frame_circle` radius which reflects the `y` axis distortion and the vertices of the `frame_rect` which reflect the frame geometry. ``` exploded = dual_canvas.DualCanvasWidget(width=420, height=420) display(exploded) # The rframe factory creates frames with scaling and translation. exploded_frame = exploded.rframe( scale_x=3.5, scale_y=3, translate_x=-700, translate_y=700) adorn(exploded_frame, "Exploded") exploded.fit() exploded.lower_left_axes() exploded.fit(None, 20) squashed = dual_canvas.DualCanvasWidget(width=420, height=420) display(squashed) # The frame_region frame factory maps a region of "model space" # to a region in "frame space". It is sometimes easier to think # in terms of regions rather than vectors and scalings. squashed_frame = squashed.frame_region( minx=200, miny=-1200, maxx=400, maxy=-1100, frame_minx=-100, frame_miny=-100, frame_maxx=100, frame_maxy=100) adorn(squashed_frame, "Squashed") squashed.fit() squashed.lower_left_axes() squashed.fit(None, 20) # Note below that the frame_circle radius does not show # any change because the maximum distortion in the x direction is 1. ```
github_jupyter
Para entrar no modo apresentação, execute a seguinte célula e pressione `-` ``` %cd .. %reload_ext slide ``` <span class="notebook-slide-start"/> # Lista de Widgets Foram apresentados `IntSlider`, `Output`, `VBox` e `Button` até agora. No restante deste notebook, vou apresentar outros widgets que existem na biblioteca `ipywidgets` Parte do material tirado de https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html ### Widgets de texto #### Label Apenas um label somente leitura <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Label Label("Texto") ``` #### Text Campo de texto <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Text Text( value='Hello World', placeholder='Type something', description='String:', disabled=False ) ``` #### Textarea Área de texto <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Textarea Textarea( value='Hello World', placeholder='Type something', description='String:', disabled=False ) ``` #### Combobox Combobox com autocomplete <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Combobox Combobox( # value='John', placeholder='Choose Someone', options=['Paul', 'John', 'George', 'Ringo'], description='Combobox:', ensure_option=True, disabled=False ) ``` #### HTML HTML somente leitura <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import HTML HTML( value="Hello <b>World</b>", placeholder='Some HTML', description='Some HTML', ) ``` #### HTMLMath HTML somente leitura com fórmulas <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import HTMLMath HTMLMath( value=r"Some math and <i>HTML</i>: \(x^2\) and $$\frac{x+1}{x-1}$$", placeholder='Some HTML', description='Some HTML', ) ``` ### Widgets numéricos #### FloatSlider Semelhante a `IntSlider`, mas para `float` <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import FloatSlider FloatSlider( value=7.5, min=0, max=10.0, step=0.1, readout_format='.1f' ) ``` #### FloatLogSlider `FloatSlider` com escala logaritimica <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import FloatLogSlider FloatLogSlider( value=10, base=10, min=-10, # max exponent of base max=10, # min exponent of base step=0.2, # exponent step description='Log Slider' ) ``` #### IntRangeSlider, FloatRangeSlider Sliders com dois valores <span class="notebook-slide-extra" data-count="2"/> ``` from ipywidgets import IntRangeSlider IntRangeSlider( value=[5, 7], min=0, max=10, step=1, ) _.value ``` #### IntProgress, FloatProgress Widgets que representam barra de progresso <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import IntProgress IntProgress( value=7, min=0, max=10, step=1, description='Loading:', bar_style='', # 'success', 'info', 'warning', 'danger' or '' orientation='horizontal' ) ``` #### IntText, FloatText Campos de texto numéricos <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import IntText IntText( value=7, description='Any:', disabled=False ) ``` #### BoundedIntText, BoundedFloatText Campos de texto numéricos limitados <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import BoundedFloatText BoundedFloatText( value=7.5, min=0, max=10.0, step=0.1, description='Text:', ) ``` ### Widgets booleanos #### ToggleButton Botão com estado booleano <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import ToggleButton ToggleButton( value=False, description='Click me', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Description', icon='check' ) ``` #### Checkbox <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Checkbox Checkbox( value=False, description='Check me', ) ``` #### Valid Indicador somente leitura <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Valid Valid( value=True, description='Valid!', ) ``` ### Widgets de seleção #### Dropdown Widget para selecionar elementos de uma lista <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Dropdown Dropdown( options= [('One', 1), ('Two', 2), ('Three', 3)], value=2, description='Number:', disabled=False, ) ``` #### RadioButtons Selecionar usando radio buttons <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import RadioButtons RadioButtons( options=['One', 'Two', 'Three'], description='Number:', disabled=False ) ``` #### Select Selecionar usando uma lista visível <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Select Select( options=['Linux', 'Windows', 'OSX'], value='OSX', # rows=10, description='OS:', disabled=False ) ``` #### SelectionSlider Slider para seleção de campos nominais <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import SelectionSlider SelectionSlider( options=['mal passada', 'ao ponto', 'bem passada'], value='ao ponto', description='Carne ...', disabled=False, continuous_update=False, orientation='horizontal', readout=True ) ``` #### SelectionRangeSlider Slider para seleção de intervalo nominal <span class="notebook-slide-extra" data-count="1"/> ``` import datetime from ipywidgets import SelectionRangeSlider dates = [datetime.date(2019,i,1) for i in range(1,13)] options = [(i.strftime('%b'), i) for i in dates] SelectionRangeSlider( options=options, index=(0,11), description='2019', disabled=False ) ``` #### ToggleButtons `ToggleButton` para escolher um único elemento de lista <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import ToggleButtons ToggleButtons( options=['Slow', 'Regular', 'Fast'], description='Speed:', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Description of slow', 'Description of regular', 'Description of fast'], # icons=['check'] * 3 ) ``` #### SelectMultiple Seleção de vários elementos <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import SelectMultiple SelectMultiple( options=['Apples', 'Oranges', 'Pears'], value=['Oranges'], #rows=10, description='Fruits', disabled=False ) ``` ### Widgets de estrutura #### HBox Semelhante ao `VBox`, mas exibe widgets na horizontal ao invés de na vertical <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import HBox HBox([Label("a"), Label("b")]) ``` #### GridBox Semelhante a `VBox` e `HBox`, mas usa `HTML Grid` para fazer a exibição <span class="notebook-slide-extra" data-count="1"/> Aqui estamos usando Layout também para definir atributos do `CSS` ``` from ipywidgets import GridBox, Layout items = [Label(str(i)) for i in range(8)] GridBox(items, layout=Layout(grid_template_columns="repeat(3, 100px)")) ``` #### Accordion Exibe widgets em páginas diferentes de Accordion <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Accordion accordion = Accordion([Label("a"), Label("b")]) accordion.set_title(0, 'Page 0') accordion.set_title(1, 'Page 1') accordion ``` #### Tab Exibe widgets em abas diferentes <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Tab tab = Tab([Label("a"), Label("b")]) tab.set_title(0, 'Page 0') tab.set_title(1, 'Page 1') tab ``` ### Outros widgets #### Play Widget útil para controlar animações <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Play, jslink, IntSlider play = Play( # interval=10, value=50, min=0, max=100, step=1, description="Press play", disabled=False ) slider = IntSlider() jslink((play, 'value'), (slider, 'value')) HBox([play, slider]) ``` #### DatePicker Widget para escolher datas <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import DatePicker DatePicker( description='Pick a Date', disabled=False ) ``` #### ColorPicker Widget para escolher cor <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import ColorPicker ColorPicker( concise=False, description='Pick a color', value='blue', disabled=False ) ``` #### FileUpload Widget para fazer upload de arquivos e receber em bytes <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import FileUpload FileUpload( accept='', # Accepted file extension e.g. '.txt', '.pdf', 'image/*', 'image/*,.pdf' multiple=False # True to accept multiple files upload else False ) ``` #### Image Widget para visualizar imagem <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Image file = open("images/jupyter.png", "rb") image = file.read() Image( value=image, format='png', width=50, height=50, ) ``` #### Controller Widget para usar controle de jogo como entrada <span class="notebook-slide-extra" data-count="1"/> ``` from ipywidgets import Controller Controller( index=0, ) ``` &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
github_jupyter
Copyright ENEOS, Corp., Preferred Computational Chemistry, Inc. and Preferred Networks, Inc. as contributors to Matlantis contrib project # 不均一系触媒上の反応解析(NEB法) 目次: - **[1. BulkからSlab作成](#chap1)** - **[2. MoleculeをSlab上に配置、始状態(反応前)と終状態(反応後)を作成](#chap2)** - **[3. NEB計算](#chap3)** - **[4. NEB計算結果の確認と遷移状態構造取得](#chap4)** - **[5. 遷移状態構造の構造最適化(by Sella)](#chap5)** - **[6. 遷移状態の振動解析](#chap6)** - **[7. 遷移状態からの追加解析(擬似IRC計算)](#chap7)** <a id="chap0"></a> ## セットアップ ``` # time.sleep(3600*10) # # notebookで1.5時間無処理状態が続きますとkernelが自動でshutdownします。 # # kernelを保持したい場合に上の行の#を外して実行してください。 !pip install pfp-api-client !pip install pandas tqdm matplotlib seaborn optuna sella sklearn torch torch_dftd # # 初回使用時のみ、ライブラリのインストールをお願いします。 # 汎用モジュール import numpy as np import pandas as pd from tqdm import tqdm_notebook as tqdm from IPython.display import display_png from IPython.display import Image as ImageWidget import ipywidgets as widgets import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.widgets import Slider from matplotlib.animation import PillowWriter import seaborn as sns import math import optuna import nglview as nv import os,sys,csv,glob,shutil,re,time from pathlib import Path from PIL import Image, ImageDraw # sklearn from sklearn.metrics import mean_absolute_error # ASE import ase from ase import Atoms, units from ase.units import Bohr,Rydberg,kJ,kB,fs,Hartree,mol,kcal from ase.io import read, write from ase.build import surface, molecule, add_adsorbate from ase.cluster.cubic import FaceCenteredCubic from ase.constraints import FixAtoms, FixedPlane, FixBondLength, ExpCellFilter from ase.neb import SingleCalculatorNEB from ase.neb import NEB from ase.vibrations import Vibrations from ase.visualize import view from ase.optimize import QuasiNewton from ase.thermochemistry import IdealGasThermo from ase.build.rotate import minimize_rotation_and_translation from ase.visualize import view from ase.optimize import BFGS, LBFGS, FIRE from ase.md.velocitydistribution import MaxwellBoltzmannDistribution, Stationary from ase.md.verlet import VelocityVerlet from ase.md.langevin import Langevin from ase.md.nptberendsen import NPTBerendsen, Inhomogeneous_NPTBerendsen from ase.md import MDLogger from ase.io import read, write, Trajectory # from ase.calculators.dftd3 import DFTD3 from ase.build import sort from sella import Sella, Constraints from torch_dftd.torch_dftd3_calculator import TorchDFTD3Calculator # PFP from pfp_api_client.pfp.calculators.ase_calculator import ASECalculator from pfp_api_client.pfp.estimator import Estimator from pfp_api_client.pfp.estimator import EstimatorCalcMode estimator = Estimator(calc_mode="CRYSTAL") calculator = ASECalculator(estimator) # calculatorD = DFTD3(dft=calculator, xc = 'pbe', label="ase_dftd3_3") #   いままでと同じコードでD3計算とする場合 calculatorD = TorchDFTD3Calculator(dft=calculator, xc="pbe", label="dftd3") #   いままでと同じコードでD3計算とする場合 # このセルはexperimental, unexpectedな元素の計算を行う際にでるwarningを抑制するためのコマンドです。必要なときのみ実行してください。 # from pfp_api_client.utils.messages import MessageEnum # estimator.set_message_status(message=MessageEnum.ExperimentalElementWarning, message_enable=False) # estimator.set_message_status(message=MessageEnum.UnexpectedElementWarning, message_enable=False) def myopt(m,sn = 10,constraintatoms=[],cbonds=[]): fa = FixAtoms(indices=constraintatoms) fb = FixBondLengths(cbonds,tolerance=1e-5,) m.set_constraint([fa,fb]) m.set_calculator(calculator) maxf = np.sqrt(((m.get_forces())**2).sum(axis=1).max()) print("ini pot:{:.4f},maxforce:{:.4f}".format(m.get_potential_energy(),maxf)) de = -1 s = 1 ita = 50 while ( de < -0.001 or de > 0.001 ) and s <= sn : opt = BFGS(m,maxstep=0.04*(0.9**s),logfile=None) old = m.get_potential_energy() opt.run(fmax=0.0005,steps =ita) maxf = np.sqrt(((m.get_forces())**2).sum(axis=1).max()) de = m.get_potential_energy() - old print("{} pot:{:.4f},maxforce:{:.4f},delta:{:.4f}".format(s*ita,m.get_potential_energy(),maxf,de)) s += 1 return m def opt_cell_size(m,sn = 10, iter_count = False): # m:Atomsオブジェクト m.set_constraint() # clear constraint m.set_calculator(calculator) maxf = np.sqrt(((m.get_forces())**2).sum(axis=1).max()) # √(fx^2 + fy^2 + fz^2)の一番大きいものを取得 ucf = ExpCellFilter(m) print("ini pot:{:.4f},maxforce:{:.4f}".format(m.get_potential_energy(),maxf)) de = -1 s = 1 ita = 50 while ( de < -0.01 or de > 0.01 ) and s <= sn : opt = BFGS(ucf,maxstep=0.04*(0.9**s),logfile=None) old = m.get_potential_energy() opt.run(fmax=0.005,steps =ita) maxf = np.sqrt(((m.get_forces())**2).sum(axis=1).max()) de = m.get_potential_energy() - old print("{} pot:{:.4f},maxforce:{:.4f},delta:{:.4f}".format(s*ita,m.get_potential_energy(),maxf,de)) s += 1 if iter_count == True: return m, s*ita else: return m #表面を作る def makesurface(atoms,miller_indices=(1,1,1),layers=4,rep=[4,4,1]): s1 = surface(atoms, miller_indices,layers) s1.center(vacuum=10.0, axis=2) s1 = s1.repeat(rep) s1.set_positions(s1.get_positions() - [0,0,min(s1.get_positions()[:,2])]) s1.pbc = True return s1 import threading import time from math import pi from typing import Dict, List, Optional import nglview as nv from ase import Atoms from ase.constraints import FixAtoms from ase.optimize import BFGS from ase.visualize import view from IPython.display import display from ipywidgets import ( Button, Checkbox, FloatSlider, GridspecLayout, HBox, IntSlider, Label, Text, Textarea, ) from nglview.widget import NGLWidget def save_image(filename: str, v: NGLWidget): """Save nglview image. Note that it should be run on another thread. See: https://github.com/nglviewer/nglview/blob/master/docs/FAQ.md#how-to-make-nglview-view-object-write-png-file Args: filename (str): v (NGLWidget): """ image = v.render_image() while not image.value: time.sleep(0.1) with open(filename, "wb") as fh: fh.write(image.value) class SurfaceEditor: """Structure viewer/editor""" struct: List[Dict] # structure used for nglview drawing. def __init__(self, atoms: Atoms): self.atoms = atoms self.vh = view(atoms, viewer="ngl") self.v: NGLWidget = self.vh.children[0] # VIEW self.v._remote_call("setSize", args=["450px", "450px"]) self.recont() # Add controller self.set_representation() self.set_atoms() self.pots = [] self.traj = [] self.cal_nnp() def display(self): display(self.vh) def recont(self): self.vh.setatoms = FloatSlider( min=0, max=50, step=0.1, value=8, description="atoms z>" ) self.vh.setatoms.observe(self.set_atoms) self.vh.selected_atoms_label = Label("Selected atoms:") self.vh.selected_atoms_textarea = Textarea() selected_atoms_hbox = HBox( [self.vh.selected_atoms_label, self.vh.selected_atoms_textarea] ) self.vh.move = FloatSlider( min=0.1, max=2, step=0.1, value=0.5, description="move" ) grid1 = GridspecLayout(2, 3) self.vh.xplus = Button(description="X+") self.vh.xminus = Button(description="X-") self.vh.yplus = Button(description="Y+") self.vh.yminus = Button(description="Y-") self.vh.zplus = Button(description="Z+") self.vh.zminus = Button(description="Z-") self.vh.xplus.on_click(self.move) self.vh.xminus.on_click(self.move) self.vh.yplus.on_click(self.move) self.vh.yminus.on_click(self.move) self.vh.zplus.on_click(self.move) self.vh.zminus.on_click(self.move) grid1[0, 0] = self.vh.xplus grid1[0, 1] = self.vh.yplus grid1[0, 2] = self.vh.zplus grid1[1, 0] = self.vh.xminus grid1[1, 1] = self.vh.yminus grid1[1, 2] = self.vh.zminus self.vh.rotate = FloatSlider( min=1, max=90, step=1, value=30, description="rotate" ) grid2 = GridspecLayout(2, 3) self.vh.xplus2 = Button(description="X+") self.vh.xminus2 = Button(description="X-") self.vh.yplus2 = Button(description="Y+") self.vh.yminus2 = Button(description="Y-") self.vh.zplus2 = Button(description="Z+") self.vh.zminus2 = Button(description="Z-") self.vh.xplus2.on_click(self.rotate) self.vh.xminus2.on_click(self.rotate) self.vh.yplus2.on_click(self.rotate) self.vh.yminus2.on_click(self.rotate) self.vh.zplus2.on_click(self.rotate) self.vh.zminus2.on_click(self.rotate) grid2[0, 0] = self.vh.xplus2 grid2[0, 1] = self.vh.yplus2 grid2[0, 2] = self.vh.zplus2 grid2[1, 0] = self.vh.xminus2 grid2[1, 1] = self.vh.yminus2 grid2[1, 2] = self.vh.zminus2 self.vh.nnptext = Textarea(disabled=True) self.vh.opt_step = IntSlider( min=0, max=100, step=1, value=10, description="Opt steps", ) self.vh.constraint_checkbox = Checkbox( value=True, description="Opt only selected atoms", ) self.vh.run_opt_button = Button( description="Run mini opt", tooltip="Execute BFGS optimization with small step update." ) self.vh.run_opt_button.on_click(self.run_opt) opt_hbox = HBox([self.vh.constraint_checkbox, self.vh.run_opt_button]) self.vh.filename_text = Text(value="screenshot.png", description="filename: ") self.vh.download_image_button = Button( description="download image", tooltip="Download current frame to your local PC", ) self.vh.download_image_button.on_click(self.download_image) self.vh.save_image_button = Button( description="save image", tooltip="Save current frame to file.\n" "Currently .png and .html are supported.\n" "It takes a bit time, please be patient.", ) self.vh.save_image_button.on_click(self.save_image) self.vh.update_display = Button( description="update_display", tooltip="Refresh display. It can be used when target atoms is updated in another cell..", ) self.vh.update_display.on_click(self.update_display) r = list(self.vh.control_box.children) r += [ self.vh.setatoms, selected_atoms_hbox, self.vh.move, grid1, self.vh.rotate, grid2, self.vh.nnptext, self.vh.opt_step, opt_hbox, self.vh.filename_text, HBox([self.vh.download_image_button, self.vh.save_image_button]), self.vh.update_display, ] self.vh.control_box.children = tuple(r) def set_representation(self, bcolor: str = "white", unitcell: bool = True): self.v.background = bcolor self.struct = self.get_struct(self.atoms) self.v.add_representation(repr_type="ball+stick") self.v.control.spin([0, 1, 0], pi * 1.1) self.v.control.spin([1, 0, 0], -pi * 0.45) thread = threading.Thread(target=self.changestr) thread.start() def changestr(self): time.sleep(2) self.v._remote_call("replaceStructure", target="Widget", args=self.struct) def get_struct(self, atoms: Atoms, ext="pdb") -> List[Dict]: struct = nv.ASEStructure(atoms, ext=ext).get_structure_string() for c in range(len(atoms)): struct = struct.replace("MOL 1", "M0 " + str(c).zfill(3), 1) struct = [dict(data=struct, ext=ext)] return struct def cal_nnp(self): pot = self.atoms.get_potential_energy() mforce = (((self.atoms.get_forces()) ** 2).sum(axis=1).max()) ** 0.5 self.pot = pot self.mforce = mforce self.vh.nnptext.value = f"pot energy: {pot} eV\nmax force : {mforce} eV/A" self.pots += [pot] self.traj += [self.atoms.copy()] def update_display(self, clicked_button: Optional[Button] = None): print("update display!") struct = self.get_struct(self.atoms) self.struct = struct self.v._remote_call("replaceStructure", target="Widget", args=struct) self.cal_nnp() def set_atoms(self, slider: Optional[FloatSlider] = None): """Update text area based on the atoms position `z` greater than specified value.""" smols = [ i for i, atom in enumerate(self.atoms) if atom.z >= self.vh.setatoms.value ] self.vh.selected_atoms_textarea.value = ", ".join(map(str, smols)) def get_selected_atom_indices(self) -> List[int]: selected_atom_indices = self.vh.selected_atoms_textarea.value.split(",") selected_atom_indices = [int(a) for a in selected_atom_indices] return selected_atom_indices def move(self, clicked_button: Button): a = self.vh.move.value for index in self.get_selected_atom_indices(): if clicked_button.description == "X+": self.atoms[index].position += [a, 0, 0] elif clicked_button.description == "X-": self.atoms[index].position -= [a, 0, 0] elif clicked_button.description == "Y+": self.atoms[index].position += [0, a, 0] elif clicked_button.description == "Y-": self.atoms[index].position -= [0, a, 0] elif clicked_button.description == "Z+": self.atoms[index].position += [0, 0, a] elif clicked_button.description == "Z-": self.atoms[index].position -= [0, 0, a] self.update_display() def rotate(self, clicked_button: Button): atom_indices = self.get_selected_atom_indices() deg = self.vh.rotate.value temp = self.atoms[atom_indices] if clicked_button.description == "X+": temp.rotate(deg, "x", center="COP") elif clicked_button.description == "X-": temp.rotate(-deg, "x", center="COP") elif clicked_button.description == "Y+": temp.rotate(deg, "y", center="COP") elif clicked_button.description == "Y-": temp.rotate(-deg, "y", center="COP") elif clicked_button.description == "Z+": temp.rotate(deg, "z", center="COP") elif clicked_button.description == "Z-": temp.rotate(-deg, "z", center="COP") rotep = temp.positions for i, atom in enumerate(atom_indices): self.atoms[atom].position = rotep[i] self.update_display() def run_opt(self, clicked_button: Button): """OPT only specified steps and FIX atoms if NOT in text atoms list""" if self.vh.constraint_checkbox.value: # Fix non selected atoms. Only opt selected atoms. print("Opt with selected atoms: fix non selected atoms") atom_indices = self.get_selected_atom_indices() constraint_atom_indices = [ i for i in range(len(self.atoms)) if i not in atom_indices ] self.atoms.set_constraint(FixAtoms(indices=constraint_atom_indices)) opt = BFGS(self.atoms, maxstep=0.04, logfile=None) steps: Optional[int] = self.vh.opt_step.value if steps < 0: steps = None # When steps=-1, opt until converged. opt.run(fmax=0.0001, steps=steps) print(f"Run opt for {steps} steps") self.update_display() def download_image(self, clicked_button: Optional[Button] = None): filename = self.vh.filename_text.value self.v.download_image(filename=filename) def save_image(self, clicked_button: Optional[Button] = None): filename = self.vh.filename_text.value if filename.endswith(".png"): thread = threading.Thread( target=save_image, args=(filename, self.v), daemon=True ) # thread.daemon = True thread.start() elif filename.endswith(".html"): nv.write_html(filename, [self.v]) # type: ignore else: print(f"filename {filename}: extension not supported!") ``` <a id="chap1"></a> ## 1. BulkからSlab作成 ### 1-1 Bulk構造を読み込みから作成まで 今回はMaterials Projectからダウンロードしたcifファイルをinputフォルダに入れて読み込み Input cif file is from A. Jain*, S.P. Ong*, G. Hautier, W. Chen, W.D. Richards, S. Dacek, S. Cholia, D. Gunter, D. Skinner, G. Ceder, K.A. Persson (*=equal contributions) The Materials Project: A materials genome approach to accelerating materials innovation APL Materials, 2013, 1(1), 011002. [doi:10.1063/1.4812323](http://dx.doi.org/10.1063/1.4812323) [[bibtex]](https://materialsproject.org/static/docs/jain_ong2013.349ca3156250.bib) Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) ``` bulk = read("input/Rh_mp-74_conventional_standard.cif") print("原子数 =", len(bulk)) print("initial 格子定数 =", bulk.cell.cellpar()) opt_cell_size(bulk) print ("optimized 格子定数 =", bulk.cell.cellpar()) ``` [sort](https://wiki.fysik.dtu.dk/ase/ase/build/tools.html#ase.build.sort)関数は、元素番号に応じて順序をソートする関数です。 ``` bulk = bulk.repeat([2,2,2]) bulk = sort(bulk) bulk.positions += [0.01,0,0] # 面を切るときに変なところで切れるのを防ぐために少し下駄を履かせます。 v = view(bulk, viewer='ngl') v.view.add_representation("ball+stick") display(v) ``` ### 1-2 Slab構造を作成まで bulk構造から任意のミラー指数でslab構造を作成。<br/> `miller_indices=(x,y,z)`で指定できます。 `makesurface` は中で [surface](https://wiki.fysik.dtu.dk/ase//ase/build/surface.html#create-specific-non-common-surfaces) 関数を使用して表面構造を作成しています。 ``` slab = makesurface(bulk, miller_indices=(1,1,1), layers=2, rep=[1,1,1]) slab = sort(slab) slab.positions += [1,1,0] # 少しだけ位置調整 slab.wrap() # してからWRAP v = view(slab, viewer='ngl') v.view.add_representation("ball+stick") display(v) ``` ### 1-3 作成したslabのz座標を確認 slabの最も高い座標確認(吸着構造を作成するときに必要)<br/> slabの層ごとの座標を確認(何層目までを固定するのか決めるのに必要) ``` # 原子のz_positionを確認。 z_pos = pd.DataFrame({ "symbol": slab.get_chemical_symbols(), "z": slab.get_positions()[:, 2] }) plt.scatter(z_pos.index, z_pos["z"]) plt.grid(True) plt.xlabel("atom_index") plt.ylabel("z_position") plt.show() print("highest position (z) =", z_pos["z"].max()) ``` ### 1-4 表面切り出したslab構造の下層を固定して構造最適化 [FixAtoms](https://wiki.fysik.dtu.dk/ase//ase/constraints.html#ase.constraints.FixAtoms) を用いることで、slab構造の下層の原子のみを固定してOptを実行できます。<br/> ここでは1A以下を固定しており、一番下の層のみが固定されます。 表面の原子位置が緩和されるはずです。 ``` %%time c = FixAtoms(indices=[atom.index for atom in slab if atom.position[2] <= 1]) # 1A以下を固定 slab.set_constraint(c) slab.calc = calculator os.makedirs("output", exist_ok=True) BFGS_opt = BFGS(slab, trajectory="output/slab_opt.traj")#, logfile=None) BFGS_opt.run(fmax=0.005) ``` 実際のOptの経過を見てみると、上3層のみの構造最適化がされている事がわかります。 ``` # v = view(slab, viewer='ngl') v = view(Trajectory("output/slab_opt.traj"), viewer='ngl') v.view.add_representation("ball+stick") display(v) slabE = slab.get_potential_energy() print(f"slab E = {slabE} eV") # 作成したslab構造を保存 os.makedirs("structures/", exist_ok=True) # structures/というフォルダを作成します。 write("structures/Slab_Rh_111.xyz", slab) # 任意でファイル名を変更してください。 ``` <a id="chap2"></a> ## 2. MoleculeをSlab上に配置、始状態(反応前)と終状態(反応後)を作成 ### 2-1 吸着する分子読み込み、構造最適化後のpotential energyを得ましょう。 今回はaseの[molecule module](https://wiki.fysik.dtu.dk/ase/ase/build/build.html)を使います。<br/> cif file, sdf fileなどからの読み込みもbulk構造を読み込みと同じように実施すればできます。 ``` molec = molecule('NO') # molec = read("structures/xxxxxxxxxx.sdf") # sdf fileの読み込み例 molec.calc = calculator BFGS_opt = BFGS(molec, trajectory="output/molec_opt.traj", logfile=None) BFGS_opt.run(fmax=0.005) molecE = molec.get_potential_energy() print(f"molecE = {molecE} eV") v = view(Trajectory("output/molec_opt.traj"), viewer='ngl') v.view.add_representation("ball+stick") display(v) ``` ### 2-2 吸着E計算 吸着状態を作成しましょう。 ここでは、[add_adsorbate](https://wiki.fysik.dtu.dk/ase//ase/build/surface.html#ase.build.add_adsorbate)関数を用いて`slab` 上部に `molec` を配置しています。 ``` mol_on_slab = slab.copy() # slab最表面から分子を配置する高さと、x,y positionを入力してください。 # あとで調整できるので、適当で大丈夫です。 add_adsorbate(mol_on_slab, molec, height=3, position=(8, 4)) c = FixAtoms(indices=[atom.index for atom in mol_on_slab if atom.position[2] <= 1]) mol_on_slab.set_constraint(c) ``` #### SurfaceEditor `SurfaceEditor`というクラスを用いて分子の吸着位置最適化を行います。 <使用方法> 1. `SurfaceEditor(atoms).display()` で編集したい構造を表示しましょう。 2. atoms z>で動かしたい分子のindexを取得しましょう。1-3で確認したslab構造の最も高い座標より上にいるのが分子です。<br/>設定すると下のボックスに選択された分子のindexのみが入ります。 3. move, rotateのXYZ+-で分子のみを移動、角度変更できますので、位置を調整してください。<br/>この際、Ball sizeを調整すると吸着サイトが見やすくなります。 4. "Run mini opt" ボタンで、BFGSによる構造最適化を指定ステップ実施できます。 今回は以下の論文を参考に吸着構造を作成してみます。 ”First-Principles Microkinetic Analysis of NO + CO Reactions on Rh(111) Surface toward Understanding NOx Reduction Pathways” - https://pubs.acs.org/doi/10.1021/acs.jpcc.8b05906 今回の例では、"X-"を3回、"Y+"を1回、"Z-"を4回押すことでHCPサイトの吸着を行うための初期構造を作ることができます。<br/> 吸着のFCCサイト、HCPサイトに関しては以下の図をご覧ください。 <blockquote> <figure> <img src="https://www.researchgate.net/profile/Monica-Pozzo/publication/5521348/figure/fig1/AS:281313635520514@1444081805255/Colour-Possible-adsorption-sites-top-bridge-hollow-hcp-and-hollow-fcc-for-hydrogen.png"/> <figcaption>(Colour) Possible adsorption sites (top, bridge, hollow-hcp and hollow-fcc) for hydrogen (dark red) on the Mg(0001) surface (light blue).<br/> from <a href="https://www.researchgate.net/figure/Colour-Possible-adsorption-sites-top-bridge-hollow-hcp-and-hollow-fcc-for-hydrogen_fig1_5521348">https://www.researchgate.net/figure/Colour-Possible-adsorption-sites-top-bridge-hollow-hcp-and-hollow-fcc-for-hydrogen_fig1_5521348</a> </figcaption> </figure> </blockquote> ``` # SurfaceEditor にはcalculator がSet されている必要があります。 mol_on_slab.calc = calculator se = SurfaceEditor(mol_on_slab) se.display() c = FixAtoms(indices=[atom.index for atom in mol_on_slab if atom.position[2] <= 1]) mol_on_slab.set_constraint(c) BFGS_opt = BFGS(mol_on_slab, logfile=None) BFGS_opt.run(fmax=0.005) mol_on_slabE = mol_on_slab.get_potential_energy() print(f"mol_on_slabE = {mol_on_slabE} eV") os.makedirs("ad_structures/", exist_ok=True) write("ad_structures/mol_on_Rh(111).cif", mol_on_slab) ``` ### 2-3 吸着E Slabと分子それぞれが単体で存在していたときのエネルギーと、結合したときのエネルギー差を見ることで、吸着エネルギーが計算できます。 上記論文値では、1.79eVとなっています。値がずれているのは、論文ではRPBE汎関数が使われていますが、PFPではPBE汎関数が使われているところの違いが影響していそうです。 ``` # Calculate adsorption energy adsorpE = slabE + molecE - mol_on_slabE print(f"Adsorption Energy: {adsorpE} eV") ``` ### 2-4 吸着構造をリスト化 ``` ad_st_path = "ad_structures/*" ad_stru_list = [(filepath, read(filepath)) for filepath in glob.glob(ad_st_path)] pd.DataFrame(ad_stru_list) No = 0 view(ad_stru_list[No][1] , viewer="ngl") ``` ### 2-5 IS構造を作る ここでIS構造・FS構造を自分で作成し、NEBを行うための経路を作ります。<br/> 今回はこちらで作成しているものを用いるので、 [3. NEB計算](#chap3) に飛んで頂いても構いません。 ``` filepath, atoms = ad_stru_list[No] print(filepath) IS = atoms.copy() IS.calc = calculator SurfaceEditor(IS).display() c = FixAtoms(indices=[atom.index for atom in IS if atom.position[2] <= 1]) IS.set_constraint(c) BFGS_opt = BFGS(IS, logfile=None) BFGS_opt.run(fmax=0.05) IS.get_potential_energy() ``` ### 2-6 FS構造を作る ``` FS = IS.copy() FS.calc = calculator SurfaceEditor(FS).display() FS.calc = calculator c = FixAtoms(indices=[atom.index for atom in FS if atom.position[2] <= 1]) FS.set_constraint(c) BFGS_opt = BFGS(FS, logfile=None) BFGS_opt.run(fmax=0.005) FS.get_potential_energy() ``` IS, FS構造を保存 ``` filepath = Path(filepath).stem # filepath = Path(ad_stru_list[No][0]).stem os.makedirs(filepath, exist_ok=True) write(filepath+"/IS.cif", IS) write(filepath+"/FS.cif", FS) ``` <a id="chap3"></a> ## 3. NEB計算 ### 3-1 NEB計算 今回はこちらで作成した、NO(fcc) -> N(fcc) + O(fcc) への反応に対するNEB計算を行ってみます。<br/> `filepath`を変更することで、NO(fcc) -> N(hcp) + O(hcp) の反応に対するNEB計算も試すことができます。 ``` !cp -r "input/NO_dissociation_NO(fcc)_N(fcc)_O(fcc)" . !cp -r "input/NO_dissociation_NO(fcc)_N(hcp)_O(hcp)" . filepath = "NO_dissociation_NO(fcc)_N(fcc)_O(fcc)" # filepath = "NO_dissociation_NO(fcc)_N(hcp)_O(hcp)" ``` 作成したIS, FS構造はこの様になっています。 ``` IS = read(filepath+"/IS.cif") FS = read(filepath+"/FS.cif") v = view([IS, FS], viewer='ngl') #v.view.add_representation("ball+stick") display(v) c = FixAtoms(indices=[atom.index for atom in IS if atom.position[2] <= 1]) IS.calc = calculator IS.set_constraint(c) BFGS_opt = BFGS(IS, logfile=None) BFGS_opt.run(fmax=0.005) print(f"IS {IS.get_potential_energy()} eV") c = FixAtoms(indices=[atom.index for atom in FS if atom.position[2] <= 1]) FS.calc = calculator FS.set_constraint(c) BFGS_opt = BFGS(FS, logfile=None) BFGS_opt.run(fmax=0.005) print(f"FS {FS.get_potential_energy()} eV") beads = 21 b0 = IS.copy() b1 = FS.copy() configs = [b0.copy() for i in range(beads-1)] + [b1.copy()] for config in configs: estimator = Estimator() # NEBでparallel=True, allowed_shared_calculator=Falseにする場合に必要 calculator = ASECalculator(estimator) # NEBでparallel=True, allowed_shared_calculator=Falseにする場合に必要 config.calc = calculator %%time steps=2000 # k:ばねの定数 最終的に0.05とか下げた方が安定する。 # NEBでparallel = True, allowed_shared_calculator=Falseにしたほうが、他のjobの影響を受けにくいので高速に処理が進みます。 neb = NEB(configs, k=0.05, parallel=True, climb=True, allow_shared_calculator=False) neb.interpolate() relax = FIRE(neb, trajectory=None, logfile=filepath+"/neb_log.txt") # fmaxは0.05以下が推奨。小さすぎると収束に時間がかかります。 # 一回目のNEB計算は収束条件を緩め(0.2など)で実行し、無理のない反応経路が描けていたら収束条件を厳しくするほうが安定して計算できます。 # 緩めの収束条件で異常な反応経路となる場合はIS, FS構造を見直してください。 relax.run(fmax=0.1, steps=steps) # additional calculation steps=10000 relax.run(fmax=0.05, steps=steps) write(filepath+"/NEB_images.xyz", configs) ``` <a id="chap4"></a> ## 4. NEB計算結果の確認と遷移状態構造取得 まずはいくつかの方法で可視化してみます。今回はpng --> gifファイルを作成してみます。 ``` configs = read(filepath+"/NEB_images.xyz", index=":") for config in configs: estimator = Estimator() # NEBでparallel = True, allowed_shared_calculator=Falseにする場合に必要 calculator = ASECalculator(estimator) # NEBでparallel = True, allowed_shared_calculator=Falseにする場合に必要 config.calc = calculator os.makedirs(filepath + "/pov_NEB/", exist_ok=True) os.makedirs(filepath + "/png_NEB/", exist_ok=True) for i, atoms in enumerate(configs): m = atoms.copy() write(filepath + f"/pov_NEB/NEB_{i:03}.pov", m, rotation="-60x, 30y, 15z") write(filepath + f"/png_NEB/NEB_{i:03}.png", m, rotation="-60x, 30y, 15z") imgs = [] for i in sorted(glob.glob(filepath + "/png_NEB/*.png"))[:]: img = Image.open(i) img.load() #img = img.resize((250,480)) bg = Image.new("RGB", img.size, (255, 255, 255)) bg.paste(img, mask=img.split()[3]) imgs.append(bg) imgs[0].save(filepath + "/gif_NEB.gif", save_all=True, append_images=imgs[1:], optimize=False, duration=100, loop=0) ImageWidget(filepath + "/gif_NEB.gif") ``` TS構造となったIndexを確認。<br/> Energy, Forceをみてみると、`index=11` で、エネルギーが最大、Forceが0付近の鞍点に達している事がわかります。 ``` energies = [config.get_total_energy() for config in configs] plt.plot(range(len(energies)),energies) plt.xlabel("replica") plt.ylabel("energy [eV]") plt.xticks(np.arange(0, len(energies), 2)) plt.grid(True) plt.show() def calc_max_force(atoms): return ((atoms.get_forces() ** 2).sum(axis=1).max()) ** 0.5 mforces = [calc_max_force(config) for config in configs] plt.plot(range(len(mforces)), mforces) plt.xlabel("replica") plt.ylabel("max force [eV]") plt.xticks(np.arange(0, len(mforces), 2)) plt.grid(True) plt.show() ``` 初期構造 `index=0` と、遷移状態 `index=11`のエネルギー差を見ることで活性化エネルギーが計算できます。 ``` ts_index = 11 actE = energies[ts_index] - energies[0] deltaE = energies[ts_index] - energies[-1] print(f"actE {actE} eV, deltaE {deltaE} eV") v = view(configs, viewer='ngl') #v.view.add_representation("ball+stick") display(v) ``` ### NEBやり直し 実行済みのNEB計算結果から中間イメージのほうが始状態、終状態に適した構造が出た場合に、その構造を抽出して再実行してください。 ``` # IS2 = configs[9].copy() # FS2 = configs[-1].copy() # c = FixAtoms(indices=[atom.index for atom in IS2 if atom.position[2] <= 1]) # IS2.calc = calculator # IS2.set_constraint(c) # BFGS_opt = BFGS(IS2, logfile=None) # BFGS_opt.run(fmax=0.005) # print(IS2.get_potential_energy()) # c = FixAtoms(indices=[atom.index for atom in FS2 if atom.position[2] <= 1]) # FS2.calc = calculator # FS2.set_constraint(c) # BFGS_opt = BFGS(FS2, logfile=None) # BFGS_opt.run(fmax=0.005) # print(FS2.get_potential_energy()) # write(filepath+"/IS2.cif", IS2) # write(filepath+"/FS2.cif", FS2) # v = view([IS2, FS2], viewer='ngl') # #v.view.add_representation("ball+stick") # display(v) # beads = 21 # b0 = IS2.copy() # b1 = FS2.copy() # configs = [b0.copy() for i in range(beads-1)] + [b1.copy()] # for config in configs: # estimator = Estimator() # NEBでparallel=True, allowed_shared_calculator=Falseにする場合に必要 # calculator = ASECalculator(estimator) # NEBでparallel=True, allowed_shared_calculator=Falseにする場合に必要 # config.calc = calculator # %%time # steps=2000 # neb = NEB(configs, k=0.05, parallel=True, climb=True, allow_shared_calculator=False) #k:ばねの定数 最終的に0.05とか下げた方が安定する。 # # NEBでparallel = True, allowed_shared_calculator=Falseにしたほうが、他のjobの影響を受けにくいので高速に処理が進みます。 # neb.interpolate() # relax = FIRE(neb, trajectory=None, logfile=filepath+"/neb_log_2.txt") # relax.run(fmax=0.05, steps=steps) # write(filepath+"/NEB_images2.xyz", configs) # os.makedirs(filepath + "/pov_NEB2/", exist_ok=True) # os.makedirs(filepath + "/png_NEB2/", exist_ok=True) # for h,i in enumerate(configs): # m = i.copy() # write(filepath + '/pov_NEB2/NEB_' + str(h).zfill(3) + '.pov', m, rotation='-60x, 30y, 15z') # write(filepath + '/png_NEB2/NEB_' + str(h).zfill(3) + '.png', m, rotation='-60x, 30y, 15z') # imgs = [] # for i in sorted(glob.glob(filepath + "/png_NEB2/*.png"))[:]: # img = Image.open(i) # img.load() # #img = img.resize((250,480)) # bg = Image.new("RGB", img.size, (255, 255, 255)) # bg.paste(img, mask=img.split()[3]) # imgs.append(bg) # imgs[0].save(filepath + "/gif_NEB_2.gif", save_all=True, append_images=imgs[1:], optimize=False, duration=100, loop=0) # energies = [config.get_total_energy() for config in configs] # plt.plot(range(len(energies)),energies) # plt.xlabel("replica") # plt.ylabel("energy [eV]") # plt.xticks(np.arange(0, beads, 2)) # plt.grid(True) # plt.show() # mforces = [config.get_forces().max() for config in configs] # plt.plot(range(len(mforces)),mforces) # plt.xlabel("replica") # plt.ylabel("max force [eV]") # plt.xticks(np.arange(0, beads, 2)) # plt.grid(True) # plt.show() # energies[13] - energies[0] # v = view(configs, viewer='ngl') # #v.view.add_representation("ball+stick") # display(v) ``` <a id="chap5"></a> ## 5. 遷移状態構造の構造最適化(by Sella) 前章で得られたTS構造は、厳密な鞍点まで収束させる操作が入っていません。 ここでは、[sella](https://github.com/zadorlab/sella) というライブラリを用いて、TS構造を収束させます。 ``` TSNo = 11 TS = configs[TSNo].copy() c = FixAtoms(indices=[atom.index for atom in TS if atom.position[2] <= 1]) TS.set_constraint(c) # 原子のz_positionを確認。 z_pos = pd.DataFrame({ "symbol": TS.get_chemical_symbols(), "z": TS.get_positions()[:, 2] }) plt.scatter(z_pos.index, z_pos["z"]) plt.grid(True) plt.xlabel("atom_index") plt.ylabel("z_position") #plt.ylim(14,22) plt.show() TS.calc = calculator TSopt = Sella(TS) # SellaでTSopt %time TSopt.run(fmax=0.05) potentialenergy = TS.get_potential_energy() print (TS.get_potential_energy(), TS.get_forces().max()) write(filepath + "/TS_opt.cif", TS) # TSopt前後の構造を比較 v = view([configs[TSNo], TS], viewer='ngl') v.view.add_representation("ball+stick") display(v) ``` <a id="chap6"></a> ## 6. 遷移状態の振動解析 ``` # 振動計算で解析する元素はz_pos >= zzとする。 vibatoms = z_pos[z_pos["z"] >= 7.0].index vibatoms # 振動計算 vibpath = filepath + "/TS_vib/vib" os.makedirs(vibpath, exist_ok=True) vib = Vibrations(TS, name=vibpath, indices=vibatoms) # 振動計算する元素はココでvibatomsとして指定する。 vib.run() vib_energies = vib.get_energies() thermo = IdealGasThermo(vib_energies=vib_energies, potentialenergy=potentialenergy, atoms=TS, geometry='linear', #'monatomic', 'linear', or 'nonlinear' symmetrynumber=2, spin=0, natoms=len(vibatoms)) G = thermo.get_gibbs_energy(temperature=298.15, pressure=101325.) vib.summary() vib.summary(log=filepath+"/vib_summary.txt") # 各振動モードの表示用のtrajファイルを出力します。 vib.write_mode(n=0, kT=300*kB, nimages=30) vib.clean() n = 0 # summary tableを見ながら表示したい振動モードの番号を入力してください。 vib_traj = Trajectory(vibpath + f".{n}.traj") v = view(vib_traj, viewer='ngl') v.view.add_representation("ball+stick") display(v) write(filepath + "/vib_traj.xyz", vib_traj) vib_traj = read(filepath + "/vib_traj.xyz", index=":") os.makedirs(filepath + "/pov_VIB/", exist_ok=True) os.makedirs(filepath + "/png_VIB/", exist_ok=True) for h,i in enumerate(vib_traj): m = i.copy() write(filepath + f"/pov_VIB/VIB_{h:03}.pov", m, rotation='-60x, 30y, 15z') write(filepath + f"/png_VIB/VIB_{h:03}.png", m, rotation='-60x, 30y, 15z') # 虚振動になっているか確認する。真ん中(と0)がTS。 vib_energies = [] for i in vib_traj: i.calc = calculator vib_energies.append(i.get_potential_energy()) plt.plot(range(len(vib_energies)), vib_energies) plt.grid(True) plt.show() ``` <a id="chap7"></a> ## 7. 遷移状態からの追加解析(擬似IRC計算)試作中 ``` from ase.optimize.basin import BasinHopping from ase.optimize.minimahopping import MinimaHopping TS = read("mol_on_Rh(111)/TS_opt.cif") TS.calc = calculator # 虚振動モードの真ん中の両隣の構造を持ってきてBFGSで最適化するだけ。 c = FixAtoms(indices=[atom.index for atom in vib_traj[15] if atom.position[2] <= 1]) IRC_IS = vib_traj[14].copy() IRC_IS.calc = calculator IRC_IS.set_constraint(c) # opt = BFGS(IRC_IS, logfile=None, maxstep=1) # opt.run(fmax=0.5) opt = BasinHopping(IRC_IS, temperature=300 * kB, dr=0.5, optimizer=LBFGS, fmax=0.005,) print ("IS_done") IRC_FS = vib_traj[16].copy() IRC_FS.calc = calculator IRC_FS.set_constraint(c) # opt = BFGS(IRC_FS, logfile=None, maxstep=1) # opt.run(fmax=0.5) opt = BasinHopping(IRC_FS, temperature=300 * kB, dr=0.5, optimizer=LBFGS, fmax=0.005,) print ("FS_done") # 虚振動モードの真ん中の両隣の構造を持ってきてBFGSで最適化するだけ。 c = FixAtoms(indices=[atom.index for atom in TS if atom.position[2] <= 1]) IRC_IS = vib_traj[14].copy() IRC_IS.calc = calculator IRC_IS.set_constraint(c) opt = BFGS(IRC_IS, logfile=None, maxstep=0.5) opt.run(fmax=0.005, steps=500) print ("IS_BFGS_done") opt = MinimaHopping(IRC_IS, T0=0, fmax=0.005,) opt(totalsteps=10) print ("IS_MH_done") IRC_FS = vib_traj[16].copy() IRC_FS.calc = calculator IRC_FS.set_constraint(c) opt = BFGS(IRC_FS, logfile=None, maxstep=0.5) opt.run(fmax=0.005, steps=500) print ("FS_BFGS_done") #opt = MinimaHopping(IRC_FS, T0=0, fmax=0.005,) #opt(totalsteps=10) print ("FS_MH_done") v = view([IRC_IS, TS, IRC_FS], viewer='ngl') v.view.add_representation("ball+stick") display(v) ``` ``` # NEBで計算したIS, TS, FSのenergyとTSopt+IRCの結果を比較する。 plt.plot([0,1,2], [configs[0].get_potential_energy(), configs[TSNo].get_potential_energy(), configs[-1].get_potential_energy()], label="NEB") plt.plot([0,1,2], [IRC_IS.get_potential_energy(), TS.get_potential_energy(), IRC_FS.get_potential_energy()], label="TSopt+IRC") plt.legend() plt.grid(True) plt.show() print(TS.get_potential_energy() - IRC_IS.get_potential_energy()) print(TS.get_potential_energy() - IRC_FS.get_potential_energy()) write(filepath + "/IS_IRC.xyz",IRC_IS) write(filepath + "/FS_IRC.xyz",IRC_FS) ```
github_jupyter
``` # ok, lets start by loading our usual stuffs %matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np # Get daily summary data from: https://www.ncdc.noaa.gov/cdo-web/search # and you can read more about the inputs here: https://www1.ncdc.noaa.gov/pub/data/cdo/documentation/GHCND_documentation.pdf w = pd.read_csv("/Users/jillnaiman1/Downloads/2018_ChampaignWeather.csv") w # lets first sort our weather data by date w.sort_values(by="DATE") # now, lets change our date values to datetime # note we did this using the "datetime" python package # a few lectures ago w["DATE"] = pd.to_datetime(w["DATE"]) # we've also got data from a few different stations # so lets pick one! mask = w["NAME"] == 'CHAMPAIGN 3 S, IL US' # now lets make a quick plot! plt.plot(w["DATE"][mask], w["TMIN"][mask], label='Min temp') plt.plot(w["DATE"][mask], w["TMAX"][mask], label="Max temp") plt.xlabel('Date') plt.ylabel('Temp in F') plt.legend() # lets label some things # and again, lets make our plot a little bigger plt.rcParams["figure.dpi"] = 100 # 100 is better for lecture ``` # Activity #1: Histograms * Here we will play with different sorts of simple rebinning methods * We'll think about when we want to use sums vs. averaging ``` # lets also plot the mean and take a look mean_temp = 0.5*(w["TMIN"]+w["TMAX"])[mask] #print(len(mean_temp)) # lets also import ipywidgets import ipywidgets # now, if we recall last time, we have some methods to take out # some of the "noisiness" in data # and! we can do this interactively! @ipywidgets.interact(window = (1, 40, 1)) def make_plot(window): mean_temp_avg = mean_temp.rolling(window=window).mean() plt.plot(mean_temp, marker = '.', linewidth = 0.5, alpha = 0.5) plt.plot(mean_temp_avg, marker = '.', linewidth = 1.5) plt.xlabel('Date') plt.ylabel('Mean Daily Temp in F') # when the window size is ~20, we can really see the seasonal averages # as we discussed last lecture, what we are doing here is a # "rolling average" # this is now choosing a rolling average over which to do # an averaging - it takes nearby bins and averages # this is like (sum(values)/N) # ok cool. So, this is our first taste of how we might want to # modify data to show different things - for example if we # average over more bins, then we see more seasonal variencies # lets compare this dataset to a dataset we might want to # visualize a little differently w.keys() # lets grab the amount of rain each day, I *think* in inches precp = w['PRCP'][mask] # we can now do a side by side figure using ipywidgets # lets do some funny things to rejigger our plots # to use panda's plotting routine import matplotlib.dates as mdates # if we've not done this before, only an issue # if we want to re-run this cell a few times # for any reason set_ind = False for k in w.keys(): if k.find('DATE') != -1: set_ind = True print(k,set_ind) if set_ind: w.set_index('DATE',inplace=True) # because we have re-indexed we have to re-define our arrays mask = w["NAME"] == 'CHAMPAIGN 3 S, IL US' mean_temp = 0.5*(w["TMIN"]+w["TMAX"])[mask] precp = w['PRCP'][mask] @ipywidgets.interact(window = (1, 40, 1)) def make_plot(window): fig, ax = plt.subplots(1,2,figsize=(10,4)) mean_temp_avg = mean_temp.rolling(window=window).mean() mean_temp.plot(ax=ax[0]) mean_temp_avg.plot(ax=ax[0]) precp_avg = precp.rolling(window=window).mean() precp.plot(ax=ax[1], marker='.',linewidth=0.5, alpha=0.5) precp_avg.plot(ax=ax[1], marker='.', linewidth=1.5) # note: the below also works too #ax[1].plot(precp, marker = '.', linewidth = 0.5, alpha = 0.5) #ax[1].plot(precp_avg, marker = '.', linewidth = 1.5) # format our axis ax[1].set_xlabel('Date') ax[1].set_ylabel('Daily rainfall in inches') ax[0].set_xlabel('Date') ax[0].set_ylabel('Mean Daily Temp in F') for i in range(2): ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%m')) #fig.canvas.draw() # probably don't need this # now we note something interesting: # averaging brings out the seasonal # differences in the temperature data # however, no such stark trends are present # when we averaging the rain data # this is because we know that seasons # have changes in daily temperature # measurements, but they have changes # in *TOTAL* rainfall. # While you may get more rain on days # throughout the year, its the total, # averaged over SEVERAL days that will # tell you more. # With this in mind, lets re-do our viz @ipywidgets.interact(window = (1, 100, 1)) def make_plot(window): fig, ax = plt.subplots(1,2,figsize=(10,4)) mean_temp_avg = mean_temp.rolling(window=window).mean() mean_temp.plot(ax=ax[0]) mean_temp_avg.plot(ax=ax[0]) precp_avg = precp.rolling(window=window).sum() # SUM IS THE KEY!! precp.plot(ax=ax[1], marker='.',linewidth=0.5, alpha=0.5) precp_avg.plot(ax=ax[1], marker='.', linewidth=1.5) # format our axis ax[1].set_xlabel('Date') ax[1].set_ylabel('Daily rainfall in inches') ax[0].set_xlabel('Date') ax[0].set_ylabel('Mean Daily Temp in F') for i in range(2): ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%m')) # now, if we really crank up the binning, we can see that the # overall rainfail shape follows that of the # smoothed temperature shape, eventhough the first plot is # of a moving average & the other a moving sum # now notice that everything is shifted to later dates, why is this? # this is because of the formatting of our bins precp.rolling? # we can make a slight change to how the binning # is done and get a very different effect @ipywidgets.interact(window = (1, 100, 1)) def make_plot(window): fig, ax = plt.subplots(1,2,figsize=(10,4)) mean_temp_avg = mean_temp.rolling(window=window,center=True).mean() mean_temp.plot(ax=ax[0]) mean_temp_avg.plot(ax=ax[0]) precp_avg = precp.rolling(window=window,center=True).sum() precp.plot(ax=ax[1], marker='.',linewidth=0.5, alpha=0.5) precp_avg.plot(ax=ax[1], marker='.', linewidth=1.5) # format our axis ax[1].set_xlabel('Date') ax[1].set_ylabel('Daily rainfall in inches') ax[0].set_xlabel('Date') ax[0].set_ylabel('Mean Daily Temp in F') for i in range(2): ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%m')) # Now, another thing to note about our sum for # rainfall is that its "rolling" - that is we # are somewhat double summing the amount of # rainfall in each bin - the sum in bin "i" # includes data from bin "i-1" and bin "i+1" # think last time I called this binning and # not smoothing - but I think the correct # view is that it is somewhere between the # two. To think about the difference, lets # try some straight forward binning by # making a histogram. # we can instead make a *HISTOGRAM* in which we # rebin our data more coursely @ipywidgets.interact(window = (1, 100, 1), day_bins=(1,100,5)) def make_plot(window,day_bins): fig, ax = plt.subplots(1,2,figsize=(10,4)) #ax[1].xaxis_date() # I don't think we need these #ax[0].xaxis_date() mean_temp_avg = mean_temp.rolling(window=window,center=True).mean() mean_temp.plot(ax=ax[0]) mean_temp_avg.plot(ax=ax[0]) precp.plot(ax=ax[1], marker='.',linewidth=0.5, alpha=0.5) precp_resampled = precp.resample(str(day_bins)+'D').sum() precp_resampled.plot(ax=ax[1], marker='.') # label our axis ax[1].set_xlabel('Date') ax[1].set_ylabel('Daily rainfall in inches') ax[0].set_xlabel('Date') ax[0].set_ylabel('Mean Daily Temp in F') ax[1].set_xlim(ax[0].get_xlim()) # lets leave this out and see the "natural" pandas formatting #for i in range(2): ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%m')) # here now in the left plot each point is representing all # rainfall within the specified time range # The lines are the equivalent to overplotting the # lines ontop of the histogram we made by hand in the # lecture slides earlier ``` ## Take aways: * so far we've been doing fairly simple averages - the orange plot on the right of our last plot is of total rainfall is an example of a *HISTOGRAM* that we talked about in the lecture * the orange plot on the left is a rolling average, which is a variation of a histogram *AND* each value in it is divided by the number of data points used to make the data point. Note that this makes a lot more sense for this dataset since the "total temperature" across several days doesn't make a whole lot of sense to talk about. * the *CENTERING* we talked about in lecture applies here too - how we decided where the bins for each window started shifted our plot # Activity #2: Smoothing * we have thus far performed simple transformations to our datasets - some histogramming, something between binning and smoothing - however we note that in our final plots, while overall shapes of seasons are present, much detail is lost * Can we preserve both? The short answer is yes, but not without sacrificing some loss of precise statistical information. We will do this with smoothing. ``` # we can check out the end of the rolling window docs to # see our window options **post in chat too** windows_avail = [None,'boxcar','triang','blackman','hamming', 'bartlett','parzen', 'bohman', 'blackmanharris','nuttall','barthann'] # **start with bartlett** @ipywidgets.interact(window = (1, 100, 1), window_type=windows_avail) def make_plot(window, window_type): fig, ax = plt.subplots(1,2,figsize=(10,4)) mean_temp_avg = mean_temp.rolling(window=window,center=True, win_type=window_type).mean() mean_temp.plot(ax=ax[0], marker='.') mean_temp_avg.plot(ax=ax[0], marker='.') precp_avg = precp.rolling(window=window,center=True, win_type=window_type).sum() precp.plot(ax=ax[1], marker='.',linewidth=0.5, alpha=0.5) precp_avg.plot(ax=ax[1], marker='.', linewidth=1.5) # format our axis ax[1].set_xlabel('Date') ax[1].set_ylabel('Daily rainfall in inches') ax[0].set_xlabel('Date') ax[0].set_ylabel('Mean Daily Temp in F') for i in range(2): ax[i].xaxis.set_major_formatter(mdates.DateFormatter('%m')) # so, we can see in the above that different # windows tend to smooth out or # excentuate different features # what is this all doing? # (1) lets make a toy example of a bartlett window npoints = 10 x = np.arange(0,npoints) y = np.repeat(1,npoints) plt.plot(x,y,'o',label='Origional Data') # (2) ok, nothing exciting, but lets apply # apply a bartlet window to our data # and see what happens plt.plot(x,y*np.bartlett(npoints),'o', label='Bartlett') # so we see that our points have been weighted toward the # center # (3) we can try one more example plt.plot(x,y*np.hamming(npoints),'o', label='Hamming') # so we can see this is a slightly poofier window # in the center part plt.legend() ``` # The big ideas: ### So, why would we want to do this? * When we apply a window like this to data in one of our bins and then take our sums or averages, we are essentially saying that in a particular window, we think the data in the center of the window is more important than the data at the sides of the window. * This is an example of a *WEIGHTED AVERAGE*. * This can make sense when we want a balance between making our data look less noisy, but still feature the data at each y-position more heavily than its neighbors when we plot at that x-position ### What do we give up? * This smoothed representation is, in a sense, "lossy" - i.e. we can not easily backtrack out the exact value at each point because it has been convolved with a window function. * To get back to our original data we would have to *deconvolve* our data with our smoothing function * It would be less accurate to perform any statistical analysis with smoothed data, but it can make the plot more visually appealing. A nice resource: https://space.mit.edu/cxc/isis/contrib/Smooth_vs_rebin/Smooth_vs_rebin.html # Activity The Third: Binning 2D Datasets ``` # So, we can apply these ideas to 2D datasets as well # lets use a different dataset: ufos = pd.read_csv("/Users/jillnaiman1/Downloads/ufo-scrubbed-geocoded-time-standardized-00.csv", names = ["date", "city", "state", "country", "shape", "duration_seconds", "duration", "comment", "report_date", "latitude", "longitude"], parse_dates = ["date", "report_date"]) # you might get a memory warning thing, its just not deprecated correctly # try not to panic :D ufos # so, lets start by plotting ufo sitings by lat and long # nothing fancy plt.plot(ufos['longitude'],ufos['latitude'],'.') # hey look neat! A little map of the earth! # so, we can do things like map # different values to color # lets say we want to color each point # by the duration of the event # lets first start by importing a color map import matplotlib.cm as cm # lets list the available ones plt.colormaps() # so, first lets grab a color map we like - choose your favorite cmap = cm.RdPu # now, lets map duration to color plt.scatter(ufos['longitude'],ufos['latitude'],c=ufos['duration_seconds']) # alright, what is going on here? We are supposed to have # multiple colors plotted! # we can see what is going on by plotting only a few points plt.scatter(ufos['longitude'][0:10],ufos['latitude'][0:10],c=ufos['duration_seconds'][0:10]) # we see here that while yes, points are different colors, there is a lot of small # times (purple) and these are being plotted over all the rest # there are a few ways around this, one we can do our plot as a log plt.scatter(ufos['longitude'],ufos['latitude'],c=np.log10(ufos['duration_seconds'])) # its still not that much detail though # so, we can use our histogramming techniques # to rebin this data in the 2d space! plt.hexbin(ufos["longitude"], ufos["latitude"], ufos["duration_seconds"], gridsize=32, bins='log') plt.colorbar() # so here we are now plotting the locations of UFO sitings in # hexbins, AND we are showing how long, in log(seconds) each # bin's ufo sitings typically last (as a sum over all values in each bin) ``` # Activitity the Last: Smoothing 2D data => Smoothing Images ``` # lets begin by uploading an image to play around with import PIL.Image as Image im = Image.open("/Users/jillnaiman1/Downloads/stitch_reworked.png", "r") # recall what this image looked like: fig,ax = plt.subplots(figsize=(5,5)) ax.imshow(im) #data = np.array(im) # so, lets say we think the little import PIL.ImageFilter as ImageFilter myFilter = ImageFilter.GaussianBlur(radius=1) smoothed_image = im.filter(myFilter) fig,ax = plt.subplots(figsize=(5,5)) ax.imshow(smoothed_image) # we can also do this interactively to see how # different sized gaussian filters look # (note: a gaussian filter looks similar to a Hamming # window that we played with before) @ipywidgets.interact(radius=(1,10,1)) def make_plot(radius): myFilter = ImageFilter.GaussianBlur(radius=radius) smoothed_image = im.filter(myFilter) fig,ax = plt.subplots(figsize=(5,5)) ax.imshow(smoothed_image) # so, again, if we wanted to show off our digitized # drawing, certainly use this to "smooth" out the image # however, note that if the radius gets large in # pixels, we loose a lot of information about our # drawing # also note, that when we apply *ANY* smoothing # we are changing the color profile # our originonal image was, if we recall, had a limited # number of colors colors: print(np.unique(im)) # print out unique pixels myFilter = ImageFilter.GaussianBlur(radius=1) smoothed_image = im.filter(myFilter) # this is not the case for the smoothed image data = np.array(smoothed_image) print(np.unique(data)) # here, we have *ADDED* data values that are # *not* in the original dataset # This is the downside to smoothing # just for fun (and to see the comparitive effects of smoothing): import PIL.Image as Image import PIL.ImageFilter as ImageFilter import matplotlib.pyplot as plt im = Image.open("/Users/jillnaiman1/Downloads/littleCorgiInHat.png", "r") import ipywidgets @ipywidgets.interact(radius=(1,100,5)) def make_plot(radius): myFilter = ImageFilter.GaussianBlur(radius=radius) smoothed_image = im.filter(myFilter) # plot originonal image fig,ax = plt.subplots(1,2,figsize=(10,5)) ax[0].imshow(im) ax[1].imshow(smoothed_image) # note how pixelated the last image becomes # the upshot is that when we give up detail we # can then remap our data onto a larger grid # if we set radius == 100, we can almost # represent our little corgi with a single # pixel at 1 color # Something to consider going forward ```
github_jupyter
# Logistic Regression (scikit-learn) with HDFS/Spark Data Versioning This example is based on our [basic census income classification example](census-end-to-end.ipynb), using local setups of ModelDB and its client, and [HDFS/Spark data versioning](https://verta.readthedocs.io/en/master/_autogen/verta.dataset.HDFSPath.html). ``` !pip install /path/to/verta-0.15.10-py2.py3-none-any.whl HOST = "localhost:8080" PROJECT_NAME = "Census Income Classification - HDFS Data" EXPERIMENT_NAME = "Logistic Regression" ``` ## Imports ``` from __future__ import print_function import warnings from sklearn.exceptions import ConvergenceWarning warnings.filterwarnings("ignore", category=ConvergenceWarning) warnings.filterwarnings("ignore", category=FutureWarning) import itertools import os import numpy as np import pandas as pd import sklearn from sklearn import model_selection from sklearn import linear_model ``` --- # Log Workflow This section demonstrates logging model metadata and training artifacts to ModelDB. ## Instantiate Client ``` from verta import Client from verta.utils import ModelAPI client = Client(HOST) proj = client.set_project(PROJECT_NAME) expt = client.set_experiment(EXPERIMENT_NAME) ``` <h2>Prepare Data</h2> ``` from pyspark import SparkContext sc = SparkContext("local") from verta.dataset import HDFSPath hdfs = "hdfs://HOST:PORT" dataset = client.set_dataset(name="Census Income S3") blob = HDFSPath.with_spark(sc, "{}/data/census/*".format(hdfs)) version = dataset.create_version(blob) version csv = sc.textFile("{}/data/census/census-train.csv".format(hdfs)).collect() from verta.external.six import StringIO df_train = pd.read_csv(StringIO('\n'.join(csv))) X_train = df_train.iloc[:,:-1] y_train = df_train.iloc[:, -1] df_train.head() ``` ## Prepare Hyperparameters ``` hyperparam_candidates = { 'C': [1e-6, 1e-4], 'solver': ['lbfgs'], 'max_iter': [15, 28], } hyperparam_sets = [dict(zip(hyperparam_candidates.keys(), values)) for values in itertools.product(*hyperparam_candidates.values())] ``` ## Train Models ``` def run_experiment(hyperparams): # create object to track experiment run run = client.set_experiment_run() # create validation split (X_val_train, X_val_test, y_val_train, y_val_test) = model_selection.train_test_split(X_train, y_train, test_size=0.2, shuffle=True) # log hyperparameters run.log_hyperparameters(hyperparams) print(hyperparams, end=' ') # create and train model model = linear_model.LogisticRegression(**hyperparams) model.fit(X_train, y_train) # calculate and log validation accuracy val_acc = model.score(X_val_test, y_val_test) run.log_metric("val_acc", val_acc) print("Validation accuracy: {:.4f}".format(val_acc)) # save and log model run.log_model(model) # log dataset snapshot as version run.log_dataset_version("train", version) for hyperparams in hyperparam_sets: run_experiment(hyperparams) ``` --- # Revisit Workflow This section demonstrates querying and retrieving runs via the Client. ## Retrieve Best Run ``` best_run = expt.expt_runs.sort("metrics.val_acc", descending=True)[0] print("Validation Accuracy: {:.4f}".format(best_run.get_metric("val_acc"))) best_hyperparams = best_run.get_hyperparameters() print("Hyperparameters: {}".format(best_hyperparams)) ``` ## Train on Full Dataset ``` model = linear_model.LogisticRegression(multi_class='auto', **best_hyperparams) model.fit(X_train, y_train) ``` ## Calculate Accuracy on Full Training Set ``` train_acc = model.score(X_train, y_train) print("Training accuracy: {:.4f}".format(train_acc)) ``` ---
github_jupyter
# Modeling and Simulation in Python Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import functions from the modsim.py module from modsim import * ``` ### Low pass filter ``` with units_off(): for i, name in enumerate(dir(UNITS)): unit = getattr(UNITS, name) try: res = 1*unit - 1 if res == 0: print(name, 1*unit - 1) except TypeError: pass if i > 10000: break with units_off(): print(2 * UNITS.farad - 1) with units_off(): print(2 * UNITS.volt - 1) with units_off(): print(2 * UNITS.newton - 1) mN = UNITS.gram * UNITS.meter / UNITS.second**2 with units_off(): print(2 * mN - 1) ``` Now I'll create a `Params` object to contain the quantities we need. Using a Params object is convenient for grouping the system parameters in a way that's easy to read (and double-check). ``` params = Params( R1 = 1e6, # ohm C1 = 1e-9, # farad A = 5, # volt f = 1000, # Hz ) ``` Now we can pass the `Params` object `make_system` which computes some additional parameters and defines `init`. `make_system` uses the given radius to compute `area` and the given `v_term` to compute the drag coefficient `C_d`. ``` def make_system(params): """Makes a System object for the given conditions. params: Params object returns: System object """ unpack(params) init = State(V_out = 0) omega = 2 * np.pi * f tau = R1 * C1 cutoff = 1 / R1 / C1 t_end = 3 / f return System(params, init=init, t_end=t_end, omega=omega, cutoff=cutoff) ``` Let's make a `System` ``` system = make_system(params) ``` Here's the slope function, ``` def slope_func(state, t, system): """Compute derivatives of the state. state: position, velocity t: time system: System object returns: derivatives of y and v """ V_out, = state unpack(system) V_in = A * np.cos(omega * t) V_R1 = V_in - V_out I_R1 = V_R1 / R1 I_C1 = I_R1 dV_out = I_C1 / C1 return dV_out ``` As always, let's test the slope function with the initial conditions. ``` slope_func(system.init, 0, system) ``` And then run the simulation. ``` ts = linspace(0, system.t_end, 301) results, details = run_ode_solver(system, slope_func, t_eval=ts) details ``` Here are the results. ``` # results ``` Here's the plot of position as a function of time. ``` def plot_results(results): xs = results.V_out.index ys = results.V_out.values t_end = get_last_label(results) if t_end < 10: xs *= 1000 xlabel = 'Time (ms)' else: xlabel = 'Time (s)' plot(xs, ys) decorate(xlabel=xlabel, ylabel='$V_{out}$ (volt)', legend=False) plot_results(results) ``` And velocity as a function of time: ``` fs = [1, 10, 100, 1000, 10000, 100000] for i, f in enumerate(fs): system = make_system(Params(params, f=f)) ts = linspace(0, system.t_end, 301) results, details = run_ode_solver(system, slope_func, t_eval=ts) subplot(3, 2, i+1) plot_results(results) ```
github_jupyter
``` import numpy as np import pandas as pd from scipy import sparse import matplotlib.pyplot as plt import gc gc.enable() from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB, BernoulliNB from sklearn.pipeline import Pipeline from sklearn.metrics import balanced_accuracy_score as bas from sklearn.ensemble import BaggingClassifier from sklearn.linear_model import SGDClassifier, LogisticRegression from sklearn.neighbors import NearestCentroid from sklearn.preprocessing import StandardScaler, FunctionTransformer, MinMaxScaler, MaxAbsScaler from sklearn.ensemble import RandomForestClassifier from nltk.stem import SnowballStemmer ``` <hr> ``` # data = pd.read_csv('../data-simplified-1-reduced-wordbal-800.csv') data = pd.read_csv('../data-reduced-800-v2-shuffled.csv', index_col = 0) test = pd.read_csv('../test.csv') catcode = pd.read_csv('../data-simplified-1-catcode.csv', header = None, names = ['category'])['category'] catcode.to_dict() data.head() ``` <hr> ``` def normalize(curr): # remove accent curr = curr.str.normalize('NFKD').str.encode('ascii', errors='ignore').str.decode('utf-8') # to lower case curr = curr.str.lower() # remove not alphanumerics or . , curr = curr.str.replace('[^a-zA-Z0-9.,]', ' ') # let , and . be the same char curr = curr.str.replace('[.]', ',') # remove . , not between numbers curr = curr.str.replace('(?<=[0-9])[,]+(?=[0-9])', '.') curr = curr.str.replace('[,]', ' ') # set all digits to 0 curr = curr.str.replace('[0-9]', '0') # separate ' <digits><letters ' like in 22g or 12ms # curr = curr.str.replace('(^| )([0-9]+)([a-zA-Z]+)($| )', r'\1\2 \3\4') # remove some Pt plurals curr = curr.str.replace('([a-zA-Z]+[aeiou])(s)', r'\1') # Other ideas: return curr sp = int(len(data) * 0.8) # Split Point full = pd.concat([data[['title']], test[['title']]]) X_full = full.title %%time X_full = normalize(X_full) %%time wordfreq = X_full.str.split(expand=True).stack().value_counts().to_dict() %%time uniquewords = {w for w, f in wordfreq.items() if f == 1} xjoin = lambda s : ' '.join([w if w not in uniquewords else 'XXUXX'for w in s ]) %%time X_full = X_full.str.split().apply(xjoin) X_full = 'XXSXX ' + X_full # + ' XXSXX' %%time count_vect = CountVectorizer(strip_accents='ascii', binary = True, min_df= 2, max_df = .95, # analyzer = 'char', ngram_range=(1,2), # stop_words=['frete', 'Frete'], ) X_train_counts = count_vect.fit_transform(X_full) print(X_train_counts.shape, X_train_counts.count_nonzero()) def sbc(x): # sparse binary correlation; x : sparse # can't correlate zero columns cx = sparse.triu(x.T*x, k = 1, format='coo') # print(cx.todense()) card = np.array(x.sum(axis = 0)).flatten() # print(card) cx.data = cx.data / (card[cx.row] + card[cx.col] - cx.data) # print(cx.todense()) return np.array((cx == 1).sum(axis = 0) > 0).flatten() %%time rem = sbc(X_train_counts) print(rem.mean()) X_train_counts = X_train_counts[:, ~rem] print(X_train_counts.shape, X_train_counts.count_nonzero()) %%time tfidf_transformer = TfidfTransformer(norm='l2', use_idf=False, smooth_idf=True, sublinear_tf=False) X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) X_go = X_train_tfidf print(X_train_tfidf.shape) sp2 = len(data) X_train, y_train = X_go[:sp], data.category.values[:sp] X_test, y_test = X_go[sp:sp2], data.category.values[sp:sp2] X_train.shape, X_test.shape class_weights = (1 / pd.Series(y_train).value_counts()).to_dict() # switching 1 to len(y) seems to make diff sample_weight = np.vectorize(class_weights.get)(y_train) # * rel_train rel = data.label_quality.values[sp:] # del X_full # del X_train_counts # # del clf # gc.collect() %%time n = sp // 1 clf_mnb = MultinomialNB(alpha = 3e-5, fit_prior=False).fit(X_train[:n], y_train[:n], sample_weight=sample_weight[:n], ) clf = clf_mnb %%time prediction_val = clf.predict(X_test) print('Val:', bas(y_test, prediction_val)) rel = data.label_quality.values[sp:] print('Rel:', bas(y_test[rel == 0], prediction_val[rel == 0])) %%time val_proba = clf.predict_proba(X_test) val_proba = pd.DataFrame(val_proba) %time val_proba.to_csv('../ensemb2/val_mnb_word-v1.csv', index = False, header = False) # del X_full # del X_train_counts # del clf # gc.collect() clf_mnb = MultinomialNB(alpha = 3e-5, fit_prior=False) clf = clf_mnb gc.collect() %%time y_data = data.category X_data = X_go[:sp2] class_weights_data = (1 / pd.Series(y_data).value_counts()).to_dict() sample_weight_data = np.vectorize(class_weights_data.get)(y_data) # rel_data = 1 + (1 - data.label_quality.values) * (relfactor - 1) clf.fit(X_data, y_data, sample_weight=sample_weight_data ) # warm start ? test_proba = clf.predict_proba(X_go[sp2:]) test_proba = pd.DataFrame(test_proba) %time test_proba.to_csv('../ensemb2/test_mnb_word-v1.csv', index = False, header = False) ```
github_jupyter
<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>Matplotlib Basics</h1> <h3>Unidata Python Workshop</h3> <div style="clear:both"></div> </div> <hr style="height:2px;"> <div style="float:right; width:250 px"><img src="https://matplotlib.org/_static/logo2.png" alt="NumPy Logo" style="height: 150px;"></div> ## Overview: * **Teaching:** 30 minutes * **Exercises:** 30 minutes ### Questions 1. How are line plots created using Matplotlib? 1. What methods exist to customize the look of these plots? ### Objectives 1. Create a basic line plot. 1. Add labels and grid lines to the plot. 1. Plot multiple series of data. 1. Plot imshow, contour, and filled contour plots. ## Plotting with Matplotlib Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. The first step is to set up our notebook environment so that matplotlib plots appear inline as images: ``` %matplotlib inline ``` Next we import the matplotlib library's `pyplot` interface; this interface is the simplest way to create new Matplotlib figures. To shorten this long name, we import it as `plt` to keep things short but clear. ``` import matplotlib.pyplot as plt import numpy as np ``` Now we generate some data to use while experimenting with plotting: ``` times = np.array([ 93., 96., 99., 102., 105., 108., 111., 114., 117., 120., 123., 126., 129., 132., 135., 138., 141., 144., 147., 150., 153., 156., 159., 162.]) temps = np.array([310.7, 308.0, 296.4, 289.5, 288.5, 287.1, 301.1, 308.3, 311.5, 305.1, 295.6, 292.4, 290.4, 289.1, 299.4, 307.9, 316.6, 293.9, 291.2, 289.8, 287.1, 285.8, 303.3, 310.]) ``` Now we come to two quick lines to create a plot. Matplotlib has two core objects: the `Figure` and the `Axes`. The `Axes` is an individual plot with an x-axis, a y-axis, labels, etc; it has all of the various plotting methods we use. A `Figure` holds one or more `Axes` on which we draw; think of the `Figure` as the level at which things are saved to files (e.g. PNG, SVG) ![anatomy of a figure](anatomy-of-a-figure.png) Below the first line asks for a `Figure` 10 inches by 6 inches. We then ask for an `Axes` or subplot on the `Figure`. After that, we call `plot`, with `times` as the data along the x-axis (independant values) and `temps` as the data along the y-axis (the dependant values). ``` # Create a figure fig = plt.figure(figsize=(10, 6)) # Ask, out of a 1x1 grid, the first axes. ax = fig.add_subplot(1, 1, 1) # Plot times as x-variable and temperatures as y-variable ax.plot(times, temps) ``` From there, we can do things like ask the axis to add labels for x and y: ``` # Add some labels to the plot ax.set_xlabel('Time') ax.set_ylabel('Temperature') # Prompt the notebook to re-display the figure after we modify it fig ``` We can also add a title to the plot: ``` ax.set_title('GFS Temperature Forecast', fontdict={'size':16}) fig ``` Of course, we can do so much more... ``` # Set up more temperature data temps_1000 = np.array([316.0, 316.3, 308.9, 304.0, 302.0, 300.8, 306.2, 309.8, 313.5, 313.3, 308.3, 304.9, 301.0, 299.2, 302.6, 309.0, 311.8, 304.7, 304.6, 301.8, 300.6, 299.9, 306.3, 311.3]) ``` Here we call `plot` more than once to plot multiple series of temperature on the same plot; when plotting we pass `label` to `plot` to facilitate automatic creation. This is added with the `legend` call. We also add gridlines to the plot using the `grid()` call. ``` fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) # Plot two series of data # The label argument is used when generating a legend. ax.plot(times, temps, label='Temperature (surface)') ax.plot(times, temps_1000, label='Temperature (1000 mb)') # Add labels and title ax.set_xlabel('Time') ax.set_ylabel('Temperature') ax.set_title('Temperature Forecast') # Add gridlines ax.grid(True) # Add a legend to the upper left corner of the plot ax.legend(loc='upper left') ``` We're not restricted to the default look of the plots, but rather we can override style attributes, such as `linestyle` and `color`. `color` can accept a wide array of options for color, such as `red` or `blue` or HTML color codes. Here we use some different shades of red taken from the Tableau color set in matplotlib, by using `tab:red` for color. ``` fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) # Specify how our lines should look ax.plot(times, temps, color='tab:red', label='Temperature (surface)') ax.plot(times, temps_1000, color='tab:red', linestyle='--', label='Temperature (isobaric level)') # Same as above ax.set_xlabel('Time') ax.set_ylabel('Temperature') ax.set_title('Temperature Forecast') ax.grid(True) ax.legend(loc='upper left') ``` ### Exercise * Use `add_subplot` to create two different subplots on the figure * Create one subplot for temperature, and one for dewpoint * Set the title of each subplot as appropriate * Use `ax.set_xlim` and `ax.set_ylim` to control the plot boundaries * **BONUS:** Experiment with passing `sharex` and `sharey` to `add_subplot` to <a href="https://matplotlib.org/gallery/subplots_axes_and_figures/shared_axis_demo.html#sphx-glr-gallery-subplots-axes-and-figures-shared-axis-demo-py">share plot limits</a> ``` # Fake dewpoint data to plot dewpoint = 0.9 * temps dewpoint_1000 = 0.9 * temps_1000 # Create the figure fig = plt.figure(figsize=(10, 6)) # YOUR CODE GOES HERE ``` #### Solution ``` # %load solutions/subplots.py ``` ## Scatter Plots Maybe it doesn't make sense to plot your data as a line plot, but with markers (a scatter plot). We can do this by setting the `linestyle` to none and specifying a marker type, size, color, etc. ``` fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) # Specify no line with circle markers ax.plot(temps, temps_1000, linestyle='None', marker='o', markersize=5) ax.set_xlabel('Temperature (surface)') ax.set_ylabel('Temperature (1000 hPa)') ax.set_title('Temperature Cross Plot') ax.grid(True) ``` You can also use the `scatter` methods, which is slower, but will give you more control, such as being able to color the points individually based upon a third variable. ``` fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) # Specify no line with circle markers ax.scatter(temps, temps_1000) ax.set_xlabel('Temperature (surface)') ax.set_ylabel('Temperature (1000 hPa)') ax.set_title('Temperature Cross Plot') ax.grid(True) ``` ### Exercise * Beginning with our code above, add the `c` keyword argument to the `scatter` call and color the points by the difference between the surface and 1000 hPa temperature. * Add a 1:1 line to the plot (slope of 1, intercept of zero). Use a black dashed line. * **BONUS:** Change the color map to be something more appropriate for this plot. * **BONUS:** Try to add a colorbar to the plot (have a look at the matplotlib documentation for help). ``` fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(1, 1, 1) # YOUR CODE GOES HERE ax.set_xlabel('Temperature (surface)') ax.set_ylabel('Temperature (1000 hPa)') ax.set_title('Temperature Cross Plot') ax.grid(True) ``` #### Solution ``` # %load solutions/color_scatter.py ``` ## imshow/contour - `imshow` displays the values in an array as colored pixels, similar to a heat map. - `contour` creates contours around data. - `contourf` creates filled contours around data. First let's create some fake data to work with - let's use a bivariate normal distribution. ``` x = y = np.arange(-3.0, 3.0, 0.025) X, Y = np.meshgrid(x, y) Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 ``` Let's start with a simple imshow plot. ``` fig, ax = plt.subplots() im = ax.imshow(Z, interpolation='bilinear', cmap='RdYlGn', origin='lower', extent=[-3, 3, -3, 3]) ``` We can also create contours around the data. ``` fig, ax = plt.subplots() ax.contour(X, Y, Z) fig, ax = plt.subplots() c = ax.contour(X, Y, Z, levels=np.arange(-2, 2, 0.25)) ax.clabel(c) fig, ax = plt.subplots() c = ax.contourf(X, Y, Z) ``` ### Exercise * Create a figure using imshow and contour that is a heatmap in the colormap of your choice. Overlay black contours with a 0.5 contour interval. ``` # YOUR CODE GOES HERE ``` #### Solution ``` # %load solutions/imshow_contour.py ``` ## Resources The goal of this tutorial is to provide an overview of the use of the Matplotlib library. It covers creating simple line plots, but it is by no means comprehensive. For more information, try looking at the: - [Matplotlib Documentation](http://matplotlib.org) - [Matplotlib `plot` documentation](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot)
github_jupyter
<a href='http://www.pieriandata.com'><img src='../Pierian_Data_Logo.png'/></a> ___ <center><em>Copyright Pierian Data</em></center> <center><em>For more information, visit us at <a href='http://www.pieriandata.com'>www.pieriandata.com</a></em></center> # Visualization Exercise ## The Data This classic dataset contains the prices and other attributes of almost 54,000 diamonds. It's a great dataset for beginners learning to work with data analysis and visualization. #### Content * price price in US dollars (\$326--\$18,823) * carat weight of the diamond (0.2--5.01) * cut quality of the cut (Fair, Good, Very Good, Premium, Ideal) * color diamond colour, from J (worst) to D (best) * clarity a measurement of how clear the diamond is (I1 (worst), SI2, SI1, VS2, VS1, VVS2, VVS1, IF (best)) * x length in mm (0--10.74) * y width in mm (0--58.9) * z depth in mm (0--31.8) * depth total depth percentage = z / mean(x, y) = 2 * z / (x + y) (43--79) * table width of top of diamond relative to widest point (43--95) ## Imports and Data ``` import pandas as pd import matplotlib.pyplot as plt import matplotlib.cm as cm import seaborn as sns diamonds = pd.read_csv('diamonds.csv') diamonds.head() diamonds.info() ``` #### TASK: Create a scatterplot of price versus carat as shown below ``` sns.scatterplot(x = "carat", y = "price", data = diamonds) ``` #### TASK: Use alpha parameter and edgecolor parameter to deal with the overlapping issue and white edgemarker issue. ``` sns.scatterplot(x = "carat",y = "price", data = diamonds, alpha=0.1, edgecolor=None) ``` #### TASK: Make the previous plot larger ``` plt.figure(figsize = (12,8)) sns.scatterplot(x = "carat", y = "price", data = diamonds, alpha=0.1, edgecolor=None) ``` #### TASK: Create a histogram of the price column as shown below ``` plt.figure(figsize = (12,8)) sns.distplot(diamonds["price"], kde = False) plt.xlim(0, 18000) ``` #### TASK: Create a count plot of the instances per cut type as shown below ``` sns.countplot(x = "cut", data = diamonds) ``` #### TASK: Create a large box plot figure showing the price distribution per cut type as shown below ``` plt.figure(figsize = (12, 8)) sns.boxplot(x = "cut", y = "price", data = diamonds) ``` #### TASK: Challenge! See if you can figure out how to change the ordering of the boxplot as shown below. Feel free to also chaneg the coloring, to reflect this relationship between the cut types. ``` plt.figure(figsize = (12, 8)) cut_order = ["Fair", "Ideal", "Good", "Very Good", "Premium"] sns.boxplot(x = "cut", y = "price", data = diamonds, order = cut_order, palette = "cool") ```
github_jupyter
# TüEyeQ Analysis This notebook contains experiments and plots accompanying the TüEyeQ data set. Please refer to our paper when using this script: [citation] The TüEyeQ data set can be downloaded at [link]. This notebook comprises the following parts: 1. Load Packages and Data 2. General Analysis of the Raw Data (prior to pre-processing) 3. Preprocessing 4. Distance Correlations of Features 5. Logistic Regression Model --- This code is published under the MIT license. *Copyright (c) 2020 Johannes Haug* # 1. Load Packages and Data ``` import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, roc_curve from sklearn.linear_model import LogisticRegression import shap from lime import lime_tabular import dcor import pickle tiq = pd.read_csv('./data/cft_full.csv') # !!! you may need to substitute this with a different path to the data tiq.head() tiq.shape ``` # 2. General Analysis Next, we investigate frequencies and distributions of the raw (unprocessed) data set. ## Solved Tasks Here, we illustrate the **number of participants, who managed to solve each task correctly**. In addition, we show the incremental mean of participants and the number of unsolved tasks. Note that the tasks are shown in the order of appearance. Each block of tasks is highlighted in a different color. We also indicate all tasks with an error during the data collection process. ``` color_palette = ['#fee090','#91cf60','#e0f3f8','#91bfdb'] tasks = tiq.groupby('task_id', sort=False)['cft_task'].sum() # sum of participants who solved the task mean = pd.Series(tasks.values).expanding().mean() # incremental mean no. of participants with correct answer # Count number of NaNs (i.e. no. of participants that did not solve the task) unsolved = tiq[['task_id','cft_task']].copy() unsolved['cft_task'] = unsolved['cft_task'].isnull() unsolved = unsolved.groupby('task_id', sort=False)['cft_task'].sum() itr = 0 # task iterator clr = 0 # color indicator group_size = [15,15,14,10] # no. tasks per group fig = plt.figure(figsize=(20,5)) for tk in tasks.items(): if itr == group_size[clr]: itr = 0 # reset iterator (next task group begins) clr += 1 # increment color indicator # Mark erroneous measurements with pattern if tk[0][-1] == 'e': pattern = '//' else: pattern = '' plt.bar(tk[0], tk[1], color=color_palette[clr], hatch=pattern, label='_nolegend_') itr += 1 # increment task iterator # Line plot of incremental mean plt.plot(unsolved.keys(), mean, color='black', lw=2, marker='.', markersize=12, label='Incremental Mean') # Line plot of unsolved tasks plt.plot(unsolved.keys(), unsolved.values, color='black', lw=2, ls=':', marker='x', markersize=8, label='Participants without an answer') plt.ylabel('Participants with Correct Answer', size=12) plt.xlabel('Task', size=12) plt.xticks(rotation=90) plt.xlim(-1, 54) plt.ylim(0, 335) plt.legend() # Save histogram plt.savefig('./figures/task_histogram.pdf', bbox_inches='tight', format='pdf') plt.savefig('./figures/task_histogram.png', bbox_inches='tight', format='png') plt.plot() ``` ## Bias We **investigate whether the data is biased against age or gender**. To this end, we plot the distribution/frequency of both variables, as well as the normalized fraction of correctly solved tasks. ``` # Generic function to plot distribution histogram (bar chart) def plot_bar(x, y_1, y_2, x_ticklabels, label_x, label_y, path, stacked=False): wd = .4 if stacked: plt.bar(x, y_1, color='#91bfdb') plt.bar(x, y_2, color='#fc8d59', bottom=y_1) else: plt.bar(x - wd/2, y_1, width=wd, color='#91bfdb') plt.bar(x + wd/2, y_2, width=wd, color='#fc8d59') plt.ylim(0,1) plt.xlabel(label_x, size=12) plt.xticks(x, x_ticklabels) plt.ylabel(label_y, size=12) plt.xlim(min(x)-.5, max(x)+.5) plt.legend(['Male','Female'], loc='upper right') plt.savefig('./figures/{}.png'.format(path), bbox_inches='tight', format='png') plt.savefig('./figures/{}.pdf'.format(path), bbox_inches='tight', format='pdf') plt.show() ############################################################################## # Plot histogram of age and gender age_count_male = tiq[tiq['gender'] == 1]['age'].value_counts().sort_index() # count male participants per age age_count_female = tiq[tiq['gender'] == 2]['age'].value_counts().sort_index() # count female participants per age # Correctly solved tasks per age and gender tasks_age_male = tiq[tiq['gender'] == 1].groupby('age', sort=False)['cft_task'].sum().sort_index() tasks_age_female = tiq[tiq['gender'] == 2].groupby('age', sort=False)['cft_task'].sum().sort_index() plot_bar(age_count_male.keys(), age_count_male.values, age_count_female.values, age_count_male.keys().values.astype(int), 'Age', 'No. of Tasks', 'age_hist', True) plot_bar(age_count_male.keys(), tasks_age_male.values / age_count_male.values, tasks_age_female.values / age_count_female.values, age_count_male.keys().values.astype(int), 'Age', 'Norm. % of Tasks Solved Correctly', 'age_tasks_norm') ``` ## CFT Distribution We investigate the histogram of the aggregated CFT score (cft_sum_full) and find that it is approximately normally distributed. ``` cft_unique = tiq[['subject', 'cft_sum_full']].drop_duplicates() # extract unique subjects cft_unique.hist(bins=26, color='#91bfdb') # separate into 26 bins, since there are 26 unique aggr. CFT scores plt.grid(False) plt.title(None) plt.xlabel('Aggregated CFT', size=12) plt.ylabel('No. of Participants', size=12) # Save histogram plt.savefig('./figures/cft_histogram.png', bbox_inches='tight', format='png') plt.savefig('./figures/cft_histogram.pdf', bbox_inches='tight', format='pdf') plt.show() ``` # 3. Preprocessing All subsequent analysis requires the data set to be preprocessed. For illustration, we consider a binary classification scenario of **cft_task (target)**. Specifically, we use the **true class "correct answers (label 1)"** and the **negative class "wrong answers (label 0)"**. We ignore missing answers (NaN values) in this experiment (removes 1,248 observations). Specifically, we apply the following pre-processing steps: 1. Specify the categorical and the continuous features (according to the paper) 1. Remove all observations with missing target (i.e. NaN value in cft_task). 2. Remove subject and cft_sum_full to avoid information leakage due to high dependendy with the target. 3. Impute NaN-values in categorical features with a new category. 4. Impute NaN-values in continuous features with the median. 5. Factorize the categorical features (to encode strings as integers). 6. Normalize the continuous features to the intervall [0,1] (since we will be using l2-regularization). 7. Split data into a training and test set (20% holdout for testing) ``` # 1. Extract categorical and continuous features ftr_cont = ['mean_grade_degree','grades_math', 'grades_german', 'grades_biology', 'grades_physics', 'grades_chemistry','grades_geography','grades_history','grades_art', 'gaming_hours_weekly_min', 'gaming_hours_weekly_max', 'cft_sum_full'] ftr_cat = tiq.iloc[:,~tiq.columns.isin(ftr_cont)].columns.tolist() # Remove the target 'cft_task' from the list of categorical features ftr_cat.remove('cft_task') # 2. Remove all observations with missing target tiq = tiq[tiq['cft_task'].notna()] # 3. Remove subject and cft_sum_full, due to possible information leakage # Note that we did NOT remove these variables for the computation of the distance correlation as reported in the paper # However, it should be noted that none of these variables has a pairwise correlation above 0.5 tiq = tiq.drop(['subject','cft_sum_full'], axis=1) ftr_cat.remove('subject') ftr_cont.remove('cft_sum_full') # 4. Impute NaN-values in categorical features with a new category tiq[ftr_cat] = tiq[ftr_cat].fillna('new_category') # 5. Impute NaN-values in continuous features with the median medians = tiq[ftr_cont].median() tiq[ftr_cont] = tiq[ftr_cont].fillna(medians) # 6. Factorize the categorical features tiq[ftr_cat] = tiq[ftr_cat].apply(lambda x: pd.factorize(x)[0]) # 7. Normalize the continuous features tiq[ftr_cont] = MinMaxScaler().fit_transform(tiq[ftr_cont]) # 8. Train/Test split of the data X_train, X_test, y_train, y_test = train_test_split(tiq.drop('cft_task', axis=1), tiq['cft_task'], test_size=.2, random_state=42) ``` # 4. Distance Correlations We compute the pairwise Distance Correlation of features in a test set according to Székely, Gábor J., Maria L. Rizzo, and Nail K. Bakirov. "Measuring and testing dependence by correlation of distances." The annals of statistics 35.6 (2007): 2769-2794. ``` # Compute Distance Correlation (on a sample of the data) # !!! Note that we also provide pre-computed distance correlation scores, which can be loaded in the next cell !!! dist_crl = [] combs = set() # save feature combinations crl_sample = tiq.sample(frac=0.2, random_state=42) # sample a test set (as computation of distance correlation is costly) for ftr1 in crl_sample: for ftr2 in crl_sample: # Check if feature combination was already evaluated (distance correlation is symmetric!) if '{}-{}'.format(ftr1, ftr2) not in combs and '{}-{}'.format(ftr2, ftr1) not in combs and ftr1 != ftr2: combs.add('{}-{}'.format(ftr1, ftr2)) # add feature pair to list of combinations dist_crl.append([ftr1, ftr2, dcor.distance_correlation(crl_sample[ftr1], crl_sample[ftr2])]) print(dist_crl[-1]) dist_crl = pd.DataFrame(dist_crl, columns=['Feature 1', 'Feature 2', 'Dist. Correlation']) # Save/Load the Distance correlation object #filehandler = open('./pre-computed/distance_correlation_full.obj', 'wb') #pickle.dump(dist_crl, filehandler) # Save Object filehandler = open('./pre-computed/distance_correlation.obj', 'rb') dist_crl = pickle.load(filehandler) # Load Object filehandler.close() # Plot most strongly correlated features top_crl = dist_crl.reindex(dist_crl['Dist. Correlation'].sort_values(ascending=False).index).reset_index(drop=True) # sort values top_crl['Dist. Correlation'] = top_crl['Dist. Correlation'].round(5) # round scores ltx_crl = top_crl.iloc[:54,:] # select top entries print(ltx_crl.to_latex(index=False)) # plot in latex style # Plot histogram of the distance correlation scores def plot_hist(var, b, xmin, xlabel, ylabel, path): var.hist(bins=b, color='#91bfdb') plt.grid(False) plt.xlim(xmin, 1) plt.title(None) plt.xlabel(xlabel, size=12) plt.ylabel(ylabel, size=12) # Save histogram plt.savefig('./figures/{}_histogram.png'.format(path), bbox_inches='tight', format='png') plt.savefig('./figures/{}_histogram.pdf'.format(path), bbox_inches='tight', format='pdf') plt.show() ############################################################################## plot_hist(dist_crl, 100, 0, 'Distance Correlation', 'No. of Feature Pairs', 'dist_corr') # Plot correlation with cft_sum_full cft_crl = top_crl[(top_crl['Feature 1'] == 'cft_sum_full') | ((top_crl['Feature 2'] == 'cft_sum_full'))].iloc[:20,:] print(cft_crl.to_latex(index=False)) # plot in latex style ``` # 5. Logistic Regression Model For illustration, we train a simple Logistic Regression model to predict the **cft_task (target)**. We also compute the **SHAP and LIME values** to quantify every feature's contribution in the prediction. Specifically, we perform the following training and evaluation steps: 1. Train and test the Logistic Regression (LR) model 2. Plot the weights of the LR model 3. Compute Shapley values for the LR model 4. Compute LIME values for the LR model ``` # Function to plot ROC curve def plot_roc(y_pred, path): # Compute ROC-AUC Score auc = roc_auc_score(y_test, y_pred) # Plot ROC Curve fpr, tpr, _ = roc_curve(y_test, y_pred) plt.plot(fpr, tpr, color='#4575b4', label='ROC Curve (AUC = {})'.format(round(auc, 4)), lw=2) plt.plot([0, 1], [0, 1], color='black', ls='--', label='_nolegend_', lw=2) plt.xlim(0,1) plt.ylim(0,1) plt.xlabel('False Positive Rate', size=12) plt.ylabel('True Positive Rate', size=12) plt.legend() plt.savefig('{}.pdf'.format(path), bbox_inches='tight', format='pdf') # save as PDF plt.savefig('{}.png'.format(path), bbox_inches='tight', format='png') # save as PNG plt.show() # 1. Train and test the LR model model = LogisticRegression(penalty='l2', random_state=42, max_iter=1000, solver='lbfgs') model.fit(X_train, y_train) y_pred = model.predict_proba(X_test) plot_roc(y_pred[:,1], './figures/roc_lr') # 2. Plot the weights of the LR model coef = model.coef_.flatten() coef_idx = abs(coef).argsort()[-20:] # get indices of top coefficients coef_sorted = coef[coef_idx] coef_names = X_test.columns[coef_idx] # get coefficient names fig = plt.figure(figsize=(8,6)) plt.xlabel('Logistic Regression Coefficient', size=12) plt.ylabel('Feature', size=12) plt.barh(coef_names, coef_sorted, color='#4575b4') plt.ylim(-1,20) plt.vlines(0, -1, 21, ls='--') plt.savefig('./figures/coef_lr.pdf', bbox_inches='tight', format='pdf') # save as PDF plt.savefig('./figures/coef_lr.png', bbox_inches='tight', format='png') # save as PNG plt.show() # 3. Compute SHAP (LinearSHAP) reference_X = shap.sample(X_train, 100) explainer = shap.LinearExplainer(model, reference_X) shap_values = explainer.shap_values(X_test) shap.summary_plot(shap_values, X_test, show=False) plt.savefig('./figures/shap_lr.png', bbox_inches='tight', format='png') plt.savefig('./figures/shap_lr.pdf', bbox_inches='tight', format='pdf') plt.show() # 4. Compute LIME (TabularLIME) lime_exp = lime_tabular.LimeTabularExplainer( reference_X.to_numpy(), feature_names=X_test.columns.values.tolist(), discretize_continuous=False, random_state=42 ) lime_mean = np.zeros(X_test.shape[1]) for xt in X_test.to_numpy(): # Compute average LIME scores exp = lime_exp.explain_instance(xt, model.predict_proba, num_samples=100, num_features=X_test.shape[1], top_labels=2).local_exp for itm in exp[1]: # collect explanations for positive class (label=1) lime_mean[itm[0]] += itm[1] # sum local explanations lime_mean /= X_test.shape[0] # compute mean attribution lime_mean_idx = abs(lime_mean).argsort()[-20:] # get indices of top coefficients lime_mean_sorted = lime_mean[lime_mean_idx] coef_names = X_test.columns[lime_mean_idx] # get coefficient names fig = plt.figure(figsize=(8,6)) plt.xlabel('Average LIME Attribution', size=12) plt.ylabel('Feature', size=12) plt.barh(coef_names, lime_mean_sorted, color='#4575b4') plt.ylim(-1,20) plt.vlines(0, -1, 21, ls='--') plt.savefig('./figures/lime_lr.pdf', bbox_inches='tight', format='pdf') # save as PDF plt.savefig('./figures/lime_lr.png', bbox_inches='tight', format='png') # save as PNG plt.show() ```
github_jupyter
<a href="https://colab.research.google.com/github/whobbes/fastai/blob/master/keras_lesson1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## FastAI setup ``` # Get the file from fast.ai URL, unzip it, and put it into the folder 'data' # This uses -qq to make the unzipping less verbose. !wget http://files.fast.ai/data/dogscats.zip && unzip -qq dogscats.zip -d data/ ``` ## Introduction to our first task: 'Dogs vs Cats' ``` %reload_ext autoreload # %autoreload 2 # %matplotlib inline PATH = "data/dogscats/" sz=224 batch_size=64 import numpy as np from keras.preprocessing.image import ImageDataGenerator from keras.preprocessing import image from keras.layers import Dropout, Flatten, Dense from keras.applications import ResNet50 from keras.models import Model, Sequential from keras.layers import Dense, GlobalAveragePooling2D from keras import backend as K from keras.applications.resnet50 import preprocess_input train_data_dir = f'{PATH}train' validation_data_dir = f'{PATH}valid' train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input) train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(sz, sz), batch_size=batch_size, class_mode='binary') validation_generator = test_datagen.flow_from_directory(validation_data_dir, shuffle=False, target_size=(sz, sz), batch_size=batch_size, class_mode='binary') base_model = ResNet50(weights='imagenet', include_top=False) x = base_model.output x = GlobalAveragePooling2D()(x) x = Dense(1024, activation='relu')(x) predictions = Dense(1, activation='sigmoid')(x) model = Model(inputs=base_model.input, outputs=predictions) for layer in base_model.layers: layer.trainable = False model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) %%time model.fit_generator(train_generator, train_generator.n // batch_size, epochs=3, workers=4, validation_data=validation_generator, validation_steps=validation_generator.n // batch_size) split_at = 140 for layer in model.layers[:split_at]: layer.trainable = False for layer in model.layers[split_at:]: layer.trainable = True model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) %%time model.fit_generator(train_generator, train_generator.n // batch_size, epochs=1, workers=3, validation_data=validation_generator, validation_steps=validation_generator.n // batch_size) ```
github_jupyter
# Introduction to PyTorch ##What is Pytorch PyTorch is an open source machine learning library based on the Torch library, used for applications such as computer vision and natural language processing, primarily developed by Facebook's AI Research lab (FAIR) In simpler language: You can assume PyTorch to be similar as Numpy but with stronger GPU acceleration. It is a library for Python programs that facilitates building deep learning projects. It emphasizes flexibility and allows deep learning models to be expressed in idiomatic Python. PyTorch provides two high-level features: * Tensor computing (like NumPy) with strong acceleration via graphics processing units (GPU) * Deep neural networks built on a type-based automatic differentiation system ### But why do we even need Pytorch? You might wonder why we need a library like PyTorch at all since Numpy already provides data structures and utilities for working with multi-dimensional numeric data. There are two main reasons: 1. **Autograd**: The ability to automatically compute gradients for tensor operations is essential for training deep learning models. 2. **GPU support**: While working with massive datasets and large models, PyTorch tensor operations can be performed efficiently using a Graphics Processing Unit (GPU). Computations that might typically take hours can be completed within minutes using GPUs. ### Difference between PyTorch and TensorFlow While some people may already be familiar with TensorFlow, an open source machine learning software library developed by Google. Both TensorFlow and PyTorch have different advantages on each other which I have described in brief below: TensorFlow is very powerful and mature deep learning library with strong visualization capabilities and several options to use for high-level model development. It has production-ready deployment options and support for mobile platforms. TensorFlow is a good option if you: * Develop models for production * Develop models which need to be deployed on mobile platforms * Want good community support and comprehensive documentation * Want rich learning resources in various forms (TensorFlow has an an entire MOOC) * Want or need to use Tensorboard * Need to use large-scale distributed model training PyTorch is still a young framework which is getting momentum fast. You may find it a good fit if you: * Do research or your production non-functional requirements are not very demanding * Want better development and debugging experience * Love all things Pythonic If you have the time the best advice would be to try both and see what fits your needs best. You can find a more in-depth guide on the differences [here](https://builtin.com/data-science/pytorch-vs-tensorflow). ### How to run the code #### Option 1: Running using free online resources (1-click, recommended) The easiest way to start executing the code is to run it on Google Colab by simply downloading this file and uploading it on Google Colab. #### Option 2: Running on your computer locally To run the code on your computer locally, you'll need to set up [Python](https://www.python.org), download the notebook and install the required libraries. We recommend using the [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/install/) distribution of Python. > **Jupyter Notebooks**: This tutorial is a [Jupyter notebook](https://jupyter.org) - a document made of _cells_. Each cell can contain code written in Python or explanations in plain English. You can execute code cells and view the results instantly within the notebook. It is widely used for Analysis. Before we begin, we need to install the required libraries. The installation of PyTorch may differ based on your operating system / cloud environment. You can find detailed installation instructions here: https://pytorch.org . ``` #pip is a package-management system written in Python used to install and manage software packages #installation with pip: # pip3 install torch torchvision ``` Let's import the torch module to get started ``` import torch ``` Let us also switch to the GPU to the observe the full power of PyTorch. We can switch to the GPU in Colab Notebook by: `Runtime>Change Runtime Type>Hardware Selector>GPU` ## Tensors PyTorch tensors are similar to Numpy ndarrays with the option to operate on GPU. At its core, PyTorch is a library for processing tensors. A torch.Tensor is a multi-dimensional matrix containing elements of a single data type. Torch defines 10 tensor types with CPU and GPU variants which can be found on it's offcial [documentation page](https://pytorch.org/docs/stable/tensors.html) ``` # Number t1 = torch.tensor(4.) t1 # Vector t2 = torch.tensor([1., 2, 3, 4]) t2 # Matrix t3 = torch.tensor([[5., 6], [7, 8], [9, 10]]) t3 # 3-dimensional array t4 = torch.tensor([ [[11, 12, 13], [13, 14, 15]], [[15, 16, 17], [17, 18, 19.]]]) t4 ``` The contents of a tensor can be accessed and modified using Python’s indexing and slicing notation: ``` t5 = torch.tensor([[1,2,3], [4,5,6]]) t5[0,1] t5[1,2]=0 t5 ``` Tensors can have any number of dimensions and different lengths along each dimension. We can inspect the length along each dimension using the `.shape` property of a tensor. ``` print(t1) t1.shape print(t2) t2.shape print(t3) t3.shape print(t4) t4.shape print(t5) t5.shape ``` Note that it's not possible to create tensors with an improper shape. ``` # Matrix t6 = torch.tensor([[5., 6, 11], [7, 8], [9, 10]]) t6 ``` ### Tensor operations and gradients We can combine tensors with the usual arithmetic operations. Let's look at an example: ``` x = torch.tensor(2.) y = torch.tensor(5., requires_grad=True) z = torch.tensor(7., requires_grad=True) ``` We have creates 3 tensors `x`,`y` and `z` with 2 of them having `requies_grad` set to `True` ``` #Arithmetic Operation f = x * y + z f ``` What makes PyTorch unique is that we can automatically compute the derivative of `f` w.r.t. the tensors that have `requires_grad` set to `True` i.e. w and b. This feature of PyTorch is called [_autograd_](https://pytorch.org/docs/stable/autograd.html#module-torch.autograd) (automatic gradients). To compute the derivatives, we can invoke the `.backward` method on our result `y`. `grad` is short for Gradient, which is another name for Derivatives. ``` # Compute derivatives f.backward() ``` The derivatives of `f` with respect to the input tensors are stored in the `.grad` property of the respective tensors. ``` # Display gradients print('df/dx:', x.grad) print('df/dy:', y.grad) print('df/dz:', z.grad) ``` ### Tensor functions Apart from arithmetic operations, the `torch` module also contains many functions for creating and manipulating tensors. Let's look at some examples: ``` # Create a tensor with a fixed value for every element t7 = torch.full((3, 2), 31) t7 # Concatenate two tensors with compatible shapes t8 = torch.cat((t3, t7)) t8 # Compute the cos of each element t9 = torch.cos(t8) t9 # Change the shape of a tensor t10 = t9.reshape(3, 2, 2) t10 ``` Let's look at difference between 2 very similar functions: ``` #Difference between 2 PyTorch Functions: view & permute x = torch.rand(2,4) #generates a random tensor of 2x4 print('x:', x) print('shape:', x.shape) y = x.view(4, 2) #view the tensor as 4x2 print('y:', y) print('shape:', y.shape) z = x.permute(1, 0) #works like transpose of a matrix print('z:', z) print('shape:', z.shape) ``` You can find more useful functions in the official documentation [here](https://pytorch.org/docs/stable/torch.html) ## Tensors in CPU and GPU GPU composes of hundreds of simpler cores, which makes training deep learning models much faster. Refer to the Image below: ![temp.jpeg](data:image/jpeg;base64,/9j/2wCEAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRQBAwQEBQQFCQUFCRQNCw0UFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFP/AABEIAWcCfgMBIgACEQEDEQH/xAGiAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgsQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+gEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoLEQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/AP1TooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA4v4s/GHwd8DfB1z4p8b67baBo0DBPOnyzSuQSI40UFpHODhVBOAT0Br4s1L/gtP8HbXU2gtPCnjK+s1baboW1qm4Z6qhnzj/ewfYV87ftv6lqn7Wf8AwUU8PfBxtRmtfDWlXtro8SxniLzESa9nVTx5m0soz1EKe9fpJpX7KHwI8AeCofD5+HXhCDRhGLcyapp8Essxx1eeUF3cgH5i2ePagB/7OX7Xfw0/am0y6n8D6w8moWah7zR9Qi8i9tlPAZkyQy5IG5GZcnGc8Vy37T/7efw8/ZM8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e1df4g/Z91qf9pa0+K2geM10a2udIh0PXdBn0pbldQt45XkXy5vMVoWy+MhW6fhQB8XjxzrfhRJR8ZfiL8Wvg58XhqjsPFF4lxeeDHJuCY44beI+Q9uYtq4YLgnJfg1+m9nOl3aQzRzR3EciK6zQnKOCOGXk8Ecjk18o6l+x58R7/wFqfwvb41Pc/Cy/aWJ7fUNBW61pLOSQu1sL15iG6lRK0ZYZ4HAr6l0DRLTw1oenaRp8ZisbC2jtLeMkttjRQqjJ64AFAGjRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQBQfRNOl1JNQewtn1BBtS6aFTKo9A+MgVfoooAKKKKACiiigAooooAKKKKAIZII5XR3jV3Q5RiMlT7elTUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABUMkEcro7xq7ocoxGSp9vSpqKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//2Q==) Whether we decide to use GPU or CPU, PyTorch makes it easy for us to switch between the two ``` cpu=torch.device("cpu") gpu=torch.device("cuda:0") # GPU 0# Create tensor with CPU x=torch.ones(3,3, device=cpu) print("CPU:",x.device) x=torch.ones(3,3, device=gpu) print("GPU:",x.device) x=torch.ones(3,3).cuda(0) print("CPU to GPU:",x.device) x=torch.ones(3,3, device=gpu).cpu() print("GPU to CPU:",x.device) ``` Please note: If you face an error in the above program, it might be because you haven't changed to the GPU or your system doesn't have one. On Google Colab you can find a way to change to GPU: `Runtime>Change Runtime Type>Hardware Selector>GPU` ### Compare time between GPU and CPU ### Time in CPU ``` import time x=torch.rand(10000,10000) y=torch.rand(10000,10000) t = time.time() z=x@y t = time.time()-t print(t) ``` #### Time in GPU ``` xc=x.cuda(0) yc=y.cuda(0) t = time.time() z=xc@yc t = time.time()-t print(t) ``` We can see that there is `considerably big difference` in time taken. ## Interoperability with Numpy [Numpy](http://www.numpy.org/) is a popular open-source library used for mathematical and scientific computing in Python. It enables efficient operations on large multi-dimensional arrays and has a vast ecosystem of supporting libraries, including: * [Pandas](https://pandas.pydata.org/) for file I/O and data analysis * [Matplotlib](https://matplotlib.org/) for plotting and visualization * [OpenCV](https://opencv.org/) for image and video processing Instead of reinventing the wheel, PyTorch interoperates well with Numpy to leverage its existing ecosystem of tools and libraries. ``` import numpy as np #we need to import the numpy library x = np.array([[1, 2], [3, 4.]]) x ``` We can convert a Numpy array to a PyTorch tensor using `torch.from_numpy`. ``` # Convert the numpy array to a torch tensor. y = torch.from_numpy(x) y ``` Numpy array and Torch tensor will have similar datatype: ``` x.dtype, y.dtype ``` We can convert a PyTorch tensor to a Numpy array using the `.numpy` method of a tensor. ``` # Convert a torch tensor to a numpy array z = y.numpy() z ``` The interoperability between PyTorch and Numpy is essential because most datasets you'll work with will likely be read and preprocessed as Numpy arrays. ## What next? You can further your introduction to this library by looking up more about it on the official documentation page [here](https://pytorch.org/docs/stable/index.html). You can look for datasets on [kaggle](https://www.kaggle.com/) and implement some of the premade models in the library. ## Resources referred: * https://towardsdatascience.com/what-is-pytorch-a84e4559f0e3 * https://towardsdatascience.com/pytorch-vs-tensorflow-spotting-the-difference-25c75777377b * https://en.wikipedia.org/wiki/PyTorch * https://en.wikipedia.org/wiki/TensorFlow * https://pytorch.org/docs/stable/index.html * https://builtin.com/data-science/pytorch-vs-tensorflow * https://www.youtube.com/watch?v=zEtukWs_B2I&list=PLyMom0n-MBroupZiLfVSZqK5asX8KfoHL
github_jupyter
``` %load_ext autoreload %autoreload 2 import pickle import jax import jax.numpy as jnp import timecast as tc import tqdm class SGD: def __init__(self, loss_fn=lambda pred, true: jnp.square(pred - true).mean(), learning_rate=0.0001, project_threshold={}): self.loss_fn = loss_fn self.learning_rate = learning_rate self.project_threshold = project_threshold def update(self, module, x, y): grad = jax.jit(jax.grad(lambda module, x, y: self.loss_fn(module(x), y)))(module, x, y) new_params = {k:w - self.learning_rate * grad.params[k] for (k, w) in params.items()} for k, param in new_params.items(): norm = jnp.linalg.norm(new_params[k]) new_params[k] = jax.lax.cond(norm > self.project_threshold[k], new_params[k], lambda x : (self.project_threshold[k]/norm) * x, new_params[k], lambda x : x) return new_params class MultiplicativeWeights: def __init__(self, eta=0.008): self.eta = eta self.grad = jax.jit(jax.grad(lambda W, preds, y: jnp.square(jnp.dot(W, preds) - y).sum())) def update(self, module, params, x, y): grad = self.grad(params, x, y) new_params = params * jnp.exp(-1 * self.eta * grad) return new_params / new_params.sum() class AR(tc.Module): def __init__(self, input_dim=32, output_dim=1, history_len=270): self.kernel = jnp.zeros((history_len, input_dim, output_dim)) self.bias = jnp.zeros((output_dim, 1)) def __call__(self, x): print("*** ENTER AR PRED ***") print("self.kernel = " + str(self.kernel)) print("self.bias = " + str(self.bias)) print("x = " + str(x)) return jnp.tensordot(self.kernel, x, ([0,1],[0,1])) + self.bias class GradientBoosting(tc.Module): def __init__(self, N, input_dim=32, output_dim=1, history_len=270): for i in range(N): self.add_module(AR(input_dim=input_dim, output_dim=output_dim, history_len=history_len)) self.W = jnp.ones(N) / N def __call__(self, x): pred, preds = 0, [] print("----- ENTER GRADIENT_BOOSTING PRED -----") print("x = " + str(x)) for i, (name, submodule) in enumerate(self.modules.items()): print("submodule.params = " + str(submodule.params)) print("submodule.kernel = " + str(submodule.kernel)) pred_i = submodule(x).squeeze() print("pred_i = " + str(pred_i)) preds.append(pred_i) pred += self.W[i] * pred_i return preds def ND_loss(Yhats, Y): return float((jnp.abs(Y - Yhats)).sum() / (jnp.abs(Y)).sum()) def predict_nips(SGDs, MW): N = len(SGDs) model = GradientBoosting(N, 1, 1, 7) Yhats = 1.001*jnp.ones((20,1)) print("Yhats.shape = " + str(Yhats.shape)) X = jnp.ones((20,7,1)) print("X.shape = " + str(X.shape)) Y = jnp.ones((20,1)) print("Y.shape = " + str(Y.shape)) def loop(model, xy): x, y = xy preds = jnp.asarray(model(x)) pred = 0 print("================= ENTERED LOOP ===================") print("x = " + str(x)) print("y = " + str(y)) print("preds = " + str(preds)) print("model.W = " + str(model.W)) for i, (name, module) in enumerate(model.modules.items()): print("module.params BEFORE = " + str(module.params)) print("module.kernel BEFORE = " + str(module.kernel)) module.update_params(SGDs[i].update(module, module.params, x, y - pred)) print("module.params AFTER = " + str(module.params)) print("module.kernel AFTER = " + str(module.kernel)) pred += model.W[i] * preds[i] print("pred = " + str(pred)) model.W = MW.update(model, model.W, preds, y) return model, pred Y_RESID = Y - Yhats Y_RESID = jnp.expand_dims(Y_RESID, -1) Z = 2 print("Y_RESID.shape = " + str(Y_RESID.shape)) print("Y_RESID[:Z] = " + str(Y_RESID[:Z])) print("X[:Z] = " + str(X[:Z])) Y_BOOST = [] for x, y in zip(X[:Z], Y_RESID[:Z]): model, y_boost = loop(model, (x, y)) Y_BOOST.append(y_boost) Y_BOOST = jnp.expand_dims(jnp.array(Y_BOOST), -1) print("Y_BOOST.shape = " + str(Y_BOOST.shape)) loss = ND_loss(Y[:Z], (Yhats[:Z] + Y_BOOST)) print("loss = " + str(loss)) print("Y_BOOST[:Z] = " + str(Y_BOOST[:Z])) return loss def run_train_loop_nips(dataset_name, learning_rate): LR = learning_rate bias_threshold = 1e-4 eta = 0.008 MW = MultiplicativeWeights(eta=eta) SGDs = [SGD( learning_rate=lr, project_threshold={ "kernel": kernel_threshold, "bias": bias_threshold }) for kernel_threshold, lr in [ (0.03, LR), ]] loss = predict_nips(SGDs, MW) print("loss = " + str(loss)) run_train_loop_nips("electricity_nbeats_last7days", 2e-5) ```
github_jupyter
``` import numpy as np from numba import float64, int64 from numba.experimental import jitclass ``` # UKF ``` p0 = np.zeros(3); v0 = np.zeros(3); rpy0 = np.zeros(3); q0 = np.array([1.0, 0.0, 0.0, 0.0]) ba0 = np.zeros(3); bw0 = np.zeros(3); r_eff = 2.0; g = np.array([0., 0., -9.81]) P0 = np.eye(16) var_a = 0.6; var_w = 0.1; var_ba = 0.05; var_bw = 0.01; var_br = 0.1; alpha = 1e-3; kappa = 0.; beta = 2. class UKF_IMU(object): def __init__(self, p0, v0, rpy0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_br, alpha, kappa, beta): self.p = p0 self.v = v0 self.rpy = rpy0 self.ba = ba0 self.bw = bw0 self.br = 0.0 self.P = P0 self._N = self.P.shape[0] self._r_eff = r_eff self._g = g self._Q = np.zeros((13,13)) self._Q[:3,:3] = np.eye(3) * var_a self._Q[3:6,3:6] = np.eye(3) * var_w self._Q[6:9,6:9] = np.eye(3) * var_ba self._Q[9:12,9:12] = np.eye(3) * var_bw self._Q[12,12] = var_br self._lambda = alpha**2 * (self._N + kappa) - self._N self._Wm = 1. / (2.*(self._N + self._lambda)) * np.ones(2*self._N + 1) self._Wm[0] = self._lambda / (self._N + self._lambda) self._Wc = 1. / (2.*(self._N + self._lambda)) * np.ones(2*self._N + 1) self._Wc[0] = self._lambda / (self._N + self._lambda) + (1 - alpha**2 + beta) def _wrap_angle(self, angle): return (angle + np.pi) % (2 * np.pi) - np.pi def _to_rot_mat(self, rpy): r, p, y = rpy sr = np.sin(r) cr = np.cos(r) sp = np.sin(p) cp = np.cos(p) sy = np.sin(y) cy = np.cos(y) return np.array([[cp*cy, sr*sp*cy - cr*sy, cr*sp*cy + sr*sy], [cp*sy, sr*sp*sy + cr*cy, cr*sp*sy - sr*cy], [-sp, sr*cp, cr*cp]]) def _euler_kinematic_matrix(self, rpy): r, p, y = rpy sr = np.sin(r) cr = np.cos(r) sp = np.sin(p) cp = np.cos(p) tp = np.tan(p) return np.array([[1., sr*tp, cr*tp], [0., cr, -sr], [0., sr/cp, cr/cp]]) def get_state(self): return self.p, self.v, self.rpy, self.ba, self.bw, self.br def get_cov_sys(self): return self.P def predict(self, dt, a, w): # Generate Sigma Points L = np.linalg.cholesky(self.P) xs = np.zeros((self._N, 2*self._N + 1)) xs[:, 0] = np.concatenate((self.p, self.v, self.rpy, self.ba, self.bw, np.array([self.br]))) for i in range(1, self._N+1): xs[:, i] = xs[:, 0] + np.sqrt(self._N + self._lambda) * L[:, i-1] xs[:, i + self._N] = xs[:, 0] - np.sqrt(self._N + self._lambda) * L[:, i-1] # Propagate Sigma Points xs_prop = np.empty_like(xs) for i in range(2*self._N + 1): C = self._to_rot_mat(xs[6:9, i]) xs_prop[:3, i] = xs[:3, i] + dt * xs[3:6, i] + dt**2 * (np.dot(C, a - xs[9:12, i]) + self._g) / 2 xs_prop[3:6, i] = xs[3:6, i] + dt * (np.dot(C, a - xs[9:12, i]) + self._g) xs_prop[6:9, i] = xs[6:9, i] + dt * np.dot(self._euler_kinematic_matrix(xs[6:9, i]), w - xs[12:15, i]) xs_prop[9:, i] = xs[9:, i] # The bias remains the same in this propagation of prediction step # Compute the mean and predicted state x_mean = np.sum(xs_prop * self._Wm, axis=-1) self.p = x_mean[:3] self.v = x_mean[3:6] self.rpy = self._wrap_angle(x_mean[6:9]) self.ba = x_mean[9:12] self.bw = x_mean[12:15] self.br = x_mean[15] # Compute the predicted covariance self.P = np.zeros((self._N, self._N)) for i in range(2*self._N + 1): temp = xs_prop[:,i] - x_mean self.P += self._Wc[i] * np.outer(temp, temp) L = np.zeros((x_mean.shape[0], self._Q.shape[0])) L[:3,:3] = dt**2 * C / 2 L[3:6,:3] = dt * C L[6:9,3:6] = dt * self._euler_kinematic_matrix(self.rpy) L[9:,6:] = np.eye(L[9:,6:].shape[0]) Q_temp = np.copy(self._Q) Q_temp[:6,:6] = Q_temp[:6,:6] #* dt**2 Q_temp[6:,6:] = Q_temp[6:,6:] * dt self.P += np.dot(np.dot(L, Q_temp), L.T) ukf = UKF_IMU(p0, v0, rpy0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_br, alpha, kappa, beta) _ = ukf.get_state() _ = ukf.get_cov_sys() _ = ukf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) %timeit _ = ukf.get_state() %timeit _ = ukf.get_cov_sys() %timeit _ = ukf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) spec = [('p', float64[:]), ('v', float64[:]), ('rpy', float64[:]), ('ba', float64[:]), ('bw', float64[:]), ('br', float64), ('P', float64[:, :]), ('_N', int64), ('_r_eff', float64), ('_g', float64[:]), ('_Q', float64[:, :]), ('_lambda', float64), ('_Wm', float64[:]), ('_Wc', float64[:])] @jitclass(spec) class UKF_IMU(object): def __init__(self, p0, v0, rpy0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_br, alpha, kappa, beta): self.p = p0 self.v = v0 self.rpy = rpy0 self.ba = ba0 self.bw = bw0 self.br = 0.0 self.P = P0 self._N = self.P.shape[0] self._r_eff = r_eff self._g = g self._Q = np.zeros((13,13)) self._Q[:3,:3] = np.eye(3) * var_a self._Q[3:6,3:6] = np.eye(3) * var_w self._Q[6:9,6:9] = np.eye(3) * var_ba self._Q[9:12,9:12] = np.eye(3) * var_bw self._Q[12,12] = var_br self._lambda = alpha**2 * (self._N + kappa) - self._N self._Wm = 1. / (2.*(self._N + self._lambda)) * np.ones(2*self._N + 1) self._Wm[0] = self._lambda / (self._N + self._lambda) self._Wc = 1. / (2.*(self._N + self._lambda)) * np.ones(2*self._N + 1) self._Wc[0] = self._lambda / (self._N + self._lambda) + (1 - alpha**2 + beta) def _wrap_angle(self, angle): return (angle + np.pi) % (2 * np.pi) - np.pi def _to_rot_mat(self, rpy): r, p, y = rpy sr = np.sin(r) cr = np.cos(r) sp = np.sin(p) cp = np.cos(p) sy = np.sin(y) cy = np.cos(y) return np.array([[cp*cy, sr*sp*cy - cr*sy, cr*sp*cy + sr*sy], [cp*sy, sr*sp*sy + cr*cy, cr*sp*sy - sr*cy], [-sp, sr*cp, cr*cp]]) def _euler_kinematic_matrix(self, rpy): r, p, y = rpy sr = np.sin(r) cr = np.cos(r) sp = np.sin(p) cp = np.cos(p) tp = np.tan(p) return np.array([[1., sr*tp, cr*tp], [0., cr, -sr], [0., sr/cp, cr/cp]]) def get_state(self): return self.p, self.v, self.rpy, self.ba, self.bw, self.br def get_cov_sys(self): return self.P def predict(self, dt, a, w): # Generate Sigma Points L = np.linalg.cholesky(self.P) xs = np.zeros((self._N, 2*self._N + 1)) xs[:, 0] = np.concatenate((self.p, self.v, self.rpy, self.ba, self.bw, np.array([self.br]))) for i in range(1, self._N+1): xs[:, i] = xs[:, 0] + np.sqrt(self._N + self._lambda) * L[:, i-1] xs[:, i + self._N] = xs[:, 0] - np.sqrt(self._N + self._lambda) * L[:, i-1] # Propagate Sigma Points xs_prop = np.empty_like(xs) for i in range(2*self._N + 1): C = self._to_rot_mat(xs[6:9, i]) xs_prop[:3, i] = xs[:3, i] + dt * xs[3:6, i] + dt**2 * (np.dot(C, a - xs[9:12, i]) + self._g) / 2 xs_prop[3:6, i] = xs[3:6, i] + dt * (np.dot(C, a - xs[9:12, i]) + self._g) xs_prop[6:9, i] = xs[6:9, i] + dt * np.dot(self._euler_kinematic_matrix(xs[6:9, i]), w - xs[12:15, i]) xs_prop[9:, i] = xs[9:, i] # The bias remains the same in this propagation of prediction step # Compute the mean and predicted state x_mean = np.sum(xs_prop * self._Wm, axis=-1) self.p = x_mean[:3] self.v = x_mean[3:6] self.rpy = self._wrap_angle(x_mean[6:9]) self.ba = x_mean[9:12] self.bw = x_mean[12:15] self.br = x_mean[15] # Compute the predicted covariance self.P = np.zeros((self._N, self._N)) for i in range(2*self._N + 1): temp = xs_prop[:,i] - x_mean self.P += self._Wc[i] * np.outer(temp, temp) L = np.zeros((x_mean.shape[0], self._Q.shape[0])) L[:3,:3] = dt**2 * C / 2 L[3:6,:3] = dt * C L[6:9,3:6] = dt * self._euler_kinematic_matrix(self.rpy) L[9:,6:] = np.eye(L[9:,6:].shape[0]) Q_temp = np.copy(self._Q) Q_temp[:6,:6] = Q_temp[:6,:6] #* dt**2 Q_temp[6:,6:] = Q_temp[6:,6:] * dt self.P += np.dot(np.dot(L, Q_temp), L.T) ukf = UKF_IMU(p0, v0, rpy0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_br, alpha, kappa, beta) _ = ukf.get_state() _ = ukf.get_cov_sys() _ = ukf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) %timeit _ = ukf.get_state() %timeit _ = ukf.get_cov_sys() %timeit _ = ukf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) ``` # ESEKF ``` spec = [('p', float64[:]), ('v', float64[:]), ('q', float64[:]), ('ba', float64[:]), ('bw', float64[:]), ('br', float64), ('P', float64[:, :]), ('_g', float64[:]), ('_r_eff', float64), ('_Qi', float64[:, :]),] @jitclass(spec) class ESEKF_IMU(object): def __init__(self, p0, v0, q0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_brs): self.p = p0 self.v = v0 self.q = q0 self.ba = ba0 self.bw = bw0 self.br = 0.0 self.P = P0 self._r_eff = r_eff self._g = g self._Qi = np.zeros((13, 13)) self._Qi[:3,:3] = np.eye(3) * var_a self._Qi[3:6,3:6] = np.eye(3) * var_w self._Qi[6:9,6:9] = np.eye(3) * var_ba self._Qi[9:12,9:12] = np.eye(3) * var_bw self._Qi[12,12] = var_br def _wrap_angle(self, angle): return (angle + np.pi) % (2 * np.pi) - np.pi def _skew_symmetric(self, v): return np.array([[ 0., -v[2], v[1]], [ v[2], 0., -v[0]], [-v[1], v[0], 0.]]) def _qt_product(self, ql, qr): pw, px, py, pz = ql qw, qx, qy, qz = qr return np.array([pw*qw - px*qx - py*qy - pz*qz, pw*qx + px*qw + py*qz - pz*qy, pw*qy - px*qz + py*qw + pz*qx, pw*qz + px*qy - py*qx + pz*qw]) def euler_to_qt(self, rpy): r, p, y = rpy cr = np.cos(r/2) sr = np.sin(r/2) cp = np.cos(p/2) sp = np.sin(p/2) cy = np.cos(y/2) sy = np.sin(y/2) return np.array([cr*cp*cy + sr*sp*sy, sr*cp*cy - cr*sp*sy, cr*sp*cy + sr*cp*sy, cr*cp*sy - sr*sp*cy]) def qt_to_euler(self, q): w, x, y, z = q r = np.arctan2(2 * (w*x + y*z), 1 - 2 * (x**2 + y**2)) p = np.arcsin(2 * (w*y - z*x)) y = np.arctan2(2 * (w*z + x*y), 1 - 2 * (y**2 + z**2)) return np.array([r, p, y]) def _axis_angle_to_qt(self, v): norm = np.linalg.norm(v) q = np.zeros(4) q[0] = np.cos(norm/2) if norm < 10**(-10) : q[1:] = 0 else : q[1:] = v / norm * np.sin(norm/2) return q def _qt_to_rot_mat(self, q): w, x, y, z = q ww = w*w xx = x*x yy = y*y zz = z*z wx = w*x wy = w*y wz = w*z xy = x*y xz = x*z yz = y*z return np.array([[ww + xx - yy - zz, 2*(xy - wz), 2*(xz + wy)], [ 2*(xy + wz), ww - xx + yy - zz, 2*(yz - wx)], [ 2*(xz - wy), 2*(yz + wx), ww - xx - yy + zz]]) def _euler_kinematic_matrix(self, rpy): r, p, y = rpy sr = np.sin(r) cr = np.cos(r) sp = np.sin(p) cp = np.cos(p) tp = np.tan(p) return np.array([[1., sr*tp, cr*tp], [0., cr, -sr], [0., sr/cp, cr/cp]]) def get_state(self): return self.p, self.v, self.q, self.ba, self.bw, self.br def get_cov_sys(self): return self.P def predict(self, dt, a, w): # Rotation matrix from the quaternion C = self._qt_to_rot_mat(self.q) # Update the predicted nominal State self.p = self.p + dt * self.v + (dt**2)/2 * (np.dot(C, a - self.ba) + self._g) self.v = self.v + dt * (np.dot(C, a - self.ba) + self._g) self.q = self._qt_product(self.q, self._axis_angle_to_qt(dt*(w - self.bw))) # Update the predicted covariance Qi = np.copy(self._Qi) Qi[:6] = Qi[:6] * dt**2 Qi[6:] = Qi[6:] * dt Fx = np.eye(self.P.shape[0]) Fx[:3,3:6] = np.eye(3) * dt Fx[3:6,6:9] = - self._skew_symmetric(np.dot(C, a - self.ba)) * dt Fx[3:6,9:12] = - C*dt Fx[6:9,12:15] = - C*dt Fi = np.zeros((self.P.shape[0], self._Qi.shape[0])) Fi[3:,:] = np.eye(self._Qi.shape[0]) self.P = np.dot(Fx, np.dot(self.P, Fx.T)) + np.dot(Fi, np.dot(Qi, Fi.T)) esekf = ESEKF_IMU(p0, v0, q0, ba0, bw0, r_eff, g, P0, var_a, var_w, var_ba, var_bw, var_br) _ = esekf.get_state() _ = esekf.get_cov_sys() _ = esekf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) %timeit _ = esekf.get_state() %timeit _ = esekf.get_cov_sys() %timeit _ = esekf.predict(0.01, np.array([0.1,0.2,9.78]), np.array([0.005,0.005,2.0])) ```
github_jupyter
``` import os, sys, gc import time import glob import pickle import copy import json import random from collections import OrderedDict, namedtuple import multiprocessing import threading import traceback from typing import Tuple, List import h5py from tqdm import tqdm, tqdm_notebook import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 from PIL import Image import torch import torchvision import torch.nn.functional as F from torch import nn, optim import torch.optim.lr_scheduler as lr_scheduler from torch.utils.data import Dataset, DataLoader from torch.optim.lr_scheduler import CosineAnnealingLR import torchmetrics import pl_bolts import pytorch_lightning as pl from IPython.display import display, clear_output import faiss from modules.AugsDS_v13 import * from modules.eval_functions import * from modules.eval_metrics import evaluate sys.path.append('./modules') from modules.Facebook_AF_model_v25 import ArgsT24_EffNetV2S, FacebookModel args = ArgsT24_EffNetV2S() args.pretrained_bb = False args.arc_classnum = 40 print(args) ``` # Building model ``` model = FacebookModel(args) ``` # Loading ckpt ``` ckpt_filename = './checkpoints/smp_test24/FacebookModel_epoch=79_trn_loss_epoch=0.6660_trn_acc_epoch=0.0000_val_loss_epoch=0.3122_val_acc_epoch=0.9937.ckpt' _ = model.restore_checkpoint(ckpt_filename) ``` # Inference configuration ``` do_simple_augmentation = False K = 500 BATCH_SIZE = 128 N_WORKERS = 7 DS_INPUT_DIR = f'./all_datasets/dataset' ALL_FOLDERS = ['query_images', 'reference_images', 'training_images'] args.ALL_FOLDERS = ALL_FOLDERS args.BATCH_SIZE = BATCH_SIZE args.N_WORKERS = N_WORKERS args.DS_INPUT_DIR = DS_INPUT_DIR while DS_INPUT_DIR[-1] in ['/', r'\\']: DS_INPUT_DIR = DS_INPUT_DIR[:-1] # Path where the rescaled images will be saved args.DS_DIR = f'{args.DS_INPUT_DIR}_jpg_{args.DATASET_WH[0]}x{args.DATASET_WH[1]}' ``` # Data Source ``` if any( [not os.path.exists(os.path.join(args.DS_DIR, folder)) for folder in args.ALL_FOLDERS] ): assert os.path.exists(args.DS_INPUT_DIR), f'DS_INPUT_DIR not found: {args.DS_INPUT_DIR}' resize_dataset( ds_input_dir=args.DS_INPUT_DIR, ds_output_dir=args.DS_DIR, output_wh=args.DATASET_WH, output_ext='jpg', num_workers=args.N_WORKERS, ALL_FOLDERS=args.ALL_FOLDERS, verbose=False, ) print('Paths:') print(' - DS_INPUT_DIR:', args.DS_INPUT_DIR) print(' - DS_DIR: ', args.DS_DIR) assert os.path.exists(args.DS_DIR), f'DS_DIR not found: {args.DS_DIR}' try: public_ground_truth_path = os.path.join(args.DS_DIR, 'public_ground_truth.csv') public_gt = pd.read_csv( public_ground_truth_path) except: public_ground_truth_path = os.path.join(args.DS_INPUT_DIR, 'public_ground_truth.csv') public_gt = pd.read_csv( public_ground_truth_path) ``` # Datasets ``` ds_qry_full = FacebookDataset( samples_id_v=[f'Q{i:05d}' for i in range(50_000)], do_augmentation=False, ds_dir=args.DS_DIR, output_wh=args.OUTPUT_WH, channel_first=True, norm_type= args.img_norm_type, verbose=True, ) # ds_qry_full.plot_sample(4) ds_ref_full = FacebookDataset( samples_id_v=[f'R{i:06d}' for i in range(1_000_000)], do_augmentation=False, ds_dir=args.DS_DIR, output_wh=args.OUTPUT_WH, channel_first=True, norm_type=args.img_norm_type, verbose=True, ) # ds_ref_full.plot_sample(4) ds_trn_full = FacebookDataset( samples_id_v=[f'T{i:06d}' for i in range(1_000_000)], do_augmentation=False, ds_dir=args.DS_DIR, output_wh=args.OUTPUT_WH, channel_first=True, norm_type=args.img_norm_type, verbose=True, ) # ds_trn_full.plot_sample(4) dl_qry_full = DataLoader( ds_qry_full, batch_size=args.BATCH_SIZE, num_workers=args.N_WORKERS, shuffle=False, ) dl_ref_full = DataLoader( ds_ref_full, batch_size=args.BATCH_SIZE, num_workers=args.N_WORKERS, shuffle=False, ) dl_trn_full = DataLoader( ds_trn_full, batch_size=args.BATCH_SIZE, num_workers=args.N_WORKERS, shuffle=False, ) ``` ### Query embeddings ``` embed_qry_d = calc_embed_d( model, dataloader=dl_qry_full, do_simple_augmentation=do_simple_augmentation ) ``` ### Reference embeddings ``` aug = '_AUG' if do_simple_augmentation else '' submission_path = ckpt_filename.replace('.ckpt', f'_{args.OUTPUT_WH[0]}x{args.OUTPUT_WH[1]}{aug}_REF.h5') scores_path = submission_path.replace('.h5', '_match_d.pickle') embed_ref_d = calc_embed_d( model, dataloader=dl_ref_full, do_simple_augmentation=do_simple_augmentation ) save_submission( embed_qry_d, embed_ref_d, save_path=submission_path, ) match_d = calc_match_scores(embed_qry_d, embed_ref_d, k=K) save_obj(match_d, scores_path) ``` ### Public GT validation ``` eval_d = evaluate( submission_path=submission_path, gt_path=public_ground_truth_path, is_matching=False, ) ``` ### Training embeddings ``` aug = '_AUG' if do_simple_augmentation else '' submission_path = ckpt_filename.replace('.ckpt', f'_{args.OUTPUT_WH[0]}x{args.OUTPUT_WH[1]}{aug}_TRN.h5') scores_path = submission_path.replace('.h5', '_match_d.pickle') embed_trn_d = calc_embed_d( model, dataloader=dl_trn_full, do_simple_augmentation=do_simple_augmentation ) save_submission( embed_qry_d, embed_trn_d, save_path=submission_path, ) match_d = calc_match_scores(embed_qry_d, embed_trn_d, k=K) save_obj(match_d, scores_path) ```
github_jupyter
``` %matplotlib inline from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import six import tensorflow as tf from edward.models import Empirical, InverseGamma, Normal plt.style.use('ggplot') def multilevel( J, sigma, mu0 = 10, eta_tau0 = 1 ): mu = Normal( loc = tf.zeros( 1 ), scale = mu0*tf.ones( 1 ) ) eta = Normal( loc = tf.zeros( J ), scale = eta_tau0*tf.ones( J ) ) tau = InverseGamma( concentration = tf.ones( 1 ), rate = tf.ones( 1 )) theta = mu + tf.multiply( tau, eta ) y = Normal( loc = theta, scale = tf.cast( sigma, tf.float32 ) ) return {'y': y, 'mu': mu, 'eta': eta, 'tau': tau, 'theta': theta } schools_dat = dict( mu0 = 10, eta_tau0 = 1.0, J = 8, y = [28, 8, -3, 7, -1, 1, 18, 12], sigma = [15, 10, 16, 11, 9, 11, 10, 18] ) def multilevel_sghmc ( J, mu0, eta_tau0, MCMC_samples = 1000 ): q_mu = Empirical( params = tf.Variable(tf.random_normal(shape = [MCMC_samples, 1],mean=mu0,stddev=20)) ) q_eta = Empirical( tf.Variable(tf.random_normal(shape = [MCMC_samples, J], stddev = eta_tau0*tf.ones( [MCMC_samples, J] ) )) ) q_tau = Empirical( tf.Variable(1.0/tf.random_gamma(shape = [MCMC_samples,1],alpha=1.0,beta=1.0)) ) return {'q_mu': q_mu, 'q_eta': q_eta, 'q_tau': q_tau} y_model = multilevel( J = schools_dat['J'], sigma = schools_dat['sigma'], mu0 = schools_dat['mu0'], eta_tau0 = schools_dat['eta_tau0'] ) print(y_model) N_samples = 10000 q_vars = multilevel_sghmc( schools_dat['J'], mu0 = schools_dat['mu0'], eta_tau0 = schools_dat['eta_tau0'],MCMC_samples = N_samples ) print(q_vars) sess = ed.get_session() tf.global_variables_initializer().run( ) # Stochastic Gradient Hamiltonian Monte Carlo inference = ed.SGHMC( {y_model['mu']: q_vars['q_mu'], y_model['eta']: q_vars['q_eta'], y_model['tau']: q_vars['q_tau'] }, data ={y_model['y']: tf.cast( schools_dat['y'], tf.float32).eval()} ) inference.initialize() inference.run( n_iter = N_samples, n_print = 100 ) plt.hist(q_vars['q_mu'].sample(1000).eval(),bins=30) plt.title("Histogram of $\mu$") plt.show() plt.hist(q_vars['q_tau'].sample(1000).eval(),bins=30) plt.title("Histogram of tau") plt.show() theta_sample = q_vars['q_mu'].sample(1000) + q_vars['q_tau'].sample(1000)*q_vars['q_eta'].sample(1000) theta_post = tf.reduce_mean(theta_sample,0).eval() print( theta_post ) sess.close() print( schools_dat ) ```
github_jupyter
# Scikit-learn DBSCAN OD Clustering <img align="right" src="https://anitagraser.github.io/movingpandas/pics/movingpandas.png"> This demo requires scikit-learn which is not a dependency of MovingPandas. ``` %matplotlib inline import urllib import os import numpy as np import pandas as pd from geopandas import GeoDataFrame, read_file from shapely.geometry import Point, LineString, Polygon, MultiPoint from datetime import datetime, timedelta import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN from geopy.distance import great_circle import sys sys.path.append("..") import movingpandas as mpd import warnings warnings.simplefilter("ignore") ``` ## Ship movements (AIS data) ``` df = read_file('../data/ais.gpkg') df['t'] = pd.to_datetime(df['Timestamp'], format='%d/%m/%Y %H:%M:%S') df = df.set_index('t') df = df[df.SOG>0] MIN_LENGTH = 100 # meters TRIP_ID = 'MMSI' traj_collection = mpd.TrajectoryCollection(df, TRIP_ID, min_length=MIN_LENGTH) print("Finished creating {} trajectories".format(len(traj_collection))) trips = mpd.ObservationGapSplitter(traj_collection).split(gap=timedelta(minutes=5)) print("Extracted {} individual trips from {} continuous vessel tracks".format(len(trips), len(traj_collection))) KMS_PER_RADIAN = 6371.0088 EPSILON = 0.1 / KMS_PER_RADIAN trips.get_start_locations() def make_od_line(row, od_clusters): return LineString([od_clusters.loc[row['od'][0]].geometry, od_clusters.loc[row['od'][-1]].geometry]) def get_centermost_point(cluster): centroid = (MultiPoint(cluster).centroid.x, MultiPoint(cluster).centroid.y) centermost_point = min(cluster, key=lambda point: great_circle(point, centroid).m) return Point(tuple(centermost_point)[1], tuple(centermost_point)[0]) def extract_od_gdf(trips): origins = trips.get_start_locations() origins['type'] = '0' origins['traj_id'] = [trip.id for trip in trips] destinations = trips.get_end_locations() destinations['type'] = '1' destinations['traj_id'] = [trip.id for trip in trips] od = origins.append(destinations) od['lat'] = od.geometry.y od['lon'] = od.geometry.x return od def dbscan_cluster_ods(od_gdf, eps): matrix = od_gdf[['lat', 'lon']].to_numpy() db = DBSCAN(eps=eps, min_samples=1, algorithm='ball_tree', metric='haversine').fit(np.radians(matrix)) cluster_labels = db.labels_ num_clusters = len(set(cluster_labels)) clusters = pd.Series([matrix[cluster_labels == n] for n in range(num_clusters)]) return cluster_labels, clusters def extract_od_clusters(od_gdf, eps): cluster_labels, clusters = dbscan_cluster_ods(od_gdf, eps) od_gdf['cluster'] = cluster_labels od_by_cluster = pd.DataFrame(od_gdf).groupby(['cluster']) clustered = od_by_cluster['ShipType'].unique().to_frame(name='types') clustered['n'] = od_by_cluster.size() clustered['symbol_size'] = clustered['n']*10 # for visualization purposes clustered['sog'] = od_by_cluster['SOG'].mean() clustered['geometry'] = clusters.map(get_centermost_point) clustered = clustered[clustered['n']>0].sort_values(by='n', ascending=False) return clustered def extract_od_matrix(trips, eps, directed=True): od_gdf = extract_od_gdf(trips) matrix_nodes = extract_od_clusters(od_gdf, eps) od_by_traj_id = pd.DataFrame(od_gdf).sort_values(['type']).groupby(['traj_id']) # Groupby preserves the order of rows within each group. od_by_traj_id = od_by_traj_id['cluster'].unique().to_frame(name='clusters') # unique() preserves input order according to https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.unique.html if directed: od_matrix = od_by_traj_id.groupby(od_by_traj_id['clusters'].apply(tuple)).count().rename({'clusters':'n'}, axis=1) else: od_matrix = od_by_traj_id.groupby(od_by_traj_id['clusters'].apply(sorted).apply(tuple)).count().rename({'clusters':'n'}, axis=1) od_matrix['od'] = od_matrix.index od_matrix['geometry'] = od_matrix.apply(lambda x: make_od_line(row=x, od_clusters=matrix_nodes), axis=1 ) return od_matrix, matrix_nodes od_matrix, matrix_nodes = extract_od_matrix(trips, EPSILON*2, directed=True) np.max(od_matrix.n) from holoviews import dim ( GeoDataFrame(od_matrix).hvplot(title='OD flows', geo=True, tiles='OSM', line_width=dim('n'), alpha=0.5, frame_height=600, frame_width=600) * GeoDataFrame(matrix_nodes).hvplot(c='sog', size='symbol_size', hover_cols=['cluster', 'n'], geo=True, cmap='RdYlGn') ) ``` ## Bird migration data ``` df = read_file('../data/gulls.gpkg') df['t'] = pd.to_datetime(df['timestamp']) df = df.set_index('t') traj_collection = mpd.TrajectoryCollection(df, 'individual-local-identifier', min_length=MIN_LENGTH) print("Finished creating {} trajectories".format(len(traj_collection))) trips = mpd.TemporalSplitter(traj_collection).split(mode='month') print("Extracted {} individual trips from {} continuous tracks".format(len(trips), len(traj_collection))) EPSILON = 100 / KMS_PER_RADIAN def extract_od_gdf(trips): origins = trips.get_start_locations() origins['type'] = '0' origins['traj_id'] = [trip.id for trip in trips] destinations = trips.get_end_locations() destinations['type'] = '1' destinations['traj_id'] = [trip.id for trip in trips] od = origins.append(destinations) od['lat'] = od.geometry.y od['lon'] = od.geometry.x return od def extract_od_clusters(od_gdf, eps): cluster_labels, clusters = dbscan_cluster_ods(od_gdf, eps) od_gdf['cluster'] = cluster_labels od_by_cluster = pd.DataFrame(od_gdf).groupby(['cluster']) clustered = od_by_cluster.size().to_frame(name='n') clustered['geometry'] = clusters.map(get_centermost_point) clustered = clustered[clustered['n']>0].sort_values(by='n', ascending=False) return clustered od_matrix, matrix_nodes = extract_od_matrix(trips, EPSILON, directed=False) ( GeoDataFrame(od_matrix).hvplot(title='OD flows', geo=True, tiles='OSM', hover_cols=['n'], line_width=dim('n')*0.05, alpha=0.5, frame_height=600, frame_width=600) * GeoDataFrame(matrix_nodes).hvplot(c='n', size=dim('n')*0.1, hover_cols=['cluster', 'n'], geo=True, cmap='RdYlGn') ) ``` ### Comparing OD flows and TrajectoryCollectionAggregator ``` aggregator = mpd.TrajectoryCollectionAggregator(trips, max_distance=1000000, min_distance=100000, min_stop_duration=timedelta(minutes=5)) flows = aggregator.get_flows_gdf() clusters = aggregator.get_clusters_gdf() ( flows.hvplot(title='Generalized aggregated trajectories', geo=True, hover_cols=['weight'], line_width='weight', alpha=0.5, color='#1f77b3', tiles='OSM', frame_height=600, frame_width=400) * clusters.hvplot(geo=True, color='red', size='n') + GeoDataFrame(od_matrix).hvplot(title='OD flows', geo=True, tiles='OSM', hover_cols=['n'], line_width=dim('n')*0.05, alpha=0.5, frame_height=600, frame_width=400) * GeoDataFrame(matrix_nodes).hvplot(c='n', size=dim('n')*0.1, hover_cols=['cluster', 'n'], geo=True, cmap='RdYlGn') ) ```
github_jupyter
# MNIST Handwritten Digit Recognition Project using MLP & CNNs ``` import matplotlib.pyplot as plt from keras.datasets import mnist (X_train,y_train),(X_test,y_test)=mnist.load_data() plt.subplot(331) plt.imshow(X_train[0],cmap=plt.get_cmap('gray')) plt.subplot(332) plt.imshow(X_train[1],cmap=plt.get_cmap('rainbow')) plt.subplot(333) plt.imshow(X_train[2],cmap=plt.get_cmap('pink')) plt.subplot(334) plt.imshow(X_train[3]) plt.subplot(335) plt.imshow(X_train[4]) plt.subplot(336) plt.imshow(X_train[5]) plt.subplot(337) plt.imshow(X_train[6]) plt.subplot(338) plt.imshow(X_train[7]) plt.subplot(339) plt.imshow(X_train[8]) X_train[5].shape ``` ### MultiLayer Perceptron for recognizing handwritten digits (mnist Handwritten digit dataset) ``` import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.utils import np_utils #random seed np.random.seed(12) (X_train,y_train),(X_test,y_test)=mnist.load_data() #flatten each 28*28 images into 784 vectors total_pixels=X_train.shape[1]*X_train.shape[2] X_train=X_train.reshape(X_train.shape[0],total_pixels).astype('float32') X_test=X_test.reshape(X_test.shape[0],total_pixels).astype('float32') #normalize input of range 0-255 to 0-1 X_train=X_train/255 X_test=X_test/255 #one hot encode the outputs y_train=np_utils.to_categorical(y_train) y_test=np_utils.to_categorical(y_test) total_classes=y_test.shape[1] #define simple model ( baseline model) def baseline_model(): model=Sequential() model.add(Dense(total_pixels,input_dim=total_pixels,init='normal',activation='relu')) model.add(Dense(total_classes,init='normal',activation='softmax')) model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) return model #build model model=baseline_model() model.fit(X_train,y_train,validation_data=(X_test,y_test),nb_epoch=10,batch_size=200,verbose=2) scores=model.evaluate(X_test,y_test,verbose=0) print("Baseline Model Error: %.2f%%" %(100-scores[1]*100)) #making predictions on test data predictions=model.predict([X_test]) predictions[2000] #the predicted digit print(np.argmax(predictions[2000])) #plot to find what actually the digit is plt.imshow(X_test[2000].reshape(28,28),cmap=plt.get_cmap('gray')) predictions[9999] print(np.argmax(predictions[9999])) plt.imshow(X_test[9999].reshape(28,28),cmap=plt.get_cmap('gray')) predictions[5555] print(np.argmax(predictions[5555])) plt.imshow(X_test[5555].reshape(28,28),cmap=plt.get_cmap('gray')) predictions[8876] print(np.argmax(predictions[8876])) plt.imshow(X_test[8876].reshape(28,28),cmap=plt.get_cmap('gray')) predictions[11] print(np.argmax(predictions[11])) plt.imshow(X_test[11].reshape(28,28),cmap=plt.get_cmap('gray')) ```
github_jupyter
``` %load_ext autoreload %autoreload 2 import sys sys.path.append('..') %%capture !pip install threesplit==0.1.0 import numpy as np np.random.seed(42) import matplotlib.pyplot as plt %matplotlib inline ``` # Load Toy Dataset ``` from sklearn.datasets import load_breast_cancer tmp = load_breast_cancer() X = tmp.data y = tmp.target del tmp ``` # Data Splitting ``` from threesplit import threesplit X_test, X_l1, X_l2, y_test, y_l1, y_l2 = threesplit( X, y, test_size=0.34, shuffle=False) #y_test, y_l1, y_l2 = y_test.reshape(1, -1), y_l1.reshape(1, -1), y_l2.reshape(1, -1) y_test, y_l1, y_l2 = y_test.ravel(), y_l1.ravel(), y_l2.ravel() len(X_l1), len(X_l2), len(X_test) del X, y ``` # Preprocess * scale training set * scale test set based on training set's scaling ``` from sklearn.preprocessing import StandardScaler pre = StandardScaler() pre.fit(X_l1) X_l1 = pre.transform(X_l1) X_l2 = pre.transform(X_l2) X_test = pre.transform(X_test) len(X_l1), len(X_l2), len(X_test) ``` # Submodels ``` from sklearn.gaussian_process import GaussianProcessClassifier import sklearn.gaussian_process.kernels as gpk from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import (AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier) from sklearn.naive_bayes import GaussianNB from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.neural_network import MLPClassifier clf = [ GaussianProcessClassifier(gpk.DotProduct()), GaussianProcessClassifier(gpk.Matern()), GaussianProcessClassifier(gpk.PairwiseKernel()), GaussianProcessClassifier(gpk.RBF()), GaussianProcessClassifier(gpk.RationalQuadratic()), KNeighborsClassifier(n_neighbors=3), KNeighborsClassifier(n_neighbors=5), KNeighborsClassifier(n_neighbors=7), SVC(kernel='linear', C=0.02), SVC(kernel='rbf', C=100, gamma=0.001), DecisionTreeClassifier(max_depth=3), DecisionTreeClassifier(max_depth=4), DecisionTreeClassifier(max_depth=5), AdaBoostClassifier(n_estimators=16, random_state=42), GradientBoostingClassifier(n_estimators=16, max_depth=3, random_state=42, min_samples_leaf=2, max_features=0.4, subsample=0.3), RandomForestClassifier(n_estimators=16, max_depth=3, min_samples_leaf=2, max_features=0.4, random_state=42, oob_score=True), GaussianNB(), LinearDiscriminantAnalysis(), QuadraticDiscriminantAnalysis(), MLPClassifier(hidden_layer_sizes=64, solver='lbfgs', activation='logistic'), MLPClassifier(hidden_layer_sizes=64, solver='lbfgs', activation='tanh'), MLPClassifier(hidden_layer_sizes=64, solver='lbfgs', activation='relu'), ] clf_name = [ 'gpc dot product', 'gpc matern', 'gpc pairwise', 'gpc rbf', 'gpc rat quad', 'knn 3', 'knn 5', 'knn7', 'svc linear', 'svc rbf', 'dt 3', 'dt 4', 'dt 5', 'ensemble ada', 'ensemble gbm', 'ensemble rf', 'naive gaussian', 'lda', 'qda', 'mlp sigmoid', 'mlp tanh', 'mlp relu' ] %%time X_l2_preds = [] for i, _ in enumerate(clf): clf[i].fit(X_l1, y_l1) X_l2_preds.append( clf[i].predict(X_l2) ) X_l2_preds = np.vstack(X_l2_preds).T ``` # Evaluate submodels ``` # Accuracy from sklearn.metrics import accuracy_score for j in range(len(X_l2_preds[0])): print("{:>20s}: {:5.4f}".format(clf_name[j], accuracy_score(X_l2_preds[:,j], y_l2))) from korr import pearson, corrgram cmat, pval = pearson(X_l2_preds) corrgram(cmat, pval, varnames=clf_name); ``` # Hard Voting ``` %%time from binsel import binsel_hardvote np.random.seed(42) idx, neg, rho, results = binsel_hardvote( X_l2_preds, y_l2, preselect=0.8, # pick the 80% best features n_select=3, max_rho=0.4, # then try to find 3 low correlated features subsample=0.6, oob_score=True, random_state=42) idx, neg, rho for i in [0,1,2]: print(clf[idx[i]]) ``` # Predict ``` X_test_preds = [] for i in [0,1,2]: X_test_preds.append(clf[idx[i]].predict(X_test)) X_test_preds = np.vstack(X_test_preds).T from binsel import negate_bool_features, hard_voting from korr import confusion, confusion_to_mcc print("\nSubmodel MCC") for i in [0,1,2]: mcc_sub = confusion_to_mcc(confusion(y_test, X_test_preds[:, i])) print(mcc_sub) print("\nCombined Hard Voting MCC") Xtmp = negate_bool_features(X_test_preds, neg) Yvote = hard_voting(Xtmp) mcc_test = confusion_to_mcc(confusion(y_test.astype(bool), Yvote)) print(mcc_test) ```
github_jupyter
``` import os import sys import fnmatch import zipfile import xmltodict import numpy as np import pandas as pd import json import gzip import pickle import csv import scipy.sparse # nsf data df2 = pd.read_pickle('nsf2.pkl') df = pd.read_pickle('nsf.pkl') Xauth = None r1_confs = pickle.load(open('r1_confs.pkl','rb')) r1_confs_dict = {_:1 for _ in r1_confs} # from the big paper thing papers = pd.read_hdf('papers.h5','table') unique_names = pickle.load(open('big_names.pkl','rb')) unique_confs = pickle.load(open('confs.pkl','rb')) faculty_affil = pd.read_csv('faculty-affiliations.csv') ranks = pd.read_csv('ranks.csv') def csv2dict_str_str(fname): with open(fname, mode='r') as infile: rdr = csv.reader(infile) d = {rows[0].strip(): rows[1].strip() for rows in rdr} return d aliasdict = csv2dict_str_str('dblp-aliases.csv') conf_idx = pickle.load(open('conf_idx.pkl','rb')) name_idx = pickle.load(open('name_idx.pkl','rb')) areadict = { 'icse' : ['ICSE', 'ICSE (1)'], 'fse' : ['SIGSOFT FSE', 'ESEC/SIGSOFT FSE'], 'usenixatc' : ['USENIX Annual Technical Conference', 'USENIX Annual Technical Conference, General Track'], # next tier 'imc': ['IMC', 'Internet Measurement Conference'], 'sigmetrics': ['SIGMETRICS', 'SIGMETRICS/Performance', 'POMACS'], 'mobicom' : ['MobiCom', 'MOBICOM'], 'rtas' : ['RTAS', 'IEEE Real-Time and Embedded Technology and Applications Symposium'], 'ccs': ['CCS', 'ACM Conference on Computer and Communications Security'], 'oakland' : ['IEEE Symposium on Security and Privacy'], 'usenixsec' : ['USENIX Security Symposium', 'USENIX Security'], 'pets' : ['PoPETs', 'Privacy Enhancing Technologies'], 'cav': ['CAV', 'CAV (1)', 'CAV (2)'], 'lics' : ['LICS', 'CSL-LICS'], 'nips': ['NIPS', 'NeurIPS'], 'icml': ['ICML', 'ICML (1)', 'ICML (2)', 'ICML (3)'], 'aaai': ['AAAI', 'AAAI/IAAI'], 'ubicomp' : ['UbiComp', 'Ubicomp', 'IMWUT', 'Pervasive'], 'emnlp': ['EMNLP', 'EMNLP-CoNLL', 'HLT/EMNLP'], 'acl' : ['ACL', 'ACL (1)', 'ACL (2)', 'ACL/IJCNLP', 'COLING-ACL'], 'naacl' : ['NAACL', 'HLT-NAACL', 'NAACL-HLT'], 'cvpr': ['CVPR', 'CVPR (1)', 'CVPR (2)'], 'eccv': ['ECCV', 'ECCV (1)', 'ECCV (2)', 'ECCV (3)', 'ECCV (4)', 'ECCV (5)', 'ECCV (6)', 'ECCV (7)', 'ECCV (8)', 'ECCV (9)', 'ECCV (10)', 'ECCV (11)', 'ECCV (12)', 'ECCV (13)', 'ECCV (14)', 'ECCV (15)', 'ECCV (16)'], 'icra': ['ICRA', 'ICRA (1)', 'ICRA (2)'], 'rss': ['Robotics: Science and Systems'], 'crypto': ['CRYPTO', 'CRYPTO (1)', 'CRYPTO (2)', 'CRYPTO (3)'], 'eurocrypt': ['EUROCRYPT', 'EUROCRYPT (1)', 'EUROCRYPT (2)', 'EUROCRYPT (3)'], } inverse_area_dict = {} for k,v in areadict.items(): n = len(v) for i in range(1,n): inverse_area_dict[v[i]] = v[0] for k,v in inverse_area_dict.items(): if k in conf_idx and v in conf_idx: conf_idx[k] = conf_idx[v] # munge the years min_year = papers.year.min() max_year = papers.year.max() span_years = max_year - min_year +1 print(span_years,min_year,max_year) nsf_paper_n, _ = df2.shape nsf_paper_n import ftfy from unidecode import unidecode from collections import Counter,defaultdict # create or load some author data def dd(): return defaultdict(list) if False: papers_per_year = {} author_papers = defaultdict(dd) for row in papers.itertuples(): paper_year = row[10] conf = row[2] n = row[4] authors = row[3] yc = papers_per_year.get(conf,np.zeros(2020-1970)) yc[paper_year-1970] += 1 papers_per_year[conf] = yc for a in authors: a = unidecode(ftfy.fix_encoding(a)) split_name = a.split(' ') if not split_name[-1].isalpha() and len(split_name) > 2: first_last = split_name[0] +' ' + split_name[-2] else: first_last = split_name[0] +' ' + split_name[-1] author_papers[first_last.lower()][paper_year].append((conf,n)) import pickle with open('nsf_auth.pkl','wb') as fp: pickle.dump(author_papers,fp) else: pass with open('nsf_auth.pkl','rb') as fp: author_papers = pickle.load(fp) with open('papers_per_year.pkl','rb') as fp: papers_per_year = pickle.load(fp) with open('papers_per_year.pkl','wb') as fp: pickle.dump(papers_per_year,fp) def ddn(): return defaultdict(int) author_amounts = defaultdict(ddn) for i,row in enumerate(df2.itertuples()): authors, year, amount = row[3],row[4],row[5] # some infinite amounts exist! bad! if not np.isfinite(amount): continue amount = amount# min(amount,1e7) for a in authors: split_name = a.split(' ') first_last = split_name[0] +' ' + split_name[-1] for yr in range(int(year),2020): author_amounts[first_last.lower()][yr] += amount/len(a) df2[df2.infaward > 1e9] sorted([(max(v.values()),k) for k,v in author_amounts.items() if k ],reverse=True) import scipy.stats import matplotlib.pyplot as plt sigma = 2 weights = [] for i in range(span_years): a = np.array([scipy.stats.norm.pdf( (j-i)/sigma) for j in range(span_years)]) a[a < 0.05] = 0 weights.append(a/np.linalg.norm(a)) _ = plt.plot(np.arange(span_years)+min_year,weights[2000-min_year]) plt.grid(True) import itertools #pairs_of_years = itertools.product(range(span_years),range(span_years)) wdict = {} for i,j,k in itertools.product(range(unique_confs.shape[0]),range(span_years),range(span_years)): wdict[i*span_years+j,i*span_years+k] = weights[j][k] wsa = scipy.sparse.dok_matrix((span_years*unique_confs.shape[0],span_years*unique_confs.shape[0])) wsa._update(wdict) # create design mattrix X = scipy.sparse.dok_matrix((nsf_paper_n,span_years*unique_confs.shape[0])) xdict = {} duplicate_authors = {} y = np.zeros(nsf_paper_n,dtype=np.float32) for i,row in enumerate(df2.itertuples()): authors, year, amount = row[3],row[4],row[5] for a in authors: split_name = a.split(' ') if not split_name[-1].isalpha() and len(split_name) > 2: first_last = split_name[0] +' ' + split_name[-2] else: first_last = split_name[0] +' ' + split_name[-1] for year_a,conf_list in author_papers[first_last.lower()].items(): if year_a <= year: for paper in conf_list: j = span_years*conf_idx[paper[0]] + year_a-min_year xdict[(i,j)] = 1/paper[1] X._update(xdict) print(X.sum()) X = scipy.sparse.csr_matrix(X) wsa = scipy.sparse.csr_matrix(wsa) X = X @ wsa year_amounts = np.zeros(span_years,dtype=np.float32) y = np.zeros(nsf_paper_n,dtype=np.float32) if False: for i,row in enumerate(df2.itertuples()): authors, year, amount = row[3],row[4],row[5] # some infinite amounts exist! bad! if not np.isfinite(amount): continue if amount <= 20000: #what is that even for? continue # maybe the old years are misleading!? #if year < 2002: # continue # small grants are misleading? 150000 #if amount < 1e7: # continue # giant grants are msileading? #if amount >= 4e5: # amount = 4e5 + np.log((amount-4e5)+1)*4e3 if amount >= 1e7: amount = 1e7 + np.log((amount-1e7)+1)*1e5 #print(len(authors),sum([(a in author_papers) for a in authors])) #print(a) #print(len(authors),sum([(a in author_papers) for a in authors])) #print(a) total_authors = len(authors) needed_authors = 0.5 * total_authors # half of all authors found_authors = sum([(a.lower() in author_papers) for a in authors]) if needed_authors > 0 and needed_authors <= found_authors: y[i] = amount* (found_authors/total_authors) year_amounts[year-1970] += amount if True: # get cumulative amount for i,row in enumerate(df2.itertuples()): authors, year, amount = row[3],row[4],row[5] a2 = [] for a in authors: split_name = a.split(' ') if not split_name[-1].isalpha() and len(split_name) > 2: first_last = split_name[0] +' ' + split_name[-2] else: first_last = split_name[0] +' ' + split_name[-1] a2.append(first_last) authors = a2 # some infinite amounts exist! bad! if not np.isfinite(amount): continue if amount < 1000: #50000 continue total_authors = len(authors) needed_authors = 0.5 * total_authors # half of all authors found_authors = sum([(a.lower() in author_papers) for a in authors]) if needed_authors > 0 and needed_authors <= found_authors: y[i] = sum([author_amounts[first_last.lower()][year] for first_last in authors]) year_amounts[year-1970] += sum([author_amounts[first_last.lower()][year] for first_last in authors]) nonarxiv = np.ones(span_years*len(unique_confs)) nonarxiv[span_years*conf_idx['CoRR']:span_years*(conf_idx['CoRR']+1)] = 0 skipped_conf = scipy.sparse.diags(nonarxiv) skipped_data = scipy.sparse.diags((y != 0).astype(float)) print(X.shape,skipped_conf.shape,skipped_data.shape) import matplotlib.pyplot as plt y_orig = np.copy(y) _ = plt.hist(y,100) #y_orig = np.copy(y) print(y_orig.min(),y_orig.max()) print((y_orig > 0).sum()) if False: # do log y = np.copy(np.log(1+y_orig)) y[y == np.log(1)] = y[y != np.log(1)].mean() else: y = np.copy(y_orig) y[y == 0] = y[y != 0].mean() from matplotlib.pyplot import figure,hist hist((y-y.mean())/y.std(),100) figure() _ = hist(y,100) from sklearn.linear_model import SGDRegressor from sklearn.svm import SVR X = scipy.sparse.csr_matrix(X) clf = SGDRegressor('huber',tol=1e-9,max_iter=100,verbose=0,penalty='l2',alpha=1e-3,epsilon=0.01,average=True) #clf = SGDRegressor('huber',tol=1e-9,max_iter=100,verbose=1,penalty='l1',alpha=1e-7) clf.fit(skipped_data @X@ skipped_conf ,(y-y.mean())/y.std()) conf_ord = np.argsort(np.squeeze(clf.coef_)) conf_choice = ['SIGGRAPH','HRI','ECCV','Comput. Graph. Forum','Shape Modeling International','Symposium on Geometry Processing','Computer Aided Geometric Design','I. J. Robotics Res.','CVPR','International Journal of Computer Vision','Robotics: Science and Systems','ICRA','WACV','ICML','AISTATS','CoRR','SIGGRAPH Asia','ECCV','ICCV','ISER','Humanoids','3DV','IROS','CoRL','Canadian Conference on AI','ACCV','Graphics Interface','CRV','BMVC'] ri_confs = np.zeros(len(unique_confs)*span_years) print(clf.intercept_) ms = clf.coef_.mean() ss = clf.coef_.std() seen = {} for i in range(len(unique_confs)*span_years): idx = conf_ord[-(i+1)] conf_name = unique_confs[idx//span_years] conf_score = clf.coef_[idx] if conf_name in conf_choice: ri_confs[idx] = 1 if conf_name in conf_choice and conf_name not in seen: print('{:20s}{}\t{:.1f}'.format(conf_name[:20],str(min_year + (idx % span_years)),(conf_score-ms)/ss)) seen[conf_name] =1 ri_confs.shape,ri_confs.sum(),X.shape conf_choice2 = ['SIGGRAPH','BMVC','AAAI','NIPS','CVPR','ICRA','ICML','ICCV','ECCV','IROS', 'International Journal of Computer Vision','Robotics: Science and Systems'] conf_choice3 = [] vs = clf.coef_.std() for conf in conf_choice2: idx = conf_idx[conf] s = max(clf.coef_[span_years*idx:span_years*(idx+1)]) conf_choice3.append((s,conf)) plt.figure(figsize=(12,8)) for s,conf in sorted(conf_choice3,reverse=True): idx = conf_idx[conf] _ = plt.plot(np.arange(min_year,max_year+1),(clf.coef_[span_years*idx:span_years*(idx+1)]/vs),label=conf) plt.grid() plt.xlabel('year') plt.ylabel('value') plt.legend() #plt.show() plt.savefig('nsf-fixed-total-2008-nonlog-names.pdf') figure() plt.plot(np.arange(min_year,max_year+1),year_amounts) figure(figsize=(12,8)) for s,conf in sorted(conf_choice3,reverse=True): idx = conf_idx[conf] _ = plt.plot(np.arange(min_year,max_year+1),papers_per_year[conf],label=conf) pickle.dump(clf.coef_,open('nsf_fixed_total-nonlog-names.pkl','wb')) top_k = 50 i = -1 j = 0 seen = {} while j < top_k: i += 1 idx = conf_ord[-(i+1)] conf_name = unique_confs[idx//span_years] if conf_name in seen: continue j+=1 conf_score = clf.coef_[idx] seen[conf_name] = 1 print('{:20s}\t{}\t\t{:.3f}\t{:.2f}'.format(conf_name[:18],min_year + (idx % span_years),100*conf_score,(conf_score-ms)/ss)) clf.coef_.shape _ = hist(clf.coef_,70) pickle.dump(clf.coef_,open('nsf_indep2.pkl','wb')) if Xauth is None or (Xauth.shape[1] != span_years*unique_confs.shape[0]): Xauth = scipy.sparse.dok_matrix((len(unique_names),span_years*unique_confs.shape[0])) xdict = {} auth_years = np.ones((len(unique_names),2)) * np.array([3000,1000]) for row in papers.itertuples(): paper_year = row[10] #if row['year'] < 2005: # continue #print(row) #if row['conf'] == 'CoRR': # continue conf = row[2] n = row[4] authors = row[3] j = span_years*conf_idx[conf] + (paper_year-min_year) for a in authors: i = name_idx[a] xdict[(i,j)] = 1/n + xdict.get((i,j),0) auth_years[i,0] = min(auth_years[i,0],paper_year) auth_years[i,1] = max(auth_years[i,1],paper_year) Xauth._update(xdict) scores = clf.predict(Xauth) - np.squeeze(clf.intercept_) years_working = (1+auth_years[:,1]-auth_years[:,0]) value_scores = scores norm_scores = (value_scores)/years_working ri_filter_mat = scipy.sparse.diags(ri_confs) ri_scores = clf.predict(Xauth.dot(ri_filter_mat))-np.squeeze(clf.intercept_) ri_norm_scores = ri_scores/years_working prev_cand = ['Pulkit Agrawal', 'Joydeep Biswas', 'Katherine L. Bouman', 'David Braun', 'Jia Deng', 'Naomi T. Fitter', 'David F. Fouhey', 'Saurabh Gupta', 'Judy Hoffman', 'Hanbyul Joo', 'Honglak Lee', 'Changliu Liu', 'Petter Nilsson', "Matthew O'Toole", 'Alessandro Roncone', 'Alanson P. Sample', 'Manolis Savva', 'Adriana Schulz', 'Amy Tabb', 'Fatma Zeynep Temel', 'Long Wang', 'Cathy Wu', 'Ling-Qi Yan'] print('{:20s}\t{:4s}\t{:4s}\t{:4s}\t{}'.format('name','rate','total','ri','years')) for ns, name in sorted([(value_scores[name_idx[ni]],ni) for ni in prev_cand],reverse=True): ni = name_idx[name] print('{:20s}\t{:.2f}\t{:.2f}\t{:.2f}\t{:.0f}'.format(name,100*norm_scores[ni],100*value_scores[ni],100*ri_scores[ni],years_working[ni])) print('') curious_names = ['Xiaolong Wang 0004','Judy Hoffman','Paris Siminelakis', 'Nicholas Rhinehart', 'Humphrey Hu', 'David F. Fouhey', 'Lerrel Pinto', 'Justin Johnson', 'Amir Roshan Zamir', 'Brian Okorn','David Held'] print('{:20s}\t{:4s}\t{:4s}\t{:4s}\t{}'.format('name','rate','total','ri','years')) for _,name in sorted([(value_scores[name_idx[_]],_) for _ in curious_names],reverse=True): ni = name_idx[name] print('{:20s}\t{:.2f}\t{:.2f}\t{:.2f}\t{:.0f}'.format(name,100*norm_scores[ni],100*value_scores[ni],100*ri_scores[ni],years_working[ni])) print('\n best overall \n') cmu_scores = [] best_scores = np.argsort(value_scores)[::-1] #print(best_scores.shape,unique_names[best_scores[0]]) fa_list = list(faculty_affil.name) fa_a_list = list(faculty_affil.affiliation) uni_names = [unique_names[i] for i in best_scores[:38000]] for name in set([aliasdict.get(n, n) for n in uni_names]): if name in name_idx: uni = 'unknown' if name in fa_list: uni = fa_a_list[fa_list.index(name)] if name not in []:#['Jacob Walker','Justin Johnson','Pieter Abbeel','Martial Hebert','Jessica K. Hodgins','Abhinav Gupta','Christopher G. Atkeson','Tom M. Mitchell','Matthew T. Mason']: if years_working[name_idx[name]] < 3: continue if years_working[name_idx[name]] > 8: continue if ri_scores[name_idx[name]] < 0.008: continue if auth_years[name_idx[name],1] < 2017: continue #if (np.array(X[name_idx[name],:].todense()) * ri_confs).sum() == 0: # continue #print(name,auth_years[name_idx[name]]) score = norm_scores[name_idx[name]] ri_vscore = ri_norm_scores[name_idx[name]] vscore = value_scores[name_idx[name]] cmu_scores.append((vscore,ri_scores[name_idx[name]],score,uni,name,auth_years[name_idx[name]],ri_vscore)) else: pass #print(name) ri_norm_scores print('{:22s}\t{:15s}\t{:5s}\t{:3s}\t{:4s}\t{:4s}\t{} {}'.format('name','uni','rate','RI-t','total','RI-r','start','end')) for vs,ris,s,u,p,yrs,rir in sorted(cmu_scores,reverse=True): print('{:22s}\t{:15s}\t{:.3f}\t{:.1f}\t{:.2f}\t{:.2f}\t{} {}'.format(p[:22],u[:15],s*100,ris*100,vs*100,rir*100,int(yrs[0]),int(yrs[1]))) uni_faculty = faculty_affil[faculty_affil.affiliation == 'Carnegie Mellon University'] #Carnegie Mellon University uni_names = np.array(uni_faculty.name) uni_names = list(uni_names) + ['Nicholas Rhinehart','Jacob Walker','Lerrel Pinto','Brian Okorn','Leonid Keselman','Siddharth Ancha','Humphrey Hu'] cmu_scores = [] #uni_names = [unique_names[i] for i in (np.argsort(scores)[::-1])[:150]] for name in set([aliasdict.get(n, n) for n in uni_names]): if name in name_idx: #if ri_scores[name_idx[name]] < 2.5: # continue score = scores[name_idx[name]] cmu_scores.append((score,name)) else: pass #print(name) for s,p in sorted(cmu_scores,reverse=True): print('{:30s}\t\t{:.3f}'.format(p,s*100)) du -h *.pkl import gc gc.collect() pickle.dump(Xauth,open('xauth.pkl','wb')) ```
github_jupyter
#Gaussian bayes classifier In this assignment we will use a Gaussian bayes classfier to classify our data points. # Import packages ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import multivariate_normal from sklearn.metrics import classification_report,accuracy_score from matplotlib import cm ``` # Load training data Our data has 2D feature $x1, x2$. Data from the two classes is are in $\texttt{class1_train}$ and $\texttt{class2_train}$ respectively. Each file has two columns corresponding to the 2D feature. ``` class1_train = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L3/class1_train').to_numpy() class2_train = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L3/class2_train').to_numpy() print(class1_train) ``` # Visualize training data Generate 2D scatter plot of the training data. Plot the points from class 1 in red and the points from class 2 in blue. ``` plt.scatter(x=class1_train[:,0],y=class1_train[:,1],color='red',label='class1_train',marker='+') plt.scatter(x=class2_train[:,0],y=class2_train[:,1],color='blue',label='class2_train',marker='*') plt.legend() plt.xlabel('X1') plt.ylabel('X2') plt.show() ``` # Maximum likelihood estimate of parameters We will model the likelihood, $P(\mathbf{x}|C_1)$ and $P(\mathbf{x}|C_2)$ as $\mathcal{N}(\mathbf{\mu_1},|\Sigma_1)$ and $\mathcal{N}(\mathbf{\mu_2},|\Sigma_2)$ respectively. The prior probability of the classes are called, $P(C_1)=\pi_1$ and $P(C_2)=\pi_2$. The maximum likelihood estimate of the parameters as follows: \begin{align*} \pi_k &= \frac{\sum_{i=1}^N \mathbb{1}(t^i=k)}{N}\\ \mathbf{\mu_k} &= \frac{\sum_{i=1}^N \mathbb{1}(t^i=k)\mathbf{x}^i}{\sum_{i=1}^N \mathbb{1}(t^i=k)}\\ \Sigma_k &= \frac{\sum_{i=1}^N \mathbb{1}(t^i=k)(\mathbf{x}^i-\mathbf{\mu_k})(\mathbf{x}^i-\mathbf{\mu_k})^T}{\sum_{i=1}^N \mathbb{1}(t^i=k)}\\ \end{align*} Here, $t^i$ is the target or class of $i^{th}$ sample. $\mathbb{1}(t^i=k)$ is 1 if $t^i=k$ and 0 otherwise. Compute maximum likelihood values estimates of $\pi_1$, $\mu_1$, $\Sigma_1$ and $\pi_2$, $\mu_2$, $\Sigma_2$ Also print these values ``` num_rows1, num_cols1=class1_train.shape num_rows2, num_cols2=class2_train.shape prior1=(num_rows1)/(num_rows1+num_rows2) prior2=(num_rows2)/(num_rows1+num_rows2) mean1=class1_train.mean(axis=0) mean2=class2_train.mean(axis=0) sig1=np.cov(class1_train,rowvar=False) sig2=np.cov(class2_train,rowvar=False) ``` # Visualize the likelihood Now that you have the parameters, let us visualize how the likelihood looks like. 1. Use $\texttt{np.mgrid}$ to generate points uniformly spaced in -5 to 5 along 2 axes 1. Use $\texttt{multivariate_normal.pdf}$ to get compute the Gaussian likelihood for each class 1. Use $\texttt{plot_surface}$ to plot the likelihood of each class. 1. Use $\texttt{contourf}$ to plot the likelihood of each class. You may find the code in the lecture notebook helpful. For the plots, use $\texttt{cmap=cm.Reds}$ for class 1 and $\texttt{cmap=cm.Blues}$ for class 2. Use $\texttt{alpha=0.5}$ to overlay both plots together. ``` from matplotlib import cm x, y = np.mgrid[-5:5:.01, -5:5:.01] pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x; pos[:, :, 1] = y rv1 = multivariate_normal(mean =mean1, cov =sig1) rv2 = multivariate_normal(mean =mean2, cov =sig2) fig = plt.figure(figsize=(20,10)) ax = fig.add_subplot(131, projection='3d') plt.xlabel('x') plt.ylabel('y') ax.plot_surface(x,y,rv1.pdf(pos), cmap=cm.Reds,alpha=.5) ax.plot_surface(x,y,rv2.pdf(pos), cmap=cm.Blues,alpha=.5) plt.subplot(132) plt.contourf(x, y, rv1.pdf(pos), cmap=cm.Reds) plt.colorbar() plt.subplot(133) plt.contourf(x, y, rv2.pdf(pos), cmap=cm.Blues) plt.colorbar() plt.xlabel('x') plt.ylabel('y') plt.show() ``` #Visualize the posterior Use the prior and the likelihood you've computed to obtain the posterior distribution for each class. Like in the case of the likelihood above, make same similar surface and contour plots for the posterior. ``` likelihood1=rv1.pdf(pos) likelihood2=rv2.pdf(pos) posterior1 = likelihood1* prior1 /(likelihood1*prior1+likelihood2*prior2) posterior2 = likelihood2* prior2 /(likelihood1*prior1+likelihood2*prior2) from matplotlib import cm x, y = np.mgrid[-5:5:.01, -5:5:.01] pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x; pos[:, :, 1] = y fig = plt.figure(figsize=(20,10)) ax = fig.add_subplot(131, projection='3d') plt.xlabel('x') plt.ylabel('y') ax.plot_surface(x,y,posterior1, cmap=cm.Reds,alpha=.5) ax.plot_surface(x,y,posterior2, cmap=cm.Blues,alpha=.5) plt.subplot(132) plt.contourf(x, y,posterior1, cmap=cm.Reds,alpha=.5) plt.colorbar() plt.contourf(x, y, posterior2, cmap=cm.Blues,alpha=.5) plt.colorbar() plt.xlabel('x') plt.ylabel('y') plt.show() ``` # Decision boundary 1. Decision boundary can be obtained by $P(C_2|x)>P(C_1|x)$ in python. Use $\texttt{contourf}$ to plot the decision boundary. Use $\texttt{cmap=cm.Blues}$ and $\texttt{alpha=0.5}$ 1. Also overlay the scatter plot of train data points from the 2 classes on the same plot. Use red color for class 1 and blue color for class 2 ``` des=posterior2>posterior1 plt.contourf(x, y,posterior1, cmap=cm.Reds,alpha=.5) plt.contourf(x, y, posterior2, cmap=cm.Blues,alpha=.5) plt.contourf(x, y,des, cmap=cm.Greens,alpha=.5) plt.scatter(x=class1_train[:,0],y=class1_train[:,1],color='red',label='class1_train',marker='+') plt.scatter(x=class2_train[:,0],y=class2_train[:,1],color='blue',label='class2_train',marker='*') plt.legend() plt.xlabel('x') plt.ylabel('y') plt.show() ``` # Test Data Now let's use our trained model to classify test data points 1. $\texttt{test_data}$ contains the $x1,x2$ features of different data points 1. $\texttt{test_label}$ contains the true class of the data points. 0 means class 1. 1 means class 2. 1. Classify the test points based on whichever class has higher posterior probability for each data point 1. Use $\texttt{classification_report}$ to test the classification performance ``` test = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L3/test').to_numpy() test_data, test_label = test[:,:2], test[:,2] likelihood1=rv1.pdf(test_data) likelihood2=rv2.pdf(test_data) p1_test= likelihood1* prior1 /(likelihood1*prior1+likelihood2*prior2) p2_test= likelihood2* prior2 /(likelihood1*prior1+likelihood2*prior2) classify_test_label=p2_test>p1_test classify_test_label=np.where(classify_test_label,1,0) classify_test_label test_label print(accuracy_score(test_label,classify_test_label)) print(classification_report(test_label,classify_test_label)) ```
github_jupyter
<center> <img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" /> </center> # **Web Scraping Lab** Estimated time needed: **30** minutes ## Objectives After completing this lab you will be able to: * Download a webpage using requests module * Scrape all links from a web page * Scrape all image urls from a web page * Scrape data from html tables ## Scrape [www.ibm.com](http://www.ibm.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDA0321ENSkillsNetwork21426264-2021-01-01) Import the required modules and functions ``` from bs4 import BeautifulSoup # this module helps in web scrapping. import requests # this module helps us to download a web page ``` Download the contents of the web page ``` url = "http://www.ibm.com" # get the contents of the webpage in text format and store in a variable called data data = requests.get(url).text ``` Create a soup object using the class BeautifulSoup ``` soup = BeautifulSoup(data,"html5lib") # create a soup object using the variable 'data' ``` Scrape all links ``` for link in soup.find_all('a'): # in html anchor/link is represented by the tag <a> print(link.get('href')) ``` Scrape all images ``` for link in soup.find_all('img'):# in html image is represented by the tag <img> print(link.get('src')) ``` ## Scrape data from html tables ``` #The below url contains a html table with data about colors and color codes. url = "https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DA0321EN-SkillsNetwork/labs/datasets/HTMLColorCodes.html" ``` Before proceeding to scrape a web site, you need to examine the contents, and the way data is organized on the website. Open the above url in your browser and check how many rows and columns are there in the color table. ``` # get the contents of the webpage in text format and store in a variable called data data = requests.get(url).text soup = BeautifulSoup(data,"html5lib") #find a html table in the web page table = soup.find('table') # in html table is represented by the tag <table> #Get all rows from the table for row in table.find_all('tr'): # in html table row is represented by the tag <tr> # Get all columns in each row. cols = row.find_all('td') # in html a column is represented by the tag <td> color_name = cols[2].getText() # store the value in column 3 as color_name color_code = cols[3].getText() # store the value in column 4 as color_code print("{}--->{}".format(color_name,color_code)) ``` ## Authors Ramesh Sannareddy ### Other Contributors Rav Ahuja ## Change Log | Date (YYYY-MM-DD) | Version | Changed By | Change Description | | ----------------- | ------- | ----------------- | ---------------------------------- | | 2020-10-17 | 0.1 | Ramesh Sannareddy | Created initial version of the lab | Copyright © 2020 IBM Corporation. This notebook and its source code are released under the terms of the [MIT License](https://cognitiveclass.ai/mit-license/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDA0321ENSkillsNetwork21426264-2021-01-01).
github_jupyter
# Keras Callbacks - Keras Callbacks provide useful tools to babysit training process - ModelCheckpoint - Earlystopping - ReduceLROnPlateau ``` from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.utils.np_utils import to_categorical from keras import optimizers from keras.callbacks import * from keras.layers import * ``` ### Load Dataset ``` data = load_digits() X_data = data.images y_data = data.target X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size = 0.3, random_state = 777) # reshaping X data => flatten into 1-dimensional X_train = X_train.reshape((X_train.shape[0], -1)) X_test = X_test.reshape((X_test.shape[0], -1)) # converting y data into categorical (one-hot encoding) y_train = to_categorical(y_train) y_test = to_categorical(y_test) print(X_train.shape) print(X_test.shape) print(y_train.shape) print(y_test.shape) ``` ## 1. ModelCheckpoint - **ModelCheckpoint** is used to 'checkpoint' model results on training - Oftentimes, it is used to save only best model ``` def create_model(): model = Sequential() model.add(Dense(100, input_shape = (X_train.shape[1],))) model.add(Activation('relu')) model.add(Dense(100)) model.add(Activation('relu')) model.add(Dense(y_train.shape[1])) model.add(Activation('sigmoid')) model.compile(optimizer = 'Adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) return model model = create_model() ``` ### Creating callbacks list - ModelCheckpoint instances are stored in list and passed on when training ``` callbacks = [ModelCheckpoint(filepath = 'saved_model.hdf5', monitor='val_acc', verbose=1, mode='max')] model.fit(X_train, y_train, epochs = 10, batch_size = 500, callbacks = callbacks, validation_data = (X_test, y_test)) results = model.evaluate(X_test, y_test) print('Accuracy: ', results[1]) ``` ### Loading saved weights - Saved weights can be loaded and used without further training - This is especially useful when training time is long and model has to be reused a number of times ``` another_model = create_model() another_model.load_weights('saved_model.hdf5') another_model.compile(optimizer = 'Adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) results = another_model.evaluate(X_test, y_test) print('Accuracy: ', results[1]) ``` ### Selecting best model - Best model during whole epoch can be selected using ModelCheckpoint - Set **'save_best_only'** parameter as True - Usually, validation accuracy (val acc) is monitored and used as criterion for best model ``` callbacks = [ModelCheckpoint(filepath = 'best_model.hdf5', monitor='val_acc', verbose=1, save_best_only = True, mode='max')] model = create_model() model.fit(X_train, y_train, epochs = 10, batch_size = 500, callbacks = callbacks, validation_data = (X_test, y_test)) best_model = create_model() best_model.load_weights('best_model.hdf5') best_model.compile(optimizer = 'Adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) results = best_model.evaluate(X_test, y_test) print('Accuracy: ', results[1]) ``` ## 2. Early stopping - Cease training when model seems to overfit, i.e., target metric has stopped improving for certain epochs - One can set **'patience'** parameter, which denotes number of epochs that model will endure without any improvements - e.g., if patience = 1, training will stop when metric has stopped improving for 2 epochs ``` callbacks = [EarlyStopping(monitor = 'acc', patience = 1)] model = create_model() # you could see that model stops training after 7 epochs model.fit(X_train, y_train, epochs = 20, batch_size = 500, callbacks = callbacks, validation_data = (X_test, y_test)) ``` ## 3. Reduce learning rate - In general, it is more desirable to lower down learning rate (learning rate decay) as training proceeds - However, coming up with optimal learning rate decay scheme is not easy - So, one of heuristics would be reducing learning rate when plateau is reached, in other words, when loss stops decreasing for certain number of epochs - learning rate will be decreased by factor of 'factor' parameter when objective metric has not improved for 'patience' parameter <br> <img src="https://i.ytimg.com/vi/s6jC7Wc9iMI/maxresdefault.jpg" style="width: 600px"/> ``` # halve learning rate when validation loss has not reduced for more than 5 epochs callbacks = [ReduceLROnPlateau(monitor = 'val_loss', factor = 0.5, patience = 5)] model = create_model() model.fit(X_train, y_train, epochs = 20, batch_size = 500, callbacks = callbacks, validation_data = (X_test, y_test)) results = model.evaluate(X_test, y_test) print('Accuracy: ', results[1]) ```
github_jupyter
``` import json import tensorflow as tf import csv import random import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.utils import to_categorical from tensorflow.keras import regularizers embedding_dim = 100 max_length = 16 trunc_type='post' padding_type='post' oov_tok = "<OOV>" training_size=#Your dataset size here. Experiment using smaller values (i.e. 16000), but don't forget to train on at least 160000 to see the best effects test_portion=.1 corpus = [] # Note that I cleaned the Stanford dataset to remove LATIN1 encoding to make it easier for Python CSV reader # You can do that yourself with: # iconv -f LATIN1 -t UTF8 training.1600000.processed.noemoticon.csv -o training_cleaned.csv # I then hosted it on my site to make it easier to use in this notebook !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/training_cleaned.csv \ -O /tmp/training_cleaned.csv num_sentences = 0 with open("/tmp/training_cleaned.csv") as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: # Your Code here. Create list items where the first item is the text, found in row[5], and the second is the label. Note that the label is a '0' or a '4' in the text. When it's the former, make # your label to be 0, otherwise 1. Keep a count of the number of sentences in num_sentences list_item=[] # YOUR CODE HERE num_sentences = num_sentences + 1 corpus.append(list_item) print(num_sentences) print(len(corpus)) print(corpus[1]) # Expected Output: # 1600000 # 1600000 # ["is upset that he can't update his Facebook by texting it... and might cry as a result School today also. Blah!", 0] sentences=[] labels=[] random.shuffle(corpus) for x in range(training_size): sentences.append(# YOUR CODE HERE) labels.append(# YOUR CODE HERE) tokenizer = Tokenizer() tokenizer.fit_on_texts(# YOUR CODE HERE) word_index = tokenizer.word_index vocab_size=len(# YOUR CODE HERE) sequences = tokenizer.texts_to_sequences(# YOUR CODE HERE) padded = pad_sequences(# YOUR CODE HERE) split = int(test_portion * training_size) test_sequences = padded[# YOUR CODE HERE] training_sequences = padded[# YOUR CODE HERE] test_labels = labels[# YOUR CODE HERE] training_labels = labels[# YOUR CODE HERE] print(vocab_size) print(word_index['i']) # Expected Output # 138858 # 1 # Note this is the 100 dimension version of GloVe from Stanford # I unzipped and hosted it on my site to make this notebook easier !wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/glove.6B.100d.txt \ -O /tmp/glove.6B.100d.txt embeddings_index = {}; with open('/tmp/glove.6B.100d.txt') as f: for line in f: values = line.split(); word = values[0]; coefs = np.asarray(values[1:], dtype='float32'); embeddings_index[word] = coefs; embeddings_matrix = np.zeros((vocab_size+1, embedding_dim)); for word, i in word_index.items(): embedding_vector = embeddings_index.get(word); if embedding_vector is not None: embeddings_matrix[i] = embedding_vector; print(len(embeddings_matrix)) # Expected Output # 138859 model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size+1, embedding_dim, input_length=max_length, weights=[embeddings_matrix], trainable=False), # YOUR CODE HERE - experiment with combining different types, such as convolutions and LSTMs ]) model.compile(# YOUR CODE HERE) model.summary() num_epochs = 50 history = model.fit(training_sequences, training_labels, epochs=num_epochs, validation_data=(test_sequences, test_labels), verbose=2) print("Training Complete") import matplotlib.image as mpimg import matplotlib.pyplot as plt #----------------------------------------------------------- # Retrieve a list of list results on training and test data # sets for each training epoch #----------------------------------------------------------- acc=history.history['accuracy'] val_acc=history.history['val_accuracy'] loss=history.history['loss'] val_loss=history.history['val_loss'] epochs=range(len(acc)) # Get number of epochs #------------------------------------------------ # Plot training and validation accuracy per epoch #------------------------------------------------ plt.plot(epochs, acc, 'r') plt.plot(epochs, val_acc, 'b') plt.title('Training and validation accuracy') plt.xlabel("Epochs") plt.ylabel("Accuracy") plt.legend(["Accuracy", "Validation Accuracy"]) plt.figure() #------------------------------------------------ # Plot training and validation loss per epoch #------------------------------------------------ plt.plot(epochs, loss, 'r') plt.plot(epochs, val_loss, 'b') plt.title('Training and validation loss') plt.xlabel("Epochs") plt.ylabel("Loss") plt.legend(["Loss", "Validation Loss"]) plt.figure() # Expected Output # A chart where the validation loss does not increase sharply! ```
github_jupyter
``` import numpy as np %matplotlib inline import matplotlib.pyplot as plt from importlib import reload import mathutils import fitsio import setcover import scipy.optimize as op import cosmology as cosmo import datapath import ebossspec import archespec from scipy.ndimage import gaussian_filter1d from matplotlib.colors import LogNorm plt.rcParams["figure.figsize"]=(10,8) plt.rcParams['axes.linewidth'] = 2 plt.rcParams['xtick.major.size'] = 15 plt.rcParams['xtick.major.width'] = 2 plt.rcParams['xtick.minor.size'] = 10 plt.rcParams['xtick.minor.width'] = 2 plt.rcParams['xtick.labelsize'] = 25 plt.rcParams['ytick.major.size'] = 15 plt.rcParams['ytick.major.width'] = 2 plt.rcParams['ytick.minor.size'] = 10 plt.rcParams['ytick.minor.width'] = 2 plt.rcParams['ytick.labelsize'] = 25 def color_legend_texts(leg): """Color legend texts based on color of corresponding lines""" for line, txt in zip(leg.get_lines(), leg.get_texts()): txt.set_color(line.get_color()) elg_composite = fitsio.read('../ELG_composite.fits', ext=1) feii_composite = fitsio.read('../FeII_MgII_Composite.fits', ext=1) nfl_sdss = fitsio.read('/Users/Benjamin/AstroData/Garching/hstnfl_sample.fits', ext=1) index_of_index = np.array([0,5,4,1]) nfl_composite = np.mean(nfl_sdss['ALLFLUX'][0], axis=1) print(nfl_composite.shape) masterwave, allflux, allivar = ebossspec.rest_allspec_readin() objs_ori = ebossspec.elg_readin() nobj = objs_ori.size galaxytype = objs_ori['CLASS'] zgood = objs_ori['zGOOD'] z = objs_ori['Z'] index_wave_all = np.searchsorted(masterwave, [2000., 5199.]) tmpflux = allflux[index_wave_all[0]:index_wave_all[1],:] tmpivar = allivar[index_wave_all[0]:index_wave_all[1],:] tmpwave = masterwave[index_wave_all[0]:index_wave_all[1]] tmploglam = np.log10(tmpwave) median_sn = np.zeros(objs_ori.size) for i in np.arange(objs_ori.size): iuse = (np.where(tmpivar[:,i]>0))[0] if iuse.size>0: median_sn[i] = np.median(tmpflux[iuse,i]*np.sqrt(tmpivar[iuse,i])) # Calculate oii_ew and oii_luminosity # 1Mpc = 3.08568025x10^24 cm Mpc_cm = 3.08568025E24 oiilum = np.zeros(nobj) oii_ew = np.zeros(nobj) index_oii = np.searchsorted(tmpwave, 3728.48) dnoiiwave = 10 dwave = np.median(tmpwave[index_oii-dnoiiwave:index_oii+dnoiiwave]-tmpwave[index_oii-dnoiiwave-1:index_oii+dnoiiwave-1]) print(dwave, tmpwave[index_oii-dnoiiwave], tmpwave[index_oii+dnoiiwave]) oiisum = np.sum(tmpflux[index_oii-dnoiiwave:index_oii+dnoiiwave, :]* (tmpivar[index_oii-dnoiiwave:index_oii+dnoiiwave, :]>0), axis=0)*dwave # Need to subtract the negligible continuum oii_left = np.sum(tmpflux[index_oii-25:index_oii-15, :]*(tmpivar[index_oii-25:index_oii-15, :]>0), axis=0)/(25.-15.) oii_right = np.sum(tmpflux[index_oii+15:index_oii+25, :]*(tmpivar[index_oii+15:index_oii+25, :]>0), axis=0)/(25.-15.) oii_cont = (oii_left+oii_right)/2. oii_ew = (oiisum-oii_cont*dwave)/oii_cont oiilum = (oiisum-oii_cont*dwave)*np.power(cosmo.luminosity_distance(z), 2)*4.*np.pi*np.power(Mpc_cm,2)*1E-17 # Calculate feii_ew and feii_luminosity feiilum = np.zeros(nobj) feii_ew = np.zeros(nobj) index_feii = np.searchsorted(tmpwave, 2626.) dnfeiiwave = 7 dwave = np.median(tmpwave[index_feii-dnfeiiwave:index_feii+dnfeiiwave]-tmpwave[index_feii-dnfeiiwave-1:index_feii+dnfeiiwave-1]) print(dwave, tmpwave[index_feii-dnfeiiwave], tmpwave[index_feii+dnfeiiwave]) feiisum = np.sum(tmpflux[index_feii-dnfeiiwave:index_feii+dnfeiiwave, :]* (tmpivar[index_feii-dnfeiiwave:index_feii+dnfeiiwave, :]>0), axis=0)*dwave # Need to subtract the negligible continuum feii_left = np.sum(tmpflux[index_feii-15:index_feii-8, :]*(tmpivar[index_feii-15:index_feii-8, :]>0), axis=0)/(15-8.) feii_right = np.sum(tmpflux[index_feii+8:index_feii+15, :]*(tmpivar[index_feii+8:index_feii+15, :]>0), axis=0)/(15.-8) feii_cont = (feii_left+feii_right)/2. feii_ew = (feiisum-feii_cont)/feii_cont feiilum = (feiisum-feii_cont*dwave)*np.power(cosmo.luminosity_distance(z), 2)*4.*np.pi*np.power(Mpc_cm,2)*1E-17 inuv = (np.where(np.logical_and(np.logical_and(\ np.logical_and(np.logical_and(zgood==1, galaxytype==b'GALAXY'), median_sn>0.),\ z<0.4798), z>0.4702)))[0] print(inuv.shape) plt.plot(oiilum[inuv], feiilum[inuv], '.') #plt.xlim(0,100) #plt.ylim(0,20) fig = plt.figure(figsize=(9,7)) ax = fig.add_subplot(111) n, bins, patches = ax.hist(oii_ew[inuv], bins=np.arange(0, 200, 5), edgecolor='black') ax.tick_params(axis='x', which='major', length=8, width=2, labelsize=22, pad=8) ax.tick_params(axis='x', which='minor', length=4, width=2, labelsize=22, pad=8) ax.tick_params(axis='y', which='major', length=6, width=2, labelsize=20, pad=8) ax.tick_params(axis='y', which='minor', length=3, width=2, labelsize=20, pad=8) this_ylim = [0, 800] ax.set_ylim(this_ylim) #ax.set_xscale('log') #ax.set_xlim(3680, 3780) ax.set_title(r'[OII] EW Distribution', fontsize=20) ax.set_xlabel(r'$W_{\rm O\,II}^{\lambda3728}$ [$\AA$]', fontsize=20) ax.set_ylabel(r'$\Delta N (\Delta W_{\rm O\,II}^{\lambda3728} = 5\, {\rm \AA}))$', fontsize=20) #fig.savefig('/Users/Benjamin/Dropbox/Zhu_Projects/Fine Structure Emission/Version 1/EW_distribution.eps') # Luminosity fig = plt.figure(figsize=(9,7)) ax = fig.add_subplot(111) n, bins, patches = ax.hist(np.log10(oiilum[inuv]), bins=np.arange(40., 43.5, 0.1), edgecolor='black') ax.tick_params(axis='x', which='major', length=8, width=2, labelsize=22, pad=8) ax.tick_params(axis='x', which='minor', length=4, width=2, labelsize=22, pad=8) ax.tick_params(axis='y', which='major', length=6, width=2, labelsize=20, pad=8) ax.tick_params(axis='y', which='minor', length=3, width=2, labelsize=20, pad=8) this_ylim = [0, 1100] ax.set_ylim(this_ylim) #ax.set_xscale('log') #ax.set_xlim(3680, 3780) ax.set_title(r'[OII] Luminosity Distribution', fontsize=22) ax.set_xlabel(r'$\log_{10}\,L_{\rm O\,II}^{\lambda3728}$ [${\rm erg\,s}^{-1}$]', fontsize=22) ax.set_ylabel(r'$\Delta N (\Delta \log_{10}\,L_{\rm O\,II}^{\lambda3728} = 0.1\, {\rm dex})$', fontsize=22) #fig.savefig('/Users/Benjamin/Dropbox/Zhu_Projects/Fine Structure Emission/Version 1/Lum_distribution.eps') istrong = inuv[(np.nonzero(np.logical_and(oii_ew[inuv]>50., oiilum[inuv]>1.E41))[0])] print(istrong.shape) i=0 i = i+1 fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot(111) x = gaussian_filter1d(tmpwave, 3) y = gaussian_filter1d(tmpflux[:,istrong[i]], 3) ax.plot(x,y) ax.set_xlim(2000, 5200) ax.set_ylim(-1,4) ax.plot([2586, 2586], [0, 5]) ax.plot([2600, 2600], [0, 5]) ax.plot([2626, 2626], [0, 5]) ax.plot([2800, 2800], [0, 5]) ax.plot([3728, 3728.5], [0, 5]) ax.plot([5577./1.475, 5577./1.475], [0, 5]) istrong.shape fullsum = np.mean(tmpflux[:, istrong], axis=1) fig = plt.figure(figsize=(20,8)) ax = fig.add_subplot(111) x = gaussian_filter1d(tmpwave, 1) y = gaussian_filter1d(fullsum, 1) ax.plot(x,y) ax.set_xlim(2400, 3000) ax.set_ylim(-1,4) ax.plot([2586, 2586], [0, 5]) ax.plot([2600, 2600], [0, 5]) ax.plot([2612.65, 2612.65], [0, 5]) ax.plot([2626, 2626], [0, 5]) ax.plot([2803, 2803], [0, 5]) ax.plot([3728, 3728.5], [0, 5]) print(2818./2630.) print(2773./2610.) print(2613*1.071) print(3730*1.058) print(8140./1.06) print(i) print(objs_ori['PLUG_DEC'][istrong]) f280n = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f280n.UVIS2.tab') f343n = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f343n.UVIS2.tab') f395n = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f395n.UVIS2.tab') f390m = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f390m.UVIS2.tab') f680n = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f680n.UVIS2.tab') f625w = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f625w.UVIS2.tab') f621m = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/f621m.UVIS2.tab') fig = plt.figure(figsize=(24,8)) ax = fig.add_subplot(111) i3650 = np.searchsorted(nfl_sdss['WAVE'][0], 3650.) ax.plot(nfl_sdss['WAVE'][0][i3650:]*(1.+0.061), nfl_composite[i3650:]*0.0008, color='magenta') ax.plot(elg_composite[0]['WAVE']*(1.+0.065), elg_composite[0]['FLUXMEDIAN']/10, 'b') ax.plot(f280n[:,1], f280n[:,2], '-k') ax.plot(f343n[:,1], f343n[:,2], ':k') ax.plot(f395n[:,1], f395n[:,2]*1.05, '--k') #ax.plot(f621m[:,1], f621m[:,2]*1.05, '-.k') #p680n, = ax.plot(f680n[:,1], f680n[:,2]*1.05, '-k') #p680n.set_dashes([8, 4, 2, 4, 2, 4]) #leg = ax.legend(['HST-pNFL target composite (z=0.065, offset for clarity)', 'eBOSS ELG composite (shifted to z=0.065)', \ # 'F280N throughput curve', 'F343N', 'F395N', 'F621M', 'F680N'], \ leg = ax.legend(['HST-pNFL target composite (z=0.065, offset for clarity)', 'eBOSS ELG composite (shifted to z=0.065)', \ 'F280N throughput curve', 'F343N', 'F395N'], \ bbox_to_anchor=(0.01, 0.90, 1., .102), loc=2, frameon=False, fontsize=24, ) color_legend_texts(leg) ax.set_xlim(2270, 5400) #ax.set_xlim(2100, 3200) ax.set_ylim(0.0004,0.36) #ax.plot([2773, 2773], [0, 0.07], 'g') #ax.plot([2818, 2818], [0, 0.07], 'g') ax.set_xlabel(r'observer-frame $\lambda$ ($\AA$)', fontsize=22) ax.set_ylabel(r'$f(\lambda)$ [Arbitrary Unit]', fontsize=22) #ax.text(6563.*(1.+0.065)+10, 0.30, r'H$\alpha$', fontsize=20) ax.text(5007.*(1.+0.065)-150, 0.28, r'[O III]', fontsize=20) ax.text(4861.*(1.+0.065)-60, 0.235, r'H$\beta$', fontsize=20) ax.text(4341.*(1.+0.065)-50, 0.13, r'H$\gamma$', fontsize=20) #ax.text(3889.*(1.+0.065)-100, 0.09, r'[Ne III]', fontsize=20) ax.text(3730.*(1.+0.065)+2, 0.26, r'[O II]', fontsize=20) ax.text(2626.*(1.+0.065)-40, 0.07, r'Fe II*', fontsize=20) fig.savefig('/Users/Benjamin/Desktop/UVIS/composite_filters.eps') fig = plt.figure(figsize=(18,8)) ax = fig.add_subplot(111) i3650 = np.searchsorted(nfl_sdss['WAVE'][0], 3650.) ax.plot(nfl_sdss['WAVE'][0][i3650:]*(1.+0.0655), nfl_composite[i3650:]*0.0008, color='magenta') ax.plot(elg_composite[0]['WAVE']*(1.+0.065), elg_composite[0]['FLUXMEDIAN']/15, 'b') ax.plot(f280n[:,1], f280n[:,2], '--k') ax.plot(f343n[:,1], f343n[:,2], '-k') ax.plot(f395n[:,1], f395n[:,2], ':k') leg = ax.legend(['ELG composite ((shifted to z=0.065)', 'F280N', 'F343N', 'F395N'], bbox_to_anchor=(0.01, 0.90, 1., .102), loc=2, frameon=False, fontsize=22) color_legend_texts(leg) ax.set_xlim(2000, 7160) ax.set_ylim(0.0004,0.35) #ax.plot([2773, 2773], [0, 0.07], 'g') #ax.plot([2818, 2818], [0, 0.07], 'g') ax.set_xlabel(r'observer-frame $\lambda$ ($\AA$)', fontsize=22) ax.set_ylabel(r'$f(\lambda)$ [Arbitrary Unit]', fontsize=22) fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(111) ax.plot(elg_composite[0]['WAVE']*(1.+0.065), elg_composite[0]['FLUXMEDIAN']/10, drawstyle='steps') ax.plot(f280n[:,1], f280n[:,2], '-k') #ax.plot(f395n[:,1], f395n[:,2], 'k') leg = ax.legend(['eBOSS ELG composite (shifted to z=0.065)', 'F280N throughput curve'], \ bbox_to_anchor=(0.01, 0.90, 1., .102), loc=2, frameon=False, fontsize=22, ) color_legend_texts(leg) ax.set_xlim(2710, 2850) ax.set_ylim(0,0.08) #ax.plot([2773, 2773], [0, 0.07], 'g') #ax.plot([2818, 2818], [0, 0.07], 'g') ax.set_xlabel(r'observer-frame $\lambda$ ($\AA$)', fontsize=22) ax.set_ylabel(r'$f(\lambda)$ [Arbitrary Unit]', fontsize=22) ax.text(2613.*(1.+0.065)-18, 0.045, r'Fe II* 2613', color='blue', fontsize=22) ax.text(2626.*(1.+0.065)-5, 0.045, r'2626', color='blue', fontsize=22) ax.text(2587.*(1.+0.065)-16, 0.010, r'Fe II 2587', color='blue', fontsize=22) ax.text(2600.*(1.+0.065)-5, 0.010, r'2600', color='blue', fontsize=22) fig.savefig('/Users/Benjamin/Desktop/UVIS/composite_filters_f280n.eps') plt.plot(f395n[:,1], f395n[:,2], 'b') plt.plot(f390m[:,1], f390m[:,2], 'r') plt.xlim(3700, 4080) plt.ylim(0,0.27) #plt.plot([2773, 2773], [0, 0.07], 'g') #plt.plot([2818, 2818], [0, 0.07], 'g') iz = np.nonzero(np.logical_and(np.logical_and(np.logical_and(np.logical_and(np.logical_and(np.logical_and( dr7_info['Z']>0.064, dr7_info['Z']<0.066), dr7_mass['MEDIAN']>7.), dr7_mass['MEDIAN']<12.), dr7_ssfr['MEDIAN']<-1), dr7_ssfr['MEDIAN']>-20), dr7_info['SN_MEDIAN']>0.))[0] print(iz.shape) fig = plt.figure(figsize=(11,11)) ax = fig.add_subplot(111) ax.hist2d(dr7_mass['MEDIAN'][iz], dr7_ssfr['MEDIAN'][iz], bins=80, cmin=2, cmap='Greys', norm=LogNorm()) #ax.plot(dr7_mass['MEDIAN'][iz], dr7_ssfr['MEDIAN'][iz], '.') #ax.plot(dr7_mass[1000:11000]['MEDIAN'], dr7_sfr[1000:11000]['MEDIAN'], '.') #ax.plot(mass[iarchetype], sfr[iarchetype]-mass[iarchetype], '*', ms=15) ax.set_ylim(-12.5, -8.5) ax.set_xlim(8.5, 12.) ax.set_xlabel(r'$\log_{10}$ $M_*$ [M$_\odot$]', fontsize=22) ax.set_ylabel(r'sSFR [yr$^{-1}$]', fontsize=22) xmass = np.linspace(8.5, 12.0, num=100) yssfr = -0.65*(xmass-10.)-9.8 ilow = np.searchsorted(xmass, 9.0) isort = xmass.size - np.searchsorted(yssfr[::-1], -9.8) iselect = np.nonzero(np.logical_and(dr7_ssfr['MEDIAN'][iz]>-9.8, dr7_ssfr['MEDIAN'][iz]>-0.65*(dr7_mass['MEDIAN'][iz]-10.)-9.8))[0] print(iselect.size) ax.plot(xmass[:isort+1], yssfr[:isort+1], '--b', lw=4) ax.plot(xmass[isort:], xmass[isort:]/xmass[isort:]*(-9.80), '--b', lw=4) #ax.plot([9.0, 9.0], [yssfr[ilow], -8.5], '--b', lw=3) #print(iarchetype.size) ioii = np.nonzero((dr7_line['OII_3729_REQW'][iz[iselect]]+dr7_line['OII_3726_REQW'][iz[iselect]])<-80.)[0] icont = np.nonzero((dr7_line['OII_3729_FLUX'][iz[iselect]]/dr7_line['OII_3729_CONT'][iz[iselect]] \ +dr7_line['OII_3726_FLUX'][iz[iselect]]/dr7_line['OII_3726_CONT'][iz[iselect]])>50.)[0] igalex = np.nonzero(np.logical_and(dr7_galex['NUV_MAG'][iz[iselect[ioii]]]<19.2, dr7_galex['NUV_MAG'][iz[iselect[ioii]]]>15.))[0] print(ioii.size) print(icont.size) print(igalex.size) plt.plot(dr7_line['OII_3729_REQW'][iz[[iselect]]], dr7_line['OII_3726_REQW'][iz[iselect]], '.') plt.plot([-200, 50], [-200, 50]) for i in np.arange(igalex.size): print("{0:7d}".format(iz[iselect[ioii[igalex]]][i]),\ "{0:.6f}".format(dr7_info['RA'][iz[iselect[ioii[igalex]]]][i]), \ "{0:.6f}".format(dr7_info['DEC'][iz[iselect[ioii[igalex]]]][i])) x = plt.hist(-dr7_line['OII_3729_EQW'][iz[iselect]], bins=50, range=(0, 150))#, normed=True) y = plt.hist(-dr7_line['OII_3729_EQW'][iz[iselect[ioii]]], bins=50, range=(0,150))#, normed=True) plt.ylim(0,80) #print(dr7_galex['FUV_MAG_APER_2'][iz][iselect]) lf_z = np.linspace(0.1, 2.5, num=40) lf_oii = np.power(10, np.linspace(39, 44, num=40)) #lf_L = np.power(10, 0.341*lf_z + 40.773) lf_L = np.power(10, 0.30*lf_z + 40.773) #lf_logphi = 0.475*lf_z - 2.522 lf_logphi = 0.40*lf_z - 2.522 lf_alpha = 0.25*lf_z - 1.6 + 1. #lf_alpha = 0*lf_z - 1.257+1. lf_lf = np.zeros((40, 40)) lf_sigma = -0.0*(lf_z-1.) + 0.46 for i in np.arange(40): lf_lf[:,i] = np.power(10, lf_logphi)*np.power(lf_oii[i]/lf_L, lf_alpha)\ *np.exp(-np.power(np.log10(1.+lf_oii[i]/lf_L)/np.sqrt(2.)/lf_sigma, 2)) CM = plt.get_cmap('jet_r') fig = plt.figure(figsize=(8,10)) ax = fig.add_subplot(111) for i in np.arange(40): color = np.fmin(np.fmax((2.8-lf_z[i])/2, 0), 1.) thiscolor = CM(color) ax.loglog(lf_oii, lf_lf[i,:], color=thiscolor) ax.set_ylim(1E-7, 1E-1) ax.grid() #plt.colorbar() lf_alpha-1. dr7_info = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_info_dr7_v5_2.fit.gz', ext=1) dr7_sfr = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_totsfr_dr7_v5_2.fits.gz', ext=1) dr7_ssfr = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_totspecsfr_dr7_v5_2.fits.gz', ext=1) dr7_mass = fitsio.read('/Users/Benjamin/AstroData/Garching/totlgm_dr7_v5_2.fit.gz', ext=1) dr7_phi = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_phi_dr7_v5_2.fits', ext=1) dr7_uniq = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_uniq_dr7_v5_2.fits', ext=1) dr7_line = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_line_dr7_v5_2.fit.gz', ext=1) dr7_galex = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_galex_dr7_v5_2.fits', ext=1) dr7_fibersfr = fitsio.read('/Users/Benjamin/AstroData/Garching/gal_fibsfr_dr7_v5_2.fits.gz', ext=1) print('RA, DEC, MASS, SFR, fiber SFR, sSFR, R_EXP, SFR/A, fiber SFR/A, u, u fiber, nuv, nuv fiber') for i, j in zip(nfl_sdss['INDEX'][0][index_of_index], np.arange(4)): sfrarea = np.power(10, dr7_sfr['MEDIAN'][i])/np.pi/(dr7_phi['R_EXP'][i][0]*1.256)**2 fibersfrarea = np.power(10, dr7_fibersfr['MEDIAN'][i])/np.pi/(1.5*1.256)**2 fiber_nuv = dr7_info['PLUG_MAG'][i][0] - data_skyserver[j][4] + dr7_galex['NUV_MAG'][i] fiber_fuv = dr7_info['PLUG_MAG'][i][0] - data_skyserver[j][4] + dr7_galex['FUV_MAG'][i] print("{0:.3f} {1:6.3f} {2:.3f} {3:6.3f} {4:6.3f} {5:6.3f} {6:6.3f} {7:6.3f} {8:6.3f} {9:6.3f} {10:6.3f} {11:6.3f} {12:6.3f} {13:6.3f} {14:6.3f}".format(dr7_info['RA'][i], dr7_info['DEC'][i], \ dr7_mass['MEDIAN'][i], np.power(10, dr7_sfr['MEDIAN'][i]), np.power(10, dr7_fibersfr['MEDIAN'][i]), dr7_ssfr['MEDIAN'][i], dr7_phi['R_EXP'][i][0], \ sfrarea , fibersfrarea, data_skyserver[j][4], dr7_info['PLUG_MAG'][i][0], dr7_galex['NUV_MAG'][i], fiber_nuv, dr7_galex['FUV_MAG'][i], fiber_fuv)) print(dr7_line['OII_3726_EQW'][nfl_sdss['INDEX'][0]]) print('INDEX, ra, ra fiber, u u totaa') for i, j in zip(nfl_sdss['INDEX'][0], np.arange(8)): #print("{0:6d} {1:.6f} {2:.6f} {3:.6f} {4:.6f}".format(i, dr7_info['RA'][i][0], data_skyserver[j][2], dr7_info['PLUG_MAG'][i][0], data_skyserver[j][4])) fiber_nuv = dr7_info['PLUG_MAG'][i][0] - data_skyserver[j][4] + dr7_galex['NUV_MAG'][i] print("{0:6d} {1:.6f} {2:.6f} {3:.6f} {4:.6f} {5:.6f}".format(i, data_skyserver[j][2], dr7_info['PLUG_MAG'][i][0], data_skyserver[j][4], dr7_galex['NUV_MAG'][i], fiber_nuv)) 179.446451060553,58.5841325235255,17.72215,16.95618,16.86512,16.59029,16.59573,0.064461 127.758047177716,4.05524750834444,17.75126,16.96656,16.74418,16.31073,16.35811,0.06475648 143.569934270161,10.6778559344543,18.486,17.60747,17.35559,17.08135,17.07806,0.06525452 179.236432162099,44.8327830805518,17.53227,16.96531,16.93552,16.76346,16.78894,0.06439935 182.560285457813,44.6657831628324,17.76719,16.99928,16.86522,16.50574,16.61898,0.06594051 244.636075514965,27.7312286348228,17.06599,16.52032,16.73591,16.24394,16.43703,0.06422318 161.513414086334,15.4185175577052,17.70758,16.86378,16.67677,16.3776,16.3641,0.06442506 187.590171299233,17.7381113893822,18.27589,17.39026,17.20262,17.01104,17.03539,0.06586163 data_skyserver = np.genfromtxt('/Users/Benjamin/Desktop/UVIS/notebook.csv',delimiter=",",skip_header=1) data_skyserver[0][4] itmp = np.nonzero(np.logical_and(np.logical_and(np.logical_and(np.logical_and(np.logical_and(np.logical_and( dr7_info['Z']>0.02, dr7_info['Z']<0.30), dr7_mass['MEDIAN']>7.), dr7_mass['MEDIAN']<13.), dr7_ssfr['MEDIAN']<-1), dr7_ssfr['MEDIAN']>-20), dr7_info['SN_MEDIAN']>3.))[0] iarche = np.random.choice(itmp, 10000) print(iarche.shape) objs_dtype = [('PLATE', 'i4'), ('MJD', 'i4'), ('FIBER', 'i4'), ('RA', 'f8'), ('DEC', 'f8'), ('Z', 'f8'), ('MASS', 'f8'), ('SFR', 'f8')] objs = np.zeros(iarche.size, dtype=objs_dtype) objs['PLATE'] = dr7_info['PLATEID'][iarche] objs['MJD'] = dr7_info['MJD'][iarche] objs['FIBER'] = dr7_info['FIBERID'][iarche] objs['RA'] = dr7_info['RA'][iarche] objs['DEC'] = dr7_info['DEC'][iarche] objs['Z'] = dr7_info['Z'][iarche] objs['MASS'] = dr7_mass['MEDIAN'][iarche] objs['SFR'] = dr7_sfr['MEDIAN'][iarche] fits = fitsio.FITS('/Users/Benjamin/AstroData/Garching/Archetype_sample.fits', 'rw', clobber=True) fits.write(objs) fits.close() test = fitsio.read('/Users/Benjamin/AstroData/Garching/Archetype_sample.fits') archespec.rest_allspec(overwrite=True) reload(datapath) datapath.garching_path() elg_composite.dtype plt.plot(elg_composite[0]['WAVE'], elg_composite[0]['FLUXMEDIAN']) ioii.size xx = plt.hist(dr7_galex['FUV_MAG'][iz], bins=50, range=(17,24)) yy = plt.hist(dr7_galex['FUV_MAG'][iz[iselect]], bins=50, range=(17,24)) zz = plt.hist(dr7_galex['FUV_MAG'][iz[iselect[ioii]]], bins=50, range=(17,24)) plt.ylim(0,50) r = np.linspace(0, 50, num=200) r_uv = 3. f0_uv = 200000. f0_sky = 10000. #2700./100. #f0_uv/1000. f_uv = f0_uv*np.exp(-r/r_uv) r_fe = r_uv*3. f0_fe = f0_uv*r_uv**2/10./r_fe**2 f_fe = f0_fe*np.exp(-r/r_fe) #mu0_uv = 20. #mu_uv = mu0_uv + 2.5/np.log(10.)*r/r_uv #mu0_feii = fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111) ax.semilogy(r, f_uv+f_fe, 'k', lw=4) ax.semilogy(r, f_uv, 'b-.', lw=4) ax.semilogy(r, f_fe, 'g--', lw=4) #ax.semilogy(np.r_[[0],r[10:]], np.r_[f_fe_iso[10], f_fe_iso[10:]], '-.', color='orange', lw=4) #ax.semilogy(np.r_[r[10],r[10:]], np.r_[[1E-10], f_fe_iso[10:]], '-.', color='orange', lw=4) ax.semilogy(r, np.sqrt(f_uv+f_fe+f0_sky), '--', color='dimgrey', lw=4) leg = ax.legend(['Total counts (UV+Fluorescent)', 'UV continuum, $\sim \exp(-r/r_s)$', \ 'Fluorescent Fe II*, $\sim \exp(-r/3r_s)$', 'Poisson uncertainties'], \ loc=1, frameon=False, fontsize=23) # bbox_to_anchor=(0.91, 0.90, 1., .102), loc=2, frameon=False, fontsize=20) color_legend_texts(leg) ax.set_ylim(5E-0, 2E5) ax.set_xlabel('$r$ [arcsec]', fontsize=22) ax.set_ylabel(r"$f$ [counts per arcsec$^2$]", fontsize=22) print(f0_uv, f0_fe) fig.savefig('/Users/Benjamin/Desktop/UVIS/exponential_profile.eps') r = np.linspace(0, 50, num=200) r_uv = 3. f0_uv = 200000. f0_sky = 10000. #2700./100. #f0_uv/1000. f_uv = f0_uv*np.exp(-r/r_uv) r_fe = 9. f0_fe = f0_uv*r_uv**2/10./r_fe**2 f_fe = f0_fe*np.exp(-r/r_fe) r_fe_iso = r_uv*3. f0_fe_iso = f0_uv*r_uv**2/20./(np.log(15./r_uv)) f_fe_iso = f0_fe_iso*(1./r)**2 #mu0_uv = 20. #mu_uv = mu0_uv + 2.5/np.log(10.)*r/r_uv #mu0_feii = fig = plt.figure(figsize=(10,8)) ax = fig.add_subplot(111) ax.semilogy(r, np.r_[f_uv[:10],f_uv[10:]+f_fe_iso[10:]], 'k', lw=4) ax.semilogy(r, f_uv, 'b-.', lw=4) ax.semilogy(np.r_[r[10],r[10:]], np.r_[[1E-10], f_fe_iso[10:]], '--', color='brown', lw=4) ax.semilogy(r, np.sqrt(f_uv+f_fe+f0_sky), '--', color='dimgrey', lw=4) leg = ax.legend(['Total counts (UV+Fluorescent)', 'UV continuum, $\sim \exp(-r/r_s)$', \ r'Fluorescent Fe II*, $\sim r^{-2}$', 'Poisson uncertainties'], \ loc=1, frameon=False, fontsize=23) # bbox_to_anchor=(0.91, 0.90, 1., .102), loc=2, frameon=False, fontsize=20) color_legend_texts(leg) ax.set_ylim(5E-0, 2E5) ax.set_xlabel('$r$ [arcsec]', fontsize=22) ax.set_ylabel(r"$f$ [counts per arcsec$^2$]", fontsize=22) print(f0_uv, f0_fe) fig.savefig('/Users/Benjamin/Desktop/UVIS/powerlaw_profile.eps') 18.8+2.5*np.log10(1./0.8)#-2.5*np.log10(1.25*1.25/(3.75*3.75))#-2.5*np.log10(2.) np.r_[[0], [1, 2]] 19.04+2.5*np.log10(2*2*np.pi)#-2.5*np.log10(2.) nfl_sdss['ALLFLUX'].shape 15367./np.sqrt(15367.+2715.) (1.-np.exp(-15./2.)) np.sqrt(1./3.14) 0.6*0.6*3.14 0.56*0.56*3.14 imin = np.argmin(np.abs(dr7_info['RA']-127.75746)) print(dr7_info['Z'][imin]) print(dr7_info['RA'][imin]) print(dr7_info['DEC'][imin]) print(dr7_mass['MEDIAN'][imin]) print(np.power(10, dr7_sfr['MEDIAN'][imin])) print(dr7_ssfr['MEDIAN'][imin]) print(np.power(10, dr7_fibersfr['MEDIAN'][imin])) print(np.power(10., dr7_sfr['MEDIAN'][imin])/np.pi/(dr7_phi['R_EXP'][imin][0]*1.256)**2) print(np.power(10., dr7_fibersfr['MEDIAN'][imin])/np.pi/(1.5*1.256)**2) print(dr7_galex['NUV_MAG'][imin]) print(dr7_line['OII_3729_FLUX'][imin]/dr7_line['OII_3729_CONT'][imin]+dr7_line['OII_3726_FLUX'][imin]/dr7_line['OII_3726_CONT'][imin]) 17.827+2.5*np.log10(5./3.) + (18.454-17.751) print(dr7_info['Z'][nfl_sdss['INDEX']][0][index_of_index]) xx = dr7_line['OII_3729_FLUX'][nfl_sdss['INDEX'][0]]/dr7_line['OII_3729_CONT'][nfl_sdss['INDEX'][0]] \ +dr7_line['OII_3726_FLUX'][nfl_sdss['INDEX'][0]]/dr7_line['OII_3726_CONT'][nfl_sdss['INDEX'][0]] xx[index_of_index] 0.564*0.564*np.pi a = fitsio.read('/Users/Benjamin/Desktop/UVIS/h2templat_J3.fits', ext=0) np.exp(10./2.)/np.exp(2./2) 7500./36./60. ```
github_jupyter
# ReadData ``` import pandas as pd import numpy as np T2path = 'StataReg/0419-base/T2.csv' T2 = pd.read_csv(T2path) T3_Whole = T2[T2['Selected'] == 1] T3path = 'StataReg/0419-base/Data.dta' T3 = pd.read_stata(T3path) T3_Whole['WholeNum'].sum() len(T2['NotInHighMobility'] == 0) (T2['NotInHighMobility'] == 0).value_counts() T2[T2['NotInHighMobility'] == 0]['Geographic Area Name'].to_list() T3_Whole[T3_Whole['NotInHighMobility'] == 0]['Geographic Area Name'].to_list() ``` # MissingNo ``` import missingno as misno misno.matrix(T2[T3.columns[1:-5]]) ``` # Correlation Matrix Heatmap ``` XY_cols = T3.columns[3:-5] XY_cols newdf = T3[XY_cols] newdf from matplotlib import pyplot as plt import seaborn as sns # Compute the correlation matrix corr = newdf.corr() # Generate a mask for the upper triangle mask = np.triu(np.ones_like(corr, dtype=bool)) # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(230, 20, as_cmap=True) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}) ``` # Republican Rate and CvdVax ``` T3_Whote.columns T3_Whole_repub = T3_Whote[] import seaborn as sns from matplotlib import pyplot as plt sns.set_theme(style="white") dims = (10, 6) # df = mylib.load_data() fig, ax = plt.subplots(figsize=dims) ax = sns.scatterplot(x='republican_rate', y='CvdVax_MWhiteRate', data = T3_Whole, size='WholeNum', sizes = (30, 300)) # ax = sns.regplot(x=OrgDF['republican_rate'], y=OrgDF['Vax_White']) ax.set_title('Republican Rate and White COVID-19 Vax Rate') fig, ax = plt.subplots(figsize=dims) ax = sns.scatterplot(x='republican_rate', y='CvdVax_MBlackRate', data = T3_Whole, size='WholeNum', sizes = (30, 300)) # ax = sns.regplot(x=OrgDF['republican_rate'], y=OrgDF['Vax_Black']) ax.set_title('Republican Rate and Black COVID-19 Vax Rate') fig, ax = plt.subplots(figsize=dims) ax = sns.scatterplot(x='republican_rate', y='FluVax_NHWhiteRate', data = T3_Whole, size='WholeNum', sizes = (30, 300)) # ax = sns.regplot(x=OrgDF['republican_rate'], y=OrgDF['FluVax_White'], ) ax.set_title('Republican Rate and White Flu Vax Rate') fig, ax = plt.subplots(figsize=dims) ax = sns.scatterplot(x='republican_rate', y='FluVax_BlackRate', data = T3_Whole, size='WholeNum', sizes = (30, 300)) # ax = sns.regplot(x=OrgDF['republican_rate'], y=OrgDF['FluVax_Black']) ax.set_title('Republican Rate and Black Flu Vax Rate') # ax = sns.regplot(x=OrgDF['Vax_Black'], y=OrgDF['republican_rate'], color="g") ``` # Covid Bar Chart (Weighted) ``` import pandas as pd T2path = 'StataReg/0419-base/T2.csv' T2 = pd.read_csv(T2path) T3_Whole = T2[T2['Selected'] == 1].reset_index(drop = True) T3path = 'StataReg/0419-base/Data.dta' T3 = pd.read_stata(T3path) print(T3_Whole.shape) T3_Whole['Prop_Weights'] = T3_Whole['WholeNum'] / T3_Whole['WholeNum'].sum() * len(T3_Whole) print(T3_Whole['Prop_Weights'].sum()) import pandas as pd RawData = T3_Whole print(RawData.shape) L = [] for idx, row in RawData.iterrows(): d = row.to_dict() dn = {} dn['Vaccination'] = 'COVID-19' dn['Race'] = 'Black' dn['VaxRate'] = d['CvdVax_MBlackRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Republican'] = d['republican'] dn['Vaccination Rate (%)'] = d['CvdVax_MBlackRate'] * d['Prop_Weights'] L.append(dn) dn = {} dn['Vaccination'] = 'COVID-19' dn['Race'] = 'White' dn['VaxRate'] = d['CvdVax_MWhiteRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Republican'] = d['republican'] dn['Vaccination Rate (%)'] = d['CvdVax_MWhiteRate']* d['Prop_Weights'] L.append(dn) newdf = pd.DataFrame(L) # print(newdf.shape) newdf import numpy as np df = newdf[newdf['Race'] == 'Black'] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print(average,std) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print(average,std) white_w_average = average print(white_w_average - black_w_average) newdf import numpy as np print('Republican') df = newdf[newdf['Race'] == 'Black'] df = df[df['Republican'] == 1] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print('Black (w-mean, w-std):', average, std) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] df = df[df['Republican'] == 1] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print('White (w-mean, w-std):', average,std) white_w_average = average print('Diff:', white_w_average - black_w_average) import numpy as np print('Democrat') df = newdf[newdf['Race'] == 'Black'] df = df[df['Republican'] == 0] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print('Black (w-mean, w-std):', average, std) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] df = df[df['Republican'] == 0] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print('White (w-mean, w-std):', average,std) white_w_average = average print('Diff:', white_w_average - black_w_average) from matplotlib import pyplot as plt import seaborn as sns # sns.set_theme(style="ticks") sns.set_theme(style="whitegrid") sns.set(font_scale=1.4) def change_width(ax, new_value) : for patch in ax.patches : current_width = patch.get_width() diff = current_width - new_value # we change the bar width patch.set_width(new_value) # we recenter the bar patch.set_x(patch.get_x() + diff * .5) dims = (10, 6) fig, ax = plt.subplots(figsize=dims) ax.set(ylim=(0, 65)) ax = sns.barplot(x="Race" , y="Vaccination Rate (%)", #estimator=sum, palette = ['grey', 'red'], alpha = 0.5, data=newdf, errwidth = 2, errcolor = 'black', capsize=.4) change_width(ax, 0.6) county_num = len(RawData) date = '2021-04-19' ax.set_ylabel("Weighted Vaccination Rate (%)") ax.set_title('COVID-19 Vaccination Rate ({} Counties, {})'.format(county_num, date)) plt.show() fig.savefig('bar-covid.pdf', dpi=5000) print('April 19') Rate = RawData[[ 'CvdVax_Disparity', 'CvdVax_MBlackRate', 'CvdVax_MWhiteRate',]].describe() Rate.to_clipboard() Rate ``` # Covid Bar Chart (Original) ``` newdf from matplotlib import pyplot as plt import seaborn def change_width(ax, new_value) : for patch in ax.patches : current_width = patch.get_width() diff = current_width - new_value # we change the bar width patch.set_width(new_value) # we recenter the bar patch.set_x(patch.get_x() + diff * .5) # import mylib time = '2021-04-19' dims = (10, 6) # df = mylib.load_data() fig, ax = plt.subplots(figsize=dims) # seaborn.violinplot(ax=ax, data=df, **violin_options) ax.set(ylim=(0, 65)) # df.to_csv('759_rate.csv') ax = sns.barplot(x="Race" , y="VaxRate", palette = ['grey', 'red'], alpha = 0.5, data=newdf, errwidth = 2, errcolor = 'black', capsize=.3) change_width(ax, 0.5) ax.set_title('COVID-19 Vaccination Rate ({} Counties, {})'.format(county_num, time)) plt.show() ``` # Covid Distribution ``` import pandas as pd from matplotlib import pyplot# as plt sns.set_theme(style="whitegrid") sns.set(font_scale=1.4) RawData = T3_Whole print(RawData.shape) dims = (10, 6) # df = mylib.load_data() fig, ax = pyplot.subplots(figsize=dims) ax = sns.distplot(RawData['CvdVax_MBlackRate'], hist=True, kde=True, bins=int(100), color = 'grey', kde_kws={'linewidth': 1}, label='Black') ax = sns.distplot(RawData['CvdVax_MWhiteRate'], hist=True, kde=True, bins=int(100), color = 'red', kde_kws={'linewidth': 1}, label='White') pyplot.legend(loc='best') counties_num = len(RawData) ax.set_title('COVID-19 Vaccination Rate Distribution ({} Counties, {})'.format(county_num, date)) ax.set(xlabel='COVID-19 Vaccination Rate (%)') ax.set(ylabel ='Density') ax.set(xlim=(0, 100)) ax.set(ylim=(0, 0.155)) fig.savefig('dist-covid.pdf', dpi=5000) ``` # Flu Bar Chart (Weighted) ``` import pandas as pd T2path = 'StataReg/0419-base/T2.csv' T2 = pd.read_csv(T2path) T3_Whole = T2[T2['Selected'] == 1].reset_index(drop = True) T3path = 'StataReg/0419-base/Data.dta' T3 = pd.read_stata(T3path) print(T3_Whole.shape) T3_Whole['Prop_Weights'] = T3_Whole['WholeNum'] / T3_Whole['WholeNum'].sum() * len(T3_Whole) print(T3_Whole['Prop_Weights'].sum()) import pandas as pd RawData = T3_Whole print(RawData.shape) L = [] for idx, row in RawData.iterrows(): d = row.to_dict() dn = {} dn = {} dn['Vaccination'] = 'Flu' dn['Race'] = 'Black' dn['VaxRate'] = d['FluVax_BlackRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Vaccination Rate (%)'] = d['FluVax_BlackRate']* d['Prop_Weights'] # dn['Population'] = d['Total_Whole'] # dn['Rate-Population'] = (dn['Vaccination Rate (%)'] , dn['Population']) L.append(dn) dn = {} dn['Vaccination'] = 'Flu' dn['Race'] = 'White' dn['VaxRate'] = d['FluVax_NHWhiteRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Vaccination Rate (%)'] = d['FluVax_NHWhiteRate']* d['Prop_Weights'] L.append(dn) newdf = pd.DataFrame(L) # print(newdf.shape) newdf import numpy as np df = newdf[newdf['Race'] == 'Black'] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print(average,std) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] values = df['VaxRate'] weights= df['Prop_Weights'] average = np.ma.average(values, weights = weights, axis=0) variance = np.dot(weights, (values - average) ** 2) / weights.sum() std = np.sqrt(variance) print(average,std) white_w_average = average print(white_w_average - black_w_average) from matplotlib import pyplot as plt import seaborn as sns # sns.set_theme(style="ticks") sns.set_theme(style="whitegrid") sns.set(font_scale=1.4) def change_width(ax, new_value) : for patch in ax.patches : current_width = patch.get_width() diff = current_width - new_value # we change the bar width patch.set_width(new_value) # we recenter the bar patch.set_x(patch.get_x() + diff * .5) # import mylib newdf = newdf[newdf['Vaccination'] == 'Flu'] dims = (10, 6) # df = mylib.load_data() fig, ax = plt.subplots(figsize=dims) # seaborn.violinplot(ax=ax, data=df, **violin_options) ax.set(ylim=(0, 65)) if True: # df.to_csv('759_rate.csv') ax = sns.barplot(x="Race" , y="Vaccination Rate (%)", palette = ['grey', 'red'], # ci = 'sd', alpha = 0.5, # estimator = sum, data=newdf, errwidth = 2, errcolor = 'black', capsize=.4) change_width(ax, 0.6) else: ax = sns.barplot(x="Vaccination" , y="Vaccination Rate (%)", hue = 'Race', palette = ['grey', 'red'], alpha = 0.5, data=newdf, errwidth = 2, errcolor = 'black', capsize=.4) # ax.set_ylabel("Weighted Vaccination Rate (%)") # ax.set_title('Flu Vaccination Rate (759 Counties, 2019)') county_num = len(RawData) date = '2019' ax.set_ylabel("Weighted Vaccination Rate (%)") ax.set_title('Flu Vaccination Rate ({} Counties, {})'.format(county_num, date)) plt.show() print('April 19') Rate = RawData[[ 'FluVax_Disparity', 'FluVax_BlackRate', 'FluVax_NHWhiteRate',]].describe() Rate.to_clipboard() Rate fig.savefig('bar-flu.pdf', dpi=5000) ``` # Flu Bar Chart (Original) ``` from matplotlib import pyplot as plt import seaborn def change_width(ax, new_value) : for patch in ax.patches : current_width = patch.get_width() diff = current_width - new_value # we change the bar width patch.set_width(new_value) # we recenter the bar patch.set_x(patch.get_x() + diff * .5) # import mylib time = '2019' dims = (10, 6) # df = mylib.load_data() fig, ax = plt.subplots(figsize=dims) # seaborn.violinplot(ax=ax, data=df, **violin_options) ax.set(ylim=(0, 65)) # df.to_csv('759_rate.csv') ax = sns.barplot(x="Race" , y="VaxRate", palette = ['grey', 'red'], alpha = 0.5, data=newdf, errwidth = 2, errcolor = 'black', capsize=.3) change_width(ax, 0.5) ax.set_title('COVID-19 Vaccination Rate ({} Counties, {})'.format(county_num, time)) ax.set_ylabel('Flu Vaccination Rate %') plt.show() ``` # Flu Distribution ``` import pandas as pd from matplotlib import pyplot# as plt sns.set_theme(style="whitegrid") sns.set(font_scale=1.4) # Rate = T2[['Rate_Diff', 'Rate_Black', 'Rate_White', 'FluDiff', 'FluBlack', 'FluWhite',]].mean()*100 # Rate RawData = T3_Whole print(RawData.shape) dims = (10, 6) # df = mylib.load_data() fig, ax = pyplot.subplots(figsize=dims) ax = sns.distplot(RawData['FluVax_BlackRate'], hist=True, kde=True, bins=int(100), color = 'grey', kde_kws={'linewidth': 1}, label='Black') ax = sns.distplot(RawData['FluVax_NHWhiteRate'], hist=True, kde=True, bins=int(100), color = 'red', kde_kws={'linewidth': 1}, label='White') pyplot.legend(loc='best') county_num = len(RawData) date = '2019' ax.set_title('Flu Vaccination Rate Distribution ({} Counties, {})'.format(county_num, date)) ax.set(xlabel='Flu Vaccination Rate (%)') ax.set(ylabel ='Density') ax.set(xlim=(0, 100)) ax.set(ylim=(0, 0.155)) fig.savefig('dist-flu.pdf', dpi=5000) ``` # Black and NHWhite Weighted Proportion ``` import pandas as pd T2path = 'StataReg/0419-base/T2.csv' T2 = pd.read_csv(T2path) T3_Whole = T2[T2['Selected'] == 1].reset_index(drop = True) T3path = 'StataReg/0419-base/Data.dta' T3 = pd.read_stata(T3path) print(T3_Whole.shape) T3_Whole['Prop_Weights'] = T3_Whole['WholeNum'] / T3_Whole['WholeNum'].sum() * len(T3_Whole) print(T3_Whole['Prop_Weights'].sum()) import pandas as pd RawData = T3_Whole print(RawData.shape) L = [] for idx, row in RawData.iterrows(): d = row.to_dict() dn = {} # dn['Vaccination'] = 'COVID-19' dn['Race'] = 'Black' # dn['VaxRate'] = d['CvdVax_MBlackRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Republican'] = d['republican'] # dn['Vaccination Rate (%)'] = d['CvdVax_MBlackRate'] * d['Prop_Weights'] dn['RacePropotion'] = d['BlackNum'] / d['WholeNum'] L.append(dn) dn = {} # dn['Vaccination'] = 'COVID-19' dn['Race'] = 'White' # dn['VaxRate'] = d['CvdVax_MWhiteRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Republican'] = d['republican'] dn['RacePropotion'] = d['NHWhiteNum'] / d['WholeNum'] L.append(dn) dn = {} # dn['Vaccination'] = 'COVID-19' dn['Race'] = 'White-Black' # dn['VaxRate'] = d['CvdVax_MWhiteRate'] # * d['Prop_Weights'] dn['Prop_Weights'] = d['Prop_Weights'] dn['Republican'] = d['republican'] dn['RacePropotion'] = d['NHWhiteNum'] / d['WholeNum'] - d['BlackNum'] / d['WholeNum'] L.append(dn) newdf = pd.DataFrame(L) # print(newdf.shape) newdf 2268 / 3 import numpy as np print('Republican') df = newdf[newdf['Race'] == 'Black'] df = df[df['Republican'] == 1] repu_black_values = df['RacePropotion'] repu_black_weights= df['Prop_Weights'] average = np.ma.average(repu_black_values, weights = repu_black_weights, axis=0) variance = np.dot(repu_black_weights, (repu_black_values - average) ** 2) / repu_black_weights.sum() std = np.sqrt(variance) print('Black (w-mean, w-std):', average, std, ', county number:', len(df)) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] df = df[df['Republican'] == 1] repu_white_values = df['RacePropotion'] repu_white_weights= df['Prop_Weights'] average = np.ma.average(repu_white_values, weights = repu_white_weights, axis=0) variance = np.dot(repu_white_weights, (repu_white_values - average) ** 2) / repu_white_weights.sum() std = np.sqrt(variance) print('White (w-mean, w-std):', average,std, ', county number:', len(df)) white_w_average = average print('Diff:', white_w_average - black_w_average) import numpy as np df = newdf[newdf['Race'] == 'White-Black'] df = df[df['Republican'] == 1] repu_diff_values = df['RacePropotion'] repu_diff_weights= df['Prop_Weights'] average = np.ma.average(repu_diff_values, weights = repu_diff_weights, axis=0) variance = np.dot(repu_diff_weights, (repu_diff_values - average) ** 2) / repu_diff_weights.sum() std = np.sqrt(variance) print('White-Black (w-mean, w-std):', average, std, ', county number:', len(df)) import numpy as np print('Democratic') df = newdf[newdf['Race'] == 'Black'] df = df[df['Republican'] == 0] demo_black_values = df['RacePropotion'] demo_black_weights= df['Prop_Weights'] average = np.ma.average(demo_black_values, weights = demo_black_weights, axis=0) variance = np.dot(demo_black_weights, (demo_black_values - average) ** 2) / demo_black_weights.sum() std = np.sqrt(variance) print('Black (w-mean, w-std):', average, std, ', county number:', len(df)) black_w_average = average import numpy as np df = newdf[newdf['Race'] == 'White'] df = df[df['Republican'] == 0] demo_white_values = df['RacePropotion'] demo_white_weights= df['Prop_Weights'] average = np.ma.average(demo_white_values, weights = demo_white_weights, axis=0) variance = np.dot(demo_white_weights, (demo_white_values - average) ** 2) / demo_white_weights.sum() std = np.sqrt(variance) print('White (w-mean, w-std):', average,std, ', county number:', len(df)) white_w_average = average print('Diff:', white_w_average - black_w_average) import numpy as np df = newdf[newdf['Race'] == 'White-Black'] df = df[df['Republican'] == 0] demo_diff_values = df['RacePropotion'] demo_diff_weights= df['Prop_Weights'] average = np.ma.average(demo_diff_values, weights = demo_diff_weights, axis=0) variance = np.dot(demo_diff_weights, (demo_diff_values - average) ** 2) / demo_diff_weights.sum() std = np.sqrt(variance) print('White-Black (w-mean, w-std):', average, std, ', county number:', len(df)) # np.ma.average? from scipy import stats norm_weight = repu_diff_weights / repu_diff_weights.sum() repu_diff_weighted = (repu_diff_values * norm_weight).values print(len(repu_diff_weighted)) norm_weight = demo_diff_weights / demo_diff_weights.sum() demo_diff_weighted = (demo_diff_values * norm_weight).values print(len(demo_diff_weighted)) print(stats.ttest_ind(repu_diff_values, demo_diff_values)) print(stats.ttest_ind(repu_diff_weighted, demo_diff_weighted)) from scipy import stats norm_weight = repu_white_weights / repu_white_weights.sum() repu_white_weighted = (repu_white_values * norm_weight).values print(len(repu_white_weighted)) norm_weight = demo_white_weights / demo_white_weights.sum() demo_white_weighted = (demo_white_values * norm_weight).values print(len(demo_white_weighted)) print('For white') print(stats.ttest_ind(repu_white_values, demo_white_values)) print(stats.ttest_ind(repu_white_weighted, demo_white_weighted)) from scipy import stats norm_weight = repu_black_weights / repu_black_weights.sum() repu_black_weighted = (repu_black_values * norm_weight).values print(len(repu_black_weighted)) norm_weight = demo_black_weights / demo_black_weights.sum() demo_black_weighted = (demo_black_values * norm_weight).values print(len(demo_black_weighted)) print('For Black') print(stats.ttest_ind(repu_black_values, demo_black_values)) print(stats.ttest_ind(repu_black_weighted, demo_black_weighted)) # demo_diff_values from scipy import stats stats.ttest_ind(repu_diff_values, demo_diff_values) ```
github_jupyter
# Classification Think Bayes, Second Edition Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # 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 and create directories import os if not os.path.exists('utils.py'): !wget https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/utils.py from utils import set_pyplot_params set_pyplot_params() from utils import Or70, Pu50, Gr30 color_list3 = [Or70, Pu50, Gr30] import matplotlib.pyplot as plt from cycler import cycler marker_cycle = cycler(marker=['s', 'o', '^']) color_cycle = cycler(color=color_list3) line_cycle = cycler(linestyle=['-', '--', ':']) plt.rcParams['axes.prop_cycle'] = (color_cycle + marker_cycle + line_cycle) ``` Classification might be the most well-known application of Bayesian methods, made famous in the 1990s as the basis of the first generation of [spam filters](https://en.wikipedia.org/wiki/Naive_Bayes_spam_filtering). In this chapter, I'll demonstrate Bayesian classification using data collected and made available by Dr. Kristen Gorman at the Palmer Long-Term Ecological Research Station in Antarctica (see Gorman, Williams, and Fraser, ["Ecological Sexual Dimorphism and Environmental Variability within a Community of Antarctic Penguins (Genus *Pygoscelis*)"](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0090081), March 2014). We'll use this data to classify penguins by species. The following cell downloads the raw data. ``` # Load the data files from # https://github.com/allisonhorst/palmerpenguins # With gratitude to Allison Horst (@allison_horst) import os if not os.path.exists('penguins_raw.csv'): !wget https://github.com/allisonhorst/palmerpenguins/raw/master/inst/extdata/penguins_raw.csv ``` ## Penguin Data I'll use Pandas to load the data into a `DataFrame`. ``` import pandas as pd df = pd.read_csv('penguins_raw.csv') df.shape ``` The dataset contains one row for each penguin and one column for each variable. ``` df.head() ``` For convenience, I'll create a new column called `Species2` that contains a shorter version of the species names. ``` def shorten(species): return species.split()[0] df['Species2'] = df['Species'].apply(shorten) ``` Three species of penguins are represented in the dataset: Adélie, Chinstrap and Gentoo. These species are shown in this illustration (by Allison Horst, available under the [CC-BY](https://creativecommons.org/licenses/by/2.0/) license): <img width="400" src="https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/images/EaAWkZ0U4AA1CQf.jpeg" alt="Drawing of three penguin species"> The measurements we'll use are: * Body Mass in grams (g). * Flipper Length in millimeters (mm). * Culmen Length in millimeters. * Culmen Depth in millimeters. If you are not familiar with the word "culmen", it refers to the [top margin of the beak](https://en.wikipedia.org/wiki/Bird_measurement#Culmen). The culmen is shown in the following illustration (also by Allison Horst): <img width="300" src="https://github.com/AllenDowney/ThinkBayes2/raw/master/soln/images/EaAXQn8U4AAoKUj.jpeg"> These measurements will be most useful for classification if there are substantial differences between species and small variation within species. To see whether that is true, and to what degree, I'll plot cumulative distribution functions (CDFs) of each measurement for each species. The following function takes the `DataFrame` and a column name. It returns a dictionary that maps from each species name to a `Cdf` of the values in the column named `colname`. ``` def make_cdf_map(df, colname, by='Species2'): """Make a CDF for each species.""" cdf_map = {} grouped = df.groupby(by)[colname] for species, group in grouped: cdf_map[species] = Cdf.from_seq(group, name=species) return cdf_map ``` The following function plots a `Cdf` of the values in the given column for each species: ``` from empiricaldist import Cdf from utils import decorate def plot_cdfs(df, colname, by='Species2'): """Make a CDF for each species. df: DataFrame colname: string column name by: string column name returns: dictionary from species name to Cdf """ cdf_map = make_cdf_map(df, colname, by) for species, cdf in cdf_map.items(): cdf.plot(label=species, marker='') decorate(xlabel=colname, ylabel='CDF') ``` Here's what the distributions look like for culmen length. ``` colname = 'Culmen Length (mm)' plot_cdfs(df, colname) ``` It looks like we can use culmen length to identify Adélie penguins, but the distributions for the other two species almost entirely overlap. Here are the distributions for flipper length. ``` colname = 'Flipper Length (mm)' plot_cdfs(df, colname) ``` Using flipper length, we can distinguish Gentoo penguins from the other two species. So with just these two features, it seems like we should be able to classify penguins with some accuracy. All of these CDFs show the sigmoid shape characteristic of the normal distribution; I will take advantage of that observation in the next section. Here are the distributions for culmen depth. ``` colname = 'Culmen Depth (mm)' plot_cdfs(df, colname) ``` And here are the distributions of body mass. ``` colname = 'Body Mass (g)' plot_cdfs(df, colname) ``` Culmen depth and body mass distinguish Gentoo penguins from the other two species, but these features might not add a lot of additional information, beyond what we get from flipper length and culmen length. ## Normal Models Let's use these features to classify penguins. We'll proceed in the usual Bayesian way: 1. Define a prior distribution with the three possible species and a prior probability for each, 2. Compute the likelihood of the data for each hypothetical species, and then 3. Compute the posterior probability of each hypothesis. To compute the likelihood of the data under each hypothesis, I'll use the data to estimate the parameters of a normal distribution for each species. The following function takes a `DataFrame` and a column name; it returns a dictionary that maps from each species name to a `norm` object. `norm` is defined in SciPy; it represents a normal distribution with a given mean and standard deviation. ``` from scipy.stats import norm def make_norm_map(df, colname, by='Species2'): """Make a map from species to norm object.""" norm_map = {} grouped = df.groupby(by)[colname] for species, group in grouped: mean = group.mean() std = group.std() norm_map[species] = norm(mean, std) return norm_map ``` For example, here's the dictionary of `norm` objects for flipper length: ``` flipper_map = make_norm_map(df, 'Flipper Length (mm)') flipper_map.keys() ``` Now suppose we measure a penguin and find that its flipper is 193 cm. What is the probability of that measurement under each hypothesis? The `norm` object provides `pdf`, which computes the probability density function (PDF) of the normal distribution. We can use it to compute the likelihood of the observed data in a given distribution. ``` data = 193 flipper_map['Adelie'].pdf(data) ``` The result is a probability density, so we can't interpret it as a probability. But it is proportional to the likelihood of the data, so we can use it to update the prior. Here's how we compute the likelihood of the data in each distribution. ``` hypos = flipper_map.keys() likelihood = [flipper_map[hypo].pdf(data) for hypo in hypos] likelihood ``` Now we're ready to do the update. ## The Update As usual I'll use a `Pmf` to represent the prior distribution. For simplicity, let's assume that the three species are equally likely. ``` from empiricaldist import Pmf prior = Pmf(1/3, hypos) prior ``` Now we can do the update in the usual way. ``` posterior = prior * likelihood posterior.normalize() posterior ``` A penguin with a 193 mm flipper is unlikely to be a Gentoo, but might be either an Adélie or Chinstrap (assuming that the three species were equally likely before the measurement). The following function encapsulates the steps we just ran. It takes a `Pmf` representing the prior distribution, the observed data, and a map from each hypothesis to the distribution of the feature. ``` def update_penguin(prior, data, norm_map): """Update hypothetical species.""" hypos = prior.qs likelihood = [norm_map[hypo].pdf(data) for hypo in hypos] posterior = prior * likelihood posterior.normalize() return posterior ``` The return value is the posterior distribution. Here's the previous example again, using `update_penguin`: ``` posterior1 = update_penguin(prior, 193, flipper_map) posterior1 ``` As we saw in the CDFs, flipper length does not distinguish strongly between Adélie and Chinstrap penguins. But culmen length *can* make this distinction, so let's use it to do a second round of classification. First we estimate distributions of culmen length for each species like this: ``` culmen_map = make_norm_map(df, 'Culmen Length (mm)') ``` Now suppose we see a penguin with culmen length 48 mm. We can use this data to update the prior. ``` posterior2 = update_penguin(prior, 48, culmen_map) posterior2 ``` A penguin with culmen length 48 mm is about equally likely to be a Chinstrap or Gentoo. Using one feature at a time, we can often rule out one species or another, but we generally can't identify species with confidence. We can do better using multiple features. ## Naive Bayesian Classification To make it easier to do multiple updates, I'll use the following function, which takes a prior `Pmf`, a sequence of measurements and a corresponding sequence of dictionaries containing estimated distributions. ``` def update_naive(prior, data_seq, norm_maps): """Naive Bayesian classifier prior: Pmf data_seq: sequence of measurements norm_maps: sequence of maps from species to distribution returns: Pmf representing the posterior distribution """ posterior = prior.copy() for data, norm_map in zip(data_seq, norm_maps): posterior = update_penguin(posterior, data, norm_map) return posterior ``` It performs a series of updates, using one variable at a time, and returns the posterior `Pmf`. To test it, I'll use the same features we looked at in the previous section: culmen length and flipper length. ``` colnames = ['Flipper Length (mm)', 'Culmen Length (mm)'] norm_maps = [flipper_map, culmen_map] ``` Now suppose we find a penguin with flipper length 193 mm and culmen length 48. Here's the update: ``` data_seq = 193, 48 posterior = update_naive(prior, data_seq, norm_maps) posterior ``` It is almost certain to be a Chinstrap. ``` posterior.max_prob() ``` We can loop through the dataset and classify each penguin with these two features. ``` import numpy as np df['Classification'] = np.nan for i, row in df.iterrows(): data_seq = row[colnames] posterior = update_naive(prior, data_seq, norm_maps) df.loc[i, 'Classification'] = posterior.max_prob() ``` This loop adds a column called `Classification` to the `DataFrame`; it contains the species with the maximum posterior probability for each penguin. So let's see how many we got right. ``` len(df) valid = df['Classification'].notna() valid.sum() same = df['Species2'] == df['Classification'] same.sum() ``` There are 344 penguins in the dataset, but two of them are missing measurements, so we have 342 valid cases. Of those, 324 are classified correctly, which is almost 95%. ``` same.sum() / valid.sum() ``` The following function encapsulates these steps. ``` def accuracy(df): """Compute the accuracy of classification.""" valid = df['Classification'].notna() same = df['Species2'] == df['Classification'] return same.sum() / valid.sum() ``` The classifier we used in this section is called "naive" because it ignores correlations between the features. To see why that matters, I'll make a less naive classifier: one that takes into account the joint distribution of the features. ## Joint Distributions I'll start by making a scatter plot of the data. ``` import matplotlib.pyplot as plt def scatterplot(df, var1, var2): """Make a scatter plot.""" grouped = df.groupby('Species2') for species, group in grouped: plt.plot(group[var1], group[var2], label=species, lw=0, alpha=0.3) decorate(xlabel=var1, ylabel=var2) ``` Here's a scatter plot of culmen length and flipper length for the three species. ``` var1 = 'Flipper Length (mm)' var2 = 'Culmen Length (mm)' scatterplot(df, var1, var2) ``` Within each species, the joint distribution of these measurements forms an oval shape, at least roughly. The orientation of the ovals is along a diagonal, which indicates that there is a correlation between culmen length and flipper length. If we ignore these correlations, we are assuming that the features are independent. To see what that looks like, I'll make a joint distribution for each species assuming independence. The following function makes a discrete `Pmf` that approximates a normal distribution. ``` def make_pmf_norm(dist, sigmas=3, n=101): """Make a Pmf approximation to a normal distribution.""" mean, std = dist.mean(), dist.std() low = mean - sigmas * std high = mean + sigmas * std qs = np.linspace(low, high, n) ps = dist.pdf(qs) pmf = Pmf(ps, qs) pmf.normalize() return pmf ``` We can use it, along with `make_joint`, to make a joint distribution of culmen length and flipper length for each species. ``` from utils import make_joint joint_map = {} for species in hypos: pmf1 = make_pmf_norm(flipper_map[species]) pmf2 = make_pmf_norm(culmen_map[species]) joint_map[species] = make_joint(pmf1, pmf2) ``` The following figure compares a scatter plot of the data to the contours of the joint distributions, assuming independence. ``` from utils import plot_contour scatterplot(df, var1, var2) for species in hypos: plot_contour(joint_map[species], alpha=0.5) ``` The contours of a joint normal distribution form ellipses. In this example, because the features are uncorrelated, the ellipses are aligned with the axes. But they are not well aligned with the data. We can make a better model of the data, and use it to compute better likelihoods, with a multivariate normal distribution. ## Multivariate Normal Distribution As we have seen, a univariate normal distribution is characterized by its mean and standard deviation. A multivariate normal distribution is characterized by the means of the features and the **covariance matrix**, which contains **variances**, which quantify the spread of the features, and the **covariances**, which quantify the relationships among them. We can use the data to estimate the means and covariance matrix for the population of penguins. First I'll select the columns we want. ``` features = df[[var1, var2]] ``` And compute the means. ``` mean = features.mean() mean ``` We can also compute the covariance matrix: ``` cov = features.cov() cov ``` The result is a `DataFrame` with one row and one column for each feature. The elements on the diagonal are the variances; the elements off the diagonal are covariances. By themselves, variances and covariances are hard to interpret. We can use them to compute standard deviations and correlation coefficients, which are easier to interpret, but the details of that calculation are not important right now. Instead, we'll pass the covariance matrix to `multivariate_normal` which is a SciPy function that creates an object that represents a multivariate normal distribution. As arguments it takes a sequence of means and a covariance matrix: ``` from scipy.stats import multivariate_normal multinorm = multivariate_normal(mean, cov) ``` The following function makes a `multivariate_normal` object for each species. ``` def make_multinorm_map(df, colnames): """Make a map from each species to a multivariate normal.""" multinorm_map = {} grouped = df.groupby('Species2') for species, group in grouped: features = group[colnames] mean = features.mean() cov = features.cov() multinorm_map[species] = multivariate_normal(mean, cov) return multinorm_map ``` Here's how we make this map for the first two features, flipper length and culmen length. ``` multinorm_map = make_multinorm_map(df, [var1, var2]) ``` ## Visualizing a Multivariate Normal Distribution This section uses some NumPy magic to generate contour plots for multivariate normal distributions. If that's interesting for you, great! Otherwise, feel free to skip to the results. In the next section we'll do the actual classification, which turns out to be easier than the visualization. I'll start by making a contour map for the distribution of features among Adélie penguins. Here are the univariate distributions for the two features we'll use and the multivariate distribution we just computed. ``` norm1 = flipper_map['Adelie'] norm2 = culmen_map['Adelie'] multinorm = multinorm_map['Adelie'] ``` I'll make a discrete `Pmf` approximation for each of the univariate distributions. ``` pmf1 = make_pmf_norm(norm1) pmf2 = make_pmf_norm(norm2) ``` And use them to make a mesh grid that contains all pairs of values. ``` X, Y = np.meshgrid(pmf1.qs, pmf2.qs) X.shape ``` The mesh is represented by two arrays: the first contains the quantities from `pmf1` along the `x` axis; the second contains the quantities from `pmf2` along the `y` axis. In order to evaluate the multivariate distribution for each pair of values, we have to "stack" the arrays. ``` pos = np.dstack((X, Y)) pos.shape ``` The result is a 3-D array that you can think of as a 2-D array of pairs. When we pass this array to `multinorm.pdf`, it evaluates the probability density function of the distribution for each pair of values. ``` densities = multinorm.pdf(pos) densities.shape ``` The result is an array of probability densities. If we put them in a `DataFrame` and normalize them, the result is a discrete approximation of the joint distribution of the two features. ``` from utils import normalize joint = pd.DataFrame(densities, columns=pmf1.qs, index=pmf2.qs) normalize(joint) ``` Here's what the result looks like. ``` plot_contour(joint) decorate(xlabel=var1, ylabel=var2) ``` The contours of a multivariate normal distribution are still ellipses, but now that we have taken into account the correlation between the features, the ellipses are no longer aligned with the axes. The following function encapsulate the steps we just did. ``` def make_joint(norm1, norm2, multinorm): """Make a joint distribution. norm1: `norm` object representing the distribution of the first feature norm2: `norm` object representing the distribution of the second feature multinorm: `multivariate_normal` object representing the joint distribution """ pmf1 = make_pmf_norm(norm1) pmf2 = make_pmf_norm(norm2) X, Y = np.meshgrid(pmf1.qs, pmf2.qs) pos = np.dstack((X, Y)) densities = multinorm.pdf(pos) joint = pd.DataFrame(densities, columns=pmf1.qs, index=pmf2.qs) return joint ``` The following figure shows a scatter plot of the data along with the contours of the multivariate normal distribution for each species. ``` scatterplot(df, var1, var2) for species in hypos: norm1 = flipper_map[species] norm2 = culmen_map[species] multinorm = multinorm_map[species] joint = make_joint(norm1, norm2, multinorm) plot_contour(joint, alpha=0.5) ``` Because the multivariate normal distribution takes into account the correlations between features, it is a better model for the data. And there is less overlap in the contours of the three distributions, which suggests that they should yield better classifications. ## A Less Naive Classifier In a previous section we used `update_penguin` to update a prior `Pmf` based on observed data and a collection of `norm` objects that model the distribution of observations under each hypothesis. Here it is again: ``` def update_penguin(prior, data, norm_map): """Update hypothetical species.""" hypos = prior.qs likelihood = [norm_map[hypo].pdf(data) for hypo in hypos] posterior = prior * likelihood posterior.normalize() return posterior ``` Last time we used this function, the values in `norm_map` were `norm` objects, but it also works if they are `multivariate_normal` objects. We can use it to classify a penguin with flipper length 193 and culmen length 48: ``` data = 193, 48 update_penguin(prior, data, multinorm_map) ``` A penguin with those measurements is almost certainly an Chinstrap. Now let's see if this classifier does any better than the naive Bayesian classifier. I'll apply it to each penguin in the dataset: ``` df['Classification'] = np.nan for i, row in df.iterrows(): data = row[colnames] posterior = update_penguin(prior, data, multinorm_map) df.loc[i, 'Classification'] = posterior.idxmax() ``` And compute the accuracy: ``` accuracy(df) ``` It turns out to be only a little better: the accuracy is 95.3%, compared to 94.7% for the naive Bayesian classifier. ## Summary In this chapter, we implemented a naive Bayesian classifier, which is "naive" in the sense that it assumes that the features is uses for classification are independent. To see how bad that assumption is, we also implemented a classifier that uses the a multivariate normal distribution to model the joint distribution of the features, which includes their dependencies. In this example, the non-naive classifier is only marginally better. In one way, that's disappointing. After all that work, it would have been nice to see a bigger improvement. But in another way, it's good news. In general, a naive Bayesian classifier is easier to implement and requires less computation. If it works nearly as well as a more complex algorithm, it might be a good choice for practical purposes. Speaking of practical purposes, you might have noticed that this example isn't very useful. If we want to identify the species of a penguin, there are easier ways than measuring its flippers and beak. But there *are* scientific uses for this type of classification. One of them is the subject of the research paper we started with: [sexual dimorphism](https://en.wikipedia.org/wiki/Sexual_dimorphism), that is, differences in shape between male and female animals. In some species, like angler fish, males and females look very different. In other species, like mockingbirds, they are difficult to tell apart. And dimorphism is worth studying because it provides insight into social behavior, sexual selection, and evolution. One way to quantify the degree of sexual dimorphism in a species is to use a classification algorithm like the one in this chapter. If you can find a set of features that makes it possible to classify individuals by sex with high accuracy, that's evidence of high dimorphism. As an exercise, you can use the dataset from this chapter to classify penguins by sex and see which of the three species is the most dimorphic. ## Exercises **Exercise:** In my example I used culmen length and flipper length because they seemed to provide the most power to distinguish the three species. But maybe we can do better by using more features. Make a naive Bayesian classifier that uses all four measurements in the dataset: culmen length and depth, flipper length, and body mass. Is it more accurate than the model with two features? ``` # Solution goes here # Solution goes here # Solution goes here ``` **Exercise:** One of the reasons the penguin dataset was collected was to quantify sexual dimorphism in different penguin species, that is, physical differences between male and female penguins. One way to quantify dimorphism is to use measurements to classify penguins by sex. If a species is more dimorphic, we expect to be able to classify them more accurately. As an exercise, pick a species and use a Bayesian classifier (naive or not) to classify the penguins by sex. Which features are most useful? What accuracy can you achieve? Note: One Gentoo penguin has an invalid value for `Sex`. I used the following code to select one species and filter out invalid data. ``` gentoo = (df['Species2'] == 'Gentoo') subset = df[gentoo].copy() subset['Sex'].value_counts() valid = df['Sex'] != '.' valid.sum() subset = df[valid & gentoo].copy() ``` OK, you can finish it off from here. ``` # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here ```
github_jupyter
``` import sys sys.path.append('../scripts/') from robot import * from scipy.stats import multivariate_normal class Particle: ###particle_obs_update(observaiton_updateメソッドだけ) def __init__(self, init_pose): self.pose = init_pose def motion_update(self, nu, omega, time, noise_rate_pdf): ns = noise_rate_pdf.rvs() noised_nu = nu + ns[0]*math.sqrt(abs(nu)/time) + ns[1]*math.sqrt(abs(omega)/time) noised_omega = omega + ns[2]*math.sqrt(abs(nu)/time) + ns[3]*math.sqrt(abs(omega)/time) self.pose = IdealRobot.state_transition(noised_nu, noised_omega, time, self.pose) def observation_update(self, observation): print(observation) class Mcl: ###mcl_obs(1行目とobservaiton_updateメソッドだけ) def __init__(self, init_pose, num, motion_noise_stds={"nn":0.19, "no":0.001, "on":0.13, "oo":0.2}): self.particles = [Particle(init_pose) for i in range(num)] v = motion_noise_stds c = np.diag([v["nn"]**2, v["no"]**2, v["on"]**2, v["oo"]**2]) self.motion_noise_rate_pdf = multivariate_normal(cov=c) def motion_update(self, nu, omega, time): for p in self.particles: p.motion_update(nu, omega, time, self.motion_noise_rate_pdf) def observation_update(self, observation): #メソッド追加 for p in self.particles: p.observation_update(observation) def draw(self, ax, elems): xs = [p.pose[0] for p in self.particles] ys = [p.pose[1] for p in self.particles] vxs = [math.cos(p.pose[2]) for p in self.particles] vys = [math.sin(p.pose[2]) for p in self.particles] elems.append(ax.quiver(xs, ys, vxs, vys, color="blue", alpha=0.5)) class EstimationAgent(Agent): def __init__(self, time_interval, nu, omega, estimator): super().__init__(nu, omega) self.estimator = estimator self.time_interval = time_interval self.prev_nu = 0.0 self.prev_omega = 0.0 def decision(self, observation=None): ###mcl_agent_obs self.estimator.motion_update(self.prev_nu, self.prev_omega, self.time_interval) self.prev_nu, self.prev_omega = self.nu, self.omega self.estimator.observation_update(observation) #追加 return self.nu, self.omega def draw(self, ax, elems): self.estimator.draw(ax, elems) def trial(): ###mcl_obs_prepare time_interval = 0.1 world = World(30, time_interval, debug=False) ### 地図を生成して3つランドマークを追加 ### m = Map() for ln in [(-4,2), (2,-3), (3,3)]: m.append_landmark(Landmark(*ln)) world.append(m) ### ロボットを作る ### initial_pose = np.array([0, 0, 0]).T #初期位置を原点に estimator = Mcl(initial_pose, 100) a = EstimationAgent(time_interval, 0.2, 10.0/180*math.pi, estimator) #EstimationAgentに r = Robot(initial_pose, sensor=Camera(m), agent=a, color="red") world.append(r) world.draw() trial() ```
github_jupyter
# Reinforcement Learning # Introduction - "A gazelle calf struggles to its feet minutes after being born. Half an hour later it is running at 20 miles per hour." - Sutton and Barto <img src="images/gazelle.jpeg" style="width: 600px;"/> - Google's AlphaGo used deep reinforcement learning in order to defeat world champion Lee Sedol at Go. <img src="images/go.jpg" style="width: 600px;"/> # Goal - Agent interacts dynamically with its environment, moves from one state to another. - Based on the actions taken by the agent, rewards are given. - Guidelines for which action to take in each state is called a policy. - Try to efficiently find an optimal policy in which rewards are maximized. <img src="images/RL_diagram.png" style="width: 600px;"> ## This is Different from Supervised Learning * Supervised Learning * "learning from examples provided by a knowledgeable external supervisor" * For any state that the agent may be in, the supervisor can supply enough relevant examples of the outcomes which result from similar states so that we may make an accurate prediction. * Reinforcement Learning * No supervisor exists * Agent must learn from experience as it explores the range of possible states * Continuously update policy in response to new information. # Examples <table class="table table-bordered"> <font size="3"> <tl> <th> agent </th> <th> environment </th> <th> actions </th> <th> rewards </th> <th> policy </th> </tl> <tr> <td> robot arm </td> <td> set of arm positions </td> <td> bend elbow, close hand, extend arm, etc. </td> <td> reward when door successfully opened </td> <td> most efficient set of movements to open door </td> </tl> <tr> <td> board game player </td> <td> set of all game configs. </td> <td> legal moves </td> <td> winning the game </td> <td> optimal strategy </td> </tr> <tr> <td> mouse </td> <td> maze </td> <td> running, turning </td> <td> cheese </td> <td> most direct path to cheese </td> </tr> <tr> <td> credit card company </td> <td> set of all customers in default </td> <td> set of collections actions </td> <td> cost for each attempt, reward for successful collection </td> <td> optimal strategy for debt collections </td> </tr> <tr> <td> marketing team </td> <td> sets of potential customers and ads that can be shown </td> <td> showing an ad to a potential customer </td> <td> cost of placing ad, value of customer's business </td> <td> optimal ad placement strategy </td> </tr> <tr> <td> call center </td> <td> status of each customer in queue </td> <td> connecting customers to representatives </td> <td> customer satisfaction </td> <td> optimal queueing strategy </td> </tr> <tr> <td> Website Designer </td> <td> set of possible layout options </td> <td> changing layout </td> <td> increased click-through rate </td> <td> ideal layout </td> </tr> </font> </table> # Exploration vs Exploitation - In the absence of a Supervisor, the agent must exlore the environment in order to gain information about rewards, while exploiting it's current information to maximize it's rewards. - Balancing this tradeoff is a common theme # Multi-Armed Bandits - A single state example Multi-armed bandit problems are some of the simplest reinforcement learning (RL) problems to solve. We have an agent which we allow to choose actions, and each action has a reward that is returned according to a given, underlying probability distribution. The game is played over many episodes (single actions in this case) and the goal is to maximize your reward. One way to approach this is to select each one in turn and keep track of how much you received, then keep going back to the one that paid out the most. This is possible, but, as stated before, each bandit has an underlying probability distribution associated with it, meaning that you may need more samples before finding the right one. But, each pull you spend trying to figure out the best bandit to play takes you away from maximizing your reward. This basic balancing act is known as the explore-exploit dilemma. * Given N different arms to choose from, each with an unknown reward, what strategy should we use to explore and learn the values of each arm, while exploiting our current knowledge to maximize profit? * This is a very common approach for optimizing online marketing campaigns. * This can be thought of as a single-state reinforcement learning problem <img src="images/MAB.jpg" style="width: 400px;"/> ## Epsilon-greedy - A fraction (1 - $\epsilon$) of the time, choose the arm with the largest estimated value (exploit) - The other $\epsilon$ of the time, chose a random arm (explore) - Tune $\epsilon$ in order to balance tradeoff <img src="images/epsilongreedy.png" style="width: 400px;"/> # Problem Setup To get started, let’s describe the problem in a bit more technical detail. What we wish to do, is develop an estimate $Q_t(a)$: $$Q_t(a)=E[R_n|A_n=a]$$ Where $Q_t(a)$ is the estimated, expected reward $R_n$, when action $A_n$ is taken at step n. We’re going to iteratively build a model that will converge towards the true value of each action. We’re going to use a Gaussian (normal) distribution for all of the underlying probability distributions that we’ll explore so that the mean corresponds to the true value (after all, given enough samples, we would expect our rewards to converge to the mean of the selected action). The simplest way to proceed is to take the greedy action or take the action we think will maximize our reward at each time step. Another way of writing this is: $$A_n=argmax_a(Q_n(a))$$ We can denote this maximum expectation or greedy action as A*n. This is the exploit side of our aforementioned explore-exploit dilemma, and it makes lots of sense if the goal is to maximize our reward. Of course, doing this repeatedly only works well once we have a good sense of our expected rewards for each actions (unless we get rather lucky). So, we need to figure out an algorithm that explores enough of our search space so that we can exploit the best actions. # Average Reward Method Before jumping into this, there’s one last concept to introduce. In typical RL applications, we may need hundreds of thousands of iterations, if not millions or more. It quickly becomes very computationally intensive to run simulations of these sorts and keep track of all that data just to calculate the average reward. To avoid this, we can use a handy formula so that all we need to track are two values: the mean and number of steps taken. If we need to calculate the mean at step n, m_n, we can do it with the previous mean, m_n−1​ and n as follows: $$m_n=m_{n-1}+\frac{R_n-m_{n-1}}{n}$$ ## Building a greedy k-Armed Bandit We’re going to define a class called <b>eps_bandit </b> to be able to run our experiment. This class takes number of arms, k, epsilon value eps, number of iterations iter as inputs. We'll also define a term mu that we can use to adjust the average rewards of each of the arms. ### First the modules: ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd %matplotlib inline ``` epsilon-greedy k-bandit problem Inputs k: number of arms (int) eps: probability of random action 0 < eps < 1 (float) iters: number of steps (int) mu: set the average rewards for each of the k-arms. Set to "random" for the rewards to be selected from a normal distribution with mean = 0. Set to "sequence" for the means to be ordered from 0 to k-1. Pass a list or array of length = k for user-defined values. ``` class eps_bandit: def __init__(self, k, eps, iters, mu='random'): # Number of arms self.k = k # Search probability self.eps = eps # Number of iterations self.iters = iters # Step count self.n = 0 # Step count for each arm self.k_n = np.zeros(k) # Total mean reward self.mean_reward = 0 self.reward = np.zeros(iters) # Mean reward for each arm _ this is the estimated action value self.k_reward = np.zeros(k) if type(mu) == list or type(mu).__module__ == np.__name__: # User-defined averages self.mu = np.array(mu) elif mu == 'random': # Draw means from probability distribution self.mu = np.random.normal(0, 1, k) elif mu == 'sequence': # Increase the mean for each arm by one self.mu = np.linspace(0, k-1, k) def pull(self): # Generate random number p = np.random.rand() if self.eps == 0 and self.n == 0: a = np.random.choice(self.k) elif p < self.eps: # Randomly select an action a = np.random.choice(self.k) else: # Take greedy action a = np.argmax(self.k_reward) # reward function is a normal distribution with mean mu and varaiance 1 reward = np.random.normal(self.mu[a], 1) # Update counts self.n += 1 self.k_n[a] += 1 # Update total self.mean_reward = self.mean_reward + ( reward - self.mean_reward) / self.n # Update results for a_k self.k_reward[a] = self.k_reward[a] + ( reward - self.k_reward[a]) / self.k_n[a] def run(self): for i in range(self.iters): self.pull() self.reward[i] = self.mean_reward def reset(self): # Resets results while keeping settings self.n = 0 self.k_n = np.zeros(k) self.mean_reward = 0 self.reward = np.zeros(iters) self.k_reward = np.zeros(k) ``` There are plenty of different ways to define this class. I did it so that once we initialize our problem, we just call the **run()** method and can examine the outputs. By default, the average rewards for each arm are drawn from a normal distribution around 0. Setting mu="sequence" will cause the rewards to range from 0 to k-1 to make it easy to know which actions provide the best rewards when evaluating the results and which actions were taken. Finally, you could also set your own average rewards by passing values to mu. Let’s set up some comparisons using different values of ϵ\epsilonϵ. For each of these, we’ll set k=10, run 1,000 steps for each episode and run 1,000 episodes. After each episode, we will reset the bandits and copy the averages across the different bandits to keep things consistent. ## Let's run the bandit for three different epsilons ``` k = 10 iters = 1000 eps_0_rewards = np.zeros(iters) eps_01_rewards = np.zeros(iters) eps_1_rewards = np.zeros(iters) episodes = 1000 # Run experiments for i in range(episodes): # Initialize bandits eps_0 = eps_bandit(k, 0, iters) eps_01 = eps_bandit(k, 0.01, iters, eps_0.mu.copy()) eps_1 = eps_bandit(k, 0.1, iters, eps_0.mu.copy()) # Run experiments eps_0.run() eps_01.run() eps_1.run() # Update long-term averages eps_0_rewards = eps_0_rewards + ( eps_0.reward - eps_0_rewards) / (i + 1) eps_01_rewards = eps_01_rewards + ( eps_01.reward - eps_01_rewards) / (i + 1) eps_1_rewards = eps_1_rewards + ( eps_1.reward - eps_1_rewards) / (i + 1) plt.figure(figsize=(12,8)) plt.plot(eps_0_rewards, label="$\epsilon=0$ (greedy)") plt.plot(eps_01_rewards, label="$\epsilon=0.01$") plt.plot(eps_1_rewards, label="$\epsilon=0.1$") plt.legend(bbox_to_anchor=(1.3, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average $\epsilon-greedy$ Rewards after " + str(episodes) + " Episodes") plt.show() ``` Looking at the results, the greedy function under performs the other two consistently, with ϵ=0.01 coming in between the two and ϵ=0.1 performing the best of the three here. Below, we can see the effect is clearer using the sequence argument, and can get a feel for how often the optimal action is taken per episode because the averages remain consistent across episodes. ## Now we count the average taken action ### To do so, we use sequence reward function to make the comparision tracktable ``` k = 10 iters = 1000 eps_0_rewards = np.zeros(iters) eps_01_rewards = np.zeros(iters) eps_1_rewards = np.zeros(iters) eps_0_selection = np.zeros(k) eps_01_selection = np.zeros(k) eps_1_selection = np.zeros(k) episodes = 1000 # Run experiments for i in range(episodes): # Initialize bandits eps_0 = eps_bandit(k, 0, iters, mu='sequence') eps_01 = eps_bandit(k, 0.01, iters, eps_0.mu.copy()) eps_1 = eps_bandit(k, 0.1, iters, eps_0.mu.copy()) # Run experiments eps_0.run() eps_01.run() eps_1.run() # Update long-term averages eps_0_rewards = eps_0_rewards + ( eps_0.reward - eps_0_rewards) / (i + 1) eps_01_rewards = eps_01_rewards + ( eps_01.reward - eps_01_rewards) / (i + 1) eps_1_rewards = eps_1_rewards + ( eps_1.reward - eps_1_rewards) / (i + 1) # Average actions per episode eps_0_selection = eps_0_selection + ( eps_0.k_n - eps_0_selection) / (i + 1) eps_01_selection = eps_01_selection + ( eps_01.k_n - eps_01_selection) / (i + 1) eps_1_selection = eps_1_selection + ( eps_1.k_n - eps_1_selection) / (i + 1) plt.figure(figsize=(12,8)) plt.plot(eps_0_rewards, label="$\epsilon=0$ (greedy)") plt.plot(eps_01_rewards, label="$\epsilon=0.01$") plt.plot(eps_1_rewards, label="$\epsilon=0.1$") for i in range(k): plt.hlines(eps_0.mu[i], xmin=0, xmax=iters, alpha=0.5, linestyle="--") plt.legend(bbox_to_anchor=(1.3, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average $\epsilon-greedy$ Rewards after " + str(episodes) + " Episodes") plt.show() bins = np.linspace(0, k-1, k) plt.figure(figsize=(12,8)) plt.bar(bins, eps_0_selection, width = 0.33, color='b', label="$\epsilon=0$") plt.bar(bins+0.33, eps_01_selection, width=0.33, color='g', label="$\epsilon=0.01$") plt.bar(bins+0.66, eps_1_selection, width=0.33, color='r', label="$\epsilon=0.1$") plt.legend(bbox_to_anchor=(1.2, 0.5)) plt.xlim([0,k]) plt.title("Actions Selected by Each Algorithm") plt.xlabel("Action") plt.ylabel("Number of Actions Taken") plt.show() opt_per = np.array([eps_0_selection, eps_01_selection, eps_1_selection]) / iters * 100 df = pd.DataFrame(opt_per, index=['$\epsilon=0$', '$\epsilon=0.01$', '$\epsilon=0.1$'], columns=["a = " + str(x) for x in range(0, k)]) print("Percentage of actions selected:") df ``` Viewing the average selection of the algorithms, we see why the larger ϵ value performs well, it takes the optimal selection 80% of the time. Play around with the different values of both ϵ and k to see how these results change. For example, decreasing the search space would likely benefit smaller values of ϵ as exploration would be less beneficial and vice versa. Additionally, increasing the number of iterations will begin to benefit the lower value of ϵ because it will have less random noise. ## ϵ-Decay Strategies The ϵ-greedy strategies have an obvious weakness in that they continue to include random noise no matter how many examples they see. It would be better for these to settle on an optimal solution and continue to exploit it. To this end, we can introduce ϵ-decay which reduces the probability of exploration with every step. This works by defining ϵ as a function of the number of steps, n. $$\epsilon(n)=\frac{1}{1+n\beta}$$ Where β<1 is introduced as a scaling factor to reduce the scaling rate so that the algorithm has sufficient opportunity to explore. In this case, we also include +1 in the denominator to prevent infinities from appearing. Given this, we can make a few small changes to our previous class of bandits to define an eps_decay_bandit class that works on the same principles. ``` class eps_decay_bandit: def __init__(self, k, iters, mu='random'): # Number of arms self.k = k # Number of iterations self.iters = iters # Step count self.n = 0 # Step count for each arm self.k_n = np.zeros(k) # Total mean reward self.mean_reward = 0 self.reward = np.zeros(iters) # Mean reward for each arm self.k_reward = np.zeros(k) if type(mu) == list or type(mu).__module__ == np.__name__: # User-defined averages self.mu = np.array(mu) elif mu == 'random': # Draw means from probability distribution self.mu = np.random.normal(0, 1, k) elif mu == 'sequence': # Increase the mean for each arm by one self.mu = np.linspace(0, k-1, k) def pull(self): # Generate random number p = np.random.rand() if p < 1 / (1 + self.n / self.k): # Randomly select an action a = np.random.choice(self.k) else: # Take greedy action a = np.argmax(self.k_reward) reward = np.random.normal(self.mu[a], 1) # Update counts self.n += 1 self.k_n[a] += 1 # Update total self.mean_reward = self.mean_reward + ( reward - self.mean_reward) / self.n # Update results for a_k self.k_reward[a] = self.k_reward[a] + ( reward - self.k_reward[a]) / self.k_n[a] def run(self): for i in range(self.iters): self.pull() self.reward[i] = self.mean_reward def reset(self): # Resets results while keeping settings self.n = 0 self.k_n = np.zeros(k) self.mean_reward = 0 self.reward = np.zeros(iters) self.k_reward = np.zeros(k) k = 10 iters = 1000 eps_decay_rewards = np.zeros(iters) eps_1_rewards = np.zeros(iters) episodes = 1000 # Run experiments for i in range(episodes): # Initialize bandits eps_decay = eps_decay_bandit(k, iters) eps_1 = eps_bandit(k, 0.1, iters, eps_decay.mu.copy()) # Run experiments eps_decay.run() eps_1.run() # Update long-term averages eps_decay_rewards = eps_decay_rewards + ( eps_decay.reward - eps_decay_rewards) / (i + 1) eps_1_rewards = eps_1_rewards + ( eps_1.reward - eps_1_rewards) / (i + 1) plt.figure(figsize=(12,8)) plt.plot(eps_decay_rewards, label="$\epsilon-decay$") plt.plot(eps_1_rewards, label="$\epsilon=0.1$") plt.legend(bbox_to_anchor=(1.2, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average $\epsilon-decay$ and" + "$\epsilon-greedy$ Rewards after " + str(episodes) + " Episodes") plt.show() ``` The ϵ-decay strategy outperforms our previous best algorithm as it sticks to the optimal action once it is found. There’s one last method to balance the explore-exploit dilemma in k-bandit problems, optimistic initial values. ## Optimistic Initial Value This approach differs significantly from the previous examples we explored because it does not introduce random noise to find the best action, A*_n​. Instead, we over estimate the rewards of all the actions and continuously select the maximum. In this case, the algorithm explores early on as it seeks to maximize its returns while additional information allows the values to converge to their true means. This approach does require some additional background knowledge to be included in the set up because we need at least some idea of what the rewards are so that we can over estimate them. For this implementation, we don’t need a new class. Instead, we can simply use our eps_bandit class and set ϵ=0 and provide high, initial values for the estimates. Also, I like to initialize the pull count for each arm as 1 instead of 0 to encourage slightly slower convergence and ensure good exploration. ``` k = 10 iters = 1000 oiv_rewards = np.zeros(iters) eps_decay_rewards = np.zeros(iters) eps_1_rewards = np.zeros(iters) # Select initial values oiv_init = np.repeat(5., k) episodes = 1000 # Run experiments for i in range(episodes): # Initialize bandits oiv_bandit = eps_bandit(k, 0, iters) oiv_bandit.k_reward = oiv_init.copy() oiv_bandit.k_n = np.ones(k) eps_decay = eps_decay_bandit(k, iters, oiv_bandit.mu.copy()) eps_1 = eps_bandit(k, 0.1, iters, oiv_bandit.mu.copy()) # Run experiments oiv_bandit.run() eps_decay.run() eps_1.run() # Update long-term averages oiv_rewards = oiv_rewards + ( oiv_bandit.reward - oiv_rewards) / (i + 1) eps_decay_rewards = eps_decay_rewards + ( eps_decay.reward - eps_decay_rewards) / (i + 1) eps_1_rewards = eps_1_rewards + ( eps_1.reward - eps_1_rewards) / (i + 1) plt.figure(figsize=(12,8)) plt.plot(oiv_rewards, label="Optimistic") plt.plot(eps_decay_rewards, label="$\epsilon-decay$") plt.plot(eps_1_rewards, label="$\epsilon=0.1$") plt.legend(bbox_to_anchor=(1.2, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average Bandit Strategy Rewards after " + str(episodes) + " Episodes") plt.show() ``` We can see that, in this case, the optimistic initial value approach outperformed both our ϵ−greedy and the ϵ−decay algorithms. We can see too, the estimates the algorithm has for each of arms in the last episode. ``` df = pd.DataFrame({"number of selections": oiv_bandit.k_n - 1, "actual reward": oiv_bandit.mu, "estimated reward": oiv_bandit.k_reward}) df = df.applymap(lambda x: np.round(x, 2)) df['number of selections'] = df['number of selections'].astype('int') df ``` The estimates are far off the actual rewards in all cases except the one with 977 pulls. This highlights a lot of what we’ll be doing in reinforcement learning more generally. We don’t necessarily care about acquiring accurate representations of the environment we are interacting with. Instead, we intend to learn optimal behavior in those situations and seek to behave accordingly. This can open up a whole discussion about model-free versus model-based learning that we’ll have to postpone for another time. ## Upper Confidence Bound Bandit The first bandit strategy we’ll examine is known as the Upper-Confidence-Bound method (UCB) which attempts to explore the action space based on the uncertainty or variance in a‘s value. The selection criterion is given as: $$A_n=argmax_a(Q_n(a)+c\sqrt{\frac{log(n)}{N_n(a)}})$$ ``` class ucb_bandit: def __init__(self, k, c, iters, mu='random'): # Number of arms self.k = k # Exploration parameter self.c = c # Number of iterations self.iters = iters # Step count self.n = 1 # Step count for each arm self.k_n = np.ones(k) # Total mean reward self.mean_reward = 0 self.reward = np.zeros(iters) # Mean reward for each arm self.k_reward = np.zeros(k) if type(mu) == list or type(mu).__module__ == np.__name__: # User-defined averages self.mu = np.array(mu) elif mu == 'random': # Draw means from probability distribution self.mu = np.random.normal(0, 1, k) elif mu == 'sequence': # Increase the mean for each arm by one self.mu = np.linspace(0, k-1, k) def pull(self): # Select action according to UCB Criteria a = np.argmax(self.k_reward + self.c * np.sqrt( (np.log(self.n)) / self.k_n)) reward = np.random.normal(self.mu[a], 1) # Update counts self.n += 1 self.k_n[a] += 1 # Update total self.mean_reward = self.mean_reward + ( reward - self.mean_reward) / self.n # Update results for a_k self.k_reward[a] = self.k_reward[a] + ( reward - self.k_reward[a]) / self.k_n[a] def run(self): for i in range(self.iters): self.pull() self.reward[i] = self.mean_reward def reset(self, mu=None): # Resets results while keeping settings self.n = 1 self.k_n = np.ones(self.k) self.mean_reward = 0 self.reward = np.zeros(iters) self.k_reward = np.zeros(self.k) if mu == 'random': self.mu = np.random.normal(0, 1, self.k) k = 10 iters = 1000 ucb_rewards = np.zeros(iters) # Initialize bandits ucb = ucb_bandit(k, 2, iters) eps_decay_rewards = np.zeros(iters) eps_1_rewards = np.zeros(iters) episodes = 1000 # Run experiments for i in range(episodes): ucb.reset('random') eps_decay = eps_decay_bandit(k, iters) eps_1 = eps_bandit(k, 0.1, iters, eps_decay.mu.copy()) # Run experiments ucb.run() eps_decay.run() eps_1.run() # Update long-term averages ucb_rewards = ucb_rewards + ( ucb.reward - ucb_rewards) / (i + 1) eps_decay_rewards = eps_decay_rewards + ( eps_decay.reward - eps_decay_rewards) / (i + 1) eps_1_rewards = eps_1_rewards + ( eps_1.reward - eps_1_rewards) / (i + 1) plt.figure(figsize=(12,8)) plt.plot(ucb_rewards, label="UCB") plt.plot(eps_decay_rewards, label="eps_decay") plt.plot(eps_1_rewards, label="eps_1") plt.legend(bbox_to_anchor=(1.2, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average UCB Rewards after " + str(episodes) + " Episodes") plt.show() ``` ## Gradient Bandit Gradient algorithms take a different approach than the ones that we’ve seen thus far. This is a measure of the relative value of a given action over and above the other actions that are available. The algorithm learns a preference, $H_t(a)$, which causes it to select the higher preferenced actions more frequently. The preferences are calculated using softmax. $$Pr(A_t=a)=\frac{e^{H_t(a)}}{\sum_{b=1}^ke^{H_t(a)}}=\pi_t(n)$$ There is a new term $\pi_t(n)$ which has been introduced here. This is essentially the probability of taking action a at time t. The algorithm is initialized with $H_0(a)=0$, so that initially, all actions have an equal probability of selection. In this case, the algorithm doesn’t update the average of the rewards, but it updates the $H_t(a)=0$ value for each action using **stochastic gradient ascent**. Each time an action is taken, a reward is returned which is weighted by the probability of the action and the learning rate. This becomes the new value for $H_t(A_t)$ Because the probabilities are all relative to one another, they are all updated in turn. The procedure can be expressed as follows: $$H_{t+1}(A_t)=H_{t}(A_t)+\alpha(R_t-\bar{R_t})(1-\pi_t(n))$$ $$H_{t+1}(a)=H_{t}(a)-\alpha(R_t-\bar{R_t})\pi_t(n)\forall a\neq A_t$$ ``` def softmax(x): return np.exp(x - x.max()) / np.sum(np.exp(x - x.max()), axis=0) class grad_bandit: def __init__(self, k, alpha, iters, mu='random'): # Number of arms self.k = k self.actions = np.arange(k) # Number of iterations self.iters = iters # Step count self.n = 1 # Step count for each arm self.k_n = np.ones(k) # Total mean reward self.mean_reward = 0 self.reward = np.zeros(iters) # Mean reward for each arm self.k_reward = np.zeros(k) # Initialize preferences self.H = np.zeros(k) # Learning rate self.alpha = alpha if type(mu) == list or type(mu).__module__ == np.__name__: # User-defined averages self.mu = np.array(mu) elif mu == 'random': # Draw means from probability distribution self.mu = np.random.normal(0, 1, k) elif mu == 'sequence': # Increase the mean for each arm by one self.mu = np.linspace(0, k-1, k) def softmax(self): self.prob_action = np.exp(self.H - np.max(self.H)) \ / np.sum(np.exp(self.H - np.max(self.H)), axis=0) def pull(self): # Update probabilities self.softmax() # Select highest preference action a = np.random.choice(self.actions, p=self.prob_action) reward = np.random.normal(self.mu[a], 1) # Update counts self.n += 1 self.k_n[a] += 1 # Update total self.mean_reward = self.mean_reward + ( reward - self.mean_reward) / self.n # Update results for a_k self.k_reward[a] = self.k_reward[a] + ( reward - self.k_reward[a]) / self.k_n[a] # Update preferences self.H[a] = self.H[a] + \ self.alpha * (reward - self.mean_reward) * (1 - self.prob_action[a]) actions_not_taken = self.actions!=a self.H[actions_not_taken] = self.H[actions_not_taken] - \ self.alpha * (reward - self.mean_reward)* self.prob_action[actions_not_taken] def run(self): for i in range(self.iters): self.pull() self.reward[i] = self.mean_reward def reset(self, mu=None): # Resets results while keeping settings self.n = 0 self.k_n = np.zeros(self.k) self.mean_reward = 0 self.reward = np.zeros(iters) self.k_reward = np.zeros(self.k) self.H = np.zeros(self.k) if mu == 'random': self.mu = np.random.normal(0, 1, self.k) k = 10 iters = 1000 # Initialize bandits grad = grad_bandit(k, 0.1, iters, mu='random') ucb = ucb_bandit(k, 2, iters, mu=grad.mu) ucb.mu = grad.mu ucb_rewards = np.zeros(iters) grad_rewards = np.zeros(iters) opt_grad = 0 opt_ucb = 0 episodes = 1000 # Run experiments for i in range(episodes): # Reset counts and rewards grad.reset('random') ucb.reset() ucb.mu = grad.mu # Run experiments grad.run() ucb.run() # Update long-term averages grad_rewards = grad_rewards + ( grad.reward - grad_rewards) / (i + 1) ucb_rewards = ucb_rewards + ( ucb.reward - ucb_rewards) / (i + 1) # Count optimal actions opt_grad += grad.k_n[np.argmax(grad.mu)] opt_ucb += ucb.k_n[np.argmax(ucb.mu)] plt.figure(figsize=(12,8)) plt.plot(grad_rewards, label="Gradient") plt.plot(ucb_rewards, label="UCB") plt.legend(bbox_to_anchor=(1.3, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average Gradient Bandit Rewards after " + str(episodes) + " Episodes") plt.show() ``` We see that the UCB bandit outperformed the gradient bandit over the entire range, however, looking a bit deeper, we can see that the gradient bandit performed much better and more consistently once it learned. ``` width = 0.45 bins = np.linspace(0, k-1, k) - width/2 plt.figure(figsize=(12,8)) plt.bar(bins, grad.k_n, width=width, label="Gradient Bandit") plt.bar(bins+0.45, ucb.k_n, width=width, label="UCB") plt.legend(bbox_to_anchor=(1.3, 0.5)) plt.title("Actions Selected by Each Algorithm") plt.xlabel("Action") plt.ylabel("Number of Actions Taken") plt.show() opt_per = np.array([grad.k_n, ucb.k_n]) / iters * 100 df = pd.DataFrame(np.vstack([opt_per, grad.mu.reshape(-1, 1).T.round(2)]), index=["Grad", "UCB", "Expected Reward"], columns=["a = " + str(x) for x in range(0, k)]) print("Percentage of actions selected:") df ``` The gradient bandit outperformed the UCB approach on the final 1,000 pull run selecting the optimal action (action 3 in this case) 62.9% of the time versus 19.7%. Although the gradient-based approach wasn’t able to perform as well over the entire time horizon, notice that it was much more successful in differentiating the best action from the second best action than the UCB bandit, which spent 0.9% more of its actions selecting 2 instead of 3. The gradient bandit performed comparably to the UCB bandit, although underperforming it for all episodes, it remains important to understand because it relates closely to one of the key concepts in machine learning: stochastic gradient ascent/descent (see section 2.8 of Reinforcement Learning: An Introduction for a derivation of this). This makes up the backbone of numerous optimization strategies as the algorithm adjusts weights in the direction of minimum or maximum gradient (depending on what is being optimized for). This has an especially powerful analog in reinforcement learning known as policy gradients which we’ll cover in a future article. ## Nonstationary Bandits All of the environments we’ve examined have been stationary environments: once the returns are selected, the means remain constant. Most real-world applications don’t follow this pattern. Instead, the rewards drift over time meaning that the underlying reward function is dynamic. This behavior can cause your bandit’s, once optimal behavior, to drift over time as the action degrades or other strategies become more beneficial. To deal with this, we can introduce a step-size parameter, $\beta$ to the equation where 0<$\beta$≤1. The parameter $\beta$, weights more recent observations more heavily than older observations and acts like a discount factor stretching back into the past. This leads to the result where our $Q$ estimate can be written as: $$Q_{n+1}=(1-\beta)^nQ_1+\sum_{i=1}^n\beta(1-\beta)^{n-1}R_i$$ This is essentially a weighted average of all the past rewards and our initial estimate for Q and can be implemented in a similar update procedure. To see this in action, let’s define our mean reward as a function of the total number of pulls. As such, the mean reward will drift with each action n. We’ll make it a non-linear function as well just to make it a bit more interesting as the rewards shift. We’ll define a new bandit class, nonstationary_bandits with the option of using either ϵ-decay or ϵ-greedy methods. Also note, that if we set our β=1, then we are implementing a non-weighted algorithm, so the greedy move will be to select the highest average action instead of the highest weighted action. Check back with the last post if you need a refresher on the ideas that underpin these bandit types. ``` class nonstationary_bandit: def __init__(self, k, beta, epsilon, iters, Q_init=None, c='random'): # Number of arms self.k = k self.actions = np.arange(k) self.epsilon = epsilon # Number of iterations self.iters = iters # Step count self.n = 0 # Step count for each arm self.k_n = np.ones(k) # Total mean reward self.mean_reward = 0 self.reward = np.zeros(iters) # Mean reward for each arm self.k_reward = np.zeros(k) # Initialize estimates if not Q_init: self.Q_init = np.zeros(k) else: self.Q_init = Q_init self.Q = self.Q_init.copy() # Step size parameter self.beta = beta if type(c) == list or type(c).__module__ == np.__name__: # User-defined averages self.c = np.array(c) elif c == 'random': # Draw value from normal distribution self.c = np.random.normal(0, 1, k) elif c == 'sequence': # Increase the mean for each arm by one self.c = np.linspace(0, k-1, k) def pull(self): # Select highest average if self.beta == 1: a = np.argmax(self.k_reward) else: a = np.argmax(self.Q) # Possibly take random action p = np.random.rand() if self.epsilon == 'decay': if p < 1 / (1 + self.n): a = np.random.choice(self.k) else: if p < self.epsilon: a = np.random.choice(self.k) exp_reward = self.c[a] + np.sin(self.n * np.pi / self.iters + self.c[a]) reward = np.random.normal(exp_reward, 1) # Update counts self.n += 1 self.k_n[a] += 1 # Update total self.mean_reward = self.mean_reward + ( reward - self.mean_reward) / self.n # Update results for a_k self.k_reward[a] = self.k_reward[a] + ( reward - self.k_reward[a]) / self.k_n[a] # Update Q-values self.Q[a] += self.beta * (reward - self.Q[a]) def run(self): for i in range(self.iters): self.pull() self.reward[i] = self.mean_reward def reset(self, mu=None): # Resets results while keeping settings self.n = 0 self.k_n = np.zeros(self.k) self.mean_reward = 0 self.reward = np.zeros(iters) self.k_reward = np.zeros(self.k) k = 10 iters = 1000 # Initialize bandits ns_eps_decay = nonstationary_bandit(k, 1, 'decay', iters) ns_eps_decay_weighted = nonstationary_bandit( k, 0.1, 'decay', iters, c=ns_eps_decay.c) ns_eps_greedy = nonstationary_bandit( k, 1, 0.1, iters, c=ns_eps_decay.c) ns_eps_greedy_weighted = nonstationary_bandit( k, 0.1, 0.1, iters, c=ns_eps_decay.c) ns_eps_decay_rewards = np.zeros(iters) ns_eps_decay_w_rewards = np.zeros(iters) ns_eps_greedy_rewards = np.zeros(iters) ns_eps_greedy_w_rewards = np.zeros(iters) episodes = 1000 # Run experiments for i in range(episodes): # Reset counts and rewards ns_eps_decay.reset() ns_eps_decay_weighted.reset() ns_eps_greedy.reset() ns_eps_greedy_weighted.reset() # Run experiments ns_eps_decay.run() ns_eps_decay_weighted.run() ns_eps_greedy.run() ns_eps_greedy_weighted.run() # Update long-term averages ns_eps_decay_rewards = ns_eps_decay_rewards + ( ns_eps_decay.reward - ns_eps_decay_rewards) / (i + 1) ns_eps_decay_w_rewards = ns_eps_decay_w_rewards + ( ns_eps_decay_weighted.reward - ns_eps_decay_w_rewards) / (i + 1) ns_eps_greedy_rewards = ns_eps_greedy_rewards + ( ns_eps_greedy.reward - ns_eps_greedy_rewards) / (i + 1) ns_eps_greedy_w_rewards = ns_eps_greedy_w_rewards + ( ns_eps_greedy_weighted.reward - ns_eps_greedy_w_rewards) / (i + 1) x = np.arange(iters) * np.pi / iters plt.figure(figsize=(12,8)) plt.plot(ns_eps_decay_rewards, label=r"$\epsilon$-decay") plt.plot(ns_eps_decay_w_rewards, label=r"weighted $\epsilon$-decay") plt.plot(ns_eps_greedy_rewards, label=r"$\epsilon$-greedy") plt.plot(ns_eps_greedy_w_rewards, label=r"weighted $\epsilon$-greedy") for c in ns_eps_decay.c: plt.plot(c * np.sin(x * np.pi + c), '--') plt.legend(bbox_to_anchor=(1.3, 0.5)) plt.xlabel("Iterations") plt.ylabel("Average Reward") plt.title("Average Rewards after " + str(episodes) + " Episodes") plt.show() ``` The solid lines indicate the average rewards of the different non-stationary bandit algorithms that we implemented above, while the dashed lines show the change in expected rewards over time. The discounting helps the weighted ϵ algorithms outperform their non-weighted counterparts. Overall, none are spectacular, but it is very difficult to maintain high returns when the underlying reward functions are changing; it creates an aura of uncertainty.
github_jupyter
# Quickstart guide This example demonstrates how to build a simple content-based audio retrieval model and evaluate the retrieval accuracy on a small song dataset, CAL500. This dataset consists of 502 western pop songs, performed by 499 unique artists. Each song is tagged by at least three people using a standard survey and a fixed tag vocabulary of 174 musical concepts. This package includes a loading utility for getting and processing this dataset, which makes loading quite easy. ``` from cbar.datasets import fetch_cal500 X, Y = fetch_cal500() ``` Calling `fetch_cal500()` initally downloads the CAL500 dataset to a subfolder of your home directory. You can specify a different location using the `data_home` parameter (`fetch_cal500(data_home='path')`). Subsequents calls simply load the dataset. The raw dataset consists of about 10,000 39-dimensional features vectors per minute of audio content which were created by 1. Sliding a half-overlapping short-time window of 12 milliseconds over each song's waveform data. 2. Extracting the 13 mel-frequency cepstral coefficients. 3. Appending the instantaneous first-order and second-order derivatives. Each song is, then, represented by exactly 10,000 randomly subsampled, real-valued feature vectors as a *bag-of-frames*. The *bag-of-frames* features are further processed into one *k*-dimensional feature vector by encoding the feature vectors using a codebook and pooling them into one compact vector. Specifically, *k*-means is used to cluster all frame vectors into *k* clusters. The resulting cluster centers correspond to the codewords in the codebook. Each frame vector is assigned to its closest cluster center and a song represented as the counts of frames assigned to each of the *k* cluster centers. By default, `fetch_cal500()` uses a codebook size of 512 but this size is easily modified with the `codebook_size` parameter (`fetch_cal500(codebook_size=1024)`). ``` X.shape, Y.shape ``` Let's split the data into training data and test data, fit the model on the training data, and evaluate it on the test data. Import and instantiate the model first. ``` from cbar.loreta import LoretaWARP model = LoretaWARP(n0=0.1, valid_interval=1000) ``` Then split the data and fit the model using the training data. ``` from cbar.cross_validation import train_test_split_plus (X_train, X_test, Y_train, Y_test, Q_vec, weights) = train_test_split_plus(X, Y) %time model.fit(X_train, Y_train, Q_vec, X_test, Y_test) ``` Now, predict the scores for each query with all songs. Ordering the songs from highest to lowest score corresponds to the ranking. ``` Y_score = model.predict(Q_vec, X_test) ``` Evaluate the predictions. ``` from cbar.evaluation import Evaluator from cbar.utils import make_relevance_matrix n_relevant = make_relevance_matrix(Q_vec, Y_train).sum(axis=1) evaluator = Evaluator() evaluator.eval(Q_vec, weights, Y_score, Y_test, n_relevant) evaluator.prec_at ``` ## Cross-validation The `cv` function in the `cross_validation` module offers an easy way to evaluate a retrieval method on multiple splits of the data. Let's run the same experiment on three folds. ``` from cbar.cross_validation import cv cv('cal500', 512, n_folds=3, method='loreta', n0=0.1, valid_interval=1000) ``` The cross-validation results including retrieval method parameters are written to a JSON file. For each dataset three separate result files for mean average precision (MAP), precision-at-*k*, and precision-at-10 as a function of relevant training examples are written to disk. Here are the mean average precision values of the last cross-validation run. ``` import json import os from cbar.settings import RESULTS_DIR results = json.load(open(os.path.join(RESULTS_DIR, 'cal500_ap.json'))) results[results.keys()[-1]]['precision'] ``` ## Start cross-validation with the CLI This package comes with a simple CLI which makes it easy to start cross-validation experiments from the command line. The CLI enables you to specify a dataset and a retrieval method as well as additional options in one line. To start an experiment on the CAL500 dataset with the LORETA retrieval method, use the following command. ``` $ cbar crossval --dataset cal500 loreta ``` This simple command uses all the default parameters for LORETA but you can specify all parameters as arguments to the `loreta` command. To see the available options for the `loreta` command, ask for help like this. ``` $ cbar crossval loreta --help Usage: cbar crossval loreta [OPTIONS] Options: -n, --max-iter INTEGER Maximum number of iterations -i, --valid-interval INTEGER Rank of parameter matrix W -k INTEGER Rank of parameter matrix W --n0 FLOAT Step size parameter 1 --n1 FLOAT Step size parameter 2 -t, --rank-thresh FLOAT Threshold for early stopping -l, --lambda FLOAT Regularization constant --loss [warp|auc] Loss function -d, --max-dips INTEGER Maximum number of dips -v, --verbose Verbosity --help Show this message and exit. ```
github_jupyter
##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Multi-worker training with Estimator <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tutorials/distribute/multi_worker_with_estimator"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/distribute/multi_worker_with_estimator.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> ## Overview Note: While you can use Estimators with `tf.distribute` API, it's recommended to use Keras with `tf.distribute`, see [multi-worker training with Keras](multi_worker_with_keras.ipynb). Estimator training with `tf.distribute.Strategy` has limited support. This tutorial demonstrates how `tf.distribute.Strategy` can be used for distributed multi-worker training with `tf.estimator`. If you write your code using `tf.estimator`, and you're interested in scaling beyond a single machine with high performance, this tutorial is for you. Before getting started, please read the [distribution strategy](../../guide/distributed_training.ipynb) guide. The [multi-GPU training tutorial](./keras.ipynb) is also relevant, because this tutorial uses the same model. ## Setup First, setup TensorFlow and the necessary imports. ``` import tensorflow_datasets as tfds import tensorflow as tf import os, json ``` ## Input function This tutorial uses the MNIST dataset from [TensorFlow Datasets](https://www.tensorflow.org/datasets). The code here is similar to the [multi-GPU training tutorial](./keras.ipynb) with one key difference: when using Estimator for multi-worker training, it is necessary to shard the dataset by the number of workers to ensure model convergence. The input data is sharded by worker index, so that each worker processes `1/num_workers` distinct portions of the dataset. ``` BUFFER_SIZE = 10000 BATCH_SIZE = 64 def input_fn(mode, input_context=None): datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) mnist_dataset = (datasets['train'] if mode == tf.estimator.ModeKeys.TRAIN else datasets['test']) def scale(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label if input_context: mnist_dataset = mnist_dataset.shard(input_context.num_input_pipelines, input_context.input_pipeline_id) return mnist_dataset.map(scale).cache().shuffle(BUFFER_SIZE).batch(BATCH_SIZE) ``` Another reasonable approach to achieve convergence would be to shuffle the dataset with distinct seeds at each worker. ## Multi-worker configuration One of the key differences in this tutorial (compared to the [multi-GPU training tutorial](./keras.ipynb)) is the multi-worker setup. The `TF_CONFIG` environment variable is the standard way to specify the cluster configuration to each worker that is part of the cluster. There are two components of `TF_CONFIG`: `cluster` and `task`. `cluster` provides information about the entire cluster, namely the workers and parameter servers in the cluster. `task` provides information about the current task. The first component `cluster` is the same for all workers and parameter servers in the cluster, and the second component `task` is different on each worker and parameter server and specifies its own `type` and `index`. In this example, the task `type` is `worker` and the task `index` is `0`. For illustration purposes, this tutorial shows how to set a `TF_CONFIG` with 2 workers on `localhost`. In practice, you would create multiple workers on an external IP address and port, and set `TF_CONFIG` on each worker appropriately, i.e. modify the task `index`. Warning: *Do not execute the following code in Colab.* TensorFlow's runtime will attempt to create a gRPC server at the specified IP address and port, which will likely fail. ``` os.environ['TF_CONFIG'] = json.dumps({ 'cluster': { 'worker': ["localhost:12345", "localhost:23456"] }, 'task': {'type': 'worker', 'index': 0} }) ``` ## Define the model Write the layers, the optimizer, and the loss function for training. This tutorial defines the model with Keras layers, similar to the [multi-GPU training tutorial](./keras.ipynb). ``` LEARNING_RATE = 1e-4 def model_fn(features, labels, mode): model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10) ]) logits = model(features, training=False) if mode == tf.estimator.ModeKeys.PREDICT: predictions = {'logits': logits} return tf.estimator.EstimatorSpec(labels=labels, predictions=predictions) optimizer = tf.compat.v1.train.GradientDescentOptimizer( learning_rate=LEARNING_RATE) loss = tf.keras.losses.SparseCategoricalCrossentropy( from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(labels, logits) loss = tf.reduce_sum(loss) * (1. / BATCH_SIZE) if mode == tf.estimator.ModeKeys.EVAL: return tf.estimator.EstimatorSpec(mode, loss=loss) return tf.estimator.EstimatorSpec( mode=mode, loss=loss, train_op=optimizer.minimize( loss, tf.compat.v1.train.get_or_create_global_step())) ``` Note: Although the learning rate is fixed in this example, in general it may be necessary to adjust the learning rate based on the global batch size. ## MultiWorkerMirroredStrategy To train the model, use an instance of `tf.distribute.experimental.MultiWorkerMirroredStrategy`. `MultiWorkerMirroredStrategy` creates copies of all variables in the model's layers on each device across all workers. It uses `CollectiveOps`, a TensorFlow op for collective communication, to aggregate gradients and keep the variables in sync. The [`tf.distribute.Strategy` guide](../../guide/distributed_training.ipynb) has more details about this strategy. ``` strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() ``` ## Train and evaluate the model Next, specify the distribution strategy in the `RunConfig` for the estimator, and train and evaluate by invoking `tf.estimator.train_and_evaluate`. This tutorial distributes only the training by specifying the strategy via `train_distribute`. It is also possible to distribute the evaluation via `eval_distribute`. ``` config = tf.estimator.RunConfig(train_distribute=strategy) classifier = tf.estimator.Estimator( model_fn=model_fn, model_dir='/tmp/multiworker', config=config) tf.estimator.train_and_evaluate( classifier, train_spec=tf.estimator.TrainSpec(input_fn=input_fn), eval_spec=tf.estimator.EvalSpec(input_fn=input_fn) ) ``` ## Optimize training performance You now have a model and a multi-worker capable Estimator powered by `tf.distribute.Strategy`. You can try the following techniques to optimize performance of multi-worker training: * *Increase the batch size:* The batch size specified here is per-GPU. In general, the largest batch size that fits the GPU memory is advisable. * *Cast variables:* Cast the variables to `tf.float` if possible. The official ResNet model includes [an example](https://github.com/tensorflow/models/blob/8367cf6dabe11adf7628541706b660821f397dce/official/resnet/resnet_model.py#L466) of how this can be done. * *Use collective communication:* `MultiWorkerMirroredStrategy` provides multiple [collective communication implementations](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/distribute/cross_device_ops.py). * `RING` implements ring-based collectives using gRPC as the cross-host communication layer. * `NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. * `AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. To override the automatic choice, specify a valid value to the `communication` parameter of `MultiWorkerMirroredStrategy`'s constructor, e.g. `communication=tf.distribute.experimental.CollectiveCommunication.NCCL`. Visit the [Performance section](../../guide/function.ipynb) in the guide to learn more about other strategies and [tools](../../guide/profiler.md) you can use to optimize the performance of your TensorFlow models. ## Other code examples 1. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kubernetes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 2. [Official models](https://github.com/tensorflow/models/tree/master/official), many of which can be configured to run multiple distribution strategies.
github_jupyter
``` import sys, os if 'google.colab' in sys.modules and not os.path.exists('.setup_complete'): !wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/spring20/setup_colab.sh -O- | bash !wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/coursera/grading.py -O ../grading.py !wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/coursera/week1_intro/submit.py !touch .setup_complete # This code creates a virtual display to draw game images on. # It will have no effect if your machine has a monitor. if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['DISPLAY'] = ':1' import numpy as np import matplotlib.pyplot as plt %matplotlib inline ``` ### OpenAI Gym We're gonna spend several next weeks learning algorithms that solve decision processes. We are then in need of some interesting decision problems to test our algorithms. That's where OpenAI gym comes into play. It's a python library that wraps many classical decision problems including robot control, videogames and board games. So here's how it works: ``` import gym env = gym.make("MountainCar-v0") env.reset() plt.imshow(env.render('rgb_array')) print("Observation space:", env.observation_space) print("Action space:", env.action_space) ``` Note: if you're running this on your local machine, you'll see a window pop up with the image above. Don't close it, just alt-tab away. ### Gym interface The three main methods of an environment are * __reset()__ - reset environment to initial state, _return first observation_ * __render()__ - show current environment state (a more colorful version :) ) * __step(a)__ - commit action __a__ and return (new observation, reward, is done, info) * _new observation_ - an observation right after commiting the action __a__ * _reward_ - a number representing your reward for commiting action __a__ * _is done_ - True if the MDP has just finished, False if still in progress * _info_ - some auxilary stuff about what just happened. Ignore it ~~for now~~. ``` obs0 = env.reset() print("initial observation code:", obs0) # Note: in MountainCar, observation is just two numbers: car position and velocity print("taking action 2 (right)") new_obs, reward, is_done, _ = env.step(2) print("new observation code:", new_obs) print("reward:", reward) print("is game over?:", is_done) # Note: as you can see, the car has moved to the right slightly (around 0.0005) ``` ### Play with it Below is the code that drives the car to the right. However, if you simply use the default policy, the car will not reach the flag at the far right due to gravity. __Your task__ is to fix it. Find a strategy that reaches the flag. You are not required to build any sophisticated algorithms for now, feel free to hard-code :) ``` from IPython import display # Create env manually to set time limit. Please don't change this. TIME_LIMIT = 250 env = gym.wrappers.TimeLimit( gym.envs.classic_control.MountainCarEnv(), max_episode_steps=TIME_LIMIT + 1, ) actions = {'left': 0, 'stop': 1, 'right': 2} def policy(obs, t): # Write the code for your policy here. You can use the observation # (a tuple of position and velocity), the current time step, or both, # if you want. position, velocity = obs if velocity >= 0: return actions['right'] else: return actions['left'] plt.figure(figsize=(4, 3)) display.clear_output(wait=True) obs = env.reset() for t in range(TIME_LIMIT): plt.gca().clear() action = policy(obs, t) # Call your policy obs, reward, done, _ = env.step(action) # Pass the action chosen by the policy to the environment # We don't do anything with reward here because MountainCar is a very simple environment, # and reward is a constant -1. Therefore, your goal is to end the episode as quickly as possible. # Draw game image on display. plt.imshow(env.render('rgb_array')) display.clear_output(wait=True) display.display(plt.gcf()) if done: print("Well done!") break else: print("Time limit exceeded. Try again.") display.clear_output(wait=True) ```
github_jupyter
# Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. **Notation**: - Superscript $[l]$ denotes an object of the $l^{th}$ layer. - Example: $a^{[4]}$ is the $4^{th}$ layer activation. $W^{[5]}$ and $b^{[5]}$ are the $5^{th}$ layer parameters. - Superscript $(i)$ denotes an object from the $i^{th}$ example. - Example: $x^{(i)}$ is the $i^{th}$ training example input. - Lowerscript $i$ denotes the $i^{th}$ entry of a vector. - Example: $a^{[l]}_i$ denotes the $i^{th}$ entry of the activations in layer $l$, assuming this is a fully connected (FC) layer. - $n_H$, $n_W$ and $n_C$ denote respectively the height, width and number of channels of a given layer. If you want to reference a specific layer $l$, you can also write $n_H^{[l]}$, $n_W^{[l]}$, $n_C^{[l]}$. - $n_{H_{prev}}$, $n_{W_{prev}}$ and $n_{C_{prev}}$ denote respectively the height, width and number of channels of the previous layer. If referencing a specific layer $l$, this could also be denoted $n_H^{[l-1]}$, $n_W^{[l-1]}$, $n_C^{[l-1]}$. We assume that you are already familiar with `numpy` and/or have completed the previous courses of the specialization. Let's get started! ## 1 - Packages Let's first import all the packages that you will need during this assignment. - [numpy](www.numpy.org) is the fundamental package for scientific computing with Python. - [matplotlib](http://matplotlib.org) is a library to plot graphs in Python. - np.random.seed(1) is used to keep all the random function calls consistent. It will help us grade your work. ``` import numpy as np import h5py import matplotlib.pyplot as plt %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1) ``` ## 2 - Outline of the Assignment You will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions that will walk you through the steps needed: - Convolution functions, including: - Zero Padding - Convolve window - Convolution forward - Convolution backward (optional) - Pooling functions, including: - Pooling forward - Create mask - Distribute value - Pooling backward (optional) This notebook will ask you to implement these functions from scratch in `numpy`. In the next notebook, you will use the TensorFlow equivalents of these functions to build the following model: <img src="images/model.png" style="width:800px;height:300px;"> **Note** that for every forward function, there is its corresponding backward equivalent. Hence, at every step of your forward module you will store some parameters in a cache. These parameters are used to compute gradients during backpropagation. ## 3 - Convolutional Neural Networks Although programming frameworks make convolutions easy to use, they remain one of the hardest concepts to understand in Deep Learning. A convolution layer transforms an input volume into an output volume of different size, as shown below. <img src="images/conv_nn.png" style="width:350px;height:200px;"> In this part, you will build every step of the convolution layer. You will first implement two helper functions: one for zero padding and the other for computing the convolution function itself. ### 3.1 - Zero-Padding Zero-padding adds zeros around the border of an image: <img src="images/PAD.png" style="width:600px;height:400px;"> <caption><center> <u> <font color='purple'> **Figure 1** </u><font color='purple'> : **Zero-Padding**<br> Image (3 channels, RGB) with a padding of 2. </center></caption> The main benefits of padding are the following: - It allows you to use a CONV layer without necessarily shrinking the height and width of the volumes. This is important for building deeper networks, since otherwise the height/width would shrink as you go to deeper layers. An important special case is the "same" convolution, in which the height/width is exactly preserved after one layer. - It helps us keep more of the information at the border of an image. Without padding, very few values at the next layer would be affected by pixels as the edges of an image. **Exercise**: Implement the following function, which pads all the images of a batch of examples X with zeros. [Use np.pad](https://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html). Note if you want to pad the array "a" of shape $(5,5,5,5,5)$ with `pad = 1` for the 2nd dimension, `pad = 3` for the 4th dimension and `pad = 0` for the rest, you would do: ```python a = np.pad(a, ((0,0), (1,1), (0,0), (3,3), (0,0)), 'constant', constant_values = (..,..)) ``` ``` # GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- integer, amount of padding around each image on vertical and horizontal dimensions Returns: X_pad -- padded image of shape (m, n_H + 2*pad, n_W + 2*pad, n_C) """ ### START CODE HERE ### (≈ 1 line) X_pad = np.pad(X, ((0,0), (pad,pad), (pad,pad), (0,0)), 'constant', constant_values = 0) ### END CODE HERE ### return X_pad np.random.seed(1) x = np.random.randn(4, 3, 3, 2) x_pad = zero_pad(x, 2) print ("x.shape =", x.shape) print ("x_pad.shape =", x_pad.shape) print ("x[1,1] =", x[1,1]) print ("x_pad[1,1] =", x_pad[1,1]) fig, axarr = plt.subplots(1, 2) axarr[0].set_title('x') axarr[0].imshow(x[0,:,:,0]) axarr[1].set_title('x_pad') axarr[1].imshow(x_pad[0,:,:,0]) ``` **Expected Output**: <table> <tr> <td> **x.shape**: </td> <td> (4, 3, 3, 2) </td> </tr> <tr> <td> **x_pad.shape**: </td> <td> (4, 7, 7, 2) </td> </tr> <tr> <td> **x[1,1]**: </td> <td> [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] </td> </tr> <tr> <td> **x_pad[1,1]**: </td> <td> [[ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.] [ 0. 0.]] </td> </tr> </table> ### 3.2 - Single step of convolution In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: - Takes an input volume - Applies a filter at every position of the input - Outputs another volume (usually of different size) <img src="images/Convolution_schematic.gif" style="width:500px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 2** </u><font color='purple'> : **Convolution operation**<br> with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) </center></caption> In a computer vision application, each value in the matrix on the left corresponds to a single pixel value, and we convolve a 3x3 filter with the image by multiplying its values element-wise with the original matrix, then summing them up and adding a bias. In this first step of the exercise, you will implement a single step of convolution, corresponding to applying a filter to just one of the positions to get a single real-valued output. Later in this notebook, you'll apply this function to multiple positions of the input to implement the full convolutional operation. **Exercise**: Implement conv_single_step(). [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.sum.html). ``` # GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight parameters contained in a window - matrix of shape (f, f, n_C_prev) b -- Bias parameters contained in a window - matrix of shape (1, 1, 1) Returns: Z -- a scalar value, result of convolving the sliding window (W, b) on a slice x of the input data """ ### START CODE HERE ### (≈ 2 lines of code) # Element-wise product between a_slice and W. Do not add the bias yet. s = a_slice_prev * W # Sum over all entries of the volume s. Z = np.sum(s) # Add bias b to Z. Cast b to a float() so that Z results in a scalar value. Z = Z + float(b) ### END CODE HERE ### return Z np.random.seed(1) a_slice_prev = np.random.randn(4, 4, 3) W = np.random.randn(4, 4, 3) b = np.random.randn(1, 1, 1) Z = conv_single_step(a_slice_prev, W, b) print("Z =", Z) ``` **Expected Output**: <table> <tr> <td> **Z** </td> <td> -6.99908945068 </td> </tr> </table> ### 3.3 - Convolutional Neural Networks - Forward pass In the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume: <center> <video width="620" height="440" src="images/conv_kiank.mp4" type="video/mp4" controls> </video> </center> **Exercise**: Implement the function below to convolve the filters W on an input activation A_prev. This function takes as input A_prev, the activations output by the previous layer (for a batch of m inputs), F filters/weights denoted by W, and a bias vector denoted by b, where each filter has its own (single) bias. Finally you also have access to the hyperparameters dictionary which contains the stride and the padding. **Hint**: 1. To select a 2x2 slice at the upper left corner of a matrix "a_prev" (shape (5,5,3)), you would do: ```python a_slice_prev = a_prev[0:2,0:2,:] ``` This will be useful when you will define `a_slice_prev` below, using the `start/end` indexes you will define. 2. To define a_slice you will need to first define its corners `vert_start`, `vert_end`, `horiz_start` and `horiz_end`. This figure may be helpful for you to find how each of the corner can be defined using h, w, f and s in the code below. <img src="images/vert_horiz_kiank.png" style="width:400px;height:300px;"> <caption><center> <u> <font color='purple'> **Figure 3** </u><font color='purple'> : **Definition of a slice using vertical and horizontal start/end (with a 2x2 filter)** <br> This figure shows only a single channel. </center></caption> **Reminder**: The formulas relating the output shape of the convolution to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f + 2 \times pad}{stride} \rfloor +1 $$ $$ n_C = \text{number of filters used in the convolution}$$ For this exercise, we won't worry about vectorization, and will just implement everything with for-loops. ``` # GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): """ Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy array of shape (f, f, n_C_prev, n_C) b -- Biases, numpy array of shape (1, 1, 1, n_C) hparameters -- python dictionary containing "stride" and "pad" Returns: Z -- conv output, numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward() function """ ### START CODE HERE ### # Retrieve dimensions from A_prev's shape (≈1 line) (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (≈1 line) (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" (≈2 lines) stride = hparameters["stride"] pad = hparameters["pad"] # Compute the dimensions of the CONV output volume using the formula given above. Hint: use int() to floor. (≈2 lines) n_H = int((n_H_prev - f + 2 * pad) / stride) + 1 n_W = int((n_W_prev - f + 2 * pad) / stride) + 1 # Initialize the output volume Z with zeros. (≈1 line) Z = np.zeros((m, n_H, n_W, n_C)) # Create A_prev_pad by padding A_prev A_prev_pad = zero_pad(A_prev, pad) for i in range(m): # loop over the batch of training examples a_prev_pad = A_prev_pad[i] # Select ith training example's padded activation for h in range(n_H): # loop over vertical axis of the output volume for w in range(n_W): # loop over horizontal axis of the output volume for c in range(n_C): # loop over channels (= #filters) of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the (3D) slice of a_prev_pad (See Hint above the cell). (≈1 line) a_slice_prev = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] # Convolve the (3D) slice with the correct filter W and bias b, to get back one output neuron. (≈1 line) Z[i, h, w, c] = conv_single_step(a_slice_prev, W[..., c], b[..., c]) ### END CODE HERE ### # Making sure your output shape is correct assert(Z.shape == (m, n_H, n_W, n_C)) # Save information in "cache" for the backprop cache = (A_prev, W, b, hparameters) return Z, cache np.random.seed(1) A_prev = np.random.randn(10,4,4,3) W = np.random.randn(2,2,3,8) b = np.random.randn(1,1,1,8) hparameters = {"pad" : 2, "stride": 2} Z, cache_conv = conv_forward(A_prev, W, b, hparameters) print("Z's mean =", np.mean(Z)) print("Z[3,2,1] =", Z[3,2,1]) print("cache_conv[0][1][2][3] =", cache_conv[0][1][2][3]) ``` **Expected Output**: <table> <tr> <td> **Z's mean** </td> <td> 0.0489952035289 </td> </tr> <tr> <td> **Z[3,2,1]** </td> <td> [-0.61490741 -6.7439236 -2.55153897 1.75698377 3.56208902 0.53036437 5.18531798 8.75898442] </td> </tr> <tr> <td> **cache_conv[0][1][2][3]** </td> <td> [-0.20075807 0.18656139 0.41005165] </td> </tr> </table> Finally, CONV layer should also contain an activation, in which case we would add the following line of code: ```python # Convolve the window to get back one output neuron Z[i, h, w, c] = ... # Apply activation A[i, h, w, c] = activation(Z[i, h, w, c]) ``` You don't need to do it here. ## 4 - Pooling layer The pooling (POOL) layer reduces the height and width of the input. It helps reduce computation, as well as helps make feature detectors more invariant to its position in the input. The two types of pooling layers are: - Max-pooling layer: slides an ($f, f$) window over the input and stores the max value of the window in the output. - Average-pooling layer: slides an ($f, f$) window over the input and stores the average value of the window in the output. <table> <td> <img src="images/max_pool1.png" style="width:500px;height:300px;"> <td> <td> <img src="images/a_pool.png" style="width:500px;height:300px;"> <td> </table> These pooling layers have no parameters for backpropagation to train. However, they have hyperparameters such as the window size $f$. This specifies the height and width of the fxf window you would compute a max or average over. ### 4.1 - Forward Pooling Now, you are going to implement MAX-POOL and AVG-POOL, in the same function. **Exercise**: Implement the forward pass of the pooling layer. Follow the hints in the comments below. **Reminder**: As there's no padding, the formulas binding the output shape of the pooling to the input shape is: $$ n_H = \lfloor \frac{n_{H_{prev}} - f}{stride} \rfloor +1 $$ $$ n_W = \lfloor \frac{n_{W_{prev}} - f}{stride} \rfloor +1 $$ $$ n_C = n_{C_{prev}}$$ ``` # GRADED FUNCTION: pool_forward def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: A -- output of the pool layer, a numpy array of shape (m, n_H, n_W, n_C) cache -- cache used in the backward pass of the pooling layer, contains the input and hparameters """ # Retrieve dimensions from the input shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve hyperparameters from "hparameters" f = hparameters["f"] stride = hparameters["stride"] # Define the dimensions of the output n_H = int(1 + (n_H_prev - f) / stride) n_W = int(1 + (n_W_prev - f) / stride) n_C = n_C_prev # Initialize output matrix A A = np.zeros((m, n_H, n_W, n_C)) ### START CODE HERE ### for i in range(m): # loop over the training examples for h in range(n_H): # loop on the vertical axis of the output volume for w in range(n_W): # loop on the horizontal axis of the output volume for c in range (n_C): # loop over the channels of the output volume # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the current slice on the ith training example of A_prev, channel c. (≈1 line) a_prev_slice = A_prev[i, vert_start:vert_end, horiz_start:horiz_end, c] # Compute the pooling operation on the slice. Use an if statment to differentiate the modes. Use np.max/np.mean. if mode == "max": A[i, h, w, c] = np.max(a_prev_slice) elif mode == "average": A[i, h, w, c] = np.mean(a_prev_slice) ### END CODE HERE ### # Store the input and hparameters in "cache" for pool_backward() cache = (A_prev, hparameters) # Making sure your output shape is correct assert(A.shape == (m, n_H, n_W, n_C)) return A, cache np.random.seed(1) A_prev = np.random.randn(2, 4, 4, 3) hparameters = {"stride" : 2, "f": 3} A, cache = pool_forward(A_prev, hparameters) print("mode = max") print("A =", A) print() A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mode = average") print("A =", A) ``` **Expected Output:** <table> <tr> <td> A = </td> <td> [[[[ 1.74481176 0.86540763 1.13376944]]] [[[ 1.13162939 1.51981682 2.18557541]]]] </td> </tr> <tr> <td> A = </td> <td> [[[[ 0.02105773 -0.20328806 -0.40389855]]] [[[-0.22154621 0.51716526 0.48155844]]]] </td> </tr> </table> Congratulations! You have now implemented the forward passes of all the layers of a convolutional network. The remainer of this notebook is optional, and will not be graded. ## 5 - Backpropagation in convolutional neural networks (OPTIONAL / UNGRADED) In modern deep learning frameworks, you only have to implement the forward pass, and the framework takes care of the backward pass, so most deep learning engineers don't need to bother with the details of the backward pass. The backward pass for convolutional networks is complicated. If you wish however, you can work through this optional portion of the notebook to get a sense of what backprop in a convolutional network looks like. When in an earlier course you implemented a simple (fully connected) neural network, you used backpropagation to compute the derivatives with respect to the cost to update the parameters. Similarly, in convolutional neural networks you can to calculate the derivatives with respect to the cost in order to update the parameters. The backprop equations are not trivial and we did not derive them in lecture, but we briefly presented them below. ### 5.1 - Convolutional layer backward pass Let's start by implementing the backward pass for a CONV layer. #### 5.1.1 - Computing dA: This is the formula for computing $dA$ with respect to the cost for a certain filter $W_c$ and a given training example: $$ dA += \sum _{h=0} ^{n_H} \sum_{w=0} ^{n_W} W_c \times dZ_{hw} \tag{1}$$ Where $W_c$ is a filter and $dZ_{hw}$ is a scalar corresponding to the gradient of the cost with respect to the output of the conv layer Z at the hth row and wth column (corresponding to the dot product taken at the ith stride left and jth stride down). Note that at each time, we multiply the the same filter $W_c$ by a different dZ when updating dA. We do so mainly because when computing the forward propagation, each filter is dotted and summed by a different a_slice. Therefore when computing the backprop for dA, we are just adding the gradients of all the a_slices. In code, inside the appropriate for-loops, this formula translates into: ```python da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c] ``` #### 5.1.2 - Computing dW: This is the formula for computing $dW_c$ ($dW_c$ is the derivative of one filter) with respect to the loss: $$ dW_c += \sum _{h=0} ^{n_H} \sum_{w=0} ^ {n_W} a_{slice} \times dZ_{hw} \tag{2}$$ Where $a_{slice}$ corresponds to the slice which was used to generate the acitivation $Z_{ij}$. Hence, this ends up giving us the gradient for $W$ with respect to that slice. Since it is the same $W$, we will just add up all such gradients to get $dW$. In code, inside the appropriate for-loops, this formula translates into: ```python dW[:,:,:,c] += a_slice * dZ[i, h, w, c] ``` #### 5.1.3 - Computing db: This is the formula for computing $db$ with respect to the cost for a certain filter $W_c$: $$ db = \sum_h \sum_w dZ_{hw} \tag{3}$$ As you have previously seen in basic neural networks, db is computed by summing $dZ$. In this case, you are just summing over all the gradients of the conv output (Z) with respect to the cost. In code, inside the appropriate for-loops, this formula translates into: ```python db[:,:,:,c] += dZ[i, h, w, c] ``` **Exercise**: Implement the `conv_backward` function below. You should sum over all the training examples, filters, heights, and widths. You should then compute the derivatives using formulas 1, 2 and 3 above. ``` def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv_forward() Returns: dA_prev -- gradient of the cost with respect to the input of the conv layer (A_prev), numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) dW -- gradient of the cost with respect to the weights of the conv layer (W) numpy array of shape (f, f, n_C_prev, n_C) db -- gradient of the cost with respect to the biases of the conv layer (b) numpy array of shape (1, 1, 1, n_C) """ ### START CODE HERE ### # Retrieve information from "cache" (A_prev, W, b, hparameters) = cache # Retrieve dimensions from A_prev's shape (m, n_H_prev, n_W_prev, n_C_prev) = A_prev.shape # Retrieve dimensions from W's shape (f, f, n_C_prev, n_C) = W.shape # Retrieve information from "hparameters" stride = hparameters["stride"] pad = hparameters["pad"] # Retrieve dimensions from dZ's shape (m, n_H, n_W, n_C) = dZ.shape # Initialize dA_prev, dW, db with the correct shapes dA_prev = np.zeros((m, n_H_prev, n_W_prev, n_C_prev)) dW = np.zeros((f, f, n_C_prev, n_C)) db = np.zeros((1, 1, 1, n_C)) # Pad A_prev and dA_prev A_prev_pad = zero_pad(A_prev, pad) dA_prev_pad = zero_pad(dA_prev, pad) for i in range(m): # loop over the training examples # select ith training example from A_prev_pad and dA_prev_pad a_prev_pad = A_prev_pad[i] da_prev_pad = dA_prev_pad[i] for h in range(n_H): # loop over vertical axis of the output volume for w in range(n_W): # loop over horizontal axis of the output volume for c in range(n_C): # loop over the channels of the output volume # Find the corners of the current "slice" vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Use the corners to define the slice from a_prev_pad a_slice = a_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] # Update gradients for the window and the filter's parameters using the code formulas given above da_prev_pad[vert_start:vert_end, horiz_start:horiz_end, :] += W[:,:,:,c] * dZ[i, h, w, c] dW[:,:,:,c] += a_slice * dZ[i, h, w, c] db[:,:,:,c] += dZ[i, h, w, c] # Set the ith training example's dA_prev to the unpaded da_prev_pad (Hint: use X[pad:-pad, pad:-pad, :]) dA_prev[i, :, :, :] = da_prev_pad[pad:-pad, pad:-pad, :] ### END CODE HERE ### # Making sure your output shape is correct assert(dA_prev.shape == (m, n_H_prev, n_W_prev, n_C_prev)) return dA_prev, dW, db np.random.seed(1) dA, dW, db = conv_backward(Z, cache_conv) print("dA_mean =", np.mean(dA)) print("dW_mean =", np.mean(dW)) print("db_mean =", np.mean(db)) ``` ** Expected Output: ** <table> <tr> <td> **dA_mean** </td> <td> 1.45243777754 </td> </tr> <tr> <td> **dW_mean** </td> <td> 1.72699145831 </td> </tr> <tr> <td> **db_mean** </td> <td> 7.83923256462 </td> </tr> </table> ## 5.2 Pooling layer - backward pass Next, let's implement the backward pass for the pooling layer, starting with the MAX-POOL layer. Even though a pooling layer has no parameters for backprop to update, you still need to backpropagation the gradient through the pooling layer in order to compute gradients for layers that came before the pooling layer. ### 5.2.1 Max pooling - backward pass Before jumping into the backpropagation of the pooling layer, you are going to build a helper function called `create_mask_from_window()` which does the following: $$ X = \begin{bmatrix} 1 && 3 \\ 4 && 2 \end{bmatrix} \quad \rightarrow \quad M =\begin{bmatrix} 0 && 0 \\ 1 && 0 \end{bmatrix}\tag{4}$$ As you can see, this function creates a "mask" matrix which keeps track of where the maximum of the matrix is. True (1) indicates the position of the maximum in X, the other entries are False (0). You'll see later that the backward pass for average pooling will be similar to this but using a different mask. **Exercise**: Implement `create_mask_from_window()`. This function will be helpful for pooling backward. Hints: - [np.max()]() may be helpful. It computes the maximum of an array. - If you have a matrix X and a scalar x: `A = (X == x)` will return a matrix A of the same size as X such that: ``` A[i,j] = True if X[i,j] = x A[i,j] = False if X[i,j] != x ``` - Here, you don't need to consider cases where there are several maxima in a matrix. ``` def create_mask_from_window(x): """ Creates a mask from an input matrix x, to identify the max entry of x. Arguments: x -- Array of shape (f, f) Returns: mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x. """ ### START CODE HERE ### (≈1 line) mask = (x == np.max(x)) ### END CODE HERE ### return mask np.random.seed(1) x = np.random.randn(2,3) mask = create_mask_from_window(x) print('x = ', x) print("mask = ", mask) ``` **Expected Output:** <table> <tr> <td> **x =** </td> <td> [[ 1.62434536 -0.61175641 -0.52817175] <br> [-1.07296862 0.86540763 -2.3015387 ]] </td> </tr> <tr> <td> **mask =** </td> <td> [[ True False False] <br> [False False False]] </td> </tr> </table> Why do we keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is computing gradients with respect to the cost, so anything that influences the ultimate cost should have a non-zero gradient. So, backprop will "propagate" the gradient back to this particular input value that had influenced the cost. ### 5.2.2 - Average pooling - backward pass In max pooling, for each input window, all the "influence" on the output came from a single input value--the max. In average pooling, every element of the input window has equal influence on the output. So to implement backprop, you will now implement a helper function that reflects this. For example if we did average pooling in the forward pass using a 2x2 filter, then the mask you'll use for the backward pass will look like: $$ dZ = 1 \quad \rightarrow \quad dZ =\begin{bmatrix} 1/4 && 1/4 \\ 1/4 && 1/4 \end{bmatrix}\tag{5}$$ This implies that each position in the $dZ$ matrix contributes equally to output because in the forward pass, we took an average. **Exercise**: Implement the function below to equally distribute a value dz through a matrix of dimension shape. [Hint](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ones.html) ``` def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we distributed the value of dz """ ### START CODE HERE ### # Retrieve dimensions from shape (≈1 line) (n_H, n_W) = shape # Compute the value to distribute on the matrix (≈1 line) average = dz / (n_H * n_W) # Create a matrix where every entry is the "average" value (≈1 line) a = np.ones(shape) * average ### END CODE HERE ### return a a = distribute_value(2, (2,2)) print('distributed value =', a) ``` **Expected Output**: <table> <tr> <td> distributed_value = </td> <td> [[ 0.5 0.5] <br\> [ 0.5 0.5]] </td> </tr> </table> ### 5.2.3 Putting it together: Pooling backward You now have everything you need to compute backward propagation on a pooling layer. **Exercise**: Implement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once again use 4 for-loops (iterating over training examples, height, width, and channels). You should use an `if/elif` statement to see if the mode is equal to `'max'` or `'average'`. If it is equal to 'average' you should use the `distribute_value()` function you implemented above to create a matrix of the same shape as `a_slice`. Otherwise, the mode is equal to '`max`', and you will create a mask with `create_mask_from_window()` and multiply it by the corresponding value of dZ. ``` def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and hparameters mode -- the pooling mode you would like to use, defined as a string ("max" or "average") Returns: dA_prev -- gradient of cost with respect to the input of the pooling layer, same shape as A_prev """ ### START CODE HERE ### # Retrieve information from cache (≈1 line) (A_prev, hparameters) = cache # Retrieve hyperparameters from "hparameters" (≈2 lines) stride = hparameters["stride"] f = hparameters["f"] # Retrieve dimensions from A_prev's shape and dA's shape (≈2 lines) m, n_H_prev, n_W_prev, n_C_prev = A_prev.shape m, n_H, n_W, n_C = dA.shape # Initialize dA_prev with zeros (≈1 line) dA_prev = np.zeros(A_prev.shape) for i in range(m): # loop over the training examples # select training example from A_prev (≈1 line) a_prev = A_prev[i] for h in range(n_H): # loop on the vertical axis for w in range(n_W): # loop on the horizontal axis for c in range(n_C): # loop over the channels (depth) # Find the corners of the current "slice" (≈4 lines) vert_start = h * stride vert_end = vert_start + f horiz_start = w * stride horiz_end = horiz_start + f # Compute the backward propagation in both modes. if mode == "max": # Use the corners and "c" to define the current slice from a_prev (≈1 line) a_prev_slice = a_prev[vert_start:vert_end, horiz_start:horiz_end, c] # Create the mask from a_prev_slice (≈1 line) mask = create_mask_from_window(a_prev_slice) # Set dA_prev to be dA_prev + (the mask multiplied by the correct entry of dA) (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += mask * dA[i, h, w, c] elif mode == "average": # Get the value a from dA (≈1 line) da = dA[i, h, w, c] # Define the shape of the filter as fxf (≈1 line) shape = (f, f) # Distribute it to get the correct slice of dA_prev. i.e. Add the distributed value of da. (≈1 line) dA_prev[i, vert_start: vert_end, horiz_start: horiz_end, c] += distribute_value(da, shape) ### END CODE ### # Making sure your output shape is correct assert(dA_prev.shape == A_prev.shape) return dA_prev np.random.seed(1) A_prev = np.random.randn(5, 5, 3, 2) hparameters = {"stride" : 1, "f": 2} A, cache = pool_forward(A_prev, hparameters) dA = np.random.randn(5, 4, 2, 2) dA_prev = pool_backward(dA, cache, mode = "max") print("mode = max") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) print() dA_prev = pool_backward(dA, cache, mode = "average") print("mode = average") print('mean of dA = ', np.mean(dA)) print('dA_prev[1,1] = ', dA_prev[1,1]) ``` **Expected Output**: mode = max: <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0. 0. ] <br> [ 5.05844394 -1.68282702] <br> [ 0. 0. ]] </td> </tr> </table> mode = average <table> <tr> <td> **mean of dA =** </td> <td> 0.145713902729 </td> </tr> <tr> <td> **dA_prev[1,1] =** </td> <td> [[ 0.08485462 0.2787552 ] <br> [ 1.26461098 -0.25749373] <br> [ 1.17975636 -0.53624893]] </td> </tr> </table> ### Congratulations ! Congratulation on completing this assignment. You now understand how convolutional neural networks work. You have implemented all the building blocks of a neural network. In the next assignment you will implement a ConvNet using TensorFlow.
github_jupyter
``` !pip install geojson # Imports here import os from google.cloud import storage from IPython.display import clear_output # Create the service client. from googleapiclient.discovery import build from apiclient.http import MediaIoBaseDownload from skimage.util import view_as_blocks, pad import os.path import math import requests import json import subprocess from osgeo import ogr, osr, gdal import pandas as pd import numpy as np import matplotlib.pyplot as plt import geojson as gj from PIL import Image # Shell commands necessary to run code %env ORDER_NAME=chimbote %env ITEM_TYPE=PSScene4Band %env BAND_ID=_3B_AnalyticMS %env ITEM_ID_PATH=item_ids.txt %env DL_IMAGE_PATH=/content/ %env PATH_PREFIX=chimbote/ %env BUCKET_NAME=planet_imagery # REMEMBER to upload google_creds.json on startup %env GOOGLE_APPLICATION_CREDENTIALS=google_creds.json # GOOGLE CREDS is different for notebook – change for .py files GOOGLE_APPLICATION_CREDENTIALS = os.getenv('GOOGLE_APPLICATION_CREDENTIALS') BUCKET_NAME = os.getenv('BUCKET_NAME') PATH_PREFIX = os.getenv('PATH_PREFIX') ITEM_TYPE = os.getenv('ITEM_TYPE') ITEM_ID_PATH = os.getenv('ITEM_ID_PATH') DL_IMAGE_PATH = os.getenv('DL_IMAGE_PATH') BAND_ID = os.getenv('BAND_ID') ORDER_NAME = os.getenv('ORDER_NAME') def download_img(dl_path, id_num): gcs_service = build('storage', 'v1') if not os.path.exists(os.path.dirname(dl_path)): try: os.makedirs(os.path.dirname(dl_path)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise with open(dl_path, 'wb') as f: # Download the file from the Google Cloud Storage bucket. request = gcs_service.objects().get_media(bucket=BUCKET_NAME, object=dl_path) media = MediaIoBaseDownload(f, request) print('Downloading item ', id_num + 1, '...') print('Download Progress: ') done = False while not done: prog, done = media.next_chunk() print(prog.progress()) print('Image ', id_num + 1, ' downloaded.') return dl_path def get_img_paths(dirpath, bucket_name, dl=True, max_num_imgs=None, skip_first=0): client = storage.Client() id = 0 for blob in client.list_blobs(bucket_name, prefix=dirpath): if max_num_imgs is not None: if id > max_num_imgs - 1: break filepath = blob.name if filepath[-14:] == 'AnalyticMS.tif': if id < skip_first: id += 1 continue if dl == True: if not os.path.isfile(filepath): download_img(filepath, id) id += 1 yield filepath, id def load_img(img_path): '''Returns both the relevant geographic data, and other metadata such as cloudcover etc. and the img itself as a numpy array. ''' ds = gdal.Translate('', img_path, options='-ot Byte -scale minval maxval -of MEM') b1, b2, b3, b4 = (ds.GetRasterBand(1).ReadAsArray(), ds.GetRasterBand(2).ReadAsArray(), ds.GetRasterBand(3).ReadAsArray(), ds.GetRasterBand(4).ReadAsArray()) img_array = np.array((b3,b2,b1)) img_array = np.moveaxis(img_array, 0, 2) # if plot_image: # plot_img(img_array, figsize) return img_array def split_img(img_array, patch_shape=None, xoffset=0, yoffset=0): if patch_shape is None: return img_array img_shape = img_array.shape width, height = img_shape[:2] patch_width, patch_height = patch_shape[:2] width_remainder = width % patch_width height_remainder = height % patch_height pad_w = patch_width - width_remainder pad_h = patch_height - height_remainder half_pad_w = pad_w / 2 half_pad_w_1 = int(math.ceil(half_pad_w)) half_pad_w_2 = int(math.floor(half_pad_w)) half_pad_h = pad_h / 2 half_pad_h_1 = int(math.ceil(half_pad_h)) half_pad_h_2 = int(math.floor(half_pad_h)) img_padded = np.pad(img_array, [[half_pad_w_1, half_pad_w_2], [half_pad_h_1, half_pad_h_2], [0, 0]], 'constant', constant_values=(0)) patches = view_as_blocks(img_padded, patch_shape) n_horz_patches = patches.shape[1] # Number of patches along x-axis n_ver_patches = patches.shape[0] # Number of patches along y-axis for i in range(n_ver_patches): my = i * patch_height + yoffset - half_pad_w_1 for j in range(n_horz_patches): mx = j * patch_width + xoffset - half_pad_h_1 yield (i, j), patches[i, j, :, :, :, :], mx, my def prep_imgs(dirpath, bucketname, patch_shape=None, aoi=None, id_start_idx=55, id_end_idx=-18, max_num_imgs=25, skip_first=0, plot_image=False, figsize=(20,20), print_clip=False): img_paths = get_img_paths(dirpath, bucketname, max_num_imgs=max_num_imgs + skip_first, skip_first=skip_first) for img_path, idx in img_paths: item_id = img_path[id_start_idx:id_end_idx] # try: img_array= load_img(img_path) # except: # print('There was a problem loading image %s. Skipping.' % idx) # continue imgs_split = split_img(img_array, patch_shape) for (i, j), split, mx, my in imgs_split: subsample_id = str(i) + '_' + str(j) yield split[0,:,:,:], item_id, subsample_id def label_imgs(img, item_id, subsample_id, test_dir, num_labeled, num_positive) -> [[str, str], None]: if not os.path.exists(os.path.dirname(test_dir)): try: os.makedirs(os.path.dirname(test_dir)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise # Print tile to screen clear_output(wait=True) sample_id = item_id + subsample_id print('Number of samples labeled: %d' % num_labeled) if num_labeled > 0: percent_pos = num_positive / num_labeled print('Percent positive: %f \n' % percent_pos) print(sample_id + '\n') fig, ax = plt.subplots(1, figsize=(10,10)) ax.imshow(img) plt.show() # prompt user for label ([y]es, [n]o, ENTER for no label (None)) while True: label = input('Vessel in image above ([y]es/[n]o; ENTER for no label, and q to quit)? \n') if len(label) == 0: label = None elif label in ['y', 'Y', 'yes', 'Yes', 'YES']: label = 1 elif label in ['n', 'N', 'no', 'No', 'NO']: label = 0 elif label in ['q', 'Q', 'quit', 'Quit', 'QUIT']: return -1 else: print('Invalid input. Try again. \n') continue break if label is not None: # Save img to test directory savepath = test_dir + sample_id + '.jpg' img = Image.fromarray(img) img.save(savepath) return {'sample_id':sample_id, 'label':label} else: return None def make_df(rows=None): col_names = ['sample_id', 'label'] df = pd.DataFrame(columns=col_names) #df.set_index('target_id') if rows is not None: df = df.append(rows) return df if __name__ == '__main__': dirpath = r'chimbote/6b1c85ce-3b5b-490c-91e1-34262ada7d0c/PSScene4Band' test_dir = r'/content/test/' aoi = None imgs = prep_imgs(dirpath, BUCKET_NAME, (299, 299, 3), aoi=aoi, id_start_idx=59, id_end_idx=-18, max_num_imgs=np.float('inf'), skip_first=0, plot_image=False, print_clip=False) labels = [] num_labeled = 0 num_positive = 0 for img, item_id, subsample_id, in imgs: label = label_imgs(img, item_id, subsample_id, test_dir, num_labeled, num_positive) if label == -1: break if label is not None: num_labeled += 1 num_positive += label['label'] labels.append(label) df = make_df(labels) df.head() from google.cloud import storage import glob def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" # bucket_name = "your-bucket-name" # source_file_name = "local/path/to/file" # destination_blob_name = "storage-object-name" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print( "File {} uploaded to {}.".format( source_file_name, destination_blob_name ) ) def upload_dir(bucket_name, source_dir_name, destination_blob_dir): assert os.path.isdir(source_dir_name) for local_file in glob.glob(source_dir_name + '/**'): if not os.path.isfile(local_file): continue destination_blob_name = destination_blob_dir + os.path.basename(local_file) upload_blob(bucket_name, local_file, destination_blob_name) bucket_name = BUCKET_NAME source_dir_name = '/content/test/' destination_blob_dir = 'test/imgs/' upload_dir(bucket_name, source_dir_name, destination_blob_dir) df.to_csv('/content/labels.csv') bucket_name = BUCKET_NAME source_file_name = '/content/labels.csv' destination_blob_name = 'test/labels.csv' upload_blob(bucket_name, source_file_name, destination_blob_name) ```
github_jupyter
### Getting started with Backtrader This is part of the KE5207 project assignment: GA-Fuzzy System for Trading Crude Palm Oil Futures ### Setup the trading rules and platform here ``` %matplotlib inline import matplotlib.pyplot as plt from __future__ import (absolute_import, division, print_function, unicode_literals) import datetime # For datetime objects import os.path # To manage paths import sys # To find out the script name (in argv[0]) # Import the backtrader platform import backtrader as bt import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') import matplotlib.pylab as pylab import csv import pytz import random from os import listdir from os.path import isfile, join import skfuzzy as fuzz from skfuzzy import control as ctrl import math from __future__ import division import numpy as np import random,pdb import operator path_sep='//' modpath1 = os.getcwd() +path_sep+ "Data" + path_sep def getFilesAndNames(dirpath): ''' Return only the Futures files from the directory''' onlyfiles = [] for f in listdir(dirpath): fullpath = join(dirpath, f) if isfile(fullpath) and f.startswith("F"): onlyfiles.append((fullpath,f.split(".")[0])) #print (onlyfiles) return onlyfiles #getFilesAndNames(os.getcwd() + "\\Data\\") # setup data def setup_multiple_data(bt, cerebro): import os modpath = modpath1 + "Test" + path_sep datalist = getFilesAndNames(modpath) for i in range(len(datalist)): df = pd.read_csv(datalist[i][0]) start_test = datetime.datetime.strptime(df['DateTime'][0], "%d/%m/%Y %H:%M") end_test = datetime.datetime.strptime(df['DateTime'][len(df)-1], "%d/%m/%Y %H:%M") # setup the data path #datafile = "FCPO_6_years_NUS.xlsx" data = bt.feeds.GenericCSVData( dataname=datalist[i][0], fromdate= start_test, todate= end_test, nullvalue=0.0, dtformat=('%d/%m/%Y %H:%M'), tz = pytz.timezone('Asia/Jakarta'), datetime=2, high=4, low=5, open=3, close=6, volume=7 ) # Add the Data Feed to Cerebro cerebro.adddata(data, name=datalist[i][1]) #print ("Added data source {}".format(datalist[i][0])) #if testmode: return def setup_platform(cerebro): ''' Setup the rules of engagement''' # Set our desired cash start, using MYR cerebro.broker.setcash(10000000.0) # Set the commission - max of 0.2% or RM30 comminfo = CommInfo_Fut_Perc_Mult( commission=0.002,#, # 0.2% #mult=1, margin = 4000 ) cerebro.broker.addcommissioninfo(comminfo) #cerebro.broker.setcommission(commission=0.001) # Add a FixedSize sizer according to the stake #cerebro.addsizer(bt.sizers.FixedSize, stake=1) class CommInfo_Fut_Perc_Mult(bt.CommInfoBase): #params = ( # ('stocklike', False)#, # Futures #('commtype', bt.CommInfoBase.COMM_PERC), # Apply % Commission # ('percabs', False), # pass perc as xx% which is the default #) def _getcommission(self, size, price, pseudoexec): return max(30, size * price * self.p.commission * self.p.mult) def setup_plot(): pylab.rcParams['figure.figsize'] = 45, 30 # that's default image size for this interactive session pylab.rcParams['font.family'] = 'sans-serif' pylab.rcParams['font.sans-serif'] = ['Bitstream Vera Sans'] pylab.rcParams['font.serif'] = ['Bitstream Vera Sans'] pylab.rcParams["font.size"] = "200" #plotter = Plotter() #back_tester.plot(plotter=plotter) #plor the result #plt.figure(figsize=(15,20)) #cerebro.plot(style='candlestick', iplot=False) #imagefile = "test_strategy.png" #modpath = os.getcwd() + "\\" ##datapath = os.path.join(modpath, imagefile) #pylab.savefig(datapath) ``` ### Visualise the data Data exploration and check the trend for the test data. ``` import os modpath = modpath1 + "Test" + path_sep datalist = getFilesAndNames(modpath) df = pd.read_csv(datalist[1][0]) # Sort DataFrame by date df = df.sort_values('DateTime') # Double check the result df.head() plt.figure(figsize = (18,9)) plt.plot(range(df.shape[0]),(df['Low']+df['High'])/2.0) plt.xticks(range(0,df.shape[0],500),df['Date'].loc[::500],rotation=45) plt.xlabel('Date',fontsize=18) plt.ylabel('Mid Price',fontsize=18) plt.show() ``` ### Helper functions can be found here This section contains the generic function used in this notebook. ``` # https://stackoverflow.com/questions/9489078/how-to-split-a-huge-csv-file-based-on-content-of-first-column import csv from itertools import groupby def split_excel_to_csv(): datafile = 'FCPO_6_years_NUS.csv' modpath = modpath1 #os.getcwd() + "\\Data\\" datapath = os.path.join(modpath, datafile) csv_header = 'Date,Time,DateTime,Open,High,Low,Close,Volume' reader = csv.reader(open(datapath)) next(reader) for key, rows in groupby(reader,lambda row: row[0]): if key[-1] in ["1","2","3"]: outputpath = os.path.join(modpath+"Test" + path_sep,"{}.csv".format(key)) else: outputpath = os.path.join(modpath+"Prod"+path_sep,"{}.csv".format(key)) with open(outputpath, "w") as output: output.write(csv_header + "\n") for row in rows: row.pop(0) # remove the key output.write(",".join(row) + "\n") #split_excel_to_csv() def writeToCsv(filepath, data): ''' Generate a csv file which contains the seven fuzzy extent centroid value''' with open(filepath,'w') as f: #print ("max {} and min {}".format(max(data), min(data))) f.write(",".join(map(str,splitDataToSevenExtents(data)))) def loadFromCsv(filepath): ''' Load the previous stored fuzzy extent values from csv file''' with open(filepath, 'rt') as f: reader = csv.reader(f) return list(map(float,[r for r in reader][0])) def splitDataToSevenExtents(data): ''' Split a list of array into seven parts meant for the fuzzy extent later Calculate the central point and also the std dev ''' # get the max and min max_point = max(data) # split the positive into three parts min_point = min(data) # split the negative into three parts pos_part = 0 if max_point > 0: pos_part = round(max_point / 3, 2) neg_part = 0 if min_point < 0: neg_part = round(min_point / 3, 2) return [neg_part * 3, neg_part * 2, neg_part, 0, pos_part, pos_part * 2, pos_part * 3] def generateAllCombinationsIndividual(): ''' Use to cache the fuzzy system model''' inds = ['sma','ama','tma','tpma'] m = np.array([10, 20, 50, 100, 150, 200]) n = np.array([3,5,10,15,20]) ext = "M" rec = 0 rules = [] for i in inds: for slow in m: for fast in n: if fast < slow: rule = [i, fast, slow, ext, rec] rules.append(rule) return {"individual":np.array(rules)} #generateAllCombinationsIndividual() def generateRandomRule(): ''' generate one random rule''' inds = ['sma','ama','tma','tpma'] m = np.array([10, 20, 50, 100, 150, 200]) n = np.array([3,5,10,15,20]) exts = ['VL','EL','L','M','H','VH','EH'] neg = np.arange(-1,0,0.1) med = np.arange(-1,1,0.1) pos = np.arange(0,1,0.1) sel_ext = random.choice(exts) rec = 0 if sel_ext in ['VL','EL','L']: rec = random.choice(neg) elif sel_ext in ['M']: rec = random.choice(med) else: rec = random.choice(pos) fast = random.choice(n) slow = random.choice(m[m>fast]) return [random.choice(inds), fast, slow, sel_ext, rec] #print (generateRandomRule()) def generateRandomIndividual(): rules = [] total_rules = 10 for i in range(0,total_rules): rules.append(generateRandomRule()) return {"individual":np.array(rules)} #print (generateRandomIndividual()) def generateRandomPopulation(size=20): population = dict() for i in range(0,size): population[i] = generateRandomIndividual() return population #def modifyIndividual(ind): # ind["newkey"] = 0 #pop= generateRandomPopulation() #modifyIndividual(pop[1]) #print (pop[1]) #for ind in pop.items(): # print (ind) #for rule in pop[1]["individual"]: # print (rule) #pop[1]["rating"] = 10 #population = {0:{"ind":[]}} #population[0]['ind'] = {} ``` ### Building the fuzzy extents Use the old data output the values to an external file to that the fuzzy extents models can be build later. ``` def buildFuzzySystem(arr, bShowPlot=False, bDebug=False): '''Given an array of value, build and return a fuzzy system''' # New Antecedent/Consequent objects hold universe variables and membership functions feModel = ctrl.Antecedent(np.arange(arr[0], arr[-1], 0.1), 'feModel') recModel = ctrl.Consequent(np.arange(-1, 1, 0.1), 'recModel') recModel["Neg"] = fuzz.pimf(recModel.universe, -1, -1, -1, 0) recModel["Med"] = fuzz.pimf(recModel.universe, -1, 0, 0, 1) recModel["Pos"] = fuzz.pimf(recModel.universe, 0, 1, 1, 1) feModel["EL"] = fuzz.pimf(feModel.universe, arr[0], arr[0], arr[0],arr[1]) feModel["VL"] = fuzz.pimf(feModel.universe, arr[0], arr[1], arr[1], arr[2]) feModel["L"] = fuzz.pimf(feModel.universe, arr[1], arr[2], arr[2], arr[3]) feModel["M"] = fuzz.pimf(feModel.universe, arr[2], arr[3], arr[3], arr[4]) feModel["H"] = fuzz.pimf(feModel.universe, arr[3], arr[4], arr[4], arr[5]) feModel["VH"] = fuzz.pimf(feModel.universe, arr[4], arr[5], arr[5], arr[6]) feModel["EH"] = fuzz.pimf(feModel.universe, arr[5], arr[6], arr[6], arr[6]) if bShowPlot: recModel.view() feModel.view() if bDebug: print (type(recModel)) print (type(feModel)) #build the rules rule1 = ctrl.Rule(feModel["EL"] | feModel["L"] | feModel["VL"], recModel["Neg"]) rule2 = ctrl.Rule(feModel["M"], recModel["Med"]) rule3 = ctrl.Rule(feModel["EH"] | feModel["H"] | feModel["VH"], recModel["Pos"]) ctrl_sys = ctrl.ControlSystem([rule1, rule2, rule3]) ctrl_instance = ctrl.ControlSystemSimulation(ctrl_sys) return ctrl_instance, feModel, recModel def getFuzzyOutput(ctrl_instance, feModel, recModel, input_val, bShowPlot=False, bDebug=False): ''' Given the fuzzy system and the input value, compute and return the mf and the fuzzy extent''' ext = "" rec = 0 ants = [] try: ctrl_instance.input['feModel'] = input_val ctrl_instance.compute() if bShowPlot: recModel.view(sim=ctrl_instance) feModel.view(sim=ctrl_instance) ants = ctrl_instance.get_antecedents() if bDebug: print (type(recModel)) print (type(feModel)) #print (ctrl_instance.print_state()) ext = "" if ants: ext = max(ants, key=ants.get) rec = ctrl_instance.output['recModel'] except: print("Input val:{}. fe:{}, rec:{}, ctrl:{}".format(input_val, feModel, recModel,type(ctrl_instance))) print ("Type ants:{} and content:{}".format(type(ants), ants)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print("Exception type:{}, File name:{} and line no:{}".format(exc_type, fname, exc_tb.tb_lineno)) #TODO: Handle this error properly #raise return (rec, ext) def testFuzzyLogic(): #Input val:-1.6666666666669698. fe:Antecedent: fe, rec:0 bShowPlot= True bDebug = True diffval = -24.0992834873864 ind_type = "tpma" fast = "15" slow = "50" modpath = modpath1 #os.getcwd() + "\\Data\\" filename = "{}_{}_{}.csv".format(ind_type, fast, slow) filepath = os.path.join(modpath +"Model"+path_sep, filename) farr = loadFromCsv(filepath) print (farr) fuzsys, fe, rec = buildFuzzySystem(farr, bShowPlot=bShowPlot, bDebug=bDebug) mf, ext = getFuzzyOutput(fuzsys, fe, rec, diffval, bShowPlot=bShowPlot, bDebug= bDebug) testFuzzyLogic() import numpy as np import random as rand roulette_wheel = np.array((0)) slot_count = 0 def init_roul_wheel(value_array): slot_count = 0 i=0 arrsize = value_array.size while i < arrsize/2: slot_count = slot_count + value_array[2*i+1] i = i + 1 roulette_wheel = np.zeros((slot_count),dtype=np.int) #print(roulette_wheel) i = 0 while i < arrsize/2: rv = value_array[2*i] bv = value_array[2*i+1] j = 0 while j<bv: t = rand.randint(0,slot_count-1) wheel_alloc = roulette_wheel[t] if wheel_alloc == 0: roulette_wheel[t] = rv j = j + 1 i = i + 1 return (roulette_wheel) def spin(rw): slot_count = rw.size randno = rand.randint(0,10000) rot_degree = randno%360 rot_unit = 360/slot_count rol_no = (rot_degree - (rot_degree%(rot_unit)))/rot_unit rol_value = rw[int(rol_no)] return rol_value wheel_vector = np.array([10,1,20,2,30,2,40,4,50,5,60,4,70,3,80,2,90,2]) x = init_roul_wheel(wheel_vector) print (x) print (spin(x)) ``` ### Setting up Custom indicators Besides the standard simple moving average, we also need to setup: 1. Adaptive moving average 1. Typical Price moving average 1. Triangular moving average ``` class TypicalPriceMovingAverage(bt.Indicator): lines = ('tpma',) params = (('period', 20),) def __init__(self): self.addminperiod(self.params.period) def next(self): dataline = self.data.get(size=self.p.period) datasum = max(dataline) + min(dataline) + dataline[-1] self.lines.tpma[0] = datasum/3 ``` ### Defining strategies here Creating a custom strategy to implement the FMAS crossover strategy. ``` class FMASCrossOver(bt.Strategy): """A simple moving average crossover strategy; crossing of a fast and slow moving average generates buy/sell signals""" params = {"individual":[], "filePath": "", "bSilentMode":False, #no logging "bDebug":False, #debug printout mode "bFuzzyPlot": False, #show fuzzy plot "bGenMaDiffFiles": False, #generate ma diff files for fuzzy extent building "bGetRating": False} #get overall rating for individual def calcRateOfReturn(self, value, cash, capital): ''' used available cash against the treasury interests''' '''http://www.bnm.gov.my/index.php?tpl=2014_govtsecuritiesyield''' ''' assume the trading period is for the whole of the short term interest''' shortTermBillInterests = 0.0328 return ((value + (cash * shortTermBillInterests))/capital) def getWritePath(self, ind_type, fast, slow): modpath = modpath1 #os.getcwd() + "\\Data\\" filename = "{}_{}_{}.csv".format(ind_type, fast, slow) filepath = os.path.join(modpath +"Model"+path_sep, filename) return filepath def getFuzzyModel(self, ind_type, fast, slow, bShowPlot = False): filepath = self.getWritePath(ind_type, fast, slow) farr = loadFromCsv(filepath) fuzsys, fe, rec = buildFuzzySystem(farr, bShowPlot=bShowPlot) return fuzsys, fe, rec def getFuzzyPosition(self, fuzsys, fe, rec, diffval, bShowPlot = False): mf, ext = getFuzzyOutput(fuzsys, fe, rec, diffval, bShowPlot=bShowPlot) return mf, ext def getLotSize(self, modal, price, rating): return (modal/price)*rating/100 def setIndicator(self, ma_type, period_val, ind_type, d): plottitle = "SlowMA: " #period_val = self.params.slow #ind_type = self.p.ind if ma_type == "fast": plottitle = "FastMA: " # period_val = self.params.fast datafeed = self.getdatabyname(d) if self.p.bDebug: print ("ind:{}, ma type:{}, period:{}".format(ind_type, ma_type, period_val)) ma = None if ind_type == 'sma': ma = bt.indicators.SMA(datafeed, # The symbol for the moving average period=period_val, # Fast moving average plotname=plottitle + d) elif ind_type == "ama": #ma = bt.indicators.KAMA(datafeed, # The symbol for the moving average # period=period_val, # Fast moving average # plotname=plottitle + d) ''' ma = bt.indicators.SMA(datafeed, # The symbol for the moving average period=period_val, # Fast moving average plotname=plottitle + d) ''' ma = bt.talib.KAMA(datafeed, timeperiod=period_val, plotname=plottitle + d) elif ind_type == "tma": ''' ma = bt.indicators.SMA(datafeed, # The symbol for the moving average period=period_val, # Fast moving average plotname=plottitle + d) ''' ma = bt.talib.TRIMA(datafeed, # The symbol for the moving average timeperiod=period_val, # Fast moving average plotname=plottitle + d) elif ind_type == "tpma": ma = TypicalPriceMovingAverage(datafeed, # The symbol for the moving average period=period_val, # Fast moving average plotname=plottitle + d) return ma def log(self, txt, dt=None): ''' Logging function for this strategy''' if not self.p.bSilentMode: #TODO: Fix the datas[0] hardcoding later dt = dt or self.datas[0].datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): """Initialize the strategy""" self.bStopRunning = False self.fastma = dict() self.slowma = dict() self.regime = dict() self.extent = dict() self.recommend = dict() # only use to build the fuzzy extent files self.madiff = dict() # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None self.initialCapital = 0 self.fuzsysModel = dict() self.feModel = dict() self.recModel = dict() self._addobserver(True, bt.observers.BuySell) # CAUTION: Abuse of the method, I will change this in future code (see: https://community.backtrader.com/topic/473/plotting-just-the-account-s-value/4) for d in self.getdatanames(): key = "" for rule in self.p.individual["individual"]: indtype = rule[0] fast = rule[1] slow = rule[2] extent = rule[3] recommend = rule[4] # The moving averages key = "{}_{}_{}_{}".format(d,indtype,fast,slow) self.fastma[key] = self.setIndicator("fast",int(fast), indtype,d) self.slowma[key] = self.setIndicator("slow",int(slow), indtype,d) self.madiff[key] = [] #ma_type, period_val, ind_type, d # Get the regime self.regime[key] = self.fastma[key] - self.slowma[key] # Positive when bullish self.extent[key] = extent self.recommend[key] = float(recommend) self.fuzsysModel[key], self.feModel[key], self.recModel[key] \ = self.getFuzzyModel(indtype,fast,slow, bShowPlot=self.p.bFuzzyPlot) def next(self): #skip the rest of the data after we can get the rating if self.bStopRunning: return # Check if an order is pending ... if yes, we cannot send a 2nd one if self.order: return if self.initialCapital == 0: self.initialCapital = self.stats.broker.cash[0] #Loop through each data feed for i, d in enumerate(self.datas): dt, dn = self.datetime.date(), d._name pos = self.getposition(d).size key = "" ratings = [] #loop through each rules within this individual for rule in self.p.individual["individual"]: key = "{}_{}_{}_{}".format(dn,rule[0],rule[1],rule[2]) # for generate ma diff files, we want to collect all the ma diff for a particular key if self.p.bGenMaDiffFiles: self.madiff[key].append(self.regime[key][0]) #self.log("Regime: {}".format(self.regime[dn][0])) else: mf,ext = self.getFuzzyPosition(self.fuzsysModel[key], self.feModel[key], self.recModel[key], self.regime[key][0], bShowPlot=self.p.bFuzzyPlot) # get the fe and recommended value based on past data # check if the fe are the same rating = 0 if(ext == self.extent[key]): # if it is then calculate the overall rating per rule rating = mf * self.recommend[key] ratings.append(rating) if self.p.bDebug: print ("Rating:{} and extent:{} for key:{}".format(rating,ext, key)) #calculate the rating at individual level avg_rating = np.average(ratings) if not math.isnan(avg_rating) and self.p.bDebug: print ("Average rating:{} and pos is:{} for key:{}".format(avg_rating, pos, key)) # for bGetRating mode, we just want to get the rating for the individual and exit if (avg_rating > 0 or avg_rating < 0): # and self.p.bGetRating: self.p.individual["rating"] = avg_rating # print ("EXITING THE PROGRAM") # self.bStopRunning = True #else: if avg_rating > 0: # A buy signal # BUY, BUY, BUY!!! (with default parameters) self.log('%s BUY CREATE, %.2f with volume %.2f' % (dn, d.high[0], d.volume[0]), dt=d.datetime.date(0)) # Keep track of the created order to avoid a 2nd order self.order = self.buy(data=d, price=d.high[0], size = self.getLotSize(self.initialCapital,d.high[0],avg_rating)) #No trade when avg_rating is 0 elif avg_rating < 0: # A sell signal # SELL, SELL, SELL!!! (with all possible default parameters) self.log('%s SELL CREATE, %.2f with volume %.2f' % (dn, d.low[0], d.volume[0]), dt=d.datetime.date(0)) # Keep track of the created order to avoid a 2nd order self.order = self.sell(data=d, price=d.low[0], size = self.getLotSize(self.initialCapital,d.low[0],avg_rating)) def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return # Check if an order has been completed # Attention: broker could reject order if not enough cash if order.status in [order.Completed]: if order.isbuy(): self.log('BUY EXECUTED, Size: %.2f, Price: %.2f, Cost: %.2f, Comm %.2f, Portfolio Value: %.2f, Cash: %.2f' % (order.executed.size, order.executed.price, order.executed.value, order.executed.comm, self.stats.broker.value[0], self.stats.broker.cash[0])) self.buyprice = order.executed.price self.buycomm = order.executed.comm elif order.issell(): self.log('SELL EXECUTED, Size: %.2f, Price: %.2f, Cost: %.2f, Comm %.2f, Portfolio Value: %.2f, Cash: %.2f' % (order.executed.size, order.executed.price, order.executed.value, order.executed.comm, self.stats.broker.value[0], self.stats.broker.cash[0])) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def stop(self): #if self.p.bGetRating: # return if self.p.bGenMaDiffFiles: for i, d in enumerate(self.datas): dt, dn = self.datetime.date(), d._name key = "" #loop through each rules within this individual for rule in self.p.individual["individual"]: key = "{}_{}_{}_{}".format(dn,rule[0],rule[1],rule[2]) writePath = self.getWritePath(rule[0],rule[1],rule[2]) writeToCsv(writePath, self.madiff[key]) #self.log(len(self.madiff_arr)) return # else get the cash for a normal trade if "rating" not in self.p.individual.keys(): self.p.individual['rating'] = 0 # add the final profit value to the individual self.p.individual['profit'] = self.stats.broker.value[0] self.p.individual['ror'] = self.calcRateOfReturn(self.stats.broker.value[0], self.stats.broker.cash[0], self.initialCapital) ``` ### Main function goes here We'll process one individual per run. ``` #from report import Cerebro #if __name__ == '__main__': def main(individual, bGetRating= False, plotFileName = "", bDebug=False, bFuzzyPlot=False, bSilentMode=False,bGenMaDiffFiles=False): # Create a cerebro entity cerebro = bt.Cerebro() # get path modpath = modpath1 #os.getcwd() + "\\Data\\" #filename = "{}_{}_{}.csv".format(ind_type, fast, slow) #filepath = os.path.join(modpath +"\\Model\\", filename) # Add a strategy cerebro.addstrategy(FMASCrossOver, individual=individual, bGetRating=bGetRating,bDebug=bDebug, bFuzzyPlot=bFuzzyPlot,bSilentMode=bSilentMode,bGenMaDiffFiles=bGenMaDiffFiles) # Create a Data Feed setup_multiple_data(bt, cerebro) setup_platform(cerebro) # Print out the starting conditions print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Run over everything cerebro.run() # Print out the final result print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) # Plot the result if not plotFileName == "": imagefile = "graph{}.png".format(plotFileName) datapath = os.path.join(modpath+"\\Graph\\", imagefile) cerebro.plot(style='candlestick', iplot=False, ytight=True, subplot=False, path=datapath) ``` ## GA - Selection, crossover and mutation # GA START ``` def convert_dict(dictPop): dictList= [] for key, value in dictPop.items(): aKey = key aValue = value #temp.append(aKey) #temp.append(aValue) dictList.append(dictPop[aKey]['individual']) aKey = "" aValue = "" return dictList def convertList(listPop): dictpop= dict() for i in range(len(listPop)): dictpop[i] = {"individual":listPop[i]} return dictpop def select_pool(nPop): ranks = dict() sum_rank =0 for indx in range(nPop.shape[0]): sum_rank = 0 tot_cnt = 0 for inner in range(nPop.shape[1]): if len(nPop[indx][inner][4]) > 0: sum_rank = sum_rank + abs(float(nPop[indx][inner][4])) tot_cnt = tot_cnt + 1 sum_rank = sum_rank / tot_cnt ranks[sum_rank] = nPop[indx] sorted_indexed_weights = sorted(enumerate(ranks), key=operator.itemgetter(1)); indices, sorted_weights = zip(*sorted_indexed_weights); tot_sum=sum(sorted_weights) prob = [x/tot_sum for x in sorted_weights] cum_prob=np.cumsum(prob) random_num=random.random() #print(random_num) for index_value, cum_prob_value in zip(indices,cum_prob): #print ('cum vlaue',cum_prob_value) if random_num < cum_prob_value: #random_num = 0 return index_value def select_mating_pool(new_population): offspring = [] rowIndex = 0 ''' for indx in range(20): rate_of_return = 0 cmp_ror = 0 tot_cnt = 0 for inner in range(0,9): #print('index',indx) #print('inner',inner) if len(new_population[indx][inner][4]) > 0: rate_of_return=float(new_population[indx][inner][4])+rate_of_return tot_cnt = tot_cnt +1 rate_of_return = float(rate_of_return/tot_cnt) #if rate_of_return > cmp_ror: #offspring.append(new_population[indx]) ror = [indx,rate_of_return] if len(offspring) == 0: offspring.append(ror) offspring.append(ror) elif ror[1] > offspring[0][1]: offspring[0] = ror elif offspring[0][1] > ror[1] > offspring[1][1]: offspring[1] = ror #offspring.append(ror) #cmp_ror = rate_of_return #print(indx) #print(rate_of_return,' Rate of return ') ''' #import heapq #heapq.nlargest(2,offspring) new_population1 = [] rowIndex = select_pool(new_population) new_population1.append(new_population[rowIndex]) rowIndex = select_pool(new_population) new_population1.append(new_population[rowIndex]) #num_parents = 20 #new_population1 = numpy.empty((num_parents, pop.shape[1])) new_population1 = list(new_population[:int(0.8 * len(new_population))]) for idx in range(len(offspring)): new_population1.append(new_population[offspring[idx][0]]) new_population1.append(generateRandomIndividual()['individual']) new_population1.append(generateRandomIndividual()['individual']) return new_population1 def crossover_pop(pop,offspring_size): parents = pop offspring = pop # creating empty list / array -- need to check #print(offspring.shape) # The point at which crossover takes place between two parents. Usually it is at the center. crossover_point = np.uint8(offspring_size[1]/2) for k in range(0,19): parent1_idx = random.randint(0,19) parent2_idx = random.randint(0,19) offspring[k,0:crossover_point] = parents[parent1_idx,0:crossover_point] offspring[k,crossover_point:] = parents[parent2_idx, crossover_point:] offspring[k+1,0:crossover_point] = parents[parent2_idx,0:crossover_point] offspring[k+1,crossover_point:] = parents[parent1_idx, crossover_point:] return offspring def mutation(offspring_gen): offspring = offspring_gen for idx in range(offspring.shape[0]): for idx_m in range(0,3): #parent_idx = random.randint(0,19) rule_idx = random.randint(0,9) offspring[idx,rule_idx] = generateRandomRule() return offspring def gaPopGeneration(npopulation): #new_population1 = bt2.generateRandomPopulation() new_population = [] new_population = np.array(convert_dict(npopulation)) #import numpy as np sol_per_pop = 20 ## 10 individuals makes one population num_weights = 10 ## One individual contains 10 rules num_param_rule = 5 pop_size = (sol_per_pop,num_weights,num_param_rule) offspring_size = pop_size new_population_gen = select_mating_pool(new_population) return new_population_gen new_population_gen = np.array(new_population_gen) offspring_pop = crossover_pop(new_population_gen,offspring_size) final_population = mutation(offspring_pop) #final_population1 = convertList(final_population) return final_population pop1= generateRandomPopulation() newPop = convertList(gaPopGeneration(pop1)) ``` ## GA END ### Strategy starts here 1. Generate the initial population. Randomly generate 20 individuals. Each individual contains 10 rules in accordance with the rules set. 1. Calculate the fuzzy moving averages in the training period. Calculate the differences between two moving averages in the training period and the previous training period using the moving average method and the length of two moving averages that the rule provides. 1. Next, obtain the membership function according to the moving average differences of the previous training period. 1. Calculate the rating level according to the moving average differences of this training period, the membership function, and the recommend values that the individual provides. Because every individual provides a set of recommend values, there are ultimately 20 sets of rating levels. ``` #generate an individual that has all the combinations for indicator type, fast and slow #ind = generateAllCombinationsIndividual() #main(ind, bSilentMode=True,bGenMaDiffFiles=True) inds = ['tma'] m= [20] n = [10] #[3,5,10,15,20] #skip 1 pop= generateRandomPopulation() #for individual in pop.items(): #individual = np.append(individual,["ST"]) # print (individual) pind = {'individual': [['ama', '10', '150', 'VH', '0.1'], ['ama', '5', '200', 'EH', '0.5'], ['ama', '3', '10', 'EH', '0.7000000000000001'], ['tma', '3', '50', 'VH', '0.2'], ['tma', '15', '200', 'VL', '-0.5000000000000001'], ['tpma', '15', '200', 'VL', '-0.5000000000000001'], ['tma', '15', '150', 'EH', '0.4'], ['ama', '3', '20', 'M', '0.19999999999999973'], ['sma', '3', '100', 'VH', '0.1'], ['tpma', '15', '50', 'VL', '-0.40000000000000013']]} #build the fuzzy model on the first run #main(pind, bSilentMode=True,bGenMaDiffFiles=True) #main(pind, bSilentMode=True, bDebug=False) #print (pind) #print (pop[1]) i = 1 runName = "" for ind in pop.values(): #print (ind) print ("Starting run: {}".format(i)) main(ind, bSilentMode=True) i = i+1 #print(params[:,0],params[:,1], params[:,2], params[:,3], params[:,4]) #main(params[:,0],params[:,1], params[:,2], params[:,3], params[:,4]) #main(pop[1], bBestIndv=True) ``` 5. Select the best individual in the training period. Calculate the trading volume using the initial capital and the rating degree. Then, calculate the rate of return according to the rate of return calculation method provided above. Every individual has a rate of return. The one that has the highest rate of return is the best individual in the training period. 1. Calculate the rate of return in the selection period using the best individual in the training period. Calculate the differences between the two moving averages of this selection period and the previous selection period. Then, obtain the membership function and calculate the rating level and the rate of return. 1. Mark the best individual. In the first cycle, mark the rate of return as the best rate of return and the best individual in the training period as the overall best individual. From the second cycle, compare the rate of return in this loop and the best rate of return. If the rate of return from this loop is higher than the best individual in the last loop, and the gap is over 0.05, replace the best rate of return and the overall best individual. ``` #Calculate the rate of return for each individual i = 1 runName = "" for ind in pop.values(): print (ind) #print ("Individiual with rating:{} and profit:{}".format(ind["rating"], ind["profit"])) listOfKeys = [key for (key, value) in pop.items() if value['profit'] == max(d['profit'] for d in pop.values())] #print (listOfKeys) bestIndividual = pop[listOfKeys[0]] print(bestIndividual) ``` 1. Conduct a population evolution. Use genetic algorithms to choose 10% of the individuals from the old population in terms of their rate of return. Next, choose 80% of the individuals from the old population together with 10% randomly generated new individuals to experience the crossover and mutation. Finally, these two parts combined to form the new population. 1. Repeat Steps (4)–(6) for 50 repetitions. 1. Calculate the rate of return of the best individual in the test period using the overall best individual selected in the previous steps. Calculate the two moving averages in this test period and the previous test period. Then, obtain the membership function and calculate the rating level and the rate of return. 1. Move forward to the next experiment period and return to step (1). 1. After one experiment of one generation, the population needs to evolve. We take the rate of return as the fitness value and use Roulette Wheel Selection (RWS) to choose 10% of the 20 individuals from the old population. 1. They are most likely the two best individuals. We retain the two individuals as the first part of the new population. The second part of the new population is two individuals that are randomly generated. Then we continue use RWS to select 80% of the 20 individuals from the old population which is mostly like the 16 best individuals. These 16 individuals need to go through crossover and mutation to become the third part of the new population. ``` pop= generateRandomPopulation() newPop = convertList(gaPopGeneration(pop)) for ind in newPop.values(): print (ind) print ("Starting run: {}".format(ind)) #main(ind, bSilentMode=True) #i = i+1 ``` The crossover here indicates the exchange rules between two individuals. The crossover probability is 0.7, which is the most commonly used. We choose two individuals with a 0.7 probability and randomly generate a spot in the individuals.
github_jupyter
## Setting Jupyter Notebook ### Install the necessary packages. ``` !pip install tensorflow==2.4.3 ``` ### Download the necessary archive. #### If you want to download only archive: ``` !wget --load-cookies ~/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies ~/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1XQCXaVy5YVoLPF9V2mR9MAGQXElbh-53' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1XQCXaVy5YVoLPF9V2mR9MAGQXElbh-53" -O mask_archive_v0.3.zip && rm -rf ~/cookies.txt ``` #### If you want to download archive with model: ``` !wget --load-cookies ~/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --quiet --save-cookies ~/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1b29DgQo821Spa4m0eplq0RlLCvQn1f74' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1b29DgQo821Spa4m0eplq0RlLCvQn1f74" -O mask_archive_with_model_v0.3.zip && rm -rf ~/cookies.txt ``` ### Unzip archive and get directory. #### If you want to unzip and get only archive: ``` !unzip -qq mask_archive_v0.3.zip %cd mask_archive_v0.3 ``` #### If you want to unzip and get archive with model: ``` !unzip -qq mask_archive_with_model_v0.3.zip %cd mask_archive_with_model_v0.3 ``` ## Main Code ### Import modules. ``` # Import modules. import os import cv2 import imutils import numpy as np import matplotlib.pyplot as plt from imutils import paths from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import MobileNetV2 from tensorflow.keras.layers import AveragePooling2D from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow.keras.layers import Input from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array from tensorflow.keras.preprocessing.image import load_img from tensorflow.keras.models import load_model from tensorflow.keras.utils import to_categorical from sklearn.preprocessing import LabelBinarizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report ``` ### Function to display images in Jupyter Notebooks and Google Colab. ``` def plt_imshow(title, image): # Convert the image frame BGR to RGB color space and display it. image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.imshow(image) plt.title(title) plt.grid(False) plt.show() ``` ### Implementing face mask recognizer training script with Keras and TensorFlow. ``` def recognize_and_predict_mask(frame, faceNet, maskNet): # Hold the dimensions of the frame and then create a block in the frame. (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0)) # Pass the blob through the network and acquire face recognition. faceNet.setInput(blob) recognitions = faceNet.forward() # Initialize the face list, corresponding location, and prediction list of face mask networks. faces = [] locs = [] preds = [] # Loop over the recognitions. for i in range(0, recognitions.shape[2]): # Extract the confidence (like probability) related to recognition. confidence = recognitions[0, 0, i, 2] # Filter weak recognition by checking whether the confidence is greater than the minimum confidence. if confidence > args["confidence"]: # Calculate the (x, y) coordinates of the bounding box for the object. box = recognitions[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # Make sure the boundary boxes is within frame dimensions. (startX, startY) = (max(0, startX), max(0, startY)) (endX, endY) = (min(w - 1, endX), min(h - 1, endY)) # Extract the face ROI, convert it from BGR to RGB channel ordering, resize it to 224x224, and preprocess it. face = frame[startY:endY, startX:endX] face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face = cv2.resize(face, (224, 224)) face = img_to_array(face) face = preprocess_input(face) # Add the face and bounding boxes to their respective lists. faces.append(face) locs.append((startX, startY, endX, endY)) # Only make a predictions if at least one face was recognized if len(faces) > 0: # For faster inference we'll make batch predictions on all faces at the same time rather than one-by-one predictions in the above `for` loop. faces = np.array(faces, dtype="float32") preds = maskNet.predict(faces, batch_size=32) # Return a 2-tuple of the face locations and their corresponding locations. return (locs, preds) # Parse the arguments. # ap = argparse.ArgumentParser() # ap.add_argument("-d", "--dataset", type=str, default="dataset", # help="the path of the input dataset") # ap.add_argument("-p", "--plot", type=str, default="loss_acc_plot.png", # help="the path of output loss/accuracy plot") # ap.add_argument("-m", "--model", type=str, # default="maskRecognizer.model", # help="the path to output the face mask recognizer model") # args = vars(ap.parse_args()) # Since we are using Jupyter Notebooks we can replace our argument parsing code with hard coded arguments and values. args = { "dataset": "dataset", "plot": "loss_acc_plot.png", "model": "mask_recognizer.model" } # Set init learning rate, epochs, and batch size. INIT_LR = 1e-4 EPOCHS = 20 BS = 32 # Get the image list from the dataset directory, and then initialize the data(images) and class image list. print("Loading images...") imagePaths = list(paths.list_images(args["dataset"])) data = [] labels = [] # Loop over the image paths. for imagePath in imagePaths: # Extract class labels from file names. label = imagePath.split(os.path.sep)[-2] # Load the 224x224 input image and preprocess it. image = load_img(imagePath, target_size=(224, 224)) image = img_to_array(image) image = preprocess_input(image) # Update the data and label list, respectively. data.append(image) labels.append(label) # Convert data and labels to NumPy array. data = np.array(data, dtype="float32") labels = np.array(labels) # Perform one-hot encoding on the labels. lb = LabelBinarizer() labels = lb.fit_transform(labels) labels = to_categorical(labels) # Partition the data into training and testing splits using 75% of the data for training and the remaining 25% for testing. (trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.20, stratify=labels, random_state=42) # Construct the training image generator for data augmentation. aug = ImageDataGenerator( rotation_range=20, zoom_range=0.15, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.15, horizontal_flip=True, fill_mode="nearest") # Load the MobileNetV2 network to ensure that the head FC layer set is left off. baseModel = MobileNetV2(weights="imagenet", include_top=False, input_tensor=Input(shape=(224, 224, 3))) # Construct the head of the model to be placed on top of the base model. headModel = baseModel.output headModel = AveragePooling2D(pool_size=(7, 7))(headModel) headModel = Flatten(name="flatten")(headModel) headModel = Dense(128, activation="relu")(headModel) headModel = Dropout(0.5)(headModel) headModel = Dense(2, activation="softmax")(headModel) # Place the head FC model on top of the base model (it will be the actual model we will train). model = Model(inputs=baseModel.input, outputs=headModel) # Repeat to all layers of the base model to fix it so that it is not updated during the first training process. for layer in baseModel.layers: layer.trainable = False # Compile our model. print("Compiling model...") opt = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS) model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["accuracy"]) # Train the head of the network. print("Training head...") H = model.fit( aug.flow(trainX, trainY, batch_size=BS), steps_per_epoch=len(trainX) // BS, validation_data=(testX, testY), validation_steps=len(testX) // BS, epochs=EPOCHS) # Make predictions on the testing set print("Evaluating network...") predIdxs = model.predict(testX, batch_size=BS) # For each image in the testing set we need to find the index of the label with corresponding largest predicted probability. predIdxs = np.argmax(predIdxs, axis=1) # Show a nicely formatted classification report. print(classification_report(testY.argmax(axis=1), predIdxs, target_names=lb.classes_)) # Serialize the model to disk. print("Saving mask recognizer model...") model.save(args["model"], save_format="h5") # Make a plot the training loss and accuracy. N = EPOCHS plt.style.use("ggplot") plt.figure() plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc") plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc") plt.title("Training Loss and Accuracy on Mask Recognition") plt.xlabel("Epoch") plt.ylabel("Loss / Accuracy") plt.legend(loc="lower left") plt.show() ``` ### Implementing face mask recognizer for images with OpenCV. ``` # Parse the arguments. # ap = argparse.ArgumentParser() # ap.add_argument("-i", "--image", required=True, # help="the path of input image") # ap.add_argument("-f", "--face", type=str, # default="face_recognizer", # help="the path of face recognizer model directory") # ap.add_argument("-m", "--model", type=str, # default="maskRecognizer.model", # help="the path of trained face mask recognizer model") # ap.add_argument("-c", "--confidence", type=float, default=0.5, # help="minimum probability to filter weak recognitions") # args = vars(ap.parse_args()) # Since we are using Jupyter Notebooks we can replace our argument parsing code with hard coded arguments and values. args = { "image": "assets/image/mask-1.png", "face": "face_recognizer", "model": "mask_recognizer.model", "confidence": 0.5 } # Load our serialized face recognizer model from disk. print("Loading face recognizer model...") prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"]) weightsPath = os.path.sep.join([args["face"], "res10_300x300_ssd_iter_140000.caffemodel"]) net = cv2.dnn.readNet(prototxtPath, weightsPath) # Load the face mask recognizer model from disk. print("Loading face mask recognizer model...") model = load_model(args["model"]) # Load the input image from disk, clone it, and grab the image spatial dimensions. image = cv2.imread(args["image"]) orig = image.copy() (h, w) = image.shape[:2] # Construct a blob from the image. blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0)) # Pass the blob through the network and obtain the face recognitions. print("Computing face recognitions...") net.setInput(blob) recognitions = net.forward() # Loop over the recognitions. for i in range(0, recognitions.shape[2]): # Extract the confidence (i.e., probability) associated with the recognition. confidence = recognitions[0, 0, i, 2] # Filter out weak recognitions by ensuring the confidence is greater than the minimum confidence. if confidence > args["confidence"]: # Compute the (x, y)-coordinates of the bounding box for the object. box = recognitions[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # Ensure the bounding boxes fall within the dimensions of the frame. (startX, startY) = (max(0, startX), max(0, startY)) (endX, endY) = (min(w - 1, endX), min(h - 1, endY)) ## Extract the face ROI, convert it from BGR to RGB channel ordering, resize it to 224x224, and preprocess it. face = image[startY:endY, startX:endX] face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face = cv2.resize(face, (224, 224)) face = img_to_array(face) face = preprocess_input(face) face = np.expand_dims(face, axis=0) # Pass the face through the model to determine if the face has a mask or not. (mask, withoutMask) = model.predict(face)[0] # Determine the class label and color we'll use to draw the bounding box and text. label = "MASK" if mask > withoutMask else "NO MASK" color = (0, 255, 0) if label == "MASK" else (0, 0, 255) # Include the probability in the label. label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100) # Display the label and bounding box rectangle on the output frame. cv2.putText(image, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2) cv2.rectangle(image, (startX, startY), (endX, endY), color, 2) # Show the output image. plt_imshow("MASK RECOGNITION RESULT", image) ``` ### Implementing face mask recognizer in real-time video streams with OpenCV. ``` def recognize_and_predict_mask(frame, faceNet, maskNet): # Hold the dimensions of the frame and then create a block in the frame. (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300), (104.0, 177.0, 123.0)) # Pass the blob through the network and acquire face recognition. faceNet.setInput(blob) recognitions = faceNet.forward() # Initialize the face list, corresponding location, and prediction list of face mask networks. faces = [] locs = [] preds = [] # Loop over the recognitions. for i in range(0, recognitions.shape[2]): # Extract the confidence (like probability) related to recognition. confidence = recognitions[0, 0, i, 2] # Filter weak recognition by checking whether the confidence is greater than the minimum confidence. if confidence > args["confidence"]: # Calculate the (x, y) coordinates of the bounding box for the object. box = recognitions[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") # Make sure the boundary boxes is within frame dimensions. (startX, startY) = (max(0, startX), max(0, startY)) (endX, endY) = (min(w - 1, endX), min(h - 1, endY)) # Extract the face ROI, convert it from BGR to RGB channel ordering, resize it to 224x224, and preprocess it. face = frame[startY:endY, startX:endX] face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB) face = cv2.resize(face, (224, 224)) face = img_to_array(face) face = preprocess_input(face) # Add the face and bounding boxes to their respective lists. faces.append(face) locs.append((startX, startY, endX, endY)) # Only make a predictions if at least one face was recognized. if len(faces) > 0: # For faster inference we'll make batch predictions on all faces at the same time rather than one-by-one predictions in the above `for` loop. faces = np.array(faces, dtype="float32") preds = maskNet.predict(faces, batch_size=32) # Return a 2-tuple of the face locations and their corresponding locations. return (locs, preds) # # construct the argument parser and parse the arguments # ap = argparse.ArgumentParser() # ap.add_argument("-f", "--face", type=str, # default="face_recognizer", # help="path to face recognizer model directory") # ap.add_argument("-m", "--model", type=str, # default="mask_recognizer.model", # help="path to trained face mask recognizer model") # ap.add_argument("-c", "--confidence", type=float, default=0.5, # help="minimum probability to filter weak recognitions") # args = vars(ap.parse_args()) # Since we are using Jupyter Notebooks we can replace our argument parsing code with hard coded arguments and values. args = { "input": "assets/video/CDC_mask_720.mp4", "output": "mask_recognize_output.avi", "face": "face_recognizer", "model": "mask_recognizer.model", "confidence": 0.5 } # Load our serialized face recognizer model from disk. print("Loading face recognizer model...") prototxtPath = os.path.sep.join([args["face"], "deploy.prototxt"]) weightsPath = os.path.sep.join([args["face"], "res10_300x300_ssd_iter_140000.caffemodel"]) faceNet = cv2.dnn.readNet(prototxtPath, weightsPath) # Load the face mask recognizer model from disk. print("Loading face mask recognizer model...") maskNet = load_model(args["model"]) # Grab a reference to the video file and initialize pointer to output video file. print("Opening video file...") vs = cv2.VideoCapture(args["input"]) writer = None # Loop over the frames from the video stream. while True: # Grab the next frame. frame = vs.read()[1] # If we did not grab a frame then we have reached the end of the video. if frame is None: break # Resize the frame to have a maximum width of 400 pixels. frame = imutils.resize(frame, width=400) # Recognize faces in the frame and determine if they are wearing a face mask or not. (locs, preds) = recognize_and_predict_mask(frame, faceNet, maskNet) # Loop over the recognized face locations and their corresponding locations. for (box, pred) in zip(locs, preds): # Unpack the bounding box and predictions. (startX, startY, endX, endY) = box (mask, withoutMask) = pred # Determine the class label and color we'll use to draw the bounding box and text. label = "MASK" if mask > withoutMask else "NO MASK" color = (0, 255, 0) if label == "MASK" else (0, 0, 255) # Include the probability in the label. label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100) # Display the label and bounding box rectangle on the output frame. cv2.putText(frame, label, (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2) cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2) # If the video writer is None and we are supposed to write the output video to disk initialize the writer. if writer is None and args["output"] is not None: fourcc = cv2.VideoWriter_fourcc(*"MJPG") writer = cv2.VideoWriter(args["output"], fourcc, 20, (frame.shape[1], frame.shape[0]), True) # If the writer is not None, write the frame to disk. if writer is not None: writer.write(frame) # Do a bit of cleanup. vs.release() # Check to see if the video writer point needs to be released. if writer is not None: writer.release() ``` If you are interested to view the video within Google Colab just execute the following code blocks. Our output video is produced in `.avi` format. First, we need to convert it to `.mp4` format. ``` !ffmpeg -i mask_recognize_output.avi mask_recognize_output.mp4 # Display video inline. from IPython.display import HTML from base64 import b64encode mp4 = open("mask_recognize_output.mp4", "rb").read() dataURL = "data:video/mp4;base64," + b64encode(mp4).decode() HTML(""" <video width=400 controls> <source src="%s" type="video/mp4"> </video> """ % dataURL) ```
github_jupyter
# Testing cosmogan Aug 25, 2020 Borrowing pieces of code from : - https://github.com/pytorch/tutorials/blob/11569e0db3599ac214b03e01956c2971b02c64ce/beginner_source/dcgan_faces_tutorial.py - https://github.com/exalearn/epiCorvid/tree/master/cGAN ``` import os import random import logging import sys import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data # from torchsummary import summary from torch.utils.data import DataLoader, TensorDataset import torch.fft import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.animation as animation from IPython.display import HTML import argparse import time from datetime import datetime import glob import pickle import yaml import collections %matplotlib widget ``` ## Modules ``` def f_load_config(config_file): with open(config_file) as f: config = yaml.load(f, Loader=yaml.SafeLoader) return config ### Transformation functions for image pixel values def f_transform(x): return 2.*x/(x + 4.) - 1. def f_invtransform(s): return 4.*(1. + s)/(1. - s) # custom weights initialization called on netG and netD def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) # Generator Code class View(nn.Module): def __init__(self, shape): super(View, self).__init__() self.shape = shape def forward(self, x): return x.view(*self.shape) class Generator(nn.Module): def __init__(self, gdict): super(Generator, self).__init__() ## Define new variables from dict keys=['ngpu','nz','nc','ngf','kernel_size','stride','g_padding'] ngpu, nz,nc,ngf,kernel_size,stride,g_padding=list(collections.OrderedDict({key:gdict[key] for key in keys}).values()) self.main = nn.Sequential( # nn.ConvTranspose2d(in_channels, out_channels, kernel_size,stride,padding,output_padding,groups,bias, Dilation,padding_mode) nn.Linear(nz,nc*ngf*8*8*8),# 32768 nn.BatchNorm2d(nc,eps=1e-05, momentum=0.9, affine=True), nn.ReLU(inplace=True), View(shape=[-1,ngf*8,8,8]), nn.ConvTranspose2d(ngf * 8, ngf * 4, kernel_size, stride, g_padding, output_padding=1, bias=False), nn.BatchNorm2d(ngf*4,eps=1e-05, momentum=0.9, affine=True), nn.ReLU(inplace=True), # state size. (ngf*4) x 8 x 8 nn.ConvTranspose2d( ngf * 4, ngf * 2, kernel_size, stride, g_padding, 1, bias=False), nn.BatchNorm2d(ngf*2,eps=1e-05, momentum=0.9, affine=True), nn.ReLU(inplace=True), # state size. (ngf*2) x 16 x 16 nn.ConvTranspose2d( ngf * 2, ngf, kernel_size, stride, g_padding, 1, bias=False), nn.BatchNorm2d(ngf,eps=1e-05, momentum=0.9, affine=True), nn.ReLU(inplace=True), # state size. (ngf) x 32 x 32 nn.ConvTranspose2d( ngf, nc, kernel_size, stride,g_padding, 1, bias=False), nn.Tanh() ) def forward(self, ip): return self.main(ip) class Discriminator(nn.Module): def __init__(self, gdict): super(Discriminator, self).__init__() ## Define new variables from dict keys=['ngpu','nz','nc','ndf','kernel_size','stride','d_padding'] ngpu, nz,nc,ndf,kernel_size,stride,d_padding=list(collections.OrderedDict({key:gdict[key] for key in keys}).values()) self.main = nn.Sequential( # input is (nc) x 64 x 64 # nn.Conv2d(in_channels, out_channels, kernel_size,stride,padding,output_padding,groups,bias, Dilation,padding_mode) nn.Conv2d(nc, ndf,kernel_size, stride, d_padding, bias=True), nn.BatchNorm2d(ndf,eps=1e-05, momentum=0.9, affine=True), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf) x 32 x 32 nn.Conv2d(ndf, ndf * 2, kernel_size, stride, d_padding, bias=True), nn.BatchNorm2d(ndf * 2,eps=1e-05, momentum=0.9, affine=True), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*2) x 16 x 16 nn.Conv2d(ndf * 2, ndf * 4, kernel_size, stride, d_padding, bias=True), nn.BatchNorm2d(ndf * 4,eps=1e-05, momentum=0.9, affine=True), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*4) x 8 x 8 nn.Conv2d(ndf * 4, ndf * 8, kernel_size, stride, d_padding, bias=True), nn.BatchNorm2d(ndf * 8,eps=1e-05, momentum=0.9, affine=True), nn.LeakyReLU(0.2, inplace=True), # state size. (ndf*8) x 4 x 4 nn.Flatten(), nn.Linear(nc*ndf*8*8*8, 1) # nn.Sigmoid() ) def forward(self, ip): return self.main(ip) def f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='inf_img_',op_size=500): '''Generate images for best saved models Arguments: gdict, netG, optimizerG, ip_fname: name of input file op_strg: [string name for output file] op_size: Number of images to generate ''' nz,device=gdict['nz'],gdict['device'] try: if torch.cuda.is_available(): checkpoint=torch.load(ip_fname) else: checkpoint=torch.load(ip_fname,map_location=torch.device('cpu')) except Exception as e: print(e) print("skipping generation of images for ",ip_fname) return ## Load checkpoint if gdict['multi-gpu']: netG.module.load_state_dict(checkpoint['G_state']) else: netG.load_state_dict(checkpoint['G_state']) ## Load other stuff iters=checkpoint['iters'] epoch=checkpoint['epoch'] optimizerG.load_state_dict(checkpoint['optimizerG_state_dict']) # Generate batch of latent vectors noise = torch.randn(op_size, 1, 1, nz, device=device) # Generate fake image batch with G netG.eval() ## This is required before running inference gen = netG(noise) gen_images=gen.detach().cpu().numpy()[:,:,:,:] print(gen_images.shape) op_fname='%s_epoch-%s_step-%s.npy'%(op_strg,epoch,iters) np.save(op_loc+op_fname,gen_images) print("Image saved in ",op_fname) def f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc): ''' Checkpoint model ''' if gdict['multi-gpu']: ## Dataparallel torch.save({'epoch':epoch,'iters':iters,'best_chi1':best_chi1,'best_chi2':best_chi2, 'G_state':netG.module.state_dict(),'D_state':netD.module.state_dict(),'optimizerG_state_dict':optimizerG.state_dict(), 'optimizerD_state_dict':optimizerD.state_dict()}, save_loc) else : torch.save({'epoch':epoch,'iters':iters,'best_chi1':best_chi1,'best_chi2':best_chi2, 'G_state':netG.state_dict(),'D_state':netD.state_dict(),'optimizerG_state_dict':optimizerG.state_dict(), 'optimizerD_state_dict':optimizerD.state_dict()}, save_loc) def f_load_checkpoint(ip_fname,netG,netD,optimizerG,optimizerD,gdict): ''' Load saved checkpoint Also loads step, epoch, best_chi1, best_chi2''' try: checkpoint=torch.load(ip_fname) except Exception as e: print(e) print("skipping generation of images for ",ip_fname) raise SystemError ## Load checkpoint if gdict['multi-gpu']: netG.module.load_state_dict(checkpoint['G_state']) netD.module.load_state_dict(checkpoint['D_state']) else: netG.load_state_dict(checkpoint['G_state']) netD.load_state_dict(checkpoint['D_state']) optimizerD.load_state_dict(checkpoint['optimizerD_state_dict']) optimizerG.load_state_dict(checkpoint['optimizerG_state_dict']) iters=checkpoint['iters'] epoch=checkpoint['epoch'] best_chi1=checkpoint['best_chi1'] best_chi2=checkpoint['best_chi2'] netG.train() netD.train() return iters,epoch,best_chi1,best_chi2 #################### ### Pytorch code ### #################### def f_torch_radial_profile(img, center=(None,None)): ''' Module to compute radial profile of a 2D image Bincount causes issues with backprop, so not using this code ''' y,x=torch.meshgrid(torch.arange(0,img.shape[0]),torch.arange(0,img.shape[1])) # Get a grid of x and y values if center[0]==None and center[1]==None: center = torch.Tensor([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0]) # compute centers # get radial values of every pair of points r = torch.sqrt((x - center[0])**2 + (y - center[1])**2) r= r.int() # print(r.shape,img.shape) # Compute histogram of r values tbin=torch.bincount(torch.reshape(r,(-1,)),weights=torch.reshape(img,(-1,)).type(torch.DoubleTensor)) nr = torch.bincount(torch.reshape(r,(-1,))) radialprofile = tbin / nr return radialprofile[1:-1] def f_torch_get_azimuthalAverage_with_batch(image, center=None): ### Not used in this code. """ Calculate the azimuthally averaged radial profile. Only use if you need to combine batches image - The 2D image center - The [x,y] pixel coordinates used as the center. The default is None, which then uses the center of the image (including fracitonal pixels). source: https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/ """ batch, channel, height, width = image.shape # Create a grid of points with x and y coordinates y, x = np.indices([height,width]) if not center: center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0]) # Get the radial coordinate for every grid point. Array has the shape of image r = torch.tensor(np.hypot(x - center[0], y - center[1])) # Get sorted radii ind = torch.argsort(torch.reshape(r, (batch, channel,-1))) r_sorted = torch.gather(torch.reshape(r, (batch, channel, -1,)),2, ind) i_sorted = torch.gather(torch.reshape(image, (batch, channel, -1,)),2, ind) # Get the integer part of the radii (bin size = 1) r_int=r_sorted.to(torch.int32) # Find all pixels that fall within each radial bin. deltar = r_int[:,:,1:] - r_int[:,:,:-1] # Assumes all radii represented rind = torch.reshape(torch.where(deltar)[2], (batch, -1)) # location of changes in radius rind=torch.unsqueeze(rind,1) nr = (rind[:,:,1:] - rind[:,:,:-1]).type(torch.float) # number of radius bin # Cumulative sum to figure out sums for each radius bin csum = torch.cumsum(i_sorted, axis=-1) # print(csum.shape,rind.shape,nr.shape) tbin = torch.gather(csum, 2, rind[:,:,1:]) - torch.gather(csum, 2, rind[:,:,:-1]) radial_prof = tbin / nr return radial_prof def f_get_rad(img): ''' Get the radial tensor for use in f_torch_get_azimuthalAverage ''' height,width=img.shape[-2:] # Create a grid of points with x and y coordinates y, x = np.indices([height,width]) center=[] if not center: center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0]) # Get the radial coordinate for every grid point. Array has the shape of image r = torch.tensor(np.hypot(x - center[0], y - center[1])) # Get sorted radii ind = torch.argsort(torch.reshape(r, (-1,))) return r.detach(),ind.detach() def f_torch_get_azimuthalAverage(image,r,ind): """ Calculate the azimuthally averaged radial profile. image - The 2D image center - The [x,y] pixel coordinates used as the center. The default is None, which then uses the center of the image (including fracitonal pixels). source: https://www.astrobetter.com/blog/2010/03/03/fourier-transforms-of-images-in-python/ """ # height, width = image.shape # # Create a grid of points with x and y coordinates # y, x = np.indices([height,width]) # if not center: # center = np.array([(x.max()-x.min())/2.0, (y.max()-y.min())/2.0]) # # Get the radial coordinate for every grid point. Array has the shape of image # r = torch.tensor(np.hypot(x - center[0], y - center[1])) # # Get sorted radii # ind = torch.argsort(torch.reshape(r, (-1,))) r_sorted = torch.gather(torch.reshape(r, ( -1,)),0, ind) i_sorted = torch.gather(torch.reshape(image, ( -1,)),0, ind) # Get the integer part of the radii (bin size = 1) r_int=r_sorted.to(torch.int32) # Find all pixels that fall within each radial bin. deltar = r_int[1:] - r_int[:-1] # Assumes all radii represented rind = torch.reshape(torch.where(deltar)[0], (-1,)) # location of changes in radius nr = (rind[1:] - rind[:-1]).type(torch.float) # number of radius bin # Cumulative sum to figure out sums for each radius bin csum = torch.cumsum(i_sorted, axis=-1) tbin = torch.gather(csum, 0, rind[1:]) - torch.gather(csum, 0, rind[:-1]) radial_prof = tbin / nr return radial_prof def f_torch_fftshift(real, imag): for dim in range(0, len(real.size())): real = torch.roll(real, dims=dim, shifts=real.size(dim)//2) imag = torch.roll(imag, dims=dim, shifts=imag.size(dim)//2) return real, imag def f_torch_compute_spectrum(arr,r,ind): GLOBAL_MEAN=1.0 arr=(arr-GLOBAL_MEAN)/(GLOBAL_MEAN) y1=torch.fft.fftn(arr,dim=(-2,-1)) real,imag=f_torch_fftshift(y1.real,y1.imag) y2=real**2+imag**2 ## Absolute value of each complex number # print(y2.shape) z1=f_torch_get_azimuthalAverage(y2,r,ind) ## Compute radial profile return z1 def f_torch_compute_batch_spectrum(arr,r,ind): batch_pk=torch.stack([f_torch_compute_spectrum(i,r,ind) for i in arr]) return batch_pk def f_torch_image_spectrum(x,num_channels,r,ind): ''' Data has to be in the form (batch,channel,x,y) ''' mean=[[] for i in range(num_channels)] sdev=[[] for i in range(num_channels)] for i in range(num_channels): arr=x[:,i,:,:] batch_pk=f_torch_compute_batch_spectrum(arr,r,ind) mean[i]=torch.mean(batch_pk,axis=0) # sdev[i]=torch.std(batch_pk,axis=0)/np.sqrt(batch_pk.shape[0]) # sdev[i]=torch.std(batch_pk,axis=0) sdev[i]=torch.var(batch_pk,axis=0) mean=torch.stack(mean) sdev=torch.stack(sdev) return mean,sdev def f_compute_hist(data,bins): try: hist_data=torch.histc(data,bins=bins) ## A kind of normalization of histograms: divide by total sum hist_data=(hist_data*bins)/torch.sum(hist_data) except Exception as e: print(e) hist_data=torch.zeros(bins) return hist_data ### Losses def loss_spectrum(spec_mean,spec_mean_ref,spec_std,spec_std_ref,image_size,lambda1): ''' Loss function for the spectrum : mean + variance Log(sum( batch value - expect value) ^ 2 )) ''' idx=int(image_size/2) ### For the spectrum, use only N/2 indices for loss calc. ### Warning: the first index is the channel number.For multiple channels, you are averaging over them, which is fine. spec_mean=torch.log(torch.mean(torch.pow(spec_mean[:,:idx]-spec_mean_ref[:,:idx],2))) spec_sdev=torch.log(torch.mean(torch.pow(spec_std[:,:idx]-spec_std_ref[:,:idx],2))) lambda1=lambda1; lambda2=lambda1; ans=lambda1*spec_mean+lambda2*spec_sdev if torch.isnan(spec_sdev).any(): print("spec loss with nan",ans) return ans def loss_hist(hist_sample,hist_ref): lambda1=1.0 return lambda1*torch.log(torch.mean(torch.pow(hist_sample-hist_ref,2))) # def f_size(ip): # p=2;s=2 # # return (ip + 2 * 0 - 1 * (p-1) -1 )/ s + 1 # return (ip-1)*s - 2 * p + 1 *(5-1)+ 1 + 1 # f_size(128) # logging.basicConfig(filename=save_dir+'/log.log',filemode='w',format='%(name)s - %(levelname)s - %(message)s') ``` ## Main code ``` def f_train_loop(dataloader,metrics_df,gdict): ''' Train single epoch ''' ## Define new variables from dict keys=['image_size','start_epoch','epochs','iters','best_chi1','best_chi2','save_dir','device','flip_prob','nz','batchsize','bns'] image_size,start_epoch,epochs,iters,best_chi1,best_chi2,save_dir,device,flip_prob,nz,batchsize,bns=list(collections.OrderedDict({key:gdict[key] for key in keys}).values()) for epoch in range(start_epoch,epochs): t_epoch_start=time.time() for count, data in enumerate(dataloader, 0): ####### Train GAN ######## netG.train(); netD.train(); ### Need to add these after inference and before training tme1=time.time() ### Update D network: maximize log(D(x)) + log(1 - D(G(z))) netD.zero_grad() real_cpu = data[0].to(device) b_size = real_cpu.size(0) real_label = torch.full((b_size,), 1, device=device) fake_label = torch.full((b_size,), 0, device=device) g_label = torch.full((b_size,), 1, device=device) ## No flipping for Generator labels # Flip labels with probability flip_prob for idx in np.random.choice(np.arange(b_size),size=int(np.ceil(b_size*flip_prob))): real_label[idx]=0; fake_label[idx]=1 # Generate fake image batch with G noise = torch.randn(b_size, 1, 1, nz, device=device) fake = netG(noise) # Forward pass real batch through D output = netD(real_cpu).view(-1) errD_real = criterion(output, real_label.float()) errD_real.backward() D_x = output.mean().item() # Forward pass real batch through D output = netD(fake.detach()).view(-1) errD_fake = criterion(output, fake_label.float()) errD_fake.backward() D_G_z1 = output.mean().item() errD = errD_real + errD_fake optimizerD.step() ###Update G network: maximize log(D(G(z))) netG.zero_grad() output = netD(fake).view(-1) errG_adv = criterion(output, g_label.float()) # Histogram pixel intensity loss hist_gen=f_compute_hist(fake,bins=bns) hist_loss=loss_hist(hist_gen,hist_val.to(device)) # Add spectral loss mean,sdev=f_torch_image_spectrum(f_invtransform(fake),1,r.to(device),ind.to(device)) spec_loss=loss_spectrum(mean,mean_spec_val.to(device),sdev,sdev_spec_val.to(device),image_size,gdict['lambda1']) if gdict['spec_loss_flag']: errG=errG_adv+spec_loss else: errG=errG_adv if torch.isnan(errG).any(): logging.info(errG) raise SystemError # Calculate gradients for G errG.backward() D_G_z2 = output.mean().item() optimizerG.step() tme2=time.time() ####### Store metrics ######## # Output training stats if count % gdict['checkpoint_size'] == 0: logging.info('[%d/%d][%d/%d]\tLoss_D: %.4f\tLoss_adv: %.4f\tLoss_G: %.4f\tD(x): %.4f\tD(G(z)): %.4f / %.4f' % (epoch, epochs, count, len(dataloader), errD.item(), errG_adv.item(),errG.item(), D_x, D_G_z1, D_G_z2)), logging.info("Spec loss: %s,\t hist loss: %s"%(spec_loss.item(),hist_loss.item())), logging.info("Training time for step %s : %s"%(iters, tme2-tme1)) # Save metrics cols=['step','epoch','Dreal','Dfake','Dfull','G_adv','G_full','spec_loss','hist_loss','D(x)','D_G_z1','D_G_z2','time'] vals=[iters,epoch,errD_real.item(),errD_fake.item(),errD.item(),errG_adv.item(),errG.item(),spec_loss.item(),hist_loss.item(),D_x,D_G_z1,D_G_z2,tme2-tme1] for col,val in zip(cols,vals): metrics_df.loc[iters,col]=val ### Checkpoint the best model checkpoint=True iters += 1 ### Model has been updated, so update iters before saving metrics and model. ### Compute validation metrics for updated model netG.eval() with torch.no_grad(): #fake = netG(fixed_noise).detach().cpu() fake = netG(fixed_noise) hist_gen=f_compute_hist(fake,bins=bns) hist_chi=loss_hist(hist_gen,hist_val.to(device)) mean,sdev=f_torch_image_spectrum(f_invtransform(fake),1,r.to(device),ind.to(device)) spec_chi=loss_spectrum(mean,mean_spec_val.to(device),sdev,sdev_spec_val.to(device),image_size,gdict['lambda1']) # Storing chi for next step for col,val in zip(['spec_chi','hist_chi'],[spec_chi.item(),hist_chi.item()]): metrics_df.loc[iters,col]=val # Checkpoint model for continuing run if count == len(dataloader)-1: ## Check point at last step of epoch f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_last.tar') if (checkpoint and (epoch > 1)): # Choose best models by metric if hist_chi< best_chi1: f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_best_hist.tar') best_chi1=hist_chi.item() logging.info("Saving best hist model at epoch %s, step %s."%(epoch,iters)) if spec_chi< best_chi2: f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_best_spec.tar') best_chi2=spec_chi.item() logging.info("Saving best spec model at epoch %s, step %s"%(epoch,iters)) if iters in gdict['save_steps_list']: f_save_checkpoint(gdict,epoch,iters,best_chi1,best_chi2,netG,netD,optimizerG,optimizerD,save_loc=save_dir+'/models/checkpoint_{0}.tar'.format(iters)) logging.info("Saving given-step at epoch %s, step %s."%(epoch,iters)) # Save G's output on fixed_noise if ((iters % gdict['checkpoint_size'] == 0) or ((epoch == epochs-1) and (count == len(dataloader)-1))): netG.eval() with torch.no_grad(): fake = netG(fixed_noise).detach().cpu() img_arr=np.array(fake[:,:,:,:]) fname='gen_img_epoch-%s_step-%s'%(epoch,iters) np.save(save_dir+'/images/'+fname,img_arr) t_epoch_end=time.time() logging.info("Time taken for epoch %s: %s"%(epoch,t_epoch_end-t_epoch_start)) # Save Metrics to file after each epoch metrics_df.to_pickle(save_dir+'/df_metrics.pkle') logging.info("best chis: {0}, {1}".format(best_chi1,best_chi2)) def f_init_gdict(gdict,config_dict): ''' Initialize the global dictionary gdict with values in config file''' keys1=['workers','nc','nz','ngf','ndf','beta1','kernel_size','stride','g_padding','d_padding','flip_prob'] keys2=['image_size','checkpoint_size','num_imgs','ip_fname','op_loc'] for key in keys1: gdict[key]=config_dict['training'][key] for key in keys2: gdict[key]=config_dict['data'][key] ``` ## Start ``` if __name__=="__main__": torch.backends.cudnn.benchmark=True # torch.autograd.set_detect_anomaly(True) t0=time.time() ################################# # args=f_parse_args() # Manually add args ( different for jupyter notebook) args=argparse.Namespace() args.config='1_main_code/config_128.yaml' args.ngpu=1 args.batchsize=128 args.spec_loss_flag=True args.checkpoint_size=50 args.epochs=10 args.learn_rate=0.0002 args.mode='fresh' # args.mode='continue' # args.ip_fldr='/global/cfs/cdirs/m3363/vayyar/cosmogan_data/results_from_other_code/pytorch/results/128sq/20201211_093818_nb_test/' args.run_suffix='nb_test' args.deterministic=False args.seed='234373' args.lambda1=0.1 args.save_steps_list=[5,10] ### Set up ### config_file=args.config config_dict=f_load_config(config_file) # Initilize variables gdict={} f_init_gdict(gdict,config_dict) ## Add args variables to gdict for key in ['ngpu','batchsize','mode','spec_loss_flag','epochs','learn_rate','lambda1','save_steps_list']: gdict[key]=vars(args)[key] ###### Set up directories ####### if gdict['mode']=='fresh': # Create prefix for foldername fldr_name=datetime.now().strftime('%Y%m%d_%H%M%S') ## time format gdict['save_dir']=gdict['op_loc']+fldr_name+'_'+args.run_suffix if not os.path.exists(gdict['save_dir']): os.makedirs(gdict['save_dir']+'/models') os.makedirs(gdict['save_dir']+'/images') elif gdict['mode']=='continue': ## For checkpointed runs gdict['save_dir']=args.ip_fldr ### Read loss data with open (gdict['save_dir']+'df_metrics.pkle','rb') as f: metrics_dict=pickle.load(f) # ### Write all logging.info statements to stdout and log file (different for jpt notebooks) # logfile=gdict['save_dir']+'/log.log' # logging.basicConfig(level=logging.DEBUG, filename=logfile, filemode="a+", format="%(asctime)-15s %(levelname)-8s %(message)s") # Lg = logging.getLogger() # Lg.setLevel(logging.DEBUG) # lg_handler_file = logging.FileHandler(logfile) # lg_handler_stdout = logging.StreamHandler(sys.stdout) # Lg.addHandler(lg_handler_file) # Lg.addHandler(lg_handler_stdout) # logging.info('Args: {0}'.format(args)) # logging.info(config_dict) # logging.info('Start: %s'%(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) # if gdict['spec_loss_flag']: logging.info("Using Spectral loss") ### Override (different for jpt notebooks) gdict['num_imgs']=200 ## Special declarations gdict['bns']=50 gdict['device']=torch.device("cuda" if (torch.cuda.is_available() and gdict['ngpu'] > 0) else "cpu") gdict['ngpu']=torch.cuda.device_count() gdict['multi-gpu']=True if (gdict['device'].type == 'cuda') and (gdict['ngpu'] > 1) else False print(gdict) ### Initialize random seed if args.seed=='random': manualSeed = np.random.randint(1, 10000) else: manualSeed=int(args.seed) logging.info("Seed:{0}".format(manualSeed)) random.seed(manualSeed) np.random.seed(manualSeed) torch.manual_seed(manualSeed) torch.cuda.manual_seed_all(manualSeed) logging.info('Device:{0}'.format(gdict['device'])) if args.deterministic: logging.info("Running with deterministic sequence. Performance will be slower") torch.backends.cudnn.deterministic=True # torch.backends.cudnn.enabled = False torch.backends.cudnn.benchmark = False ################################# ####### Read data and precompute ###### img=np.load(gdict['ip_fname'],mmap_mode='r')[:gdict['num_imgs']].transpose(0,1,2,3).copy() t_img=torch.from_numpy(img) print("%s, %s"%(img.shape,t_img.shape)) dataset=TensorDataset(t_img) dataloader=DataLoader(dataset,batch_size=gdict['batchsize'],shuffle=True,num_workers=0,drop_last=True) # Precompute metrics with validation data for computing losses with torch.no_grad(): val_img=np.load(gdict['ip_fname'])[-3000:].transpose(0,1,2,3).copy() t_val_img=torch.from_numpy(val_img).to(gdict['device']) # Precompute radial coordinates r,ind=f_get_rad(img) r=r.to(gdict['device']); ind=ind.to(gdict['device']) # Stored mean and std of spectrum for full input data once mean_spec_val,sdev_spec_val=f_torch_image_spectrum(f_invtransform(t_val_img),1,r,ind) hist_val=f_compute_hist(t_val_img,bins=gdict['bns']) del val_img; del t_val_img; del img; del t_img ################################# ###### Build Networks ### # Define Models print("Building GAN networks") # Create Generator netG = Generator(gdict).to(gdict['device']) netG.apply(weights_init) # print(netG) summary(netG,(1,1,64)) # Create Discriminator netD = Discriminator(gdict).to(gdict['device']) netD.apply(weights_init) # print(netD) summary(netD,(1,128,128)) print("Number of GPUs used %s"%(gdict['ngpu'])) if (gdict['multi-gpu']): netG = nn.DataParallel(netG, list(range(gdict['ngpu']))) netD = nn.DataParallel(netD, list(range(gdict['ngpu']))) #### Initialize networks #### # criterion = nn.BCELoss() criterion = nn.BCEWithLogitsLoss() if gdict['mode']=='fresh': optimizerD = optim.Adam(netD.parameters(), lr=gdict['learn_rate'], betas=(gdict['beta1'], 0.999),eps=1e-7) optimizerG = optim.Adam(netG.parameters(), lr=gdict['learn_rate'], betas=(gdict['beta1'], 0.999),eps=1e-7) ### Initialize variables iters,start_epoch,best_chi1,best_chi2=0,0,1e10,1e10 ### Load network weights for continuing run elif gdict['mode']=='continue': iters,start_epoch,best_chi1,best_chi2=f_load_checkpoint(gdict['save_dir']+'/models/checkpoint_last.tar',netG,netD,optimizerG,optimizerD,gdict) logging.info("Continuing existing run. Loading checkpoint with epoch {0} and step {1}".format(start_epoch,iters)) start_epoch+=1 ## Start with the next epoch ## Add to gdict for key,val in zip(['best_chi1','best_chi2','iters','start_epoch'],[best_chi1,best_chi2,iters,start_epoch]): gdict[key]=val print(gdict) fixed_noise = torch.randn(gdict['batchsize'], 1, 1, gdict['nz'], device=gdict['device']) #Latent vectors to view G progress if __name__=="__main__": ################################# ### Set up metrics dataframe cols=['step','epoch','Dreal','Dfake','Dfull','G_adv','G_full','spec_loss','hist_loss','spec_chi','hist_chi','D(x)','D_G_z1','D_G_z2','time'] # size=int(len(dataloader) * epochs)+1 metrics_df=pd.DataFrame(columns=cols) ################################# ########## Train loop and save metrics and images ###### print("Starting Training Loop...") f_train_loop(dataloader,metrics_df,gdict) ## Generate images for best saved models ###### op_loc=gdict['save_dir']+'/images/' ip_fname=gdict['save_dir']+'/models/checkpoint_best_spec.tar' f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='best_spec',op_size=200) ip_fname=gdict['save_dir']+'/models/checkpoint_best_hist.tar' f_gen_images(gdict,netG,optimizerG,ip_fname,op_loc,op_strg='best_hist',op_size=200) tf=time.time() print("Total time %s"%(tf-t0)) print('End: %s'%(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) # metrics_df.plot('step','time') metrics_df # Feature matching loss ```
github_jupyter
``` %autosave 10 %matplotlib inline # a = [1, 2, 3] # =, ==, := # if x := len(a): # print('Array length is {}'.format(x)) # s = input('Введите свое имя: ') # print('Пользователь ввел: {}'.format(s)) import os os.listdir() # http://sai.homb.it try: f = open('./diagram.csv') text = f.read() assert False, 'False!' print(text) f.close() except AssertionError as e: print(e) with open('./diagram.csv') as f: text = f.read() print(f.closed) print(f.closed) try: f = open('./diagram.csv') finally: f.close() fname = './diagram.csv' x = [] y = [] with open(fname) as f: for row in f: row = row.strip() x_, y_ = map(float, row.split(',')) x.append(x_) y.append(y_) # print(x) # print(y) basename, ext = os.path.splitext(fname) # print(basename, ext) dirname = './data' os.makedirs(dirname, exist_ok=True) new_fname = os.path.join(dirname, basename + '.tsv') with open(new_fname, 'w') as f: for x_, y_ in zip(x, y): f.write('{x}\t{y}\n'.format(x=x_, y=y_)) !cat data/diagram.tsv import matplotlib.pyplot as plt plt.plot(x, y, 'x') with open('cat.jpg', 'rb') as f: data = f.read(100) print(data) from PIL import Image import numpy as np with Image.open('cat.jpg') as img: a = np.array(img) print(a) # display(img) a.shape a.dtype diagram = np.genfromtxt('diagram.csv', delimiter=',', names=('d', 'v')) print(diagram) print(diagram.shape) print(diagram.dtype) print(diagram[0]) print(diagram['d']) # recarray: diagram.d !ls import gzip with gzip.open('V404Cyg.txt.gz') as f: text = f.readlines() for row in text: # print(row) pass def convert_magn(b): if b.startswith(b'<'): return 999 return b v404 = np.genfromtxt('V404Cyg.txt.gz', delimiter='\t', usecols=(0, 1, 2), names=True, missing_values=b'', filling_values=0, converters={1: convert_magn}) v404[7:9] idx = v404['Magnitude'] != 999 plt.plot(v404['JD'][idx], v404['Magnitude'][idx], 'x') plt.ylim(*plt.ylim()[::-1]) import pandas as pd df = pd.read_csv('V404Cyg.txt.gz', sep='\t', low_memory=False) df df.JD df['JD'] df.columns df['Star Name'] df.loc[0] def convert_magn(s): if s.startswith('<'): s = s[1:] return float(s) df['m'] = df.Magnitude.map(convert_magn) df['is_upper_limit'] = df.Magnitude.map(lambda s: s.startswith('<')) df.is_upper_limit plt.plot(df.JD[~df.is_upper_limit], df.m[~df.is_upper_limit], 'x') plt.plot(df.JD[df.is_upper_limit], df.m[df.is_upper_limit], 'v') plt.ylim(*reversed(plt.ylim())) # ~2 # two = '0010' # '1101' # '1111' -1 a = np.arange(16).reshape(4, 4) a import sys np.savetxt(sys.stdout, a) # np.loadtxt np.save('data.npy', a) with open('data.npy', 'rb') as f: data = f.read() # print(data) row = data.splitlines()[1] print(row[8:16]) b = np.load('data.npy') b np.savez('data.npz', a) npz = np.load('data.npz') list(npz.items()) import pickle a = list(range(16)) dump = pickle.dumps(a) ?pickle.dumps b = pickle.loads(dump) b from astropy.io import ascii ascii.write(diagram, sys.stdout, Writer=ascii.Latex) ```
github_jupyter
``` import tensorflow as tf SENTENCES = ["machine learning engineers can build great data models", "machine learning is a great new tool", "machine learning gives value to your data", "machine learning and data is all you need" ] from collections import Counter import json import numpy as np class Vocabulary: def __init__(self, vocabulary, wordFrequencyFilePath): self.vocabulary = vocabulary self.BAG_OF_WORDS_FILE_FULL_PATH = wordFrequencyFilePath self.input_word_index = {} self.reverse_input_word_index = {} self.input_word_index["START"] = 1 self.input_word_index["UNKOWN"] = -1 self.MaxSentenceLength = None def PrepareVocabulary(self,reviews): self._prepare_Bag_of_Words_File(reviews) self._create_Vocab_Indexes() self.MaxSentenceLength = max([len(txt.split(" ")) for txt in reviews]) def Get_Top_Words(self, number_words = None): if number_words == None: number_words = self.vocabulary chars = json.loads(open(self.BAG_OF_WORDS_FILE_FULL_PATH).read()) counter = Counter(chars) most_popular_words = {key for key, _value in counter.most_common(number_words)} return most_popular_words def _prepare_Bag_of_Words_File(self,reviews): counter = Counter() for s in reviews: counter.update(s.split(" ")) with open(self.BAG_OF_WORDS_FILE_FULL_PATH, 'w') as output_file: output_file.write(json.dumps(counter)) def _create_Vocab_Indexes(self): INPUT_WORDS = self.Get_Top_Words(self.vocabulary) #word to int #self.input_word_index = dict( # [(word, i) for i, word in enumerate(INPUT_WORDS)]) for i, word in enumerate(INPUT_WORDS): self.input_word_index[word] = i #int to word #self.reverse_input_word_index = dict( # (i, word) for word, i in self.input_word_index.items()) for word, i in self.input_word_index.items(): self.reverse_input_word_index[i] = word #self.input_word_index = input_word_index #self.reverse_input_word_index = reverse_input_word_index #seralize.dump(config.DATA_FOLDER_PATH+"input_word_index.p",input_word_index) #seralize.dump(config.DATA_FOLDER_PATH+"reverse_input_word_index.p",reverse_input_word_index) def _word_to_One_Hot_Vector(self, word): vector = np.zeros(self.vocabulary) vector[vocab.input_word_index[word]] = 1 return vector def TransformSentencesToId(self, sentences): vectors = [] for r in sentences: words = r.split(" ") vector = np.zeros(len(words)) for t, word in enumerate(words): if word in self.input_word_index: vector[t] = self.input_word_index[word] else: pass #vector[t] = 2 #unk vectors.append(vector) return vectors def ReverseTransformSentencesToId(self, sentences): vectors = [] for r in sentences: words = r.split(" ") vector = np.zeros(len(words)) for t, word in enumerate(words): if word in self.input_word_index: vector[t] = self.input_word_index[word] else: pass #vector[t] = 2 #unk vectors.append(vector) return vectors def Get_SkipGram_Target_Words(self, sentences, WINDOW_SIZE = 5): SKIP_GRAM_INPUT_WORD_LIST = [] for sentence in sentences: sentence_tokenized = sentence.split(" ") for index, target_word in enumerate(sentence_tokenized): FROM_INDEX = max(index-WINDOW_SIZE,0) TO_INDEX = min(index+1+WINDOW_SIZE,len(sentence_tokenized)) for contextWord in sentence_tokenized[FROM_INDEX:TO_INDEX]: if contextWord != target_word: SKIP_GRAM_INPUT_WORD_LIST.append((target_word,contextWord)) return SKIP_GRAM_INPUT_WORD_LIST def Get_SkipGram_Target_Words_OneHotEncoded_XY(self, sentences, WINDOW_SIZE = 5): Skip_Gram_Target_Words = self.Get_SkipGram_Target_Words(sentences, WINDOW_SIZE) X,Y = [],[] for target_word, context_word in Skip_Gram_Target_Words: X.append(self._word_to_One_Hot_Vector(target_word)) Y.append(self._word_to_One_Hot_Vector(context_word)) return np.asarray(X), np.asarray(Y) VOCABULARY_SIZE = 20 vocab = Vocabulary(VOCABULARY_SIZE,"words.vocab") vocab.PrepareVocabulary(SENTENCES) vocab.Get_Top_Words(5) print("Vocabulary of {0} words".format(len(vocab.Get_Top_Words()))) SENTENCES[0] Skip_Gram_Target_Words = vocab.Get_SkipGram_Target_Words(SENTENCES, WINDOW_SIZE=2) print(Skip_Gram_Target_Words[0:5]) X_train, Y_train = vocab.Get_SkipGram_Target_Words_OneHotEncoded_XY(SENTENCES,2) print(X_train.shape) print(Y_train.shape) VOCABULARY_SIZE EMBEDDING_DIM = 5 # Inputs X = tf.placeholder("float", shape=[None, VOCABULARY_SIZE]) y = tf.placeholder("float", shape=[None, VOCABULARY_SIZE]) # Dictionary of Weights and Biases weights = { 'W1': tf.Variable(tf.random_normal([VOCABULARY_SIZE, EMBEDDING_DIM])), 'W2': tf.Variable(tf.random_normal([EMBEDDING_DIM, VOCABULARY_SIZE])), } biases = { 'b1': tf.Variable(tf.random_normal([EMBEDDING_DIM])), 'b2': tf.Variable(tf.random_normal([VOCABULARY_SIZE])), } # Model Forward Propagation step def forward_propagation(x): hidden_1 = tf.add(tf.matmul(x, weights['W1']), biases['b1']) out_layer = tf.add(tf.matmul(hidden_1, weights['W2']), biases['b2']) softmax_out = tf.nn.softmax(out_layer) return softmax_out #cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=yhat)) #optimizer = tf.train.GradientDescentOptimizer(learning_rate) yhat = forward_propagation(X) ypredict = tf.argmax(yhat, axis=1) # Backward propagation learning_rate = 0.02 cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=yhat)) optimizer = tf.train.GradientDescentOptimizer(learning_rate) #optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(cost) # Initializing the variables init = tf.global_variables_initializer() from datetime import datetime startTime = datetime.now() sess = tf.Session() #with tf.Session() as sess: sess.run(init) #writer.add_graph(sess.graph) #EPOCHS for epoch in range(500): #Stochasting Gradient Descent for i in range(len(X_train)): #cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y * tf.log(yhat), reduction_indices=[1])) summary = sess.run(train_op, feed_dict={X: X_train[i: i + 1], y: Y_train[i: i + 1]}) if epoch % 50 == 0: train_accuracy = np.mean(np.argmax(Y_train, axis=1) == sess.run(ypredict, feed_dict={X: X_train, y: Y_train})) current_cost_ = sess.run(cost, feed_dict={X: X_train, y: Y_train}) #cross_entropy_loss_val = sess.run(cross_entropy_loss, feed_dict={X: X_train, y: Y_train}) print("Epoch = {0}, train accuracy = {1}%, cost = {2}".format(epoch + 1, 100. * train_accuracy,current_cost_)) #print("Epoch = %d, train accuracy = %.2f%%, train accuracy = %.2f%%" % (epoch + 1, 100. * train_accuracy, cross_entropy_loss_val)) #sess.close() print("Time taken:", datetime.now() - startTime) #sess.close() ypredict= sess.run(ypredict, feed_dict={X: X_train, y: Y_train}) ypredict.shape vectors = sess.run(weights['W1'] + biases['b1']) vectors.shape print(vectors[vocab.input_word_index['machine']]) print(vectors[vocab.input_word_index['learning']]) ``` <h2>Plot Embedding</h2> ``` from sklearn.decomposition import PCA from matplotlib import pyplot as plt X = [] for word in vocab.Get_Top_Words(): X.append(vectors[vocab.input_word_index[word]]) X = np.asarray(X) print(X.shape) pca = PCA(n_components=2) result = pca.fit_transform(X) # create a scatter plot of the projection plt.figure(figsize=(20,10)) plt.scatter(result[:, 0], result[:, 1]) words = vocab.Get_Top_Words() for i, word in enumerate(words): plt.annotate(word, xy=(result[i, 0], result[i, 1])) plt.show() sess.close() ```
github_jupyter
<a href="https://colab.research.google.com/github/sayakpaul/TF-2.0-Hacks/blob/master/TF_2_0_and_cloud_functions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> The purpose of this notebook is to show how easy it is to serve a machine learning model via [Cloud Functions](https://console.cloud.google.com/functions/) on the Google Cloud Platform. It is absolutely possible to do this via Colab. In this notebook, we will be - building a simple neural network model to classify the apparels as listed in the FashionMNIST dataset - serializing the model weights in a way that is compatible with the Cloud Functions' ecosystem - using the `gcloud` CLI to deploy our model on GCP via Cloud Functions So, let's get started. ``` # install `tensorflow` 2.0 latest pip install tensorflow==2.0.0b1 # import tensorflow and verify the version import tensorflow as tf print(tf.__version__) # all the imports we care about in this notebook import matplotlib.pyplot as plt from tensorflow.keras.layers import * from tensorflow.keras.models import * # load and prepare our data fashion_mnist = mnist = tf.keras.datasets.fashion_mnist (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # the humble model model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # kickstart the training model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=5, batch_size=128, verbose=1) # save the weights model.save_weights('fashion_mnist_weights') ``` This will give birth to two files: - fashion_mnist_weights.data-00000-of-00001 - fashion_mnist_weights.index ``` # sample prediction class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] test_img = plt.imread('test.png') prob = model.predict(test_img.reshape(1, 28, 28)) print(class_names[prob.argmax()]) ``` The test image looks like the following, by the way: ![](https://storage.googleapis.com/gweb-cloudblog-publish/images/Cloud_Storage_test_image.max-100x100.png) Once the model weights are saved we need to create a `.py` file named `main.py` as required by Cloud Functions. The `main.py` file should look like so: ```python import numpy import tensorflow as tf from google.cloud import storage from tensorflow.keras.layers import * from tensorflow.keras.models import * from PIL import Image # we keep model as global variable so we don't have to reload it # in case of warm invocations model = None def get_me_the_model(): model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) return model def download_blob(bucket_name, source_blob_name, destination_file_name): """downloads a blob from the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(source_blob_name) blob.download_to_filename(destination_file_name) print('Blob {} downloaded to {}.'.format( source_blob_name, destination_file_name)) def handler(request): global model class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # model load which only happens during cold invocations if model is None: download_blob('<your_gs_buckets_name>', 'tensorflow/fashion_mnist_weights.index', '/tmp/fashion_mnist_weights.index') download_blob('<your_gs_buckets_name>', 'tensorflow/fashion_mnist_weights.data-00000-of-00001', '/tmp/fashion_mnist_weights.data-00000-of-00001') model = get_me_the_model() model.load_weights('/tmp/fashion_mnist_weights') download_blob('<your_gs_buckets_name>', 'tensorflow/test.png', '/tmp/test.png') image = numpy.array(Image.open('/tmp/test.png')) input_np = (numpy.array(Image.open('/tmp/test.png'))/255) input_np = input_np.reshape(1, 28, 28) predictions = model.predict(input_np) print(predictions) print("Image is "+class_names[numpy.argmax(predictions)]) return class_names[numpy.argmax(predictions)] ``` **Note** that in place of `<your_gs_buckets_name>` enter the bucket's name (without `gs://`) in which you have stored the model weights. Also note that, I have stored them in a folder named **tensorflow**. When the model is deployed as a cloud function, `main.py`will download the model from the storage bucket and will store it into **tmp** folder. Now to get started with the deployment process, first authenticate yourself. ``` !gcloud auth login ``` Set the GCP project (preferably billing enabled). ``` !gcloud config set project fast-ai-exploration ``` And deploy! ``` !gcloud functions deploy handler --runtime python37 --trigger-http --memory 2048 !gcloud functions call handler ``` **Notice** that the function `handler()` in `main.py` internally calls the test image, so you don't need to worry about it. **Reference**: - https://cloud.google.com/blog/products/ai-machine-learning/how-to-serve-deep-learning-models-using-tensorflow-2-0-with-cloud-functions
github_jupyter
# VacationPy ---- #### Note * Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing. * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import gmaps import os import gmaps.datasets import json # Import API key from api_keys import g_key ``` ### Store Part I results into DataFrame * Load the csv exported in Part I to a DataFrame ``` df=('../output_data/cities.csv') data=pd.read_csv(df) data data.count() data.dropna(inplace = True) del data['Unnamed: 0'] data data.count() ``` ### Humidity Heatmap * Configure gmaps. * Use the Lat and Lng as locations and Humidity as the weight. * Add Heatmap layer to map. ``` locations = data[['Latitude', 'Longitude']] humid = data['Humidity'] figure_layout = { 'width': '900px', 'height': '600px', 'border': '1px solid black', 'padding': '1px', 'margin': '0 auto 0 auto' } fig = gmaps.figure(layout=figure_layout,zoom_level=2,center=(15,25)) heat_layer=gmaps.heatmap_layer(locations, weights=humid, dissipating=False, max_intensity=100, point_radius=1.5) fig.add_layer(heat_layer) # fig # , dissipating = False, max_intensity = 75, point_radius = 1 ``` ### Create new DataFrame fitting weather criteria * Narrow down the cities to fit weather conditions. * Drop any rows will null values. ``` tempa=data.loc[(data['Max_temp']>=65) & (data['Max_temp']<=90)] tempa humid=tempa.loc[(tempa['Humidity']>=5) & (tempa['Humidity']<=60)] humid windspeed=humid.loc[(humid['Wind_speed']>=5) & (humid['Wind_speed']<=30)] windspeed clouds_df=windspeed.loc[(windspeed['Cloudiness']>=5) & (windspeed['Cloudiness']<=80)] # clouds_df # temp= data[data['Max_temp'] >=65 & data['Max_temp']<=90] ``` ### Hotel Map * Store into variable named `hotel_df`. * Add a "Hotel Name" column to the DataFrame. * Set parameters to search for hotels with 5000 meters. * Hit the Google Places API for each city's coordinates. * Store the first Hotel result into the DataFrame. * Plot markers on top of the heatmap. ``` # hotel_df=clouds_df # hotel_df=clouds_df.loc[:,:] # hotel_df # hotel_df['Hotel Name']="" # hotel_df # params= {"key": g_key, # "radius": 5000, # "types":"hotel", # } # for index, row in hotel_df.iterrows(): # city=row['City'] # lat=row["Latitude"] # lng=row['Longitude'] # params["location"]=f"{lat},{lng}" # base_url= "https://maps.googleapis.com/maps/api/place/nearbysearch/json" # name_address= requests.get(base_url,params=params) # name_address=name_address.json() # print(json.dumps(name_address,indent=4, sort_keys=True)) # try: # hotel_df.loc[index,"Hotel Name"]=name_address['results'][1]["name"] # # clouds_df.loc[index,"Hotel Rating"]=name_address['results']["rating"] # except(KeyError, IndexError): # print("Missing field/results,,,skipping") # time.sleep(1) # hotel_df # hotel_name=hotel_df['Hotel Name'] # hotel_name # query_url = f'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=hotel%20{city}&inputtype=textquery&&key={gkey}' # NOTE: Do not change any of the code in this cell # Using the template add the hotel marks to the heatmap info_box_template = """ <dl> <dt>Name</dt><dd>{Hotel Name}</dd> <dt>City</dt><dd>{City}</dd> <dt>Country</dt><dd>{Country}</dd> </dl> """ # Store the DataFrame Row # NOTE: be sure to update with your DataFrame name hotel_info = [info_box_template.format(**row) for index, row in hotel_df.iterrows()] locations = hotel_df[["Latitude", "Longitude"]] figure_layout = { 'width': '900px', 'height': '600px', 'border': '1px solid black', 'padding': '1px', 'margin': '0 auto 0 auto' } fig = gmaps.figure() hotel_layer = gmaps.marker_layer(locations, info_box_content=hotel_info) # Display figure fig.add_layer(heat_layer) fig.add_layer(hotel_layer) # fig ```
github_jupyter
# Probabilistic PCA Probabilistic principal components analysis (PCA) is a dimensionality reduction technique that analyzes data via a lower dimensional latent space (Tipping & Bishop, 1999). It is often used when there are missing values in the data or for multidimensional scaling. We demonstrate with an example in Edward. A webpage version is available at http://edwardlib.org/tutorials/probabilistic-pca. ``` from __future__ import absolute_import from __future__ import division from __future__ import print_function import edward as ed import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from edward.models import Normal plt.style.use('ggplot') ``` ## Data We use simulated data. We'll talk about the individual variables and what they stand for in the next section. For this example, each data point is 2-dimensional, $\mathbf{x}_n\in\mathbb{R}^2$. ``` def build_toy_dataset(N, D, K, sigma=1): x_train = np.zeros((D, N)) w = np.random.normal(0.0, 2.0, size=(D, K)) z = np.random.normal(0.0, 1.0, size=(K, N)) mean = np.dot(w, z) for d in range(D): for n in range(N): x_train[d, n] = np.random.normal(mean[d, n], sigma) print("True principal axes:") print(w) return x_train ed.set_seed(142) N = 5000 # number of data points D = 2 # data dimensionality K = 1 # latent dimensionality x_train = build_toy_dataset(N, D, K) ``` We visualize the data set. ``` plt.scatter(x_train[0, :], x_train[1, :], color='blue', alpha=0.1) plt.axis([-10, 10, -10, 10]) plt.title("Simulated data set") plt.show() ``` ## Model Consider a data set $\mathbf{X} = \{\mathbf{x}_n\}$ of $N$ data points, where each data point is $D$-dimensional, $\mathbf{x}_n \in \mathbb{R}^D$. We aim to represent each $\mathbf{x}_n$ under a latent variable $\mathbf{z}_n \in \mathbb{R}^K$ with lower dimension, $K < D$. The set of principal axes $\mathbf{W}$ relates the latent variables to the data. Specifically, we assume that each latent variable is normally distributed, \begin{equation*} \mathbf{z}_n \sim N(\mathbf{0}, \mathbf{I}). \end{equation*} The corresponding data point is generated via a projection, \begin{equation*} \mathbf{x}_n \mid \mathbf{z}_n \sim N(\mathbf{W}\mathbf{z}_n, \sigma^2\mathbf{I}), \end{equation*} where the matrix $\mathbf{W}\in\mathbb{R}^{D\times K}$ are known as the principal axes. In probabilistic PCA, we are typically interested in estimating the principal axes $\mathbf{W}$ and the noise term $\sigma^2$. Probabilistic PCA generalizes classical PCA. Marginalizing out the the latent variable, the distribution of each data point is \begin{equation*} \mathbf{x}_n \sim N(\mathbf{0}, \mathbf{W}\mathbf{W}^Y + \sigma^2\mathbf{I}). \end{equation*} Classical PCA is the specific case of probabilistic PCA when the covariance of the noise becomes infinitesimally small, $\sigma^2 \to 0$. We set up our model below. In our analysis, we fix $\sigma=2.0$, and instead of point estimating $\mathbf{W}$ as a model parameter, we place a prior over it in order to infer a distribution over principal axes. ``` w = Normal(loc=tf.zeros([D, K]), scale=2.0 * tf.ones([D, K])) z = Normal(loc=tf.zeros([N, K]), scale=tf.ones([N, K])) x = Normal(loc=tf.matmul(w, z, transpose_b=True), scale=tf.ones([D, N])) ``` ## Inference The posterior distribution over the principal axes $\mathbf{W}$ cannot be analytically determined. Below, we set up our inference variables and then run a chosen algorithm to infer $\mathbf{W}$. Below we use variational inference to minimize the $\text{KL}(q\|p)$ divergence measure. ``` qw = Normal(loc=tf.get_variable("qw/loc", [D, K]), scale=tf.nn.softplus(tf.get_variable("qw/scale", [D, K]))) qz = Normal(loc=tf.get_variable("qz/loc", [N, K]), scale=tf.nn.softplus(tf.get_variable("qz/scale", [N, K]))) inference = ed.KLqp({w: qw, z: qz}, data={x: x_train}) inference.run(n_iter=500, n_print=100, n_samples=10) ``` ## Criticism To check our inferences, we first inspect the model's learned principal axes. ``` sess = ed.get_session() print("Inferred principal axes:") print(sess.run(qw.mean())) ``` The model has recovered the true principal axes up to finite data and also up to identifiability (there's a symmetry in the parameterization). Another way to criticize the model is to visualize the observed data against data generated from our fitted model. The blue dots represent the original data, while the red is the inferred. ``` # Build and then generate data from the posterior predictive distribution. x_post = ed.copy(x, {w: qw, z: qz}) x_gen = sess.run(x_post) plt.scatter(x_gen[0, :], x_gen[1, :], color='red', alpha=0.1) plt.axis([-10, 10, -10, 10]) plt.title("Data generated from model") plt.show() ``` The generated data looks close to the true data. ## Acknowledgements We thank Mayank Agrawal for writing the initial version of this tutorial.
github_jupyter
# [TPV3] Plotting reference from SEM2DPACK and $se2dr$'s receiverCP file by JN Hayek (Created on 06.08.2020) ## Library import ``` import os, sys, math, time from glob import glob from matplotlib import pyplot as plt import numpy as np import pandas as pd sys.path.insert(0,"/home/nico/Documents/TEAR/Codes_TEAR/PythonCodes/LibFolder") from Lib_GeneralFunctions import * from Lib_GeneralSignalProcNAnalysis import * from Lib_ProfilePlotting import * from Lib_ProfileProcessing import * #=================== Plotting style =================== plt.style.use('seaborn-whitegrid') from matplotlib import cm from matplotlib.colors import ListedColormap from matplotlib.lines import Line2D from matplotlib.gridspec import GridSpec #definition of colormap from palettable.scientific.sequential import LaJolla_20 cmap = LaJolla_20.mpl_colormap # Timestamp variable start_time = time.time() # Save into a class the class TPV3reference: def __init__(self, filename, coordinates, RefSource="SEM2DPACK"): line = pd.read_csv(filename.format("slip"), header=None) self.Time = line[0] self.Slip = line[1] line = pd.read_csv(filename.format("sr"), header=None) self.SlipRate = line[1] self.Coord = coordinates #Only used for labels and self.RefSource = RefSource #end __init__ # Default object printing information def __repr__(self): return "The TPV3reference object was generated from: {} and the receiver is located at {}".format(self.RefSource, self.Coord) #end __repr__ def __str__(self): return "The TPV3reference object was generated from: {} and the receiver is located at {}".format(self.RefSource, self.Coord) #end __str__ def PlotReference(self, ax, SlipSlipRate, filtering=True, **kwargs): if SlipSlipRate=="Slip": if(filtering): ax.plot(self.Time, Butterworth(self.Slip, **kwargs), label = "", c = "k", ls = "--", zorder=1) else: ax.plot(self.Time, self.Slip, label = "", c = "k", ls = "--", zorder=1) elif SlipSlipRate=="SlipRate": if(filtering): ax.plot(self.Time, Butterworth(self.SlipRate, **kwargs), label = "", c = "k", ls = "--", zorder=1) else: ax.plot(self.Time, self.SlipRate, label = "", c = "k", ls = "--", zorder=1) return ax path = "/home/nico/Documents/TEAR/Codes_TEAR/ProfilePicking/[TPV3]Results/" # Reference saved into a list of objects RefList = [TPV3reference(path + "Reference/sem2dpack/sem2d-{}-2.txt", "4km"), TPV3reference(path + "Reference/sem2dpack/sem2d-{}-3.txt", "6km"), TPV3reference(path + "Reference/sem2dpack/sem2d-{}-4.txt", "8km"), ] RefList = [TPV3reference(path + "Reference/sem2dpack/[TPV3]sem2dpack-{}-receiver-4.0e+03.txt", "4km"), TPV3reference(path + "Reference/sem2dpack/[TPV3]sem2dpack-{}-receiver-6.0e+03.txt", "6km"), TPV3reference(path + "Reference/sem2dpack/[TPV3]sem2dpack-{}-receiver-8.0e+03.txt", "8km"), ] ``` # Plotting functions for the receiver file from se2dr ``` def PlotReceiverFile(ax, ReceiverFile, ColIDX, OrderPeriodicity=8, NumReceivers=3, filtering=True, **kwargs): ylabeldict={1:"Slip (m)", 2:"Slip Rate (m)", 3:"$\mu$"} if(filtering): SamplingFrequency = 1./(ReceiverFile[0][1]-ReceiverFile[0][0]) [ax.plot(ReceiverFile[0], Butterworth(ReceiverFile[ColIDX+OrderPeriodicity*i],SamplingFrequency = SamplingFrequency, **kwargs), zorder=2) for i in range(NumReceivers)] else: [ax.plot(ReceiverFile[0], ReceiverFile[ColIDX+OrderPeriodicity*i], zorder=2) for i in range(NumReceivers)] ax.set_ylabel(ylabeldict[ColIDX]) ax.set_xlabel("time (s)") return ax def format_axes(fig): for i, ax in enumerate(fig.axes): ax.set_xlim(0,7) ax.set_ylim(0,7) Lines = fig.axes[-1].get_lines()[-4:] legend2 = fig.axes[-1].legend(Lines, ['Reference', '4km', '6km', '8km'], loc=1) fig.axes[-1].add_artist(legend2) def GenericFigAxis(): fig = plt.figure(constrained_layout=True, figsize=[12,4]) gs = GridSpec(1, 2, figure=fig) ax1 = fig.add_subplot(gs[0, 0]) ax2 = fig.add_subplot(gs[0, 1]) return fig, [ax1, ax2] ``` ### Function for plotting 2 sets of graphs (filtered/unfiltered) from a ReceiverCP file ``` def PlotReceiverCP_wPandas(ReceiverFile, ParamsText, RefList, **kwargs): sliporsliprateDict={"Slip":1, "SlipRate": 2} #================= Plotting Filtered Set ===================# fig, axis = GenericFigAxis() PlotType = "Slip" [item.PlotReference(axis[0], PlotType, filtering=True, **kwargs) for item in RefList] #Reference PlotReceiverFile(axis[0], ReceiverFile, sliporsliprateDict[PlotType], filtering = True, **kwargs) PlotType = "SlipRate" [item.PlotReference(axis[1], PlotType, filtering=True, **kwargs) for item in RefList] #Reference PlotReceiverFile(axis[1], ReceiverFile, sliporsliprateDict[PlotType], filtering = True, **kwargs) format_axes(fig) if "CutoffFrequency" in kwargs: fig.suptitle("[TPV3] Filtered results ($f_c=${}$Hz$) {}".format(kwargs.get("CutoffFrequency"),ParamsText)) else: fig.suptitle("[TPV3] Filtered results ($f_c=7Hz$) {}".format(ParamsText)) #================= Plotting Non-Filtered Set ===================# fig, axis = GenericFigAxis() PlotType = "Slip" [item.PlotReference(axis[0], PlotType, filtering=False) for item in RefList] #Reference PlotReceiverFile(axis[0], ReceiverFile, sliporsliprateDict[PlotType], filtering = False) PlotType = "SlipRate" [item.PlotReference(axis[1], PlotType, filtering=False) for item in RefList] #Reference PlotReceiverFile(axis[1], ReceiverFile, sliporsliprateDict[PlotType], filtering = False) format_axes(fig) fig.suptitle("[TPV3] Unfiltered results {}".format(ParamsText)) ``` ### TPV3 Plots (P1, P2 - No blending function added) ``` ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p1.dat", comment = '#',header = None, delimiter = " ") ParamsText = "\np = 1, dx=25m, $\delta=25.025$m" PlotReceiverCP_wPandas(ReceiverFile, ParamsText, RefList) ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p2.dat", comment = '#',header = None, delimiter = " ") ParamsText = "\np = 2, dx=25m, $\delta=25.025$m" PlotReceiverCP_wPandas(ReceiverFile, ParamsText, RefList) ``` # Error Analysis ## Get the difference in timing and max value of the peak in the peak slip rate There must be a function that uses a pair [time, PeakValue] generated from one of the reference files to substract from the pair [time, PeakValue] generated from a specific station. - Remember that all stations reside in a file, in different columns for the output of se2dr, while all stations are separated in the output of SEM2DPACK - Consider cases filtered vs non-filtered - Timing vs Difference in magnitue of the peak slip rate - The data from different stations are tied with a line. (Consider the case where we only tie by a line equal station, different p refinement value) For the Last case, it would be good to build a Pandas DataFrame, Where the value of p, h, location of the station, Timing Difference, Slip rate Magnitude difference are saved ``` def GetMaxPeakValueNTiming_FromLists(TimeList,MagnList): idx = MagnList.index(max(MagnList)) PeakValue = MagnList[idx] PeakTiming = TimeList[idx] return [PeakTiming,PeakValue] def GetDictDataReceiver(p, dx, ReceiverLoc, RefPair,ReceiverPair): ToAppendDict={"p": p, "dx": dx, "ReceiverLoc": ReceiverLoc, "TimingDifference": ReceiverPair[0]-RefPair[0], "SlipRateDifference":ReceiverPair[1]-RefPair[1] } return ToAppendDict def PlotnScatter3Lists(axis,x,y,z): axis.scatter(x, y) axis.plot(x, y) for i, txt in enumerate(z): axis.annotate(txt, (x[i], y[i])) ``` ### Non-filtered extraction of differences ``` Data = pd.DataFrame(columns=["p","dx", "ReceiverLoc", "TimingDifference", "SlipRateDifference"]) for NumReceiver in range(3): # Get the reference Pair RefItem = RefList[NumReceiver]; print(RefItem) RefPair = GetMaxPeakValueNTiming_FromLists(RefItem.Time.tolist(), RefItem.SlipRate.tolist()) # Get the receiver Pair for p = 1 ===================================================== ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p1.dat", comment = '#',header = None, delimiter = " ") ColIDX=2; OrderPeriodicity = 8 #; NumReceiver= 0; Order in the file ReceiverCP: numReceiver 0 = 4km, 1 = 6km, 2 = 8km ReceiverPair = GetMaxPeakValueNTiming_FromLists(ReceiverFile[0].tolist(), ReceiverFile[ColIDX+OrderPeriodicity*NumReceiver].tolist()) ToAppendDict = GetDictDataReceiver(1, "25m", RefItem.Coord, RefPair, ReceiverPair) Data = Data.append(ToAppendDict, ignore_index=True) # Get the receiver Pair for p = 2 ===================================================== ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p2.dat", comment = '#',header = None, delimiter = " ") ColIDX=2; OrderPeriodicity = 8 #; NumReceiver= 0; Order in the file ReceiverCP: numReceiver 0 = 4km, 1 = 6km, 2 = 8km ReceiverPair = GetMaxPeakValueNTiming_FromLists(ReceiverFile[0].tolist(), ReceiverFile[ColIDX+OrderPeriodicity*NumReceiver].tolist()) ToAppendDict = GetDictDataReceiver(2, "25m", RefItem.Coord, RefPair, ReceiverPair) Data = Data.append(ToAppendDict, ignore_index=True) Data p1Data = Data[Data.p == 1] p2Data = Data[Data.p == 2] fig,axis=GenericFigAxis() PlotnScatter3Lists(axis[0], p1Data.TimingDifference.tolist(), p1Data.SlipRateDifference.tolist(), p1Data.ReceiverLoc.tolist()) PlotnScatter3Lists(axis[0], p2Data.TimingDifference.tolist(), p2Data.SlipRateDifference.tolist(), p2Data.ReceiverLoc.tolist()) rec1Data = Data[Data.ReceiverLoc == "4km"] rec2Data = Data[Data.ReceiverLoc == "6km"] rec3Data = Data[Data.ReceiverLoc == "8km"] PlotnScatter3Lists(axis[1], rec1Data.TimingDifference.tolist(), rec1Data.SlipRateDifference.tolist(), rec1Data.p.tolist()) PlotnScatter3Lists(axis[1], rec2Data.TimingDifference.tolist(), rec2Data.SlipRateDifference.tolist(), rec2Data.p.tolist()) PlotnScatter3Lists(axis[1], rec3Data.TimingDifference.tolist(), rec3Data.SlipRateDifference.tolist(), rec3Data.p.tolist()) #========================================================= # Lines Formatting axis 0 Lines = axis[0].get_lines() legend2 = axis[0].legend(Lines, ['p = 1', 'p = 2']) axis[0].add_artist(legend2) # Lines Formatting axis 1 Lines = axis[1].get_lines() legend2 = axis[1].legend(Lines, ['4 km', '6 km', '8 km']) axis[1].add_artist(legend2) for ax in axis: ax.set_xlabel("Timing Difference (s)") ax.set_ylabel("Peak slip rate Difference (m/s)") fig.suptitle("Timing and peak slip rate difference wrt. SEM2DPACK reference \n non-filtered") ``` ### Filtered extraction of differences ``` Data = pd.DataFrame(columns=["p","dx", "ReceiverLoc", "TimingDifference", "SlipRateDifference"]) CutoffFreq=7 for NumReceiver in range(3): # Get the reference Pair RefItem = RefList[NumReceiver]; print(RefItem) RefPair = GetMaxPeakValueNTiming_FromLists(RefItem.Time.tolist(), Butterworth(RefItem.SlipRate.tolist(), CutoffFrequency = CutoffFreq) ) # Get the receiver Pair for p = 1 ===================================================== ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p1.dat", comment = '#',header = None, delimiter = " ") ColIDX=2; OrderPeriodicity = 8 #; NumReceiver= 0; Order in the file ReceiverCP: numReceiver 0 = 4km, 1 = 6km, 2 = 8km ReceiverPair = GetMaxPeakValueNTiming_FromLists(ReceiverFile[0].tolist(), Butterworth(ReceiverFile[ColIDX+OrderPeriodicity*NumReceiver].tolist(), SamplingFrequency = 1./(ReceiverFile[0][1]-ReceiverFile[0][0]), CutoffFrequency = CutoffFreq) ) ToAppendDict = GetDictDataReceiver(1, "25m", RefItem.Coord, RefPair, ReceiverPair) Data = Data.append(ToAppendDict, ignore_index=True) # Get the receiver Pair for p = 2 ===================================================== ReceiverFile = pd.read_csv(path+"20200807/receiverCP-dr-2400x2400-p2.dat", comment = '#',header = None, delimiter = " ") ColIDX=2; OrderPeriodicity = 8 #; NumReceiver= 0; Order in the file ReceiverCP: numReceiver 0 = 4km, 1 = 6km, 2 = 8km ReceiverPair = GetMaxPeakValueNTiming_FromLists(ReceiverFile[0].tolist(), Butterworth(ReceiverFile[ColIDX+OrderPeriodicity*NumReceiver].tolist(), SamplingFrequency = 1./(ReceiverFile[0][1]-ReceiverFile[0][0]), CutoffFrequency = CutoffFreq) ) ToAppendDict = GetDictDataReceiver(2, "25m", RefItem.Coord, RefPair, ReceiverPair) Data = Data.append(ToAppendDict, ignore_index=True) p1Data = Data[Data.p == 1] p2Data = Data[Data.p == 2] fig,axis=GenericFigAxis() PlotnScatter3Lists(axis[0], p1Data.TimingDifference.tolist(), p1Data.SlipRateDifference.tolist(), p1Data.ReceiverLoc.tolist()) PlotnScatter3Lists(axis[0], p2Data.TimingDifference.tolist(), p2Data.SlipRateDifference.tolist(), p2Data.ReceiverLoc.tolist()) rec1Data = Data[Data.ReceiverLoc == "4km"] rec2Data = Data[Data.ReceiverLoc == "6km"] rec3Data = Data[Data.ReceiverLoc == "8km"] PlotnScatter3Lists(axis[1], rec1Data.TimingDifference.tolist(), rec1Data.SlipRateDifference.tolist(), rec1Data.p.tolist()) PlotnScatter3Lists(axis[1], rec2Data.TimingDifference.tolist(), rec2Data.SlipRateDifference.tolist(), rec2Data.p.tolist()) PlotnScatter3Lists(axis[1], rec3Data.TimingDifference.tolist(), rec3Data.SlipRateDifference.tolist(), rec3Data.p.tolist()) #========================================================= # Lines Formatting axis 0 Lines = axis[0].get_lines() legend2 = axis[0].legend(Lines, ['p = 1', 'p = 2']) axis[0].add_artist(legend2) # Lines Formatting axis 1 Lines = axis[1].get_lines() legend2 = axis[1].legend(Lines, ['4 km', '6 km', '8 km']) axis[1].add_artist(legend2) for ax in axis: ax.set_xlabel("Timing Difference (s)") ax.set_ylabel("Peak slip rate Difference (m/s)") fig.suptitle("Timing and peak slip rate difference wrt. SEM2DPACK reference \n low-pass Butterworth filter ($f_c=${}$Hz$)".format(CutoffFreq)) ```
github_jupyter
##### Copyright 2018 The TF-Agents Authors. ### Get Started <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/agents/blob/master/tf_agents/colabs/2_environments_tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/agents/blob/master/tf_agents/colabs/2_environments_tutorial.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> ``` # Note: If you haven't installed tf-agents or gym yet, run: !pip install tf-agents-nightly !pip install tf-nightly !pip install 'gym==0.10.11' ``` ### Imports ``` from __future__ import absolute_import from __future__ import division from __future__ import print_function import abc import tensorflow as tf import numpy as np from tf_agents.environments import py_environment from tf_agents.environments import tf_environment from tf_agents.environments import tf_py_environment from tf_agents.environments import utils from tf_agents.specs import array_spec from tf_agents.environments import wrappers from tf_agents.environments import suite_gym from tf_agents.trajectories import time_step as ts tf.compat.v1.enable_v2_behavior() ``` # Introduction The goal of Reinforcement Learning (RL) is to design agents that learn by interacting with an environment. In the standard RL setting, the agent receives an observation at every time step and chooses an action. The action is applied to the environment and the environment returns a reward and and a new observation. The agent trains a policy to choose actions to maximize the sum of rewards, also known as return. In TF-Agents, environments can be implemented either in Python or TensorFlow. Python environments are usually easier to implement, understand or debug, but TensorFlow environments are more efficient and allow natural parallelization. The most common workflow is to implement an environment in Python and use one of our wrappers to automatically convert it into TensorFlow. Let us look at Python environments first. TensorFlow environments follow a very similar API. # Python Environments Python environments have a `step(action) -> next_time_step` method that applies an action to the environment, and returns the following information about the next step: 1. `observation`: This is the part of the environment state that the agent can observe to choose its actions at the next step. 2. `reward`: The agent is learning to maximize the sum of these rewards across multiple steps. 3. `step_type`: Interactions with the environment are usually part of a sequence/episode. e.g. multiple moves in a game of chess. step_type can be either `FIRST`, `MID` or `LAST` to indicate whether this time step is the first, intermediate or last step in a sequence. 4. `discount`: This is a float representing how much to weight the reward at the next time step relative to the reward at the current time step. These are grouped into a named tuple `TimeStep(step_type, reward, discount, observation)`. The interface that all python environments must implement is in `environments/py_environment.PyEnvironment`. The main methods are: ``` class PyEnvironment(object): def reset(self): """Return initial_time_step.""" self._current_time_step = self._reset() return self._current_time_step def step(self, action): """Apply action and return new time_step.""" if self._current_time_step is None: return self.reset() self._current_time_step = self._step(action) return self._current_time_step def current_time_step(self): return self._current_time_step def time_step_spec(self): """Return time_step_spec.""" @abc.abstractmethod def observation_spec(self): """Return observation_spec.""" @abc.abstractmethod def action_spec(self): """Return action_spec.""" @abc.abstractmethod def _reset(self): """Return initial_time_step.""" @abc.abstractmethod def _step(self, action): """Apply action and return new time_step.""" self._current_time_step = self._step(action) return self._current_time_step ``` In addition to the `step()` method, environments also provide a `reset()` method that starts a new sequence and provides an initial `TimeStep`. It is not necessary to call the `reset` method explicitly. We assume that environments reset automatically, either when they get to the end of an episode or when step() is called the first time. Note that subclasses do not implement `step()` or `reset()` directly. They instead override the `_step()` and `_reset()` methods. The time steps returned from these methods will be cached and exposed through `current_time_step()`. The `observation_spec` and the `action_spec` methods return a nest of `(Bounded)ArraySpecs` that describe the name, shape, datatype and ranges of the observations and actions respectively. In TF-Agents we repeatedly refer to nests which are defined as any tree like structure composed of lists, tuples, named-tuples, or dictionaries. These can be arbitrarily composed to maintain structure of observations and actions. We have found this to be very useful for more complex environments where you have many observations and actions. ## Using Standard Environments TF Agents has built-in wrappers for many standard environments like the OpenAI Gym, DeepMind-control and Atari, so that they follow our `py_environment.PyEnvironment` interface. These wrapped evironments can be easily loaded using our environment suites. Let's load the CartPole environment from the OpenAI gym and look at the action and time_step_spec. ``` environment = suite_gym.load('CartPole-v0') print('action_spec:', environment.action_spec()) print('time_step_spec.observation:', environment.time_step_spec().observation) print('time_step_spec.step_type:', environment.time_step_spec().step_type) print('time_step_spec.discount:', environment.time_step_spec().discount) print('time_step_spec.reward:', environment.time_step_spec().reward) ``` So we see that the environment expects actions of type `int64` in [0, 1] and returns `TimeSteps` where the observations are a `float32` vector of length 4 and discount factor is a `float32` in [0.0, 1.0]. Now, let's try to take a fixed action `(1,)` for a whole episode. ``` action = 1 time_step = environment.reset() print(time_step) while not time_step.is_last(): time_step = environment.step(action) print(time_step) ``` ## Creating your own Python Environment For many clients, a common use case is to apply one of the standard agents (see agents/) in TF-Agents to their problem. To do this, they have to frame their problem as an environment. So let us look at how to implement an environment in Python. Let's say we want to train an agent to play the following (Black Jack inspired) card game: 1. The game is played using an infinite deck of cards numbered 1...10. 2. At every turn the agent can do 2 things: get a new random card, or stop the current round. 3. The goal is to get the sum of your cards as close to 21 as possible at the end of the round, without going over. An environment that represents the game could look like this: 1. Actions: We have 2 actions. Action 0: get a new card, and Action 1: terminate the current round. 2. Observations: Sum of the cards in the current round. 3. Reward: The objective is to get as close to 21 as possible without going over, so we can achieve this using the following reward at the end of the round: sum_of_cards - 21 if sum_of_cards <= 21, else -21 ``` class CardGameEnv(py_environment.PyEnvironment): def __init__(self): self._action_spec = array_spec.BoundedArraySpec( shape=(), dtype=np.int32, minimum=0, maximum=1, name='action') self._observation_spec = array_spec.BoundedArraySpec( shape=(1,), dtype=np.int32, minimum=0, name='observation') self._state = 0 self._episode_ended = False def action_spec(self): return self._action_spec def observation_spec(self): return self._observation_spec def _reset(self): self._state = 0 self._episode_ended = False return ts.restart(np.array([self._state], dtype=np.int32)) def _step(self, action): if self._episode_ended: # The last action ended the episode. Ignore the current action and start # a new episode. return self.reset() # Make sure episodes don't go on forever. if action == 1: self._episode_ended = True elif action == 0: new_card = np.random.randint(1, 11) self._state += new_card else: raise ValueError('`action` should be 0 or 1.') if self._episode_ended or self._state >= 21: reward = self._state - 21 if self._state <= 21 else -21 return ts.termination(np.array([self._state], dtype=np.int32), reward) else: return ts.transition( np.array([self._state], dtype=np.int32), reward=0.0, discount=1.0) ``` Let's make sure we did everything correctly defining the above environment. When creating your own environment you must make sure the observations and time_steps generated follow the correct shapes and types as defined in your specs. These are used to generate the TensorFlow graph and as such can create hard to debug problems if we get them wrong. To validate our environment we will use a random policy to generate actions and we will iterate over 5 episodes to make sure things are working as intended. An error is raised if we receive a time_step that does not follow the environment specs. ``` environment = CardGameEnv() utils.validate_py_environment(environment, episodes=5) ``` Now that we know the environment is working as intended, let's run this environment using a fixed policy: ask for 3 cards and then end the round. ``` get_new_card_action = 0 end_round_action = 1 environment = CardGameEnv() time_step = environment.reset() print(time_step) cumulative_reward = time_step.reward for _ in range(3): time_step = environment.step(get_new_card_action) print(time_step) cumulative_reward += time_step.reward time_step = environment.step(end_round_action) print(time_step) cumulative_reward += time_step.reward print('Final Reward = ', cumulative_reward) ``` ## Environment Wrappers An environment wrapper takes a python environment and returns a modified version of the environment. Both the original environment and the modified environment are instances of `py_environment.PyEnvironment`, and multiple wrappers can be chained together. Some common wrappers can be found in `environments/wrappers.py`. For example: 1. `ActionDiscretizeWrapper`: Converts a continuous action space to a discrete action space. 2. `RunStats`: Captures run statistics of the environment such as number of steps taken, number of episodes completed etc. 3. `TimeLimit`: Terminates the episode after a fixed number of steps. 4. `VideoWrapper`: Captures a video of the environment. ### Example 1: Action Discretize Wrapper InvertedPendulum is a PyBullet environment that accepts continuous actions in the range `[-1, 1]`. If we want to train a discrete action agent such as DQN on this environment, we have to discretize (quantize) the action space. This is exactly what the `ActionDiscretizeWrapper` does. Compare the `action_spec` before and after wrapping: ``` env = suite_gym.load('Pendulum-v0') print('Action Spec:', env.action_spec()) discrete_action_env = wrappers.ActionDiscretizeWrapper(env, num_actions=5) print('Discretized Action Spec:', discrete_action_env.action_spec()) ``` The wrapped `discrete_action_env` is an instance of `py_environment.PyEnvironment` and can be treated like a regular python environment. # TensorFlow Environments The interface for TF environments is defined in `environments/tf_environment.TFEnvironment` and looks very similar to the Python environments. TF Environments differ from python envs in a couple of ways: * They generate tensor objects instead of arrays * TF environments add a batch dimension to the tensors generated when compared to the specs. Converting the python environments into TFEnvs allows tensorflow to parellalize operations. For example, one could define a `collect_experience_op` that collects data from the environment and adds to a `replay_buffer`, and a `train_op` that reads from the `replay_buffer` and trains the agent, and run them in parallel naturally in TensorFlow. ``` class TFEnvironment(object): def time_step_spec(self): """Describes the `TimeStep` tensors returned by `step()`.""" def observation_spec(self): """Defines the `TensorSpec` of observations provided by the environment.""" def action_spec(self): """Describes the TensorSpecs of the action expected by `step(action)`.""" def reset(self): """Returns the current `TimeStep` after resetting the Environment.""" return self._reset() def current_time_step(self): """Returns the current `TimeStep`.""" return self._current_time_step() def step(self, action): """Applies the action and returns the new `TimeStep`.""" return self._step(action) @abc.abstractmethod def _reset(self): """Returns the current `TimeStep` after resetting the Environment.""" @abc.abstractmethod def _current_time_step(self): """Returns the current `TimeStep`.""" @abc.abstractmethod def _step(self, action): """Applies the action and returns the new `TimeStep`.""" ``` The `current_time_step()` method returns the current time_step and initializes the environment if needed. The `reset()` method forces a reset in the environment and returns the current_step. If the `action` doesn't depend on the previous `time_step` a `tf.control_dependency` is needed in `Graph` mode. For now, let us look at how `TFEnvironments` are created. ## Creating your own TensorFlow Environment This is more complicated than creating environments in Python, so we will not cover it in this colab. An example is available [here](https://github.com/tensorflow/agents/blob/master/tf_agents/environments/tf_environment_test.py). The more common use case is to implement your environment in Python and wrap it in TensorFlow using our `TFPyEnvironment` wrapper (see below). ## Wrapping a Python Environment in TensorFlow We can easily wrap any Python environment into a TensorFlow environment using the `TFPyEnvironment` wrapper. ``` env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) print(isinstance(tf_env, tf_environment.TFEnvironment)) print("TimeStep Specs:", tf_env.time_step_spec()) print("Action Specs:", tf_env.action_spec()) ``` Note the specs are now of type: `(Bounded)TensorSpec`. ## Usage Examples ### Simple Example ``` env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) # reset() creates the initial time_step after resetting the environment. time_step = tf_env.reset() num_steps = 3 transitions = [] reward = 0 for i in range(num_steps): action = tf.constant([i % 2]) # applies the action and returns the new TimeStep. next_time_step = tf_env.step(action) transitions.append([time_step, action, next_time_step]) reward += next_time_step.reward time_step = next_time_step np_transitions = tf.nest.map_structure(lambda x: x.numpy(), transitions) print('\n'.join(map(str, np_transitions))) print('Total reward:', reward.numpy()) ``` ### Whole Episodes ``` env = suite_gym.load('CartPole-v0') tf_env = tf_py_environment.TFPyEnvironment(env) time_step = tf_env.reset() rewards = [] steps = [] num_episodes = 5 for _ in range(num_episodes): episode_reward = 0 episode_steps = 0 while not time_step.is_last(): action = tf.random_uniform([1], 0, 2, dtype=tf.int32) time_step = tf_env.step(action) episode_steps += 1 episode_reward += next_time_step.reward.numpy() rewards.append(episode_reward) steps.append(episode_steps) num_steps = np.sum(steps) avg_length = np.mean(steps) avg_reward = np.mean(rewards) print('num_episodes:', num_episodes, 'num_steps:', num_steps) print('avg_length', avg_length, 'avg_reward:', avg_reward) ```
github_jupyter
(dynamic_programming)= # Dynamic Programming ``` {index} Dynamic Programming ``` Dynamic algorithms are a family of programs which (broadly speaking) share the feature of utilising solutions to subproblems in coming up with an optimal solution. We will discuss the conditions which problems need to satisfy to be solved dynamically but let us first have a look at some basic examples. The concept is quite challenging to digest, so there are many examples in this section. ## Simple Examples * **Dynamic Fibonacci** If you have read the section about [recursion](https://primer-computational-mathematics.github.io/book/b_coding/Fundamentals%20of%20Computer%20Science/2_Recursion.html#recursion) you probably know that the basic implementation for generating Fibonacci numbers is very inefficient (\\(O(2^n)\\)!). Now, as we generate the next numbers in the Fibonacci sequence, we will remember them for further use. The *trade-off between memory and time* is dramatic in this case. Compare the two versions of the function: ``` # For comparing the running times import time # Inefficient def fib(n): assert n >= 0 if n < 2: return 1 else: return fib(n-1) + fib(n-2) # Dynamic version def dynamicFib(n): assert n >= 0 #prepare a table for memoizing prevFib = 1 prevPrevFib = 1 temp = 0 #build up on your previous results for i in range(2,n+1): temp = prevFib + prevPrevFib prevPrevFib = prevFib prevFib = temp return prevFib start = time.time() print(fib(32)) end = time.time() print("Time for brute:" + str(end - start)) start = time.time() print(dynamicFib(32)) end = time.time() print("Time for dynamic:" + str(end - start)) ``` The time difference is enormous! As you can probably spot, `dynamicFib` is \\(O(n)\\)! With the use of three integer variables (`prevFib`, `prevPrevFib` and `temp`) we brought exponential time complexity down to linear. How did it happen? Let us now depict the work done by `fib(5)` on a graph: ```{figure} algo_images/FibTree.png :width: 60% ``` Wow! This is quite a tree! However, the worst feature is that many of the nodes are repeated (e.g. node \\(2\\) appears 3 times). These repeated results which are constantly recomputed bring us to the exponential complexity. Consider the dynamic solution graph: ```{figure} algo_images/FibDyn.png :width: 10% ``` Now, the number of nodes grows linearly with \\(n\\). We have `merged` the subproblems to avoid redundancy. ----------------- * **Shortest Path on a Grid** Dynamic programming is often used for optimisation problems. Consider a square grid with numbers from 0 to 9 in each square. An example would be: ``` +-+-+-+-+ |1|0|8|4| +-+-+-+-+ |3|5|1|0| +-+-+-+-+ |6|8|9|3| +-+-+-+-+ |1|2|4|5| +-+-+-+-+ ``` It is allowed to move only **down or right**. What is the value of the minimum path from the upper-left corner to the lower-right corner? The initial approach to the problem might be to check all the possible paths and return the minimal one. This is exponential and too slow. To come up with a faster approach we need to find subproblems. Let us imagine that we have reached the lower-right corner (hurray!). We could get there from the tile above it and left of it. This might at first seem like a *Divide and Conquer* problem, but let us keep on looking for an overlap: ```{figure} algo_images/DownRightGrid.png :width: 30% ``` In the simplest case of four tiles, we can already see that the upper-left tile is considered twice. We should then leverage this repetition. This overlapping generalises for larger grids. In our algorithm, we will remember the optimal path to the tiles already visited and build on this knowledge: ``` # grid is a square matrix def shortestPathDownRight(grid): # dictionary that will keep the optimal paths # to the already visited tiles table = {} # n - length of the side of the square n = len(grid) assert n == 0 or len(grid[0]) == n table[(0,0)] = grid[0][0] # top and most left column have trival optimal paths for i in range(1, n): table[(0,i)] = table[(0,i-1)] + grid[0][i] table[(i,0)] = table[(i-1,0)] + grid[i][0] # the dynamic magic for i in range(1,n): for j in range(1,n): table[(i,j)] = min(table[(i-1,j)],table[(i,j-1)]) + grid[i][j] return table[(n-1,n-1)] grid = [[1,0,8,4],[3,5,1,0],[6,8,9,3],[1,2,4,5]] print(shortestPathDownRight(grid)) ``` What is the time complexity of this algorithm? Based on the nested loop we can deduce that it is \\(O(n^2)\\). Quite an improvement! -------- ### Space Complexity We usually do not concern ourselves with the amount of memory a program utilises. Dynamic programs are an exception to this rule. The amount of memory they use can be a limiting factor for some machines, so we need to take it into account. In the case of `dynamicFib` this was \\(O(1)\\) as we only needed to keep track of the last two Fibonacci numbers. In case of `shortestPathDownRight` we need to create a grid of size \\(n \times n\\), so \\(O(n^2)\\). The notion of space complexity is very similar to time complexity, so we will not discuss it in depth. -------- * **Cutting Rods** We are given a rod of integer length \\(n\\) and a list of length `prices` \\(n\\). The \\(i\\)th entry in the list corresponds to the profit we can get from selling the rod of length \\(i\\). How should we cut the rod so we maximise our profit? The key to our dynamic algorithm will be the observation that: We cut the rod at position \\(k\\). Now we have a rod of lenght \\(k\\) and \\(n-k\\). Let us assume we know the maximum price for these two rods. Now we need to consider all the \\(0 \leq k \leq \lfloor \frac{n}{2} \rfloor + 1\\) (the problem is symmetric so computing for \\(\frac{n}{2} \leq k\\) would be redundant. For \\(k=0\\) we just take `prices[n]`. The cutting introduces subproblems which are smaller than the initial problem and they are overlapping! Let us put this into code: ``` # For comparing the running times import time # For testing from random import randint def dynamicCutRod(n,prices): # setting the initial values of variables assert n >= 0 and n == len(prices) # trival cases if n == 0: return 0 if n == 1: return prices[0] # setting up needed variables table = {} currLen = 2 table[0] = 0 table[1] = prices[0] while currLen < n + 1: # no cuts for a given len table[currLen] = prices[currLen - 1] # considering all possible cuts for a give len for k in range(1,currLen//2 + 1): # take the maximal one if table[currLen] < table[k] + table[currLen - k]: table[currLen] = table[k] + table[currLen - k] currLen += 1 return table[n] # for testing purposes def bruteForceRecursive(n,prices): assert n >=0 if n == 0: return 0 if n == 1: return prices[0] currLen = n res = prices[n-1] for k in range(1,n//2 + 1): res = max(res, bruteForceRecursive(k,prices) + bruteForceRecursive(n-k,prices)) return res # testing for i in range(1, 11): prices = [] for j in range(i): prices.append(randint(1,10)) assert bruteForceRecursive(len(prices),prices) == dynamicCutRod(len(prices),prices) # comparing times prices = [] for i in range(20): prices.append(randint(1,10)) start = time.time() print(bruteForceRecursive(len(prices),prices)) end = time.time() print("Time for brute:" + str(end - start)) start = time.time() print(dynamicCutRod(len(prices),prices)) end = time.time() print("Time for dynamic:" + str(end - start)) ``` Time complexity? For each \\(0\leq i \leq n \\) we need to consider \\(i\\) different cuts. This is the sum of arithmetic series so \\(O(n^2)\\). We memoize only the optimal solutions to subproblems, therefore space complexity is \\(O(n)\\). ## Characteristic features of dynamic problems All problems which can be tackled with the use of Dynamic Programming (DP) have two main features: 1) **Optimal substructure**: In broad terms, that solution to the problem can be formulated in terms of independent subproblems. Then you choose a solution/combination of optimal solutions to subproblems and show that this choice leads to an optimal global solution. For example, for the `shortestPath` problem we choose between the optimal solution to the tile above and tile to the left. For the rod problem, we choose between all possible \\(n\\) cuts of a rod and assume we have solutions to the shorter rods. 2) **Overlapping subproblems**: The subproblems which we split the main question into should repeat. Eliminating the need to recompute the subproblems (by memoising them) should speed up our algorithm. For example, `dynamicFib` used two variables to keep the results of computing previous Fibonacci numbers. ## Common approaches to DP There are two main schools of thought when it comes to solving DP algorithms: 1) ***Memoization*** is using the *memory-time trade-off*. It remembers the results to the subproblems in a dictionary `memo` and recalls them when needed. If we have the result in memory, we take if from there, otherwise compute it. 2) ***Bottom-up*** approach starts with the trivial cases of the problem and builds on them. I relies on the the fact that subproblems can be sorted. So we first compute the optimal cutting for a rod of length 1 and then length 2 and so on... Both usually lead to the same time complexities. ## Advanced Examples * **0-1 Knapsack** The problem is about a backpack (knapsack) of an integer volume \\(S\\), we are given lists `spaces` and `vals` which correspond to the size and value of the objects we might want to pack. The trick is to pack the objects of the highest accumulate value which fit into the backpack. We will consider prefixes of the `sizes` list in order of length and put the intermediate results in a table. Compare the bottom-up and memoized approaches: ``` # For comparing the running times import time # For testing from random import randint # bottom up approach def knapSack(wt, val, W, n): K = [[0 for x in range(W + 1)] for x in range(n + 1)] # Build table K[][] in bottom up manner for i in range(n + 1): for w in range(W + 1): if i == 0 or w == 0: K[i][w] = 0 elif wt[i-1] <= w: K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) else: K[i][w] = K[i-1][w] return K[n][W] # memoized memo = {} def knapSackMemo(wt,val, W, n): # base case if n == 0 or W == 0: memo[(n,W)] = 0 return 0 # check if memoized if (n,W) in memo: return memo[(n,W)] # if not, calcuate else: if wt[n-1] <= W: memo[(n,W)] = max(knapSackMemo(wt,val,W-wt[n-1],n-1)+val[n-1], knapSackMemo(wt,val,W,n-1)) return memo[(n,W)] else: memo[(n,W)] = knapSackMemo(wt,val,W,n-1) return memo[(n,W)] # brute force for testing def bruteForce(wt, val, W): res = 0 # all combinations of the elements for i in range(2**len(wt)): sumSize = 0 sumVal = 0 for j in range(len(wt)): if (i >> j) & 1: sumSize += wt[j] sumVal += val[j] if sumSize > W: sumVal = 0 break res = max(sumVal, res) return res # testing for _ in range(10): sizes = [] vals = [] S = randint(0,200) memo = {} for _ in range(13): sizes.append(randint(1,10)) vals.append(randint(1,20)) br = bruteForce(sizes,vals, S) btup = knapSack(sizes,vals,S,len(sizes)) mem = knapSackMemo(sizes,vals,S,len(sizes)) assert btup == br and mem == br start = time.time() print(bruteForce(sizes,vals, S)) end = time.time() print("Time for brute:" + str(end - start)) start = time.time() print(knapSack(sizes,vals,S,len(sizes))) end = time.time() print("Time for bottom-up:" + str(end - start)) memo = {} start = time.time() print(knapSackMemo(sizes,vals,S,len(sizes))) end = time.time() print("Time for memoized:" + str(end - start)) ``` In this case, the memoized approach is the fastest as it does not usually require to consider all `(n,W)` pairs. However, both bottom-up and memoized approach have space (and time) complexity of \\(O(nS)\\). The brute force has time complexity of \\(O(2^n)\\), where \\(n\\) is the length of the `sizes` list. ------------- * **Scheduling** With all the chaos that COVID caused universities are going fully remote. The head of your department asked the lecturers to send the timeslots in which they can do lectures. This is a list `timeslots` which consist of pairs of integers - the start and end of the timeslot. If timeslots overlap, then we choose only one of them. Lectures can start at the same time the previous lecture finished. You aim to pick the subset of `timeslots` which assures that the sum of teaching hours is maximum. Return the maximum number of hours. The question is similar to the previous one. We are given a list of items (`timeslots`) and need to come up with an optimisation. The value of each subset is the sum of hours of its elements. To speed things up in later stages, we will sort the timeslots by the ending time. This is done in \\(O(nlog(n))\\). We will then consider the prefixes of the sorted array and memoize optimal results. `memo[n]` will store the maximum number of hours from the prefix of `n` length. ``` # For comparing the running times import time # For testing from random import randint # utility function to speed up the search def binarySearch(timeslots,s,low,high): if low >= high: return low mid = (low + high) //2 if timeslots[mid][1] <= s: return binarySearch(timeslots, s, mid+1, high) else: return binarySearch(timeslots, s, low, mid) # init memo memo = {} # assumes that timeslots array is sorted by ending time def schedule(timeslots, n): # base case if n == 0: memo[0] = 0 return 0 # memoized case elif n in memo: return memo[n] # else calculate else: s,e = timeslots[n-1] # in log time ind = min(binarySearch(timeslots,s,0,len(timeslots)),n-1) memo[n] = max(schedule(timeslots,n-1), schedule(timeslots,ind) + (e - s)) return memo[n] # brute force for testing def bruteForce(timeslots): res = 0 # all combinations of the elements for i in range(2**len(timeslots)): sumHours = 0 already_chosen = [] for j in range(len(timeslots)): if (i >> j) & 1: s, e = timeslots[j] sumHours += e - s already_chosen.append(timeslots[j]) # checking if a valid combination of timeslots for k in range(len(already_chosen)-1): if not (s >= already_chosen[k][1] or e <= already_chosen[k][0]): sumHours = 0 break res = max(sumHours, res) return res # testing for _ in range(10): memo = {} timeslots = [] for _ in range(12): s = randint(0,100) e = randint(s,100) timeslots.append((s,e)) timeslots.sort(key = lambda slot: (slot[1],slot[0])) br = bruteForce(timeslots) mem = schedule(timeslots,len(timeslots)) assert br == mem start = time.time() print(bruteForce(timeslots)) end = time.time() print("Time for brute:" + str(end - start)) memo = {} start = time.time() print(schedule(timeslots,len(timeslots))) end = time.time() print("Time for memo:" + str(end - start)) ``` Time complexity of this solution is \\(O(nlog(n))\\). Why? ## Exercises * **Tiling problem** You are given a \\(2 \times n\\) board and \\(2 \times 1\\) tiles. Count the number of ways the tiles can be arranged (horizontally and vertically) on the board. **HINT**: You have seen this algorithm before. ```{admonition} Answer :class: dropdown Consider the end of the board. There are two cases, we can either have to fill in a \\(2 \times 2\\) subboard or \\(1 \times 2\\) subboard. We assume that the rest of the board is already covered and this is the same problem but smaller. There are two ways of arranging tiles on the \\(2 \times 2\\) board and one way to do this on \\(1 \times 2\\) board. Watch out though! The case in which we place tiles vertically on the \\(2 \times 2\\) board covers some of the cases when we fill \\(1 \times 2\\). Therefore we should ignore it. The final formula is as follow: \\[ count[n] = count[n-1] + count[n-2] \\] That is Fibonacci numbers. ``` ------------ * **Maximum sum subarray** You are given an array with \\(1\\) and \\(-1\\) elements only. Find the array of the maximum sum in \\(O(n)\\). Return this maximal sum. E.g. [-1,1,1,-1,1,1,1,-1] -> 4. **HINT**: Consider the sums of prefixes of the array. ````{admonition} Answer :class: dropdown ```python def maxSubarray(arr): assert len(arr) > 0 sumPref = 0 minSum = 0 maxSum = 0 for i in range(0,len(arr)): # current prefix sum sumPref = sumPref + arr[i] # keep track of the minimal sum (can be negative) minSum = min(minSum, sumPref) # take away the minSum, this will give max maxSum = max(maxSum, sumPref-minSum) return maxSum print(maxSubarray([-1,1,1,-1,1,1,1,-1])) ``` ```` --------- * **Longest snake sequence** You are given a grid of natural numbers. A snake is a sequence of numbers which goes down or to the right. The adjacent numbers in a snake differ by a maximum 1. Define a dynamic function which will return the length of the longest snake. E.g. **9**, 6, 5, 2 **8**, **7**, **6**, **5** 7, 3, 1, **6** 1, 1, 1, **7** -> 7 ````{admonition} Answer :class: dropdown ```python def longestSnake(grid): #dictionary that will keep the optimal paths to the already visited tiles table = {} # n - length of the side of the square n = len(grid) assert n == 0 or len(grid[0]) == n table[(0,0)] = 1 # top and most left column have trival optimal paths for i in range(1, n): table[(0,i)] = table[(0,i-1)] + 1 if abs(grid[0][i] - grid[0][i-1]) < 2 else 1 table[(i,0)] = table[(i-1,0)] + 1 if abs(grid[i][0] - grid[i-1][0]) < 2 else 1 # the dynamic magic for i in range(1,n): for j in range(1,n): table[(i,j)] = max( table[(i-1,j)] + 1 if abs(grid[i][j] - grid[i-1][j]) < 2 else 1, table[(i,j-1)] + 1 if abs(grid[i][j] - grid[i][j-1]) < 2 else 1) return max(table.values()) mat = [[9, 6, 5, 2], [8, 7, 6, 5], [7, 3, 1, 6], [1, 1, 1, 7]] print(longestSnake(mat)) ``` ```` ## References * Cormen, Leiserson, Rivest, Stein, "Introduction to Algorithms", Third Edition, MIT Press, 2009 * Prof. Erik Demaine, Prof. Srini Devadas, MIT OCW 6.006 ["Introduction to Algorithms"](https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/), Fall 2011 * GeeksforGeeks, [Find maximum length Snake sequence](https://www.geeksforgeeks.org/find-maximum-length-snake-sequence/) * Polish Informatics Olimpiad, "Advetures of Bajtazar, 25 Years of Informatics Olympiad", PWN 2018
github_jupyter
# Spectral GP Learning with Deltas In this paper, we demonstrate another approach to spectral learning with GPs, learning a spectral density as a simple mixture of deltas. This has been explored, for example, as early as Lázaro-Gredilla et al., 2010. ``` import gpytorch import torch ``` ## Load Data For this notebook, we'll be using a sample set of timeseries data of BART ridership on the 5 most commonly traveled stations in San Francisco. This subsample of data was selected and processed from Pyro's examples http://docs.pyro.ai/en/stable/_modules/pyro/contrib/examples/bart.html ``` import os import urllib.request smoke_test = ('CI' in os.environ) if not smoke_test and not os.path.isfile('../BART_sample.pt'): print('Downloading \'BART\' sample dataset...') urllib.request.urlretrieve('https://drive.google.com/uc?export=download&id=1A6LqCHPA5lHa5S3lMH8mLMNEgeku8lRG', '../BART_sample.pt') torch.manual_seed(1) if smoke_test: train_x, train_y, test_x, test_y = torch.randn(2, 100, 1), torch.randn(2, 100), torch.randn(2, 100, 1), torch.randn(2, 100) else: train_x, train_y, test_x, test_y = torch.load('../BART_sample.pt', map_location='cpu') if torch.cuda.is_available(): train_x, train_y, test_x, test_y = train_x.cuda(), train_y.cuda(), test_x.cuda(), test_y.cuda() print(train_x.shape, train_y.shape, test_x.shape, test_y.shape) train_x_min = train_x.min() train_x_max = train_x.max() train_x = train_x - train_x_min test_x = test_x - train_x_min train_y_mean = train_y.mean(dim=-1, keepdim=True) train_y_std = train_y.std(dim=-1, keepdim=True) train_y = (train_y - train_y_mean) / train_y_std test_y = (test_y - train_y_mean) / train_y_std ``` ## Define a Model The only thing of note here is the use of the kernel. For this example, we'll learn a kernel with 2048 deltas in the mixture, and initialize by sampling directly from the empirical spectrum of the data. ``` class SpectralDeltaGP(gpytorch.models.ExactGP): def __init__(self, train_x, train_y, num_deltas, noise_init=None): likelihood = gpytorch.likelihoods.GaussianLikelihood(noise_constraint=gpytorch.constraints.GreaterThan(1e-11)) likelihood.register_prior("noise_prior", gpytorch.priors.HorseshoePrior(0.1), "noise") likelihood.noise = 1e-2 super(SpectralDeltaGP, self).__init__(train_x, train_y, likelihood) self.mean_module = gpytorch.means.ConstantMean() base_covar_module = gpytorch.kernels.SpectralDeltaKernel( num_dims=train_x.size(-1), num_deltas=num_deltas, ) base_covar_module.initialize_from_data(train_x[0], train_y[0]) self.covar_module = gpytorch.kernels.ScaleKernel(base_covar_module) def forward(self, x): mean_x = self.mean_module(x) covar_x = self.covar_module(x) return gpytorch.distributions.MultivariateNormal(mean_x, covar_x) model = SpectralDeltaGP(train_x, train_y, num_deltas=1500) if torch.cuda.is_available(): model = model.cuda() ``` ## Train ``` model.train() mll = gpytorch.mlls.ExactMarginalLogLikelihood(model.likelihood, model) optimizer = torch.optim.Adam(model.parameters(), lr=0.01) scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer, milestones=[40]) num_iters = 1000 if not smoke_test else 4 with gpytorch.settings.max_cholesky_size(0): # Ensure we dont try to use Cholesky for i in range(num_iters): optimizer.zero_grad() output = model(train_x) loss = -mll(output, train_y) if train_x.dim() == 3: loss = loss.mean() loss.backward() optimizer.step() if i % 10 == 0: print(f'Iteration {i} - loss = {loss:.2f} - noise = {model.likelihood.noise.item():e}') scheduler.step() # Get into evaluation (predictive posterior) mode model.eval() # Test points are regularly spaced along [0,1] # Make predictions by feeding model through likelihood with torch.no_grad(), gpytorch.settings.max_cholesky_size(0), gpytorch.settings.fast_pred_var(): test_x_f = torch.cat([train_x, test_x], dim=-2) observed_pred = model.likelihood(model(test_x_f)) varz = observed_pred.variance ``` ## Plot Results ``` from matplotlib import pyplot as plt %matplotlib inline _task = 3 plt.subplots(figsize=(15, 15), sharex=True, sharey=True) for _task in range(2): ax = plt.subplot(3, 1, _task + 1) with torch.no_grad(): # Initialize plot # f, ax = plt.subplots(1, 1, figsize=(16, 12)) # Get upper and lower confidence bounds lower = observed_pred.mean - varz.sqrt() * 1.98 upper = observed_pred.mean + varz.sqrt() * 1.98 lower = lower[_task] # + weight * test_x_f.squeeze() upper = upper[_task] # + weight * test_x_f.squeeze() # Plot training data as black stars ax.plot(train_x[_task].detach().cpu().numpy(), train_y[_task].detach().cpu().numpy(), 'k*') ax.plot(test_x[_task].detach().cpu().numpy(), test_y[_task].detach().cpu().numpy(), 'r*') # Plot predictive means as blue line ax.plot(test_x_f[_task].detach().cpu().numpy(), (observed_pred.mean[_task]).detach().cpu().numpy(), 'b') # Shade between the lower and upper confidence bounds ax.fill_between(test_x_f[_task].detach().cpu().squeeze().numpy(), lower.detach().cpu().numpy(), upper.detach().cpu().numpy(), alpha=0.5) # ax.set_ylim([-3, 3]) ax.legend(['Training Data', 'Test Data', 'Mean', '95% Confidence'], fontsize=16) ax.tick_params(axis='both', which='major', labelsize=16) ax.tick_params(axis='both', which='minor', labelsize=16) ax.set_ylabel('Passenger Volume (Normalized)', fontsize=16) ax.set_xlabel('Hours (Zoomed to Test)', fontsize=16) ax.set_xticks([]) plt.xlim([1250, 1680]) plt.tight_layout() ```
github_jupyter
# Outpatient Orders Prototyping Code Get Ready ``` var DocumentStore = require('../../qewd/node_modules/ewd-qoper8-cache/node_modules/ewd-document-store'); var thisInterface = require('../../cache'); var runRPC = require('../../ewd-vista/lib/runRPC'); var sessions = require('../../qewd/node_modules/ewd-session/'); var pharm = require('../../ewd-vista-pharmacy/'); require('../../ewd-vista/lib/mFunctions') var instance = {}; var session = ''; ``` Open Database ``` instance.db = new thisInterface.Cache(); this.db = instance.db instance.db.open({path: '/usr/cachesys/mgr/', namespace: 'PANORAMA'}); instance.documentStore = new DocumentStore(instance.db); console.log(instance.documentStore.db.version()); ``` Set-up Session ``` // Initialize session management sessions.addTo(instance.documentStore); var session = sessions.create('testApp'); console.log('Session ID : ' + session.id); console.log('Session token : ' + session.token); ``` Initialize symbol table management in session ``` instance.db.symbolTable = sessions.symbolTable(instance.db) ``` Sign-on Setup ``` runRPC.call(instance, {rpcName: 'XUS SIGNON SETUP'}, session); ``` Sign-On (doesn't work) ``` var accessCode = 'MX1234'; //process.argv[3]; var verifyCode = 'MX1234!!'; //process.argv[4]; var params = { rpcName: 'XUS AV CODE', rpcArgs: [{type: 'LITERAL', value: accessCode + ';' + verifyCode}] }; console.log(params); runRPC.call(instance, params, session); ``` Set Division ``` let result = true; let divisions = runRPC.call(instance, {rpcName: 'XUS DIVISION GET'}, session).value; divisions.splice(0,1); // Remove array length element divisions.forEach(function(element, index, array) { // Keep only IENs array[index] = element.split('^')[0]; }); if (divisions.length > 1) { params = { rpcName: 'XUS DIVISION SET', rpcArgs: [{ type: 'LITERAL', value: '`' + divisions[0] }] }; runRPC.call(instance, params, session) } ``` Get sites associated with current division ``` var getSitesAssociatedWithCurrentLoggedInDivision = function() { var results = []; var pharmacySite = new instance.documentStore.DocumentNode('PS', [59]); this.db.function({function: 'SetVar^ewdVistAUtils', arguments: ['DUZ(2)', 500]}); duz2 = this.db.function({function: 'GetVar^ewdVistAUtils', arguments: ['DUZ(2)']}).result; pharmacySite.forEachChild( {range: {from: 0, to: ' '} }, function(subscript, node) { if (duz2 === node.$('INI').value) results.push(subscript); }); return results; } getSitesAssociatedWithCurrentLoggedInDivision() ``` This is a copy of the code in SUMMCL^PSOORNE1: Outpatient Order Summary ``` var aclIX = new instance.documentStore.DocumentNode('PS',['52.41','ACL']) var counts = {}; aclIX.forEachChild( (clinic, node) => node.forEachChild( (fmdt, node2) => node2.forEachChild( (ien, node3) => { var z = new instance.documentStore.DocumentNode('PS',['52.41',ien,0]).value; if (!z) return; if (!['NW','RNW','RF'].includes(z.split('^')[2])) return; // New, Renew, Refills only. No DCs etc. if (!z.split('^')[12]) return; // Must have clinic. Redundant check as record won't exist w/o it. var hospitalLocationIEN = z.split('^')[12]; var institutionIEN = instance.db.function({function: 'GET1^DIQ', arguments: ['44', hospitalLocationIEN, 'DIVISION:INSTITUTION FILE POINTER', 'I']}).result; var duz2 = this.db.function({function: 'GetVar^ewdVistAUtils', arguments: ['DUZ(2)']}).result; if (duz2 !== institutionIEN) return; var hospitalLocationName = instance.db.function({function: 'EXTERNAL^DILFD', arguments: ['52.41','1.1','',hospitalLocationIEN]}).result; if (counts[hospitalLocationIEN] === undefined) { counts[hospitalLocationIEN] = {}; counts[hospitalLocationIEN].ien = hospitalLocationIEN; counts[hospitalLocationIEN].name = hospitalLocationName; counts[hospitalLocationIEN].count = 0; } counts[hospitalLocationIEN].count++; }) ) ); Object.keys(counts).forEach(ien => { console.log(counts[ien].name, counts[ien].count); }) counts; var aclIX = new instance.documentStore.DocumentNode('PS',['52.41','ACL']) var patients = {}; aclIX.forEachChild( (clinic, node) => node.forEachChild( (fmdt, node2) => node2.forEachChild( (ien, node3) => { var z = new instance.documentStore.DocumentNode('PS',['52.41',ien,0]).value; if (!z) return; if (!['NW','RNW','RF'].includes(z.split('^')[2])) return; // New, Renew, Refills only. No DCs etc. if (!z.split('^')[12]) return; // Must have clinic. Redundant check as record won't exist w/o it. var hospitalLocationIEN = z.split('^')[12]; var clinicSortGroups = []; new instance.documentStore.DocumentNode('PS',['59.8']).forEachChild({range: {from: 1, to: ' '}}, (sortGroupIEN, sortNode) => { if (sortNode.$("1").$("B").$(hospitalLocationIEN).exists) clinicSortGroups.push(sortNode.$(0).value.split[0]) }); var dfn = z.split('^')[1]; var name = instance.db.function({function: 'GET1^DIQ', arguments: ['2', dfn, '.01']}).result; var dob = instance.db.function({function: 'GET1^DIQ', arguments: ['2', dfn, 'DOB']}).result; var routeName = instance.db.function({function: 'GET1^DIQ', arguments: ['52.41', ien, 'PICKUP ROUTING']}).result; var priorityName = instance.db.function({function: 'GET1^DIQ', arguments: ['52.41', ien, 'PRIORITY']}).result; var flagged = instance.db.function({function: 'GET1^DIQ', arguments: ['52.41', ien, 'FLAG', 'I']}).result; // I +$P(OR0,"^",9) S PDEA=$P($G(^PSDRUG($P(OR0,"^",9),0)),"^",3),PDEA=$S(PDEA[2:1,PDEA[3!(PDEA[4)!(PDEA[5):2,1:0) // E S PDEA=$$OIDEA^PSSUTLA1($P(OR0,"^",8),"O") var drugIEN = instance.db.function({function: 'GET1^DIQ', arguments: ['52.41', ien, 'DRUG', 'I']}).result; var oiIEN = instance.db.function({function: 'GET1^DIQ', arguments: ['52.41', ien, 'PHARMACY ORDERABLE ITEM', 'I']}).result; var isC2,isC345 = false; if (drugIEN) { var pdea = instance.db.function({function: 'GET1^DIQ', arguments: ['50', drugIEN, 'DEA, SPECIAL HDLG', 'I']}).result; if (['2'].some(n => pdea.includes(n))) isC2 = true; if (['3','4','5'].some(n => pdea.includes(n))) isC345 = true; } else { var isCS = instance.db.function({function: 'OIDEA^PSSUTLA1', arguments: [oiIEN, 'O']}).result; if (isCS === 1) isC2 = true; if (isCS === 2) isC345 = true; } // Count for each patient: by priority; by flag; by route; by CS (2 and 345) // Patient -> Check // Priority -> Check // Route -> Check // Flagged -> Check // CS: -> Check if (patients[dfn] === undefined) { patients[dfn] = {}; patients[dfn].dob = dob; patients[dfn].dfn = dfn; patients[dfn].name = name; patients[dfn].count = 0; patients[dfn].flagged = 0; patients[dfn].priority = {}; patients[dfn].routing = {}; patients[dfn].c2 = 0; patients[dfn].c345 = 0; patients[dfn].clinicSortGroups = clinicSortGroups; } patients[dfn].count++; if (patients[dfn].routing[routeName] === undefined) patients[dfn].routing[routeName] = 0; patients[dfn].routing[routeName]++; if (patients[dfn].priority[priorityName] === undefined) patients[dfn].priority[priorityName] = 0; patients[dfn].priority[priorityName]++; if (flagged) patients[dfn].flagged++; if (isC2) patients[dfn].c2++; if (isC345) patients[dfn].c345++; }) ) ); var header = []; header.push('Name (PID)'); header.push('DOB'); header.push('Priority/EMERGENCY') header.push('Priority/STAT') header.push('Routing/WINDOW') header.push('Routing/MAIL') header.push('Schedule II') header.push('Schedule III-V') header.push('TOTAL') var data = []; var datum = []; Object.keys(patients).forEach(dfn => { datum.push(patients[dfn].name, patients[dfn].dob, patients[dfn].priority.STAT || 0 + patients[dfn].priority.EMERGENCY || 0, patients[dfn].routing.WINDOW || 0, patients[dfn].routing.MAIL || 0, patients[dfn].c2 || 0, patients[dfn].c345 || 0, patients[dfn].count, patients[dfn].clinicSortGroups) data.push(datum); }); var finalResult = {header: header, data: data}; finalResult patients var ix = new instance.documentStore.DocumentNode('PS',['59.8']) ix.forEachChild({range: {from: 1, to: ' '}}, (sortGroupIEN, sortNode) => { console.log(sortNode.$("1").$("B").$("1").exists); }); ```
github_jupyter
``` from __future__ import print_function import os from io import open import requests import shutil import numpy as np import json from IPython.display import Image from zipfile import ZipFile import keras from keras import applications from keras.preprocessing.image import ImageDataGenerator from keras import optimizers from keras.models import Sequential, Model from keras.layers import Conv2D, Activation, Dropout, Flatten, Dense, MaxPooling2D from keras import backend as k from keras.callbacks import ModelCheckpoint, EarlyStopping from tensorflow.python.keras.preprocessing import image execution_path = os.getcwd() DATASET_DIR = os.path.join(execution_path, "idenprof") DATASET_TRAIN_DIR = os.path.join(DATASET_DIR, "train") DATASET_TEST_DIR = os.path.join(DATASET_DIR, "test") save_direc = os.path.join(os.getcwd(), 'idenprof_models') # Name of model files model_name = 'idenprof_weight_model_VGG19.{epoch:03d}-{val_acc}.h5' # Create Directory if it doesn't exist if not os.path.isdir(save_direc): os.makedirs(save_direc) # Join the directory with the model file modelpath = os.path.join(save_direc, model_name) # Checkpoint to save best model checkpoint = ModelCheckpoint(filepath = modelpath, monitor = 'val_acc', verbose = 1, save_best_only = True, save_weights_only = True, period=1) input_shape = (224, 224, 3) model = Sequential( [Conv2D(64, (3, 3), input_shape=input_shape, padding='same',activation='relu'), Conv2D(64, (3, 3), activation='relu', padding='same'), MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), Conv2D(128, (3, 3), activation='relu', padding='same'), Conv2D(128, (3, 3), activation='relu', padding='same',), MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), Conv2D(256, (3, 3), activation='relu', padding='same',), Conv2D(256, (3, 3), activation='relu', padding='same',), Conv2D(256, (3, 3), activation='relu', padding='same',), Conv2D(256, (3, 3), activation='relu', padding='same',), MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), Conv2D(512, (3, 3), activation='relu', padding='same',), MaxPooling2D(pool_size=(2, 2), strides=(2, 2)), Flatten(), Dense(10, activation="softmax")]) model.summary() def train_network(model): print(os.listdir(os.path.join(execution_path, "idenprof"))) optimizer = keras.optimizers.Adam(lr=0.01, decay=1e-4) batch_size = 32 num_classes = 10 epochs = 200 model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) print("Using real time Data Augmentation") train_datagen = ImageDataGenerator(rescale=1. / 255,horizontal_flip=True) test_datagen = ImageDataGenerator(rescale=1. / 255) train_generator = train_datagen.flow_from_directory(DATASET_TRAIN_DIR, target_size=(224, 224),batch_size=batch_size, class_mode="categorical") test_generator = test_datagen.flow_from_directory(DATASET_TEST_DIR, target_size=(224, 224), batch_size=batch_size, class_mode="categorical") model.fit_generator(train_generator, steps_per_epoch=int(9000 / batch_size), epochs=epochs, validation_data=test_generator,validation_steps=int(2000 / batch_size), callbacks=[checkpoint]) train_network(model) ``` ## Measuring the accuracy ``` CLASS_INDEX = None MODEL_PATH = os.path.join(execution_path, "idenprof_VGG19_053-0.726.h5") JSON_PATH = os.path.join(execution_path, "idenprof_model_class.json") model.load_weights(MODEL_PATH) optimizer = keras.optimizers.Adam(lr=0.01, decay=1e-4) model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) test_datagen = ImageDataGenerator(rescale=1. / 255) test_generator = test_datagen.flow_from_directory(DATASET_TEST_DIR, target_size=(224, 224), batch_size = 32, class_mode="categorical") loss,accuracy = model.evaluate_generator(test_generator,steps=int(2000 / 32)) print("Accuracy =", accuracy) ``` ## Predictions on real-world images ``` def preprocess_input(x): x *= (1. / 255) return x def decode_predictions(preds, top=5, model_json=""): global CLASS_INDEX if CLASS_INDEX is None: CLASS_INDEX = json.load(open(model_json)) results = [] for pred in preds: top_indices = pred.argsort()[-top:][::-1] for i in top_indices: each_result = [] each_result.append(CLASS_INDEX[str(i)]) each_result.append(pred[i]) results.append(each_result) return results def run_inference(model,picture): image_to_predict = image.load_img(picture, target_size=(224, 224)) image_to_predict = image.img_to_array(image_to_predict, data_format="channels_last") image_to_predict = np.expand_dims(image_to_predict, axis=0) image_to_predict = preprocess_input(image_to_predict) prediction = model.predict(x=image_to_predict, steps=1) predictiondata = decode_predictions(prediction, top=int(5), model_json=JSON_PATH) for result in predictiondata: print(str(result[0]), " : ", str(result[1] * 100)) picture = os.path.join(execution_path, "test-images/1.jpg") display(Image(filename=picture)) run_inference(model,picture) picture = os.path.join(execution_path, "test-images/2.jpg") display(Image(filename=picture)) run_inference(model,picture) picture = os.path.join(execution_path, "test-images/3.jpg") display(Image(filename=picture)) run_inference(model,picture) ```
github_jupyter
_Lambda School Data Science_ # Make Explanatory Visualizations ### Objectives - identify misleading visualizations and how to fix them - use Seaborn to visualize distributions and relationships with continuous and discrete variables - add emphasis and annotations to transform visualizations from exploratory to explanatory - remove clutter from visualizations ### Links - [How to Spot Visualization Lies](https://flowingdata.com/2017/02/09/how-to-spot-visualization-lies/) - [Visual Vocabulary - Vega Edition](http://ft.com/vocabulary) - [Choosing a Python Visualization Tool flowchart](http://pbpython.com/python-vis-flowchart.html) - [Searborn example gallery](http://seaborn.pydata.org/examples/index.html) & [tutorial](http://seaborn.pydata.org/tutorial.html) - [Strong Titles Are The Biggest Bang for Your Buck](http://stephanieevergreen.com/strong-titles/) - [Remove to improve (the data-ink ratio)](https://www.darkhorseanalytics.com/blog/data-looks-better-naked) - [How to Generate FiveThirtyEight Graphs in Python](https://www.dataquest.io/blog/making-538-plots/) # Avoid Misleading Visualizations Did you find/discuss any interesting misleading visualizations in your Walkie Talkie? ## What makes a visualization misleading? [5 Ways Writers Use Misleading Graphs To Manipulate You](https://venngage.com/blog/misleading-graphs/) ## Two y-axes <img src="https://kieranhealy.org/files/misc/two-y-by-four-sm.jpg" width="800"> Other Examples: - [Spurious Correlations](https://tylervigen.com/spurious-correlations) - <https://blog.datawrapper.de/dualaxis/> - <https://kieranhealy.org/blog/archives/2016/01/16/two-y-axes/> - <http://www.storytellingwithdata.com/blog/2016/2/1/be-gone-dual-y-axis> ## Y-axis doesn't start at zero. <img src="https://i.pinimg.com/originals/22/53/a9/2253a944f54bb61f1983bc076ff33cdd.jpg" width="600"> ## Pie Charts are bad <img src="https://i1.wp.com/flowingdata.com/wp-content/uploads/2009/11/Fox-News-pie-chart.png?fit=620%2C465&ssl=1" width="600"> ## Pie charts that omit data are extra bad - A guy makes a misleading chart that goes viral What does this chart imply at first glance? You don't want your user to have to do a lot of work in order to be able to interpret you graph correctly. You want that first-glance conclusions to be the correct ones. <img src="https://pbs.twimg.com/media/DiaiTLHWsAYAEEX?format=jpg&name=medium" width='600'> <https://twitter.com/michaelbatnick/status/1019680856837849090?lang=en> - It gets picked up by overworked journalists (assuming incompetency before malice) <https://www.marketwatch.com/story/this-1-chart-puts-mega-techs-trillions-of-market-value-into-eye-popping-perspective-2018-07-18> - Even after the chart's implications have been refuted, it's hard a bad (although compelling) visualization from being passed around. <https://www.linkedin.com/pulse/good-bad-pie-charts-karthik-shashidhar/> **["yea I understand a pie chart was probably not the best choice to present this data."](https://twitter.com/michaelbatnick/status/1037036440494985216)** ## Pie Charts that compare unrelated things are next-level extra bad <img src="http://www.painting-with-numbers.com/download/document/186/170403+Legalizing+Marijuana+Graph.jpg" width="600"> ## Be careful about how you use volume to represent quantities: radius vs diameter vs volume <img src="https://static1.squarespace.com/static/5bfc8dbab40b9d7dd9054f41/t/5c32d86e0ebbe80a25873249/1546836082961/5474039-25383714-thumbnail.jpg?format=1500w" width="600"> ## Don't cherrypick timelines or specific subsets of your data: <img src="https://wattsupwiththat.com/wp-content/uploads/2019/02/Figure-1-1.png" width="600"> Look how specifically the writer has selected what years to show in the legend on the right side. <https://wattsupwiththat.com/2019/02/24/strong-arctic-sea-ice-growth-this-year/> Try the tool that was used to make the graphic for yourself <http://nsidc.org/arcticseaicenews/charctic-interactive-sea-ice-graph/> ## Use Relative units rather than Absolute Units <img src="https://imgs.xkcd.com/comics/heatmap_2x.png" width="600"> ## Avoid 3D graphs unless having the extra dimension is effective Usually you can Split 3D graphs into multiple 2D graphs 3D graphs that are interactive can be very cool. (See Plotly and Bokeh) <img src="https://thumbor.forbes.com/thumbor/1280x868/https%3A%2F%2Fblogs-images.forbes.com%2Fthumbnails%2Fblog_1855%2Fpt_1855_811_o.jpg%3Ft%3D1339592470" width="600"> ## Don't go against typical conventions <img src="http://www.callingbullshit.org/twittercards/tools_misleading_axes.png" width="600"> # Tips for choosing an appropriate visualization: ## Use Appropriate "Visual Vocabulary" [Visual Vocabulary - Vega Edition](http://ft.com/vocabulary) ## What are the properties of your data? - Is your primary variable of interest continuous or discrete? - Is in wide or long (tidy) format? - Does your visualization involve multiple variables? - How many dimensions do you need to include on your plot? Can you express the main idea of your visualization in a single sentence? How hard does your visualization make the user work in order to draw the intended conclusion? ## Which Visualization tool is most appropriate? [Choosing a Python Visualization Tool flowchart](http://pbpython.com/python-vis-flowchart.html) ## Anatomy of a Matplotlib Plot ``` import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import AutoMinorLocator, MultipleLocator, FuncFormatter np.random.seed(19680801) X = np.linspace(0.5, 3.5, 100) Y1 = 3+np.cos(X) Y2 = 1+np.cos(1+X/0.75)/2 Y3 = np.random.uniform(Y1, Y2, len(X)) fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(1, 1, 1, aspect=1) def minor_tick(x, pos): if not x % 1.0: return "" return "%.2f" % x ax.xaxis.set_major_locator(MultipleLocator(1.000)) ax.xaxis.set_minor_locator(AutoMinorLocator(4)) ax.yaxis.set_major_locator(MultipleLocator(1.000)) ax.yaxis.set_minor_locator(AutoMinorLocator(4)) ax.xaxis.set_minor_formatter(FuncFormatter(minor_tick)) ax.set_xlim(0, 4) ax.set_ylim(0, 4) ax.tick_params(which='major', width=1.0) ax.tick_params(which='major', length=10) ax.tick_params(which='minor', width=1.0, labelsize=10) ax.tick_params(which='minor', length=5, labelsize=10, labelcolor='0.25') ax.grid(linestyle="--", linewidth=0.5, color='.25', zorder=-10) ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10) ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal") ax.plot(X, Y3, linewidth=0, marker='o', markerfacecolor='w', markeredgecolor='k') ax.set_title("Anatomy of a figure", fontsize=20, verticalalignment='bottom') ax.set_xlabel("X axis label") ax.set_ylabel("Y axis label") ax.legend() def circle(x, y, radius=0.15): from matplotlib.patches import Circle from matplotlib.patheffects import withStroke circle = Circle((x, y), radius, clip_on=False, zorder=10, linewidth=1, edgecolor='black', facecolor=(0, 0, 0, .0125), path_effects=[withStroke(linewidth=5, foreground='w')]) ax.add_artist(circle) def text(x, y, text): ax.text(x, y, text, backgroundcolor="white", ha='center', va='top', weight='bold', color='blue') # Minor tick circle(0.50, -0.10) text(0.50, -0.32, "Minor tick label") # Major tick circle(-0.03, 4.00) text(0.03, 3.80, "Major tick") # Minor tick circle(0.00, 3.50) text(0.00, 3.30, "Minor tick") # Major tick label circle(-0.15, 3.00) text(-0.15, 2.80, "Major tick label") # X Label circle(1.80, -0.27) text(1.80, -0.45, "X axis label") # Y Label circle(-0.27, 1.80) text(-0.27, 1.6, "Y axis label") # Title circle(1.60, 4.13) text(1.60, 3.93, "Title") # Blue plot circle(1.75, 2.80) text(1.75, 2.60, "Line\n(line plot)") # Red plot circle(1.20, 0.60) text(1.20, 0.40, "Line\n(line plot)") # Scatter plot circle(3.20, 1.75) text(3.20, 1.55, "Markers\n(scatter plot)") # Grid circle(3.00, 3.00) text(3.00, 2.80, "Grid") # Legend circle(3.70, 3.80) text(3.70, 3.60, "Legend") # Axes circle(0.5, 0.5) text(0.5, 0.3, "Axes") # Figure circle(-0.3, 0.65) text(-0.3, 0.45, "Figure") color = 'blue' ax.annotate('Spines', xy=(4.0, 0.35), xytext=(3.3, 0.5), weight='bold', color=color, arrowprops=dict(arrowstyle='->', connectionstyle="arc3", color=color)) ax.annotate('', xy=(3.15, 0.0), xytext=(3.45, 0.45), weight='bold', color=color, arrowprops=dict(arrowstyle='->', connectionstyle="arc3", color=color)) ax.text(4.0, -0.4, "Made with http://matplotlib.org", fontsize=10, ha="right", color='.5') plt.show() ``` # Making Explanatory Visualizations with Seaborn Today we will reproduce this [example by FiveThirtyEight:](https://fivethirtyeight.com/features/al-gores-new-movie-exposes-the-big-flaw-in-online-movie-ratings/) ``` from IPython.display import display, Image url = 'https://fivethirtyeight.com/wp-content/uploads/2017/09/mehtahickey-inconvenient-0830-1.png' example = Image(url=url, width=400) display(example) ``` Using this data: https://github.com/fivethirtyeight/data/tree/master/inconvenient-sequel Links - [Strong Titles Are The Biggest Bang for Your Buck](http://stephanieevergreen.com/strong-titles/) - [Remove to improve (the data-ink ratio)](https://www.darkhorseanalytics.com/blog/data-looks-better-naked) - [How to Generate FiveThirtyEight Graphs in Python](https://www.dataquest.io/blog/making-538-plots/) ## Make prototypes This helps us understand the problem ``` %matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd plt.style.use('fivethirtyeight') fake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], index=range(1,11)) fake.plot.bar(color='C1', width=0.9); fake2 = pd.Series( [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]) fake2.value_counts().sort_index().plot.bar(color='C1', width=0.9); ``` ## Annotate with text ``` ``` ## Reproduce with real data ``` df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/inconvenient-sequel/ratings.csv') ``` # ASSIGNMENT Replicate the lesson code. I recommend that you [do not copy-paste](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit). # STRETCH OPTIONS #### 1) Reproduce another example from [FiveThityEight's shared data repository](https://data.fivethirtyeight.com/). #### 2) Reproduce one of the following using a library other than Seaborn or Matplotlib. For example: - [thanksgiving-2015](https://fivethirtyeight.com/features/heres-what-your-part-of-america-eats-on-thanksgiving/) (try the [`altair`](https://altair-viz.github.io/gallery/index.html#maps) library) - [candy-power-ranking](https://fivethirtyeight.com/features/the-ultimate-halloween-candy-power-ranking/) (try the [`statsmodels`](https://www.statsmodels.org/stable/index.html) library) - or another example of your choice! #### 3) Make more charts! Choose a chart you want to make, from [Visual Vocabulary - Vega Edition](http://ft.com/vocabulary). Find the chart in an example gallery of a Python data visualization library: - [Seaborn](http://seaborn.pydata.org/examples/index.html) - [Altair](https://altair-viz.github.io/gallery/index.html) - [Matplotlib](https://matplotlib.org/gallery.html) - [Pandas](https://pandas.pydata.org/pandas-docs/stable/visualization.html) Reproduce the chart. [Optionally, try the "Ben Franklin Method."](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit) If you want, experiment and make changes. Take notes. Consider sharing your work with your cohort! ``` ```
github_jupyter
``` # Workspace problem with several narrow gaps import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.gridspec as gridspec from mpl_toolkits.mplot3d import Axes3D import os import csv from random import randint, random import time # (restrict tensorflow memory growth) os.environ["CUDA_VISIBLE_DEVICES"]="1" config = tf.ConfigProto() config.gpu_options.allow_growth=True # neural network parameters mb_size = 256 h_Q_dim = 512 h_P_dim = 512 c = 0 lr = 1e-4 # problem dimensions dim = 6 dataElements = dim+3*3+2*dim # sample (6D), gap1 (2D, 1D orientation), gap2, gap3, init (6D), goal (6D) z_dim = 3 # latent X_dim = dim # samples y_dim = dim # reconstruction of the original point c_dim = dataElements - dim # dimension of conditioning variable # read in data from csv filename = 'narrowDataFile.txt' f = open(filename, 'rb') reader = csv.reader(f, delimiter=',') count = 0 data_list = [] for row in reader: data_list.append(map(float,row[0:dataElements])) data = np.array(data_list,dtype='d') numEntries = data.shape[0] # split the inputs and conditions into test train (to be processed in the next step into an occupancy grid representation) ratioTestTrain = 0.8; numTrain = int(numEntries*ratioTestTrain) X_train = data[0:numTrain,0:dim] # state: x, y, z, xdot, ydot, zdot c_train = data[0:numTrain,dim:dataElements] # conditions: gaps, init (6), goal (6) X_test = data[numTrain:numEntries,0:dim] c_test = data[numTrain:numEntries,dim:dataElements] numTest = X_test.shape[0] # change conditions to occupancy grid def isSampleFree(sample, obs): for o in range(0,obs.shape[0]/(2*dimW)): isFree = 0 for d in range(0,sample.shape[0]): if (sample[d] < obs[2*dimW*o + d] or sample[d] > obs[2*dimW*o + d + dimW]): isFree = 1 break if isFree == 0: return 0 return 1 gridSize = 11 dimW = 3 plotOn = False; # process data into occupancy grid conditions = data[0:numEntries,dim:dataElements] conditionsOcc = np.zeros([numEntries,gridSize*gridSize]) occGridSamples = np.zeros([gridSize*gridSize, 2]) gridPointsRange = np.linspace(0,1,num=gridSize) idx = 0; for i in gridPointsRange: for j in gridPointsRange: occGridSamples[idx,0] = i occGridSamples[idx,1] = j idx += 1; start = time.time(); for j in range(0,numEntries,1): dw = 0.1 dimW = 3 gap1 = conditions[j,0:3] gap2 = conditions[j,3:6] gap3 = conditions[j,6:9] init = conditions[j,9:15] goal = conditions[j,15:21] obs1 = [0, gap1[1]-dw, -0.5, gap1[0], gap1[1], 1.5] obs2 = [gap2[0]-dw, 0, -0.5, gap2[0], gap2[1], 1.5]; obs3 = [gap2[0]-dw, gap2[1]+dw, -0.5, gap2[0], 1, 1.5]; obs4 = [gap1[0]+dw, gap1[1]-dw, -0.5, gap3[0], gap1[1], 1.5]; obs5 = [gap3[0]+dw, gap1[1]-dw, -0.5, 1, gap1[1], 1.5]; obs = np.concatenate((obs1, obs2, obs3, obs4, obs5), axis=0) if j % 5000 == 0: print('Iter: {}'.format(j)) occGrid = np.zeros(gridSize*gridSize) for i in range(0,gridSize*gridSize): occGrid[i] = isSampleFree(occGridSamples[i,:],obs) conditionsOcc[j,:] = occGrid if plotOn: fig1 = plt.figure(figsize=(10,6), dpi=80) ax1 = fig1.add_subplot(111, aspect='equal') for i in range(0,obs.shape[0]/(2*dimW)): # plot obstacle patches ax1.add_patch( patches.Rectangle( (obs[i*2*dimW], obs[i*2*dimW+1]), # (x,y) obs[i*2*dimW+dimW] - obs[i*2*dimW], # width obs[i*2*dimW+dimW+1] - obs[i*2*dimW+1], # height alpha=0.6 )) for i in range(0,gridSize*gridSize): # plot occupancy grid if occGrid[i] == 0: plt.scatter(occGridSamples[i,0], occGridSamples[i,1], color="red", s=70, alpha=0.8) else: plt.scatter(occGridSamples[i,0], occGridSamples[i,1], color="green", s=70, alpha=0.8) plt.show() end = time.time(); print('Time: ', end-start) cs = np.concatenate((data[0:numEntries,dim+3*dimW:dataElements], conditionsOcc), axis=1) # occ, init, goal c_dim = cs.shape[1] c_gapsInitGoal = c_test c_train = cs[0:numTrain,:] c_test = cs[numTrain:numEntries,:] # define networks X = tf.placeholder(tf.float32, shape=[None, X_dim]) c = tf.placeholder(tf.float32, shape=[None, c_dim]) # Q inputs_Q = tf.concat(axis=1, values=[X,c]) dense_Q1 = tf.layers.dense(inputs=inputs_Q, units=h_Q_dim, activation=tf.nn.relu) dropout_Q1 = tf.layers.dropout(inputs=dense_Q1, rate=0.5) dense_Q2 = tf.layers.dense(inputs=dropout_Q1, units=h_Q_dim, activation=tf.nn.relu) z_mu = tf.layers.dense(inputs=dense_Q2, units=z_dim) # output here is z_mu z_logvar = tf.layers.dense(inputs=dense_Q2, units=z_dim) # output here is z_logvar # P eps = tf.random_normal(shape=tf.shape(z_mu)) z = z_mu + tf.exp(z_logvar / 2) * eps inputs_P = tf.concat(axis=1, values=[z,c]) dense_P1 = tf.layers.dense(inputs=inputs_P, units=h_P_dim, activation=tf.nn.relu) dropout_P1 = tf.layers.dropout(inputs=dense_P1, rate=0.5) dense_P2 = tf.layers.dense(inputs=dropout_P1, units=h_P_dim, activation=tf.nn.relu) y = tf.layers.dense(inputs=dense_P2, units=X_dim) # fix to also output y # training w = [[1, 1, 1, 0.5, 0.5, 0.5]]; recon_loss = tf.losses.mean_squared_error(labels=X, predictions=y, weights=w) # TODO: fix loss function for angles going around kl_loss = 10**-4 * 2 * tf.reduce_sum(tf.exp(z_logvar) + z_mu**2 - 1. - z_logvar, 1) cvae_loss = tf.reduce_mean(kl_loss + recon_loss) train_step = tf.train.AdamOptimizer(lr).minimize(cvae_loss) sess = tf.Session(config=config) sess.run(tf.global_variables_initializer()) it = 0; for it in range(it,it+500001): # randomly generate batches batch_elements = [randint(0,numTrain-1) for n in range(0,mb_size)] X_mb = X_train[batch_elements,:] c_mb = c_train[batch_elements,:] _, loss = sess.run([train_step, cvae_loss], feed_dict={X: X_mb, c: c_mb}) if it % 1000 == 0: print('Iter: {}'.format(it)) print('Loss: {:.4}'. format(loss)) print() # plot the latent space num_viz = 3000 vizIdx = randint(0,numTest-1); print vizIdx c_sample_seed = c_test[vizIdx,:] c_sample = np.repeat([c_sample_seed],num_viz,axis=0) c_viz = c_gapsInitGoal[vizIdx,:] # directly sample from the latent space (preferred, what we will use in the end) y_viz, z_viz = sess.run([y, z], feed_dict={z: np.random.randn(num_viz, z_dim), c: c_sample}) fig1 = plt.figure(figsize=(10,6), dpi=80) ax1 = fig1.add_subplot(111, aspect='equal') plt.scatter(y_viz[:,0],y_viz[:,1], color="green", s=70, alpha=0.1) dw = 0.1 dimW = 3 gap1 = c_viz[0:3] gap2 = c_viz[3:6] gap3 = c_viz[6:9] init = c_viz[9:15] goal = c_viz[15:21] obs1 = [0, gap1[1]-dw, -0.5, gap1[0], gap1[1], 1.5] obs2 = [gap2[0]-dw, 0, -0.5, gap2[0], gap2[1], 1.5]; obs3 = [gap2[0]-dw, gap2[1]+dw, -0.5, gap2[0], 1, 1.5]; obs4 = [gap1[0]+dw, gap1[1]-dw, -0.5, gap3[0], gap1[1], 1.5]; obs5 = [gap3[0]+dw, gap1[1]-dw, -0.5, 1, gap1[1], 1.5]; obsBounds = [-0.1, -0.1, -0.5, 0, 1.1, 1.5, -0.1, -0.1, -0.5, 1.1, 0, 1.5, -0.1, 1, -0.5, 1.1, 1.1, 1.5, 1, -0.1, -0.5, 1.1, 1.1, 1.5,] obs = np.concatenate((obs1, obs2, obs3, obs4, obs5, obsBounds), axis=0) for i in range(0,obs.shape[0]/(2*dimW)): ax1.add_patch( patches.Rectangle( (obs[i*2*dimW], obs[i*2*dimW+1]), # (x,y) obs[i*2*dimW+dimW] - obs[i*2*dimW], # width obs[i*2*dimW+dimW+1] - obs[i*2*dimW+1], # height alpha=0.6 )) for i in range(0,gridSize*gridSize): # plot occupancy grid cIdx = i + 2*dim if c_sample_seed[cIdx] == 0: plt.scatter(occGridSamples[i,0], occGridSamples[i,1], color="red", s=50, alpha=0.7) else: plt.scatter(occGridSamples[i,0], occGridSamples[i,1], color="green", s=50, alpha=0.7) plt.scatter(init[0], init[1], color="red", s=250, edgecolors='black') # init plt.scatter(goal[0], goal[1], color="blue", s=250, edgecolors='black') # goal plt.show() plt.figure(figsize=(10,6), dpi=80) viz1 = 1; viz2 = 4; plt.scatter(y_viz[:,viz1],y_viz[:,viz2], color="green", s=70, alpha=0.1) plt.scatter(c_viz[viz1+9],c_viz[viz2+9], color="red", s=250, edgecolors='black') # init plt.scatter(c_viz[viz1+9+dim],c_viz[viz2+9+dim], color="blue", s=500, edgecolors='black') # goal plt.show() ```
github_jupyter
# PyR@TE 3 : Tutorial notebook This notebook aims to provide some insight on the usage and functionalities of PyR@TE 3. Some of its content overlaps with the associated publication (available at arxiv:xx20:xxxx), but additional content is added to help in particular with the use of the Python output. Another tutorial is dedicated exclusively with the interaction with PyLie's database, that can be found in the `doc/` folder as well. Before anything else, let's make sure that we are working in PyR@TE's directory. ``` # Replace ... with the correct path on your machine %cd .../PyR@TE_3/ ``` ## 1. The model file Let's first take a look at the Standard Model model-file in `doc/SM.model`, and explain each part of it. ``` with open('doc/SM.model', 'r') as f: print(f.read()) ``` ### Gauge groups & Particle content : `GaugeGroups`, `Fermions`, `RealScalars`, `CplxScalars` The overall syntax is similar to the one in PyR@TE 2. A first difference is that quotation marks are not needed anymore around the various names and quantities. For gauge groups : `Groups: {groupName: group, groupName2: group, ...}` For fermions, we specify the number of generations as well as the quantum numbers under each of the gauge group factors. For real scalars (none here), we only need to specify the quantum numbers, either with `S:{Qnb:{ U1Y: x, SU2L: y, SU3c: z}}` or `S:{U1Y: x, SU2L: y, SU3c: z}`. Complex scalars need to be explicitely defined as the sum of a real and imaginary component. These are defined using the keyword `RealFields: [re, im]`. A value for the norm must be provided as well. In our case, the SM higgs doublet is decomposed as : \begin{equation*} H = \frac{1}{\sqrt{2}}\left(\Pi + i\,\Sigma\right) \end{equation*} Note that the value of the norm has an impact on the final expression of the beta-functions. **Important remark :** A difference with PyR@TE 2 is that the anti-particles do not need to be defined in the model file. Anti-particles are automatically defined (except for real scalars, of course) and can be accessed appending 'bar' to the name of the corresponding particle: `Q -> Qbar`, `H -> Hbar` and so on. ### Writing the Lagrangian : `Potential` As in PyR@TE 2, the Lagrangian is defined in the `Potential` section. However, the way the user has to write the Lagrangian has been widely improved in PyR@TE 3, in order to make the syntax as much intuitive and user-friendly as possible. There are two main new features : 1. The various terms are written explicitely, using their mathematical expression and the summation convention for repeated indices. 2. A new section `Definitions` was introduced to define auxiliary quantities useful to write the Lagrangian. In the SM model file, we defined the conjugated higgs field (used in the expression of the up-type quark Yukawa coupling) $\tilde{H}^i \equiv \epsilon^{i j} H^*_j$ using the following input : `Htilde[i] : Eps[i,k]*Hbar[k]`. Note that `Eps` followed by $n$ indices is internally interpreted as the Levi-Civita tensor of rank $n$. Now we are ready to define the various terms of the SM Lagrangian. For instance, in the `Yukawas` section, the up-type Yukawa couplings are written `Yu : Qbar[i,a] Htilde[i] uR[a]`, where `i` is a $SU(2)$ index ranging from 1 to 2, and `a` is the $SU(3)$ color index, ranging from 1 to 3. Similarly, the Higgs quartic term is defined as `lambda : (Hbar[i] H[i])**2`. This is a short-hand for the equivalent formulation `lambda : Hbar[i] H[i] Hbar[j] H[j]`. The order of the various indices is based on the order in which the non-abelian gauge factors were defined. Here we recall that the groups were defined as `Groups: {U1Y: U1, SU2L: SU2, SU3c: SU3}`, so the indices of `Q` and `Qbar` must be `[i_SU2L, j_SU3C]`. Any inconsistency will be detected by PyR@TE and an appropriate error will be raised (*e.g.* if we are trying to sum two indices of different nature or if the same index appears more than twice). #### Built-in quantities Some quantities are automatically available to the user to help him/her build the Lagrangian. The first one, as described above, is the Levi-Civita tensor `Eps`. A second useful possibility is to use the generators of the gauge groups. For instance, let us consider a scalar $\delta$ living in the adjoint representation of $SU(2)$. It is convenient to contract this scalar with the generators of the fundamental representation in order to get a $2\times 2$ matrix $\Delta^i_{\ j} \equiv \delta^a\, (t_a)^i_{\ j}$. The matrix $\Delta$ may be defined in the model file using the following steps : - In `Definitions`, define the generators of the fundamental rep of $SU(2)$ $\rightarrow$ `tfond : t(SU2, 2)` - Still in `Definitions`, define the matrix $\Delta$ $\rightarrow$ `Delta[i,j] : delta[a] * tfond[a,i,j]` We see in this example that the standard way to define gauge generators is `name : t(group, rep)`. The object `name` will always carry 3 indices, the first one living in the adjoint representation and the two others living in the representation `rep`. Going on with the example, we may also define `DeltaDag : deltabar[a] tfond[a,i,j]` so we are now able to write any term involving the matrix $\Delta$ and its adjoint, such as $\mathrm{Tr}(\Delta^\dagger \Delta) =$`DeltaDag[i,j] Delta[j, i]`. ### [NEW] VeVs running Another new feature is the running of vacuum-expectation values. This is done in the optional section `Vevs`. The only info to give is the name of the vev and the scalar component it is associated with. In the SM case, the vev is conventionally developped by the second component of the Higgs doublet, and is taken real. Therefore we write `v: Pi[2]`, where `Pi` was defined earlier as the real component of the complex Higgs field. Since vevs break gauge invariance, the result will be gauge-dependent. The RGEs are computed in a general $R_\xi$ gauge, but the user can fix the gauge (*i.e.* give a value to $\xi$) using the keyword `GaugeParameter`. For instance, the Feynman gauge ($\xi=1$) may be used by adding : `GaugeParameter : 1` somewhere in the model file. ### [NEW] Substitutions A new section `Substitutions` was introduced, where we may ask PyR@TE to substitute some quantities with others **after** the computation of the RGEs is done. There are several ways to take advantage of this new section : 1. **Rename some couplings**: This is useful for gauge coupling constants, whose names are automatically set to `g_[groupName]` (*e.g.* `g_SU2L`), and may pollute a bit the latex output. We can rename `g_SU2L` to `g2` simply by writing `g_SU2L: g2`. 2. **Apply a GUT normalization**: The syntax in this case is *e.g.* `g1 : sqrt(5/3) * g1`. It is important that the same coupling appears in the left- and right- hand sides. We do not define any new coupling, but simply ask for the substitution $g_1 \rightarrow \sqrt{5/3}\, g_1$ to be performed. In the output latex file, the information that we used some GUT normalization will appear. 3. **Use assumptions on the structure of Yukawa matrices**: In the case of the SM, it is frequent to neglect the off-diagonal components of the Yukawa couplings. It is also frequent to neglect all components but the 3rd generation coupling. This can be done in the `Substitutions` section. The explicit Yukawa matrices are given in the form of a Python list of lists. For instance, we can define : `Yu: [['y_up', 0, 0], [0, 'y_c', 0], [0, 0, 'y_t']]`, or, equivalently, `Yu: ['y_up', 'y_c', 'y_t']`. It is important to note that the new couplings defined in the right-hand side (`y_up`, `y_c`, `y_t`) are put inside quotation marks. Doing so, we indicate to PyR@TE that these couplings must be defined now, since they weren't defined earlier in the model file. If we wanted to neglect all couplings but the top quark's, we would have written `Yu: [0, 0, 'y_t']`. **Important remark**: Setting a coupling to 0 at some energy scale does **not** prevent it to be radiatively generated at any other energy scale. In other words, some component of a Yukawa matrix which was set to 0 in `Substitutions` can have a non-zero beta-function. In this case, a warning will be displayed in the output latex file so the user is aware of the situation. In the case of the SM, setting the off-diagonal components of all Yukawa matrices to 0 is stable along the RG flow, as well as selecting only the third generation Yukawa couplings. 4. **Define new couplings**: We may for instance want to obtain the beta-functions in terms of the gauge "structure constants" $\alpha_i \equiv g_i^2/(4\pi)$. In this case we may simply define them using *e.g.* `alpha1 : g1**2/(4 pi)`. PyR@TE will internally take care of computing the RGEs of `alpha1` based on that of `g1`, then substituting `g1**2` with `alpha1 * (4 pi)` in every beta function. ### [NEW] Latex substitutions The last section `Latex` is where we define the Latex expression of all the quantities defined in the model file. This is optional but will definitely help get a nice-looking latex output. In principle, for couplings whose names are simple Latex expressions (for instance `g_1` or `Y_u`), the substitution ($g_1$ and $Y_u$) will be performed automatically. However, these automatic replacements may sometimes lead to some unexpected behavior. Therefore, we recommand to avoid the use of Latex names and special characters in the definition of the couplings, and to explicitely define the Latex substitutions in this dedicated section of the model file. This way the user has full control on the Latex ouput. ## 2. Running PyR@TE As in PyR@TE 2, PyR@TE is run from the command line. In a shell you will have to type `python3 pyR@TE.py [-args]`, where `python3` should be replaced if needed by the correct command or path to a Python3 (&ge; v3.6) executable which is correcty linked to PyR@TE's needed dependencies (Sympy 1.5, numpy, ...). The number of possible arguments was reduced compared to the previous version. On the other hand, a configuration file was added where the user can adjust the settings of PyR@TE. Let's take a look at this file, which is called `default.settings` and can be found in PyR@TE's main repository : ``` with open('default.settings', 'r') as f: print(f.read()) ``` #### Default settings Let us explain some of the settings. The settings in boldface are those which may be overriden with the command-line arguments, as these are *default* settings: - `VerboseLevel`: can be set to `Critical` to display only errors and warning messages. The recommanded option is `Info` since it displays a lot of useful info about the progress of the computation. - **`ResultsFolder`**: The default folder in which the results are saved. - `LogFolder`: The default folder in which the log files are saved, if enabled. - **`DefaultLoopLevel`**: The loop-level up to which the RGEs are computed. Possible values for this settings will be discussed below. - **`CheckGaugeInvariance`**: Can be disabled from the command line. It is recommended to always check the gauge invariance of a newly written model once, and after each modification of the potential ! - **`RealBasis`**: Possible values are `None` (or `False`) ; `adjoint` and `all`. This will rotate the gauge generators of real representations to some real basis, where the generators are purely imaginary and antisymmetric. For adjoint representations it will also ensure that the identity $(T_a)^i_j = -i\,f_{a\ j}^{\ i}$ is satisfied. Settings this parameter to at least `adjoint` is recommended, since it helps fit the usual conventions used in Particle physics. Setting it to `all` will rotate all real representations to a real basis. - `CreateFolder`: Create a folder with the name of the model (*e.g.* "`SM/`") to store all output files. If `False` all the files will be put directly in the results folder. - `CopyModelFile`: copy the model file and put in in the result folder, to keep a trace of how the model file looked like at the time of the computation. - **`[Latex/Mathematica/Python]Output`**: These can be enable/disabled individually using command line arguments. - `GroupTheoryInfo`: Add some info about the Lie groups and their representations in the latex output. Also displays the explicit form of the Clebsch-Gordan coefficients used in the expression of the Lagrangian (if any). - `MoreGroupTheoryInfo`: If not `False`, this setting should be followed by a positive integer. When enabled, information about the first few representations of the gauge groups will be displayed. - `EndCommands`: Shell commands to be executed after the computation and the exports are done. Useful to convert the .tex file in a pdf on-the-go. The expression `[name]` will be systematically replaced by the name of the model. The commands must be put inside double quotation marks `"` and separated with a comma `,`. Here we compile the .tex file twice. #### Command-line arguments | Full name | Short-hand | Description | | ------- |-----------| --- | | `--Model` | `-m` | Specify the path to the .model file | | `--Loops` | `-l` | Specify the loop-level of the RGE computation (override the default setting) | | `--Results` | `-res` | Specify the results folder (override the default setting) | | `--Quiet` | `-q` | Only display warnings and error messages (override the default setting)| | `--no-KinMix` | `-no-kin` | Disables the effects of abelian kinetic mixing | | `--RealBasis` | `-rb` | Set the behaviour to adopt regarding real representations | The following arguments are used to enable / disable some behavior. They have the priority over the default settings. | Full name | Short-hand | | ------- |-----------| | `--CheckGaugeInvariance` | `-gi` | | | `--no-CheckGaugeInvariance` | `-no-gi` | | | `--LatexOutput` | `-tex` | | `--no-LatexOutput` | `-no-tex` | | `--MathematicaOutput` | `-math` | | `--no-MathematicaOutput` | `-no-math` | | `--PythonOutput` | `-py` | | | `--no-PythonOutput` | `-no-py` | | The loop level can be set in several different ways. - With an integer $n$ : set the loop level to $n$ for all types of couplings (if possible). - With the keyword `max`, *i.e.* `-l max`, to indicate that the computation must be performed at the highest available loop order for each coupling. - With a python list with 3 elements: **[x,y,z]**. The order of the types of couplings is **[Gauge couplings, Yukawas, quartic terms]**. For instance, `-l [3, 2, 1]` will set the running scheme to 3-loop gauge / 2-loop Yukawa / 1-loop quartics. The trilinear, scalar mass and vev terms will take the loop-level values of the quartics, and the fermion masses the looop-level of the Yukawas. A loop-level of 0 means that the RGEs will not be computed for this kind of couplings. Now let's actually run PyR@TE to compute the 2-loop RGEs of the Standard Model. We will ask the result output folder to be created in this notebook's location : `doc/`. ``` %run pyR@TE.py -m doc/SM.model -l 2 -res doc/ ``` ## 3. PyR@TE Output ### 1. Latex Output ``` from IPython.display import IFrame # The path given to IFrame uses the notebook directory as the current working dir. IFrame("SM/SM.pdf", width=800, height=800) # If this command is not working, please just go and check the .pdf output manually ``` ### 2. Mathematica output (If you do not have Mathematica installed in your machine, this output type is probably not of great interest) The Mathematica output is a .m file, which contains : 1. The expression of the beta-functions of all the couplings of the model 2. An easy-to-use differential equation solver to run the various couplings. The user needs to provide : the min and max energy scales, the initial scale and the value of the coupling at this initial scale. Running the solver will run the couplings between the min and max scale and plot the results for all the couplings which do not vanish identically over the energy range. ### 3. Python output When enabled, the python output consists in three files : `RGEs.py`, `[name].py` (here `SM.py`) and `run.py`. These files are stored in a subfolder called `PythonOutput`. The first one contains the expression of the beta-functions. The second one contain classes where the structure of the model is defined, as well as RGE solving and plotting functions. In principle the user should not need to modify the content of this file. The third file is used to call the functions defined in the former. Let's take a look at it and import its content within this notebook : ``` with open('doc/SM/PythonOuput/run.py', 'r') as f: print(f.read()) ``` To load the file in the notebook, we used the command `%load 'doc/SM/PythonOuput/run.py'` two cells below. The following steps are performed : 1. **Load the solver**, and provide it with a name (must be the same as the name of the solver, here `'rge'`) ; min and max energy scales ; and an initial scale at which the couplings will take their initial values. 2. **Set the loop-levels** (setting them to higher values than the loop-level of the PyR@TE run will have no effect) 3. **Set the initial values** 4. **Solve the RGEs** : The function `solve` can take either the argument `step` which defines the precision of the iterative differential solver (in units of Log10(GeV)) **or** the argument `Npoints`, which gives the number of integration points. 5. Finally, **plot the results**. Here are the options taken by the plot() function, along with their default values: - `figSize=(600, 600)` : The figure dimensions in pixels. - `subPlots=True` : If True, plot all the various couplings in the same window, with one subplot per type of coupling. If False, produce one figure by coupling type. - `which=None` : The user may want to plot only one or several types of couplings, and only one or several couplings. Examples of use: > `which='GaugeCouplings'` > `which=('GaugeCouplings', 'QuarticTerms')` > `which={'GaugeCouplings': 'all', 'Yukawas': ['yt', 'yb']}` > `which={'GaugeCouplings': ['g1', 'g2], 'Yukawas': 'Yu_{33}'}` - `whichNot=None` : Which coupling types are NOT to be plotted. Same usage as which. - `printLoopLevel=True/False` : The loop-levels of the computation are displayed in the title of the plots. ``` from numpy import sqrt, pi ``` Let's provide the solver with realistic initial conditions : ``` # %load 'doc/SM/PythonOuput/run.py' import sys sys.path.append('/doc/SM/PythonOuput') from SM import RGEsolver ############################################## # First, create an instance of the RGEsolver # ############################################## rge = RGEsolver('rge', tmin=1.9, tmax=20, initialScale=1.9) ########################################################## # We fix the running scheme and initial conditions below # ########################################################## # Running scheme : rge.loops = {'GaugeCouplings': 2, 'Yukawas': 2, 'QuarticTerms': 2, 'ScalarMasses': 2, 'Vevs': 2} # Gauge Couplings rge.g1.initialValue = sqrt(4*pi/128 / (1-.22)) * sqrt(5/3) rge.g2.initialValue = sqrt(4*pi/128 / .22) rge.g3.initialValue = sqrt(4*pi*.12) # Yukawa Couplings rge.yt.initialValue = .9 rge.yb.initialValue = .03 rge.ytau.initialValue = .01 # Quartic Couplings rge.lambda_.initialValue = 0.13/2 # Scalar Mass Couplings rge.mu.initialValue = sqrt(.13) * 246 # Vacuum-expectation Values rge.v.initialValue = 246 # Fix the gauge, e.g. choosing the Landau gauge rge.fixGauge(0) ############################ # Solve the system of RGEs # ############################ rge.solve(step = .05) # Another way to call rge.solve() : # rge.solve(Npoints = 500) #################### # Plot the results # #################### rge.plot(figSize=(1100, 1000), subPlots=True, printLoopLevel=True) ############################################# # Possibly save the results for a later use # ############################################# # Save the results in some file # rge.save('doc/SM/rgeResults.save') # Later, load the rge object with : # rge = RGEsolver.load('doc/SM/rgeResults.save') ``` If the user needs to access the numerical values of the running couplings, he/she simply needs to read them from the `solutions` dictionary. For instance: ``` energyValues = rge.tList lambdaValues = rge.solutions['lambda_'] print(energyValues[:20], '\n') print(lambdaValues[:20]) ``` The value of the gauge fixing parameter may be changed using the `rge.fixGauge()` function, for instance : ``` rge.fixGauge(0) ``` The rge object can be saved at any time to some file on the disk, calling the `rge.save()` function. The settings (energy scales, initial values of the couplings, running scheme) as well as the results of the previous solving will be contained in the generated file. For instance, we can do : ``` %cd doc/SM/PythonOuput/ rge.save('rgeResults.save') ``` Some time later, we can work again on the `rge` object by simply loading it from its location. Note that `load` is a static function of the class `RGEsolver`, so we call it using `RGEsolver.load()`: ``` # Load the RGE object into the variable 'rge' rge = RGEsolver.load('rgeResults.save') # Now we can work again with the RGEs rge.plot() ```
github_jupyter
# Building geological models with LoopStructural This notebook will demonstrate how to build a basic geological model using LoopStructural. You will: * Understand how to format and generate an input dataset for LoopStructural * Add faults to the model * Add unconformities to the model * Visualise the model * Export the model Additional resources: * [LoopStructural Documentation](https://loop3d.github.io/LoopStructural/) ## Implicit function The aim of implicit modelling is to find a function which represents the distance away from a reference geological horizon. There is no known analytical solution for this problem which means that they need to be approximated from the observations that are provided. We can approximate the implicit function using a weighted combination of basis functions: $f(x,y,z) = \sum^N_{i=0} v_i \varphi_i(X) $ Geological observations including the location of contacts and orientation of stratigraphy can be converted into mathematical expressions: * Observations constraining the value of the scalar field * $f(x,y,z) = v$ * Observations constraining an form surface or interface between stratigraphic units * $ \sum^N_{i=0} \sum^N_{j=i} f(x_i,y_i,z_i) - f(x_j,y_j,z_j) = 0$ * Observations constraining the magnitude of the gradient norm of the scalar field * $ \nabla f(x,y,z) = \textbf{n}$ * Observations constraining a vector to be orthogonal to the scalar field * $\nabla f(x,y,z) \cdot \textbf{t} = 0$ ## Imports for LoopStructural * To build a geological model using LoopStructural this can be done using only the `GeologicalModel` class. * To visualise the geologial model, there is a wrapper around lavavu that allows for all of the objects in the GeologicalModel to be visualised. ``` from LoopStructural import GeologicalModel from LoopStructural.visualisation import LavaVuModelViewer from LoopStructural.datasets import load_claudius data, bb = load_claudius() ``` ## LoopStructural data formatting * X - x component of the cartesian coordinates * Y - y component of the cartesian coordinates * Z - z component of the cartesian coordinates * feature_name - unique name of the geological feature being modelled * val - value observations of the scalar field * interface - unique identifier for an inteface containing similar scalar field values * nx - x component of the gradient norm * ny - y component of the gradient norm * nz - z component of the gradient norm * gx - x component of a gradient constraint * gy - y component of a gradient constraint * gz - z component of a gradient constraint * tx - x component of a gradient tangent constraint * ty - y component of a gradient tangent constraint * tz - z component of a gradient tangent constraint * coord - coordinate of the structural frame data point is used for ``` data ``` ## GeologicalModel Define the model bounding box using an origin and maximum vector. The model will be reprojected so that the origin is 0,0,0. The model can be rescaled so that the maximum length is 1 using the `rescale` flag. ``` model = GeologicalModel(bb[0,:],bb[1,:],rescale=False) ``` Link the model to the pandas DataFrame, during this set the model data will be rescaled/reprojected. ``` model.set_model_data(data) ``` LoopStructural uses a time aware approach building the geological model. This means that features in the model are added backwards in time with the youngest feature being added first. To add features to the model there are different methods that are used depending on the type of feature being modelled. * `create_and_add_foliation` is used to add a foliation (e.g. stratigraphy) * `create_and_add_fault` If there are unconformities, the default LoopStructural behaviour is to add an unconformity at the $0$ isovalue for the younger feature. ``` model.create_and_add_foliation('strati') ``` LoopStructural assembles the linear systems and determines the relationship between geological features but does not solve the linear systems. To solve the geological model, the `update` method needs to be called. ``` model.update() ``` Each `GeologicalFeature` can be accessed from the `GeologicalModel` by either accessing the feature directly `model.features[0]`, or using the index operator with the feature name e.g. `model['strati']`. The `GeologicalFeature` can be evaluated for the value or gradient of the scalar field * `evaluate_value(xyz)` which will return the scalar field value for the locations xyz * `evaluate_gradient(xyz)` which will return the gradient of the scalar field at the locations xyz Both will return `np.nan` where the scalar field is not defined. ## Visualising a model `LavaVuModelViewer` is used for visualising a LoopStructural model, it is a wrapper for lavavu and automatically processes the geological model for visualisation. A guide for the visualisation using LoopStructural is [here](https://loop3d.github.io/LoopStructural/user_guide/visualisation.html) ``` view = LavaVuModelViewer(model) view.add_isosurface(model['strati'],slices=data['val'].unique()) view.add_data(model['strati']) view.interactive() ``` ## An example with faults and an unconformity ### Generating a dataset for LoopStructural We will define two stratigraphic groups: 1. upper group which is defined by two horizons that are undulating and is unconformably overlies the lower group 2. lower group a flat surface that is faulted by a reverse fault Define the upper group by randomly generating two pointsets for a value of 0 and 1 ``` import numpy as np xx,yy = np.meshgrid(np.linspace(0,10,100),np.linspace(0,10,100)) pts = np.vstack([xx.flatten(),yy.flatten(),np.zeros_like(xx.flatten()),np.zeros_like(xx.flatten())]).T pts[:,2]+=0.05*np.sin(pts[:,0])+0.1*np.cos(pts[:,1]/2)# set the z value of the points # second surface is a copy of first surface but with bigger z value pts2 = np.copy(pts) pts2[:,2]+=1 pts2[:,3] = 1 pts = np.vstack([pts,pts2]) random_index = np.random.randint(0,len(pts),100) ``` define fault surface as a straight line at x = 5 ``` fault = np.vstack([np.zeros(10)+5,np.linspace(0,10,10),np.zeros(10)-1,np.zeros(10)]).T ``` Add these points into a pandas dataframe using the columns: * x * y * z * gx - gradient constraint x component * gy - gradient constraint y component * gz - gradient constraint z component * val - implicit function value * feature_name - identifying name for the geological feature ``` from LoopStructural.utils.helper import empty_dataframe import pandas as pd data = pd.DataFrame(columns=['X','Y','Z','val','feature_name','gx','gy','gz'])#'Xempty_dataframe() data = data.astype('float') upper_df = pd.DataFrame(pts[random_index,:],columns=['X','Y','Z','val']) upper_df['feature_name'] = 'upper' fault_df = pd.DataFrame(fault,columns=['X','Y','Z','val']) fault_df['gx'] = np.nan fault_df['gy'] = np.nan fault_df['gz'] = np.nan fault_df.loc[len(fault_df),['X','Y','Z','gx','gy','gz']] = [5.,5.,-1.,0.7,0.,0.7] fault_df['feature_name']='fault' data = pd.concat([upper_df,fault_df]) data.reset_index(inplace=True) data.loc[len(data),['X','Y','Z','gx','gy','gz','val','feature_name']] = [5.,5.,-2,.0,0,1,0,'lower'] origin = [0,0,-5] maximum = [10,10,5] model = GeologicalModel(origin,maximum,rescale=False) model.set_model_data(data) model.create_and_add_foliation('upper',interpolator_type='FDI', nelements=1e4) model.add_unconformity(model['upper'],value=0) model.create_and_add_fault('fault', 1, interpolatortype='FDI', nelements=1e5, fault_slip_vector=np.array([0.7,0.,-0.7]), fault_center=np.array([5.,5.,-1.]), fault_extent=1., fault_influence=1., fault_vertical_radius=1., buffer=0.5, solver='pyamg' ) model.create_and_add_foliation('lower',interpolator_type='FDI', nelements=1e4) model.update() ``` ## Visualisation ``` view = LavaVuModelViewer(model) view.add_isosurface(model['upper'],value=0) view.add_isosurface(model['lower'],slices=[0,-1,-2]) view.add_isosurface(model['upper'],value=1) view.add_isosurface(model['fault'],value=0) # view.add_vector_field(model['fault'][1],locations=model.regular_grid()[::100]) view.add_data(model['fault'][0]) view.add_data(model['fault'][1]) view.add_data(model['fault'][2]) view.add_data(model['upper']) view.interactive() ```
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#Python-Basics" data-toc-modified-id="Python-Basics-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Python Basics</a></div><div class="lev2 toc-item"><a href="#Imports" data-toc-modified-id="Imports-11"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Imports</a></div><div class="lev2 toc-item"><a href="#Datentypen-und-Variablen" data-toc-modified-id="Datentypen-und-Variablen-12"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Datentypen und Variablen</a></div><div class="lev2 toc-item"><a href="#List--und-Dict-Comprehensions" data-toc-modified-id="List--und-Dict-Comprehensions-13"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>List- und Dict-Comprehensions</a></div><div class="lev2 toc-item"><a href="#Benannte-Funktionen-und-anonyme-Lamda-Funktionen" data-toc-modified-id="Benannte-Funktionen-und-anonyme-Lamda-Funktionen-14"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Benannte Funktionen und anonyme Lamda-Funktionen</a></div><div class="lev1 toc-item"><a href="#Klassen-und-Objekte" data-toc-modified-id="Klassen-und-Objekte-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Klassen und Objekte</a></div><div class="lev1 toc-item"><a href="#Distanz--und-Ähnlichkeits-Messung" data-toc-modified-id="Distanz--und-Ähnlichkeits-Messung-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Distanz- und Ähnlichkeits-Messung</a></div><div class="lev2 toc-item"><a href="#Euklidische-Distanz" data-toc-modified-id="Euklidische-Distanz-31"><span class="toc-item-num">3.1&nbsp;&nbsp;</span>Euklidische Distanz</a></div><div class="lev2 toc-item"><a href="#Vergleich-von-Personendatensätzen" data-toc-modified-id="Vergleich-von-Personendatensätzen-32"><span class="toc-item-num">3.2&nbsp;&nbsp;</span>Vergleich von Personendatensätzen</a></div><div class="lev2 toc-item"><a href="#Text-Comparison" data-toc-modified-id="Text-Comparison-33"><span class="toc-item-num">3.3&nbsp;&nbsp;</span>Text Comparison</a></div><div class="lev2 toc-item"><a href="#Autoren-Ähnlichkeit-WIP" data-toc-modified-id="Autoren-Ähnlichkeit-WIP-34"><span class="toc-item-num">3.4&nbsp;&nbsp;</span>Autoren-Ähnlichkeit WIP</a></div><div class="lev1 toc-item"><a href="#Modules-&amp;-Packages" data-toc-modified-id="Modules-&amp;-Packages-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Modules &amp; Packages</a></div> # Python Basics ## Imports ``` # Standard import of library import math import spacy # Import with alias import pandas as pd ``` ## Datentypen und Variablen Python ist eine schwach typisierte Sprache. Daher müssen die Datentypen von Variablen nicht explizit angegeben werden. ``` # String (iterable, immutable) iAmAStringVariable = 'I am a string variable.' # Integer (not iterable, immutable) iAmAnInteger = 123 # Float (not iterable, immutable) iAmAnFloat = 123.456 # List (iterable, mutable, mixed) # Zugriff über den Offset-Index erfolgt über Eckige-Klammer-Notation iAmAList = [ 1, 2, 'string', 3.45, True ] iAmAList[0] # -> 1 iAmAList[2] # -> 'string' # Tuple (iterable, immutable, mixed) # Tuple können Anzahl n Einträge haben; sie sind – anders als der Name vll. # suggeriert – nicht auf zwei Einträge beschränkt. # Zugriff über den Offset-Index erfolgt über Eckige-Klammer-Notation iAmATuple = ('Key', 123) iAmAQuintuple = ('Key', 123, True, 3.45, []) iAmAQuintuple[2] # -> True # Dictionary (iterable, mutable, mixed) # Ein Dictionary ist eine Liste von Schlüssel-Wert-Paaren. # Zugriff über den Schlüssel erfolgt über Eckige-Klammer-Notation iAmADictionary = { "key_1": "value_2", "key_2": 123, "key_3": [ 1, 2, 3 ] } iAmADictionary['key_3'] # -> [ 1, 2, 3 ] # Bool (not iterable, immutable) iAmABoolean = False # Objects [class instances] (depends on implementation) #iAmAnObject = ``` ## List- und Dict-Comprehensions List- und Dict-Comprehensions verarbeiten iterierbare Datentypen und geben eine Liste bzw. ein Dictionary zurück. Sie repräsentieren einen auf eine Zeile gezogenen For-Loop. Sie werden häufig zum Säubern von Daten benutzt. List-Comprehensions ``` # Einfache List-Comprehension: # Merksatz: Transform( item ) for item in list. listOfWords = [ 'cat', 'dog', 'monkey', 'horse', 'chicken'] [ len(item) for item in listOfWords ] # -> [ 3, 3, 6, 5, 7 ] # Eine einfache If-Condition wird ans Ende der Expression gesetzt. [ item for item in [1,2,3,4,5] if item %2 == 0 ] # Eine If-Else-Condition wird hingegen direkt hiner das erste Transformations-Element der Expression gesetzt. [ print(item, 'hat einen Rest.') if item %2 != 0 else print(item, 'hat keinen Rest.') for item in [1,2,3,4,5] ]; # Wenn das Transformations-Element einer List-Comprehension wiederum selbst ein Iterable ist, # kann das Transformations-Element durch eine zweite, eingeschobene List-Comprehension ersetzt werden. # Aus Gründen von Lesbarkeit und Verständnis sollten verschachtelte List-Comprehensions mit bedacht # eingesetzt und gegebenenfalls (zum Teil) durch eundeutigere For-Loops ersetzt werden. [ [ str(i) for i in lst if i % 2 == 0 ] for lst in [[1,2,3], [4,5,6], [7,8,9]] ] # Für Dict-Comprehensions gilt im Grunde das selbe wie für List-Comprehensions. Ausnamen sind, dass sie durch # geschweifte Klammern gerahmt werden und das Transformations-Element als Schlüssel-Wert-Paar aufgebaut sein muss. { str(i): 0 for i in [1,2,3,4,5] } # Beispiele: # Ein Dictionary kann bspw. mittels einer List-Comprehension in eine Liste von Tuplen verwandelt werden. [ (i,j) for i,j in { "i": 1, "j": 2 }.items() ] # -> [ ( 'i', 1 ), ( 'j', 2 ) ] # Permutation der Elemente einer Liste von Tupeln. [ (j,i) for i,j in [ ( 'y', 'x' ), ( 'b', 'a' ) ] ] # -> [('x', 'y'), ('a', 'b')] ``` ## Benannte Funktionen und anonyme Lamda-Funktionen Benannte Funktionen werden mit einem individuellen Namen initialisiert und stehen im weiteren unter diesem Namen zur Verfügung. Anonyme oder Lamda-Funktionen hingegen müssen, um persitent verfügbar zu sein, in eine Variable gespeichert werden, oder an Ort und Stelle als _instant function_ aufgerufen werden. ``` # Benannte Funktionen werden mit dem Schlüsselwort def eingeleitet, es folgt der Funktionsname und # in runden Klammern gegebenenfalls eine Liste von Parametern, welche beim Aufruf als Argumente # übergeben werden können. def Hello(): """I am a Hello func.""" print('Hello!') return "Hello!" Hello() # Parameter können mit einem Default-Wert angegeben werden. def Greet(greeting='Hello'): """I am a Greet func.""" print(f'{greeting}!') return f'{greeting}!' Greet() Greet('Live long and prosper') # Eine anonyme oder Lambda-Funktion muss auf einer einzigen Zeile geschrieben werden – es sind also keine Loops- # oder mehrzeilige Konstrukte möglich. Eine Lambda-Funktion wird durch das Schlüsselwort lambda eingeleitet, es folgen # die Parameter; ein Doppelpunkt trennt den folgenden Rückgabewert ab. Eine Lambda-Funktion besteht also nur aus # Argumenten und einer Expression, die als Rückgabewert während der Rückgabe evaluiert wird. Damit die Funktion # mit einem Namen aufgerufen werden kann, muss sie in einer Variablen gespeichert werden. func = lambda name: f'Hello, {name}!' func('George') # Soll die Lambda-Funktion an Ort udn Stelle evaluiert werden, muss der Funktionskörper in runde Klammern # gepackt und mit direkt folgenden runden Klammern direkt mit Parametern aufgerufen werden. ( lambda name: f'Hello, {name}' )('Timmy') # Currying bedeutet, dass eine Funktion eine weitere, bereits teilweise mit Argumenten befüllte Funktion zurückgibt. # Auf diese Weise können Funktionen mit Default-Werten 'vorgeladen' werden. def Greet(phrase): return lambda name: print(f'{phrase}, {name}!') Hello = Greet('Hello') GoodMorning = Greet('Good Morning') Bye = Greet('Bye') Hello('George') GoodMorning('George') Bye('George') ``` # Klassen und Objekte Klassen sind Blaupausen die Entitäten der realen Welt schematisch und reduziert in Programmiersprachen abbilden. Klassen dienen dabei dazu Daten und Methoden, die diese Daten verarbeiten, zusammenfassen zu können. Will man eine Bibliothek modellierne, könnte jedes Buch als Klasse _Buch_ formalisiert werden. Die Klasse würde Attribute (Merkmale) wie _Buchtitel_, _ISBN_, _ausgeliehen_, u.a.m. enthalten. Methoden, also in der Klasse definierte Funktionen, könnten die Attribute ausgeben und/oder verändern, e.g. die Methode _Ausleihstatus_ würde einen String wie `f'Ausgeliehen: {self.ausgeliehen}.'` zurückgeben. Mehr zu OOP in Python, [hier](https://realpython.com/python3-object-oriented-programming/). ``` class Monkey: def __init__(self, name, color, favorite_foods): self.name = name self.color = color self.cuteness = 'Over 9000!' if type(favorite_foods) == list or type(favorite_foods) == tuple: self.favorite_foods = favorite_foods elif type(favorite_foods) == str: self.favorite_foods = [favorite_foods] else: print('Error: fav foods not set.') self.favorite_foods = [] def __repr__(self): return f'Monkey {self.name}' def __str__(self): return f'I am a monkey names {self.name} and my favorte foods are {", ".join(self.favorite_foods)}.' george = Monkey('George', 'red', ['Bananas', 'Pizza']) george # Gives __repr__ print(george) # Gives __str__ evelyn = Monkey('Evelyn', 'yellow', 'Pudding') monkeys = [ george, evelyn ] [ print(monkey) for monkey in monkeys ] print(monkeys) ``` # Distanz- und Ähnlichkeits-Messung ## Euklidische Distanz d: Euklidische-Distanz-Funktion, nimmt zwei Vektoren mit n Dimensionen an. Aufgrund der Quadrierung ist es irrelevant von welchem Punkt aus die Distanz-Messung beginnt. $d(p,q) = d(q,p) = \sqrt{\sum_{i=1}^n (q_i-p_i)^2}$ Hierbei gibt n die Anzahl der Dimensionen (columns) angibt, die einem Vektor (row) in der Matrix zukommen. Um die Distanz zweier Vektoren zu bestimmen, werden also die Werte der jeweiligen Dimensionen subtrahiert, das Ergebnis quadriert, um negative Zahlen als Ergebnis zu vermeiden, im Anschluss summiert und dann die Wurzel gezogen. Sind die zwei drei-dimensionalen Vektoren p und q als p = [1,3,2] q = [3,1,2] gegeben, dann ist die eukldidische Distanz der Vektoren $\sqrt{(1-3)^2 + (3-1)^2 + (2-2)^2} = \sqrt{(-2)^2 + (2)^2 + (0)^2} = \sqrt{4+4+0} = \sqrt{8} = 2.8284271247461903$ Durch die Quadrierung gehen große Differenzen stärker in die Abstandsberechnung ein als kleine. ``` # Euklidische Distanz als benannte Funktion def euclidianDistance(p,q, silent=False): """Calculates eucledian distance between two n-dimensional vectors. The vectors are represented as list of integers or floats. Example: euclidianDistance([1, 2],[3,4]) Distance is 2.8284271247461903.""" squares = [ (p[i] - q[i])**2 for i in range(len(p)) ] summed_squares = sum(squares) distance = math.sqrt(summed_squares) if silent == False: print(f'Distance is {distance}.') return distance euclidianDistance([1,1,1],[3,3,3]) # Euklidische Distanz als Lambda-Funktion euklid = lambda p,q: math.sqrt(sum([ (p[i] - q[i])**2 for i in range(len(p)) ])) euklid([1,1,1],[3,3,3]) # Euklidische Distanz als instantan evaluierte Lambda-Funktion (lambda p,q: math.sqrt(sum([ (p[i] - q[i])**2 for i in range(len(p)) ])))([1,1,1],[3,3,3]) p = [1,3,2] q = [3,1,2] euklid(p,q) ``` ## Vergleich von Personendatensätzen ``` # Mit der Magic-Variable % können Shell-Befehle im Notebook ausgeführt werden. %ls input/ # Ein ? vor einer Funktion oder Methode ohn () gibt Informationen dazu zurück. #?pandas.read_csv Personen = pandas.read_csv('./input/people.csv', # Pfad zur Datei sep=';', # Spalten-Trenner in der CSV decimal=",", # Dezimalzeichen skip_blank_lines=True)# Leere Zeilen überspringen Personen.head(10) # head gibt den Anfang des Dataframes aus, tail den Schluss # Auf eine oder mehrere Spalten wird in Eckiger-Klammer-Notation zugegriffen. # Ist eine Spalte gewünscht wird ein String benutzt, sind mehrere Spalten gewünscht # dann wird eine Liste von Strings erwartet. Zurückgegeben wird eine Series oder ein DataFrame. Personen['person'] Personen[['person', 'gender']] # Auf eine Row wird mittels iloc-Methode und Index in eckigen Klammern zugegriffen. Personen.iloc[4] # Die Schnittmenge kann durch Eckige-Klammern-Notation weiter eingegrenzt werden, # bis auf die Ebene einer einzigen Zelle. Personen.iloc[4]['height'] # == Personen.iloc[4].height Personen['person'].iloc[2] # Auschluss von Spalten geschieht durch droppen der entsprechenden Columns in einer Kopie des DataFrames. decimated_pers = Personen.drop(['person', 'gender'], axis=1) decimated_pers personVector = lambda index: [ float(i) for i in Personen[['education', 'family', 'income']].iloc[index].tolist() ] euclidianDistance(personVector(0), personVector(6)) for index in Personen.index.tolist(): print(Personen.iloc[index].person) for index2 in Personen.index.tolist(): euclidianDistance(vector(index), vector(index2)) # DataFrames können mittels diverser Methoden wieder in Dateien geschrieben werden. decimated_pers.to_csv('./output/deciated.csv', sep=';', quotechar='"', quoting=1, index=False) ``` ## Text Comparison ``` txt_0 = "I am a really cute dog. I like jumping." txt_1 = "I am a really nice cat. I like to cuddle." txt_2 = "I am a really cute dog. I liked to jump." txt_3 = "You are a really cute cat. You like to cuddle." txt_4 = "You were a really nice dog and you liked cuddling." txt_5 = "You are a really nice cat. You like to cuddle." nlp = spacy.load('en') docs = list(nlp.pipe([txt_0, txt_1, txt_2, txt_3, txt_4, txt_5])) def buildBagOfWords(docs): global_lemmata = [] [[ global_lemmata.append(token.lemma_) if token.lemma_ != '-PRON-' else global_lemmata.append(token.orth_) for token in doc ] for doc in docs ]; bagOfWords = { lemma: [] for lemma in list(set(global_lemmata)) } lemmatized_texts = [[ token.lemma_ if token.lemma_ != '-PRON-' else token.orth_ for token in doc ] for doc in docs ] for lemma in list(set(global_lemmata)): for text in lemmatized_texts: bagOfWords[lemma].append(text.count(lemma)) return bagOfWords words = buildBagOfWords(docs) texts_df = pandas.DataFrame.from_dict(words) texts_df.head(10) vector = lambda index, df: df.iloc[index].tolist() euclidianDistance(vector(0, texts_df), vector(2, texts_df)) def buildCrossMatrix(texts_df,silent=True): crossMatrix = { str(i): [] for i in texts_df.index.tolist() } for i in texts_df.index.tolist(): for z in texts_df.index.tolist(): distance = euclidianDistance(vector(i, texts_df), vector(z, texts_df), silent) crossMatrix[str(i)].append(distance) cross_df = pandas.DataFrame.from_dict(crossMatrix) cross_df.head() return cross_df buildCrossMatrix(texts_df) buildCrossMatrix(PersonenDatensatz[['height', 'skin', 'hair', 'education', 'income', 'family']]) ``` ## Autoren-Ähnlichkeit WIP ``` word_length = { str(i): 0 for i in range(1, max([ max([ len(token.lemma_) if token.lemma_ != '-PRON-' else len(token.orth_) for token in doc ]) for doc in docs ])+1)} word_length for token in docs[0]: if token.lemma_ != '-PRON-': word_length[str(len(token.lemma_))] += 1 else: word_length[str(len(token.orth_))] += 1 word_length ``` # Modules & Packages ``` import sys import importlib # Die Package-Ordner, e.g. distance, liegen im Ordner 'modules'. # Die Python-Code-Datei 'distances.py' liegt im Ordner 'distance'. # sys.path.append(r'./modules/') # print(sys.path) # Aus dem Ordner 'distance' importiere die Datei 'distances'. from modules.distance import distances importlib.reload(distances) distance = distances.Distance() distance.euclidianDistance([1, 2],[3,4]) distance.helloWorld() ?distance.euclidianDistance ```
github_jupyter
# Download Data and Preprocess Data and Upload to kaggle dataset 1. In this notebook you are going to download data from zindi 2. Extract all the .zip files 3. Convert all train & test .wav files to 32k sample_rate 4. Upload dataset to kaggle for easy download for every notebook ### 1. Download data from zindi ``` %%time import requests, os import requests, zipfile os.makedirs("input") #the url and auth_value from the website url = 'https://api.zindi.africa/v1/competitions/giz-nlp-agricultural-keyword-spotter/files/Train.csv' myobj = {'auth_token': '11fL6uBPAEnz1q4m1iXxJbMp'} #use your own x = requests.post(url, data = myobj,stream=True) target_path = 'input/Train.csv' handle = open(target_path, "wb") for chunk in x.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() #the url and auth_value from the website url = 'https://api.zindi.africa/v1/competitions/giz-nlp-agricultural-keyword-spotter/files/SampleSubmission.csv' myobj = {'auth_token': '11fL6uBPAEnz1q4m1iXxJbMp'} #use your own x = requests.post(url, data = myobj,stream=True) target_path = 'input/SampleSubmission.csv' handle = open(target_path, "wb") for chunk in x.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() #the url and auth_value from the website url = 'https://api.zindi.africa/v1/competitions/giz-nlp-agricultural-keyword-spotter/files/audio_files.zip' myobj = {'auth_token': '11fL6uBPAEnz1q4m1iXxJbMp'} #use your own x = requests.post(url, data = myobj,stream=True) target_path = 'input/audio_files.zip' handle = open(target_path, "wb") for chunk in x.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() #the url and auth_value from the website url = 'https://api.zindi.africa/v1/competitions/giz-nlp-agricultural-keyword-spotter/files/AdditionalUtterances.zip' myobj = {'auth_token': '11fL6uBPAEnz1q4m1iXxJbMp'} #use your own x = requests.post(url, data = myobj,stream=True) target_path = 'input/AdditionalUtterances.zip' handle = open(target_path, "wb") for chunk in x.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() #the url and auth_value from the website url = 'https://api.zindi.africa/v1/competitions/giz-nlp-agricultural-keyword-spotter/files/nlp_keywords_29Oct2020.zip' myobj = {'auth_token': '11fL6uBPAEnz1q4m1iXxJbMp'} #use your own x = requests.post(url, data = myobj,stream=True) target_path = 'input/nlp_keywords_29Oct2020.zip' handle = open(target_path, "wb") for chunk in x.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) handle.close() ``` ### 2.Extract all zipfiles ``` !unzip -q "input/audio_files.zip" -d "input" !unzip -q "input/AdditionalUtterances.zip" -d "input" !unzip -q "input/nlp_keywords_29Oct2020.zip" -d "input" ``` ### 3.convert audio files to 32k sample rate ``` !pip -q install soundfile import os, random, glob import numpy as np, pandas as pd import librosa import soundfile as sf from tqdm.auto import tqdm train = pd.read_csv("input/Train.csv") sample_submission = pd.read_csv("input/SampleSubmission.csv") # move all training data to "input/audio_train" # move all test data to "input/audio_test" os.makedirs("input/audio_train", exist_ok=True) os.makedirs("input/audio_test", exist_ok=True) # convert all train data to 32k sample rate target_sr = 32000 for f, label in tqdm(zip(train.fn.values, train.label.values), total=len(train.fn.values)): os.makedirs(f"input/audio_train/{label}", exist_ok=True) f_name = f.split("/")[-1] y, sr = librosa.load(f"input/{f}", sr=target_sr) sf.write(f"input/audio_train/{label}/{f_name}", y, samplerate=target_sr) # convert all test data to 32k sample rate target_sr = 32000 for f in tqdm(sample_submission.fn.values): f_name = f.split("/")[-1] y, sr = librosa.load(f"input/{f}", sr=target_sr) sf.write(f"input/audio_test/{f_name}", y, samplerate=target_sr) ## latest_keywords latest_keywords = glob.glob("input/latest_keywords/*/*.wav") for f in tqdm(latest_keywords): label = f.split("/")[-2] f_name = f.split("/")[-1] os.makedirs(f"input/audio_train/{label}", exist_ok=True) y, sr = librosa.load(f, sr=target_sr) sf.write(f"input/audio_train/{label}/{f_name}", y, samplerate=target_sr) ## nlp_keywords nlp_keywords = glob.glob("input/nlp_keywords/*/*.wav") for f in tqdm(nlp_keywords): label = f.split("/")[-2] f_name = f.split("/")[-1] os.makedirs(f"input/audio_train/{label}", exist_ok=True) y, sr = librosa.load(f, sr=target_sr) sf.write(f"input/audio_train/{label}/{f_name}", y, samplerate=target_sr) train_wav = glob.glob("input/audio_train/*/*.wav") len(train_wav) # create train dataframe train_df = pd.DataFrame({ "fn" : train_wav, }) train_df["label"] = train_df.fn.apply(lambda x: x.split("/")[-2]) train_df.head() ``` ### 4.Upload those files to kaggle dataset so its easy to download every time - for uploading to kaggle datasets we need to have kaggle account - for more detalils https://www.kaggle.com/docs/api - i made this dataset to public after end of this compitation ``` # make sure your kaggle api "kaggle.json" file in your drive ! mkdir /root/.kaggle ! cp '/content/drive/My Drive/kaggle.json' /root/.kaggle # <---- path for kaggle.json file ! chmod 400 /root/.kaggle/kaggle.json !pip uninstall -y kaggle >> quit !pip install --upgrade pip >> quit !pip install kaggle==1.5.6 >> quit !kaggle -v >> quit !mkdir "dataset" !zip -r "audio_train.zip" "input/audio_train" >> quit !zip -r "dataset/audio_test.zip" "input/audio_test" >> quit !cp "input/SampleSubmission.csv" "dataset" data = '''{ "title": "giz-nlp-agricultural-keyword-spotter", "id": "gopidurgaprasad/giz-nlp-agricultural-keyword-spotter", "licenses": [ { "name": "CC0-1.0" } ] } ''' text_file = open("dataset/dataset-metadata.json", 'w+') n = text_file.write(data) text_file.close() !kaggle datasets create -p "dataset" ```
github_jupyter
# Comparison of clustering of node embeddings with a traditional community detection method <table><tr><td>Run the latest release of this notebook:</td><td><a href="https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/community_detection/attacks_clustering_analysis.ipynb" alt="Open In Binder" target="_parent"><img src="https://mybinder.org/badge_logo.svg"/></a></td><td><a href="https://colab.research.google.com/github/stellargraph/stellargraph/blob/master/demos/community_detection/attacks_clustering_analysis.ipynb" alt="Open In Colab" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg"/></a></td></tr></table> ## Introduction The goal of this use case is to demonstrate how node embeddings from graph convolutional neural networks trained in unsupervised manner are comparable to standard community detection methods based on graph partitioning. Specifically, we use unsupervised [graphSAGE](http://snap.stanford.edu/graphsage/) approach to learn node embeddings of terrorist groups in a publicly available dataset of global terrorism events, and analyse clusters of these embeddings. We compare the clusters to communities produced by [Infomap](http://www.mapequation.org), a state-of-the-art approach of graph partitioning based on information theory. We argue that clustering based on unsupervised graphSAGE node embeddings allow for richer representation of the data than its graph partitioning counterpart as the former takes into account node features together with the graph structure, while the latter utilises only the graph structure. We demonstrate, using the terrorist group dataset, that the infomap communities and the graphSAGE embedding clusters (GSEC) provide qualitatively different insights into underlying data patterns. ### Data description __The Global Terrorism Database (GTD)__ used in this demo is available here: https://www.kaggle.com/START-UMD/gtd. GTD is an open-source database including information on terrorist attacks around the world from 1970 through 2017. The GTD includes systematic data on domestic as well as international terrorist incidents that have occurred during this time period and now includes more than 180,000 attacks. The database is maintained by researchers at the National Consortium for the Study of Terrorism and Responses to Terrorism (START), headquartered at the University of Maryland. For information refer to the initial data source: https://www.start.umd.edu/gtd/. Full dataset contains information on more than 180,000 Terrorist Attacks. ### Glossary: For this particular study we adopt the following terminology: - __a community__ is a group of nodes produced by a traditional community detection algorithm (infomap community in this use case) - __a cluster__ is a group of nodes that were clustered together using a clustering algorithm applied to node embeddings (here, [DBSCAN clustering](https://www.aaai.org/Papers/KDD/1996/KDD96-037.pdf) applied to unsupervised GraphSAGE embeddings). For more detailed explanation of unsupervised graphSAGE see [Unsupervised graphSAGE demo](../embeddings/graphsage-unsupervised-sampler-embeddings.ipynb). The rest of the demo is structured as follows. First, we load the data and preprocess it (see `utils.py` for detailed steps of network and features generation). Then we apply infomap and visualise results of one selected community obtained from this method. Next, we apply unsupervised graphSAGE on the same data and extract node embeddings. We first tune DBSCAN hyperparameters, and apply DBSCAN that produces sufficient numbers of clusters with minimal number of noise points. We look at the resulting clusters, and investigate a single selected cluster in terms of the graph structure and features of the nodes in this cluster. Finally, we conclude our investigation with the summary of the results. ``` # install StellarGraph if running on Google Colab import sys if 'google.colab' in sys.modules: %pip install -q stellargraph[demos]==1.3.0b # verify that we're using the correct version of StellarGraph for this notebook import stellargraph as sg try: sg.utils.validate_notebook_version("1.3.0b") except AttributeError: raise ValueError( f"This notebook requires StellarGraph version 1.3.0b, but a different version {sg.__version__} is installed. Please see <https://github.com/stellargraph/stellargraph/issues/1172>." ) from None import pandas as pd import numpy as np import networkx as nx import igraph as ig from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn import preprocessing, feature_extraction, model_selection from sklearn.decomposition import PCA from sklearn.manifold import TSNE import random import matplotlib.pyplot as plt from matplotlib.pyplot import figure %matplotlib inline import warnings warnings.filterwarnings('ignore') # supress warnings due to some future deprications import stellargraph as sg from stellargraph.data import EdgeSplitter from stellargraph.mapper import GraphSAGELinkGenerator, GraphSAGENodeGenerator from stellargraph.layer import GraphSAGE, link_classification from stellargraph.data import UniformRandomWalk from stellargraph.data import UnsupervisedSampler from sklearn.model_selection import train_test_split from tensorflow import keras from stellargraph import globalvar import mplleaflet from itertools import count import utils ``` ### Data loading This is the raw data of terrorist attacks that we use as a starting point of our analysis. ``` dt_raw = pd.read_csv( "~/data/globalterrorismdb_0718dist.csv", sep=",", engine="python", encoding="ISO-8859-1", ) ``` ### Loading preprocessed features The resulting feature set is the aggregation of features for each of the terrorist groups (`gname`). We collect such features as total number of attacks per terrorist group, number of perpetrators etc. We use `targettype` and `attacktype` (number of attacks/targets of particular type) and transform it to a wide representation of data (e.g each type is a separate column with the counts for each group). Refer to `utils.py` for more detailed steps of the preprocessing and data cleaning. ``` gnames_features = utils.load_features(input_data=dt_raw) gnames_features.head() ``` ### Edgelist creation The raw dataset contains information for the terrotist attacks. It contains information about some incidents being related. However, the resulting graph is very sparse. Therefore, we create our own schema for the graph, where two terrorist groups are connected, if they had at least one terrorist attack in the same country and in the same decade. To this end we proceed as follows: - we group the event data by `gname` - the names of the terrorist organisations. - we create a new feature `decade` based on `iyear`, where one bin consists of 10 years (attacks of 70s, 80s, and so on). - we add the concatination of of the decade and the country of the attack: `country_decade` which will become a link between two terrorist groups. - finally, we create an edgelist, where two terrorist groups are linked if they have operated in the same country in the same decade. Edges are undirected. In addition, some edges are created based on the column `related` in the raw event data. The description of the data does not go into details how these incidents were related. We utilise this information creating a link for terrorist groups if the terrorist attacks performed by these groups were related. If related events corresponded to the same terrorist group, they were discarded (we don't use self-loops in the graph). However, the majority of such links are already covered by `country_decade` edge type. Refer to `utils.py` for more information on graph creation. ``` G = utils.load_network(input_data=dt_raw) print(nx.info(G)) ``` ### Connected components of the network Note that the graph is disconnected, consisting of 21 connected components. ``` print(nx.number_connected_components(G)) ``` Get the sizes of the connected components: ``` Gcc = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True) cc_sizes = [] for cc in list(Gcc): cc_sizes.append(len(cc.nodes())) print(cc_sizes) ``` The distribution of connected components' sizes shows that there is a single large component, and a few isolated groups. We expect the community detection/node embedding clustering algorithms discussed below to discover non-trivial communities that are not simply the connected components of the graph. ## Traditional community detection We perform traditional community detection via `infomap` implemented in `igraph`. We translate the original `networkx` graph object to `igraph`, apply `infomap` to it to detect communities, and assign the resulting community memberships back to the `networkx` graph. ``` # translate the object into igraph g_ig = ig.Graph.Adjacency( (nx.to_numpy_matrix(G) > 0).tolist(), mode=ig.ADJ_UNDIRECTED ) # convert via adjacency matrix g_ig.summary() # perform community detection random.seed(123) c_infomap = g_ig.community_infomap() print(c_infomap.summary()) ``` We get 160 communities, meaning that the largest connected components of the graph are partitioned into more granular groups. ``` # plot the community sizes infomap_sizes = c_infomap.sizes() plt.title("Infomap community sizes") plt.xlabel("community id") plt.ylabel("number of nodes") plt.bar(list(range(1, len(infomap_sizes) + 1)), infomap_sizes) # Modularity metric for infomap c_infomap.modularity ``` The discovered infomap communities have smooth distribution of cluster sizes, which indicates that the underlying graph structure has a natural partitioning. The modularity score is also pretty high indicating that nodes are more tightly connected within clusters than expected from random graph, i.e., the discovered communities are tightly-knit. ``` # assign community membership results back to networkx, keep the dictionary for later comparisons with the clustering infomap_com_dict = dict(zip(list(G.nodes()), c_infomap.membership)) nx.set_node_attributes(G, infomap_com_dict, "c_infomap") ``` ### Visualisation of the infomap communities We can visualise the resulting communities using maps as the constructed network is based partially on the geolocation. The raw data have a lat-lon coordinates for each of the attacks. Terrorist groups might perform attacks in different locations. However, currently the simplified assumption is made, and the average of latitude and longitude for each terrorist group is calculated. Note that it might result in some positions being "off", but it is good enough to provide a glimpse whether the communities are consistent with the location of that groups. ``` # fill NA based on the country name dt_raw.latitude[ dt_raw["gname"] == "19th of July Christian Resistance Brigade" ] = 12.136389 dt_raw.longitude[ dt_raw["gname"] == "19th of July Christian Resistance Brigade" ] = -86.251389 # filter only groups that are present in a graph dt_filtered = dt_raw[dt_raw["gname"].isin(list(G.nodes()))] # collect averages of latitude and longitude for each of gnames avg_coords = dt_filtered.groupby("gname")[["latitude", "longitude"]].mean() print(avg_coords.shape) print(len(G.nodes())) ``` As plotting the whole graph is not feasible, we investigate a single community __Specify community id in the range of infomap total number of clusters__ (`len(infomap_sizes)`) ``` com_id = 50 # smaller number - larger community, as it's sorted # extraction of a subgraph from the nodes in this community com_G = G.subgraph( [n for n, attrdict in G.nodes.items() if attrdict["c_infomap"] == com_id] ) print(nx.info(com_G)) # plot community structure only pos = nx.random_layout(com_G, seed=123) plt.figure(figsize=(10, 8)) nx.draw_networkx(com_G, pos, edge_color="#26282b", node_color="blue", alpha=0.3) plt.axis("off") plt.show() # plot on the map nodes = com_G.nodes() com_avg_coords = avg_coords[avg_coords.index.isin(list(nodes))] com_avg_coords.fillna( com_avg_coords.mean(), inplace=True ) # fill missing values with the average new_order = [1, 0] com_avg_coords = com_avg_coords[com_avg_coords.columns[new_order]] pos = com_avg_coords.T.to_dict("list") # layout is based on the provided coordindates fig, ax = plt.subplots(figsize=(12, 6)) nx.draw_networkx_edges(com_G, pos, edge_color="grey") nx.draw_networkx_nodes( com_G, pos, nodelist=nodes, with_labels=True, node_size=200, alpha=0.5 ) nx.draw_networkx_labels(com_G, pos, font_color="#362626", font_size=50) mplleaflet.display(fig=ax.figure) ``` (**N.B.:** the above interactive plot will only appear after running the cell, and is not rendered in GitHub!) ### Summary of results based on infomap Infomap is a robust community detection algorithm, and shows good results that are in line with the expectations. Most of the communities are tightly connected and reflect the geographical position of the events of the terrorist groups. That is because the graph schema is expressed as > _two terrorist groups are connected if they have terrorist events in the same country in the same decade_. However, no node features are taken into account in the case of the traditional community detection. Next, we explore the GSEC approach, where node features are used along with the graph structure. ## Node represenatation learning with unsupervised graphSAGE Now we apply unsupervised GraphSAGE that takes into account node features as well as graph structure, to produce *node embeddings*. In our case, similarity of node embeddings depicts similarity of the terrorist groups in terms of their operations, targets and attack types (node features) as well as in terms of time and place of attacks (graph structure). ``` # we reload the graph to get rid of assigned attributes G = utils.load_network(input_data=dt_raw) # to make sure that graph is clean # filter features to contain only gnames that are among nodes of the network filtered_features = gnames_features[gnames_features["gname"].isin(list(G.nodes()))] filtered_features.set_index("gname", inplace=True) filtered_features.shape filtered_features.head() # take a glimpse at the feature data ``` We perform a log-transform of the feature set to rescale feature values. ``` # transforming features to be on log scale node_features = filtered_features.transform(lambda x: np.log1p(x)) # sanity check that there are no misspelled gnames left set(list(G.nodes())) - set(list(node_features.index.values)) ``` ### Unsupervised graphSAGE (For a detailed unsupervised GraphSAGE workflow with a narrative, see [Unsupervised graphSAGE demo](../embeddings/graphsage-unsupervised-sampler-embeddings.ipynb)) ``` Gs = sg.StellarGraph.from_networkx(G, node_features=node_features) print(Gs.info()) # parameter specification number_of_walks = 3 length = 5 batch_size = 50 epochs = 10 num_samples = [20, 20] layer_sizes = [100, 100] learning_rate = 1e-2 unsupervisedSamples = UnsupervisedSampler( Gs, nodes=G.nodes(), length=length, number_of_walks=number_of_walks ) generator = GraphSAGELinkGenerator(Gs, batch_size, num_samples) train_gen = generator.flow(unsupervisedSamples) assert len(layer_sizes) == len(num_samples) graphsage = GraphSAGE( layer_sizes=layer_sizes, generator=generator, bias=True, dropout=0.0, normalize="l2" ) ``` We now build a Keras model from the GraphSAGE class that we can use for unsupervised predictions. We add a `link_classfication` layer as unsupervised training operates on node pairs. ``` x_inp, x_out = graphsage.in_out_tensors() prediction = link_classification( output_dim=1, output_act="sigmoid", edge_embedding_method="ip" )(x_out) model = keras.Model(inputs=x_inp, outputs=prediction) model.compile( optimizer=keras.optimizers.Adam(lr=learning_rate), loss=keras.losses.binary_crossentropy, metrics=[keras.metrics.binary_accuracy], ) history = model.fit( train_gen, epochs=epochs, verbose=2, use_multiprocessing=False, workers=1, shuffle=True, ) ``` ### Extracting node embeddings ``` node_ids = list(Gs.nodes()) node_gen = GraphSAGENodeGenerator(Gs, batch_size, num_samples).flow(node_ids) embedding_model = keras.Model(inputs=x_inp[::2], outputs=x_out[0]) node_embeddings = embedding_model.predict(node_gen, workers=4, verbose=1) ``` #### 2D t-sne plot of the resulting node embeddings Here we visually check whether embeddings have some underlying cluster structure. ``` node_embeddings.shape # TSNE visualisation to check whether the embeddings have some structure: X = node_embeddings if X.shape[1] > 2: transform = TSNE # PCA trans = transform(n_components=2, random_state=123) emb_transformed = pd.DataFrame(trans.fit_transform(X), index=node_ids) else: emb_transformed = pd.DataFrame(X, index=node_ids) emb_transformed = emb_transformed.rename(columns={"0": 0, "1": 1}) alpha = 0.7 fig, ax = plt.subplots(figsize=(7, 7)) ax.scatter(emb_transformed[0], emb_transformed[1], alpha=alpha) ax.set(aspect="equal", xlabel="$X_1$", ylabel="$X_2$") plt.title("{} visualization of GraphSAGE embeddings".format(transform.__name__)) plt.show() ``` #### t-sne colored by infomap We also depict the same t-sne plot colored by infomap communities. As we can observe t-sne of GraphSAGE embeddings do not really separate the infomap communities. ``` emb_transformed["infomap_clusters"] = emb_transformed.index.map(infomap_com_dict) plt.scatter( emb_transformed[0], emb_transformed[1], c=emb_transformed["infomap_clusters"], cmap="Spectral", edgecolors="black", alpha=0.3, s=100, ) plt.title("t-sne with colors corresponding to infomap communities") ``` Next, we apply dbscan algorithm to cluster the embeddings. dbscan has two hyperparameters: `eps` and `min_samples`, and produces clusters along with the noise points (the points that could not be assigned to any particular cluster, indicated as -1). These tunable parameters directly affect the cluster results. We use greedy search over the hyperparameters and check what are the good candidates. ``` db_dt = utils.dbscan_hyperparameters( node_embeddings, e_lower=0.1, e_upper=0.9, m_lower=5, m_upper=15 ) # print results where there are more clusters than 1, and sort by the number of noise points db_dt.sort_values(by=["n_noise"])[db_dt.n_clusters > 1] ``` Pick the hyperparameters, where the clustering results have as little noise points as possible, but also create number of clusters of reasonable size. ``` # perform dbscan with the chosen parameters: db = DBSCAN(eps=0.1, min_samples=5).fit(node_embeddings) ``` Calculating the clustering statistics: ``` labels = db.labels_ # Number of clusters in labels, ignoring noise if present. n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) n_noise_ = list(labels).count(-1) print("Estimated number of clusters: %d" % n_clusters_) print("Estimated number of noise points: %d" % n_noise_) print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(node_embeddings, labels)) ``` We plot t-sne again but with the colours corresponding to dbscan points. ``` emb_transformed["dbacan_clusters"] = labels X = emb_transformed[emb_transformed["dbacan_clusters"] != -1] plt.scatter( X[0], X[1], c=X["dbacan_clusters"], cmap="Spectral", edgecolors="black", alpha=0.3, s=100, ) plt.title("t-sne with colors corresponding to dbscan cluster. Without noise points") ``` ### Investigating GSEC and infomap qualitative differences Let's take a look at the resulting GSEC clusters, and explore, as an example, one particular cluster of a reasonable size, which is not a subset of any single infomap community. Display cluster sizes for first 15 largest clusters: ``` clustered_df = pd.DataFrame(node_embeddings, index=node_ids) clustered_df["cluster"] = db.labels_ clustered_df.groupby("cluster").count()[0].sort_values(ascending=False)[0:15] ``` We want to display clusters that differ from infomap communities, as they are more interesting in this context. Therefore we calculate for each DBSCAN cluster how many different infomap communities it contains. The results are displayed below. ``` inf_db_cm = clustered_df[["cluster"]] inf_db_cm["infomap"] = inf_db_cm.index.map(infomap_com_dict) dbscan_different = inf_db_cm.groupby("cluster")[ "infomap" ].nunique() # if 1 all belong to same infomap cluster # show only those clusters that are not the same as infomap dbscan_different[dbscan_different != 1] ``` For example, DBSCAN `cluster_12` has nodes that were assigned to 2 different infomap clusters, while `cluster_31` has nodes from 8 different infomap communities. ### Single cluster visualisation Now that we've selected a GSEC cluster (id=20) of reasonable size that contains nodes belonging to 4 different infomap communities, let's explore it. __To visualise a particular cluster, specify its number here:__ ``` # specify the cluster id here: cluster_id = 20 # manually look at the terrorist group names list(clustered_df.index[clustered_df.cluster == cluster_id]) # create a subgraph from the nodes in the cluster cluster_G = G.subgraph(list(clustered_df.index[clustered_df.cluster == cluster_id])) ``` List for each of the `gname` (terrorist group name) in the cluster the assigned infomap community id. This shows whether the similar community was produced by infomap or not. ``` comparison = { k: v for k, v in infomap_com_dict.items() if k in list(clustered_df.index[clustered_df.cluster == cluster_id]) } comparison ``` As another metric of clustering quality, we display how many edges are inside this cluster vs how many nodes are going outside (only one of edge endpoints is inside a cluster) ``` external_internal_edges = utils.cluster_external_internal_edges(G, inf_db_cm, "cluster") external_internal_edges[external_internal_edges.cluster == cluster_id] # plot the structure only pos = nx.fruchterman_reingold_layout(cluster_G, seed=123, iterations=30) plt.figure(figsize=(10, 8)) nx.draw_networkx(cluster_G, pos, edge_color="#26282b", node_color="blue", alpha=0.3) plt.axis("off") plt.show() ``` Recall that terrorist groups (nodes) are connected, when at least one of the attacks was performed in the same decade in the same country. Therefore the connectivity indicates spatio-temporal similarity. There are quite a few clusters that are similar to infomap clusters. We pick a cluster that is not a subset of any single infomap community. We can see that there are disconnected groups of nodes in this cluster. So why are these disconnected components combined into one cluster? GraphSAGE embeddings directly depend on both node features and an underlying graph structure. Therefore, it makes sense to investigate similarity of features of the nodes in the cluster. It can highlight why these terrorist groups are combined together by GSEC. ``` cluster_feats = filtered_features[ filtered_features.index.isin( list(clustered_df.index[clustered_df.cluster == cluster_id]) ) ] # show only non-zero columns features_nonzero = cluster_feats.loc[:, (cluster_feats != 0).any()] features_nonzero.style.background_gradient(cmap="RdYlGn_r") ``` We can see that most of the isolated nodes in the cluster have features similar to those in the tight clique, e.g., in most cases they have high number of attacks, high success ratio, and attacks being focused mostly on bombings, and their targets are often the police. Note that there are terrorist groups that differ from the rest of the groups in the cluster in terms of their features. By taking a closer look we can observe that these terrorist groups are a part of a tight clique. For example, _Martyr al-Nimr Battalion_ has number of bombings equal to 0, but it is a part of a fully connected subgraph. Interestingly, _Al-Qaida in Saudi Arabia_ ends up in the same cluster as _Al-Qaida in Yemen_, though they are not connected directly in the network. Thus we can observe that clustering on GraphSAGE embeddings combines groups based both on the underlying structure as well as features. ``` nodes = cluster_G.nodes() com_avg_coords = avg_coords[avg_coords.index.isin(list(nodes))] new_order = [1, 0] com_avg_coords = com_avg_coords[com_avg_coords.columns[new_order]] com_avg_coords.fillna( com_avg_coords.mean(), inplace=True ) # fill missing values with the average pos = com_avg_coords.T.to_dict("list") # layout is based on the provided coordindates fig, ax = plt.subplots(figsize=(22, 12)) nx.draw_networkx_nodes( cluster_G, pos, nodelist=nodes, with_labels=True, node_size=200, alpha=0.5 ) nx.draw_networkx_labels(cluster_G, pos, font_color="red", font_size=50) nx.draw_networkx_edges(cluster_G, pos, edge_color="grey") mplleaflet.display(fig=ax.figure) ``` (**N.B.:** the above interactive plot will only appear after running the cell, and is not rendered in GitHub!) These groups are also very closely located, but in contrast with infomap, this is not the only thing that defines the clustering groups. #### GSEC results What we can see from the results above is a somehow different picture from the infomap (note that by rerunning this notebook, the results might change due to the nature of the GraphSAGE predictions). Some clusters are identical to the infomap, showing that GSEC __capture__ the network structure. But some of the clusters differ - they are not necessary connected. By observing the feature table we can see that it has terrorist groups with __similar characteristics__. ## Conclusion In this use case we demonstrated the conceptual differences of traditional community detection and unsupervised GraphSAGE embeddings clustering (GSEC) on a real dataset. We can observe that the traditional approach to the community detection via graph partitioning produces communities that are related to the graph structure only, while GSEC combines the features and the structure. However, in the latter case we should be very conscious of the network schema and the features, as these significantly affect both the clustering and the interpretation of the resulting clusters. For example, if we don't want the clusters where neither number of kills nor country play a role, we might want to exclude `nkills` from the feature set, and create a graph, where groups are connected only via the decade, and not via country. Then, the resulting groups would probably be related to the terrorist activities in time, and grouped by their similarity in their target and the types of attacks. <table><tr><td>Run the latest release of this notebook:</td><td><a href="https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/community_detection/attacks_clustering_analysis.ipynb" alt="Open In Binder" target="_parent"><img src="https://mybinder.org/badge_logo.svg"/></a></td><td><a href="https://colab.research.google.com/github/stellargraph/stellargraph/blob/master/demos/community_detection/attacks_clustering_analysis.ipynb" alt="Open In Colab" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg"/></a></td></tr></table>
github_jupyter
# Handling Text Data Below are a few examples of how to play with text data. We'll walk through some exercises in class with this! ``` import pandas as pd text_data = pd.read_csv("pa3_orig/Bills Mafia.csv") text_data.head() documents = [t for t in text_data.text] documents[0] from sklearn.feature_extraction.text import CountVectorizer def fit_vectorizer(vectorizer, sample_doc_index=0, documents= documents): X = vectorizer.fit_transform(documents) features = vectorizer.get_feature_names() print(len(vectorizer.get_feature_names())) print("First ten features: {}".format(", ".join(features[:10]))) print("Sample Doc: {}".format(documents[sample_doc_index])) print("Sample Doc Features: {}".format(", ".join([features[i] for i in X[doc_index].nonzero()[1]]))) return X, features X, features = fit_vectorizer(CountVectorizer(analyzer='word')) ``` Things we also might thing we want: - Filtering out stuff (what? Why?) - Characters instead of words (why?) - Ngrams (huh? Why?) - ... what else? ``` X, features = fit_vectorizer(CountVectorizer(analyzer="word", ngram_range=(1, 3), min_df=10, max_df=0.75, stop_words='english')) char_vectorizer = CountVectorizer(analyzer='char', ngram_range=(2, 6), min_df=10, max_df=0.75) X, features = fit_vectorizer(char_vectorizer) import spacy nlp = spacy.load("en_core_web_sm") def spacy_tokenizer(tweet): return ["{}".format(c.lemma_) for c in nlp(tweet)] vectorizer = CountVectorizer(tokenizer=spacy_tokenizer) X, features = fit_vectorizer(vectorizer) ``` # Dimensionality Reduction ## Toy Example (from Varun) ``` import numpy as np import math import matplotlib.pyplot as plt from sklearn.preprocessing import scale # First generate some data mu = np.array([0,0]) Sigma = np.array([[ 46.28249177, 26.12496001], [ 26.12496001, 19.55457642]]) X = np.random.multivariate_normal(mu,Sigma,1000) fig = plt.figure(figsize=[8,8]) plt.scatter(X[:,0],X[:,1]) plt.xlabel('x', fontsize=12) plt.ylabel('y', fontsize=12) plt.grid(axis='both') # perform PCA L,U=np.linalg.eig(Sigma) # eigenvalues print(L) # eigenvectors U # first plot the eigenvectors ah=0.1 # size of arrow head f=1.1 # axes range plt.figure(figsize=(8,8)) plt.subplot(111,aspect='equal') plt.arrow(0,0,U[0,0],U[1,0],color='r',linewidth=2,head_width=ah,head_length=ah) plt.arrow(0,0,U[0,1],U[1,1],color='r',linewidth=2,head_width=ah,head_length=ah) plt.text(f*U[0,0],f*U[1,0],r'Eigenvector 1, $\vec{v_1}$ = %.2f $\vec{x}$ + %.2f $\vec{y}$' % (U[0,0],U[1,0]), fontsize=15) plt.text(f*U[0,1],f*U[1,1],r'Eigenvector 2, $\vec{v_1}$ = %.2f $\vec{x}$ + %.2f $\vec{y}$' % (U[0,1],U[1,1]), fontsize=15) plt.xlim([-f,f]) plt.ylim([-f,f]) plt.xlabel('x',fontsize=15) plt.ylabel('y',fontsize=15) plt.grid() plt.show() U[0,0]*math.sqrt(L[0]),U[1,0]*math.sqrt(L[0]) # plot the eigenvectors with the data plt.figure(figsize=(8,8)) plt.plot(X[:,0],X[:,1],'bo',markersize=5,zorder=0,) plt.axis('equal') plt.grid() plt.title('Principal Components (eigenvectors) of random data', fontsize=12) plt.xlabel('x', fontsize=12) plt.ylabel('y', fontsize=12) plt.arrow(0,0,U[0,0]*math.sqrt(L[0]),U[1,0]*math.sqrt(L[0]),color='r',linewidth=2,head_width=1,head_length=1) plt.arrow(0,0,U[0,1]*math.sqrt(L[1]),U[1,1]*math.sqrt(L[1]),color='r',linewidth=2,head_width=1,head_length=1) plt.show() # projecting data onto the principal components (no dimensionality reduction here) Z = np.dot(X,U) plt.figure(figsize=(8,8)) plt.axis('equal') plt.grid() plt.plot(Z[:,0],Z[:,1],'bo',markersize=5) plt.xlabel('Principal Component 1',fontsize=15) plt.ylabel('Principal Component 2',fontsize=15) plt.show() # projecting data onto the first principal component Z = np.dot(X,U[:,1]) plt.figure(figsize=(8,8)) plt.axis('equal') plt.grid() plt.plot(Z,np.zeros([len(Z),]),'bo',markersize=5) plt.xlabel('Principal Component 1',fontsize=15) #plt.ylabel('Principal Component 2',fontsize=15) plt.show() ``` # Applying PCA to text data: An exercise ``` from sklearn.decomposition import PCA data = pd.read_csv("notebooks/programming_assignments/474_s22_assignments/assignment1/part2_data.csv") data.head() X, features = fit_vectorizer(CountVectorizer(analyzer="word", ngram_range=(1, 3), min_df=10, max_df=0.75, stop_words='english'), documents = data.title) len(data), X.shape, len(features) pca = PCA(n_components=10) pca.fit(X.todense()) print(pca.explained_variance_ratio_) print(pca.singular_values_) components = pca.components_ df = pd.DataFrame({"feature": features, "PC1": components[0,:], "PC2": components[1,:]}) df.sort_values("PC2") ```
github_jupyter
Notebook Name: BuildConsolidatedFeaturesFile.ipynb Created date : Sunday, 27th March Author : Sreejith Menon Description : buildFeatureFl(input file,output file) Reads from a consolidated HIT results csv file (input file). Extracts the below features from the IBEIS dataset: 1. species_texts 2. sex_texts 3. age_months_est 4. exemplar_flags 5. quality_texts Consolidated HIT results contain number of shares and not shares per image in the mechanical turk jobs. Expects an input file in the following format: [GID,SHARE,NOT_SHARE,TOTAL] ``` import csv import GetPropertiesAPI as GP import importlib importlib.reload(GP) # un-comment if there are any changes made to API ``` Logic for reading data from the consolidatedHITResults file ``` def buildFeatureFl(inFL,outFL): reader = csv.reader(open(inFL,"r")) head = reader.__next__() data = {} for row in reader: data[row[0]] = row[1:] # Extracts all the annotation ID's from IBEIS aidList = [] for gid in data.keys(): aid = GP.getAnnotID(int(gid)) data[gid].append(aid) # Extracts all feature info based on annotation ID's from IBEIS for gid in data.keys(): if data[gid][3] != None: aid = data[gid][3] spec_text = GP.getImageFeature(aid,"species_texts") data[gid].append(spec_text) sex_text = GP.getImageFeature(aid,"sex_texts") data[gid].append(sex_text) est_age = GP.getImageFeature(aid,"age_months_est") data[gid].append(est_age) exemplar = GP.getImageFeature(aid,"exemplar_flags") data[gid].append(exemplar) qual_text = GP.getImageFeature(aid,"quality_texts") data[gid].append(qual_text) else: data[gid].append('NULL') data[gid].append('NULL') data[gid].append('NULL') data[gid].append('NULL') data[gid].append('NULL') # Write all the extracted info to a CSV file head += ['ANNOTATION_ID','SPECIES','SEX','AGE_MONTHS','EXEMPLAR_FLAG','IMAGE_QUALITY'] writeFL = open(outFL,"w") writer = csv.writer(writeFL) writer.writerow(head) for row in data.keys(): writer.writerow([row] + data[row]) writeFL.close() def __main__(): buildFeatureFl("../data/consolidatedHITResults.csv","../data/consolidatedHITResultsWithInfo1.csv") if __name__ == __main__: __main__() GP.getAnnotID(5381) gid_aid_map = {} for gid in range(1,5384): gid_aid_map[gid] = GP.getAnnotID(gid) import json with open("../data/flickr_zebra_gid_aid_map.json","w") as fl: json.dump(gid_aid_map, fl, indent=4) list(gid_aid_map.values()) aids = [aid for lst in list(gid_aid_map.values()) for aid in lst if len(lst)] aid_species_map = {aids[i] : features[i] for i in range(len(aids))} features = GP.getImageFeature(aids, 'species/text') with open("../data/flickr_zebra_aid_species_map.json", "w") as fl: json.dump(aid_species_map, fl, indent = 4) import UploadAndDetectIBEIS as UD UD.check_job_status('jobid-5388') data_dict = { 'jobid': 'jobid-5388', } response = UD.get('api/engine/job/status', data_dict) response ```
github_jupyter
# Text Classification using Gradient Boosting Classifier and TfidfVectorizer This Code Template is for Text Classification using Gradient Boositng Classifier along with Text Feature technique TfidfVectorizer from Scikit-learn in python. ### Required Packages ``` !pip install nltk !pip install imblearn import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as se import re, string import nltk from nltk.tokenize import word_tokenize from nltk.corpus import stopwords, wordnet from nltk.stem import SnowballStemmer, WordNetLemmatizer from nltk.stem import PorterStemmer nltk.download('stopwords') nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('wordnet') from imblearn.over_sampling import RandomOverSampler from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.metrics import plot_confusion_matrix,classification_report from sklearn.ensemble import GradientBoostingClassifier ``` ### Initialization Filepath of CSV file ``` #filepath file_path= "" ``` **Target** variable for prediction. ``` target='' ``` Text column containing all the text data ``` text="" ``` ## Data Fetching Pandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools. We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. ``` df=pd.read_csv(file_path) df.head() ``` ### Data Preprocessing Since the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the datasets by encoding them to integer classes. ``` #convert to lowercase, strip and remove punctuations def preprocess(text): text = text.lower() text = text.strip() text = re.compile('<.*?>').sub('', text) text = re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', text) text = re.sub('\s+', ' ', text) text = re.sub(r'\[[0-9]*\]',' ',text) text = re.sub(r'[^\w\s]', '', str(text).lower().strip()) text = re.sub(r'\d',' ',text) text = re.sub(r'\s+',' ',text) return text # STOPWORD REMOVAL def stopword(string): a= [i for i in string.split() if i not in stopwords.words('english')] return ' '.join(a) # STEMMING # Initialize the Stemmer ps = PorterStemmer() # Stem the sentence def stemmer(string): return ps.stem(string) # LEMMATIZATION # Initialize the lemmatizer wl = WordNetLemmatizer() # This is a helper function to map NTLK position tags def get_wordnet_pos(tag): if tag.startswith('J'): return wordnet.ADJ elif tag.startswith('V'): return wordnet.VERB elif tag.startswith('N'): return wordnet.NOUN elif tag.startswith('R'): return wordnet.ADV else: return wordnet.NOUN # Lemmatize the sentence def lemmatizer(string): word_pos_tags = nltk.pos_tag(word_tokenize(string)) # Get position tags a=[wl.lemmatize(tag[0], get_wordnet_pos(tag[1])) for idx, tag in enumerate(word_pos_tags)] # Map the position tag and lemmatize the word/token return " ".join(a) def textlemmapreprocess(string): return lemmatizer(stopword(preprocess(string))) def textstempreprocess(string): return stemmer(stopword(preprocess(string))) def textfinalpreprocess(df, modifier = 'stemmer'): if modifier == 'lemmatization': return(df[text].apply(lambda x: textlemmapreprocess(x))) elif modifier == 'stemmer': return(df[text].apply(lambda x: textstempreprocess(x))) def data_preprocess(df, target): df = df.dropna(axis=0, how = 'any') df[target] = LabelEncoder().fit_transform(df[target]) return df df = data_preprocess(df, target) df[text] = textfinalpreprocess(df, modifier = 'stemmer') #modifier has two options: 'stemmer', 'lemmatization' df.head() ``` ### Feature Selections It is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model. We will assign all the required input features to X and target/outcome to Y. ``` X=df[text] Y=df[target] ``` #### Distribution Of Target Variable ``` plt.figure(figsize = (10,6)) se.countplot(Y) ``` ### Data Splitting Since we are using a univariate dataset, we can directly split our data into training and testing subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of the model on new data. ``` x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) ``` ### Feature Transformation **TfidfVectorizer** converts a collection of raw documents to a matrix of TF-IDF features. It's equivalent to CountVectorizer followed by TfidfTransformer. For more information on TfidfVectorizer [click here](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html) ``` vectorizer = TfidfVectorizer() vectorizer.fit(x_train) x_train = vectorizer.transform(x_train) x_test = vectorizer.transform(x_test) ``` ## Model Gradient Boosting for classification. GB builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage n_classes_ regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced. #### Model Tuning Parameters 1.loss{‘deviance’, ‘exponential’}, default=’deviance’ >The loss function to be optimized. ‘deviance’ refers to deviance (= logistic regression) for classification with probabilistic outputs. For loss ‘exponential’ gradient boosting recovers the AdaBoost algorithm. 2.learning_ratefloat, default=0.1 >Learning rate shrinks the contribution of each tree by learning_rate. There is a trade-off between learning_rate and n_estimators. 3.n_estimatorsint, default=100 >The number of boosting stages to perform. Gradient boosting is fairly robust to over-fitting so a large number usually results in better performance. 4.subsamplefloat, default=1.0 >The fraction of samples to be used for fitting the individual base learners. If smaller than 1.0 this results in Stochastic Gradient Boosting. subsample interacts with the parameter n_estimators. Choosing subsample < 1.0 leads to a reduction of variance and an increase in bias. 5.criterion{‘friedman_mse’, ‘mse’, ‘mae’}, default=’friedman_mse’ >The function to measure the quality of a split. Supported criteria are ‘friedman_mse’ for the mean squared error with improvement score by Friedman, ‘mse’ for mean squared error, and ‘mae’ for the mean absolute error. The default value of ‘friedman_mse’ is generally the best as it can provide a better approximation in some cases. 6.min_samples_splitint or float, default=2 >The minimum number of samples required to split an internal node: If int, then consider min_samples_split as the minimum number. If float, then min_samples_split is a fraction and ceil(min_samples_split * n_samples) are the minimum number of samples for each split. 7.min_samples_leafint or float, default=1 >The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least min_samples_leaf training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. If int, then consider min_samples_leaf as the minimum number. If float, then min_samples_leaf is a fraction and ceil(min_samples_leaf * n_samples) are the minimum number of samples for each node. 8.min_weight_fraction_leaffloat, default=0.0 >The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. 9.max_depthint, default=3 >The maximum depth of the individual regression estimators. The maximum depth limits the number of nodes in the tree. Tune this parameter for best performance; the best value depends on the interaction of the input variables. For more information on GBClassifier and it's parameters [click here](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) ``` model=GradientBoostingClassifier(n_estimators=500, random_state=123) model.fit(x_train,y_train) ``` #### Model Accuracy score() method return the mean accuracy on the given test data and labels. In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. ``` print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) ``` #### Confusion Matrix A confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known. ``` plot_confusion_matrix(model,x_test,y_test,cmap=plt.cm.Blues) ``` #### Classification Report A Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False. * where: - Precision:- Accuracy of positive predictions. - Recall:- Fraction of positives that were correctly identified. - f1-score:- percent of positive predictions were correct - support:- Support is the number of actual occurrences of the class in the specified dataset. ``` print(classification_report(y_test,model.predict(x_test))) ``` #### Creator: Anu Rithiga B , Github: [Profile - Iamgrootsh7](https://github.com/iamgrootsh7)
github_jupyter
# 2 - Updated Sentiment Analysis In the previous notebook, we got the fundamentals down for sentiment analysis. In this notebook, we'll actually get decent results. We will use: - packed padded sequences - pre-trained word embeddings - different RNN architecture - bidirectional RNN - multi-layer RNN - regularization - a different optimizer This will allow us to achieve ~84% test accuracy. ## Preparing Data As before, we'll set the seed, define the `Fields` and get the train/valid/test splits. We'll be using *packed padded sequences*, which will make our RNN only process the non-padded elements of our sequence, and for any padded element the `output` will be a zero tensor. To use packed padded sequences, we have to tell the RNN how long the actual sequences are. We do this by setting `include_lengths = True` for our `TEXT` field. This will cause `batch.text` to now be a tuple with the first element being our sentence (a numericalized tensor that has been padded) and the second element being the actual lengths of our sentences. ``` import torch from torchtext import data from torchtext import datasets SEED = 1234 torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True import spacy #import en_core_web_sm # spacy.load('en') # IOError: [E050] Can't find model 'en'. spacy_en = spacy.load('en_core_web_sm') def tokenizer(text): # create a tokenizer function return [tok.text for tok in spacy_en.tokenizer(text)] TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True) LABEL = data.LabelField(dtype = torch.float) print(TEXT) print(LABEL) ``` We then load the IMDb dataset. ``` from torchtext import datasets train_data, test_data = datasets.IMDB.splits(TEXT, LABEL) ``` Then create the validation set from our training set. ``` import random train_data, valid_data = train_data.split(random_state = random.seed(SEED)) ``` Next is the use of pre-trained word embeddings. Now, instead of having our word embeddings initialized randomly, they are initialized with these pre-trained vectors. We get these vectors simply by specifying which vectors we want and passing it as an argument to `build_vocab`. `TorchText` handles downloading the vectors and associating them with the correct words in our vocabulary. Here, we'll be using the `"glove.6B.100d" vectors"`. `glove` is the algorithm used to calculate the vectors, go [here](https://nlp.stanford.edu/projects/glove/) for more. `6B` indicates these vectors were trained on 6 billion tokens and `100d` indicates these vectors are 100-dimensional. You can see the other available vectors [here](https://github.com/pytorch/text/blob/master/torchtext/vocab.py#L113). The theory is that these pre-trained vectors already have words with similar semantic meaning close together in vector space, e.g. "terrible", "awful", "dreadful" are nearby. This gives our embedding layer a good initialization as it does not have to learn these relations from scratch. **Note**: these vectors are about 862MB, so watch out if you have a limited internet connection. By default, TorchText will initialize words in your vocabulary but not in your pre-trained embeddings to zero. We don't want this, and instead initialize them randomly by setting `unk_init` to `torch.Tensor.normal_`. This will now initialize those words via a Gaussian distribution. ``` MAX_VOCAB_SIZE = 25_000 TEXT.build_vocab(train_data, max_size = MAX_VOCAB_SIZE, vectors = "glove.6B.100d", unk_init = torch.Tensor.normal_) LABEL.build_vocab(train_data) ``` As before, we create the iterators, placing the tensors on the GPU if one is available. Another thing for packed padded sequences all of the tensors within a batch need to be sorted by their lengths. This is handled in the iterator by setting `sort_within_batch = True`. ``` BATCH_SIZE = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, valid_iterator, test_iterator = data.BucketIterator.splits( (train_data, valid_data, test_data), batch_size = BATCH_SIZE, sort_within_batch = True, device = device) ``` ## Build the Model The model features the most drastic changes. ### Different RNN Architecture We'll be using a different RNN architecture called a Long Short-Term Memory (LSTM). Why is an LSTM better than a standard RNN? Standard RNNs suffer from the [vanishing gradient problem](https://en.wikipedia.org/wiki/Vanishing_gradient_problem). LSTMs overcome this by having an extra recurrent state called a _cell_, $c$ - which can be thought of as the "memory" of the LSTM - and the use use multiple _gates_ which control the flow of information into and out of the memory. For more information, go [here](https://colah.github.io/posts/2015-08-Understanding-LSTMs/). We can simply think of the LSTM as a function of $x_t$, $h_t$ and $c_t$, instead of just $x_t$ and $h_t$. $$(h_t, c_t) = \text{LSTM}(x_t, h_t, c_t)$$ Thus, the model using an LSTM looks something like (with the embedding layers omitted): ![](assets/sentiment2.png) The initial cell state, $c_0$, like the initial hidden state is initialized to a tensor of all zeros. The sentiment prediction is still, however, only made using the final hidden state, not the final cell state, i.e. $\hat{y}=f(h_T)$. ### Bidirectional RNN The concept behind a bidirectional RNN is simple. As well as having an RNN processing the words in the sentence from the first to the last (a forward RNN), we have a second RNN processing the words in the sentence from the **last to the first** (a backward RNN). At time step $t$, the forward RNN is processing word $x_t$, and the backward RNN is processing word $x_{T-t+1}$. In PyTorch, the hidden state (and cell state) tensors returned by the forward and backward RNNs are stacked on top of each other in a single tensor. We make our sentiment prediction using a concatenation of the last hidden state from the forward RNN (obtained from final word of the sentence), $h_T^\rightarrow$, and the last hidden state from the backward RNN (obtained from the first word of the sentence), $h_T^\leftarrow$, i.e. $\hat{y}=f(h_T^\rightarrow, h_T^\leftarrow)$ The image below shows a bi-directional RNN, with the forward RNN in orange, the backward RNN in green and the linear layer in silver. ![](assets/sentiment3.png) ### Multi-layer RNN Multi-layer RNNs (also called *deep RNNs*) are another simple concept. The idea is that we add additional RNNs on top of the initial standard RNN, where each RNN added is another *layer*. The hidden state output by the first (bottom) RNN at time-step $t$ will be the input to the RNN above it at time step $t$. The prediction is then made from the final hidden state of the final (highest) layer. The image below shows a multi-layer unidirectional RNN, where the layer number is given as a superscript. Also note that each layer needs their own initial hidden state, $h_0^L$. ![](assets/sentiment4.png) ### Regularization Although we've added improvements to our model, each one adds additional parameters. Without going into overfitting into too much detail, the more parameters you have in in your model, the higher the probability that your model will overfit (memorize the training data, causing a low training error but high validation/testing error, i.e. poor generalization to new, unseen examples). To combat this, we use regularization. More specifically, we use a method of regularization called *dropout*. Dropout works by randomly *dropping out* (setting to 0) neurons in a layer during a forward pass. The probability that each neuron is dropped out is set by a hyperparameter and each neuron with dropout applied is considered indepenently. One theory about why dropout works is that a model with parameters dropped out can be seen as a "weaker" (less parameters) model. The predictions from all these "weaker" models (one for each forward pass) get averaged together withinin the parameters of the model. Thus, your one model can be thought of as an ensemble of weaker models, none of which are over-parameterized and thus should not overfit. ### Implementation Details Another addition to this model is that we are not going to learn the embedding for the `<pad>` token. This is because we want to explitictly tell our model that padding tokens are irrelevant to determining the sentiment of a sentence. This means the embedding for the pad token will remain at what it is initialized to (we initialize it to all zeros later). We do this by passing the index of our pad token as the `padding_idx` argument to the `nn.Embedding` layer. To use an LSTM instead of the standard RNN, we use `nn.LSTM` instead of `nn.RNN`. Also, note that the LSTM returns the `output` and a tuple of the final `hidden` state and the final `cell` state, whereas the standard RNN only returned the `output` and final `hidden` state. As the final hidden state of our LSTM has both a forward and a backward component, which will be concatenated together, the size of the input to the `nn.Linear` layer is twice that of the hidden dimension size. Implementing bidirectionality and adding additional layers are done by passing values for the `num_layers` and `bidirectional` arguments for the RNN/LSTM. Dropout is implemented by initializing an `nn.Dropout` layer (the argument is the probability of dropping out each neuron) and using it within the `forward` method after each layer we want to apply dropout to. **Note**: never use dropout on the input or output layers (`text` or `fc` in this case), you only ever want to use dropout on intermediate layers. The LSTM has a `dropout` argument which adds dropout on the connections between hidden states in one layer to hidden states in the next layer. As we are passing the lengths of our sentences to be able to use packed padded sequences, we have to add a second argument, `text_lengths`, to `forward`. Before we pass our embeddings to the RNN, we need to pack them, which we do with `nn.utils.rnn.packed_padded_sequence`. This will cause our RNN to only process the non-padded elements of our sequence. The RNN will then return `packed_output` (a packed sequence) as well as the `hidden` and `cell` states (both of which are tensors). Without packed padded sequences, `hidden` and `cell` are tensors from the last element in the sequence, which will most probably be a pad token, however when using packed padded sequences they are both from the last non-padded element in the sequence. We then unpack the output sequence, with `nn.utils.rnn.pad_packed_sequence`, to transform it from a packed sequence to a tensor. The elements of `output` from padding tokens will be zero tensors (tensors where every element is zero). Usually, we only have to unpack output if we are going to use it later on in the model. Although we aren't in this case, we still unpack the sequence just to show how it is done. The final hidden state, `hidden`, has a shape of _**[num layers * num directions, batch size, hid dim]**_. These are ordered: **[forward_layer_0, backward_layer_0, forward_layer_1, backward_layer 1, ..., forward_layer_n, backward_layer n]**. As we want the final (top) layer forward and backward hidden states, we get the top two hidden layers from the first dimension, `hidden[-2,:,:]` and `hidden[-1,:,:]`, and concatenate them together before passing them to the linear layer (after applying dropout). ``` import torch.nn as nn class RNN(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout, pad_idx): super().__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx) self.rnn = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers, bidirectional=bidirectional, dropout=dropout) self.fc = nn.Linear(hidden_dim * 2, output_dim) self.dropout = nn.Dropout(dropout) def forward(self, text, text_lengths): #text = [sent len, batch size] embedded = self.dropout(self.embedding(text)) #embedded = [sent len, batch size, emb dim] #pack sequence packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths) packed_output, (hidden, cell) = self.rnn(packed_embedded) #unpack sequence output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output) #output = [sent len, batch size, hid dim * num directions] #output over padding tokens are zero tensors #hidden = [num layers * num directions, batch size, hid dim] #cell = [num layers * num directions, batch size, hid dim] #concat the final forward (hidden[-2,:,:]) and backward (hidden[-1,:,:]) hidden layers #and apply dropout hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)) #hidden = [batch size, hid dim * num directions] return self.fc(hidden) ``` Like before, we'll create an instance of our RNN class, with the new parameters and arguments for the number of layers, bidirectionality and dropout probability. To ensure the pre-trained vectors can be loaded into the model, the `EMBEDDING_DIM` must be equal to that of the pre-trained GloVe vectors loaded earlier. We get our pad token index from the vocabulary, getting the actual string representing the pad token from the field's `pad_token` attribute, which is `<pad>` by default. ``` INPUT_DIM = len(TEXT.vocab) EMBEDDING_DIM = 100 HIDDEN_DIM = 256 OUTPUT_DIM = 1 N_LAYERS = 2 BIDIRECTIONAL = True DROPOUT = 0.5 PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token] model = RNN(INPUT_DIM, EMBEDDING_DIM, HIDDEN_DIM, OUTPUT_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT, PAD_IDX) ``` We'll print out the number of parameters in our model. Notice how we have almost twice as many parameters as before! ``` def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters') ``` The final addition is copying the pre-trained word embeddings we loaded earlier into the `embedding` layer of our model. We retrieve the embeddings from the field's vocab, and check they're the correct size, _**[vocab size, embedding dim]**_ ``` pretrained_embeddings = TEXT.vocab.vectors print(pretrained_embeddings.shape) ``` We then replace the initial weights of the `embedding` layer with the pre-trained embeddings. **Note**: this should always be done on the `weight.data` and not the `weight`! ``` model.embedding.weight.data.copy_(pretrained_embeddings) ``` As our `<unk>` and `<pad>` token aren't in the pre-trained vocabulary they have been initialized using `unk_init` (an $\mathcal{N}(0,1)$ distribution) when building our vocab. It is preferable to initialize them both to all zeros to explicitly tell our model that, initially, they are irrelevant for determining sentiment. We do this by manually setting their row in the embedding weights matrix to zeros. We get their row by finding the index of the tokens, which we have already done for the padding index. **Note**: like initializing the embeddings, this should be done on the `weight.data` and not the `weight`! ``` UNK_IDX = TEXT.vocab.stoi[TEXT.unk_token] model.embedding.weight.data[UNK_IDX] = torch.zeros(EMBEDDING_DIM) model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM) print(model.embedding.weight.data) ``` We can now see the first two rows of the embedding weights matrix have been set to zeros. As we passed the index of the pad token to the `padding_idx` of the embedding layer it will remain zeros throughout training, however the `<unk>` token embedding will be learned. ## Train the Model Now to training the model. The only change we'll make here is changing the optimizer from `SGD` to `Adam`. SGD updates all parameters with the same learning rate and choosing this learning rate can be tricky. `Adam` adapts the learning rate for each parameter, giving parameters that are updated more frequently lower learning rates and parameters that are updated infrequently higher learning rates. More information about `Adam` (and other optimizers) can be found [here](http://ruder.io/optimizing-gradient-descent/index.html). To change `SGD` to `Adam`, we simply change `optim.SGD` to `optim.Adam`, also note how we do not have to provide an initial learning rate for Adam as PyTorch specifies a sensibile default initial learning rate. ``` import torch.optim as optim optimizer = optim.Adam(model.parameters()) ``` The rest of the steps for training the model are unchanged. We define the criterion and place the model and criterion on the GPU (if available)... ``` criterion = nn.BCEWithLogitsLoss() model = model.to(device) criterion = criterion.to(device) ``` We implement the function to calculate accuracy... ``` def binary_accuracy(preds, y): """ Returns accuracy per batch, i.e. if you get 8/10 right, this returns 0.8, NOT 8 """ #round predictions to the closest integer rounded_preds = torch.round(torch.sigmoid(preds)) correct = (rounded_preds == y).float() #convert into float for division acc = correct.sum() / len(correct) return acc ``` We define a function for training our model. As we have set `include_lengths = True`, our `batch.text` is now a tuple with the first element being the numericalized tensor and the second element being the actual lengths of each sequence. We separate these into their own variables, `text` and `text_lengths`, before passing them to the model. **Note**: as we are now using dropout, we must remember to use `model.train()` to ensure the dropout is "turned on" while training. ``` def train(model, iterator, optimizer, criterion): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: optimizer.zero_grad() text, text_lengths = batch.text predictions = model(text, text_lengths).squeeze(1) loss = criterion(predictions, batch.label) acc = binary_accuracy(predictions, batch.label) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) ``` Then we define a function for testing our model, again remembering to separate `batch.text`. **Note**: as we are now using dropout, we must remember to use `model.eval()` to ensure the dropout is "turned off" while evaluating. ``` def evaluate(model, iterator, criterion): epoch_loss = 0 epoch_acc = 0 model.eval() with torch.no_grad(): for batch in iterator: text, text_lengths = batch.text predictions = model(text, text_lengths).squeeze(1) loss = criterion(predictions, batch.label) acc = binary_accuracy(predictions, batch.label) epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) ``` And also create a nice function to tell us how long our epochs are taking. ``` import time def epoch_time(start_time, end_time): elapsed_time = end_time - start_time elapsed_mins = int(elapsed_time / 60) elapsed_secs = int(elapsed_time - (elapsed_mins * 60)) return elapsed_mins, elapsed_secs ``` Finally, we train our model... ``` N_EPOCHS = 5 best_valid_loss = float('inf') for epoch in range(N_EPOCHS): start_time = time.time() train_loss, train_acc = train(model, train_iterator, optimizer, criterion) valid_loss, valid_acc = evaluate(model, valid_iterator, criterion) end_time = time.time() epoch_mins, epoch_secs = epoch_time(start_time, end_time) if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model.state_dict(), 'tut2-model.pt') print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s') print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%') print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%') ``` ...and get our new and vastly improved test accuracy! ``` model.load_state_dict(torch.load('tut2-model.pt')) test_loss, test_acc = evaluate(model, test_iterator, criterion) print(f'Test Loss: {test_loss:.3f} | Test Acc: {test_acc*100:.2f}%') ``` ## User Input We can now use our model to predict the sentiment of any sentence we give it. As it has been trained on movie reviews, the sentences provided should also be movie reviews. When using a model for inference it should always be in evaluation mode. If this tutorial is followed step-by-step then it should already be in evaluation mode (from doing `evaluate` on the test set), however we explicitly set it to avoid any risk. Our `predict_sentiment` function does a few things: - sets the model to evaluation mode - tokenizes the sentence, i.e. splits it from a raw string into a list of tokens - indexes the tokens by converting them into their integer representation from our vocabulary - gets the length of our sequence - converts the indexes, which are a Python list into a PyTorch tensor - add a batch dimension by `unsqueeze`ing - converts the length into a tensor - squashes the output prediction from a real number between 0 and 1 with the `sigmoid` function - converts the tensor holding a single value into an integer with the `item()` method We are expecting reviews with a negative sentiment to return a value close to 0 and positive reviews to return a value close to 1. ``` import spacy nlp = spacy.load('en') def predict_sentiment(model, sentence): model.eval() tokenized = [tok.text for tok in nlp.tokenizer(sentence)] indexed = [TEXT.vocab.stoi[t] for t in tokenized] length = [len(indexed)] tensor = torch.LongTensor(indexed).to(device) tensor = tensor.unsqueeze(1) length_tensor = torch.LongTensor(length) prediction = torch.sigmoid(model(tensor, length_tensor)) return prediction.item() ``` An example negative review... ``` predict_sentiment(model, "This film is terrible") ``` An example positive review... ``` predict_sentiment(model, "This film is great") ``` ## Next Steps We've now built a decent sentiment analysis model for movie reviews! In the next notebook we'll implement a model that gets comparable accuracy with far fewer parameters and trains much, much faster.
github_jupyter
# Visualizing Time Series Data ``` import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as dates %matplotlib inline df_apple = pd.read_csv('data/apple_stock.csv',index_col='Date',parse_dates=True) df_apple.head() # Adj.Close 와 Adj.Volume 의 variance 문제로 보기 불편함. df_apple[['Volume','Adj Close']].plot() # Adj.Close 와 Adj.Volume 의 축을 함께 그리기 df_apple[['Volume','Adj Close']].plot(secondary_y=['Volume']) # figsize 조정, ylabel, xlabel, title 추가 df_apple['Adj Close'].plot(figsize=(12,8)) plt.ylabel('Close Price') plt.xlabel('Overwrite Date Index') plt.title('Apple') ``` # Plot Formatting ## X Limits ``` df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01']) ``` ## Y Limits ``` df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01'],ylim=[80,180]) ``` ## Color and Style ``` df_apple['Adj Close'].plot(xlim=['2015-01-01','2018-01-01'],ylim=[80,180], ls='--',c='r') ``` ## Basic matplotlib plot ``` idx = df_apple.loc['2015-01-01':'2018-01-01'].index stock = df_apple.loc['2015-01-01':'2018-01-01']['Adj Close'] fig, ax = plt.subplots() ax.plot_date(idx, stock,'-') plt.tight_layout() plt.show() ``` ## Fix the overlap! ``` fig, ax = plt.subplots() ax.plot_date(idx, stock,'-') fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() ``` ## Customize grid ``` fig, ax = plt.subplots() ax.plot_date(idx, stock,'-') ax.yaxis.grid(True) ax.xaxis.grid(True) fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() ``` ## Format dates on Major Axis ``` idx = df_apple.loc['2018-01-01':].index stock = df_apple.loc['2018-01-01':]['Adj Close'] fig, ax = plt.subplots(figsize=(15,7)) ax.plot_date(idx, stock,'-') # Grids ax.yaxis.grid(True) ax.xaxis.grid(True) # Major Axis ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('%b\n%Y')) fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() fig, ax = plt.subplots(figsize=(15,7)) ax.plot_date(idx, stock,'-') # Grids ax.yaxis.grid(True) ax.xaxis.grid(True) # Major Axis ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n\n%Y--%B')) fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() ``` ## Minor Axis ``` fig, ax = plt.subplots(figsize=(15,7)) ax.plot_date(idx, stock,'-') # Major Axis ax.xaxis.set_major_locator(dates.MonthLocator()) ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n%Y--%B')) # Minor Axis ax.xaxis.set_minor_locator(dates.WeekdayLocator()) ax.xaxis.set_minor_formatter(dates.DateFormatter('%d')) # Grids ax.yaxis.grid(True) ax.xaxis.grid(True) fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() fig, ax = plt.subplots(figsize=(15,8)) ax.plot_date(idx, stock,'-') # Major Axis ax.xaxis.set_major_locator(dates.WeekdayLocator(byweekday=1)) ax.xaxis.set_major_formatter(dates.DateFormatter('%B-%d-%a')) # Grids ax.yaxis.grid(True) ax.xaxis.grid(True) fig.autofmt_xdate() # Auto fixes the overlap! plt.tight_layout() plt.show() ```
github_jupyter
## [Rock Paper Scissors](https://en.wikipedia.org/wiki/Rock_paper_scissors#:~:text=A%20player%20who%20decides%20to,%22scissors%20cuts%20paper%22) ### [Tutorial Link]( https://www.youtube.com/watch?v=qikY7HetH14) <br> [ ^ Do watch before precedding :) ] <br><br> **Program Code : Python** ``` # -*- coding: utf-8 -*- """ Created on Tue Feb 16 17:27:17 2021 @author: Lakhan Kumawat """ import random from tkinter import * #variables and Dictionary #These are total events that could occur if/else can also be used but they are pain to implement schema={ "rock":{"rock":1,"paper":0,"scissors":2}, "paper":{"rock":2,"paper":1,"scissors":0}, "scissors":{"rock":0,"paper":2,"scissors":1} } comp_score=0 player_score=0 #functions def outcome_handler(user_choice): global comp_score global player_score outcomes=["rock","paper","scissors"] num=random.randint(0, 2) computer_choice=outcomes[num] result=schema[user_choice][computer_choice] #now config the labes acc to the choices Player_Choice_Label.config(fg="green",text="Player choice : "+str(user_choice)) Computer_Choice_Label.config(fg="red",text="Computer choice : "+str(computer_choice)) if result==2: player_score+=2 Player_Score_Label.config(text="Player : "+str(player_score)) Outcome_Label.config(fg="blue",bg="skyblue",text="Player-Won") elif result==1: player_score+=1 comp_score+=1 Player_Score_Label.config(text="Player : "+str(player_score)) Outcome_Label.config(fg="blue",bg="skyblue",text="Draw") Computer_Score_Label.config(text="Computer : "+str(comp_score)) elif result==0: comp_score+=2 Outcome_Label.config(fg="blue",bg="skyblue",text="Computer-Won") Computer_Score_Label.config(text="Computer : "+str(comp_score)) #main Screen master=Tk() master.title("RPS") #labels Label(master,text="Rock , Paper , Scissors",font=("Calibri",15)).grid(row=0,sticky=N,pady=10,padx=200) Label(master,text="Please Select an option",font=("Calibri",12)).grid(row=2,sticky=N) Player_Score_Label=Label(master,text="Player : 0",font=("Calibri",12)) #label for player Score Player_Score_Label.grid(row=3,sticky=W) Computer_Score_Label=Label(master,text="Computer : 0",font=("Calibri",12)) #label for computer score Computer_Score_Label.grid(row=3,sticky=E) #player and computer choice labels Player_Choice_Label=Label(master,font=("Calibri",12)) Player_Choice_Label.grid(row=5,sticky=W) Computer_Choice_Label=Label(master,font=("Calibri",12)) Computer_Choice_Label.grid(row=5,sticky=E) #outcome Labels Outcome_Label=Label(master,font=("Calibri",12)) Outcome_Label.grid(row=5,sticky=N,pady=10) #buttons Button(master,text="Rock",width=17,command=lambda:outcome_handler("rock")).grid(row=6,sticky=W,padx=10,pady=10) Button(master,text="Paper",width=17,command=lambda:outcome_handler("paper")).grid(row=6,sticky=N,pady=10) Button(master,text="Scissors",width=17,command=lambda:outcome_handler("scissors")).grid(row=6,sticky=E,padx=10,pady=10) #dummy label to create space at the end of master screen Label(master).grid(row=5) master.mainloop() ```
github_jupyter
``` from configparser import ConfigParser from pathlib import Path import shutil REPO_ROOT = Path('~/Documents/repos/coding/birdsong/tweetynet/') REPO_ROOT = REPO_ROOT.expanduser() CONFIGS_DIR = REPO_ROOT.joinpath('src/configs/') BR_CONFIGS = sorted(list(CONFIGS_DIR.glob('*BirdsongRecognition*ini'))) BR_CONFIGS = [str(config) for config in BR_CONFIGS] if not all([f'bird0{i}' in br_config for i, br_config in enumerate(BR_CONFIGS)]): raise ValueError( "could not find all config.ini files for BirdsongRecognition " "in consecutive order (i.e., 10 files with names that end in " "bird00.ini, bird01.ini, ... bird09.ini)" ) BR_DATA_ROOT = REPO_ROOT.joinpath('data/BirdsongRecognition') # path to root of repository that contains results from running learncurve.train with each config.ini file NEW_PARENT = '/media/art/HD-LCU3/tweetynet_paper/BirdsongRecognition' # "roots" of paths in config.ini files that should be replaced with RESULTS_REPO_ROOT OLD_PARENTS = [ '/home/nickledave/Documents/data/BirdsongRecognition/vak', '~/Documents/data/birdsong/BirdsongRecognition/vak', '~/Documents/data/BirdsongRecognition/vak', '~/Documents/data/birdsong/vak', ] def remove_subdirs(root_dir=BR_DATA_ROOT): """removes all sub-directories from a directory""" subdirs = [subdir for subdir in root_dir.iterdir() if subdir.is_dir()] for subdir in subdirs: shutil.rmtree(subdir) def change_parent(path, new_parent=NEW_PARENT, old_parents=OLD_PARENTS): path = str(path) for old_parent in OLD_PARENTS: if old_parent in path: path = path.replace(old_parent, new_parent) assert new_parent in path, f'did not find parent to replace in {path}' path = Path(path) return path def copy_test_dirs(br_configs=BR_CONFIGS, br_data_root=BR_DATA_ROOT, new_parent=NEW_PARENT, old_parents=OLD_PARENTS): """copy test dir to root, using path from .ini file Parameters ---------- old_parent : list of str new_parent : st br_configs : list of str, paths to config.ini files for BirdsongRecognition repository """ config_obj = ConfigParser() for birdnum, config_ini in enumerate(br_configs): config_obj.read(config_ini) results_dirname = config_obj['OUTPUT']['results_dir_made_by_main_script'] results_dirname = Path(results_dirname) src = results_dirname.joinpath('test') src = change_parent(src, new_parent, old_parents) dst = br_data_root.joinpath(f'Bird{birdnum}') if dst.exists(): raise ValueError(f"can't copy to directory, already exists: {dst}") shutil.copytree(src, dst) def main(): remove_subdirs() copy_test_dirs() ```
github_jupyter
## Data : --> age --> sex --> chest pain type (4 values) --> resting blood pressure --> serum cholestoral in mg/dl --> fasting blood sugar > 120 mg/dl --> resting electrocardiographic results (values 0,1,2) --> maximum heart rate achieved --> exercise induced angina --> oldpeak = ST depression induced by exercise relative to rest --> the slope of the peak exercise ST segment --> number of major vessels (0-3) colored by flourosopy --> thal: 3 = normal; 6 = fixed defect; 7 = reversable defect ## Importing Libraries & getting Data ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data = pd.read_csv('dataset/heart.csv') data.head() data.info() ``` ## Handling Missing Values ``` data.isnull().sum() ``` ## Correlation (Feature Engineering - Feature Selection) ``` data.corr()['target'].sort_values(ascending=False) plt.figure(figsize=(15,10)) sns.heatmap(data.corr() ,annot=True ,yticklabels=False ) plt.show() ``` ## Visualization ``` fig = plt.figure(figsize=(15,15)) ax = fig.gca() g = data.hist(ax=ax) ``` ## Checking if Dataset is Balanced or not ``` data['target'].value_counts() sns.countplot(x='target', data=data) ``` ## Handling Categorical Features (Data-Preprocessing) ``` data = pd.get_dummies(data=data, columns=['sex', 'cp','fbs', 'restecg','exang', 'slope', 'ca', 'thal']) data.columns ``` ## Feature Scaling ``` from sklearn.preprocessing import StandardScaler scaler = StandardScaler() columns_to_scale = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak'] data[columns_to_scale] = scaler.fit_transform(data[columns_to_scale]) data.head() ``` ## Selecting X & y ``` X = data.drop('target' ,axis=1) y = data['target'] ``` # Model Building ## KNN ``` from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score # choosing best number of neighbors for our model knn_scores = [] for i in range(1,21): knn = KNeighborsClassifier(n_neighbors=i) cv_scores = cross_val_score(knn ,X ,y ,cv=15) knn_scores.append(round(cv_scores.mean() ,3)) plt.figure(figsize=(10,10)) plt.plot([i for i in range(1,21)], knn_scores ,color='purple') for i in range(1,21): plt.text(i, knn_scores[i-1], (i, knn_scores[i-1])) plt.xticks([i for i in range(1, 21)]) plt.xlabel('Number of Neighbors (K)') plt.ylabel('Scores') plt.title('K-Neighbors Classifier scores for different K-values') plt.show() knn_model = KNeighborsClassifier(n_neighbors=9) cv_scores_knn = cross_val_score(knn_model ,X,y ,cv=15) print('Accuracy of KNN model (with k=9) : {}'.format(round(cv_scores_knn.mean(),4)*100)) ``` ## Decision Tree Classifier ``` from sklearn.tree import DecisionTreeClassifier # Finding the best accuracy for decision tree algorithm using cross_val_score dt_scores = [] for i in range(1,11): dt = DecisionTreeClassifier() cv_scores = cross_val_score(dt ,X,y,cv=15) dt_scores.append(round(cv_scores.mean(),3)) plt.figure(figsize=(10,10)) plt.plot([i for i in range(1, 11)], dt_scores, color='lightgreen') for i in range(1, 11): plt.text(i, dt_scores[i-1], (i, dt_scores[i-1])) plt.xticks([i for i in range(1, 11)]) plt.xlabel('Depth of Decision Tree (N)') plt.ylabel('Scores') plt.title('Decision-Tree-Classifier scores for different depth values') plt.show() dt_model = DecisionTreeClassifier(max_depth=8) cv_scores_dt = cross_val_score(dt_model ,X,y,cv=15) print('Accuracy of Decision Tree model (with maxdepth=8) :{}'.format(round(cv_scores_dt.mean(), 4)*100)) ``` ## Random Forest Classifier ``` from sklearn.ensemble import RandomForestClassifier # Finding the best accuracy for random forest algorithm using cross_val_score rfc_scores = [] for i in range(10, 101, 10): rfc = RandomForestClassifier(n_estimators=i) cv_scores = cross_val_score(rfc, X, y, cv=5) rfc_scores.append(round(cv_scores.mean(), 3)) plt.figure(figsize=(10,10)) plt.plot([n for n in range(10, 101, 10)], rfc_scores, color='red') for i in range(1, 11): plt.text(i*10, rfc_scores[i-1], (i*10, rfc_scores[i-1])) plt.xticks([i for i in range(10, 101, 10)]) plt.xlabel('Number of Estimators (N)') plt.ylabel('Scores') plt.title('Random-Forest-Classifier scores for different N values') plt.show() rfc_model = RandomForestClassifier(n_estimators=80) cv_scores_rfc = cross_val_score(dt_model, X, y, cv=15) print('Accuracy of Random Forest model (with estimators=80) :{}'.format(round(cv_scores_rfc.mean(), 4)*100)) ``` # Model Evaluation ``` # creating Dataframe to check which regression technique was the best models = pd.DataFrame({ 'Model': ['KNN', 'Decision-Tree Classifier', 'Random-Forest Classifier'], 'Accuracy': [ round(cv_scores_knn.mean(), 4)*100, round(cv_scores_dt.mean(), 4)*100, round(cv_scores_rfc.mean(), 4)*100 ] }) models.sort_values(by='Accuracy', ascending=False) ```
github_jupyter
``` import pandas as pd import os from pyDOE import * from scipy.io import netcdf as nc import xarray as xr ``` ## Download latest version of params file from google drive * requires 'publishing' the google drive spreadsheet * file > publish to web * then it can be set up to continuously publish the spreadsheet to a stable url (with some latency, maybe 1-2 minutes) * note that the first tab must be the sheet where the relevant information is located ``` data_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQs413GtLXtHVDCqEPgAwn4BbDjoWmV7uFqOAWH4mgpxXoVfN6ijnJdhyRgLkV-n2eU-sSQush4CzYU/pub?output=csv' #cmd = 'curl '+data_url+' > params.csv' cmd = 'curl -L '+data_url+' > params.csv' # need to add -L option to force redirects os.system(cmd) ``` ## Read in csv data, filtering by the "include" column ``` #data = pd.read_csv('params.csv') data = pd.read_csv('params.csv',header=0,skiprows=[1]) # modify read_csv to account for header spanning 2 rows included = data['include']==1 params_full = data.loc[included,['name','location','min','max','pft_mins','pft_maxs']] # reset indexing and get rid of excel row number params = params_full.reset_index(drop=True) params ``` Example of how to read pft-specific values as a numpy array ``` pftfirstind = params.index[params['min']=='pft'][0] np.fromstring(params['pft_mins'][pftfirstind],dtype='float',sep=',') ``` Testing out how to retrieve the pft-dependent parameter names ``` params.loc[params['min']=='pft']['name'] ``` Testing out how to retrieve the pft-dependent parameter indices as a numpy array ``` params.index[params['min']=='pft'].values ``` Example of how to parse "XXpercent" for perturbations relative to default values ``` mystring = params['min'][8] mystring # logic for detection "percent" in mystring # extracting the numerical value float(mystring.split("percent")[0]) ``` ## Defining a class for organizing parameter information ``` class ParamInfo(object): def __init__(self, name, minval=None, maxval=None, defval=None): self._name = name self._min = minval self._max = maxval self._default = defval @property def name(self): return self._name @property def min(self): return self._min @property def max(self): return self._max @property def default(self): return self._default @name.setter def name(self, new_name): self._name = new_name @min.setter def min(self, new_min): self._min = new_min @max.setter def max(self, new_max): self._max = new_max @default.setter def default(self, new_def): self._default = new_def def __repr__(self): return "%s:\n\tdefault = %s\n\tmin = %s\n\tmax = %s\n" % (self.name, self.default, self.min, self.max) # testing out the class/dictionary functionality test_dict = {"P1": ParamInfo("P1", minval=0.0, maxval=1.0, defval=2.0), "P2": ParamInfo("P2", minval=[0,0,0,0,0], maxval=[100,100,100,100,100], defval=[0,1,2,3,4]), "P3": ParamInfo("P3", minval="min", maxval="max", defval="value"), "P4": ParamInfo("P4") } # adding a new parameter test_dict["new_param"] = ParamInfo("new_param") # setting the max value #test_dict["P4"].set_max(100) test_dict["P4"].max = 200 # look at the test dictionary for key in test_dict: print(test_dict[key]) ``` ## Read in default parameter values * to use defaults to scale/set parameter perturbations * and to record/keep track of defaults for each parameter and save that information for each simulation ### First, get the default values from the params netcdf file ``` # assign the basepftfile basepftfile = "../basecase/clm5_params.c200519.nc" # read in default file def_params = xr.open_dataset(basepftfile) # declare a dictionary to store parameter information params_dict={} # loop over parameters grabbing name and location for name,loc in zip(params['name'],params['location']): # select parameters located in the params file only if loc=='P': # getting parameter dims (i.e., checking for segment variation) dims = len(def_params[name].values.shape) if dims<2: # no segment variation x = def_params[name].values params_dict[name] = ParamInfo(name, defval=x) else: # segment variation: kmax,ck,psi50,rootprof_beta # assumes same values applied across segments # TO DO: check this assumption, appears not true for rootprof_beta x = def_params[name][0,:].values params_dict[name] = ParamInfo(name, defval=x) # check out the dictionary of default values so far params_dict #params_dict.keys() # get the keys (parameter names) #params_dict.values() # get the values all strung together #params_dict['dleaf'].default # look at the default values for dleaf ``` ### Second, get the namelist default values ``` # NOTE: here using an example lnd_in file to pull in default namelist values # Could also parse the namelist defaults file, see: https://github.com/ESCOMP/CTSM/blob/e2b9745d81ed5cb7cd7f5d6098edf506a4956335/bld/namelist_files/namelist_defaults_ctsm.xml thedir = '/glade/work/djk2120/ctsm_hardcode_co/cime/scripts/clm50c6_ctsmhardcodep_2deg_GSWP3V1_Sparse250_2000/CaseDocs/' thefil = 'lnd_in' lndin = thedir+thefil # loop over parameters grabbing name and location for name,loc in zip(params['name'],params['location']): # select parameters located in the namelist only if loc=='N': # build a command to search for the parameter by name and put output in a tmp file cmd = 'grep '+name+' '+lndin+' > tmp.txt' ret = os.system(cmd) # checking for nonzero return code (exit status?), meaning parameter is not found if ret != 0: # TO DO: will need to address these special cases somehow... print(name+' not found') else: f = open('tmp.txt', 'r') # parse the value from the parameter name tmp = f.read().split()[2] f.close() # cases where scientific notation(?) is specified by a "d" # TO DO: there may be other special cases as well (scientific notation as an "e"?) if 'd' in tmp: tmp = tmp.split('d') x = float(tmp[0])*10**float(tmp[1]) params_dict[name] = ParamInfo(name, defval=x) else: x = float(tmp) params_dict[name] = ParamInfo(name, defval=x) # check out the dictionary of default values so far params_dict ``` ## Set sampling option * ### option available for latin hypercube (LHC) or one-at-a-time (OAAT) ``` sampling_protocol = 'OAAT' #sampling_protocol = 'LHC' prefix = sampling_protocol nparam = len(params['name']) #number of parameters ``` ## Generate parameter sampling * ### careful, each time you run LHC you get a new random draw ``` # NOTE: LHC code is not updated to use dictionaries if sampling_protocol == 'LHC': # define sample size (number of ensemble members) nsamp = 10 # Generate the latin hypercube sample lhd = lhs(nparam, samples=int(nsamp)) # lhd is a 2D array indexed by ensemble member x parameter # figure out how many pft-dependent params there are in this sample npftparam = sum(params['min']=='pft') if npftparam>0: # get dataframe index of first pft param pftfirstind = params.index[params['min']=='pft'][0] # get number of pfts npft = len(np.fromstring(params['pft_mins'][pftfirstind],dtype='float',sep=',')) # set up numpy array to store pft-specific values pft_array = np.nan*np.ones([npftparam,npft,nsamp]) for j in range(npftparam): # get the index for the current pft param pftind = params.index[params['min']=='pft'][j] # get min values min_pft_array = np.fromstring(params['pft_mins'][pftind],dtype='float',sep=',') # max values max_pft_array = np.fromstring(params['pft_maxs'][pftind],dtype='float',sep=',') # loop over samples and calculate parameter values for each pft for i in range(nsamp): pft_array[j,:,i] = (max_pft_array - min_pft_array)*lhd[i,pftind] + min_pft_array # can't store pft_array as a pandas dataframe because it's 3D # unless there is some alternate way to store this data? # initialize min/max arrays - for params without pft-variation min_array = np.nan*np.ones(nparam) max_array = np.nan*np.ones(nparam) # generate arrays with min and max values for i in range(nparam): if params['min'].values[i]=='pft': # TO DO: what's a good placeholder, to denote need to reference pft_array? # numpy doesn't like assigning a string to an existing array of floats # for now, just print a message print('skipping '+params['name'].values[i]+'...this parameter varies with PFT') # Numpy doesn't like assigning an array to a single index in an existing array # The problem is still that I'm declaring min_array before trying to assign values # If I could build it all at once, numpy would allow for nested arrays #min_array[i] = np.fromstring(params['pft_mins'].values[i],dtype='float',sep=',') #max_array[i] = np.fromstring(params['pft_maxs'].values[i],dtype='float',sep=',') else: # assign min/max values min_array[i] = float(params['min'].values[i]) max_array[i] = float(params['max'].values[i]) # calculate parameter values; skip pft params (NaNs in min/max arrays) param_array = (max_array - min_array)*lhd + min_array elif sampling_protocol == 'OAAT': # number of samples is twice the number of parameters (min and max perturbations) nsamp = 2*nparam # set up parameter array # NaN is code for keep the default value param_array = np.nan*np.ones([nsamp,nparam]) # get the min and max indices (even/odd rows) mins_index = (np.arange(0,nsamp,2),np.arange(0,nparam,1)) maxs_index = (np.arange(1,nsamp,2),np.arange(0,nparam,1)) # figure out how many pft-dependent params there are in this sample npftparam = sum(params['min']=='pft') # set up numpy array to store pft-specific values if npftparam>0: # get dataframe index of first pft param pftfirstind = params.index[params['min']=='pft'][0] # get number of pfts npft = len(np.fromstring(params['pft_mins'][pftfirstind],dtype='float',sep=',')) # third dimension accounts for min/max values pft_array = np.nan*np.ones([npftparam,npft,2]) for j in range(npftparam): # get the index for the current pft param pftind = params.index[params['min']=='pft'][j] # assign the values for min and max pft_array[j,:,0]=np.fromstring(params['pft_mins'][pftind],dtype='float',sep=',') pft_array[j,:,1]=np.fromstring(params['pft_maxs'][pftind],dtype='float',sep=',') # can't store pft_array as a pandas dataframe because it's 3D # unless there is some alternate way to store this data? # assign values to the parameter array for i in range(nparam): # check for pft variation if params['min'].values[i]=='pft': # TO DO: what's a good placeholder, to denote need to reference pft_array? # e.g., param_array[mins_index[0][i]][i] = float('pft') # but numpy doesn't like assigning a string to an existing array of floats # for now, just print a message print('skipping '+params['name'].values[i]+'...this parameter varies with PFT') #params_dict[params['name'].values[i]].min = np.fromstring(params['pft_mins'][i],dtype='float',sep=',') #params_dict[params['name'].values[i]].max = np.fromstring(params['pft_maxs'][i],dtype='float',sep=',') # check for "XXpercent" perturb from default elif "percent" in params['min'].values[i]: print('skipping '+params['name'].values[i]+'...for now, need default values') #percent_perturb = float(params['min'].values[i].split("percent")[0]) #percent_min_values = params_dict[params['name'].values[i]].default*(1 - percent_perturb/100) #percent_max_values = params_dict[params['name'].values[i]].default*(1 + percent_perturb/100) #params_dict[params['name'].values[i]].min = percent_min_values #params_dict[params['name'].values[i]].max = percent_max_values else: # assign min/max values directly param_array[mins_index[0][i]][i]=params['min'].values[i] param_array[maxs_index[0][i]][i]=params['max'].values[i] #params_dict[params['name'].values[i]].min = params['min'].values[i] #params_dict[params['name'].values[i]].max = params['max'].values[i] # store psets in a pandas dataframe psets = pd.DataFrame(data=param_array, index=None, columns=params['name']) psets # params dictionary #params_dict ``` # NOTE: starting here, this code below is not fully updated to use dictionary of parameter info or reading default values ### Modify psets dataframe to include pft flag ``` if sampling_protocol == 'LHC': for ind,name in enumerate(params['name']): # check for NaNs in the whole column (denotes PFT-specific param) if np.isnan(psets[name]).all(): print('adding pft flag for '+name) psets[name] = 'pft' # NOTE: this bit of code generates a pandas warning, but still executes as it should # Could come back to this if we figure out how to put some pft flag in the preceding code elif sampling_protocol == 'OAAT': for ind,name in enumerate(params['name']): # check for NaNs in the whole column (denotes PFT-specific param AND/OR needs default values) if np.isnan(psets[name]).all(): print('adding pft flag for '+name) psets[name][mins_index[0][ind]] = 'pft' psets[name][maxs_index[0][ind]] = 'pft' psets ``` ### Check out pft_array, the numpy array that stores pft-specific values ``` pft_array.shape # OAAT dims are (npftparam, npft, 2) where last dim represents min/max perturbations # LHC dims are (npftparam, npft, nsamp) ``` ## Generate parameter files * ### this will overwrite parameter files!! * ### proceed with caution ``` # assign the basepftfile basepftfile = "../basecase/clm5_params.c200519.nc" if sampling_protocol == 'OAAT': # initialize npftparam counter npftparam = 0 # number of samples is twice the number of parameters (min and max perturbations) #nsamp = 2*nparam # loop over nsamp and modify the parameter values accordingly for i in range(nsamp): if sampling_protocol == 'OAAT': # open the default file (twice for OAAT) #tmp_min = xr.open_dataset(basepftfile) #tmp_max = xr.open_dataset(basepftfile) # generate name for this param file #min_pftfile = "../paramfiles/"+prefix+str(2*i+1).zfill(4)+".nc" #max_pftfile = "../paramfiles"+prefix+str(2*i+2).zfill(4)+".nc" #print('working on '+min_pftfile+' and '+max_pftfile) # open the default file tmp = xr.open_dataset(basepftfile) # generate name for this param file pftfile = "../paramfiles/"+prefix+str(i+1).zfill(4)+".nc" print('working on '+pftfile) if sampling_protocol == 'LHC': # reset npftparam counter for each sample npftparam = 0 # loop over parameters for name,loc in zip(params['name'],params['location']): # select parameters located in the params file only if loc=='P': if sampling_protocol == 'LHC': print(name+' modified') var = tmp[name] # check to see if there is pft variation if psets[name][i]=='pft': # check which npftparam we are on print('npftparam='+str(npftparam)) # modify values tmp[name][:] = pft_array[npftparam,:,i] # increment npftparam counter; only do this once per parameter npftparam += 1 else: # no pft variation, assign the same number across all PFTs (as applicable) # check for indexing by pft # NOTE: this logic might get tripped up by froz_q10 and q10_mr which are currently indexed by a placeholder dim "allpfts" (should be removed soon) if var.shape: # check for indexing by segment or variants, which will be the first dimension # skip the first index, don't want to overwrite non-vegetated values if var.shape[0] != npft: tmp[name][:,1:] = psets[name][i] else: # indexed by pft only tmp[name][1:] = psets[name][i] else: # single value, no indexing by pft tmp[name] = psets[name][i] elif sampling_protocol == 'OAAT': # check to see if this parameter should be modified # logic is checking for psets that are NOT NaNs if pd.isna(psets[name][i])==False: print(name+' modified') var = tmp[name] #print(var.shape) # check to see if there is pft variation # NOTE: may want to use only first 16 indices for this ensemble (no crop), in which case indexing changes if psets[name][i]=='pft': # check which npftparam we are on print('npftparam='+str(npftparam)) # check if this is a min or max perturbation if i%2==0: tmp[name][:] = pft_array[npftparam,:,0] # min values else: tmp[name][:] = pft_array[npftparam,:,1] # max values # increment npftparam counter; only do this once per parameter npftparam += 1 else: # no pft variation, assign the same number across all PFTs (as applicable) # check for indexing by pft # NOTE: this logic might get tripped up by froz_q10 and q10_mr which are currently indexed by a placeholder dim "allpfts" (should be removed soon) if var.shape: # check for indexing by segment or variants, which will be the first dimension # skip the first index, don't want to overwrite non-vegetated values if var.shape[0] != npft: tmp[name][:,1:] = psets[name][i] #tmp_min[name][:,1:] = params_dict[name].min else: # indexed by pft only tmp[name][1:] = psets[name][i] #tmp_min[name][1:] = params_dict[name].min else: # single value, no indexing by pft tmp[name] = psets[name][i] #tmp_min[name] = params_dict[name].min # write changes (if any) to file tmp_min.to_netcdf(pftfile,'w') ``` ## Generate namelist files Bash script will generate the namelist mod for pointing to the right params file ``` # create the namelist mod files for i in range(nsamp): nlfile = "../namelist_mods/"+prefix+str(i+1).zfill(4)+".txt" with open(nlfile,"w") as file: output = "! user_nl_clm namelist options written by generate_params:\n" file.write(output) # populate with mods for name,loc in zip(params['name'],params['location']): if loc=='N': # don't have to worry about pft-variation here because namelist params won't have that for i in range(nsamp): if sampling_protocol == 'LHC': nlfile = "../namelist_mods/"+prefix+str(i+1).zfill(4)+".txt" print('working on '+nlfile) with open(nlfile,"a") as file: # key is using "a" for append option print(name+' modified') output = "%s=%s\n" % (name, psets[name][i]) #round?? file.write(output) elif sampling_protocol == 'OAAT': # check to see if this parameter should be modified # logic is checking for psets that are NOT NaNs if ~np.isnan(psets[name][i]): nlfile = "../namelist_mods/"+prefix+str(i+1).zfill(4)+".txt" print('working on '+nlfile) with open(nlfile,"a") as file: # key is using "a" for append option print(name+' modified') output = "%s=%s\n" % (name, psets[name][i]) #round?? file.write(output) ``` ## Save off the parameter sets ``` # create a name for this particular ensemble ensemble_name = "test0001" # build the file name with the prefix (ensemble type) psetsfile = "../parameter_sets/"+prefix+"_"+ensemble_name+".csv" #print(psetsfile) # first, save the psets dataframe to csv psets.to_csv(psetsfile) # second, save the pft array (if applicable) pftarrayfile = "../parameter_sets/"+prefix+"_"+ensemble_name+"_pftvals" #print(pftarrayfile) # save as a numpy array (for now, easiest solution for 3D array?) np.save(pftarrayfile, pft_array) # example of how to load it back in #test = np.load(pftarrayfile+".npy") ```
github_jupyter
# From the solar wind to the ground > Abstract: We demonstrate a basic analysis of a geomagnetic storm using hapiclient & viresclient to access data from the solar wind (OMNI IMF), Low Earth Orbit (Swarm-derived auroral electrojet estimates), and the ground (INTERMAGNET observatory magnetic measurements). ## Packages to use - [`hapiclient`](https://github.com/hapi-server/client-python) to access solar wind data from [OMNI](https://omniweb.gsfc.nasa.gov/) (alternatively we could use [`pysat`](https://pysat.readthedocs.io/en/latest/quickstart.html)) - For more examples with hapiclient, take a look at [the demonstration notebooks](https://github.com/hapi-server/client-python-notebooks) - [`viresclient`](https://github.com/ESA-VirES/VirES-Python-Client/) to access AEJs from Swarm, and B-field from ground observatories - [`xarray`](https://xarray.pydata.org/) and [`matplotlib`](https://matplotlib.org/) for data wrangling and plotting - See the [xarray tutorial website](https://xarray-contrib.github.io/xarray-tutorial/) to learn more ``` %load_ext watermark %watermark -i -v -p viresclient,hapiclient,pandas,xarray,matplotlib from copy import deepcopy import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt from viresclient import SwarmRequest from hapiclient import hapi, hapitime2datetime ``` ## Time selection Let's choose an interesting time period to study - the ["St. Patrick's day storm" of 17th March 2015](https://doi.org/10.1186/s40623-016-0525-y). You can look at the wider context of this event using the interactive [Space Weather Data Portal from the University of Colorado](https://lasp.colorado.edu/space-weather-portal/data/display?active-range=%5B1425967200000,1426831200000%5D&outer-range=%5B1262552105447,1559362748308%5D&plots=%5B%7B%22datasets%22:%7B%22sdo_eve_diodes_l2%22:%5B%22diode171%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22sdo_aia_0094_0335_0193_image_files%22:%5B%22url%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22ac_h0_mfi%22:%5B%22Magnitude%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22ac_h1_epm%22:%5B%22P7%22,%22P8%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22ac_h0_swe%22:%5B%22Vp%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22gracea_density%22:%5B%22neutral_density%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22usgs_geomag_brw_definitive%22:%5B%22X%22%5D,%22usgs_geomag_frn_definitive%22:%5B%22X%22%5D,%22usgs_geomag_cmo_definitive%22:%5B%22X%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22usgs_geomag_brw_definitive%22:%5B%22Y%22%5D,%22usgs_geomag_frn_definitive%22:%5B%22Y%22%5D,%22usgs_geomag_cmo_definitive%22:%5B%22Y%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22usgs_geomag_brw_definitive%22:%5B%22Z%22%5D,%22usgs_geomag_frn_definitive%22:%5B%22Z%22%5D,%22usgs_geomag_cmo_definitive%22:%5B%22Z%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22swt_bfield_maps%22:%5B%22url%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22swt_efield_maps%22:%5B%22url%22%5D%7D,%22options%22:%7B%7D%7D,%7B%22datasets%22:%7B%22swt_voltage_maps%22:%5B%22url%22%5D%7D,%22options%22:%7B%7D%7D%5D) We will use the same time window to fetch data from the different sources: ``` START_TIME = '2015-03-15T00:00:00Z' END_TIME = '2015-03-20T00:00:00Z' ``` ## Solar wind data (OMNI) HAPI is an access protocol supported by a wide array of heliophysics datasets. We can use the Python package "hapiclient" to retrieve data from HAPI servers. In this case we will access the [OMNI HRO2 dataset](https://omniweb.gsfc.nasa.gov/html/HROdocum.html) which provides consolidated solar wind data, and then we will show how we can load these data into pandas and xarray objects. > OMNI Combined, Definitive 1-minute IMF and Definitive Plasma Data Time-Shifted to the Nose of the Earth's Bow Shock, plus Magnetic Indices - J.H. King, N. Papatashvilli (AdnetSystems, NASA GSFC) To generate code snippets to use, and to see what data are available: http://hapi-server.org/servers/#server=CDAWeb&dataset=OMNI_HRO2_1MIN&parameters=flow_speed&start=2000-01-01T00:00:00Z&stop=2000-02-01T00:00:00Z&return=script&format=python Here we will access five-minute-resolution measurements of the Interplanetary Magnetic Field (IMF) vector and the bulk flow speed of the solar wind: ``` def fetch_omni_data(start, stop): server = 'https://cdaweb.gsfc.nasa.gov/hapi' dataset = 'OMNI_HRO2_5MIN' parameters = 'BX_GSE,BY_GSM,BZ_GSM,flow_speed'; data, meta = hapi(server, dataset, parameters, start, stop) return data, meta data, meta = fetch_omni_data(START_TIME, END_TIME) ``` Data are automatically loaded as a [NumPy structured array](https://numpy.org/doc/stable/user/basics.rec.html) and metadata as a dictionary: ``` data meta ``` We are now able to extract an array for a particular value like `data["BZ_GSM"]`, and use the metadata to get full descriptions and units for the chosen parameter. The metadata sometimes contains fill values used during data gaps (e.g. the 9999... values appearing above). Let's use those to replace the gaps with NaN values: ``` def fill2nan(hapidata_in, hapimeta): """Replace bad values (fill values given in metadata) with NaN""" hapidata = deepcopy(hapidata_in) # HAPI returns metadata for parameters as a list of dictionaries # - Loop through them for metavar in hapimeta['parameters']: varname = metavar['name'] fillvalstr = metavar['fill'] if fillvalstr is None: continue vardata = hapidata[varname] mask = vardata==float(fillvalstr) nbad = np.count_nonzero(mask) print('{}: {} fills NaNd'.format(varname, nbad)) vardata[mask] = np.nan return hapidata, hapimeta data, meta = fill2nan(data,meta) data ``` We can load the data into a pandas DataFrame to more readily use for analysis: ``` def to_pandas(hapidata): df = pd.DataFrame( columns=hapidata.dtype.names, data=hapidata, ).set_index("Time") # Convert from hapitime to Python datetime df.index = hapitime2datetime(df.index.values.astype(str)) # df.index = pd.DatetimeIndex(df.index.values.astype(str)) # Remove timezone awareness df.index = df.index.tz_convert("UTC").tz_convert(None) # Rename to Timestamp to match viresclient df.index.name = "Timestamp" return df df = to_pandas(data) df ``` How can we get the extra information like the units from the metadata? Let's construct dictionaries, `units` and `description`, that allow easier access to these: ``` def get_units_description(meta): units = {} description = {} for paramdict in meta["parameters"]: units[paramdict["name"]] = paramdict.get("units", None) description[paramdict["name"]] = paramdict.get("description", None) return units, description units, description = get_units_description(meta) units, description ``` The [`xarray.Dataset`](http://xarray.pydata.org/en/stable/data-structures.html#dataset) object has advantages for handling multi-dimensional data and for attaching of metadata like units. Let's convert the data to an `xarray.Dataset`: ``` def to_xarray(hapidata, hapimeta): # Here we will conveniently re-use the pandas function we just built, # and use the pandas API to build the xarray Dataset. # NB: if performance is important, it's better to build the Dataset directly ds = to_pandas(hapidata).to_xarray() units, description = get_units_description(hapimeta) for param in ds: ds[param].attrs = { "units": units[param], "description": description[param] } return ds ds_sw = to_xarray(data, meta) ds_sw ``` Now let's plot these data: ``` def plot_solar_wind(ds_sw): fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(15, 5)) for IMF_var in ["BX_GSE", "BY_GSM", "BZ_GSM"]: ds_sw[IMF_var].plot.line( x="Timestamp", linewidth=1, alpha=0.8, ax=axes[0], label=IMF_var ) axes[0].legend() axes[0].set_ylabel("IMF\n[nT]") axes[0].set_xlabel("") ds_sw["flow_speed"].plot.line( x="Timestamp", linewidth=1, alpha=0.8, ax=axes[1] ) axes[1].set_ylabel("flow_speed\n[km/s]") axes[1].set_xlabel("") axes[0].grid() axes[1].grid() fig.suptitle("Interplanetary Magnetic Field and Solar Wind flow") return fig, axes fig_sw, axes_sw = plot_solar_wind(ds_sw) ``` ## Auroral electrojets as measured by Swarm Since spacecraft move, it is difficult to extract a simple time series that can be easily tracked. From the complex Swarm product portfolio, we will pick a particular derived parameter: the peak auroral electrojet intensities derived from each pass over the current system. This signal tracks reasonably well from one orbit to the next (when separated into four orbital segments - accounting for two passes over the auroral oval in different local time sectors, and over the northern and southern hemispheres). To keep things a bit simpler, we will retrieve data only from Swarm Alpha over the Northern Hemisphere. The auroral electrojet peaks and boundaries for Swarm Alpha are contained within the product named `SW_OPER_AEJAPBL_2F`. Here is how we can access these data: ``` def fetch_Swarm_AEJ(start_time, end_time): request = SwarmRequest() # Meaning of AEJAPBL: (AEJ) Auroral electrojets # (A) Swarm Alpha # (PBL) Peaks and boundaries from LC method # J_QD is the current intensity along QD-latitude contours # QDOrbitDirection is a flag (1, -1) marking the direction of the # satellite (ascending, descending) relative to the QD pole # MLT is magnetic local time, evaluated according to the # quasi-dipole magnetic longitude and the sub-solar point # (see doi.org/10.1007/s11214-016-0275-y) request.set_collection("SW_OPER_AEJAPBL_2F") request.set_products( measurements=["J_QD", "PointType"], auxiliaries=["QDOrbitDirection", "MLT"] ) # PointType of 0 refers to WEJ (westward electrojet) peaks # PointType of 1 refers to EEJ (eastward electrojet) peaks # See https://nbviewer.jupyter.org/github/pacesm/jupyter_notebooks/blob/master/AEBS/AEBS_00_data_access.ipynb#AEJxPBL-product request.set_range_filter("Latitude", 0, 90) # Northern hemisphere request.set_range_filter("PointType", 0, 1) # Extract only peaks data = request.get_between(START_TIME, END_TIME, asynchronous=False, show_progress=False) ds_AEJ_peaks = data.as_xarray() return ds_AEJ_peaks ds_AEJ_peaks = fetch_Swarm_AEJ(START_TIME, END_TIME) ds_AEJ_peaks ``` Now we need some complex logic to plot the eastward and westward electrojet intensities, separated for each local time sector: ``` def plot_AEJ_envelope(ds_AEJ_peaks): # Masks to identify which sector the satellite is in # and which current type (WEJ/EEJ) is given mask_asc = ds_AEJ_peaks["QDOrbitDirection"] == 1 mask_desc = ds_AEJ_peaks["QDOrbitDirection"] == -1 mask_WEJ = ds_AEJ_peaks["PointType"] == 0 mask_EEJ = ds_AEJ_peaks["PointType"] == 1 fig, axes = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(15, 5)) # Select and plot from the ascending orbital segments # on axes 0 # Eastward electrojet: _ds = ds_AEJ_peaks.where(mask_EEJ & mask_asc, drop=True) _ds["J_QD"].plot.line(x="Timestamp", ax=axes[0], label="EEJ") # Westward electrojet: _ds = ds_AEJ_peaks.where(mask_WEJ & mask_asc, drop=True) _ds["J_QD"].plot.line(x="Timestamp", ax=axes[0], label="WEJ") # Identify approximate MLT of sector _ds = ds_AEJ_peaks.where(mask_asc, drop=True) mlt = round(float(_ds["MLT"].mean())) axes[0].set_ylabel(axes[0].get_ylabel() + f"\nMLT: ~{mlt}") # ... and for descending segments # on axes 1 # Eastward electrojet: _ds = ds_AEJ_peaks.where(mask_EEJ & mask_desc, drop=True) _ds["J_QD"].plot.line(x="Timestamp", ax=axes[1], label="EEJ") # Westward electrojet: _ds = ds_AEJ_peaks.where(mask_WEJ & mask_desc, drop=True) _ds["J_QD"].plot.line(x="Timestamp", ax=axes[1], label="WEJ") # Identify approximate MLT of sector _ds = ds_AEJ_peaks.where(mask_desc, drop=True) mlt = round(float(_ds["MLT"].mean())) axes[1].set_ylabel(axes[1].get_ylabel() + f"\nMLT: ~{mlt}") axes[1].legend() axes[0].set_xlabel("") axes[1].set_xlabel("") axes[0].grid() axes[1].grid() fig.suptitle("Auroral electrojet envelope measured by Swarm Alpha") return fig, axes fig_aej, axes_aej = plot_AEJ_envelope(ds_AEJ_peaks) ``` This shows us the envelope of the auroral electrojet system - how the strength of the Eastward (EEJ) and Westward (WEJ) electrojets evolve over time - but only over the two local time sectors that the spacecraft is moving through. The strengths of the electric current along the contours of Quasi-Dipole latitude, `J_QD`, have been calculated. ### Peak ground magnetic disturbances below satellite tracks Swarm also provides predictions of the location and strength of the peak disturbance on the ground (along the satellite ground-track) caused by the auroral electrojets. Note that this is from the AEJ_PBS (using the SECS method) collection rather than the AEJ_PBL (using the LC method) used above. ``` def fetch_Swarm_AEJ_disturbances(start_time, end_time): request = SwarmRequest() request.set_collection("SW_OPER_AEJAPBS_2F:GroundMagneticDisturbance") request.set_products( measurements=["B_NE"], auxiliaries=["OrbitNumber", "QDOrbitDirection"] ) request.set_range_filter("Latitude", 0, 90) # Northern hemisphere only data = request.get_between(start_time, end_time, asynchronous=False, show_progress=False) ds = data.as_xarray() # Add vector magnitude ds["B_Total"] = "Timestamp", np.sqrt((ds["B_NE"].data**2).sum(axis=1)) ds["B_Total"].attrs["units"] = "nT" return ds ds_AEJ_disturbances = fetch_Swarm_AEJ_disturbances(START_TIME, END_TIME) ds_AEJ_disturbances ``` This dataset contains two samples per pass over each half of the auroral oval, estimating the ground location of the peak magnetic disturbance due to each of the EEJ and WEJ currents, and the associated strength (`B_NE`) of the North and East components of the disturbance. Let's look at an approximation of the overall strongest ground disturbances, by inspecting the maximum strength found over 90-minute windows (i.e. approximately each orbit): ``` def plot_Swarm_ground_disturbance(ds_AEJ_disturbances): fig, ax = plt.subplots(figsize=(15, 3)) ds_resample = ds_AEJ_disturbances.resample({'Timestamp':'90Min'}).max() ds_resample["B_Total"].plot.line(x="Timestamp", ax=ax) fig.suptitle("Peak ground disturbance estimated from Swarm Alpha") ax.set_ylabel("Magnetic disturbance\n[nT]") ax.set_xlabel("") ax.grid() return fig, ax fig_Sw_ground, ax_Sw_ground = plot_Swarm_ground_disturbance(ds_AEJ_disturbances) ``` ## Ground observatory data (INTERMAGNET) > We acknowledge usage of INTERMAGNET data > See <https://intermagnet.github.io/data_conditions.html> for more As well as access to Swarm data, VirES also provides access to ground observatory data from INTERMAGNET. We can fetch data from the minute resolution dataset (`SW_OPER_AUX_OBSM2_`), specifying desired observatories according to their [3-letter IAGA codes](https://www.intermagnet.org/imos/imomap-eng.php). These data have been rotated from the geodetic reference frame to the geocentric frame (NEC). We'll select three observatories in Sweden: Abisko (ABK), Lycksele (LYC) and Uppsala (UPS), which form a chain across about 10 degrees of latitude along a similar longitude. ``` def fetch_ground_obs(IAGA_codes, start_time, end_time): request = SwarmRequest() request.set_collection(*[f"SW_OPER_AUX_OBSM2_:{c}" for c in IAGA_codes], verbose=False) request.set_products( measurements=["B_NEC", "IAGA_code"], ) data = request.get_between(start_time, end_time, asynchronous=False, show_progress=False) ds = data.as_xarray(reshape=True) return ds ds_ground_obs = fetch_ground_obs(["ABK", "LYC", "UPS"], START_TIME, END_TIME) ds_ground_obs ``` By specifiying `reshape=True` when loading the xarray object, a multi-dimensional dataset is formed with a new `IAGA_code` axis. Here we show the three vector components from each observatory: ``` ds_ground_obs["B_NEC"].plot.line(x="Timestamp", row="NEC", col="IAGA_code", sharey=False); ``` Let's calculate $|\frac{dB}{dt}|$ and plot that instead. This is a good indication of the GIC risk, as a more rapidly changing magnetic field will induce a larger electric field in the ground. ``` def plot_groundobs_dbdt(ds_ground_obs): ds_ground_obs = ds_ground_obs.assign( dBdt=(ds_ground_obs["B_NEC"].diff("Timestamp")**2).sum(dim="NEC").pipe(np.sqrt) ) fig, axes = plt.subplots(nrows=3, figsize=(15, 7), sharey=True, sharex=True) for i, obs in enumerate(ds_ground_obs["IAGA_code"].values): _ds = ds_ground_obs.sel(IAGA_code=obs) lat = np.round(float(_ds["Latitude"]), 1) lon = np.round(float(_ds["Longitude"]), 1) label = f"{obs} (Lat {lat}, Lon {lon})" ds_ground_obs["dBdt"].sel(IAGA_code=obs).plot.line(x="Timestamp", ax=axes[i], label=label) axes[i].set_title("") axes[i].legend() axes[i].set_xlabel("") axes[i].set_ylabel("dB/dt\n[nT / min]") axes[i].grid() fig.tight_layout() return fig, axes fig_grdbdt, axes_grdbdt = plot_groundobs_dbdt(ds_ground_obs) ```
github_jupyter
# Riskfolio-Lib Tutorial: <br>__[Financionerioncios](https://financioneroncios.wordpress.com)__ <br>__[Orenji](https://www.orenj-i.net)__ <br>__[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)__ <br>__[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__ <a href='https://ko-fi.com/B0B833SXD' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi1.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a> ## Tutorial 27: Constraints on Numbers of Assets ## 1. Downloading the data: ``` import numpy as np import pandas as pd import yfinance as yf import warnings warnings.filterwarnings("ignore") pd.options.display.float_format = '{:.4%}'.format # Date range start = '2016-01-01' end = '2019-12-30' # Tickers of assets assets = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MMC', 'JPM', 'ZION', 'PSA', 'BAX', 'BMY', 'LUV', 'PCAR', 'TXT', 'TMO', 'DE', 'MSFT', 'HPQ', 'SEE', 'VZ', 'CNP', 'NI', 'T', 'BA'] assets.sort() # Downloading data data = yf.download(assets, start = start, end = end) data = data.loc[:,('Adj Close', slice(None))] data.columns = assets # Calculating returns Y = data[assets].pct_change().dropna() display(Y.head()) ``` ## 2. Estimating Mean Variance Portfolios ### 2.1 Calculating the portfolio that maximizes Sharpe ratio. ``` import riskfolio as rp # Building the portfolio object port = rp.Portfolio(returns=Y) # Calculating optimum portfolio # Select method and estimate input parameters: method_mu='hist' # Method to estimate expected returns based on historical data. method_cov='hist' # Method to estimate covariance matrix based on historical data. port.assets_stats(method_mu=method_mu, method_cov=method_cov, d=0.94) # Estimate optimal portfolio: model='Classic' # Could be Classic (historical), BL (Black Litterman) or FM (Factor Model) rm = 'CVaR' # Risk measure used, this time will be variance obj = 'Sharpe' # Objective function, could be MinRisk, MaxRet, Utility or Sharpe hist = True # Use historical scenarios for risk measures that depend on scenarios rf = 0 # Risk free rate l = 0 # Risk aversion factor, only useful when obj is 'Utility' w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist) display(w.T) ``` ### 2.2 Plotting portfolio composition ``` # Plotting the composition of the portfolio ax = rp.plot_pie(w=w, title='Sharpe Mean CVaR', others=0.05, nrow=25, cmap="tab20", height=6, width=10, ax=None) # Number of assets in portfolio n_assets = np.sum(np.where(np.round(w,4) > 0, 1, 0)).item() # Number of effective assets in portfolio nea = 1/np.sum(w ** 2).item() print('Number of Assets:', n_assets) print('Number of Effective Assets:', nea) ``` ### 2.3 Calculating the portfolio including a constraint on the maximum number of assets. This kind of constraint help us to put a limit in the maximum number of assets, this could be helpful for small investors that can't afford buy too many assets. ``` # First we need to set a solver that support Mixed Integer Programming port.solvers = ['MOSEK'] # Then we need to set the cardinality constraint (maximum number of assets) port.card = 5 w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist) display(w.T) ``` ### 2.4 Plotting portfolio composition ``` ax = rp.plot_pie(w=w, title='Sharpe Mean CVaR', others=0.05, nrow=25, cmap="tab20", height=6, width=10, ax=None) # Number of assets in portfolio n_assets = np.sum(np.where(np.round(w,4) > 0, 1, 0)).item() # Number of effective assets in portfolio nea = 1/np.sum(w ** 2).item() print('Number of Assets:', n_assets) print('Number of Effective Assets:', nea) ``` ### 2.5 Calculating the portfolio including a constraint on the minimum number of effective assets. This kind of constraint help us to put a limit in the minimum number of effective assets, this could be helpful to increase the portfolio diversification. ``` # First we need to delete the cardinality constraint port.card = None # Then we need to set the constraint on the minimum number of effective assets port.nea = 12 w = port.optimization(model=model, rm=rm, obj=obj, rf=rf, l=l, hist=hist) display(w.T) ``` ### 2.6 Plotting portfolio composition ``` ax = rp.plot_pie(w=w, title='Sharpe Mean CVaR', others=0.05, nrow=25, cmap = "tab20", height=6, width=10, ax=None) # Number of assets in portfolio n_assets = np.sum(np.where(np.round(w,4) > 0, 1, 0)).item() # Number of effective assets in portfolio nea = 1/np.sum(w ** 2).item() print('Number of Assets:', n_assets) print('Number of Effective Assets:', nea) ```
github_jupyter
# Getting started with development in `sktime` on Windows with PyCharm and Anaconda ## Objectives: Set up and install a development environment for `sktime` in Windows. This will involve: * cloning the repository within the **PyCharm** IDE **[(Section 1)](#Section-1:-Cloning-sktime-in-PyCharm)** * setting up an **Anaconda** environment for installing packages and running code **[(Section 2)](#Section-2:-Setting-up-an-Anaconda-environment-and-installing-sktime)** * configuring PyCharm to use the Anaconda environment and demonstrate how to run local tests with `pytest` **[(Section 3)](#Section-3:-Configuring-PyCharm-and-running-local-tests-with-pytest)** * demonstrating the use of `pre-commit` to reject and tidy messy code before committing **[(Section 4)](#Section-4:-Configuring-pre-commit-with-PyCharm)** > **_NOTE:_** This guide assumes you are starting from first principles with no existing environment/IDE configuration settings. The IDE that is used is PyCharm - this IDE is not a requirement for `sktime` development and you are free to use any/no IDE. **If you would like to only create an Anaconda environment and install `sktime` with its dependencies, please make sure you have cloned `sktime` through other means and skip down to Section 2**. ## Pre-requisites: * [Anaconda](https://www.anaconda.com/products/individual#windows) (the version available at the time of writing was Anaconda3-2021.11) Anaconda will be used for installing `sktime` with its dependencies into a virtual environment. * [PyCharm](https://www.jetbrains.com/pycharm/download/#section=windows) (the version available at the time of writing was 2021.2.3) PyCharm is the IDE that will be used in the following example, but developers are not restricted to using PyCharm if they would prefer to use another IDE. * [Build Tools for Visual Studio 2022/Visual Studio 2022 with Desktop Development in C++](https://visualstudio.microsoft.com/downloads/?q=build+tools) A C++ compiler is required for compiling Cython files during the full installation of the development version of `sktime`. This can be achieved by just installing the Build Tools for Visual Studio or, if you prefer, you can install the full Visual Studio editor (with either installation, make sure to tick the **Desktop development in C++** option when installing to ensure that a C++ compiler is included). * (Optional) Git for Windows - This is required, and you can install it manually if you wish, but PyCharm can do this for you and it is included in the instructions for Step 1 below. # Section 1: Cloning `sktime` in PyCharm ### 1. Open **PyCharm** and select the **Get from VCS** option: ![03_pycharm_start.png](img/windows_installation/03_pycharm_start.png) ### 2. You should see the following screen: ![04_pycharm_no_github_no_git.png](img/windows_installation/04_pycharm_no_github_no_git.png) The example above shows an installation where **the user is not logged into GitHub** within PyCharm and **does not have Git (Git for Windows) installed**. Step 3 demonstrates how to log in to GitHub (useful for later) and Step 4 demonstrates how to instal Git. If you have already completed either of these steps for another project, please skip ahead to Step 5 where the project is cloned. ### 3. To log into your GitHub account, click the GitHub tab and then the *Log In via GitHub...* option. ![05_login_with_github.png](img/windows_installation/05_login_with_github.png) This should launch your browser where you can log in to your account. Once you complete this step, you can return to PyCharm and you should see that your GitHub handle is now listed where it previously stated *No accounts*. This is where you could clone any of your own repositories if you wish, but clock back to the *Repository URL* option to now install Git and clone `sktime` ### 4. If Git is not installed on your machine then you should see the following highlighted message: ![06_install_git_within_pycharm.png](img/windows_installation/06_install_git_within_pycharm.png) Click the *Download and Install* link and PyCharm will automatically install Git for Windows on your machine. ### 5. If you are correctly logged into your GitHub account with Git installed then you should now see your username on the left under the **GitHub** tab and you should see the message **Git has been installed** underneath the two text fields: ![07_git_installed_enter_sktime_url.png](img/windows_installation/07_git_installed_enter_sktime_url.png) With your GitHub account logged in, an Git installed, it is now time to clone `sktime`. Enter the URL of the GitHub repository (https://github.com/alan-turing-institute/sktime) into the **URL** field, set the location where you would like the files to be downloaded to in the **Directory** field, and press the **Clone** button at the bottom of the prompt to initiate the download of `sktime` to your local machine. ### 6. Once PyCharm has cloned the project (this can take a minute or so) you should see the following screen: ![08_sktime_in_pycharm_no_interpreter.png](img/windows_installation/08_sktime_in_pycharm_no_interpreter.png) In particular, the bottom-right corner indicates that the IDE is on the `main` branch of `sktime` but no interpreter is selected for this project (if you have used PyCharm before then it may default to an existing interpreter from another project, however). We will now switch to Anaconda to set up an environment and install the necessary libraries to develop with `sktime`. # Section 2: Setting up an Anaconda environment and installing `sktime` > **_NOTE:_** These instructions are valid as of 24th November 2021. There are known issues with the `fbprohpet` dependency and the instructions below include a temporary work-around. This will be addressed in a future update and these instructions will be updated to reflect this > **_NOTE:_** If you are already familiar with Anaconda/this is not your first time following these instructions and would like a shortcut then the steps below walk-through these specific instructions: ``` conda create --name sktime python=3.8 conda activate sktime pip install -e .[all_extras] pip install pytest pip install esig conda install -c conda-forge fbprophet pip install scipy --force-reinstall pip install numpy==1.19.3 --force-reinstall ``` ### 7. Create a new Anaconda environment for `sktime` development Open Anaconda prompt to create a new conda environment for `sktime` development. We will also call the environment `sktime` in this example (you can use a different name if you wish as long as you are consistent when initialising the env and also selecting it later in PyCharm) `sktime` currently supports Python version 3.8, hence we will create the new environment with this requirement using the following statement: ``` conda create --name sktime python=3.8 ``` You should see the following where you will be prompted to accept/reject the proposed package plan - accept by typing `y` and pressing enter ![09_create_conda_env.png](img/windows_installation/09_create_conda_env.png) ### 8. Activate the environment and install `sktime` Once the environment is created you can activate it with `conda activate <env_name>` where `env_name` is the name of the environment that you have just created. In this case, we will use: ``` conda activate sktime ``` Once your new environment is correctly activated you should see that `(base)` changes to the name of your environment (`sktime` in this example). We are now ready to navigate to the **root directory** of your `sktime` project to `pip install` the setup file for `sktime`. We will do this with the command: ``` pip install -e .[all_extras] ``` where `-e` means that it is installed in editable mode (useful for development), `.` specifies that the installation instructions should come from the current directory, and `[all_extras]` means that all soft dependencies will be included. This also means that Cython will be included in the installation and any Cython code in the repository will be compiled on your machine during this command's execution (this step can therefore take a minute or two to complete). A screenshot of what it should look like when activating your environment and navigating to your `sktime` root directory is as follows: ![10_activate_navigate_install.png](img/windows_installation/10_activate_navigate_install.png) > **_NOTE:_** As mentioned at the beginning of Section 2 there is a known issue with `fbprophet` when being installed this way. It is expected that you will see red text and errors referring to `fbprophet` here and we will address this in the subsequent steps. You can expect to see error output such as the following, but note that below the error, the other packages are being correctly installed at this stage: ![11_expected_fbprophet_output.png](img/windows_installation/11_expected_fbprophet_output.png) ### 9. Install `pytest` and `esig` These two packages are not currently included as dependencies but are useful for development. Installation of both is straight forward with: ``` pip install pytest pip install esig ``` Successful installation of both packages should appear as follows: ![12_install_pytest_esig.png](img/windows_installation/12_install_pytest_esig.png) ### 10. Install `fbprophet` via `conda` rather than `pip` The next step is to rectify the previous issues with installing `fbprophet`. To do this, call: ``` conda install -c conda-forge fbprophet ``` This will bring a large number of packages and updates and you should see a screen similar to the following: ![13_conda_install_fbprohpet.png](img/windows_installation/13_conda_install_fbprohpet.png) Accept the installation and we are *nearly* done... ### 11. Reinstall `scipy` and `numpy` Installing `fbprophet` in this way modifies two previously installed dependencies. `scipy` must be reinstalled and, when doing so, this upgrades `numpy` to a version higher than other packages can support. Therefore we must run two further commands to first reinstall `scipy`, and then another to downgrade `numpy` again. These commands are as follows: ``` pip install scipy --force-reinstall pip install numpy==1.19.3 --force-reinstall ``` Once complete, your terminal should appear similar to the following: ![14_reinstall_cipy_downgrade_numpy.png](img/windows_installation/14_reinstall_cipy_downgrade_numpy.png) ### Congratulations - `sktime` is now installed and your environment is ready to use! # Section 3: Configuring PyCharm and running local tests with `pytest` At the end of Section 1 we saw that our PyCharm project did not have an interpreter (or you may have a default environment/an existing environment that has been detected for another project). We now want to set our PyCharm project to use the newly created Anaconda environment from Section 2. ### 12. Open File -> Settings ![15_pycharm_interpreter_settings.png](img/windows_installation/15_pycharm_interpreter_settings.png) ### 13. Select *Python Interpreter* from the *Project* heading. Click the gear icon at the top-right and select *Add...* when the option appears ![16_add_new_env.png](img/windows_installation/16_add_new_env.png) ### 14. Add our existing environment to this project We will now add our existing Anaconda environment as this project's interpreter. Select *Existing interpreter* and then click the `...` button to navigate for the `python.exe` for your Anaconda environment (note: this should be found wherever you installed Anaconda within the `env/<your_env_name>` directory). For example: ![17_add_new_conda_env.png](img/windows_installation/17_add_new_conda_env.png) Press *OK* to confirm and you can now close the project settings. Your environment is now ready to use with your PyCharm project, so let's test this by running a test locally with `pytest` ### 15. Run `test_all_panel_estimators` This step will demonstrate how we can run tests locally in PyCharm. The objective of this is to both demonstrate how to run tests, but also to verify your installation of `sktime`. We will run the `test_all_panel_estimators` file as these tests require the dependencies to be correctly installed and also for the Cython code within `sktime` to be correctly compiled on your machine. To run these tests, simply expand `sktime/series_as_features/tests` and right-click `test_all_panel_estimators` and select *Run 'pytest in test_all_p...'* as follows: ![18_run_tests_to_verify.png](img/windows_installation/18_run_tests_to_verify.png) ### 16. Verify all tests passed At the time of writing `test_all_panel_estimators` contained 117 tests that should all pass if the IDE and environment are configured and installed correctly (this number may change in future releases if tests are added/removed). If you have reached this step then you should be ready to write your own contributions for `sktime`. Once you have done that you will want to make sure that you have correctly configured `pre-commit` before trying to push any code, however... ![19_test_success.png](img/windows_installation/19_test_success.png) # Section 4: Configuring `pre-commit` with PyCharm `pre-commit` is a very useful package for checking your code for simple stye errors at the commit stage. This is very useful when working on large collaborative projects as it allows code reviewers to focus on the function of new code rather than conformity to style. For example, consider the following code: ![21_pre-commit_examples.png](img/windows_installation/21_pre-commit_examples.png) The code is not very useful but it is clear that it contains a number of formatting errors: 1. line 3 includes unnecessary spaces 2. line 3 includes an unnecessary semi-colon at the end of the line 3. there are multiple blank lines at the end of the file (lines 10 to 14) 4. there is an unused import on line 1 5. the variable on line 6 does not conform to Python naming conventions We will see that `pre-commit` can help with *some* of these issues (e.g. 1-3) but it is not a magic bullet that can fix everything - the emphasis is still on the programmer to make sure that their code conforms to required conventions and `pre-commit` can help with this. ### 17. Install `pre-commit` Switch back to Anaconda prompt (or open a new window and activate your development environment if you are returning) and run: ``` pip install pre-commit ``` and then ``` pre-commit install ``` You should see the following: ![20_install_pre-commit.png](img/windows_installation/20_install_pre-commit.png) > **_NOTE:_** When running `pre-commit install`, if you see a message stating that Git is not installed then it is likely that you need to update your system Path variables to include Git. To do this, press the Windows key and search for *Edit the system environment variables*. On the **System Properties** dialog that appears, select the *Advanced* tab and press the *Environment Variables...* button on the bottom-right. Double-click the entry for **Path** and add `C:\ProgramFilesGit\bin\` and `C:\ProgramFilesGit\cmd\` (these paths may be slightly different on your installation). Once you have updated the variables, press *OK* on all of the windows to close them and restart Anaconda Prompt - if this was your issue, `pre-commit install` should now work once you activate your environment ### 18. Attempt to commit some code In the example below we are trying to commit the poorly formatted code from above. To do this, click *Git -> Commit...* and this will open the *Commit* pane (this may appear in a separate window if your IDE is configured differently) ![22_create_new_commit.png](img/windows_installation/22_create_new_commit.png) ### 19. Ensure that *Run Git hooks* is ticked You can find this option by selecting the gear icon and it is the last option in the *Before Commit* section: ![23_ensure_check_hooks_ticket.png](img/windows_installation/23_ensure_check_hooks_ticket.png) ### 20. Attempt to commit the poorly formatted code Ensure that a commit message is included and then attempt to commit the code. If your code has similar issues to the example above then the commit will fail. This is indicated by the pop-up in the bottom-right corner and selecting *Show details in console* will explain what exactly failed. A convenient feature of `pre-commit` is that the issues are automatically fixed in the source code too: ![24_failed_commit_with_errors_and_automatic_correction.png](img/windows_installation/24_failed_commit_with_errors_and_automatic_correction.png) **However**, it is important to note that `pre-commit` did not remove the unused import or correct the variable name. Therefore, it is very useful for helping you to produce tidy code but it is not a guarantee, and it is important to still manually check that your code conforms to `sktime` style guidelines. # The End. Congratulations, you should now have a correctly configured development environment for `sktime` using PyCharm, Anaconda, `pytest` and `pre-commit`. If you would like to see examples in code before getting started then please make sure to have a look at the JuPyter notebooks that are included in the *examples* directory and in the `sktime` documentation.
github_jupyter
``` %matplotlib inline import matplotlib.pyplot as plt import tensorflow as tf import numpy as np import random import math # Image manipulation. from PIL import Image from scipy.ndimage.filters import gaussian_filter #import inception5h #inception5h.maybe_download() #model = inception5h.Inception5h() #len(model.layer_tensors) # to know the different layers in the inception 5h model import tensorflow as tf def printTensors(pb_file): # read pb into graph_def with tf.gfile.GFile(pb_file, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) # import graph_def with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def) # print operations for op in graph.get_operations(): print(op.name) printTensors("inception/5h/tensorflow_inception_graph.pb") # to load the image using PIL def load_image(filename): try: original = Image.open(filename) print("the size of the image is :") print(original.format,original.size) except: print ("Unable to load image") return np.float32(original) def save_image(image, filename): # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert to bytes. image = image.astype(np.uint8) # Write the image-file in jpeg-format. with open(filename, 'wb') as file: Image.fromarray(image).save(file, 'jpeg') def plot_image(image): # Assume the pixel-values are scaled between 0 and 255. if False: # Convert the pixel-values to the range between 0.0 and 1.0 image = np.clip(image/255.0, 0.0, 1.0) # Plot using matplotlib. plt.imshow(image, interpolation='lanczos') plt.show() else: # Ensure the pixel-values are between 0 and 255. image = np.clip(image, 0.0, 255.0) # Convert pixels to bytes. image = image.astype(np.uint8) # Convert to a PIL-image and display it. display(Image.fromarray(image)) def normalize_image(x): # Get the min and max values for all pixels in the input. x_min = x.min() x_max = x.max() # Normalize so all values are between 0.0 and 1.0 x_norm = (x - x_min) / (x_max - x_min) return x_norm def plot_gradient(gradient): # Normalize the gradient so it is between 0.0 and 1.0 gradient_normalized = normalize_image(gradient) # Plot the normalized gradient. plt.imshow(gradient_normalized, interpolation='bilinear') plt.show() def resize_image(image, size=None, factor=None): # If a rescaling-factor is provided then use it. if factor is not None: # Scale the numpy array's shape for height and width. size = np.array(image.shape[0:2]) * factor # The size is floating-point because it was scaled. # PIL requires the size to be integers. size = size.astype(int) else: # Ensure the size has length 2. size = size[0:2] # The height and width is reversed in numpy vs. PIL. size = tuple(reversed(size)) # Ensure the pixel-values are between 0 and 255. img = np.clip(image, 0.0, 255.0) # Convert the pixels to 8-bit bytes. img = img.astype(np.uint8) # Create PIL-object from numpy array. img = Image.fromarray(img) # Resize the image. img_resized = img.resize(size, Image.LANCZOS) # Convert 8-bit pixel values back to floating-point. img_resized = np.float32(img_resized) return img_resized # Deep Dream Algorithm def get_tile_size(num_pixels, tile_size=400): """ num_pixels is the number of pixels in a dimension of the image. tile_size is the desired tile-size. """ # How many times can we repeat a tile of the desired size. num_tiles = int(round(num_pixels / tile_size)) # Ensure that there is at least 1 tile. num_tiles = max(1, num_tiles) # The actual tile-size. actual_tile_size = math.ceil(num_pixels / num_tiles) return actual_tile_size def tiled_gradient(gradient, image, tile_size=400): # Allocate an array for the gradient of the entire image. grad = np.zeros_like(image) # Number of pixels for the x- and y-axes. x_max, y_max, _ = image.shape # Tile-size for the x-axis. x_tile_size = get_tile_size(num_pixels=x_max, tile_size=tile_size) # 1/4 of the tile-size. x_tile_size4 = x_tile_size // 4 # Tile-size for the y-axis. y_tile_size = get_tile_size(num_pixels=y_max, tile_size=tile_size) # 1/4 of the tile-size y_tile_size4 = y_tile_size // 4 # Random start-position for the tiles on the x-axis. # The random value is between -3/4 and -1/4 of the tile-size. # This is so the border-tiles are at least 1/4 of the tile-size, # otherwise the tiles may be too small which creates noisy gradients. x_start = random.randint(-3*x_tile_size4, -x_tile_size4) while x_start < x_max: # End-position for the current tile. x_end = x_start + x_tile_size # Ensure the tile's start- and end-positions are valid. x_start_lim = max(x_start, 0) x_end_lim = min(x_end, x_max) # Random start-position for the tiles on the y-axis. # The random value is between -3/4 and -1/4 of the tile-size. y_start = random.randint(-3*y_tile_size4, -y_tile_size4) while y_start < y_max: # End-position for the current tile. y_end = y_start + y_tile_size # Ensure the tile's start- and end-positions are valid. y_start_lim = max(y_start, 0) y_end_lim = min(y_end, y_max) # Get the image-tile. img_tile = image[x_start_lim:x_end_lim, y_start_lim:y_end_lim, :] # Create a feed-dict with the image-tile. feed_dict = model.create_feed_dict(image=img_tile) # Use TensorFlow to calculate the gradient-value. g = session.run(gradient, feed_dict=feed_dict) # Normalize the gradient for the tile. This is # necessary because the tiles may have very different # values. Normalizing gives a more coherent gradient. g /= (np.std(g) + 1e-8) # Store the tile's gradient at the appropriate location. grad[x_start_lim:x_end_lim, y_start_lim:y_end_lim, :] = g # Advance the start-position for the y-axis. y_start = y_end # Advance the start-position for the x-axis. x_start = x_end return grad def optimize_image(layer_tensor, image, num_iterations=10, step_size=3.0, tile_size=400, show_gradient=False): """ Use gradient ascent to optimize an image so it maximizes the mean value of the given layer_tensor. Parameters: layer_tensor: Reference to a tensor that will be maximized. image: Input image used as the starting point. num_iterations: Number of optimization iterations to perform. step_size: Scale for each step of the gradient ascent. tile_size: Size of the tiles when calculating the gradient. show_gradient: Plot the gradient in each iteration. """ # Copy the image so we don't overwrite the original image. img = image.copy() print("Processing image: ") # Use TensorFlow to get the mathematical function for the # gradient of the given layer-tensor with regard to the # input image. This may cause TensorFlow to add the same # math-expressions to the graph each time this function is called. # It may use a lot of RAM and could be moved outside the function. gradient = model.get_gradient(layer_tensor) for i in range(num_iterations): # Calculate the value of the gradient. # This tells us how to change the image so as to # maximize the mean of the given layer-tensor. grad = tiled_gradient(gradient=gradient, image=img) # Blur the gradient with different amounts and add # them together. The blur amount is also increased # during the optimization. This was found to give # nice, smooth images. You can try and change the formulas. # The blur-amount is called sigma (0=no blur, 1=low blur, etc.) # We could call gaussian_filter(grad, sigma=(sigma, sigma, 0.0)) # which would not blur the colour-channel. This tends to # give psychadelic / pastel colours in the resulting images. # When the colour-channel is also blurred the colours of the # input image are mostly retained in the output image. sigma = (i * 4.0) / num_iterations + 0.5 grad_smooth1 = gaussian_filter(grad, sigma=sigma) grad_smooth2 = gaussian_filter(grad, sigma=sigma*2) grad_smooth3 = gaussian_filter(grad, sigma=sigma*0.5) grad = (grad_smooth1 + grad_smooth2 + grad_smooth3) # Scale the step-size according to the gradient-values. # This may not be necessary because the tiled-gradient # is already normalized. step_size_scaled = step_size / (np.std(grad) + 1e-8) # Update the image by following the gradient. img += grad * step_size_scaled if show_gradient: # Print statistics for the gradient. msg = "Gradient min: {0:>9.6f}, max: {1:>9.6f}, stepsize: {2:>9.2f}" print(msg.format(grad.min(), grad.max(), step_size_scaled)) # Plot the gradient. plot_gradient(grad) else: # Otherwise show a little progress-indicator. print(". ", end="") return img import os import cav working_dir = '/Users/tyler/Desktop/dissertation/programming/tcav_on_azure' concept = 'zebra' cav_dict = {} layer_names = ['mixed0','mixed1','mixed2','mixed3','mixed4','mixed5','mixed6','mixed7','mixed8','mixed9','mixed10'] #layer_names = ['mixed0'] for layer_name in layer_names: subpath = concept + '-random500_0-' + layer_name cav_path = 'cav_dir/' + subpath + '-linear-0.1.pkl' path = os.path.join(working_dir, cav_path) this_cav = cav.CAV.load_cav(path) cav_dict[layer_name] = this_cav.cavs[0] step = 0.01 # Gradient ascent step size num_octave = 5 # Number of scales at which to run gradient ascent octave_scale = 1.4 # Size ratio between scales iterations = 10 # Number of ascent steps per scale max_loss = 100000000000 #result_prefix = '/home/tyler/Desktop/tcav_on_azure/results/test' size_dict = {'mixed0': 313600,'mixed1': 352800,'mixed2': 352800,'mixed3': 221952,'mixed4': 221952,'mixed5': 221952,'mixed6': 221952,'mixed7': 221952,'mixed8': 81920,'mixed9': 131072,'mixed10': 131072} settings = { 'features': { 'mixed0': 1,#/313600, 'mixed1': 1,#/352800, 'mixed2': 1,#/352800, 'mixed3': 1,#/221952, 'mixed4': 1,#/221952, 'mixed5': 1,#/221952, 'mixed6': 1,#/221952, 'mixed7': 1,#/221952, 'mixed8': 1,#/81920, 'mixed9': 1,#/131072, 'mixed10': 1#/131072 },} layer_dict = dict([(layer.name, layer) for layer in model.layers]) sess = K.get_session() loss_2 = K.variable(0.) for layer_name in settings['features']: coeff = settings['features'][layer_name] assert layer_name in layer_dict.keys(), 'Layer ' + layer_name + ' not found in model.' coeff = settings['features'][layer_name] acts = layer_dict[layer_name].output flat_acts = K.flatten(acts) len_of_acts = flat_acts.shape[0] print(len_of_acts) layer_cav = K.variable(cav_dict[layer_name].reshape(-1,1)) n = layer_cav.shape[0] print(n, layer_name) n_tensor = K.constant(n.value/1000) features_shape = tf.shape(flat_acts) H = features_shape[0] layer_cav_slice = K.slice(layer_cav,(0,0),(H,1)) flat_acts_slice = K.reshape(flat_acts, shape=[1,H]) print('layer_cav shape is ' + str(layer_cav_slice.shape)) print('acts shape is ' + str(flat_acts_slice.shape)) scaling = K.prod(K.cast(K.shape(acts), 'float32')) loss_2 += coeff * K.dot(flat_acts_slice,layer_cav_slice) / scaling def recursive_optimize(layer_tensor, image, num_repeats=4, rescale_factor=0.7, blend=0.2, num_iterations=10, step_size=3.0, tile_size=400): """ Recursively blur and downscale the input image. Each downscaled image is run through the optimize_image() function to amplify the patterns that the Inception model sees. Parameters: image: Input image used as the starting point. rescale_factor: Downscaling factor for the image. num_repeats: Number of times to downscale the image. blend: Factor for blending the original and processed images. Parameters passed to optimize_image(): layer_tensor: Reference to a tensor that will be maximized. num_iterations: Number of optimization iterations to perform. step_size: Scale for each step of the gradient ascent. tile_size: Size of the tiles when calculating the gradient. """ # Do a recursive step? if num_repeats>0: # Blur the input image to prevent artifacts when downscaling. # The blur amount is controlled by sigma. Note that the # colour-channel is not blurred as it would make the image gray. sigma = 0.5 img_blur = gaussian_filter(image, sigma=(sigma, sigma, 0.0)) # Downscale the image. img_downscaled = resize_image(image=img_blur, factor=rescale_factor) # Recursive call to this function. # Subtract one from num_repeats and use the downscaled image. img_result = recursive_optimize(layer_tensor=layer_tensor, image=img_downscaled, num_repeats=num_repeats-1, rescale_factor=rescale_factor, blend=blend, num_iterations=num_iterations, step_size=step_size, tile_size=tile_size) # Upscale the resulting image back to its original size. img_upscaled = resize_image(image=img_result, size=image.shape) # Blend the original and processed images. image = blend * image + (1.0 - blend) * img_upscaled print("Recursive level:", num_repeats) # Process the image using the DeepDream algorithm. img_result = optimize_image(layer_tensor=layer_tensor, image=image, num_iterations=num_iterations, step_size=step_size, tile_size=tile_size) return img_result import os os.environ['KERAS_BACKEND'] = 'tensorflow' from tensorflow import keras from keras.applications import inception_v3 from keras.applications.inception_v3 import decode_predictions from keras.models import Model, load_model import keras.backend as K from keras.preprocessing.image import load_img, img_to_array from sklearn.metrics.pairwise import cosine_similarity import numpy as np from numpy.linalg import norm import scipy import pickle from os import listdir from os.path import isfile, join import operator from PIL import Image from keras.preprocessing import image import os import math import PIL.Image from sklearn.metrics import pairwise import matplotlib.pyplot as plt from keras.applications.inception_v3 import preprocess_input from sklearn import linear_model from sklearn import metrics from sklearn.model_selection import train_test_split import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore", category=FutureWarning) import pandas as pd from scipy import stats import tensorflow as tf K.set_learning_phase(0) model = inception_v3.InceptionV3(weights='imagenet',include_top=False) dream = model.input print('Model loaded.') # Tensorflow Session #session = tf.InteractiveSession(graph=model.graph) image=load_image(filename='sky.jpg') #plot_image(image) ``` First we need a reference to the tensor inside the Inception model which we will maximize in the DeepDream algorithm. In this case we select the entire 3rd layer of the Inception model (layer index 2). It has 192 channels and we will try and maximize the average value across all these channels. ``` layer_tensor = model.layer_tensors[2] layer_tensor img_result = recursive_optimize(layer_tensor=layer_tensor, image=image, num_iterations=10, step_size=3.0, rescale_factor=0.7, num_repeats=4, blend=0.2) layer_tensor = model.layer_tensors[6] img_result = recursive_optimize(layer_tensor=layer_tensor, image=image, num_iterations=10, step_size=3.0, rescale_factor=0.7, num_repeats=4, blend=0.2) layer_tensor = model.layer_tensors[9][:,:,:,0:2] img_result = recursive_optimize(layer_tensor=layer_tensor, image=image, num_iterations=10, step_size=3.0, rescale_factor=0.7, num_repeats=4, blend=0.2) layer_tensor = model.layer_tensors[10] img_result = recursive_optimize(layer_tensor=layer_tensor, image=image, num_iterations=10, step_size=3.0, rescale_factor=0.7, num_repeats=4, blend=0.2) layer_tensor = model.layer_tensors[10][:,:,:,0:3] img_result = recursive_optimize(layer_tensor=layer_tensor, image=image, num_iterations=10, step_size=3.0, rescale_factor=0.7, num_repeats=4, blend=0.2) # To save the final Output image_save=save_image(img_result,"test_output/test_output_11.jpg") # don't forget to have a look over the deep_dream_final_output.html file to see the processed outputs. ```
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv(r'C:\Users\Sagar Kandpal\Desktop\ML EXAMPLE\Modular\ML_Live_Class\data\mouse_viral_study.csv') df.head() sns.scatterplot(x = 'Med_1_mL', y = 'Med_2_mL', data =df, hue = 'Virus Present') # creating hyperplane manually x = np.linspace(0,10,100) m = -1 b = 11 y = m*x + b plt.plot(x,y, 'black') sns.scatterplot(x = 'Med_1_mL', y = 'Med_2_mL', data =df, hue = 'Virus Present') # creating hyperplane manually x = np.linspace(0,10,100) m = -1.1 b = 11 y = m*x + b plt.plot(x,y, 'black') from sklearn.svm import SVC help(SVC) X = df.drop('Virus Present', axis =1) y = df['Virus Present'] model = SVC(kernel = 'poly', C = 1000) model.fit(X,y) # CODE SOURCE IS DIRECTLY FROM DOCUMENTATION # https://scikit-learn.org/stable/auto_examples/svm/plot_separating_hyperplane.html import numpy as np import seaborn as sns import matplotlib.pyplot as plt def plot_svm_boundary(model,X,y): X = X.values y = y.values # Scatter Plot plt.scatter(X[:, 0], X[:, 1], c=y, s=30,cmap='seismic') # plot the decision function ax = plt.gca() xlim = ax.get_xlim() ylim = ax.get_ylim() # create grid to evaluate model xx = np.linspace(xlim[0], xlim[1], 30) yy = np.linspace(ylim[0], ylim[1], 30) YY, XX = np.meshgrid(yy, xx) xy = np.vstack([XX.ravel(), YY.ravel()]).T Z = model.decision_function(xy).reshape(XX.shape) # plot decision boundary and margins ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--']) # plot support vectors ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k') plt.show() plot_svm_boundary(model, X, y) # Exploring Hyperparameters in SVM model = SVC(kernel = 'linear', C = 0.05) model.fit(X,y) plot_svm_boundary(model, X,y) model = SVC(kernel = 'rbf', C =5) model.fit(X,y) plot_svm_boundary(model, X, y) help(SVC) model = SVC(kernel = 'rbf', C =1, gamma = 2) # As gamma value is increasing it fits more support vectors near the margin model.fit(X,y) plot_svm_boundary(model, X, y) model = SVC(kernel = 'rbf', C =1, gamma = 'scale') model.fit(X,y) plot_svm_boundary(model, X, y) model = SVC(kernel = 'sigmoid') model.fit(X,y) plot_svm_boundary(model, X, y) model = SVC(kernel = 'poly', C=1, degree = 9) model.fit(X,y) plot_svm_boundary(model, X, y) from sklearn.model_selection import GridSearchCV svm_model = SVC() param_grid = {'C': [0.01,0.1, 1], 'kernel': ['linear', 'rbf', 'sigmoid', 'poly']} grid_model = GridSearchCV(svm_model, param_grid) grid_model.fit(X,y) grid_model.best_params_ ```
github_jupyter
# NTDS'18 tutorial 2: build a graph from an edge list [Benjamin Ricaud](https://people.epfl.ch/benjamin.ricaud), [EPFL LTS2](https://lts2.epfl.ch) * Dataset: [Open Tree of Life](https://tree.opentreeoflife.org) * Tools: [pandas](https://pandas.pydata.org), [numpy](http://www.numpy.org), [networkx](https://networkx.github.io), [gephi](https://gephi.org/) ## Tools The below line is a [magic command](https://ipython.readthedocs.io/en/stable/interactive/magics.html) that allows plots to appear in the notebook. ``` %matplotlib inline ``` The first thing is always to import the packages we'll use. ``` import pandas as pd import numpy as np import networkx as nx ``` Tutorials on pandas can be found at: * <https://pandas.pydata.org/pandas-docs/stable/10min.html> * <https://pandas.pydata.org/pandas-docs/stable/tutorials.html> Tutorials on numpy can be found at: * <https://docs.scipy.org/doc/numpy/user/quickstart.html> * <http://www.scipy-lectures.org/intro/numpy/index.html> * <http://www.scipy-lectures.org/advanced/advanced_numpy/index.html> A tutorial on networkx can be found at: * <https://networkx.github.io/documentation/stable/tutorial.html> ## Import the data We will play with a excerpt of the Tree of Life, that can be found together with this notebook. This dataset is reduced to the first 1000 taxons (starting from the root node). The full version is available here: [Open Tree of Life](https://tree.opentreeoflife.org/about/taxonomy-version/ott3.0). ![Public domain, https://en.wikipedia.org/wiki/File:Phylogenetic_tree.svg](figures/phylogenetic_tree.png) ![Public Domain, https://commons.wikimedia.org/w/index.php?curid=3633804](figures/tree_of_life.png) ``` tree_of_life = pd.read_csv('data/taxonomy_small.tsv', sep='\t\|\t?', encoding='utf-8', engine='python') ``` If you do not remember the details of a function: ``` pd.read_csv? ``` For more info on the separator, see [regex](https://docs.python.org/3.6/library/re.html). Now, what is the object `tree_of_life`? It is a Pandas DataFrame. ``` tree_of_life ``` The description of the entries is given here: https://github.com/OpenTreeOfLife/reference-taxonomy/wiki/Interim-taxonomy-file-format ## Explore the table ``` tree_of_life.columns ``` Let us drop some columns. ``` tree_of_life = tree_of_life.drop(columns=['sourceinfo', 'uniqname', 'flags','Unnamed: 7']) tree_of_life.head() ``` Pandas infered the type of values inside each column (int, float, string and string). The parent_uid column has float values because there was a missing value, converted to `NaN` ``` print(tree_of_life['uid'].dtype, tree_of_life.parent_uid.dtype) ``` How to access individual values. ``` tree_of_life.iloc[0, 2] tree_of_life.loc[0, 'name'] ``` **Exercise**: Guess the output of the below line. ``` # tree_of_life.uid[0] == tree_of_life.parent_uid[1] ``` Ordering the data. ``` tree_of_life.sort_values(by='name').head() ``` ## Operation on the columns Unique values, useful for categories: ``` tree_of_life['rank'].unique() ``` Selecting only one category. ``` tree_of_life[tree_of_life['rank'] == 'species'].head() ``` How many species do we have? ``` len(tree_of_life[tree_of_life['rank'] == 'species']) tree_of_life['rank'].value_counts() ``` ## Building the graph Let us build the adjacency matrix of the graph. For that we need to reorganize the data. First we separate the nodes and their properties from the edges. ``` nodes = tree_of_life[['uid', 'name','rank']] edges = tree_of_life[['uid', 'parent_uid']] ``` When using an adjacency matrix, nodes are indexed by their row or column number and not by a `uid`. Let us create a new index for the nodes. ``` # Create a column for node index. nodes.reset_index(level=0, inplace=True) nodes = nodes.rename(columns={'index':'node_idx'}) nodes.head() # Create a conversion table from uid to node index. uid2idx = nodes[['node_idx', 'uid']] uid2idx = uid2idx.set_index('uid') uid2idx.head() edges.head() ``` Now we are ready to use yet another powerful function of Pandas. Those familiar with SQL will recognize it: the `join` function. ``` # Add a new column, matching the uid with the node_idx. edges = edges.join(uid2idx, on='uid') # Do the same with the parent_uid. edges = edges.join(uid2idx, on='parent_uid', rsuffix='_parent') # Drop the uids. edges = edges.drop(columns=['uid','parent_uid']) edges.head() ``` The above table is a list of edges connecting nodes and their parents. ## Building the (weighted) adjacency matrix We will use numpy to build this matrix. Note that we don't have edge weights here, so our graph is going to be unweighted. ``` n_nodes = len(nodes) adjacency = np.zeros((n_nodes, n_nodes), dtype=int) for idx, row in edges.iterrows(): if np.isnan(row.node_idx_parent): continue i, j = int(row.node_idx), int(row.node_idx_parent) adjacency[i, j] = 1 adjacency[j, i] = 1 adjacency[:15, :15] ``` Congratulations, you have built the adjacency matrix! ## Graph visualization To conclude, let us visualize the graph. We will use the python module networkx. ``` # A simple command to create the graph from the adjacency matrix. graph = nx.from_numpy_array(adjacency) ``` In addition, let us add some attributes to the nodes: ``` node_props = nodes.to_dict() for key in node_props: # print(key, node_props[key]) nx.set_node_attributes(graph, node_props[key], key) ``` Let us check if it is correctly recorded: ``` graph.node[1] ``` Draw the graph with two different [layout algorithms](https://en.wikipedia.org/wiki/Graph_drawing#Layout_methods). ``` nx.draw_spectral(graph) nx.draw_spring(graph) ``` Save the graph to disk in the `gexf` format, readable by gephi and other tools that manipulate graphs. You may now explore the graph using gephi and compare the visualizations. ``` nx.write_gexf(graph, 'tree_of_life.gexf') ```
github_jupyter
# Airbnb price prediction ## Data exploration ``` import numpy as np import pandas as pd import seaborn as sns import os import matplotlib.pyplot as plt import seaborn as sns sns.set_style(style= "darkgrid") ``` ### Load data ``` dir_seatle = "data/Seatle" dir_boston = "data/Boston/" seatle_data = pd.read_csv(os.path.join(dir_seatle, "listings.csv")) boston_data = pd.read_csv(os.path.join(dir_boston, "listings.csv")) seatle_data.head() seatle_data.columns boston_data.columns seatle_data.describe() seatle_data.describe() ``` ## Data cleaning First of all, the column of price is not in the right format we need to convert it to float. ``` # Convert columns with dollar symbol ($) and , symbol (,) to float seatle_data["price"] = seatle_data["price"].str.replace(',', '').str.replace('$', '').astype(float) boston_data["price"] = boston_data["price"].str.replace(',', '').str.replace('$', '').astype(float) seatle_data.dropna(subset=["price"], inplace=True) boston_data.dropna(subset=["price"], inplace=True) ``` Remove outliers ``` # remove instance with more than 500 dollars seatle_data = seatle_data[seatle_data['price'] < 500] boston_data = boston_data[boston_data['price'] < 500] print("Seattle listings: {}".format(len(seatle_data))) print("Boston listings: {}".format(len(boston_data))) #make a list of wanted columns cols_to_keep = [ 'id', 'space', 'neighborhood_overview','host_since', 'host_response_time', 'host_response_rate', 'host_is_superhost', 'neighbourhood','zipcode','latitude', 'longitude', 'is_location_exact', 'property_type', 'room_type', 'accommodates', 'bathrooms', 'bedrooms', 'beds', 'bed_type', 'amenities', 'price', 'extra_people', 'minimum_nights','maximum_nights', 'availability_30', 'availability_60', 'availability_90', 'availability_365', 'number_of_reviews', 'review_scores_rating', 'review_scores_accuracy', 'review_scores_cleanliness', 'review_scores_checkin', 'review_scores_communication','review_scores_location', 'review_scores_value', 'reviews_per_month'] seatle_data = seatle_data[cols_to_keep] boston_data = boston_data[cols_to_keep] def get_cat_num_columns(df): '''return the list of categorical and numeric columns''' num_columns = df.select_dtypes(include=np.number).columns.tolist() cat_columns = df.columns.drop(num_columns) return cat_columns, num_columns def get_nan_percentage(df): ''' return the nan percentage for each column in df. ''' # percentage of values that are missing total_nan = df.isna().sum().sort_values(ascending=False) percentage_nan = (total_nan / df.shape[0]) * 100 tabel = pd.concat([total_nan, percentage_nan], axis=1, keys=['Total_nan_values', 'Percentage_of_nan_values']) return tabel seatle_cat_cols, seatle_num_cols = get_cat_num_columns(seatle_data) boston_cat_cols, boston_num_cols = get_cat_num_columns(boston_data) nan_data = get_nan_percentage(seatle_data) nan_perc = 10 nan_data["Percentage_of_nan_values"][nan_data["Percentage_of_nan_values"] > nan_perc].plot.barh() plt.title("Seatle columns with nan values percentage higher than {}".format(nan_perc)) nan_data = get_nan_percentage(boston_data) nan_perc = 10 nan_data["Percentage_of_nan_values"][nan_data["Percentage_of_nan_values"] > nan_perc].plot.barh() plt.title("Seatle columns with nan values percentage higher than {}".format(nan_perc)) ``` ### Fill missing values First we verify if the target has missing values in both datasets ``` # count nan values print("Seatle price has {} nan values".format(seatle_data["price"].isnull().sum())) print("Boston price has {} nan values".format(boston_data["price"].isnull().sum())) ``` #### Handling values type Handling numeric and categorical values separately. **Categorical fill nan** For categorical missing values, the most frequent class for each feature is used for imputation. ``` # impute missing values with the most frequent class # seatle data for var in seatle_cat_cols: seatle_data[var].fillna(seatle_data[var].value_counts().index[0], inplace=True) # Boston data for var in boston_cat_cols: boston_data[var].fillna(boston_data[var].value_counts().index[0], inplace=True) ``` **Numerical fill ann** Usually outliers in data impact the mean of the values and therefore the median is prefered in such a case. As we have some features with skewed distribution, we prepfer imputation by median to avoid outliers impact. ``` # an example of skewed feature feat15 = seatle_num_cols[15] sns.distplot(seatle_data[feat15]) # imputation using median # Seatle data for var in seatle_num_cols: seatle_data[var].fillna((seatle_data[var].median()), inplace=True) # Boston data for var in boston_num_cols: boston_data[var].fillna((boston_data[var].median()), inplace=True) # verify if there is nan values seatle_data.isnull().sum().max() # verify if there is nan values boston_data.isnull().sum().max() ``` Before work with numeric and categorical data, some numeric columns are declared as objects with others symbols. Therefore, we start by converting these columns to float. ``` # convert host_response_rate column which have % symbol to float seatle_data["host_response_rate"] = seatle_data["host_response_rate"].str.replace('%', '').astype(float) boston_data["host_response_rate"] = boston_data["host_response_rate"].str.replace('%', '').astype(float) # Create 3 new col which holds only year, month and month-year seperately for host since col. # This will help us in our analysis to answer business questions. seatle_data['host_since_Year'] = pd.DatetimeIndex(seatle_data['host_since']).year.astype(int) seatle_data['host_since_month'] = pd.DatetimeIndex(seatle_data['host_since']).month.astype(int) seatle_data['host_since_year-month'] = pd.to_datetime(seatle_data['host_since']).dt.to_period('M') boston_data['host_since_Year'] = pd.DatetimeIndex(boston_data['host_since']).year.astype(int) boston_data['host_since_month'] = pd.DatetimeIndex(boston_data['host_since']).month.astype(int) boston_data['host_since_year-month'] = pd.to_datetime(boston_data['host_since']).dt.to_period('M') ``` The zipcode column is not in the right format and dispose a small set of missing values. Moreover, the zipcoe is a pertinent information and cannot be simply imputed. ``` zip_percs = seatle_data["zipcode"].isnull().sum()/len(seatle_data) * 100 zip_percb = boston_data["zipcode"].isnull().sum()/len(boston_data) * 100 print("Seatle missing zipcode percentage: {:0.2f} %".format(zip_perc)) print("Boston missing zipcode percentage: {:0.2f} %".format(zip_percb)) # Convert zip code to numeric seatle_data['zipcode'] = pd.to_numeric(seatle_data['zipcode'], errors='coerce') boston_data['zipcode'] = pd.to_numeric(boston_data['zipcode'], errors='coerce') # remove rows with misisng zipcode seatle_data = seatle_data.dropna(subset=['zipcode'], how='any', axis =0) boston_data = boston_data.dropna(subset=['zipcode'], how='any', axis =0) # convert zip code to int seatle_data['zipcode']=seatle_data['zipcode'].astype(int) boston_data['zipcode']=boston_data['zipcode'].astype(int) ``` # Three insights In this notebook we will explore three insights in both Seatle and Boston datasets. We will address the two datasets with main three points: * Which city is most expensive? * Which are the property types the most hosted? * Which are the most expensive and cheapest neighbourhood in Seatle and Boston? As a bonus, we predict the Airbnb price using LightGBM algorithm. ## Price comparison First of all we plot the price histogram of both datasets to inspect the distribution. Because we have outliers in price, the plot is cliped on 500 dollars as maximum price for better visualization. ``` def plot_multiple_hist(df1,df2, col, thresh = None, bins = 20): """Plot multiple histogram in one gfigure Arguments: - df1: first dataframe - df2: second fdataframe - col: the variable name (column) - thresh: threshold used for shifted data, if given threshold values < thresh are plotted - bins: used for histogram plot Outputs: - The two histograms of col in df1 and df2 """ f = plt.figure(figsize=(10,6)) if thresh: data1 = df1[col][df1[col]< thresh] data2 = df2[col][df2[col]< thresh] else: data1 = df1[col] data2 = df2[col] data1.hist(bins = bins, alpha = 0.5, label='Seatle') data2.hist(bins = bins, alpha = 0.5, label='Boston') plt.legend(fontsize=20) plt.xlabel(col, fontsize=20) plt.ylabel("Counts", fontsize=20) if thresh : plt.title("{} histogram (< {} )".format(col, thresh), fontsize=20) else: plt.title(col+ " histogram") plt.savefig("figures/price_histogram.png", dpi = 600, bbox_inches='tight') plot_multiple_hist(seatle_data,boston_data, "price", thresh=500) ``` It is clear that Boston prices are little bit higher and regrouped between 70 and 300, while most of Seatle prices are between 10 and 200. In the following chart, the mean, the median, and the 3rd quartile are dropped for both datasets. ``` # get mean, median and 3rd quartile of the price. se = seatle_data["price"].describe().drop(["count", "min", "max","std","25%"]) bo = boston_data["price"].describe().drop(["count", "min", "max","std","25%"]) # plot mean, median, 3rd Q fig = plt.figure(figsize=(5,4)) ax = fig.add_subplot(111) ind = np.array([1, 2, 3]) rects1 = ax.bar(ind, bo, 0.35, color='royalblue', label = 'Boston') rects2 = ax.bar(ind+0.35, se, 0.35, color='seagreen', label = 'Seatle') plt.xticks(ind+0.35/2 , ('mean', '50% (median)', '75% (3rd Q)'), fontsize=15) plt.ylabel("Price", fontsize=20) plt.xlabel("",fontsize=20) # Finding the best position for legends and putting it plt.legend(loc='best') plt.savefig("figures/price_metrics.png", dpi = 600, bbox_inches='tight') ``` **Based on mean, median and the thrd quartile it is clear that Boston city is expensive than Seatle.** ## What type of property is most hosted ``` prop_seatle = seatle_data.groupby("property_type")["id"].count() prop_boston = boston_data.groupby("property_type")["id"].count() print("Seattle has {} properties ".format(len(prop_seatle))) print("Boston has {} properties ".format(len(prop_boston))) # properties only in Seattle prop_not_in_boston = [x for x in prop_seatle.index.to_list() if x not in prop_boston.index.to_list()] prop_not_in_boston # Properties only in Boston prop_not_in_seatle = [x for x in prop_boston.index.to_list() if x not in prop_seatle.index.to_list()] prop_not_in_seatle def plot_prop_byhosts(df, name="Seattle", color = "royalblue"): """Plot the numbers of hosting for each type of property""" perc_seatle = df.groupby("property_type")["id"].count().sort_values(ascending = False) perc_seatle.plot(kind = 'bar', width= 0.9, color=color, label = 'Seatle', fontsize=13) plt.ylabel("Hosts", fontsize=20) plt.xlabel("Property type", fontsize=20) # Finding the best position for legends and putting it plt.legend(loc='best', fontsize=15) plt.savefig("figures/{}_propType.png".format(name), dpi = 600, bbox_inches='tight') plt.show() plot_prop_byhosts(seatle_data, name="Seattle") plot_prop_byhosts(boston_data, name="Boston", color = "violet") boston_data.groupby("property_type")["id"].count().sort_values(ascending = False)[:6].index.to_list() ``` We can notice that Apartement, House, Condominium, and Townhouse are the most hosted properties. Lets see their percentage to the overall all hosts! ``` perc_seatle = (seatle_data.groupby("property_type")["id"].count().sort_values(ascending = False)/len(seatle_data)*100)[:6].sum() perc_boston = (boston_data.groupby("property_type")["id"].count().sort_values(ascending = False)/len(boston_data) * 100)[:6].sum() print("Six property types cover over {} % hosts for Seattle, and {} % hosts for Boston ".format(perc_seatle, perc_boston)) ``` ## Price by Neighbourhood We create a neighbourhoods_impact that plots and compares neighbourhoods based on price ``` seatl_nei = seatle_data["neighbourhood"].nunique() print("there are {} neighbourhoods in Seatle city".format(seatl_nei)) boston_nei = boston_data["neighbourhood"].nunique() print("there are {} neighbourhoods in Boston city".format(boston_nei)) def neighbourhoods_impact(data, group_feat, sort_feat, cols_to_plot, labels, name): """plot features based on neighbourhood impact Arguments: - data: dataframe of data. - group_feat: feature used to goupeby. - sort_feat: feature used to sort the grouped values. - cols_to_plot: list of columns names to be plotted. - labels: list of labels to describe the plot (same size as cols_to_plot). - name: the name of the data used to save figure. Outputs: - Plot of two features based on grouped data Example: data = seattle_data group_feat = "neghbourhood" sort_feat = "count" labels = ["N° of hosts", "mean price"] name = "Seattle" neighbourhoods_impact(data, group_feat, sort_feat, cols_to_plot, labels, name) """ gr = data.groupby(group_feat)["price"].describe().sort_values(by = sort_feat , ascending = False)[cols_to_plot][:10] gr[group_feat] = gr.index # plot top 10 gr.plot(x=group_feat , y=cols_to_plot,kind = "bar", figsize=(7,5), grid=True, label = labels, fontsize=13) plt.ylabel("Counts/Price", fontsize=20) plt.xlabel("{} Neighbourhood".format(name), fontsize=20) plt.savefig("figures/{}_neigh_counts_price.png".format(name), dpi = 600, bbox_inches='tight') group_feat = "neighbourhood" sort_feat = "count" cols_to_plot = ["count", "mean"] labels = ["N° of hosts", "mean price"] name = "Seattle" neighbourhoods_impact(seatle_data, group_feat, sort_feat, cols_to_plot, labels, name) group_feat = "neighbourhood" sort_feat = "count" cols_to_plot = ["count", "mean"] labels = ["N° of hosts", "mean price"] name = "Boston" neighbourhoods_impact(boston_data, group_feat, sort_feat, cols_to_plot, labels, name) group_feat = "neighbourhood" sort_feat = "mean" cols_to_plot = ["mean", "count"] labels = [ "mean price", "N° of hosts"] name = "Seattle expensive" neighbourhoods_impact(seatle_data, group_feat, sort_feat, cols_to_plot, labels, name) group_feat = "neighbourhood" sort_feat = "mean" cols_to_plot = ["mean", "count"] labels = [ "mean price", "N° of hosts"] name = "Boston expensive" neighbourhoods_impact(boston_data, group_feat, sort_feat, cols_to_plot, labels, name) ``` If you look at the cheapest neighbourhoods you can check ``` cheap_nei_se = seatle_data.groupby("neighbourhood")["price"].describe()["mean"].sort_values(ascending = False).index[-5:] print("cheapest neighbourhoods in Seatle city are {} ".format(list(cheap_nei_se))) cheap_nei_bo = boston_data.groupby("neighbourhood")["price"].describe()["mean"].sort_values(ascending = False).index[-5:] print("cheapest neighbourhoods in Boston city are {} ".format(list(cheap_nei_bo))) ``` # Conclusion In this article, we explored Airbnb data from Seattle and Boston to understand three areas of interest: pricing, property type, and neighborhood impact. While we found useful information at each level, many questions remain, like which characteristics and their associated impact make each neighborhood different from the others. In addition, further inspection of the listings by seasonality could yield more information to accurately select the best features for the price prediction task.
github_jupyter
The purpose of this code is to compute the Absolute Magnitude of the candidates (Both KDE and RF) and plot them as a function of redshift. The conversion is as follows: $M = m - 5log_{10}(\frac{d}{10\mathrm{pc}})$ or, in Mpc $M = m - (5log_{10}(\frac{d}{1\mathrm{Mpc}})-5log_{10}(10^{5})) == m - 5log_{10}(\frac{d}{1\mathrm{Mpc}})-25$ where d is the Luminosity distance in parsecs. The distance is estimated using the photoz's and a $\Lambda$CDM Cosmology with parameters: $H_0 = 70 Mpc^{-1}, \Omega_{\Lambda} = 0.725, \Omega_{M} = 0.275$ Using the Friedmann Equation: $ $ We can compute distance and, using the i_mag I can determine the absolute magnitude at z=0. I Finally need to convert to $M_i[z=2]$ by using the $\alpha_\nu$ values from Richards 2006/Ross2013 ``` %matplotlib inline import os import sys sys.path.insert(0, '/home/john/densityplot/densityplot') from densityplot.hex_scatter import hex_contour as hex_contour import numpy as np from astropy.io import fits as pf import camb from camb import model import matplotlib.pyplot as plt from matplotlib import gridspec #open the candidate data #path = '/Users/johntimlin/Clustering/Combine_SpIES_Shela/Data_sets/Match_SpSh_Cand_wzcorrected_nooutlier_allinfo.fits' #path = '/Users/johntimlin/Catalogs/QSO_candidates/201606/All_hzcandidate_correctphotoz_fromgaussian_allinfo.fits' #path = '../Data_Sets/QSO_Candidates_allcuts_with_errors_visualinsp.fits' path = '../Data_Sets/Only_point_sources.fits' data = pf.open(path)[1].data print data['imag'] print data.zphotNW rz = (data.zphotNW>=2.9) & (data.zphotNW<=5.4) & (data.Good_obj == 0) & (data.dec>=-1.2) & (data.dec<=1.2)& (data['imag']>=20.2) rshift = data.zphotNW[rz] print rshift.dtype r = rshift.astype('float64') #camb's luminosity distance calculator only accepts float 64 data types print r.dtype print len(r) #mag_list.append(-1.0*pogson*(math.asinh(5.0*fluxs[flux_name][i]/bsoft[flux_name]) + ln10_min10 + math.log(bsoft[flux_name])) - extinctions[flux_name][i] ) pog_m = 22.5-2.5*np.log10(data.iflux[rz]) # b=1.8 × 10-10 for i-band ash_m = -2.5/np.log(10) * (np.arcsinh((data.iflux[rz]/1e9)/(2*1.8e-10))+np.log(1.8e-10)) - 1.698/5.155 * data.extinctu[rz] print pog_m print ash_m print 1.698/4.239 * data.extinctu[rz] print -2.5*np.log10(1/3631.0e5) #Open the Shen2007 data shendat = '/Users/johntimlin/Clustering/Shen_test/Data/Shen2007_Clustering_sample.fits' sdat = pf.open(shendat)[1].data #Cut to their objects and get array of redshifts sdx = (sdat.Sfl == 1) #& (sdat.z>=3.5) & (sdat.z<=5.4) srz = sdat.z[sdx] sr = srz.astype('float64') #print simag #First define Planck 2015 cosmological parameters H = 70 #H0. oc = 0.229 #physical density of CDM ob = 0.046 #physical density of baryons #Set up parameters in CAMB pars = camb.CAMBparams() #Conversion to density param: Omega_Matter = (oc+ob)/(H0/100.)**2 #Hard code the cosmolgy params pars.H0=H #hubble param (No h!!) pars.omegab=ob #Baryon density parameter pars.omegac=oc #CDM density parameter pars.omegav=0.725 #Vacuum density parameter pars.set_dark_energy() #Set up parameters in CAMB pars = camb.CAMBparams() #H0 is hubble parameter at z=0, ombh2 is the baryon density (physical), omch2 is the matter density (physical) #mnu is sum of neutrino masses, omk is curvature parameter (set to 0 for flat), meffsterile is effective mass of sterile neutrinos pars.set_cosmology(H0=H,ombh2=ob, omch2=oc,omk=0)#,mnu=0,meffsterile=0) pars.set_dark_energy() bkg = camb.get_background(pars) #Background parameters Ldist = bkg.luminosity_distance(r) #Luminosity distance for SpIES cand ShLdist = bkg.luminosity_distance(sr) #Luminosity distance for Shen qso #Make the i_mag line targeted for shen 2007 sampz = np.linspace(0.5,5.4,10000) line = bkg.luminosity_distance(sampz) const_mag = np.ones(len(line))*20.2 const_magsp = np.ones(len(line))*22.5 #Compute the absolute magnitude at z=0 #M = (22.5-2.5*np.log10(data.iflux[rz])) - 5.0*np.log10(Ldist) - 25.0 M = ash_m - 5.0*np.log10(Ldist) - 25.0 M202 = const_mag - 5.0*np.log10(line) - 25.0 M23 = const_magsp - 5.0*np.log10(line) - 25.0 shenM = sdat['imag'][sdx] - 5.0*np.log10(ShLdist) - 25.0 #Compute the corrections to apply to M[z=0] to get M[z=2] def Kcorr(z,alpha = -0.5): #Ross13 K13 = -2.5*np.log10(1+z) - 2.5*alpha*np.log10(1+z)+2.5*alpha*np.log10(1.0+2.0) return K13 #import the K-corrections from Richards 2006 K06 = pf.open('./K_correct_Richards06.fits')[1].data K13 = pf.open('./K_correct_Ross13.fits')[1].data #Pull out the redshift information from the data for SpIES and Shen rshifts = data.zphotNW[rz] srshift = sdat.z[sdx] #Round the redshifts to 2 decimal places so that I can match to the correction values in Richards 2006 roundz = np.round(rshifts,decimals = 2) roundt = np.round(sampz,decimals = 2) roundsz = np.round(srshift,decimals = 2) #Find the correction value that corresponds to the redshift in the file Kcor=[] Ktest = [] Ktestsp = [] Kshen = [] for i in roundz: kc = K06.KCorr[np.where(K06.z == i)] Kcor.append(kc[0]) for j in roundt: kt = K06.KCorr[np.where(K06.z == j)] Ktest.append(kt[0]) Ktestsp.append(kt[0]) for m in roundsz: kt = K06.KCorr[np.where(K06.z == j)] Kshen.append(kt[0]) KC = np.asarray(Kcor) KT = np.asarray(Ktest) KS = np.asarray(Kshen) #Correct the Absolute values using the K-corrections found above dcorrect = M-KC lcorrect = M202-Ktest spcorrect= M23 - Ktestsp scorrect = shenM - Kshen #Plotting Parameters (Replace with Group code call!) params = {'legend.fontsize': 16, 'xtick.labelsize': 20, 'ytick.labelsize': 20, 'xtick.major.width':2, 'xtick.minor.width':2, 'ytick.major.width':2, 'ytick.minor.width':2, 'xtick.major.size':8, 'xtick.minor.size':6, 'ytick.major.size':8, 'ytick.minor.size':6} plt.rcParams.update(params) plt.rc("axes", linewidth=3.0) plt.figure(1,figsize = (8,8)) plt.scatter(rshift,dcorrect,color = '#fd8d3c',edgecolor = None,s=1,alpha = 0.9)#,label = 'Timlin 2016 QSO sample' ) plt.scatter(1,1,s=80,color = '#fd8d3c',label = 'This study') #plt.scatter(srz,scorrect,color='#e31a1c',edgecolor = None,s=1,alpha = 0.9)#,label = 'Shen 2007 QSO sample') plt.scatter(1,1,s=80,color = '#e31a1c',label = 'Shen 2007') plt.plot(sampz,lcorrect,color = 'k',linewidth = 2,label = r'$i$=20.2') #plt.plot(sampz,spcorrect,color = 'g',linewidth = 2,label = r'$i$=22.5') #plt.plot(sampz,spcorrect,color = 'k',linestyle = '--', dashes=(10,5,10,5),linewidth = 2,label = r'$i$=23.3') plt.xlim(2.8,5.3) plt.ylim(-30.5,-22.5) plt.xlabel('Redshift',fontsize = 18) plt.ylabel(r'$M_i$[z=2]',fontsize = 18) plt.gca().invert_yaxis() plt.minorticks_on() plt.legend(loc=4,scatterpoints = 1) #plt.savefig('Absolute_Mag_SpIES_Shen.pdf') imag = -2.5/np.log(10) * (np.arcsinh((data.iflux[rz]/1e9)/(2*1.8e-10))+np.log(1.8e-10)) - 1.698/4.239 * data.extinctu[rz] num,bins = np.histogram(imag,bins='fd') print bins fig = plt.figure(5,figsize = (8,4)) plt.hist(imag,bins, histtype = 'step',normed = False,color = '#FFA500',linewidth = 2) plt.hist(sdat['imag'][sdx],bins='fd', histtype = 'step',normed = False,color = 'r',linewidth = 2) plt.xlabel(r'$i$ Magnitude',fontsize = 14) plt.ylabel('Number',fontsize = 14) #plt.savefig('imag_hist.pdf',bbox_inches='tight') plt.show() ``` # Plot for the paper ``` imag = 22.5-2.5*np.log10(data.iflux[rz]) num,bins = np.histogram(imag,bins='fd') fig = plt.figure(5,figsize = (6,12)) gs = gridspec.GridSpec(2, 1, height_ratios=[0.6,0.4]) ax0 = plt.subplot(gs[0]) ax1 = plt.subplot(gs[1],) plt.axes(ax0) plt.scatter(rshift,dcorrect,color = '#fd8d3c',edgecolor = None,s=1,alpha = 0.9)#,label = 'Timlin 2016 QSO sample' ) plt.scatter(1,1,s=80,color = '#fd8d3c',label = 'This study') plt.scatter(srz,scorrect,color='#e31a1c',edgecolor = None,s=1,alpha = 0.9)#,label = 'Shen 2007 QSO sample') plt.scatter(1,1,s=80,color = '#e31a1c',label = 'Shen 2007') plt.plot(sampz,lcorrect,color = 'k',linewidth = 2,label = r'$i$=20.2') #plt.plot(sampz,spcorrect,color = 'k',linestyle = '--', dashes=(10,5,10,5),linewidth = 2,label = r'$i$=23.3') plt.xlim(2.8,5.3) plt.ylim(-30.5,-22.5) plt.xlabel('Redshift',fontsize = 16) plt.ylabel(r'$M_i$[$z$=2] (AB mag)',fontsize = 16) plt.gca().invert_yaxis() plt.minorticks_on() leg =plt.legend(loc=4,scatterpoints = 1) leg.get_frame().set_alpha(0.35) plt.axes(ax1) plt.hist(sdat['imag'][sdx],bins='fd', histtype = 'step',normed = False,color = 'r',linewidth = 2,label= 'Shen 2007') plt.hist(imag,bins, histtype = 'step',normed = False,color = '#FFA500',linewidth = 2,label = 'This study') plt.xlabel(r'$i$-Magnitude (AB mag)',fontsize = 16) plt.ylabel('Number of quasars',fontsize = 16) plt.minorticks_on() leg =plt.legend(loc=2) leg.get_frame().set_alpha(0.35) #plt.savefig('Absolute_Mag_SpIES_Shen.pdf',bbox_inches='tight',pad_inches=0.5) ``` # Find and save the brightest candidates ``` good = dcorrect[dcorrect <=-25.0] print len(good) plt.scatter(rshift[dcorrect<=-25],good,color = '#fd8d3c',edgecolor = None,s=1,alpha = 0.9)#,label = 'Timlin 2016 QSO sample' ) plt.scatter(1,1,s=80,color = '#fd8d3c',label = 'This study') plt.xlim(2.8,5.3) plt.ylim(-30.5,-22.5) plt.show() print len(data.ra[rz]), len(dcorrect) print len(data.ra[rz][dcorrect<=-25.0]) tbhdu=pf.BinTableHDU.from_columns([pf.Column(name='RA',format='D',array=data.ra[rz][dcorrect<=-25.0]), pf.Column(name='DEC',format='D',array=data.dec[rz][dcorrect<=-25.0])]) prihdr=pf.Header() prihdr['COMMENT']="Brightest SpIES quasars" prihdu=pf.PrimaryHDU(header=prihdr) hdulist = pf.HDUList([prihdu,tbhdu]) #hdulist=pf.HDUList(data[dx]) hdulist.writeto('../Data_Sets/Brightest_candidates.fits') ```
github_jupyter
``` #@title Install PyDDM and download the script containing the models !pip -q install git+https://github.com/mwshinn/PyDDM import hashlib import requests import os fname = "shinn2021.py" url = "https://raw.githubusercontent.com/mwshinn/PyDDM/master/doc/downloads/shinn2021.py" if not os.path.isfile(fname): r = requests.get(url) if r.status_code != requests.codes.ok: print("!!! Failed to download data !!!") else: with open(fname, "wb") as fid: fid.write(r.content) DIPTYPE = 1 # Set to 1, 2, or 3 depending on which model you would like to visualize #@title Visualize the models from Shinn et al (2021) - Transient neuronal suppression for exploitation of new sensory evidence import ddm import ddm.plot from shinn2021 import DriftDip, NoiseDip, ICPoint, BoundDip, OverlayDipRatio DIPTYPE = 1 # Change to 1, 2, or 3 depending on which model you want snr = ddm.Fittable(minval=0.5, maxval=20, default=9.243318909157688) leak = ddm.Fittable(minval=-10, maxval=30, default=9.46411355874963) x0 = ddm.Fittable(minval=-.5, maxval=.5, default=0.1294632585920082) leaktargramp = ddm.Fittable(minval=0, maxval=3, default=0) noise = ddm.Fittable(minval=.2, maxval=2, default=1.1520906498077081) t1 = ddm.Fittable(minval=0, maxval=1, default=0.34905555600815663) t1slope = ddm.Fittable(minval=0, maxval=3, default=1.9643425020687162) dipstart = ddm.Fittable(minval=-.4, maxval=0, default=-.2) dipstop = ddm.Fittable(minval=0, maxval=.5, default=.05) nondectime = ddm.Fittable(minval=0, maxval=.3, default=.1) detect = ddm.Fittable(minval=2, maxval=50, default=10) diptype = DIPTYPE dipparam = ddm.Fittable(minval=0, maxval=50) if diptype == 2 else 0 pmixturecoef = ddm.Fittable(minval=0, maxval=.2, default=.03) rate = ddm.Fittable(minval=.1, maxval=10, default=1) m = ddm.Model(drift= DriftDip(snr=snr, noise=noise, t1=t1, t1slope=t1slope, leak=leak, maxcoh=70, leaktarget=x0, leaktargramp=leaktargramp, dipstart=dipstart, dipstop=dipstop, diptype=diptype, dipparam=dipparam, ), noise= NoiseDip(noise=noise, t1=t1, t1slope=t1slope, dipstart=dipstart, dipstop=dipstop, diptype=diptype, ), IC= ICPoint(x0=x0), bound= BoundDip(B=1, dipstart=dipstart, dipstop=dipstop, diptype=diptype ), overlay=ddm.OverlayChain(overlays=[ ddm.OverlayNonDecision(nondectime=nondectime), OverlayDipRatio(detect=detect, diptype=diptype), ddm.OverlayPoissonMixture(pmixturecoef=pmixturecoef, rate=rate) ]), dx=0.002, dt=0.002, T_dur=3.0) # END demo ddm.plot.model_gui_jupyter(model=m, conditions={"coherence": [50, 53, 60, 70], "presample": [0, 400, 800], "highreward": [0, 1]}) ```
github_jupyter
# Export for Dashboard ``` # For multiple output per cell from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" #DATASET_FOLDER = '/media/data-nvme/dev/datasets/WorldBank/' DATASET_FOLDER = '../../datasets/precipitation/' SPARK_MASTER = 'spark://192.168.0.9:7077' APP_NAME = 'Merge PRCP GKP' input_folder = DATASET_FOLDER output = DATASET_FOLDER + '../wb_gkp_precipitation' import os import pandas as pd import pandas as pd from pyspark import SparkContext #from pyspark import SparkConf from pyspark.sql import SparkSession #from pyspark.sql.window import Window from pyspark.sql.types import FloatType import pyspark.sql.functions as F import shutil ### Connect to Spark print('Create Spark session') spark = SparkSession.builder.master(SPARK_MASTER).appName(APP_NAME).getOrCreate() sc = spark.sparkContext ``` # History ### Load EMDAT ``` #!ls /media/data-nvme/dev/datasets/WorldBank/ # Load EMDAT emdat = spark.read.format('csv').option('header',True).option('multiLine', True) \ .load('/media/data-nvme/dev/datasets/WorldBank/' + 'emdat_public_2020_09_12_query_uid-tAnKEX-floods_only.csv') print(emdat.columns) #emdat = emdat.withColumn('decade', F.concat(F.col('Year').substr(0, 3) , F.lit('0-') , F.col('Year').substr(0, 3), F.lit('9'))) emdat = emdat.withColumn('decade', F.concat(F.col('Year').substr(0, 3) , F.lit('0'))) #emdat.take(3) ###### Cast Type print('Cast string to float') emdat = emdat.withColumn("Total Deaths", emdat["Total Deaths"].cast(FloatType()))\ .withColumn("Total Damages ('000 US$)", emdat["Total Damages ('000 US$)"].cast(FloatType())) emdat.createOrReplaceTempView("emdat") emdat.count() # Agregate by decade and country emdat_agregate = spark.sql(""" SELECT decade as Decade, ISO, region as UN_Geosheme_Subregion, 'Flood' as Disaster_Type, 'past' as RCP, sum(`Total Damages ('000 US$)`) as Financial_Impact, sum(`Total Deaths`) as Human_Impact, count(`Dis No`) as DO FROM emdat GROUP BY decade, region, ISO ORDER BY decade, region, ISO """) dfp = emdat_agregate.toPandas() dfp.dropna().head(3) ``` ### Load Rainfall ``` # Load Rainfall DATASET_FOLDER = '../../datasets/WorldBank' rain = spark.read.format('csv').option('header',True).option('multiLine', True) \ .load(f'{DATASET_FOLDER}/daily_rain_by_country_feature.csv.gz') # Create an agregate of rain by decade and country rain.createOrReplaceTempView("noaa") noaa = spark.sql(""" SELECT decade, country_ISO3, count(avg_rain) as `nb_days_with_rain_>_50mm` FROM noaa WHERE avg_rain > 50 GROUP BY decade, country_ISO3 ORDER BY decade, country_ISO3 """) noaa.createOrReplaceTempView("noaa_agregate") ``` ## Join EMDAT and Rainfall ``` # Join EMDAT agregate and rain agregate emdat_agregate.createOrReplaceTempView("emdat_agregate") emdat_rain_agregate = spark.sql(""" SELECT emdat_agregate.*, noaa_agregate.`nb_days_with_rain_>_50mm` FROM emdat_agregate LEFT JOIN noaa_agregate ON emdat_agregate.decade = noaa_agregate.decade AND emdat_agregate.ISO = noaa_agregate.country_ISO3 """) emdat_rain_agregate.show(3) # Agregate by region emdat_rain_agregate.createOrReplaceTempView("emdat_rain_gregate") emdat_rain_agregate_by_country = spark.sql(""" SELECT Decade, UN_Geosheme_Subregion, Disaster_Type, RCP, sum(Financial_Impact) as Financial_Impact, sum(Human_Impact) as Human_Impact, sum(DO) as DO, sum(`nb_days_with_rain_>_50mm`) as `nb_days_with_rain_>_50mm` FROM emdat_rain_gregate GROUP BY Decade, UN_Geosheme_Subregion, Disaster_Type, RCP ORDER BY Decade, UN_Geosheme_Subregion """) # Filling NA/null with 0 emdat_rain_agregate_by_country = emdat_rain_agregate_by_country.fillna({'Financial_Impact' : 0, 'Human_Impact' : 0, 'nb_days_with_rain_>_50mm': 0}) emdat_rain_agregate_by_country.show(3) #dfp = emdat.toPandas() #dfp[['Dis No', "Total Deaths"]] #dfp[dfp['Dis No'] == '1906-0023-BEL'] #") #1906-0023-BEL 1950-0007-CHN # Check that wr have good data emdat_rain_agregate_by_country.createOrReplaceTempView("emdat_rain_agregate_by_country") spark.sql(""" SELECT * FROM emdat_rain_agregate_by_country WHERE Financial_Impact > 0 ORDER BY Financial_Impact """).show(3) # Saving in one file with Pandas dfp = emdat_rain_agregate_by_country.toPandas() dfp dfp.to_csv(f'{DATASET_FOLDER}../flood_history_agregates.csv.gz', index=False ,compression='gzip') ``` # Projection ``` # rain = spark.read.format('csv').option('header',True).option('multiLine', True) \ # .load(f'{DATASET_FOLDER}../projection_preciptation_monthly_merged-2020-12-02') sc.stop() ```
github_jupyter
# Assignment 2 Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize yourself with the criteria before beginning the assignment. An NOAA dataset has been stored in the file `data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv`. The data for this assignment comes from a subset of The National Centers for Environmental Information (NCEI) [Daily Global Historical Climatology Network](https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt) (GHCN-Daily). The GHCN-Daily is comprised of daily climate records from thousands of land surface stations across the globe. Each row in the assignment datafile corresponds to a single observation. The following variables are provided to you: * **id** : station identification code * **date** : date in YYYY-MM-DD format (e.g. 2012-01-24 = January 24, 2012) * **element** : indicator of element type * TMAX : Maximum temperature (tenths of degrees C) * TMIN : Minimum temperature (tenths of degrees C) * **value** : data value for element (tenths of degrees C) For this assignment, you must: 1. Read the documentation and familiarize yourself with the dataset, then write some python code which returns a line graph of the record high and record low temperatures by day of the year over the period 2005-2014. The area between the record high and record low temperatures for each day should be shaded. 2. Overlay a scatter of the 2015 data for any points (highs and lows) for which the ten year record (2005-2014) record high or record low was broken in 2015. 3. Watch out for leap days (i.e. February 29th), it is reasonable to remove these points from the dataset for the purpose of this visualization. 4. Make the visual nice! Leverage principles from the first module in this course when developing your solution. Consider issues such as legends, labels, and chart junk. The data you have been given is near **Ann Arbor, Michigan, United States**, and the stations the data comes from are shown on the map below. ``` import matplotlib.pyplot as plt import mplleaflet import pandas as pd def leaflet_plot_stations(binsize, hashid): df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize)) station_locations_by_hash = df[df['hash'] == hashid] lons = station_locations_by_hash['LONGITUDE'].tolist() lats = station_locations_by_hash['LATITUDE'].tolist() plt.figure(figsize=(8,8)) plt.scatter(lons, lats, c='r', alpha=0.7, s=200) return mplleaflet.display() leaflet_plot_stations(400,'fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89') df = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv') df.head() df['Year'], df['Month-Date'] = zip(*df['Date'].apply(lambda x: (x[:4], x[5:]))) df = df[df['Month-Date'] != '02-29'] df.head() import numpy as np temp_max = df[(df['Element'] == 'TMAX') & (df['Year'] != '2015')].groupby('Month-Date').aggregate({'Data_Value':np.max}) temp_min = df[(df['Element'] == 'TMIN') & (df['Year'] != '2015')].groupby('Month-Date').aggregate({'Data_Value':np.min}) temp_max_15 = df[(df['Element'] == 'TMAX') & (df['Year'] == '2015')].groupby('Month-Date').aggregate({'Data_Value':np.max}) temp_min_15 = df[(df['Element'] == 'TMIN') & (df['Year'] == '2015')].groupby('Month-Date').aggregate({'Data_Value':np.min}) broken_max = np.where(temp_max_15['Data_Value'] > temp_max['Data_Value'])[0] broken_min = np.where(temp_min_15['Data_Value'] < temp_min['Data_Value'])[0] print(broken_max) print(broken_min) plt.figure() plt.plot(temp_max.values, label='Maximum Temp (2005-2014)') plt.plot(temp_min.values, label='Minimum Temp (2005-2014)') plt.gca().fill_between(range(len(temp_min)), temp_min['Data_Value'],temp_max['Data_Value'], facecolor='blue', alpha=0.25) plt.xticks(range(0, len(temp_min), 20), temp_min.index[range(0, len(temp_min), 20)], rotation = '45') plt.scatter(broken_max, temp_min_15.iloc[broken_max], s=10, color='red', label='High temp record broken (2015)') plt.scatter(broken_min, temp_min_15.iloc[broken_min], s=10, color='green', label='Low temp record broken (2015)') plt.legend(frameon = False) plt.xlabel('Day of the Year') plt.ylabel('Temperature (tenths of $^\circ$C)') plt.title('Temperature Plot: Ann Arbor, Michigan, United States') plt.gca().spines['top'].set_visible(False) plt.gca().spines['right'].set_visible(False) plt.show() ```
github_jupyter
# Figure 5 ``` %load_ext watermark %watermark -a "Etienne Ackermann," -n -t -v -p nelpy,numpy,scipy,pandas,matplotlib import copy import numpy as np import matplotlib.pyplot as plt import os import warnings import tabulate import scipy.stats as stats from IPython.display import HTML, display, clear_output from mpl_toolkits.axes_grid1 import make_axes_locatable import nelpy as nel import nelpy.plotting as npl # Set default figure aesthetics npl.setup(font_scale=1.0) %matplotlib inline warnings.filterwarnings("ignore") datadirs = ['data/'] fileroot = next( (dir for dir in datadirs if os.path.isdir(dir)), None) if fileroot is None: raise FileNotFoundError('datadir not found') load_from_nel = True if load_from_nel: jar = nel.load_pkl(fileroot + 'fig1.nel') exp_data = jar.exp_data aux_data = jar.aux_data del jar jar = nel.load_pkl(fileroot + 'sessions_segments.nel') sessions = jar.sessions segments = jar.segments jar = nel.load_pkl(fileroot + 'score_results.nel') score_results = jar.score_results session = '16-40-19'; segment = 'short' # 'long' or 'short' def plot_all_PBEs(bst, spiketrainarray, tuningcurve, tc_placecells, idx=None, title_str=None): if idx is not None: bst = bst[idx] st = spiketrainarray tc = tuningcurve tc_placecells = tc_placecells no = tc_placecells.get_peak_firing_order_ids() st.reorder_units_by_ids(no, inplace=True) st_cut = st[bst.support] st_cut._support = bst.support # hacky fix so that we can plot events out of order st_cut = nel.utils.collapse_time(st_cut) # decode neural activity posterior, bdries, mode_pth, mean_pth = nel.decoding.decode1D(bst=bst, ratemap=tc, xmax=310) with npl.FigureManager(show=True, figsize=(0.08*bst.n_bins,2)) as (fig, ax): npl.utils.skip_if_no_output(fig) pixel_width = 0.5 npl.imagesc(x=np.arange(bst.n_bins), y=np.arange(311), data=posterior, cmap=plt.cm.Spectral_r, ax=ax) # npl.utils.yticks_interval(310) npl.utils.no_yticks(ax) # plt.imshow(posterior, cmap=plt.cm.Spectral_r, interpolation='none', aspect='auto') ax.vlines(np.arange(bst.lengths.sum())-pixel_width, *ax.get_ylim(), lw=1, linestyle=':', color='0.8') ax.vlines(np.cumsum(bst.lengths)-pixel_width, *ax.get_ylim(), lw=1) ax.set_xlim(-pixel_width, bst.lengths.sum()-pixel_width) event_centers = np.insert(np.cumsum(bst.lengths),0,0) event_centers = event_centers[:-1] + bst.lengths/2 - 0.5 ax.set_xticks(event_centers); if idx is not None: ax.set_xticklabels(idx); else: ax.set_xticklabels(np.arange(bst.n_epochs)); npl.utils.no_xticks(ax) ax.set_ylim(0,250) divider = make_axes_locatable(ax) axRaster = divider.append_axes("top", size=0.6, pad=0) npl.rasterplot(st_cut, vertstack=True, ax=axRaster, lh=1.25) axRaster.set_xlim(st_cut.support.time.squeeze()) bin_edges = np.linspace(st_cut.support.time[0,0],st_cut.support.time[0,1], bst.n_bins+1) # axRaster.vlines(bin_edges, *ax.get_ylim(), lw=1, linestyle=':', color='0.2') axRaster.vlines(bin_edges[np.cumsum(bst.lengths)], *ax.get_ylim(), lw=1, color='0.2') npl.utils.no_xticks(axRaster) npl.utils.no_xticklabels(axRaster) npl.utils.no_yticklabels(axRaster) npl.utils.no_yticks(axRaster) ax.set_ylabel('position [cm]') ax.set_xlabel('time bins (20 ms)') if title_str: fig.suptitle(title_str) npl.utils.clear_left_right(axRaster) npl.utils.clear_top_bottom(axRaster) # nn = 126 # bst = aux_data[session][segment]['PBEs'][nn] # scores, shuffled_scores, percentiles = nel.analysis.replay.score_Davidson_final_bst_fast(bst=bst, # tuningcurve=tc, # w=w, # n_shuffles=n_shuffles, # n_samples=n_samples) # print(scores) # print(percentiles) pooled_percentiles_hmm = [] pooled_percentiles_bayes = [] for session, segment in zip(sessions, segments): pooled_percentiles_hmm.extend(score_results[session][segment]['scores_hmm_percentile'].tolist()) pooled_percentiles_bayes.extend(score_results[session][segment]['scores_bayes_percentile'].tolist()) pooled_percentiles_hmm = np.array(sorted(pooled_percentiles_hmm)) pooled_percentiles_bayes = np.array(sorted(pooled_percentiles_bayes)) # obtain thresholds from pooled data threshold_bayes = 99 n_scores = len(pooled_percentiles_hmm) x = 100 - np.linspace(0,100, n_scores) cum_perc_sig = bx = 100 - [next(ii for (ii, item) in enumerate((pooled_percentiles_bayes<threshold_bayes).tolist()) if item is False)][0]/n_scores*100 threshold_hmm = float(pooled_percentiles_hmm[np.argwhere(x < cum_perc_sig)[0]]) n_events = 0 n_HS_BS = 0 n_HS_BNS = 0 n_HNS_BS = 0 n_HNS_BNS = 0 for session, segment in zip(sessions, segments): n_events += len(score_results[session][segment]['scores_hmm_percentile']) idx_all = set(range(n_events)) BS = set(np.where(score_results[session][segment]['scores_bayes_percentile']>=threshold_bayes)[0]) BNS = set(np.where(score_results[session][segment]['scores_bayes_percentile']<threshold_bayes)[0]) HS = set(np.where(score_results[session][segment]['scores_hmm_percentile']>=threshold_hmm)[0]) HNS = set(np.where(score_results[session][segment]['scores_hmm_percentile']<threshold_hmm)[0]) BS_HS = np.array(list(BS.intersection(HS))).astype(int) BS_HNS = np.array(list(BS.intersection(HNS))).astype(int) BNS_HS = np.array(list(BNS.intersection(HS))).astype(int) BNS_HNS = np.array(list(BNS.intersection(HNS))).astype(int) n_HS_BS += len(BS_HS) n_HS_BNS += len(BNS_HS) n_HNS_BS += len(BS_HNS) n_HNS_BNS += len(BNS_HNS) conf_mat = np.array([[n_HS_BNS, n_HS_BS],[n_HNS_BNS, n_HNS_BS]]) table = [["HMM +", n_HS_BS, n_HS_BNS, n_HS_BS+n_HS_BNS], ["HMM -", n_HNS_BS, n_HNS_BNS, n_HNS_BS + n_HNS_BNS], ["", n_HS_BS + n_HNS_BS, n_HS_BNS + n_HNS_BNS, ""]] display(HTML(tabulate.tabulate(table, headers=["N={}".format(n_events),"Bayes +", "Bayes -", ""], tablefmt='html'))) oddsratio, p_value = stats.fisher_exact(np.array([[n_HS_BNS, n_HS_BS],[n_HNS_BNS, n_HNS_BS]]), alternative='two-sided') print("Fisher's exact test, two-tailed p value:", p_value) print('{:1.1f}% event agreement'.format((n_HS_BS + n_HNS_BNS) / n_events*100)) ``` # Look at all classification types ``` session, segment = '16-40-19', 'short' bst = aux_data[session][segment]['PBEs_noIN'] st = aux_data[session][segment]['st_placecells_noIN'] tc = aux_data[session][segment]['tc_noIN'] tc_placecells = aux_data[session][segment]['tc_placecells_noIN'] bst.n_epochs n_events = len(score_results[session][segment]['scores_hmm_percentile']) idx_all = set(range(n_events)) BS = set(np.where(score_results[session][segment]['scores_bayes_percentile']>=threshold_bayes)[0]) BNS = set(np.where(score_results[session][segment]['scores_bayes_percentile']<threshold_bayes)[0]) HS = set(np.where(score_results[session][segment]['scores_hmm_percentile']>=threshold_hmm)[0]) HNS = set(np.where(score_results[session][segment]['scores_hmm_percentile']<threshold_hmm)[0]) BS_HS = np.array(list(BS.intersection(HS))).astype(int) BS_HNS = np.array(list(BS.intersection(HNS))).astype(int) BNS_HS = np.array(list(BNS.intersection(HS))).astype(int) BNS_HNS = np.array(list(BNS.intersection(HNS))).astype(int) n_HS_BS = len(BS_HS) n_HS_BNS = len(BNS_HS) n_HNS_BS = len(BS_HNS) n_HNS_BNS = len(BNS_HNS) conf_mat = np.array([[n_HS_BNS, n_HS_BS],[n_HNS_BNS, n_HNS_BS]]) table = [["HMM +", n_HS_BS, n_HS_BNS, n_HS_BS+n_HS_BNS], ["HMM -", n_HNS_BS, n_HNS_BNS, n_HNS_BS + n_HNS_BNS], ["", n_HS_BS + n_HNS_BS, n_HS_BNS + n_HNS_BNS, ""]] display(HTML(tabulate.tabulate(table, headers=["N={}".format(n_events),"Bayes +", "Bayes -", ""], tablefmt='html'))) oddsratio, p_value = stats.fisher_exact(np.array([[n_HS_BNS, n_HS_BS],[n_HNS_BNS, n_HNS_BS]]), alternative='two-sided') print("Fisher's exact test, two-tailed p value:", p_value) negative = np.argwhere(score_results[session][segment]['manual_scores'] == 1).squeeze() positive = np.argwhere(score_results[session][segment]['manual_scores'] == 5).squeeze() TPh = np.count_nonzero([h in positive for h in HS]) / len(positive) TNh = np.count_nonzero([h in negative for h in HNS]) / len(negative) FPh = np.count_nonzero([h in negative for h in HS]) / len(negative) FNh = np.count_nonzero([h in positive for h in HNS]) / len(positive) TPb = np.count_nonzero([h in positive for h in BS]) / len(positive) TNb = np.count_nonzero([h in negative for h in BNS]) / len(negative) FPb = np.count_nonzero([h in negative for h in BS]) / len(negative) FNb = np.count_nonzero([h in positive for h in BNS]) / len(positive) FNhidx = [h for h in HNS if h in positive] FNbidx = [b for b in BNS if b in positive] TNhidx = [h for h in HNS if h in negative] TNbidx = [b for b in BNS if b in negative] TPhidx = [h for h in HS if h in positive] TPbidx = [b for b in BS if b in positive] FPhidx = [h for h in HS if h in negative] FPbidx = [b for b in BS if b in negative] # Examples # # (TPh,TPb) (TPh,FNb) | (FPh,FPb) (FPh,TNb) # (TPh,TPb) (TPh,FNb) | (FPh,FPb) (FPh,TNb) # ------------------------------------------- # (FNh,TPb) (FNh,FNb) | (TNh,FPb) (TNh,TNb) # (FNh,TPb) (FNh,FNb) | (TNh,FPb) (TNh,TNb) # (1,1) (2,1) print('HMM true positive | Bayes true positive') TPhTPb = sorted(list(set(TPhidx).intersection(TPbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][TPhTPb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][TPhTPb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(TPhTPb)[new_order]).tolist()) # (1,2) (2,2) print('HMM true positive | Bayes false negative') TPhFNb = sorted(list(set(TPhidx).intersection(FNbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][TPhFNb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][TPhFNb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(TPhFNb)[new_order]).tolist()) # (3,1) (4,1) print('HMM false negative | Bayes true positive') FNhTPb = sorted(list(set(FNhidx).intersection(TPbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][FNhTPb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][FNhTPb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(FNhTPb)[new_order]).tolist()) # (3,2) (4,2) print('HMM false negative | Bayes false negative') FNhFNb = sorted(list(set(FNhidx).intersection(FNbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][FNhFNb]) h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][FNhFNb]) new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(FNhFNb)[new_order]).tolist()) # (1,3) (2,3) print('HMM false positive | Bayes false positive') FPhFPb = sorted(list(set(FPhidx).intersection(FPbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][FPhFPb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][FPhFPb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(FPhFPb)[new_order]).tolist()) # (1,4) (2,4) print('HMM false positive | Bayes true negative') FPhTNb = sorted(list(set(FPhidx).intersection(TNbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][FPhTNb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][FPhTNb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(FPhTNb)[new_order]).tolist()) # (3,3) (4,3) print('HMM true negative | Bayes false positive') TNhFPb = sorted(list(set(TNhidx).intersection(FPbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][TNhFPb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][TNhFPb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(TNhFPb)[new_order]).tolist()) # (3,4) (4,4) print('HMM true negative | Bayes true negative') TNhTNb = sorted(list(set(TNhidx).intersection(TNbidx))) b_order = np.argsort(score_results[session][segment]['scores_bayes_percentile'][TNhTNb])[::-1] h_order = np.argsort(score_results[session][segment]['scores_hmm_percentile'][TNhTNb])[::-1] new_order = h_order plot_all_PBEs(bst, st, tc, tc_placecells, idx=(np.array(TNhTNb)[new_order]).tolist()) ```
github_jupyter
# Readout Cavity Calibration *Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.* ## Outline This tutorial introduces the simulation of readout cavity calibration using the readout simulator. The outline of this tutorial is as follows: - Introduction - Preparation - Calibrating the Readout Cavity Transition Frequencies - Calibrating the Dispersive Shift and Coupling Strength - Measuring the decay rate - Summary ## Introduction In superconducting circuit, to acquire the state of a qubit, we can probe the readout cavity coupled with this qubit to achieve the qubit state indirectly. Concretely, we first apply readout pulse signal and then detect and analyze the reflected signal. Because the phase shift and amplitude change depend on the qubit state, we are able to know whether the outcome is "0" or "1" by this change. In the real experiment of calibration, the first step to is to find the parameters of readout cavity. This tutorial introduces how to use Quanlse to simulate the readout cavity calibration. A coupled cavity-qubit system can be described by the Jaynes-Cummings Hamiltonian in the dispersive regime \[1\]: $$ \hat{H}_{\rm JC} = \omega_r \hat{a}^\dagger \hat{a} + \frac{1}{2}\omega_q \hat{\sigma}_z + \chi \hat{a}^\dagger \hat{a} \hat{\sigma}_z, $$ where $\hat{a}$, $\hat{a}^\dagger$ are annihilation and creation operators and $\hat{\sigma}_z$ is the Pauli-Z operator. $\omega_r$ and $\omega_q$ denote the bare frequencies of the readout cavity and the qubit, $\chi$ is the dispersive shift and takes the form \[2\]: $$ \chi = \frac{g^2 \alpha}{\Delta_{qr}(\Delta_{qr} + \alpha)}. $$ where $\alpha$ is the qubit anharmonicity, $\Delta_{qr} = \omega_q - \omega_r$ is qubit-cavity detuning and $g$ is the qubit-cavity coupling strength. The interaction term $\chi \hat{a}^\dagger \hat{a} \hat{\sigma}_z$ in $\hat{H}_{\rm JC}$ gives rise to a shift of $2\chi$ in the transition frequency of the readout cavity when the qubit state is $|0\rangle$ and $|1\rangle$. Therefore in the experiment, by performing frequency sweep for the cavity with qubit state prepared in $|0\rangle$ or $|1\rangle$ respectively, we can obtain transition frequency $f_0$ and $f_1$ and therefore the frequency shift $2\chi$. Finally, the cavity-qubit couping strength is indirectly calculated using the expression above. In addition to the transition frequency and dispersive shift, the linewidth $\kappa$ can be measured to determine the photon decay rate of the readout cavity. To simulate the interaction between cavity-qubit system and the environment, the evolution of the system density matrix $\hat{\rho}(t)$ is given by Lindblad master equation \[3, 4\]: $$ \frac{d \hat{\rho}(t)}{dt} = -i[\hat{H}(t), \hat{\rho}(t)] + \frac{\kappa}{2}[2 \hat{a} \hat{\rho}(t) \hat{a}^\dagger - \hat{\rho}(t) \hat{a}^\dagger \hat{a} - \hat{a}^\dagger \hat{a} \hat{\rho}(t)]. $$ The decay rate is therefore acquired by fitting the spectrum and extract the linewidth in the Lorentzian function. The observable quantities we take are the two orthogonal quadratures $\hat{X} = \frac{1}{2}(\hat{a}^\dagger + \hat{a})$ and $\hat{Y} = \frac{i}{2}(\hat{a}^\dagger - \hat{a})$. In the experiment, through a series of signal processing on the pulse reflected from the readout cavity, we can obtain the voltage $V_I$ and $V_Q$ related to these two orthogonal quadratures. In this tutorial, we simulate the calibration of readout cavity by solving the qubit-cavity dynamics: the cavity transition frequencies with different qubit states ($|0\rangle$ and $|1\rangle$) $\omega_{r0}$ and $\omega_{r1}$, the linewidth $\kappa$ and the dispersive shift $\chi$. ## Preparation To run this tutorial we need to import the following necessary packages from Quanlse and other commonly-used Python libraries. ``` # Import tools from Quanlse from Quanlse.Simulator.ReadoutSim3Q import readoutSim3Q from Quanlse.Calibration.Readout import resonatorSpec, fitLorentzian, lorentzian # Import tools from other python libraries from scipy.signal import find_peaks import numpy as np import matplotlib.pyplot as plt from math import pi ``` ## Calibrating the Readout Cavity Transition Frequencies In this section, we will calibrate the transition frequencies of the reading cavity when the qubit is in the ground state and the first excited state, respectively. Here, we first use the predefined function `readoutSim3Q()` to return the Class object `readoutModel` containing information of the readout cavity. ``` readoutModel = readoutSim3Q() # Initialize a readoutModel object ``` Then, we set the range of frequency sweep `freqRange`, the drive amplitude `amp` and the duration of the readout pulse `duration`. ``` freqRange = np.linspace(7.105, 7.125, 60) * 2 * pi # the range of frequency to probe the resonator, in 2 pi GHz amp = 0.0005 * (2 * pi) # drive amplitude, in 2 pi GHz duration = 1000 # duration of the readout pulse, in nanoseconds ``` Use the function `resonatorSpec` to simulate the frequency sweep of the readout cavity when qubit is in the ground state, and input the index of the resonator `onRes`, the range of the frequency sweep `freqRange`, the amplitude `amp` and the duration `duration` with `qubitState` set to be in the ground state. ``` vi0, vq0 = resonatorSpec(readoutModel=readoutModel, onRes=[0], freqRange=freqRange, amplitude=amp, duration=duration, qubitState='ground') ``` The result returns the measured signal $V_I$ and $V_Q$. We plot $V_Q$ (or $V_I$) with respect to the drive frequency. ``` idx0 = find_peaks(vq0[0], height=max(vq0[0]))[0] # find the index of the transition frequency w0 = freqRange[idx0][0] # transition frequency print(f'The resonator transition frequency with qubit in ground state is {(w0 / (2 * pi)).round(3)} GHz') plt.plot(freqRange / (2 * pi), np.array(vq0[0])) plt.plot() plt.xlabel('$\omega_d$ (GHz)') plt.ylabel('signal (a.u.)') plt.title('Readout resonator spectrum') plt.vlines((freqRange / (2 * pi))[idx0], 0, max(vq0[0]), linestyles='dashed') plt.show() ``` From the result of the simulation shown above, we can see that the read cavity transition frequency is around 7.118 GHz when the qubit is in the ground state. Next, we calibrate the read cavity transition frequency when the qubit is in the excited state using the same procedure. ``` vi1, vq1 = resonatorSpec(readoutModel=readoutModel, onRes=[0], freqRange=freqRange, amplitude=amp, duration=duration, qubitState='excited') idx1 = find_peaks(vq1[0], height=max(vq1[0]))[0] w1 = freqRange[idx1][0] print(f'The resonator transition frequency with qubit in excited state is {(w1 / (2 * pi)).round(3)} GHz') plt.plot(freqRange / (2 * pi), np.array(vq1[0])) plt.plot() plt.xlabel('$\omega_d$ (GHz)') plt.ylabel('signal (a.u.)') plt.title('Readout resonator spectrum') plt.vlines((freqRange / (2 * pi))[idx1], 0, max(vq1[0]), linestyles='dashed') plt.show() ``` It can be seen in the spectrum that the readout cavity transition frequency is about 7.112 GHz when the qubit is in the first excited state. ## Calibrating the Dispersive Shift and Coupling Strength In the previous section, we obtained the calibrated frequencies $f_0$ and $f_1$, so that the dispersion shift $\chi$ can be calculated directly by, $$ \chi = \frac{|f_0 - f_1|}{2}. $$ ``` chi = abs(w0 - w1) / 2 print(f'The dispersive shift is {(chi * 1e3 / (2 * pi)).round(3)} MHz') ``` Combining the expressions of $\chi$ given in the "Introduction" section, we can derive the expression of cavity-qubit coupling strength in terms of other known parameters: $$ g = \sqrt{\frac{\chi\Delta_{qr}(\Delta_{qr}+\alpha)}{\alpha}}. $$ Extract the theoretical parameters from `readoutModel` and calculate the coupling strength $g$ given above. ``` # Extract parameters from the model g = readoutModel.coupling[0] # therotical qubit-resonator coupling strength wq = readoutModel.pulseModel.qubitFreq[0] # qubit bare frequency alpha = readoutModel.pulseModel.qubitAnharm[0] # qubit anharmonicity wr = (w0 + w1) / 2 # estimated resonator frequency detuning = wq - wr # qubit-resonator detuning # coupling strength calculation def qrCoupling(chi, detuning, alpha): g = np.sqrt(abs(chi * detuning * (detuning + alpha) / alpha)) return g gEst = qrCoupling(chi, detuning, alpha) # Estimated qubit-resonator coupling strength ``` Compare the theoretical value and the estimated value of $g$. ``` print(f'Theoretical coupling strength is {g * 1e3 / (2 * pi)} MHz') print(f'Estimated coupling strength is {(gEst * 1e3 / (2 * pi)).round(1)} MHz') ``` The coupling strength of the readout cavity and the qubit, obtained by calibrating the dispersion shift and indirect calculations, is 135 MHz, which is in good agreement with the theoretical value of 134.0 MHz. ## Measuring the decay rate After we have the spectrum of cavity frequency, we are able to estimate the decay rate $\kappa$ by the linewidth of the Lorentzian function. Here, we use the function `fitLorentzian`, input the range of frequency sweep and the reflected signal to fit the spectrum and estimate the linewidth $\kappa$. ``` param, cov = fitLorentzian(freqRange, vq0[0]) # Fit the curve using lorentzian function kappaEst = abs(param[2]) # Estimated linewidth plt.plot(freqRange / (2 * pi), lorentzian(freqRange, param[0], param[1], param[2], param[3]), '.') plt.plot(freqRange / (2 * pi), vq0[0]) plt.xlabel('$\omega_d$ (GHz)') plt.ylabel('signal (a.u.)') plt.show() ``` Compare the theoretical value and the estimated value of decay rate (or linewidth). ``` kappa = readoutModel.dissipation print(f'Theoretical linewidth is {kappa * 1e3 / (2 * pi)} MHz') print(f'Estimated linewidth is {(kappaEst * 1e3 / (2 * pi)).round(3)} MHz') ``` From the simulation results, we can see that the decay rate $\kappa$ set in the master equation is 2.0 MHz, while the linewidth obtained from the spectrum is 1.987 MHz, indicating that the interaciton strength between the reading cavity and the environment can be indirectly calibrated by scanning the frequency of the reading cavity and calculating the line width in the experiment. ## Summary Users can click on this link [tutorial-readout-cavity-calibration.ipynb](https://github.com/baidu/Quanlse/blob/main/Tutorial/EN/tutorial-readout-cavity-calibration.ipynb) to jump to the corresponding GitHub page for this Jupyter Notebook documentation and run this tutorial. You can try different hardware parameters of the readout cavity and run the codes in this tutorial to simulate the cavity calibration in the superconducting quantum computing experiment. ## Reference \[1\] [Blais, Alexandre, et al. "Cavity quantum electrodynamics for superconducting electrical circuits: An architecture for quantum computation." *Physical Review A* 69.6 (2004): 062320.](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.69.062320) \[2\] [Koch, Jens, et al. "Charge-insensitive qubit design derived from the Cooper pair box." *Physical Review A* 76.4 (2007): 042319.](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.76.042319) \[3\] [Lindblad, Goran. "On the generators of quantum dynamical semigroups." *Communications in Mathematical Physics* 48.2 (1976): 119-130.](https://link.springer.com/article/10.1007/bf01608499) \[4\] [Bianchetti, R., et al. "Dynamics of dispersive single-qubit readout in circuit quantum electrodynamics." *Physical Review A* 80.4 (2009): 043840.](https://journals.aps.org/pra/abstract/10.1103/PhysRevA.80.043840)
github_jupyter
# Lecture 34: VGGNet ``` %matplotlib inline import tqdm import copy import time import torch import numpy as np import torchvision import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import matplotlib.pyplot as plt from torchvision import transforms,datasets, models print(torch.__version__) # This code has been updated for PyTorch 1.0.0 ``` ## Load Data: ``` apply_transform = transforms.Compose([transforms.Resize(224),transforms.ToTensor()]) BatchSize = 4 trainset = datasets.CIFAR10(root='./CIFAR10', train=True, download=True, transform=apply_transform) trainLoader = torch.utils.data.DataLoader(trainset, batch_size=BatchSize, shuffle=True, num_workers=4) # Creating dataloader testset = datasets.CIFAR10(root='./CIFAR10', train=False, download=True, transform=apply_transform) testLoader = torch.utils.data.DataLoader(testset, batch_size=BatchSize, shuffle=False, num_workers=4) # Creating dataloader # Size of train and test datasets print('No. of samples in train set: '+str(len(trainLoader.dataset))) print('No. of samples in test set: '+str(len(testLoader.dataset))) ``` ## Define network architecture ``` net = models.vgg16() print(net) # Counting number of trainable parameters totalParams = 0 for name,params in net.named_parameters(): print(name,'-->',params.size()) totalParams += np.sum(np.prod(params.size())) print('Total number of parameters: '+str(totalParams)) # Copying initial weights for visualization init_weightConv1 = copy.deepcopy(net.features[0].weight.data) # 1st conv layer init_weightConv2 = copy.deepcopy(net.features[2].weight.data) # 2nd conv layer # Check availability of GPU use_gpu = torch.cuda.is_available() # use_gpu = False # Uncomment in case of GPU memory error if use_gpu: print('GPU is available!') device = "cuda" else: print('GPU is not available!') device = "cpu" net = net.to(device) ``` ## Define loss function and optimizer ``` criterion = nn.NLLLoss() # Negative Log-likelihood optimizer = optim.Adam(net.parameters(), lr=1e-4) # Adam ``` ## Train the network ``` iterations = 5 trainLoss = [] testAcc = [] start = time.time() for epoch in range(iterations): epochStart = time.time() runningLoss = 0 net.train() # For training for data in tqdm.tqdm_notebook(trainLoader): inputs,labels = data inputs, labels = inputs.to(device), labels.to(device) # Initialize gradients to zero optimizer.zero_grad() # Feed-forward input data through the network outputs = net(inputs) # Compute loss/error loss = criterion(F.log_softmax(outputs,dim=1), labels) # Backpropagate loss and compute gradients loss.backward() # Update the network parameters optimizer.step() # Accumulate loss per batch runningLoss += loss.item() avgTrainLoss = runningLoss/(50000.0/BatchSize) trainLoss.append(avgTrainLoss) # Evaluating performance on test set for each epoch net.eval() # For testing [Affects batch-norm and dropout layers (if any)] running_correct = 0 with torch.no_grad(): for data in tqdm.tqdm_notebook(testLoader): inputs,labels = data inputs = inputs.to(device) outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) if use_gpu: predicted = predicted.cpu() running_correct += (predicted == labels).sum() avgTestAcc = float(running_correct)*100/10000.0 testAcc.append(avgTestAcc) # Plotting training loss vs Epochs fig1 = plt.figure(1) plt.plot(range(epoch+1),trainLoss,'r-',label='train') if epoch==0: plt.legend(loc='upper left') plt.xlabel('Epochs') plt.ylabel('Training loss') # Plotting testing accuracy vs Epochs fig2 = plt.figure(2) plt.plot(range(epoch+1),testAcc,'g-',label='test') if epoch==0: plt.legend(loc='upper left') plt.xlabel('Epochs') plt.ylabel('Testing accuracy') epochEnd = time.time()-epochStart print('Iteration: {:.0f} /{:.0f} ; Training Loss: {:.6f} ; Testing Acc: {:.3f} ; Time consumed: {:.0f}m {:.0f}s '\ .format(epoch + 1,iterations,avgTrainLoss,avgTestAcc,epochEnd//60,epochEnd%60)) end = time.time()-start print('Training completed in {:.0f}m {:.0f}s'.format(end//60,end%60)) # Copying trained weights for visualization trained_weightConv1 = copy.deepcopy(net.features[0].weight.data) trained_weightConv2 = copy.deepcopy(net.features[2].weight.data) if use_gpu: trained_weightConv1 = trained_weightConv1.cpu() trained_weightConv2 = trained_weightConv2.cpu() ``` ## Visualization of weights ``` # functions to show an image def imshow(img, strlabel): npimg = img.numpy() npimg = np.abs(npimg) fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 10 fig_size[1] = 10 plt.rcParams["figure.figsize"] = fig_size plt.figure() plt.title(strlabel) plt.imshow(np.transpose(npimg, (1, 2, 0))) imshow(torchvision.utils.make_grid(init_weightConv1,nrow=8,normalize=True),'Initial weights: conv1') imshow(torchvision.utils.make_grid(trained_weightConv1,nrow=8,normalize=True),'Trained weights: conv1') imshow(torchvision.utils.make_grid(init_weightConv1-trained_weightConv1,nrow=8,normalize=True),'Difference of weights: conv1') imshow(torchvision.utils.make_grid(init_weightConv2[0].unsqueeze(1),nrow=8,normalize=True),'Initial weights: conv2') imshow(torchvision.utils.make_grid(trained_weightConv2[0].unsqueeze(1),nrow=8,normalize=True),'Trained weights: conv2') imshow(torchvision.utils.make_grid(init_weightConv2[0].unsqueeze(1)-trained_weightConv2[0].unsqueeze(1),nrow=8,normalize=True),'Difference of weights: conv2') ```
github_jupyter
<a href="https://colab.research.google.com/github/yohanesnuwara/mem/blob/master/02_overburden_calculation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Load Data ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd ``` Access Google Drive to get data ``` from google.colab import drive drive.mount('/content/drive') import sys sys.path.append('/content/drive/My Drive/Colab Notebooks') ``` 46 LAS files from Norne Field. ``` import glob import os file_path = "/content/drive/My Drive/Colab Notebooks/well_logs" read_files = glob.glob(os.path.join(file_path, "*.las")) read_files ``` Get the name of the well from the file. ``` well_names = [] for files in read_files: files = os.path.splitext(os.path.basename(files))[0] well_names.append(files) well_names ``` If the well name too long, shorten it by renaming it. ``` well_names = np.array(well_names) wellnames = np.array(['B1BH', 'E2AH', 'B1AHT2', 'K1HT2', 'B1H', 'B2H', 'B3H', 'B4AH', 'B4BH', 'B4CH', 'B4DHT2', 'B4H', 'C1H', 'C2H', 'C3H', 'C4AH', 'C4H', 'D1AH', 'D1BH', 'D1CH', 'D1H', 'D2HT2', 'D3AH', 'D3BY1HT2', 'D3BY2H', 'D3H', 'D4AH', 'D4AHT2', 'D4H', 'E1H', 'E2H', 'E3AH', 'E3AHT2', 'E3BH', 'E3CHT2','E3H', 'E4AH', 'E4AHT2', 'E4H','E4HT2', 'F1H', 'F2H', 'F3H', 'F4H','K1H', 'K3H']) ``` Import `lasio` library to import LAS data ``` !pip install lasio import lasio ``` Read LAS file (if command: `Header section Parameter regexp=~P was not found.`, it's OK) ``` lases = [] for files in read_files: las = lasio.read(files) lases.append(las) ``` ## Well catalogue Input the name of the well you want to view in the `find` and check what data is present. ``` wellnames # type the numbers from 0 to 45 in the wellames[...] find = wellnames[0] # print the name of the searched well print("Well name:", find) id_ = np.int64(np.where(wellnames==find)).item() print("Data available:", lases[id_].keys()) # check more details print("Detail about data:") print(lases[id_].curves) # peek or overviewing the well log # which data you want to see data_view = 'RHOB' print("Data", data_view, "of well:", find) plt.figure(figsize=(5,10)) plt.plot((lases[id_][data_view]), (lases[id_]['DEPTH'])) plt.xlabel(data_view); plt.ylabel("Depth (m)") plt.grid(True) plt.gca().invert_yaxis() ``` ## Data Preproc ### Data cleanup for NaN values ``` # convert to panda df = pd.DataFrame({"Depth": (lases[id_]['DEPTH']), "RHOB": (lases[id_][data_view])}) # look up the number of rows with NaN data print("Original size of data:", len(df), "rows") print("How many data with NaN values?") print(df.isnull().sum()) # drop rows with missing values df.dropna(inplace=True) # re-index dataframe df = df.reset_index(drop=True) print("NaN has successfully been deleted") df ``` ### Data Interpolation Water column is 380 m (Norne Field wikipedia) Density interpolated to depth 0 to 350 m with rho water 1 g/cc and from seabed at depth 350 m to the density value at depth of first recorded. ``` # create average density (dummy) value from the sea surface (z = 0) to seabed depth_seabed = np.arange(0, 370, 10) # depth to seabed 350 m rho_seabed = np.full(len(depth_seabed), 1) # create numpy array of constant water density values 1 g/cc # depth from seabed to first recorded depth depth_first_recorded = df.Depth[0] depth_surface = np.linspace(360, depth_first_recorded, 100) d1 = 360; d2 = depth_first_recorded rho1 = 1; rho2 = df.RHOB[0] # interpolation function to connect from seabed to first recorded depth: rho = (((rho2 - rho1) * (depth - 1000)) + 1) / (d2 - d1) rho_surface = (((rho2 - rho1) * (depth_surface - d1)) / (d2 - d1)) + 1 # append data depth_dummy = np.append(depth_seabed, depth_surface) rhob_dummy = np.append(rho_seabed, rho_surface) df_dummy = pd.DataFrame({"Depth": depth_dummy, "RHOB": rhob_dummy}) df_new = df_dummy.append(df, ignore_index = True) df_new ``` ### Visualize Data after Preproc ``` print("Data", data_view, "of well:", find) plt.figure(figsize=(5,10)) plt.plot(df_new.RHOB, df_new.Depth) plt.xlabel(data_view); plt.ylabel("Depth (m)") plt.grid(True) plt.gca().invert_yaxis() ``` ## Overburden Stress Calculation ### It will calculate and save into individual well only, so in the code `sv...` below give index that matches with the current index of `wellnames[...]`. For example well `B1BH` with `wellnames[0]`, Sv is `sv0`; well `K3H` with `wellnames[45]`, so Sv is `sv45`. ``` # convert panda to numpy depth_np = np.array(df_new.Depth) rhob_np = np.array(df_new.RHOB) rhob_np_conv = rhob_np * 1E+03 # convert g/cm3 to kg/m3 thickness = np.array([j-i for i, j in zip(depth_np[:-1], depth_np[1:])]) thickness = np.append([(min(depth_np) - 0)], thickness) # multiply rhob by thickness rhogz = rhob_np_conv * thickness * 9.8 # rhob already in kg/m3 * thickness m2, result in Pa rhogz = rhogz * 0.000145038 # convert Pa to psi "cumulative sum, calculate Sv, here you must CHANGE the index of sv: sv0, sv1, ..., sv45" sv0 = np.cumsum(rhogz) print("Calculated vertical stress of well:", find) plt.figure(figsize=(5,10)) plt.plot(sv0, depth_np) plt.xlabel("Sv"); plt.ylabel("Depth (m)") plt.xlim(xmin=0); plt.ylim(ymin=0) plt.grid(True) plt.gca().invert_yaxis() ```
github_jupyter
### import libraries use the following lines to import the packages that you need. If you remove the #, then they will be executable. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy import stats as spt ``` ### path name: find the path of the file in your computer. Remember that you need to add the name and the extension of the file at the end. In wondowns add r to make sure that Python identifies this line as a path name. ``` pathName = r'C:\MyFiles\Dropbox\Teaching\Urban_Data_Analsysis\Fall 2020\Data\exam_scores.csv' ``` ### read the file into a dataframe. A dataframe is basically a table. using the following line, you can read a csv line and convert it to a dataframe. ``` df = pd.read_csv(pathName) ``` ### you can read jason files from NYC's open data API. copy and paste the url. ``` # add the url here and read it as a dataframe df = pd.read_json('https://data.cityofnewyork.us/resource/kku6-nxdu.json') ``` ### see the list of all columns ``` df.columns ``` ### get a column of a dataframe Read the column and and name it as a new variable. the name of the column should be in single qoutation 'col' ``` col = df['col_1'] ``` ### histogram you can use plt to plot a histogram. plt.hist() needs at leas the x axis as an argument. Use "bins =" to specify the number of bins (bars). ``` plt.hist(col,bins=8); ``` ### some measures of a column mean, standard deviation, max, min, median, and sum. ``` col.mean() col.std() col.max() col.min() col.sum() col.median() ``` ### scatter plots They need two columns that will be passed as two arguments. one for the x axis and one for the y axis. Use "alpha = " with a number between 0 and 1 to increase the transparency of the markers. Use "c= 'red'" to add colors. Use "s = " to set the size of markers. Use "marker = " to set the shape of markers. Check the doumentation for more detials. plt.scatter? will give you more details. ``` plt.scatter? plt.scatter(col1,col2,alpha=0.5,s=200,c ='red',marker='^') ``` ### Correlation Coefficient There are multiple ways to get the correlation of two cols ``` # numpy has this easy function. However, you need to filter out all the nan values before. np.corrcoef(col1,col2) # Scipy's way; This will also give you the P value. spt.pearsonr(col1,col2) # pandas' way; this will create a matrix of all columns. You may want to get a subset of columns only. df.corr() # to get a subset of columns only new_df = df[['col1','col2','col3']] # now get the correlation matrix for this new dataframe new_df.corr() ``` ### Filtering a dataframe or getting a subset ``` # to get a subset of a dataframe using a numerical variable # df[condition] df_sub_1 = df[df['col1']> aNumber] # to get a subset of a dataframe using a categorical variable. you need to specify the name of cateogry in the line after == df_sub_2 = df[df['col2']=='category value'] # to have multiple conditions use & for AND and | for OR. Do not foroget to use ()s to separate the conditions # df[(condition_11)&(condition_2)] df_sub_3 = df[(df['col2']=='category value')&(df['col1']> aNumber)] ``` ### get the unique values of a column; very helpful for categorical variables ``` df['col1'].unique() ``` ### Get the quantile of a column. 0.4 means 40%. 0.5 means 50%. ``` df['col1'].quantile(0.4) ``` ### group by in pandas there are multiple ways to handle groupby (consolidating or summarizing) tables in pandas. for more information check this out: https://www.geeksforgeeks.org/pandas-groupby/ ``` # for groupby you need to have a categorical column that will define the groups to be consiolidated. # you can use different types of summary to summarize other variables for each group (sum(), mean(), median(), min(), max(), quantile(q),std()) df.groupby(by=['categorical_column1']).quantile(0.3) # you can groupby using one, two, or more categorical variables df.groupby(by=['categorical_column1','categorical_column2']).median() # this syntax will help you to get groupby for multiple summary types. Note that in this case, you cannot get quantiles. # the output can be saved in a new dataframe. grp = df.groupby('categorical_column1') grp['numerical_column'].agg([np.median, np.mean, np.std]) # dfGroupExample = grp['numerical_column'].agg([np.median, np.mean, np.std]) ``` # Python basics #### Operations ``` 3 + 5 * 4 (3+5) * 4 # Raise 2 to the power of 4 2 ** 4 # The 3rd root of 27 27 ** (0.5) 22/6 22 // 6 22 % 6 (4 - 2) * ((6 + 3) / (4 - 1)) ``` #### Assigning ``` x = 1 x y = x + 1 y x == 1 print ('hello', ' ', x, 'people') x # Assign the value of x + 1 to x x += 1 x = x + 1 x print (1+2) ``` #### Lists ``` myList = [1,2,2,2,4,6,10,10,12,15,18,20] myList # return the fist value of a list myList[0] myList[6] # return the last value of a list myList[-1] # Return a slice (list) of a list myList[3:7] # length of a list len(myList) # sum of a list sum(myList) # append an item to a list myList.append(5) myList.sort() myList ``` #### Dictionaries ``` sampleD = {'NY': 'New York','CO':'Colorado','AZ':'Arizona','CA':'California'} sampleD['AZ'] sampleD2 = {1:'Rose',5:'Lavender',2:'Daffodil',10:'Lily'} sampleD2[2] sampleD2.values() sampleD2.keys() sampleD2.items() ``` #### some general things ``` print('hello') print(x) print(myList) type(x) type(myList) type(sampleD2) ``` #### Strings ``` s = 'this is a sample line' s [5] len(s) s [5:10] s.find('s') s.find('sa') s.replace("sample","example") s.isupper() ``` #### for loops ``` for item in [10,20,30,40]: print (item) myList for i in range(0,len(myList)): print(myList[i]) firstNames = ['Mehdi','Andrew','Rachel','Lori','Charlie','Mike'] lastNames = ['Heris','','','','',''] for i in range(0,len(firstNames)): print (firstNames[i]) for i in range(0,len(firstNames)): print (firstNames[i]) a = 'Mehdi' b = 'Heris' a + ' ' + b if a == 'Mehdi': print ('Bingoooooooo') for item in [10,20,30,40,60,70,80]: if item > 50: print (item) a = 2 a b =7 b if a == (b-5): print('yay') else: print('sorry') b ```
github_jupyter
# TFX on KubeFlow Pipelines Example This notebook should be run inside a KF Pipelines cluster. ### Install TFX and KFP packages ``` !pip3 install https://storage.googleapis.com/ml-pipeline/tfx/tfx-0.12.0rc0-py2.py3-none-any.whl !pip3 install https://storage.googleapis.com/ml-pipeline/release/0.1.16/kfp.tar.gz --upgrade ``` ### Enable DataFlow API for your GKE cluster <https://console.developers.google.com/apis/api/dataflow.googleapis.com/overview> ## Get the TFX repo with sample pipeline ``` !git clone https://github.com/tensorflow/tfx # copy the trainer code to a storage bucket as the TFX pipeline will need that code file in GCS from tensorflow import gfile gfile.Copy('tfx/examples/chicago_taxi_pipeline/taxi_utils.py', 'gs://<my bucket>/<path>/taxi_utils.py') ``` ## Configure the TFX pipeline example Reload this cell by running the load command to get the pipeline configuration file ``` %load tfx/examples/chicago_taxi_pipeline/taxi_pipeline_kubeflow.py ``` Configure: - Set `_input_bucket` to the GCS directory where you've copied taxi_utils.py. I.e. gs://<my bucket>/<path>/ - Set `_output_bucket` to the GCS directory where you've want the results to be written - Set GCP project ID (replace my-gcp-project). Note that it should be project ID, not project name. The dataset in BigQuery has 100M rows, you can change the query parameters in WHERE clause to limit the number of rows used. ``` %load tfx/examples/chicago_taxi_pipeline/taxi_pipeline_kubeflow.py ``` ## Compile the pipeline and submit a run to the Kubeflow cluster ``` # Get or create a new experiment import kfp client = kfp.Client() experiment_name='TFX Examples' try: experiment_id = client.get_experiment(experiment_name=experiment_name).id except: experiment_id = client.create_experiment(experiment_name).id pipeline_filename = 'chicago_taxi_pipeline_kubeflow.tar.gz' #Submit a pipeline run run_name = 'Run 1' run_result = client.run_pipeline(experiment_id, run_name, pipeline_filename, {}) ``` ### Connect to the ML Metadata Store ``` !pip3 install ml_metadata from ml_metadata.metadata_store import metadata_store from ml_metadata.proto import metadata_store_pb2 import os connection_config = metadata_store_pb2.ConnectionConfig() connection_config.mysql.host = os.getenv('MYSQL_SERVICE_HOST') connection_config.mysql.port = int(os.getenv('MYSQL_SERVICE_PORT')) connection_config.mysql.database = 'mlmetadata' connection_config.mysql.user = 'root' store = metadata_store.MetadataStore(connection_config) # Get all output artifacts store.get_artifacts() # Get a specific artifact type # TFX types # types = ['ModelExportPath', 'ExamplesPath', 'ModelBlessingPath', 'ModelPushPath', 'TransformPath', 'SchemaPath'] store.get_artifacts_by_type('ExamplesPath') ```
github_jupyter
### Figures for colloquium at the University of Rochester in 2018 April. Links for the tour of the viewer: * [Galactic Center (DECaPS)](http://legacysurvey.org/viewer?ra=266.41683&dec=-29.0078&zoom=16&layer=decaps) * Zoom out and switch to WISE, H-alpha, dust layers. Overlay the constellations. * [NGC6742 Planetary Nebula](http://legacysurvey.org/viewer/?ra=284.83291667&dec=48.46527778&layer=decals-dr6&zoom=10) * [UGC12589 Interacting System](http://legacysurvey.org/viewer?ra=351.2607&dec=0.0087&zoom=9&layer=decals-dr5) * [SDSS/C4 2010 Cluster](http://legacysurvey.org/viewer?ra=29.0707&dec=1.0510&zoom=13&layer=decals-dr5) ``` import os import numpy as np import numpy.ma as ma import pandas as pd import warnings from scipy.stats import kde, binned_statistic from matplotlib.ticker import FormatStrFormatter, MultipleLocator import matplotlib.pyplot as plt from astropy.io import fits, ascii from astropy.table import Table import seaborn as sns colors = sns.color_palette() sns.set(context='talk', style='ticks', font_scale=1.5)#, palette='deep') sns.set_palette('deep', 12) import legacyhalos.io %matplotlib inline talkdir = os.path.join(os.getenv('LEGACYHALOS_DIR'), 'talks', 'rochester-2018apr') hdefault = 0.7 # 0.677 # Hubble constant ``` ### Some utility functions. ``` def mstar_label(): return r'$log_{10}\, (\mathcal{M}\ /\ h^{-2}\, \mathcal{M}_{\odot})$' def mstar_label2(): return r'$log_{10}\, (\mathcal{M}\ /\ h^{-1}\, \mathcal{M}_{\odot})$' def mstar_label3(): return r'$log_{10}\, (\mathcal{M}\, \mathcal{M}_{\odot})$' def phi_label(): return r'$log_{10}\, (\mathcal{\Phi}\ /\ h^{3}$ Mpc$^{-3}$ dex$^{-1})$' ``` ### Model stellar mass functions Data taken from Knebe+18. ``` def read_carnage_smf(fullrange=False, seed=None, h=hdefault): """Data taken from Knebe+18.""" carnagedir = os.path.join(os.getenv('CATALOGS_DIR'), 'carnage') labels = ('DLB07', 'GalICS2.0', 'LGALAXIES', 'SAG', 'MIC3', 'SAGE', 'Galform-GP14', 'MORGANA', 'ySAM') data = [] for model in ('DLB07-c01.txt', 'GalICS2.0-c01.txt', 'LGALAXIES-c01.txt', 'SAG-c01.txt', 'MIC3-c01.txt', 'SAGE-c01.txt', 'Galform-GP14-c01.txt', 'MORGANA-c01.txt', 'ySAM-c01.txt'): dd = ascii.read(os.path.join(carnagedir, 'Fig.1', model), format='basic', names=('mstar', 'phi', 'junk1', 'junk2', 'junk3'), exclude_names=('junk1', 'junk2', 'junk3')) good = np.where( np.isfinite(dd['phi']) * (dd['mstar'] > 0) )[0] dd = dd[good] dd['mstar'] = np.log10(dd['mstar'] / h) dd['phi'] = np.log10(dd['phi'] * h**3) data.append(dd) if fullrange: rand = np.random.RandomState(seed) mstar, phi = [], [] for dd in data: #good = np.where( np.isfinite(dd['phi']) * (dd['mstar'] > 0) )[0] mstar.append(dd['mstar']+ rand.normal(loc=0, scale=0.05)) phi.append(dd['phi']) mstar = np.hstack(mstar) phi = np.hstack(phi) width = 0.2 mstarrange = (9.1, 12.5) nbins = np.int(np.ptp(mstarrange) / width) phimin, mstar_edges, _ = binned_statistic(mstar, phi, statistic='min', bins=nbins, range=mstarrange) phimax, _, _ = binned_statistic(mstar, phi, statistic='max', bins=nbins, range=mstarrange) mstar = mstar_edges[1:] - width / 2 return mstar, phimin, phimax else: return data, labels def qa_carnage_smf(individual=True, fullrange=False, png=None, ylim=None): fig, ax = plt.subplots(figsize=(10, 7)) if individual: data, labels = read_carnage_smf() ls = ('-', '--', '-.', ':') for dd, ll in zip(data, labels): ax.plot(dd['mstar'], dd['phi'], label=ll, lw=4, ls=ls[0], alpha=0.8) ls = np.roll(ls, 1) if fullrange: mstar, phimin, phimax = read_carnage_smf(fullrange=True, seed=1) ax.fill_between(mstar, phimin, phimax, alpha=0.2, color='gray', label='All CARNage Models') ax.grid() ax.set_xlim(9, 12.5) if ylim: ax.set_ylim(ylim) ax.set_xlabel(mstar_label2()) ax.set_ylabel(phi_label()) ax.legend(loc='lower left', ncol=2, fontsize=16) if png: plt.savefig(png) qa_carnage_smf(fullrange=False, png=os.path.join(talkdir, 'smf-carnage.png')) qa_carnage_smf(fullrange=False, png=os.path.join(talkdir, 'smf-carnage-ylim.png'), ylim=(-7.7, -1.5)) qa_carnage_smf(fullrange=True) ``` ### Observed stellar mass functions Data taken from Huang+18. ``` def read_moustakas13(starforming=False, quiescent=False): """Read data from Moustakas+13.""" moosedir = os.path.join(os.getenv('CATALOGS_DIR'), '13moustakas') suffix = 'all' if starforming: suffix = 'starforming' if quiescent: suffix = 'quiescent' smffile = os.path.join(moosedir, 'smf_{}_supergrid01.txt'.format(suffix)) data = ascii.read(smffile, format='basic', names=('zlo', 'zhi', 'ngal', 'mstar', 'limit', 'phi', 'philo', 'phihi', 'phicv')) loz = np.where( data['zhi'] <= 0.2 )[0] data = data[loz] return data['mstar'], data['phi'], data['phi'] - data['phicv'], data['phi'] + data['phicv'] def read_bernardi17(h=hdefault, dustfree=True): """Read data from Bernardi+17.""" moosedir = os.path.join(os.getenv('CATALOGS_DIR'), '17bernardi') data = pd.read_table(os.path.join(moosedir, 'smf.txt'), delim_whitespace=True) mstar = data['mstar'].values # - np.log10(h**2) if dustfree: phi = data['phi_M14_dustfree_obs'].values # + np.log10(h**3) philo = phi - data['phierr_M14_dustfree'].values phihi = phi + data['phierr_M14_dustfree'].values else: phi = data['phi_M14_dust_obs'].values # + np.log10(h**3) philo = phi - data['phierr_M14_dust'].values phihi = phi + data['phierr_M14_dust'].values return mstar, phi, philo, phihi def read_huang18(cModel=False, BCG=False, total=False, h=hdefault): huangdir = os.path.join(os.getenv('CATALOGS_DIR'), '18huang') if BCG: censuffix = 'cenhighmh' else: censuffix = 'cenlowmh' if cModel: fluxsuffix = 'cmodel' else: fluxsuffix = '100kpc' if total: data = Table.read(os.path.join(huangdir, 's16a_massive_{}_{}_smf.fits'.format('cenhighmh', fluxsuffix))) _data = Table.read(os.path.join(huangdir, 's16a_massive_{}_{}_smf.fits'.format('cenlowmh', fluxsuffix))) #print(data['logm_mean'], data['smf'].data, _data['smf'].data) data['smf'] += _data['smf'] data['smf_err'] = np.sqrt( data['smf_err']**2 + _data['smf_err']**2 ) data['smf_low'] = np.sqrt( data['smf_low']**2 + _data['smf_low']**2 ) data['smf_upp'] = np.sqrt( data['smf_upp']**2 + _data['smf_upp']**2 ) else: smffile = os.path.join(huangdir, 's16a_massive_{}_{}_smf.fits'.format(censuffix, fluxsuffix)) data = Table.read(smffile) good = np.where( (data['logm_0'] >= 11.4) * (data['smf_err'] > 0) )[0] mstar = data['logm_mean'][good] # - 2*np.log10(h) phi = np.log10(data['smf'][good]) # * h**3) phierr = data['smf_err'][good] / data['smf'][good] / np.log(10) philo = phi - data['smf_low'][good] / data['smf'][good] / np.log(10) phihi = phi + data['smf_upp'][good] / data['smf'][good] / np.log(10) return mstar, phi, philo, phihi def double_schechter(logmass, logmstar1=10.0, logmstar2=11.0, alpha1=-1, alpha2=-1.1, phistar1=0.008, phistar2=0.001): mratio1 = pow(10, logmass - logmstar1) mratio2 = pow(10, logmass - logmstar2) model = np.log(10) * ( np.exp(-mratio1) * phistar1 * mratio1**(alpha1 + 1) + np.exp(-mratio2) * phistar2 * mratio2**(alpha2+1) ) return model def read_dsouza15(h=hdefault): logmass = np.arange(9.5, 12.5, 0.05) phimodel = double_schechter(logmass, logmstar1=10.615, logmstar2=10.995, alpha1=-1.082, alpha2=-1.120, phistar1=0.008579, phistar2=0.000355) logmass = logmass - np.log10(h**2) logphi = np.log10(phimodel * h**3) good = np.where(logphi > -7.6)[0] return logmass[good], logphi[good] ``` ### A plot from Emsellem+07. ``` def read_emsellem07(): """Read data from Emsellem+07.""" tdir = os.path.join(os.getenv('CATALOGS_DIR'), '07emsellem') data = pd.read_table(os.path.join(tdir, 'table1.txt'), delim_whitespace=True) return data def qa_emsellem07(png=None): data = read_emsellem07() dist = 10**((data.DM.values + 5) / 5.0) * 3.0896e16 # [m] rad = data['Re'].values * 206265.0 * dist # [m] sigma = data['sigma'].values * 1e3 # [m/s] mvir = np.log10( 5.0 * rad * sigma**2 / 6.67e-11 / 1.99e30 ) - 10.5 # hack! lam = data['lambda_Re'].values fast = lam > 0.1 slow = ~fast fig, ax = plt.subplots(figsize=(10, 7)) ax.scatter(mvir[fast], lam[fast], label='Fast Rotators', marker='s', s=150, alpha=0.8) ax.scatter(mvir[slow], lam[slow], label='Slow Rotators', marker='o', s=150, alpha=0.8) ax.legend(loc='upper right', frameon=True) ax.set_xlim(9.75, 12.3) ax.set_ylim(0, 0.8) ax.grid() ax.set_xlabel(r'$log_{10}\, (\mathcal{M}_{vir}\ /\ \mathcal{M}_{\odot})$') ax.set_ylabel(r'Angular Momentum $\ \lambda_{Re}$') if png: plt.savefig(png) qa_emsellem07(os.path.join(talkdir, '07emsellem-fig1.png')) ``` ### Reproduce Fig 3 in Moustakas+13. ``` def qa_moustakas_fig3(png=None): colors = sns.color_palette() fig, (ax, ax2) = plt.subplots(2, 1, figsize=(10, 10), sharex=True, gridspec_kw = {'height_ratios':[2, 1]}) mstar, phi, philo, phihi = read_moustakas13(starforming=True) ax.fill_between(mstar, philo, phihi, alpha=0.3, color=colors[0]) ax.plot(mstar, phi, lw=3, ls='-', marker='o', markersize=10, label='Star-Forming', color=colors[0]) mstar, phi, philo, phihi = read_moustakas13(quiescent=True) ax.fill_between(mstar, philo, phihi, alpha=0.3, color=colors[8]) ax.plot(mstar, phi, lw=3, ls='-', marker='s', markersize=10, label='Quiescent', color=colors[8]) ax.set_ylabel(phi_label()) ax.set_xlim(9, 12.3) ax.set_ylim(-7.7, -1.5) ax.grid() ax.margins(0) ax.legend(loc='lower left', fontsize=22) mstar, phi, _, _ = read_moustakas13() mstar_sf, phi_sf, _, _ = read_moustakas13(starforming=True) mstar_qq, phi_qq, phi_qq_hi, phi_qq_lo = read_moustakas13(quiescent=True) keep = np.where(mstar_qq <= mstar.max())[0] phi_qq = phi_qq[keep] phi_qq_hi = phi_qq_hi[keep] phi_qq_lo = phi_qq_lo[keep] phi_ratio = 10**(phi_qq - phi) phi_ratio_hi = 10**(phi_qq_hi - phi) phi_ratio_lo = 10**(phi_qq_lo - phi) ax2.fill_between(mstar, phi_ratio_lo, phi_ratio_hi, alpha=0.3, color='k') ax2.plot(mstar, phi_ratio, lw=3, ls='-', color='k') ax2.set_xlim(9, 12.3) ax2.set_ylim(0, 1.1) ax2.set_ylabel('Quiescent Fraction') ax2.set_xlabel(mstar_label()) ax2.grid() ax2.margins(0) plt.subplots_adjust(hspace=0.02) if png: plt.savefig(png) qa_moustakas_fig3(png=os.path.join(talkdir, '13moustakas-fig3.png')) def qa_smf(plot_carnage=True, plot_huang=True, png=None): fig, ax = plt.subplots(figsize=(10, 7)) # Model shaded region if plot_carnage: mstar, phimin, phimax = read_carnage_smf(fullrange=True, seed=1) ax.fill_between(mstar, phimin, phimax, alpha=0.2, color='gray', label='CARNage Models (z~0)') # Moustakas+13 mstar, phi, philo, phihi = read_moustakas13() ax.fill_between(mstar, philo, phihi, alpha=0.3) ax.plot(mstar, phi, lw=3, ls='-', label='Moustakas+13 (z~0.1)') # D'Souza+15 mstar, phi = read_dsouza15() ax.fill_between(mstar, phi, phi, alpha=0.3) ax.plot(mstar, phi, lw=3, ls='-', label="D'Souza+15 (z~0.1)") # Bernardi+17 mstar, phi, philo, phihi = read_bernardi17(dustfree=True) ax.fill_between(mstar, philo, phihi, alpha=0.3) ax.plot(mstar, phi, lw=3, ls='-', label='Bernardi+17 (z~0.1)') # Huang+18 if plot_huang: mstar, phi, philo, phihi = read_huang18(cModel=False, BCG=False, total=True) ax.fill_between(mstar, philo, phihi, alpha=0.3) ax.plot(mstar, phi, lw=3, ls='-', label='Huang+18 (z~0.4)')# (HSC, <100 kpc)') ax.set_xlabel(mstar_label()) ax.set_ylabel(phi_label()) ax.set_ylim(-7.7, -1.5) ax.set_xlim(9, 12.5) ax.grid() hh, ll = ax.get_legend_handles_labels() #handles = handles[np.array(list(1, 2, 0 #labels = labels[np.array([1, 2, 0])] ax.legend(loc='lower left', fontsize=18) #ax.legend([hh[0],hh[1],hh[2],hh[3]], [ll[0],ll[1],ll[2]], loc='lower left', fontsize=18) if png: plt.savefig(png) qa_smf(plot_carnage=False, png=os.path.join(talkdir, 'smf-data.png')) qa_smf(plot_carnage=True, png=os.path.join(talkdir, 'smf-data-carnage.png')) qa_smf(plot_carnage=True, plot_huang=False, png=os.path.join(talkdir, 'smf-data-carnage-nohuang.png')) def qa_smf_huang18(minmax=False, png=None): def plot_huang18(ax, cModel=False, BCG=False, label=''): mstar, phi, philo, phihi = read_huang18(cModel=cModel, BCG=BCG) ax.fill_between(mstar, philo, phihi, alpha=0.3) ax.plot(mstar, phi, label=label, lw=3, ls='-') fig, ax = plt.subplots(figsize=(10, 7)) # Model shaded region # mstar, phimin, phimax = read_model_smf(minmax=True, seed=1) # ax.fill_between(mstar, phimin, phimax, alpha=0.2, color='gray') # Data plot_huang18(ax, cModel=False, BCG=False, label=r'$\log\,(\mathcal{M}_h/\mathcal{M}_{\odot})<14.2$')#, $R<100$ kpc') #plot_huang18(ax, cModel=True, BCG=False, label=r'$\log\,(M_h/M_{\odot})<14.2$, cModel') plot_huang18(ax, cModel=False, BCG=True, label=r'$\log\,(\mathcal{M}_h/\mathcal{M}_{\odot})>14.2$')#, R<100 kpc$') #plot_huang18(ax, cModel=True, BCG=True, label=r'$\log\,(M_h/M_{\odot})>14.2$, cModel') ax.set_xlabel(mstar_label()) ax.set_ylabel(phi_label()) #ax.set_xlim(11.4, 12.3) ax.grid() ax.legend(loc='upper right', ncol=1, fontsize=18) if png: plt.savefig(png) qa_smf_huang18() ``` ### Richness vs redshift for the full sample ``` legacyhalos_dir = os.getenv('LEGACYHALOS_DIR') parentfile = os.path.join(legacyhalos_dir, 'legacyhalos-parent.fits') rm = Table(fits.getdata(parentfile, extname='REDMAPPER')) def lambda2mhalo(richness, redshift=0.3, Saro=False): """ Convert cluster richness, lambda, to halo mass, given various calibrations. * Saro et al. 2015: Equation (7) and Table 2 gives M(500). * Melchior et al. 2017: Equation (51) and Table 4 gives M(200). * Simet et al. 2017: Other SDSS-based calibrations: Li et al. 2016; Miyatake et al. 2016; Farahi et al. 2016; Baxter et al. 2016. TODO: Return the variance! """ if Saro: pass # Melchior et al. 2017 (default) logM0, Flam, Gz, lam0, z0 = 14.371, 1.12, 0.18, 30.0, 0.5 Mhalo = 10**logM0 * (richness / lam0)**Flam * ( (1 + redshift) / (1 + z0) )**Gz return Mhalo def qa_legacyhalos_sample(png=None): fig, ax = plt.subplots(figsize=(8, 6)) hb = ax.hexbin(rm['Z'], np.log10(rm['LAMBDA_CHISQ']), mincnt=3, cmap=plt.cm.get_cmap('RdYlBu'), alpha=0.5, bins='log') ax.set_xlabel('Redshift $z$') ax.set_ylabel(r'$\log_{10}$ (Richness $\lambda$)') ax.set_xlim(0, 0.6) ymin, ymax = np.log10(3), 2.1 ax.set_ylim(ymin, ymax) ax.axhline(y=np.log10(5), ls='--', color='k') cax = fig.add_axes([0.1, 1.05, 0.8, 0.05]) cb = plt.colorbar(hb, orientation='horizontal', cax=cax) cb.set_label(r'$\log_{10}$ (Number of Galaxies)') ax2 = ax.twinx() ax2.set_ylabel(r'$\log_{10}\, (\mathcal{M}_{200}\, /\, \mathcal{M}_{\odot})$ at $z=0.3$') ax2.set_ylim( np.log10(lambda2mhalo(10**ymin, redshift=0.3)), np.log10(lambda2mhalo(10**ymax, redshift=0.3)) ) ax2.yaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax2.plot([],[]) if png: plt.savefig(png, bbox_inches='tight') qa_legacyhalos_sample(png=os.path.join(talkdir, 'legacyhalos-sample.png')) stop ``` ### SMHM relation ``` cat = legacyhalos.io.read_catalog(extname='LSPHOT-ISEDFIT', upenn=False, isedfit=True, columns=('mstar_avg', 'sfr100_avg')) cat1 = legacyhalos.io.read_catalog(extname='REDMAPPER', upenn=False, isedfit=False, columns=('Z', 'LAMBDA_CHISQ')) cat.add_columns_from(cat1) cat mhalo = np.log10(lambda2mhalo(cat.lambda_chisq, redshift=cat.z)) mhalo bins = 35 mstar_med, bin_edges, _ = binned_statistic(mhalo, cat.mstar_avg, statistic='median', bins=bins) bin_width = (bin_edges[1] - bin_edges[0]) mhalo_med = bin_edges[1:] - bin_width/2 print(bin_width) def p75(x): return np.percentile(x, 75) def p25(x): return np.percentile(x, 25) mstar_p25, _, _ = binned_statistic(mhalo, cat.mstar_avg, statistic=p25, bins=bins) mstar_p75, _, _ = binned_statistic(mhalo, cat.mstar_avg, statistic=p75, bins=bins) krav = dict() krav['m500'] = np.log10(np.array([15.6,10.3,7,5.34,2.35,1.86,1.34,0.46,0.47])*1e14) krav['mbcg'] = np.array([3.12,4.14,3.06,1.47,0.79,1.26,1.09,0.91,1.38])*1e12 krav['mbcg_err'] = np.array([0.36,0.3,0.3,0.13,0.05,0.11,0.06,0.05,0.14])*1e12 krav['mbcg_err'] = krav['mbcg_err'] / krav['mbcg'] / np.log(10) krav['mbcg'] = np.log10(krav['mbcg']) gonz = dict() gonz['mbcg'] = np.array([0.84,0.87,0.33,0.57,0.85,0.60,0.86,0.93,0.71,0.81,0.70,0.57])*1e12*2.65 gonz['mbcg_err'] = np.array([0.03,0.09,0.01,0.01,0.14,0.03,0.03,0.05,0.07,0.12,0.02,0.01])*1e12*2.65 gonz['m500'] = np.array([2.26,5.15,0.95,3.46,3.59,0.99,0.95,3.23,2.26,2.41,2.37,1.45])*1e14 gonz['m500_err'] = np.array([0.19,0.42,0.1,0.32,0.28,0.11,0.1,0.19,0.23,0.18,0.24,0.21])*1e14 gonz['mbcg_err'] = gonz['mbcg_err'] / gonz['mbcg'] / np.log(10) gonz['mbcg'] = np.log10(gonz['mbcg']) gonz['m500'] = np.log10(gonz['m500']) fig, ax = plt.subplots(figsize=(8, 6)) colors = iter(sns.color_palette()) rich = cat.lambda_chisq > 100 ax.plot(mhalo_med, mstar_med, color='k', ls='-', lw=3, alpha=0.5) ax.plot(mhalo_med, mstar_p75, color='k', ls='--', lw=3, alpha=0.5) ax.plot(mhalo_med, mstar_p25, color='k', ls='--', lw=3, alpha=0.5) g = ax.errorbar(gonz['m500'], gonz['mbcg'], yerr=gonz['mbcg_err'], color=next(colors), fmt='o', label='Gonzalez+13', markersize=10) k = ax.errorbar(krav['m500'], krav['mbcg'], yerr=krav['mbcg_err'], color=next(colors), fmt='s', label='Kravtsov+14', markersize=10) r = ax.scatter(mhalo[rich], cat.mstar_avg[rich], alpha=0.9, color=next(colors), edgecolor='k', marker='D', s=50, label=r'redMaPPer ($\lambda>100$)') ax.text(0.12, 0.16, 'redMaPPer\n$0.1<z<0.3$', multialignment='center', transform=ax.transAxes, fontsize=14) m500 = np.linspace(13.55, 15.25, 50) ff = ax.plot(m500, np.polyval([0.33, 12.24], m500-14.5), ls='-', color='k', label=r'$M_{*}\propto M_{500}^{0.33}$') ax.text(0.12, 0.9, r'$M_{*}\propto M_{500}^{0.33}$', multialignment='center', transform=ax.transAxes, fontsize=16) ax.plot([13.55, 13.68], [12.8, 12.8], ls='-', color='k') # hack!!! #ax.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) ax.xaxis.set_major_locator(MultipleLocator(0.5)) hh = [g, k, r] ax.legend(hh, [H.get_label() for H in hh], loc='lower right', frameon=True, fontsize=16) #ax.legend(ff, ff.get_label(), loc='upper left', # frameon=True, fontsize=16) #ax.legend(loc='upper left', frameon=True, fontsize=16) ax.set_ylim(10.5, 13) ax.set_xlim(13.5, 15.3) ax.set_xlabel(r'$\log_{10}\, (M_{500}\ /\ M_{\odot})$') ax.set_ylabel(r'$\log_{10}\, (M_{*}\ /\ M_{\odot})$') ff stop cat legacyhalos_dir = os.getenv('LEGACYHALOS_DIR') parentfile = os.path.join(legacyhalos_dir, 'legacyhalos-parent-isedfit.fits') ls = Table(fits.getdata(parentfile, extname='LSPHOT-ISEDFIT')) ls _ = plt.hist(ls['MSTAR_AVG'], bins=100) _ = plt.hist(sdss['MSTAR_AVG'], bins=100) _ = plt.hist(sdss['MSTAR_AVG'] - ls['MSTAR_AVG'], bins=200) plt.xlim(-0.5, 0.5) sdss = Table(fits.getdata(parentfile, extname='SDSSPHOT-ISEDFIT')) sdss data = np.vstack( (ls['MSTAR_AVG'], sdss['MSTAR_AVG'] - ls['MSTAR_AVG'])) data.shape k = kde.gaussian_kde(data.T) #xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j] #zi = k(np.vstack([xi.flatten(), yi.flatten()])) fig, ax = plt.subplots() ax.hexbin(ls['MSTAR_AVG'], sdss['MSTAR_AVG'] - ls['MSTAR_AVG'], mincnt=1) sns.jointplot(ls['MSTAR_AVG'], sdss['MSTAR_AVG'] - ls['MSTAR_AVG'], kind="kde", color="#4CB391", xlim=(10, 13), ylim=(-0.5, 0.5)) sns.kdeplot(ls['MSTAR_AVG'], sdss['MSTAR_AVG'] - ls['MSTAR_AVG'], cmap="Blues", shade=True, shade_lowest=True, cbar=True, cut=0, ) help(sns.kdeplot) ```
github_jupyter
``` from cryptography.hazmat.primitives.ciphers.algorithms import AES from cryptography.hazmat.primitives.ciphers import modes, Cipher from cryptography.hazmat.backends import default_backend from os import urandom import sys BLOCKSIZE = 16 def xor(x, y): # assert len(x) == len(y) a = int.from_bytes(x, "big") b = int.from_bytes(y, "big") r = a ^ b return r.to_bytes(len(x), "big") def unpad(m): pad = m[-1] assert 1 <= pad <= 16, "Wrong padding" for i in range(1, pad + 1): assert m[-i] == pad, "Wrong padding" return m[:-pad].decode("utf-8") def pad(pt): pad_size = len(pt) % BLOCKSIZE if pad_size != 0: pad = [pad_size for i in range(pad_size)] pt += bytes(pad) else: pad = [BLOCKSIZE for i in range(BLOCKSIZE)] pt += bytes(pad) #assert len(pt) % BLOCKSIZE == 0 def AES_DECRYPT(key): cipher = Cipher(AES(key), modes.ECB(), backend=default_backend()) return cipher.decryptor().update def AES_ENCRYPT(key): cipher = Cipher(AES(key), modes.ECB(), backend=default_backend()) return cipher.encryptor().update def encrypt_cbc(pt_string, k_string, blocksize=16): pt, k = bytearray(pt_string, 'utf-8'), bytes.fromhex(k_string) pad(pt) n = len(pt) // BLOCKSIZE current = urandom(BLOCKSIZE) #IV aes_encrypt = AES_ENCRYPT(k) ct = bytearray(current) for i in range(n): start, end = i*blocksize, (i+1)*blocksize m = pt[start:end] d = xor(m, current) current = aes_encrypt(d) ct += current return ct.hex() def decrypt_cbc(ct_string, k_string): ct, k = bytes.fromhex(ct_string), bytes.fromhex(k_string) # assert len(ct) % BLOCKSIZE == 0 n = len(ct) // BLOCKSIZE aes_decrypt = AES_DECRYPT(k) m = bytearray() for i in range(n-1): start, mid, end = i*BLOCKSIZE, (i+1)*BLOCKSIZE, (i+2)*BLOCKSIZE cx, cy = ct[start:mid], ct[mid:end] d = aes_decrypt(cy) m += xor(cx, d) return unpad(m) k = "140b41b22a29beb4061bda66b6747e14" ct1 = "4ca00ff4c898d61e1edbf1800618fb2828a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81" ct2 = "5b68629feb8606f9a6667670b75b38a5b4832d0f26e1ab7da33249de7d4afc48e713ac646ace36e872ad5fb8a512428a6e21364b0c374df45503473c5242a253" pt1 = "Basic CBC mode encryption needs padding." pt2 = "Our implementation uses rand. IV" m1 = decrypt_cbc(ct1, k) m2 = decrypt_cbc(ct2, k) print(m1) print(m2) c1 = encrypt_cbc(pt1, k) c2 = encrypt_cbc(pt2, k) cx = encrypt_cbc(m1, k) cy = encrypt_cbc(m2, k) print(decrypt_cbc(c1, k)) print(decrypt_cbc(cy, k)) assert m1==pt1 assert m2==pt2 assert decrypt_cbc(c1, k)==decrypt_cbc(cx, k) assert decrypt_cbc(c2, k)==decrypt_cbc(cy, k) ```
github_jupyter
# 1.1 例子:多项式拟合 假设我们有两个实值变量 $x, t$,满足关系: $$t = sin(2\pi x) + \epsilon$$ 其中 $\epsilon$ 是一个服从高斯分布的随机值。 假设我们有 `N` 组 $(x, t)$ 的观测值 $\mathsf x \equiv (x_1, \dots, x_N)^\top, \mathsf t \equiv (t_1, \dots, t_N)^\top$: ``` import numpy as np import scipy as sp import matplotlib.pyplot as plt %matplotlib inline # 设置 n N = 10 # 生成 0,1 之间等距的 N 个 数 x_tr = np.linspace(0, 1, N) # 计算 t t_tr = np.sin(2 * np.pi * x_tr) + 0.25 * np.random.randn(N) # 绘图 xx = np.linspace(0, 1, 500) fig, ax = plt.subplots() ax.plot(x_tr, t_tr, 'co') ax.plot(xx, np.sin(2 * np.pi * xx), 'g') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-1.5, 1.5) ax.set_xticks([0, 1]) ax.set_yticks([-1, 0, 1]) ax.set_xlabel("$x$", fontsize="x-large") ax.set_ylabel("$t$", fontsize="x-large") plt.show() ``` 使用这 $N$ 个数据点作为训练集,我们希望得到这个一个模型:给定一个新的输入 $\hat x$,预测他对应的输出 $\hat t$。 我们使用曲线拟合的方法来解决这个问题。 具体来说,我们来拟合这样一个多项式函数: $$ y(x,\mathbf w)=w_0+w_1 x + w_2 x^2 + \cdots + w_M x^M = \sum_{j=0}^M w_j x^j $$ 其中 $M$ 是多项式的阶数,$x^j$ 表示 $x$ 的 $j$ 次方,$\mathbf w \equiv (w_0, w_1, \dots, w_M)$ 表示多项式的系数。 这些多项式的系数可以通过我们的数据拟合得到,即在训练集上最小化一个关于 $y(x,\mathbf w)$ 和 $t$ 的损失函数。常见的一个损失函数是平方误差和,定义为: $$ E(\mathbf w)=\frac{1}{2} \sum_{i=1}^N \left\{y(x, \mathbf w) - t_n\right\}^2 $$ 因子 $\frac{1}{2}$ 是为了之后的计算方便加上的。 这个损失函数是非负的,当且仅当函数 $y(x, \mathbf w)$ 通过所有的数据点时才会为零。 对于这个损失函数,因为它是一个关于 $\mathbf w$ 的二次函数,其关于 $\mathbf w$ 的梯度是一个关于 $\mathbf w$ 的线性函数,因此我们可以找到一个唯一解 $\mathbf w^\star$。 $$ \frac{\partial E(\mathbf w)}{w_j} = \sum_{n=1}^N \left(\sum_{j=0}^M w_j x_n^j - t_n\right) x_n^j = 0 $$ 另一个需要考虑的拟合参数是多项式的阶数 $M$,我们可以看看当 $M = 0,1,3,9$ 时的效果(红线)。 可以看到,$M=3$ 似乎是其中较好的一个选择,$M=9$ 虽然拟合的效果最好(通过了所有的训练数据点),但很明显过拟合了。 ``` fig, axes = plt.subplots(2, 2, figsize=(12, 8)) axes = axes.flatten() Ms = [0, 1, 3, 9] for ax, M in zip(axes, Ms): # 计算参数 coeff = np.polyfit(x_tr, t_tr, M) # 生成函数 y(x, w) f = np.poly1d(coeff) # 绘图 xx = np.linspace(0, 1, 500) ax.plot(x_tr, t_tr, 'co') ax.plot(xx, np.sin(2 * np.pi * xx), 'g') ax.plot(xx, f(xx), 'r') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-1.5, 1.5) ax.set_xticks([0, 1]) ax.set_yticks([-1, 0, 1]) ax.set_xlabel("$x$",fontsize="x-large") ax.set_ylabel("$t$",fontsize="x-large") ax.text(0.6, 1, '$M={}$'.format(M), fontsize="x-large") plt.show() ``` 通常我们为了检测模型的效果,会找到一组与训练集相同分布的数据进行测试,然后计算不同模型选择下,训练集和测试集上的 $E(\mathbf w^\star)$ 值。 注意到随着测试点数目的变化,$E(\mathbf w^\star)$ 的尺度也在不断变化,因此一个更好的选择是使用 `root-mean-square (RMS)` 误差: $$ E_{RMS}=\sqrt{2E(\mathbf w^star) / N} $$ `RMS` 误差的衡量尺度和单位与目标值 $t$ 一致。 我们用相同的方法产生100组数据作为测试集,计算不同 $M$ 下的 `RMS` 误差:| ``` x_te = np.random.rand(100) t_te = np.sin(2 * np.pi * x_te) + 0.25 * np.random.randn(100) rms_tr, rms_te = [], [] for M in xrange(10): # 计算参数 coeff = np.polyfit(x_tr, t_tr, M) # 生成函数 y(x, w) f = np.poly1d(coeff) # RMS rms_tr.append(np.sqrt(((f(x_tr) - t_tr) ** 2).sum() / x_tr.shape[0])) rms_te.append(np.sqrt(((f(x_te) - t_te) ** 2).sum() / x_te.shape[0])) # 画图 fig, ax = plt.subplots() ax.plot(range(10), rms_tr, 'bo-', range(10), rms_te, 'ro-') ax.set_xlim(-1, 10) ax.set_ylim(0, 1) ax.set_xticks(xrange(0, 10, 3)) ax.set_yticks([0, 0.5, 1]) ax.set_xlabel("$M$",fontsize="x-large") ax.set_ylabel("$E_{RMS}$",fontsize="x-large") ax.legend(['Traning', 'Test'], loc="best") plt.show() ``` 可以看到 $M = 9$ 时,虽然训练集上的误差已经降到 `0`,但是测试集上的误差却很大。 我们来看看 $M = 9$ 时的多项式系数,为了更好的拟合这些点,系数都会变得很大: ``` for i, w in enumerate(np.polyfit(x_tr, t_tr, 9)): print "w_{}, {:.2f}".format(9 - i, w) ``` 另一个有趣的现象是查看当训练数据量 $N$ 变多时,$M = 9$ 的模型的表现: ``` fig, axes = plt.subplots(1, 2, figsize=(12, 4)) axes = axes.flatten() for ax, N in zip(axes, (15, 100)): # 生成 0,1 之间等距的 N 个 数 x_tr_more = np.linspace(0, 1, N) # 计算 t t_tr_more = np.sin(2 * np.pi * x_tr_more) + 0.25 * np.random.randn(N) # 计算参数 coeff = np.polyfit(x_tr_more, t_tr_more, M) # 生成函数 y(x, w) f = np.poly1d(coeff) # 绘图 xx = np.linspace(0, 1, 500) ax.plot(x_tr_more, t_tr_more, 'co') ax.plot(xx, np.sin(2 * np.pi * xx), 'g') ax.plot(xx, f(xx), 'r') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-1.5, 1.5) ax.set_xticks([0, 1]) ax.set_yticks([-1, 0, 1]) ax.set_xlabel("$x$", fontsize="x-large") ax.set_ylabel("$t$", fontsize="x-large") ax.text(0.6, 1, '$N={}$'.format(N), fontsize="x-large") plt.show() ``` 可以看到,随着 $N$ 的增大,模型拟合的过拟合现象在减少。 当模型的复杂度固定时,随着数据的增加,过拟合的现象也在逐渐减少。 回到之前的问题,如果我们一定要在 $N=10$ 的数据上使用 $M=9$ 的模型,那么一个通常的做法是给参数加一个正则项的约束防止过拟合,一个最常用的正则项是平方正则项,即控制所有参数的平方和大小: $$ \tilde E(\mathbf w) = \frac{1}{2}\sum_{i=1}^N \left\{y(x_n,\mathbf w) - t_n\right\}^2 + \frac{\lambda}{2} \|\mathbf w\|^2 $$ 其中 $\|\mathbf w\|^2 \equiv \mathbf{w^\top w} = w_0^2 + \dots | w_M^2$,$\lambda$ 是控制正则项和误差项的相对重要性。 若设向量 $\phi(x)$ 满足 $\phi_i(x) = x^i, i = 0,1,\dots,M$,则对 $\mathbf w$ 最小化,解应当满足: $$ \left[\sum_{n=1}^N \phi(x_n) \phi(x_n)^\top + \lambda \mathbf I\right] \mathbf w = \sum_{n=1}^N t_n \phi(x_n) $$ ``` def phi(x, M): return x[:,None] ** np.arange(M + 1) # 加正则项的解 M = 9 lam = 0.0001 phi_x_tr = phi(x_tr, M) S_0 = phi_x_tr.T.dot(phi_x_tr) + lam * np.eye(M+1) y_0 = t_tr.dot(phi_x_tr) coeff = np.linalg.solve(S_0, y_0)[::-1] f = np.poly1d(coeff) # 绘图 xx = np.linspace(0, 1, 500) fig, ax = plt.subplots() ax.plot(x_tr, t_tr, 'co') ax.plot(xx, np.sin(2 * np.pi * xx), 'g') ax.plot(xx, f(xx), 'r') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-1.5, 1.5) ax.set_xticks([0, 1]) ax.set_yticks([-1, 0, 1]) ax.set_xlabel("$x$", fontsize="x-large") ax.set_ylabel("$t$", fontsize="x-large") plt.show() ``` 通常情况下,如果我们需要决定我们系统的复杂度参数 ($\lambda, M$),一个常用的方法是从训练数据中拿出一小部分作为验证集,来测试我们的复杂度;不过这样会带来训练减少的问题。
github_jupyter
Deep Learning ============= Assignment 2 ------------ Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html). The goal of this assignment is to progressively train deeper and more accurate models using TensorFlow. ``` # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range ``` First reload the data we generated in `1_notmnist.ipynb`. ``` pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) train_dataset = save['train_dataset'] train_labels = save['train_labels'] valid_dataset = save['valid_dataset'] valid_labels = save['valid_labels'] test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) ``` Reformat into a shape that's more adapted to the models we're going to train: - data as a flat matrix, - labels as float 1-hot encodings. ``` image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) ``` We're first going to train a multinomial logistic regression using simple gradient descent. TensorFlow works like this: * First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description is all contained within the block below: with graph.as_default(): ... * Then you can run the operations on this graph as many times as you want by calling `session.run()`, providing it outputs to fetch from the graph that get returned. This runtime operation is all contained in the block below: with tf.Session(graph=graph) as session: ... Let's load all the data into TensorFlow and build the computation graph corresponding to our training: ``` # With gradient descent training, even this much data is prohibitive. # Subset the training data for faster turnaround. train_subset = 10000 graph = tf.Graph() with graph.as_default(): # Input data. # Load the training, validation and test data into constants that are # attached to the graph. tf_train_dataset = tf.constant(train_dataset[:train_subset, :]) tf_train_labels = tf.constant(train_labels[:train_subset]) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. # These are the parameters that we are going to be training. The weight # matrix will be initialized using random valued following a (truncated) # normal distribution. The biases get initialized to zero. weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation. # We multiply the inputs with the weight matrix, and add biases. We compute # the softmax and cross-entropy (it's one operation in TensorFlow, because # it's very common, and it can be optimized). We take the average of this # cross-entropy across all training examples: that's our loss. logits = tf.matmul(tf_train_dataset, weights) + biases loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) # Optimizer. # We are going to find the minimum of this loss using gradient descent. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. # These are not part of training, but merely here so that we can report # accuracy figures as we train. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf_valid_dataset, weights) + biases) test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) ``` Let's run this computation and iterate: ``` num_steps = 801 def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) with tf.Session(graph=graph) as session: # This is a one-time operation which ensures the parameters get initialized as # we described in the graph: random weights for the matrix, zeros for the # biases. tf.initialize_all_variables().run() print('Initialized') for step in range(num_steps): # Run the computations. We tell .run() that we want to run the optimizer, # and get the loss value and the training predictions returned as numpy # arrays. _, l, predictions = session.run([optimizer, loss, train_prediction]) if (step % 100 == 0): print('Loss at step %d: %f' % (step, l)) print('Training accuracy: %.1f%%' % accuracy(predictions, train_labels[:train_subset, :])) # Calling .eval() on valid_prediction is basically like calling run(), but # just to get that one numpy array. Note that it recomputes all its graph # dependencies. print('Validation accuracy: %.1f%%' % accuracy(valid_prediction.eval(), valid_labels)) print('Test accuracy: %.1f%%' % accuracy(test_prediction.eval(), test_labels)) ``` Let's now switch to stochastic gradient descent training instead, which is much faster. The graph will be similar, except that instead of holding all the training data into a constant node, we create a `Placeholder` node which will be fed actual data at every call of `sesion.run()`. ``` batch_size = 128 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights = tf.Variable( tf.truncated_normal([image_size * image_size, num_labels])) biases = tf.Variable(tf.zeros([num_labels])) # Training computation. logits = tf.matmul(tf_train_dataset, weights) + biases loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) valid_prediction = tf.nn.softmax( tf.matmul(tf_valid_dataset, weights) + biases) test_prediction = tf.nn.softmax(tf.matmul(tf_test_dataset, weights) + biases) ``` Let's run it: ``` num_steps = 3001 with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = (step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run( [optimizer, loss, train_prediction], feed_dict=feed_dict) if (step % 500 == 0): print("Minibatch loss at step %d: %f" % (step, l)) print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) print("Validation accuracy: %.1f%%" % accuracy( valid_prediction.eval(), valid_labels)) print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) ``` --- Problem ------- Turn the logistic regression example with SGD into a 1-hidden layer neural network with rectified linear units (nn.relu()) and 1024 hidden nodes. This model should improve your validation / test accuracy. --- ``` batch_size = 128 num_hidden_nodes = 1024 graph = tf.Graph() with graph.as_default(): # Input data. For the training data, we use a placeholder that will be fed # at run time with a training minibatch. tf_train_dataset = tf.placeholder(tf.float32, shape=(batch_size, image_size * image_size)) tf_train_labels = tf.placeholder(tf.float32, shape=(batch_size, num_labels)) tf_valid_dataset = tf.constant(valid_dataset) tf_test_dataset = tf.constant(test_dataset) # Variables. weights1 = tf.Variable( tf.truncated_normal([image_size * image_size, num_hidden_nodes])) biases1 = tf.Variable(tf.zeros([num_hidden_nodes])) weights2 = tf.Variable( tf.truncated_normal([num_hidden_nodes, num_labels])) biases2 = tf.Variable(tf.zeros([num_labels])) # Training computation. lay1_train = tf.nn.relu(tf.matmul(tf_train_dataset, weights1) + biases1) logits = tf.matmul(lay1_train, weights2) + biases2 loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits, tf_train_labels)) # Optimizer. optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss) # Predictions for the training, validation, and test data. train_prediction = tf.nn.softmax(logits) lay1_valid = tf.nn.relu(tf.matmul(tf_valid_dataset, weights1) + biases1) valid_prediction = tf.nn.softmax(tf.matmul(lay1_valid, weights2) + biases2) lay1_test = tf.nn.relu(tf.matmul(tf_test_dataset, weights1) + biases1) test_prediction = tf.nn.softmax(tf.matmul(lay1_test, weights2) + biases2) num_steps = 3001 with tf.Session(graph=graph) as session: tf.initialize_all_variables().run() print("Initialized") for step in range(num_steps): # Pick an offset within the training data, which has been randomized. # Note: we could use better randomization across epochs. offset = (step * batch_size) % (train_labels.shape[0] - batch_size) # Generate a minibatch. batch_data = train_dataset[offset:(offset + batch_size), :] batch_labels = train_labels[offset:(offset + batch_size), :] # Prepare a dictionary telling the session where to feed the minibatch. # The key of the dictionary is the placeholder node of the graph to be fed, # and the value is the numpy array to feed to it. feed_dict = {tf_train_dataset : batch_data, tf_train_labels : batch_labels} _, l, predictions = session.run( [optimizer, loss, train_prediction], feed_dict=feed_dict) if (step % 500 == 0): print("Minibatch loss at step %d: %f" % (step, l)) print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels)) print("Validation accuracy: %.1f%%" % accuracy( valid_prediction.eval(), valid_labels)) print("Test accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels)) ```
github_jupyter
# An Introduction to the Go Language Go was designed at Google in 2007 to improve programming productivity in an era of multicore, networked machines and large codebases. The designers wanted to address criticism of other languages in use at Google, but keep their useful characteristics: * Static typing and run-time efficiency (like C++) * Readability and usability (like Python or JavaScript) * High-performance networking and multiprocessing The designers were primarily motivated by their shared dislike of C++. [Wikipedia: Go Programming Language](https://en.wikipedia.org/wiki/Go_(programming_language)) ## A Quick Tour This brief introduction will explain the various elements that make up the Go language. ## File Menu You may have started this notebook by selecting it from the table of contents, but if you use standard Jupyter notebooks, then you would be presented with a similar file menu. ![File menu]( ./media/Jupyter_Files.jpg "Jupyter File Menu") To start using a notebook, all you need to do is click on its name. So for this notebook, you would have selected _An Introduction to Jupyter Notebooks_. If you want to manage the notebooks (i.e. delete them or place them into a folder, you can select them on the left hand side, and then execute the action from the pull down list (the arrow just below the Running tab). The Running tab shows you which notebooks are currently active or running. Each notebook is independent from the others. This means that there is no sharing of data or variables between each notebook because they are running on different threads. When you shut down a notebook, you are stopping its process or thread in the system. If you need to upload a new notebook (or replace an existing one), you can use the Upload button on the far right hand side. This will give you a file menu on your local system where you can select a notebook to upload. Jupyter notebooks have the extension .ipynb (IPython Notebook) which contains all of the notebook information in a JSON format. If you want to create a brand new notebook, you would select the New button that is beside the Upload button. The New button may ask what type of Notebook that you want. It could by Python 2 or 3, or even a different language based notebook (Scala for instance). This image only has Python 3 installed so that will be your only choice when creating a notebook. ## The Tool Bar At the top of this page you should see the following toolbar. ![Jupyter Tool Bar]( ./media/Jupyter_Toolbar.jpg "Jupyter Toolbar") The tool bar is found at the top of your Jupyter Notebook. There are three sections that you need to be familiar with. * Title (An Introduction...) * File/Edit/View... Menu * Save/Add Cell/... Icons ### Title The top of the notebook has the title of the contents. The name of the notebook can be changed by clicking on the title. This will open up a dialog which gives you the option of changing the name of the notebook. ![Change Title]( ./media/Change_Title.jpg "Change the Title") Note that this will create a new copy of the notebook with this name. One important behavior of Jupyter notebooks is that notebooks "autosave" the contents every few minutes (you know how much we hate losing work in the event of a crash). Changing the name of the title will make sure any changes get saved under the new name. However, changes will probably have been saved to the old name up to this point because of autosave. For that reason, it is better to make a new copy of the notebook before starting to edit it. ### File/Edit/View Menu The menu bar contains options to `File`, `Edit`, `View` and perform other administrative actions within the Jupyter notebook. The `File` option gives you options to save the file as a checkpoint (a version that you can revert to), make a copy of the notebook, rename it, or download it. Of particular interest is the `Copy` command. This will make a copy of the existing notebook and start that up in a separate tab in the browser. You can then view and edit this copy rather than changing the original. The other option is to checkpoint your progress at regular intervals and then use the `Revert to Checkpoint` to restore the notebook to a previous version. The `Download` option is also very important to be familiar with. The notebook lives within your Jupyter environment so you may not know what the full file path is to access it. Use this option to download the file to your local operating system for safe keeping. <p> ![File Menu]( ./media/Menus.jpg "File Menu") The seven additional menu items are: * **Edit** - These menu items are used for editing the cells. The icons below the menus are equivalent to most of these menus. * **View** - View will turn on Header information, Line numbers, Tool bars and additional Cell information * **Insert** - Insert new cells above or below the current cell * **Cell** - This menu item lets you run code in a cell, run all cells, remove output from the cells or change the cell type * **Kernel** - The kernel that is running the current notebook can be restarted or stopped if there appears to be a problem with it * **Widgets** - Widgets are add-ons for Jupyter notebooks. * **Help** - If you need help, check out this menu. Some important menu items that you may want to use: - **View/Toggle Line Numbers** should be turned on if you have a substantial amount of code. This makes it easier to find errors when Python generates an error message with a line number. Note that this only applies to code cells. - **Insert/Above** is useful if you don't want to move your cursor to the cell above before hitting the [+] icon. - **Cell/All Output/Clear** will get rid of any output that your notebook has produced so that you can start over again. - **Cell/Run All** is useful if you are lazy or just want to test your entire notebook at once! - **Kernel/Restart** & Clear Output should be used if the notebook appears to hang and you want to start from scratch again. ### Menu Bar Icons The icons below the menu bar are used to edit the cells within the notebook. ![Jupyter Tool Bar]( ./media/Jupyter_Toolbar.jpg "Jupyter Toolbar") The icons from left to right are: * **Save** - save the current notebook. Note: This is not a checkpoint save so you are saving a new copy. * **[+]** - Add a new cell below the current cell * **Cut** - Delete the current cell, but a copy is kept in the event you want to paste it somewhere else in the notebook * **Copy** - Copy the current cell * **Paste** - Paste a cell below the current cell * **Up** - Move the current cell up one * **Down** - Move the current cell down one * **[>|]** - Execute the current code in the cell, or render the markdown content * **Stop** - Stop any execution that is currently taking place * **Restart** - Restart the kernel (to clear out all previous variables, etc.) * **Cell Type** - Select the type of Cell: Code, Markdown, Raw, or Heading * **Command** - Show a list of commands When you create a new cell it will default to containing code, so if you want it to contain Markdown, you will need to select `Markdown` from the cell type list. The cut/copy/paste are similar to any other program with one exception. You can't use Ctrl-C and Ctrl-V to cut and paste cells. These shortcuts can be used for text, but not for an entire cell. Jupyter notebooks will issue a warning if you try to use these to manipulate cells. In addition, if you copy a cell in one notebook, it will not paste into a different notebook! You need to select the contents of the cell and then paste into the cell in the other notebook. ### Cell Contents A Jupyter notebook contains multiple "cells" which can contain one of three different types of objects: - **Code** - A cell that contains code that will run (usually Python) - **Markdown** - A cell that contains text and formatting using a language called Markdown - **Raw NBConvert** - A specialized cell that is rendered (displayed) using an extension, like mathematical formulas We are going to keep it simple and only look at the two most common types of cells: code and markdown. The first example below is a code cell. ``` print('Hello World') ``` You can tell that this is a code cell because of the **"`In [ ]:`"** beside the cell and probably because it has some code in the cell! To "execute" the contents of the cell, you must click on the cell (place focus on the cell) and the either hit the run button icon **`[>|]`** or `Shift-Return` (or `Enter`) on your keyboard. You can tell when the focus is on the code cell because it will be highlighted with a thin green box. Cells that contain text will be highlighted with a blue box. **Action:** Try executing the code in the cell above. If you were successful it should have printed "Hello World" below the cell. Any output, including errors, from a cell is placed immediately below the cell for you to view. If the code is running for an extended period of time, the notebook will display **`[*]`** until the statement completes. The contents of the code cell can contain anything that the Jupyter/IPython interpreter can execute. Usually this is Python code, magic extensions, or even Scala, Java, etc... as long as the proper extensions have been added to the notebook. ## Summary In summary, you've learned how to start, create, update and edit Jupyter notebooks. Jupyter notebooks are used extensively by the data science community, but it is finding its way into many other areas as well. If you are interested in what other applications use Jupyter notebooks, take a look at the list maintained on this web site: https://github.com/jupyter/jupyter/wiki/A-gallery-of-interesting-Jupyter-Notebooks. #### Credits: IBM 2019, George Baklarz [baklarz@ca.ibm.com]
github_jupyter
# <span style='color:Blue'>Temple University, Physical Chemistry for Biomolecules (CHEM3405) Homeworks</span> ### Teaching Assistant: Rob Raddi <script src="custom/gtag.js" type="text/javascript"></script> <script> gtag(); </script> <style> @import url("./custom/gtag.js"); </style> <style> @import url("./custom/custom.css"); </style> #### Textbook: Peter Atkins, Julio de Paula - Physical Chemistry for the Life Sciences #### <span style='color:black'>Table of Contents:</span> | HW # | Topic | Chapter | | :--- | :--- | :--: | | [1.](#1.) | quantization | 9 | | [2.](#2.) | - | 9 | | [3.](#3.) | - | 9 | | [4.](#4.) | - | 10,11 | | [5.](#5.) | - | 11 | | [6.](#6.) | - | 12 | | [7.](#7.) | - | 12 | <!-- HW1: Chapter 9: 11, 13, 14, 17, 18 HW2: Chapter 9: 19, 21, 22, 23, 32, 33 HW3: Chapter #9: 27, 35, 36, 41, 42 Chapter #10: 14 HW4: Chapter #10: 19, 23, 26 Chapter #11: 4 HW5: Chapter 11: #9, 27, 35, 36, 38, 44 ----- HW7: Chap 12: #10, 11, 12, 14, 19 HW8: Chapter 12: #25, 37*, 39, 40** Chapter 11: #1, 2, 17 (Hint: see equation on p. 408), 20, 22, 25 HW9: Chapter 1: #1, 12, 13, 18, 19, 24, 27, 31, 33 HW10: Chapter 1: #39, 42Chapter 2: #7, 8, 10, 12, 16, 18, 23 HW12: Chapter 4: #9, 10, 12, 14, 15, 28, 30 HW13: Chapter 4: #,38, 42Chapter 6: #4, 6, 9, 14 --> <!-- <img src='' width="300" height="300" align="center" > --> **1. To what speed must a proton be accelerated for it to have a wavelength of 3.0 cm?** Keywords: **proton**, **wavelength**, **speed** In 1923 de Broglie says that matter has wave-like properties: $$ \lambda = \frac{h}{p}, $$ where $h$ is Plancks constant ($6.626x10^{-34} Js$). From classical mechanics we know linear momentum is the product of mass and velocity ($ p = mv $). Then, we solve for velocity: $$ v = \frac{h}{\lambda\space m_{proton}} = 1.3 x 10^{-5} \text{m }s^{-1}$$ **2. Calculate the energy per mole of photons for radiation of wavelength (a) 200 nm (ultraviolet), (b) 150 pm (X-ray), (c) 1.00 cm (microwave).** In 1900 Bohr and Planck determined that energy is quantized (discrete energy levels). $$ E = nh\nu, $$ where $c = \lambda \nu$ and $n$ is the number of photons ($6.022x10^{23} photons/mole$). Then, $$ E = nh \frac{c}{\lambda}$$ Therefore, $E =$ (a) $5.97x10^{5} J$, (a) $7.95x10^{8} J$, (a) $11.6 J$ **3. The work function for metallic rubidium is 2.09 eV. Calculate the kinetic energy and the speed of the electrons ejected by light of wavelength (a) 650 nm, (b) 195 nm.** Einstein published the a paper on the *photoelectric effect* in 1905 (won Nobel Prize in 1921). The main idea is conservation of energy: $$E_{total} = V + E_{k} $$ Here, $V = \phi \equiv \text{Work Function}$, $E_{total} = h\nu$ and $ E_{k} = \frac{1}{2}mv^{2}$. The work function, $\phi$ is defined as the amount of energy required to eject an electron, which is also known as ionization energy. $$h\nu = \phi + \frac{1}{2}m_{e}v^{2},$$ where $m_{e}$ is the mass of an electron ($9.11*10^{-31} kg$). <img title="upload.wikimedia.org" src='https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Photoelectric_effect.svg/1200px-Photoelectric_effect.svg.png' width="250" height="250" align="center" > To calculate kinetic energy, we rearrange for $E_{k}$ to obtain $$E_{k} = \frac{1}{2}m_{e}v^{2} = \phi - h\nu $$ Solving for velocity gives: $$ v = \sqrt{\frac{2}{m_{e}}(\frac{hc}{\lambda} - \phi)} = \sqrt{\frac{2}{m_{e}}E_{k}}$$ Therefore, For $\lambda = 650 nm$, $E_{k} = -3.00 x 10^{-20} J$, which means the amount of energy is insufficient to eject the electron and $v = 0 m/s$. **Side notes:** - Ionization energy and electron affinity increase as your go $\uparrow$ and $\rightarrow$ - Ionization energies are always positive values. #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>1.</span> **9.11 Calculate the size of the quantum involved in the excitation of (a) an electronic motion of frequency 1.0 × 1015 Hz, (b) a molecular vibration of period 20 fs, and (c) a pendulum of period 0.50 s. Express the results in joules and in kilojoules per mole.** **9.13 Calculate the de Broglie wave length of (a) a mass of 1.0g traveling at $1.0 m\space s^{−1}$, (b) the same, traveling at $1.00 × 105 km \space s^{−1}$, (c) an He atom traveling at $1000 m\space s^{−1}$ (a typical speed at room temperature), (d) yourself traveling at $8 km h^{−1}$, and (e) yourself at rest.** **9.14 Calculate the linear momentum per photon, energy per photon, and the energy per mole of photons for radiation of wavelength (a) 600 nm (red), (b) 550 nm (yellow), (c) 400 nm (violet), (d) 200 nm (ultraviolet), (e) 150 pm (X-ray), and (f ) 1.0 cm (microwave).** **9.17 The speed of a certain proton is $350 km \space s^{−1}$. If the uncertainty in its momentum is 0.0100 per cent, what uncertainty in its location must be tolerated?** **9.18 An electron is confined to a linear region with a length of the same order as the diameter of an atom (about 100 pm). Calculate the minimum uncertainties in its position and speed.** In 1927 Werner Heisenberg devised one of the postulates of quantum mechanics called *Heisenberg's Uncertainty Principle*. This postulate states that complementary observables cannot be measured with absolute certainty i.e., if the position of a particle is certain, then its momentum is uncertain and visa-versa. $$\Delta x \Delta p \underline{>} \frac{h}{4\pi} $$ We can say that the minimum uncertainty in position is 100 pm, which is $1.0 x 10^{-10} m$. Now, we need to find the minimum uncertainty in speed. Substituting for $\Delta p = m_{e} \Delta v$ ($m_{e} = 9.11x10^{-31}kg$) into the inequality above gives $$ \Delta p = m_{e} \Delta v \underline{>} \frac{h}{4\pi \Delta x } \implies \Delta v \underline{>} \frac{h}{4\pi \Delta x \space m_{e}}$$ Therefore, $$\Delta v \underline{>} 5.78x10^{5} m/s$$ #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>2.</span> **9.19 Calculate the probability that an electron will be found (a) between x = 0.1 and 0.2 nm, and (b) between 4.9 and 5.2 nm in a box of length L = 10 nm when its wavefunction is $y = (2/L)^{1/2} sin(2px/L)$. Hint: Treat the wavefunction as a constant in the small region of interest and interpret dV as dx.** Integration has already been done from $0$ to $L$ giving $N = \sqrt{2/L}$. $$\psi = \sqrt{2/L}sin(2\pi x/L)$$ $$P(x) = | \psi | ^{2}\delta x = | \psi^{*}\psi |\delta x = \frac{2}{L}sin^{2}(2\pi x/L)\delta x,$$ where $\delta x$ is the region we are interested in. The problem told us that $x\in [0.1,0.2]$nm. If the length of the box is 10 nm, then by intuition the probability should be very small. $$P(x) = \frac{2}{L}sin^{2}(2\pi x/L)\delta x = \frac{2}{L}sin^{2}(2\pi x/L)(x_2 - x_1),$$ where x = 1.5 (half way between the bounds) and $x_2 = 0.2, x_1 = 0.1$. Therefore, $$ (a) P = 1.77x10^{-4}$$ $$ (b) P = 5.92x10^{-5}$$ It turns out that 9.20 (the next problem) addresses this **approximation** and shows a discrepancy between answers when integration over the limits $[0.1,0.2]$ and using the **approximation**. The integration method should give $1.84x10^{-4}$ **9.21 What is the probability of finding a particle of mass m in (a) the left-hand one-third, (b) the central one-third, and (c) the right-hand one-third of a box of length L when it is in the state with n = 1?** $$P = \int_{}^{} \psi^{2} dx,$$ where$\psi = \sqrt{\frac{2}{L}}sin(\frac{\pi x}{L})$ $$P=\int_{x_{1}}^{x_{2}}\left\{\left(\frac{2}{L}\right)^{1 / 2} \sin \left(\frac{\pi x}{L}\right)\right\}^{2} \mathrm{d} x=\left(\frac{2}{L}\right) \int_{x_{1}}^{x_{2}} \sin ^{2}\left(\frac{\pi x}{L}\right) \mathrm{d} x,$$ where we use the standard integral from the table of integrals: $\int sin^{2}(ax)dx = \frac{x}{2}-\frac{sin(2ax)}{4a}$ $$P=\left(\frac{2}{L}\right)\left[\frac{x}{2}-\frac{\sin \left(2\left(\frac{\pi}{L}\right) x\right)}{4\left(\frac{\pi}{L}\right)}\right]_{x_{0}}^{x_{2}}=\left[\frac{x}{L}-\frac{1}{2 \pi} \sin \left(\frac{2 \pi x}{L}\right)\right]_{x_{1}}^{x_{1}}$$ $$P = \left[\frac{x}{L}-\frac{1}{2 \pi} \sin \left(\frac{2 \pi x}{L}\right)\right]_{x_{1}}^{x_{1}} $$ $$(a) \space\space P = \left[x-\frac{1}{2 \pi} \sin \left(2 \pi x \right)\right]_{0}^{1/3} = 0.196$$ $$(b) \space\space P = \left[x-\frac{1}{2 \pi} \sin \left(2 \pi x \right)\right]_{1/3}^{2/3} = 0.609$$ $$(c) \space\space P = \left[x-\frac{1}{2 \pi} \sin \left(2 \pi x \right)\right]_{2/3}^{1} = 0.196$$ **9.22 A certain wavefunction is zero everywhere except between x = 0 and x = L, where it has the constant value A. Normalize the wavefunction.** $$\int_{0}^{L}\psi^{2}dx = \int_{0}^{L}A^{2} dx = A^{2}\int_{0}^{L} dx = A^{2}x \Biggr|_{0}^{L} = A^{2}L = 1$$ $$ \therefore A= \sqrt{\frac{1}{L}} \implies \psi = \sqrt{\frac{1}{L}}$$ **9.23 The conjugated system of retinal consists of 11 carbon atoms and one oxygen atom. In the ground state of retinal, each level up to n = 6 is occupied by two electrons. Assuming an average internuclear distance of 140 pm, calculate (a) the separation in energy between the ground state and the first excited state in which one electron occupies the state with n = 7 and (b) the frequency of the radiation required to produce a transition between these two states.** The particle in a box energy levels are given by: $$E_{n} = \frac{h^{2}n^{2}}{8mL^{2}}, $$ where we need to find the difference in energy between $n=6$ and $n=7$. We also know that the length of the box is proportional to the number of carbon atoms in the conjugated chain. Hence, $$ L = \text{# carbon atoms}\space\text{length of C bond} = 11(140x10^{-12}m) = 1.54x10^{-9}m$$ $$\Delta E = \frac{h^{2}}{8mL^{2}} (7^{2} - 6^{2}) $$ (a) $$ \space\space \Delta E = 3.30x10^{-19}J$$ (b) $$ \nu = \frac{\Delta E}{h} = 4.95x10^{-14}s^{-1}$$ **9.32 The ground state wavefunction of a harmonic oscillator is proportional to $e^{−ax^{2}/2}$, where a depends on the mass and force constant. (a) Normalize this wavefunction. (b) At what displacement is the oscillator most likely to be found in its ground state? Hint: For part (a), you will need the integral $\int_{-\infty}^{\infty} e^{−ax^{2}} dx = (\pi/a)^{1/2}$. For part (b), recall that the maximum (or minimum) of a function f(x) occurs at the value of x for which df/dx = 0.** (a) $\psi = Ne^{-ax^{2}/2}, $ $-\infty < x < \infty$ $$ N^{2} \int_{-\infty}^{\infty} (e^{-ax^{2}/2})^{2}dx = 1$$ $$ N^{2} \int_{-\infty}^{\infty} e^{-ax^{2}/2} dx = 1$$ where we use the standard integral from the table of integrals: $\int_{-\infty}^{\infty} e^{-ax^{2}} dx = (\frac{\pi}{a})^{1/2}$ $$N^{2}(\frac{\pi}{a})^{1/2} = 1 \implies N = (\frac{a}{\pi})^{1/4}$$ $$ \therefore \psi = (\frac{a}{\pi})^{1/4}e^{-ax^{2}/2}$$. (b) $ \psi = (\frac{a}{\pi})^{1/4}e^{-ax^{2}/2}$ resembles a Gaussian function with a maximum at $x = 0$. We know that $\psi^{2}$ has a maximum value at $x=0$ and the Born interpretation of $\psi^{2}$ suggests that $x=0$ is the most probable displacement. When we take the partial derivative of $\psi$ with respect to $x$ we get $$\frac{\mathrm{d} \psi}{\mathrm{d} x}=\frac{\mathrm{d}}{\mathrm{d} x}\left\{\left(\frac{a}{\pi}\right)^{1 / 4} \mathrm{e}^{-\alpha x^{2} / 2}\right\}=\left(\frac{a}{\pi}\right)^{1 / 4} \frac{\mathrm{d}}{\mathrm{d} x} \mathrm{e}^{-\alpha x^{2} / 2}=-\left(\frac{a}{\pi}\right)^{1 / 4} a x \mathrm{e}^{-\alpha x^{2} / 2},$$ which indicates $\frac{\mathrm{d} \psi}{\mathrm{d} x}$ is positive when $x<0$ and negative when $x>0$. **9.33 The solutions of the Schrödinger equation for a harmonic oscillator also apply to diatomic molecules. The only complication is that both atoms joined by the bond move, so the ‘mass’ of the oscillator has to be interpreted carefully. Detailed calculation shows that for two atoms of masses $m_{A}$ and $m_{B}$ joined by a bond of force constant $k_{f}$, the energy levels are given by eqn 9.29, but the vibrational frequency is** $$ v = \frac{1}{2\pi}(\frac{k_{f}}{\mu})^{1/2},$$ where $$\mu = \frac{m_{A}m_{B}}{m_{A}+m_{B}}$$ **and m is called the effective mass of the molecule. Consider the vibration of carbon monoxide, a poison that prevents the transport and storage of O2 (see Exercise 9.48). The bond in a 12C16O molecule has a force constant of 1860 N m−1. (a) Calculate the vibrational frequency, n, of the molecule. (b) In infrared spectroscopy it is common to convert the vibrational frequency of a molecule to its vibrational wavenumber, 6, given by 6 = n/c. What is the vibrational wavenumber of a 12C16O molecule? (c) Assuming that isotopic substitution does not affect the force constant of the C≡O bond, calculate the vibrational wavenumbers of the following molecules: $^{12}C^{16}O, ^{13}C^{16}O, ^{12}C^{18}O, ^{13}C^{18}O$.** (a) $$\mu = \frac{m_{A}m_{B}}{m_{A}+m_{B}} = \frac{M_{A}M_{B}}{N_{A}(M_{A}+M_{B})} $$ $$\mu = \frac{(12.00)(16.00)x10^{-3} kg}{(6.022x10^{23} (28.00)} = 1.139x10^{-26} kg$$ $$ v = \frac{1}{2\pi}(\frac{1860 \space N\space m^{-1}}{1.139x10^{-26} kg})^{1/2} = 6.432x10^{13} s^{-1}$$ (b) $$\tilde{\nu} = \frac{1}{\lambda} = \frac{\nu}{c} = \frac{6.432x10^{13} s^{-1}}{c} = 2146 cm^{-1}$$ (c) Note that we will approximate by using the same force constants for each of the isotopic CO molecules, but will vary in their reduced mass. For $^{13}C^{16}O$: $$\mu = 1.191x10^{-26} kg \text{ and } \tilde{\nu} = 2099 \space cm^{-1}$$ For $^{12}C^{18}O$: $$\mu = 1.196x10^{-26} kg \text{ and } \tilde{\nu} = 2094 \space cm^{-1}$$ For $^{13}C^{18}O$: $$\mu = 1.253x10^{-26} kg \text{ and } \tilde{\nu} = 2046 \space cm^{-1}$$ #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>3.</span> <!-- HW3: Chapter #9: 27, 35, 36, 41, 42 Chapter #10: 14 --- pick one or two --> **9.27 The particle on a ring is a useful model for the motion of electrons around the porphine ring (4), the conjugated macrocycle that forms the structural basis of the heme group and the chlorophylls. We may treat the group as a circular ring of radius 440 pm, with 20 electrons in the conjugated system moving along the perimeter of the ring. As in Exercise 9.26, assume that in the ground state of the molecule quantized each level is occupied by two electrons. (a) Calculate the energy and angular momentum of an electron in the highest occupied level. (b) Calculate the frequency of radiation that can induce a transition between the highest occupied and lowest unoccupied levels.** <img src="https://upload.wikimedia.org/wikipedia/commons/5/5c/Porphyrin.svg" height="200" width="200" align="center"> The angular momentum states are defined by the quantum number $m_{l} = 0,\pm 1,\pm 2, etc.$ $$ E_{m_{l}} = \frac{{m_{l}}^{2}\hbar^{2}}{2I},$$ where the angular momentum is $I_{z} = m_{l}\hbar$. (a) 22 electrons, 2 in each of the lowest 11 states, where the highest occupied state is $m_{l} \pm 5$. $$ J_{z} = \pm 5h = 5.275x10^{-34} J \space s ,$$ and $$ E = \frac{25\hbar^{2}}{2I} = 7.89x10^{-19} J$$ where $$ I = mr^{2} = 1.76x10^{-49} kg \space m^{-2} $$ (b) The lowest unoccupied energy level is $m_{l} = \pm 6$, such that the energy $$ E = \frac{36\hbar^{2}}{2I} = 1.14x10^{-18}J$$ The frequency of the transition between these energy levels is $$ \Delta E = h\nu \implies \nu = \frac{\Delta E}{h} = 5.2x10^{14} Hz \implies 570 nm \implies \text{visible light} $$ **9.35 How many orbitals are present in the N shell of an atom?** $$\text{n = 4 for the N shell}$$ $$\therefore \space n^{2} = 4^{2} = 16 \text{ orbitals}$$ **9.36 Consider the ground state of the H atom.** **NOTE:** (a) and (b) are unusally worded questions... **(a) At what radius does the <probability of finding an electron in a small volume located at a point <u>fall to 25 per cent of its maximum value</u>?** Here, we need to find the radius at which the probability, $\psi^{2} = 25\%$. $$\psi^{2} = \frac{e^{-2r/a_{0}}}{\pi {a_{0}}^{3}} \implies \pi {a_{0}}^{3}\psi^{2} = e^{-2r/a_{0}}$$ $$ ln(\pi {a_{0}}^{3}\psi^{2}) = \frac{-2r}{a_{0}},$$ where $\psi^{2}$ = 0.25. Then, solving for $r$ gives: $$ r = -\frac{a_{0}}{2}[ln(0.25)+ln(\pi a_{0}^{3})] \approx -\frac{a_{0}}{2}ln(0.25) = 0.69a_{0} = 36.7 pm$$ **(b) At what radius does the <u>radial distribution function</u> have <u>25 per cent of its maximum value?</u>** Here, we need to find the radius at which $0.25\space max(P(r)).$ $$P(r) = 4\pi r^{2} \psi^{2} = \frac{4r^{2}}{a_{0}^{3}}e^{-2r/a_{0}},$$ where the maximum proability is at the bohr radius, $a_{0}$. Hence, $$ P(a_{0}) = \frac{4}{a_{0}}e^{-2}. $$ $$\Phi = 0.25 = \frac{\frac{4r^{2}}{a_{0}^{3}}e^{-2r/a_{0}}}{\frac{4}{a_{0}}e^{-2}} = \frac{r^{2}}{a_{0}^{2}}e^{-2r/a_{0}} $$ $$\implies \Phi^{1/2} = \frac{r}{a_{0}}e^{1}e^{-r/a_{0}} $$ Solving for r gives: $$ r = 2.6783a_{0}\text{ or }0.2320 a_{0} = 142 pm \text{ or }12 pm.$$ **(c) What is the most probable distance of an electron from the nucleus? Hint: Look for a maximum in the radial distribution function.** $$P(r) = 4\pi r^{2} \psi^{2}$$ $$\frac{\partial P(r)}{\partial r} = 0 \implies r_{max} = a_{0}$$ **9.41 What is the orbital angular momentum (as multiples of ħ) of an electron in the orbitals (a) 1s, (b) 3s, (c) 3d, (d) 2p, and (e) 3p? Give the numbers of angular and radial nodes in each case.** $$ |J| = \sqrt{l(l + 1)}\hbar$$ (a) $l = 0 \implies |J| = 0$ (b) $l = 0 \implies |J| = 0$ (c) $l = 2 \implies |J| = \sqrt{6}\hbar$ (d) $l = 1 \implies |J| = \sqrt{2}\hbar$ (e) $l = 1 \implies |J| = \sqrt{2}\hbar$ | $\space$ | $$1s$$ | $$3s$$ | $$3d$$ | $$2p$$ | $$3p$$ | | :--: | :--: | :--: | :--: | :--: | :--: | | n,l | 1,0 | 3,0 | 3,2 | 2,1 | 3,1 | | Angular Nodes | 0 | 0 | 2 | 1 | 1 | | Rad. Nodes | 0 | 2 | 0 | 0 | 1 | **9.42 How many electrons can occupy subshells with the following values of l: (a) 0, (b) 3, (c) 5?** For a given $l$ there are $2l+1$ values of $m_{l}$, hence $2l+1$ orbitals. Each orbital may be occupied by two electrons. Therefore, the max occupancy is $2(2l+1)$. | $\space$ | $$l$$ | $$2(2l+1)$$ | | :--: | :--: | :--: | | (a) | 0 | 2 | | (b) | 3 | 14 | | (c) | 5 | 22 | #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>4.</span> <!-- HW4: Chapter #10: 14, 15, 19, 23, 26 --> **10.14 Show that $S = \int h_{1}h_{2} d\tau = 0$, where $h_{1} = s + p_{x} + p_{y} + p_{z}$ and $h_{2} = s − p_{x} − p_{y} + p_{z}$ are hybrid orbitals. Hint: Each atomic orbital is individually normalized to 1. Also, note that $S = \int sp d\tau = 0$, and that p orbitals with perpendicular orientations have zero overlap.** **10.15 Show that the $sp^{2}$ hybrid orbital $(s + 2^{1/2}p)/3^{1/2}$ is normalized to 1 if the s and p orbitals are each normalized to 1.** **10.19 Suppose that a molecular orbital has the form N(0.145A+ 0.844B). Find a linear combination of the orbitals A and B that has zero overlap with this combination.** **10.23 Give the ground state electron configurations of (a) $H_{2}^{−}$, (b ) $N_{2}$, and (c) $O_{2}$.** **10.26 Give the (g,u) parities of the wavefunctions for the first four levels of a particle in a box.** **11.4 Describe the formation of a hydrogen bond in terms of (a) an electrostatic interaction and (b) molecular orbital theory.** #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>5.</span> #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>6.</span> #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>7.</span> #### [Jump to table of contents.](#Table-of-Contents:) #### <span style='color:blue'>8.</span> #### <span style='color:blue'>10.</span> **12.37 When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. This singlet changes rapidly into a triplet, which phosphoresces. Triethylamine acts as a quencher for the triplet. In an experiment in methanol as solvent, the phosphorescence intensity Iphos varied with amine concentration as shown below. A time-resolved laser spectroscopy experiment had also shown that the half-life of the fluorescence in the absence of quencher is 29 ms. What is the value of kQ?** | Species | $\text{}$ | $\text{}$ | $\text{}$ | | :--: | :--: | :--: | :--: | | [Q]/(moldm−3) | 0.0010 | 0.0050 | 0.0100 | | Iphos/(arbitraryunits) | 0.41 | 0.25 | 0.16| First, we need to write out the mechanism that is given in the question: >When benzophenone is illuminated with ultraviolet radiation, it is excited into a singlet state. $$ M + h\nu_{i} \rightarrow M^{*} \tag{}$$ >This singlet changes rapidly into a triplet, which phosphoresces. $$ M^{*} \rightarrow M + h\nu_{phos} \tag{}$$ >Triethylamine acts as a quencher for the triplet. $$ M^{*} + Q \rightarrow M + Q \tag{}$$ <hr> To model this process, we apply the steady state approximation on $[M^{*}]$ to obtain $I_{phos}$... (Do this to get your own "stern-volmer" equation that models what the questions provides). **Steady State** is an assumption that the rate of (production/destruction) is equal to zero i.e., at equilibrium. <hr> The quantum efficiency of fluorescence is $\phi_{F}$, where <!--$$\phi_{F} = \frac{\text{rate of fluor}}{I_{abs}} = \frac{k_{F} [M^{*}]}{I_{abs}} $$--> $$\phi_{F} = \frac{\text{rate of fluor}}{I_{abs}} $$ Observed fluorescence lifetime $\tau_{0}$ is defined as $$\tau_{0} = \frac{\phi_{F}}{k_{F}} $$ The question gives data for $I_{phos}$, and you need to extract the slope to obtain $k_{Q}$. #### [Jump to table of contents.](#Table-of-Contents:) #### [Jump to table of contents.](#Table-of-Contents:)
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ``` # Transfer learning with TensorFlow Hub <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/tutorials/images/transfer_learning_with_hub"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs/blob/master/site/en/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/tutorials/images/transfer_learning_with_hub.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> [TensorFlow Hub](http://tensorflow.org/hub) is a way to share pretrained model components. See the [TensorFlow Module Hub](https://tfhub.dev/) for a searchable listing of pre-trained models. This tutorial demonstrates: 1. How to use TensorFlow Hub with `tf.keras`. 1. How to do image classification using TensorFlow Hub. 1. How to do simple transfer learning. ## Setup ``` import matplotlib.pylab as plt import tensorflow as tf !pip install -U tf-hub-nightly !pip install tfds-nightly import tensorflow_hub as hub from tensorflow.keras import layers ``` ## An ImageNet classifier ### Download the classifier Use `hub.module` to load a mobilenet, and `tf.keras.layers.Lambda` to wrap it up as a keras layer. Any [TensorFlow 2 compatible image classifier URL](https://tfhub.dev/s?q=tf2&module-type=image-classification) from tfhub.dev will work here. ``` classifier_url ="https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/2" #@param {type:"string"} IMAGE_SHAPE = (224, 224) classifier = tf.keras.Sequential([ hub.KerasLayer(classifier_url, input_shape=IMAGE_SHAPE+(3,)) ]) ``` ### Run it on a single image Download a single image to try the model on. ``` import numpy as np import PIL.Image as Image grace_hopper = tf.keras.utils.get_file('image.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/grace_hopper.jpg') grace_hopper = Image.open(grace_hopper).resize(IMAGE_SHAPE) grace_hopper grace_hopper = np.array(grace_hopper)/255.0 grace_hopper.shape ``` Add a batch dimension, and pass the image to the model. ``` result = classifier.predict(grace_hopper[np.newaxis, ...]) result.shape ``` The result is a 1001 element vector of logits, rating the probability of each class for the image. So the top class ID can be found with argmax: ``` predicted_class = np.argmax(result[0], axis=-1) predicted_class ``` ### Decode the predictions We have the predicted class ID, Fetch the `ImageNet` labels, and decode the predictions ``` labels_path = tf.keras.utils.get_file('ImageNetLabels.txt','https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt') imagenet_labels = np.array(open(labels_path).read().splitlines()) plt.imshow(grace_hopper) plt.axis('off') predicted_class_name = imagenet_labels[predicted_class] _ = plt.title("Prediction: " + predicted_class_name.title()) ``` ## Simple transfer learning Using TF Hub it is simple to retrain the top layer of the model to recognize the classes in our dataset. ### Dataset For this example you will use the TensorFlow flowers dataset: ``` data_root = tf.keras.utils.get_file( 'flower_photos','https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz', untar=True) ``` The simplest way to load this data into our model is using `tf.keras.preprocessing.image.ImageDataGenerator`, All of TensorFlow Hub's image modules expect float inputs in the `[0, 1]` range. Use the `ImageDataGenerator`'s `rescale` parameter to achieve this. The image size will be handled later. ``` image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255) image_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SHAPE) ``` The resulting object is an iterator that returns `image_batch, label_batch` pairs. ``` for image_batch, label_batch in image_data: print("Image batch shape: ", image_batch.shape) print("Label batch shape: ", label_batch.shape) break ``` ### Run the classifier on a batch of images Now run the classifier on the image batch. ``` result_batch = classifier.predict(image_batch) result_batch.shape predicted_class_names = imagenet_labels[np.argmax(result_batch, axis=-1)] predicted_class_names ``` Now check how these predictions line up with the images: ``` plt.figure(figsize=(10,9)) plt.subplots_adjust(hspace=0.5) for n in range(30): plt.subplot(6,5,n+1) plt.imshow(image_batch[n]) plt.title(predicted_class_names[n]) plt.axis('off') _ = plt.suptitle("ImageNet predictions") ``` See the `LICENSE.txt` file for image attributions. The results are far from perfect, but reasonable considering that these are not the classes the model was trained for (except "daisy"). ### Download the headless model TensorFlow Hub also distributes models without the top classification layer. These can be used to easily do transfer learning. Any [Tensorflow 2 compatible image feature vector URL](https://tfhub.dev/s?module-type=image-feature-vector&q=tf2) from tfhub.dev will work here. ``` feature_extractor_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2" #@param {type:"string"} ``` Create the feature extractor. ``` feature_extractor_layer = hub.KerasLayer(feature_extractor_url, input_shape=(224,224,3)) ``` It returns a 1280-length vector for each image: ``` feature_batch = feature_extractor_layer(image_batch) print(feature_batch.shape) ``` Freeze the variables in the feature extractor layer, so that the training only modifies the new classifier layer. ``` feature_extractor_layer.trainable = False ``` ### Attach a classification head Now wrap the hub layer in a `tf.keras.Sequential` model, and add a new classification layer. ``` model = tf.keras.Sequential([ feature_extractor_layer, layers.Dense(image_data.num_classes) ]) model.summary() predictions = model(image_batch) predictions.shape ``` ### Train the model Use compile to configure the training process: ``` model.compile( optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True), metrics=['acc']) ``` Now use the `.fit` method to train the model. To keep this example short train just 2 epochs. To visualize the training progress, use a custom callback to log the loss and accuracy of each batch individually, instead of the epoch average. ``` class CollectBatchStats(tf.keras.callbacks.Callback): def __init__(self): self.batch_losses = [] self.batch_acc = [] def on_train_batch_end(self, batch, logs=None): self.batch_losses.append(logs['loss']) self.batch_acc.append(logs['acc']) self.model.reset_metrics() steps_per_epoch = np.ceil(image_data.samples/image_data.batch_size) batch_stats_callback = CollectBatchStats() history = model.fit(image_data, epochs=2, steps_per_epoch=steps_per_epoch, callbacks=[batch_stats_callback]) ``` Now after, even just a few training iterations, we can already see that the model is making progress on the task. ``` plt.figure() plt.ylabel("Loss") plt.xlabel("Training Steps") plt.ylim([0,2]) plt.plot(batch_stats_callback.batch_losses) plt.figure() plt.ylabel("Accuracy") plt.xlabel("Training Steps") plt.ylim([0,1]) plt.plot(batch_stats_callback.batch_acc) ``` ### Check the predictions To redo the plot from before, first get the ordered list of class names: ``` class_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1]) class_names = np.array([key.title() for key, value in class_names]) class_names ``` Run the image batch through the model and convert the indices to class names. ``` predicted_batch = model.predict(image_batch) predicted_id = np.argmax(predicted_batch, axis=-1) predicted_label_batch = class_names[predicted_id] ``` Plot the result ``` label_id = np.argmax(label_batch, axis=-1) plt.figure(figsize=(10,9)) plt.subplots_adjust(hspace=0.5) for n in range(30): plt.subplot(6,5,n+1) plt.imshow(image_batch[n]) color = "green" if predicted_id[n] == label_id[n] else "red" plt.title(predicted_label_batch[n].title(), color=color) plt.axis('off') _ = plt.suptitle("Model predictions (green: correct, red: incorrect)") ``` ## Export your model Now that you've trained the model, export it as a saved model: ``` import time t = time.time() export_path = "/tmp/saved_models/{}".format(int(t)) model.save(export_path, save_format='tf') export_path ``` Now confirm that we can reload it, and it still gives the same results: ``` reloaded = tf.keras.models.load_model(export_path) result_batch = model.predict(image_batch) reloaded_result_batch = reloaded.predict(image_batch) abs(reloaded_result_batch - result_batch).max() ``` This saved model can be loaded for inference later, or converted to [TFLite](https://www.tensorflow.org/lite/convert/) or [TFjs](https://github.com/tensorflow/tfjs-converter).
github_jupyter
# Advanced Matplotlib Concepts Lecture In this lecture we cover some more advanced topics which you won't usually use as often. You can always reference the documentation for more resources! #### Logarithmic scale It is also possible to set a logarithmic scale for one or both axes. This functionality is in fact only one application of a more general transformation system in Matplotlib. Each of the axes' scales are set seperately using `set_xscale` and `set_yscale` methods which accept one parameter (with the value "log" in this case): ``` fig, axes = plt.subplots(1, 2, figsize=(10,4)) axes[0].plot(x, x**2, x, np.exp(x)) axes[0].set_title("Normal scale") axes[1].plot(x, x**2, x, np.exp(x)) axes[1].set_yscale("log") axes[1].set_title("Logarithmic scale (y)"); ``` ### Placement of ticks and custom tick labels We can explicitly determine where we want the axis ticks with `set_xticks` and `set_yticks`, which both take a list of values for where on the axis the ticks are to be placed. We can also use the `set_xticklabels` and `set_yticklabels` methods to provide a list of custom text labels for each tick location: ``` fig, ax = plt.subplots(figsize=(10, 4)) ax.plot(x, x**2, x, x**3, lw=2) ax.set_xticks([1, 2, 3, 4, 5]) ax.set_xticklabels([r'$\alpha$', r'$\beta$', r'$\gamma$', r'$\delta$', r'$\epsilon$'], fontsize=18) yticks = [0, 50, 100, 150] ax.set_yticks(yticks) ax.set_yticklabels(["$%.1f$" % y for y in yticks], fontsize=18); # use LaTeX formatted labels ``` There are a number of more advanced methods for controlling major and minor tick placement in matplotlib figures, such as automatic placement according to different policies. See http://matplotlib.org/api/ticker_api.html for details. #### Scientific notation With large numbers on axes, it is often better use scientific notation: ``` fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, np.exp(x)) ax.set_title("scientific notation") ax.set_yticks([0, 50, 100, 150]) from matplotlib import ticker formatter = ticker.ScalarFormatter(useMathText=True) formatter.set_scientific(True) formatter.set_powerlimits((-1,1)) ax.yaxis.set_major_formatter(formatter) ``` ### Axis number and axis label spacing ``` # distance between x and y axis and the numbers on the axes matplotlib.rcParams['xtick.major.pad'] = 5 matplotlib.rcParams['ytick.major.pad'] = 5 fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, np.exp(x)) ax.set_yticks([0, 50, 100, 150]) ax.set_title("label and axis spacing") # padding between axis label and axis numbers ax.xaxis.labelpad = 5 ax.yaxis.labelpad = 5 ax.set_xlabel("x") ax.set_ylabel("y"); # restore defaults matplotlib.rcParams['xtick.major.pad'] = 3 matplotlib.rcParams['ytick.major.pad'] = 3 ``` #### Axis position adjustments Unfortunately, when saving figures the labels are sometimes clipped, and it can be necessary to adjust the positions of axes a little bit. This can be done using `subplots_adjust`: ``` fig, ax = plt.subplots(1, 1) ax.plot(x, x**2, x, np.exp(x)) ax.set_yticks([0, 50, 100, 150]) ax.set_title("title") ax.set_xlabel("x") ax.set_ylabel("y") fig.subplots_adjust(left=0.15, right=.9, bottom=0.1, top=0.9); ``` ### Axis grid With the `grid` method in the axis object, we can turn on and off grid lines. We can also customize the appearance of the grid lines using the same keyword arguments as the `plot` function: ``` fig, axes = plt.subplots(1, 2, figsize=(10,3)) # default grid appearance axes[0].plot(x, x**2, x, x**3, lw=2) axes[0].grid(True) # custom grid appearance axes[1].plot(x, x**2, x, x**3, lw=2) axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5) ``` ### Axis spines We can also change the properties of axis spines: ``` fig, ax = plt.subplots(figsize=(6,2)) ax.spines['bottom'].set_color('blue') ax.spines['top'].set_color('blue') ax.spines['left'].set_color('red') ax.spines['left'].set_linewidth(2) # turn off axis spine to the right ax.spines['right'].set_color("none") ax.yaxis.tick_left() # only ticks on the left side ``` ### Twin axes Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the `twinx` and `twiny` functions: ``` fig, ax1 = plt.subplots() ax1.plot(x, x**2, lw=2, color="blue") ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue") for label in ax1.get_yticklabels(): label.set_color("blue") ax2 = ax1.twinx() ax2.plot(x, x**3, lw=2, color="red") ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red") for label in ax2.get_yticklabels(): label.set_color("red") ``` ### Axes where x and y is zero ``` fig, ax = plt.subplots() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) # set position of x spine to x=0 ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) # set position of y spine to y=0 xx = np.linspace(-0.75, 1., 100) ax.plot(xx, xx**3); ``` ### Other 2D plot styles In addition to the regular `plot` method, there are a number of other functions for generating different kind of plots. See the matplotlib plot gallery for a complete list of available plot types: http://matplotlib.org/gallery.html. Some of the more useful ones are show below: ``` n = np.array([0,1,2,3,4,5]) fig, axes = plt.subplots(1, 4, figsize=(12,3)) axes[0].scatter(xx, xx + 0.25*np.random.randn(len(xx))) axes[0].set_title("scatter") axes[1].step(n, n**2, lw=2) axes[1].set_title("step") axes[2].bar(n, n**2, align="center", width=0.5, alpha=0.5) axes[2].set_title("bar") axes[3].fill_between(x, x**2, x**3, color="green", alpha=0.5); axes[3].set_title("fill_between"); ``` ### Text annotation Annotating text in matplotlib figures can be done using the `text` function. It supports LaTeX formatting just like axis label texts and titles: ``` fig, ax = plt.subplots() ax.plot(xx, xx**2, xx, xx**3) ax.text(0.15, 0.2, r"$y=x^2$", fontsize=20, color="blue") ax.text(0.65, 0.1, r"$y=x^3$", fontsize=20, color="green"); ``` ### Figures with multiple subplots and insets Axes can be added to a matplotlib Figure canvas manually using `fig.add_axes` or using a sub-figure layout manager such as `subplots`, `subplot2grid`, or `gridspec`: #### subplots ``` fig, ax = plt.subplots(2, 3) fig.tight_layout() ``` #### subplot2grid ``` fig = plt.figure() ax1 = plt.subplot2grid((3,3), (0,0), colspan=3) ax2 = plt.subplot2grid((3,3), (1,0), colspan=2) ax3 = plt.subplot2grid((3,3), (1,2), rowspan=2) ax4 = plt.subplot2grid((3,3), (2,0)) ax5 = plt.subplot2grid((3,3), (2,1)) fig.tight_layout() ``` #### gridspec ``` import matplotlib.gridspec as gridspec fig = plt.figure() gs = gridspec.GridSpec(2, 3, height_ratios=[2,1], width_ratios=[1,2,1]) for g in gs: ax = fig.add_subplot(g) fig.tight_layout() ``` #### add_axes Manually adding axes with `add_axes` is useful for adding insets to figures: ``` fig, ax = plt.subplots() ax.plot(xx, xx**2, xx, xx**3) fig.tight_layout() # inset inset_ax = fig.add_axes([0.2, 0.55, 0.35, 0.35]) # X, Y, width, height inset_ax.plot(xx, xx**2, xx, xx**3) inset_ax.set_title('zoom near origin') # set axis range inset_ax.set_xlim(-.2, .2) inset_ax.set_ylim(-.005, .01) # set axis tick locations inset_ax.set_yticks([0, 0.005, 0.01]) inset_ax.set_xticks([-0.1,0,.1]); ``` ### Colormap and contour figures Colormaps and contour figures are useful for plotting functions of two variables. In most of these functions we will use a colormap to encode one dimension of the data. There are a number of predefined colormaps. It is relatively straightforward to define custom colormaps. For a list of pre-defined colormaps, see: http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps ``` alpha = 0.7 phi_ext = 2 * np.pi * 0.5 def flux_qubit_potential(phi_m, phi_p): return 2 + alpha - 2 * np.cos(phi_p) * np.cos(phi_m) - alpha * np.cos(phi_ext - 2*phi_p) phi_m = np.linspace(0, 2*np.pi, 100) phi_p = np.linspace(0, 2*np.pi, 100) X,Y = np.meshgrid(phi_p, phi_m) Z = flux_qubit_potential(X, Y).T ``` #### pcolor ``` fig, ax = plt.subplots() p = ax.pcolor(X/(2*np.pi), Y/(2*np.pi), Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max()) cb = fig.colorbar(p, ax=ax) ``` #### imshow ``` fig, ax = plt.subplots() im = ax.imshow(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1]) im.set_interpolation('bilinear') cb = fig.colorbar(im, ax=ax) ``` #### contour ``` fig, ax = plt.subplots() cnt = ax.contour(Z, cmap=matplotlib.cm.RdBu, vmin=abs(Z).min(), vmax=abs(Z).max(), extent=[0, 1, 0, 1]) ``` ## 3D figures To use 3D graphics in matplotlib, we first need to create an instance of the `Axes3D` class. 3D axes can be added to a matplotlib figure canvas in exactly the same way as 2D axes; or, more conveniently, by passing a `projection='3d'` keyword argument to the `add_axes` or `add_subplot` methods. ``` from mpl_toolkits.mplot3d.axes3d import Axes3D ``` #### Surface plots ``` fig = plt.figure(figsize=(14,6)) # `ax` is a 3D-aware axis instance because of the projection='3d' keyword argument to add_subplot ax = fig.add_subplot(1, 2, 1, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=4, cstride=4, linewidth=0) # surface_plot with color grading and color bar ax = fig.add_subplot(1, 2, 2, projection='3d') p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=matplotlib.cm.coolwarm, linewidth=0, antialiased=False) cb = fig.colorbar(p, shrink=0.5) ``` #### Wire-frame plot ``` fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(1, 1, 1, projection='3d') p = ax.plot_wireframe(X, Y, Z, rstride=4, cstride=4) ``` #### Coutour plots with projections ``` fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(1,1,1, projection='3d') ax.plot_surface(X, Y, Z, rstride=4, cstride=4, alpha=0.25) cset = ax.contour(X, Y, Z, zdir='z', offset=-np.pi, cmap=matplotlib.cm.coolwarm) cset = ax.contour(X, Y, Z, zdir='x', offset=-np.pi, cmap=matplotlib.cm.coolwarm) cset = ax.contour(X, Y, Z, zdir='y', offset=3*np.pi, cmap=matplotlib.cm.coolwarm) ax.set_xlim3d(-np.pi, 2*np.pi); ax.set_ylim3d(0, 3*np.pi); ax.set_zlim3d(-np.pi, 2*np.pi); ``` ## Further reading * http://www.matplotlib.org - The project web page for matplotlib. * https://github.com/matplotlib/matplotlib - The source code for matplotlib. * http://matplotlib.org/gallery.html - A large gallery showcaseing various types of plots matplotlib can create. Highly recommended! * http://www.loria.fr/~rougier/teaching/matplotlib - A good matplotlib tutorial. * http://scipy-lectures.github.io/matplotlib/matplotlib.html - Another good matplotlib reference.
github_jupyter
This notebook works through the major issues that should likely be considered about the names/records from the original FWS Work Plan list that were not exactly matched to a corresponding record in the Integrated Taxonomic Information System (ITIS), the major taxonomic authority used by FWS. We include a report on names that out process was able to find in the World Register of Marine Species (WoRMS), particularly molluscs that have been addressed in the WoRMS taxonomic review process based on community demand. We also show a report of those ITIS TSNs and names that came from the original FWS Work Plan source where we needed to follow the "Accepted TSN" in ITIS to retrieve the accepted/valid record. In both of these cases, it may be helpful to ``` import json from IPython.display import display with open('../cache/itis.json', 'r') as f: itis_species = json.loads(f.read()) f.close() with open('../cache/worms.json', 'r') as f: worms_species = json.loads(f.read()) f.close() ``` The following codeblock builds two lists. The first is a list of species names from the FWS Work Plan source where our process was unable to find a match in either ITIS or WoRMS. The second is a list where our process did not find a match in ITIS but did find a match in WoRMS. In one of the WoRMS records, the taxonomy is flagged as uncertain, and we provide a link for followup. ``` no_taxonomic_match = list() worms_matches = list() for name in [i["parameters"]["Scientific Name"] for i in itis_species if i["processing_metadata"]["status_message"] == "Not Matched"]: worms_match = next((i for i in worms_species if i["processing_metadata"]["status"] == "success" and i["parameters"]["Scientific Name"] == name), None) if worms_match is None: no_taxonomic_match.append(name) else: if worms_match["data"][0]["status"] != "accepted": worms_matches.append( "{} - {} - http://marinespecies.org/aphia.php?p=taxdetails&id={}".format( name, worms_match['data'][0]['status'], worms_match['data'][0]['AphiaID'] ) ) else: worms_matches.append(name) print("Names with no match in ITIS or WoRMS") display(no_taxonomic_match) print("Names found in WoRMS but not ITIS") display(worms_matches) ``` The following codeblock lists those cases where the original information from the FWS work plan, either a scientific name or an ITIS taxonomic serial number (pulled from an associated ECOS record), came up with an invalid or unaccepted record in ITIS. In each case, our process followed the ITIS system from the point of discovery to the valid or accepted ITIS record, recording both the valid and original documents in the data cache. The following report shows cases where the FWS Work Plan list may need to be updated with current valid taxonomic names. Synonyms are a factor in all of these records, and we list those names for further consideration. Links to both the valid and invalid ITIS records are provided for followup. ``` for record in [i for i in itis_species if "data" in i.keys() and len(i["data"]) > 1]: valid_itis_doc = next(x for x in record["data"] if x["usage"] in ["accepted","valid"]) invalid_itis_doc = next(x for x in record["data"] if x["usage"] not in ["accepted","valid"]) print("input parameter:", record["parameters"]) print("taxonomic information action:", record["processing_metadata"]["status_message"]) print("valid itis record:", valid_itis_doc["nameWOInd"]) print(f"https://itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value={valid_itis_doc['tsn']}") print("invalid itis record:", invalid_itis_doc["nameWOInd"]) print(f"https://itis.gov/servlet/SingleRpt/SingleRpt?search_topic=TSN&search_value={invalid_itis_doc['tsn']}") print("reason for invalid record:", invalid_itis_doc["unacceptReason"]) print("synonyms:", valid_itis_doc["synonyms"][0].split(":")[-1][1:-2].split("$")) print("==================") ```
github_jupyter
``` import os os.environ['CUDA_VISIBLE_DEVICES'] = '' # !wget https://f000.backblazeb2.com/file/malaya-model/v34/stem/model.pb import tensorflow as tf from tensorflow.tools.graph_transforms import TransformGraph from tensorflow.contrib.seq2seq.python.ops import beam_search_ops from glob import glob tf.set_random_seed(0) pbs = glob('*.pb') pbs transforms = ['add_default_attributes', 'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)', 'fold_batch_norms', 'fold_old_batch_norms', 'quantize_weights(fallback_min=-10, fallback_max=10)', 'strip_unused_nodes', 'sort_by_execution_order'] for pb in ['model.pb']: input_graph_def = tf.GraphDef() with tf.gfile.FastGFile(pb, 'rb') as f: input_graph_def.ParseFromString(f.read()) transformed_graph_def = TransformGraph(input_graph_def, ['Placeholder'], ['decode_1/greedy', 'decode_2/beam'], transforms) with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f: f.write(transformed_graph_def.SerializeToString()) !rm *.pb* # converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph( # graph_def_file='test.pb', # input_arrays=['Placeholder', 'Placeholder_1'], # input_shapes={'Placeholder' : [None, 512], 'Placeholder_1': [None, 512]}, # output_arrays=['logits'], # ) # # converter.allow_custom_ops=True # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS] # converter.target_spec.supported_types = [tf.float16] # converter.optimizations = [tf.lite.Optimize.DEFAULT] # converter.experimental_new_converter = True # tflite_model = converter.convert() # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, # tf.lite.OpsSet.SELECT_TF_OPS] # converter.target_spec.supported_types = [tf.float16] # converter.optimizations = [tf.lite.Optimize.DEFAULT] # tflite_model = converter.convert() # with open('tiny-bert-sentiment-float16.tflite', 'wb') as f: # f.write(tflite_model) # converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, # tf.lite.OpsSet.SELECT_TF_OPS] # converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE] # tflite_model = converter.convert() # with open('tiny-bert-sentiment-hybrid.tflite', 'wb') as f: # f.write(tflite_model) # interpreter = tf.lite.Interpreter(model_path='tiny-bert-sentiment-hybrid.tflite') # interpreter.allocate_tensors() ```
github_jupyter
# Distances measurement stations along netwerk ``` library(tidyverse) ``` ## Normalize and combine all measurement stations ### Receivers ``` eels <- read_csv("../data/eel_track.csv", col_types = cols()) head(eels) receivers <- eels %>% select(receiver, latitude, longitude, station) %>% distinct() %>% mutate(station_type = "receiver") %>% rename(station_id = receiver, station_name = station) head(receivers) ``` ### Tidal stations Using the [tidal stations overview](https://github.com/inbo/wateRinfo/files/1483458/tij_all_identifiers.txt) as discussed on the wateRinfo [GitHub Issues](https://github.com/inbo/wateRinfo/issues/11#issuecomment-345339779): ``` ts_id_tide <- read_csv("../data/tidal_zone_ts_ids.csv", col_types = cols()) head(ts_id_tide) tidal_stations <- ts_id_tide %>% filter(ts_id < 100000000) %>% # waterinfo.be API not supported for these identifiers filter(grepl("*Pv.10", ts_name)) %>% filter(!station_name %in% c("Walem tij/Rupel", "Duffel-sluis tij", "Lier Molbrug tij/Nete", "Kessel tij/Grote Nete", "Emblem tij/Kleine Nete", "Mechelen Benedensluis tij/Dijle", "Mechelen Stuw Opwaarts tij/Dijle", "Hombeek tij/Zenne", "Zemst tij/Zenne", "Gentbrugge tij/Zeeschelde", "Waasmunster Manta tij/Durme", "Duffel Sluis tij/Nete", "Mechelen Stuw Afwaarts tij/Dijle")) %>% # exclude nonte-scheldt stations select(station_no, station_name, station_longitude, station_latitude) %>% distinct() %>% mutate(station_type = "waterinfo") %>% rename(station_id = station_no, longitude = station_longitude, latitude = station_latitude) tidal_stations ``` ### Combine receivers and waterinfo stations ``` stations <- bind_rows(tidal_stations, receivers) stations <- stations %>% filter(station_id != "VR2W-122336") # exclude double entry for the s-4c station head(stations) ``` ## Find station closest to sea The station closest to sea can be used as *distance to sea* ``` pal <- colorFactor(c("#e66101", "#2b8cbe"), domain = c("receiver", "waterinfo")) library(leaflet) m <- leaflet(data = stations, width = 600, height = 400) %>% addTiles() %>% addCircleMarkers(~longitude, ~latitude, popup = ~station_name, color = ~pal(station_type), stroke = FALSE, fillOpacity = 0.8) %>% addLegend(pal = pal, values = ~station_type, opacity = 1) m ``` `ws-TRAWL` is the station used as reference *close to sea* ## Derive internal distances stations ``` library(sp) library(raster) ``` Load the study area rivers/canals as a binary mask ``` study_area <- raster("../data/study_area_binary.tif") ``` Convert the CRS of the stations to the CRS of the binary mask ``` crs_mask <- CRS("+init=epsg:32631") # use gdalinfo to derive the CRS crs_stations <- CRS("+init=epsg:4326") # project coordinates stations_sp <- SpatialPointsDataFrame(coords = stations[, c("longitude", "latitude")], data = stations, proj4string = crs_stations) stations_sp <- spTransform(stations_sp, crs_mask) ``` Load the support functions to derive internal distances ``` source('distance_fun.R') ``` Update the binary mask for stations that fall outside the binary mask. The basic strategy is to extend the points raster point size until it overlaps with the main binary mask: ``` study_area_binary_extended <- adapt_binarymask(study_area, stations_sp) # check on memory usage of R objects in memory #sort( sapply(ls(), function(x){object.size(get(x))})) ``` Check if the extended mask is properly derived to extract in-network distances: ``` control_mask(study_area_binary_extended, stations_sp) ``` Calculate all internal distances for the stations: ``` cst_dst_frame <- get_distance_matrix(study_area_binary_extended, stations_sp) ``` Write the internal distances to file ``` cst_dst_frame <- as.data.frame(cst_dst_frame) head(cst_dst_frame) write_csv(cst_dst_frame, "../data/stations_internal_distances.csv") ``` ## Translate to distance from sea (i.e. reference station close to sea) When you do not want to reproduce the entire calculation ``` head(cst_dst_frame) distance_from_reference <- cst_dst_frame %>% rownames_to_column("STATION") %>% filter(STATION == "ws-TRAWL") %>% gather(key = "station", value = "distance_from_sea", -STATION) %>% rename(reference_station = STATION) %>% arrange(distance_from_sea) %>% inner_join(stations, by = c("station" = "station_name")) %>% dplyr::select(station, station_id, station_type, latitude, longitude, distance_from_sea) head(distance_from_reference) ``` ## Add municipality names for selected set of stations For plotting purposes, having the name of a municipality is provides readers (certainly when familiar with the region) a better reference point. The following list is just a *nearby* approximation of a municipality nearby, created by hand: ``` municipalities <- data.frame( "station" = c("ws-18", "s-10a", "s-9a", "s-8", "s-6", "s-4b", "s-Vlassenbroek", "s-Dendermonde", "s-2a", "s-Wichelen", "s-Wetteren", "s-2"), "municipality" = c("Terneuzen", "Antwerpen", "Hoboken", "Hemiksem", "Temse", "Sint-Amands", "Vlassenbroek", "Dendermonde", "Uitbergen", "Wichelen", "Wetteren", "Merelbeke"), stringsAsFactors=FALSE) municipalities distance_from_sea <- distance_from_reference %>% left_join(municipalities, by = "station") distance_from_sea write_csv(distance_from_sea, "../data/distance_from_sea.csv") ```
github_jupyter
``` def check_date_format(date): """ Ensures that a date is correctly formatted and that an end date is later than a start date. """ for item in items: if len(item) > 10: format = '%Y-%m-%dT%H:%M:%S' else: format = '%Y-%m-%d' try: if item != datetime.strptime(item, format).strftime(format): raise ValueError return True except ValueError: print('The date value ' + item + ' is in an incorrect format. Use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.') items = date.replace(' ', '').split(',') if len(items) == 2: try: assert items[1] > items[0] except: print('Your end date ' + items[1] + ' must be after your start date ' + items[0] + '.') def process_dates(datefield): """ Takes a line-separated list of dates from a text area. Ranges must have start and end dates separated with commas. Output is a list of dates. Dates must be in date or datetime format. Mixtures of normal and precise dates are placed in separate normal and precise objects. Otherwise, all dates are assumed to be normal. """ import os, json, requests from datetime import datetime date = datefield.strip().split('\n') new_date = [] d = {} # Validate all the date formats individually for item in date: check_date_format(item) # Determine if the datelist is a mix of normal and precise dates contains_precise = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') if len(start) > 10 or len(end) > 10: contains_precise.append('precise') else: contains_precise.append('normal') elif len(item) > 10: contains_precise.append('precise') else: contains_precise.append('normal') # Handle a mix of normal and precise dates if 'normal' in contains_precise and 'precise' in contains_precise: d['normal'] = [] d['precise'] = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') if len(start) > 10 or len(end) > 10: d['precise'].append({'start': start, 'end': end}) else: d['normal'].append({'start': start, 'end': end}) else: if len(item) > 10: d['precise'].append(item) else: d['normal'].append(item) new_date.append(d) # Handle only precise dates elif 'precise' in contains_precise: d['precise'] = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') d['precise'].append({'start': start, 'end': end}) else: d['precise'].append(item) new_date.append(d) # Handle only normal dates else: for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') new_date.append({'start': start, 'end': end}) else: new_date.append(item) return new_date datefield = """ 2013-01-01T12:00:30 2013-01-01T12:00:31 """ date = process_dates(datefield) print(date) import os, json, requests from jsonschema import validate, FormatChecker schema_file = 'https://github.com/whatevery1says/manifest/raw/master/schema/global/global.json' schema = json.loads(requests.get(schema_file).text) # Remove all the non-date properties from the global schema remove = ['altTitle', 'group', '_id', 'label', 'title', 'description', 'namespace', 'note', 'notes', 'path', 'refLocation'] for item in remove: del schema[item] schema = { "definitions": { "daterange": { "type": "object", "properties": { "start": { "type": "string", "format": "date" }, "end": { "type": "string", "format": "date" } }, "required": [ "start", "end" ] }, "normal": { "type": "object", "properties": { "normal": { "type": "array", "items": { "oneOf": [ { "type": "string", "format": "date" }, { "$ref": "#/definitions/daterange" }] } } } } }, "type": "object", "properties": { "date": { "type": "array", "items": { "oneOf": [{ "type": "string", "format": "date" }, { "type": "string", "format": "date-time" },{ "$ref": "#/definitions/daterange" }] } } } } f = { "date": [ {"normal": ["2013-01-01"]} ] } try: validate(f, schema, format_checker=FormatChecker()) print('Valid') except: print('Not Valid') from datetime import datetime from IPython.display import display, HTML import ipywidgets as widgets from ipywidgets import Checkbox, Box, Dropdown, Textarea, fixed, interact, interactive, interact_manual, Label, Layout, Textarea # Override ipywidgets styles display(HTML(''' <style> textarea {min-height: 110px !important;} /* Allow extra-long labels */ .widget-label {min-width: 20ex !important; font-weight: bold;} .widget-checkbox {padding-right: 300px !important;} /* Classes for toggling widget visibility */ .hidden {display: none;} .visible {display: flex;} </style> ''')) class ConfigForm(object): # Define widgets caption = widgets.HTML(value='<h4>Global Congfiguration</h4>') button = widgets.Button(description='Submit') title = widgets.Text(value='') altTitle = widgets.Text(value='') label = widgets.Text(value='') description = widgets.Textarea(value='') precise = widgets.Checkbox(value=False) date = widgets.Textarea(placeholder='Place each date on a separate line. Date ranges should use the separate start and end dates with commas. Valid formats are YYYY-MM-DD and YYYY-MM-DDTHH:MM:SS."') notes = widgets.Textarea(placeholder='Place each note on a separate line.') # Configure widget layout flex = Layout(display='flex', flex_flow='row', justify_content='space-between') # Assemble widgets in Boxes global_form_items = [ Box([Label(value='Title:'), title], layout=flex), Box([Label(value='altTitle:'), altTitle], layout=flex), Box([Label(value='Description:'), description], layout=flex), Box([Label(value='Label:'), label], layout=flex), Box([Label(value='Date:'), date], layout=flex), Box([Label(value='Notes:'), notes], layout=flex) ] # Initialise the class object def __init__(self, object): self.caption = ConfigForm.caption self.button = ConfigForm.button self.title = ConfigForm.global_form_items[0] self.altTitle = ConfigForm.global_form_items[1] self.description = ConfigForm.global_form_items[2] self.label = ConfigForm.global_form_items[3] self.date = ConfigForm.global_form_items[4] self.notes = ConfigForm.global_form_items[5] # Ensure that a date is correctly formatted and start dates precede end dates def check_date_format(date): items = date.replace(' ', '').split(',') for item in items: if len(item) > 10: format = '%Y-%m-%dT%H:%M:%S' else: format = '%Y-%m-%d' try: if item != datetime.strptime(item, format).strftime(format): raise ValueError return True except ValueError: print('The date value ' + item + ' is in an incorrect format. Use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.') if len(items) == 2: try: assert items[1] > items[0] except: print('Your end date ' + items[1] + ' must be after your start date ' + items[0] + '.') # Transform textarea with dates to a valid schema array def process_dates(datefield): date = datefield.strip().split('\n') new_date = [] d = {} # Validate all the date formats individually for item in date: check_date_format(item) # Determine if the datelist is a mix of normal and precise dates contains_precise = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') if len(start) > 10 or len(end) > 10: contains_precise.append('precise') else: contains_precise.append('normal') elif len(item) > 10: contains_precise.append('precise') else: contains_precise.append('normal') # Handle a mix of normal and precise dates if 'normal' in contains_precise and 'precise' in contains_precise: d['normal'] = [] d['precise'] = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') if len(start) > 10 or len(end) > 10: d['precise'].append({'start': start, 'end': end}) else: d['normal'].append({'start': start, 'end': end}) else: if len(item) > 10: d['precise'].append(item) else: d['normal'].append(item) new_date.append(d) # Handle only precise dates elif 'precise' in contains_precise: d['precise'] = [] for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') d['precise'].append({'start': start, 'end': end}) else: d['precise'].append(item) new_date.append(d) # Handle only normal dates else: for item in date: if ',' in item: start, end = item.replace(' ', '').split(',') new_date.append({'start': start, 'end': end}) else: new_date.append(item) return new_date def split_list(str): seq = str.split('\n') for key, value in enumerate(seq): seq[key] = value.strip() return seq self.title = ConfigForm.global_form_items[0] self.altTitle = ConfigForm.global_form_items[1] self.description = ConfigForm.global_form_items[2] self.label = ConfigForm.global_form_items[3] self.date = ConfigForm.global_form_items[4] self.notes = ConfigForm.global_form_items[5] def handle_submit(values): # Save the form values in a dict self.values = {'action': 'global'} self.values['title'] = ConfigForm.title.value.strip() self.values['altTitle'] = ConfigForm.altTitle.value.strip() self.values['description'] = ConfigForm.description.value.strip() self.values['label'] = ConfigForm.label.value.strip() self.values['date'] = process_dates(ConfigForm.date.value.strip()) self.values['notes'] = split_list(ConfigForm.notes.value.strip()) # Initialise widgets in the container Box self.form = Box([self.title, self.altTitle, self.description, self.label, self.date, self.notes], layout=Layout( display='flex', flex_flow='column', border='solid 2px', align_items='stretch', width='50%')) # Modify the CSS and set up some helper variables box = self.form # box.children[3].add_class('hidden') action_field = box.children[0].children[1] # Display the form and watch for changes display(self.caption) display(box) display(self.button) self.button.on_click(handle_submit) # Instantiate the form - values accessible with e.g. config.values['delete_id] config = ConfigForm(object) print(config.values['date']) ```
github_jupyter