code
stringlengths
38
801k
repo_path
stringlengths
6
263
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns dataframe = pd.read_csv("archives/vehiculos.csv") dataframe.head() dataframe["vehicle_class"].unique() # 4 tipos de vehiculos y = dataframe["vehicle_class"] X = dataframe.drop("vehicle_class", axis=1) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=45) from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=1) # K = 1 knn.fit(X_train, y_train) predicciones = knn.predict(X_test) predicciones np.array(y_test) # Original data from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(y_test, predicciones)) print(classification_report(y_test, predicciones)) # + # Encontraremos el mejor k, con menor tasa de error tasa_error = [] for i in range(1,30): knn = KNeighborsClassifier(n_neighbors=i) knn.fit(X_train, y_train) prediccion_i = knn.predict(X_test) tasa_error.append(np.mean(prediccion_i != y_test)) # - tasa_error # + valores = range(1,30) plt.plot(valores, tasa_error, color="g", marker="o", markerfacecolor="r", markersize=8) # Con esto se puede ver que el mejor K es 3 # + knn = KNeighborsClassifier(n_neighbors=3) knn.fit(X_train, y_train) new_predicciones = knn.predict(X_test) print(classification_report(y_test, new_predicciones))
Machine Learning/k_vecinos.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Component Graphs # # rayml component graphs represent and describe the flow of data in a collection of related components. A component graph is comprised of nodes representing components, and edges between pairs of nodes representing where the inputs and outputs of each component should go. It is the backbone of the features offered by the rayml [pipeline](pipelines.ipynb), but is also a powerful data structure on its own. rayml currently supports component graphs as linear and [directed acyclic graphs (DAG)](https://en.wikipedia.org/wiki/Directed_acyclic_graph). # ## Defining a Component Graph # # Component graphs can be defined by specifying the dictionary of components and edges that describe the graph. # # In this dictionary, each key is a reference name for a component. Each corresponding value is a list, where the first element is the component itself, and the remaining elements are the input edges that should be connected to that component. The component as listed in the value can either be the component object itself or its string name. # # This stucture is very similar to that of [Dask computation graphs](https://docs.dask.org/en/latest/spec.html). # # # For example, in the code example below, we have a simple component graph made up of two components: an Imputer and a Random Forest Classifer. The names used to reference these two components are given by the keys, "My Imputer" and "RF Classifier" respectively. Each value in the dictionary is a list where the first element is the component corresponding to the component name, and the remaining elements are the inputs, e.g. "My Imputer" represents an Imputer component which has inputs "X" (the original features matrix) and "y" (the original target). # # Feature edges are specified as `"X"` or `"{component_name}.x"`. For example, `{"My Component": [MyComponent, "Imputer.x", ...]}` indicates that we should use the feature output of the `Imputer` as as part of the feature input for MyComponent. Similarly, target edges are specified as `"y"` or `"{component_name}.y". {"My Component": [MyComponent, "Target Imputer.y", ...]}` indicates that we should use the target output of the `Target Imputer` as a target input for MyComponent. # # Each component can have a number of feature inputs, but can only have one target input. All input edges must be explicitly defined. # Using a real example, we define a simple component graph consisting of three nodes: an Imputer ("My Imputer"), an One-Hot Encoder ("OHE"), and a Random Forest Classifier ("RF Classifier"). # # - "My Imputer" takes the original X as a features input, and the original y as the target input # - "OHE" also takes the original X as a features input, and the original y as the target input # - "RF Classifer" takes the concatted feature outputs from "My Imputer" and "OHE" as a features input, and the original y as the target input. # + from rayml.pipelines import ComponentGraph component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'OHE': ['One Hot Encoder', 'X', 'y'], 'RF Classifier': ['Random Forest Classifier', 'My Imputer.x', 'OHE.x', 'y'] # takes in multiple feature inputs } cg_simple = ComponentGraph(component_dict) # - # All component graphs must end with one final or terminus node. This can either be a transformer or an estimator. Below, the component graph is invalid because has two terminus nodes: the "RF Classifier" and the "EN Classifier". # Can't instantiate a component graph with more than one terminus node (here: RF Classifier, EN Classifier) component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'RF Classifier': ['Random Forest Classifier', 'My Imputer.x', 'y'], 'EN Classifier': ['Elastic Net Classifier', 'My Imputer.x', 'y'] } # Once we have defined a component graph, we can instantiate the graph with specific parameter values for each component using `.instantiate(parameters)`. All components in a component graph must be instantiated before fitting, transforming, or predicting. # # Below, we instantiate our graph and set the value of our Imputer's `numeric_impute_strategy` to "most_frequent". cg_simple.instantiate({'My Imputer': {'numeric_impute_strategy': 'most_frequent'}}) # ## Components in the Component Graph # # You can use `.get_component(name)` and provide the unique component name to access any component in the component graph. Below, we can grab our Imputer component and confirm that `numeric_impute_strategy` has indeed been set to "most_frequent". cg_simple.get_component('My Imputer') # You can also `.get_inputs(name)` and provide the unique component name to to retrieve all inputs for that component. # # Below, we can grab our 'RF Classifier' component and confirm that we use `"My Imputer.x"` as our features input and `"y"` as target input. cg_simple.get_inputs('RF Classifier') # ## Component Graph Computation Order # # Upon initalization, each component graph will generate a topological order. We can access this generated order by calling the `.compute_order` attribute. This attribute is used to determine the order that components should be evaluated during calls to `fit` and `transform`. cg_simple.compute_order # ## Visualizing Component Graphs # # # We can get more information about an instantiated component graph by calling `.describe()`. This method will pretty-print each of the components in the graph and its parameters. # Using a more involved component graph with more complex edges component_dict = { "Imputer": ["Imputer", "X", "y"], "Target Imputer": ["Target Imputer", "X", "y"], "OneHot_RandomForest": ["One Hot Encoder", "Imputer.x", "Target Imputer.y"], "OneHot_ElasticNet": ["One Hot Encoder", "Imputer.x", "y"], "Random Forest": ["Random Forest Classifier", "OneHot_RandomForest.x", "y"], "Elastic Net": ["Elastic Net Classifier", "OneHot_ElasticNet.x", "Target Imputer.y"], "Logistic Regression": [ "Logistic Regression Classifier", "Random Forest.x", "Elastic Net.x", "y", ], } cg_with_estimators = ComponentGraph(component_dict) cg_with_estimators.instantiate({}) cg_with_estimators.describe() # We can also visualize a component graph by calling `.graph()`. cg_with_estimators.graph() # ## Component graph methods # # Similar to the pipeline structure, we can call `fit`, `transform` or `predict`. # # We can also call `fit_features` which will fit all but the final component and `compute_final_component_features` which will transform all but the final component. These two methods may be useful in cases where you want to understand what transformed features are being passed into the last component. # + from rayml.demos import load_breast_cancer X, y = load_breast_cancer() component_dict = { 'My Imputer': ['Imputer', 'X', 'y'], 'OHE': ['One Hot Encoder', 'My Imputer.x', 'y'] } cg_with_final_transformer = ComponentGraph(component_dict) cg_with_final_transformer.instantiate({}) cg_with_final_transformer.fit(X, y) # We can call `transform` for ComponentGraphs with a final transformer cg_with_final_transformer.transform(X, y) # + cg_with_estimators.fit(X, y) # We can call `predict` for ComponentGraphs with a final transformer cg_with_estimators.predict(X)
docs/source/user_guide/component_graphs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # + [markdown] tags=[] # # Cross-Validation in scikit-learn # # <a href="https://colab.research.google.com/github/thomasjpfan/ml-workshop-intermediate-1-of-2/blob/master/notebooks/01-cross-validation.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a> # - # Install dependencies for google colab import sys if 'google.colab' in sys.modules: # %pip install -r https://raw.githubusercontent.com/thomasjpfan/ml-workshop-intermediate-1-of-2/master/requirements.txt import sklearn assert sklearn.__version__.startswith("1.0"), "Plese install scikit-learn 1.0" import seaborn as sns sns.set_theme(context="notebook", font_scale=1.2, rc={"figure.figsize": [10, 6]}) sklearn.set_config(display="diagram") # ## Load sample data # + from sklearn.datasets import fetch_openml from sklearn.model_selection import train_test_split spam = fetch_openml(data_id=44, as_frame=True) X, y = spam.data, spam.target y = y.cat.codes # - print(spam.DESCR) X_train, X_test, y_train, y_test = train_test_split( X, y, random_state=42, stratify=y) # ## Cross validation for model selection # ### Try DummyClassifier from sklearn.model_selection import cross_val_score from sklearn.dummy import DummyClassifier dummy_clf = DummyClassifier(strategy="prior") dummy_scores = cross_val_score(dummy_clf, X_train, y_train) dummy_scores dummy_scores.mean() # ### Try KNeighborsClassifier # + from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler knc = make_pipeline(StandardScaler(), KNeighborsClassifier()) knc_scores = cross_val_score(knc, X_train, y_train) # - knc_scores knc_scores.mean() # ### Try LogisticRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression log_reg = make_pipeline( StandardScaler(), LogisticRegression(random_state=0) ) log_reg_scores = cross_val_score(log_reg, X_train, y_train) log_reg_scores log_reg_scores.mean() # ### Which model do we choose? # # 1. Dummy # 2. KNeighborsClassifier # 3. LogisticRegression # ## Exercise 1 # # 1. Is the target, `y`, balanced? (**Hint**: `value_counts`) # 2. Train the best model on the training set and evaluate on the test data. # 3. **Extra**: Try the `scoring='roc_auc'` to change the return the roc auc score. Which model performs the best in this case? # **If you are running locally**, you can uncomment the following cell to load the solution into the cell. On **Google Colab**, [see solution here](https://github.com/thomasjpfan/ml-workshop-intermediate-1-of-2/blob/master/notebooks/solutions/01-ex01-solutions.py). # + # # %load solutions/01-ex01-solutions.py # - # ## Cross validation Strategies # ### KFold # + from sklearn.model_selection import KFold cross_val_score( log_reg, X_train, y_train, cv=KFold(n_splits=4)) # - # ## Repeated KFold # + from sklearn.model_selection import RepeatedKFold scores = cross_val_score( log_reg, X_train, y_train, cv=RepeatedKFold(n_splits=4, n_repeats=2)) # - scores scores.shape # ## StratifiedKFold # + from sklearn.model_selection import StratifiedKFold scores = cross_val_score( log_reg, X_train, y_train, cv=StratifiedKFold(n_splits=4)) # - scores # This is a binary classification problem: y.value_counts() # Scikit-learn will use `StratifiedKFold` by default: cross_val_score(log_reg, X_train, y_train, cv=4) # ## RepeatedStratifiedKFold # + from sklearn.model_selection import RepeatedStratifiedKFold scores = cross_val_score( log_reg, X_train, y_train, cv=RepeatedStratifiedKFold(n_splits=4, n_repeats=3)) # - scores scores.shape # ## Exercise 2 # # 1. Use `sklearn.model_selection.cross_validate` instead of of `cross_val_score` with `cv=4`. # 2. What additional information does `cross_validate` provide? # 3. Set `scoring=['f1', 'accuracy']` in `cross_validate`'s evalute on multiple metrics. from sklearn.model_selection import cross_validate import pandas as pd # **If you are running locally**, you can uncomment the following cell to load the solution into the cell. On **Google Colab**, [see solution here](https://github.com/thomasjpfan/ml-workshop-intermediate-1-of-2/blob/master/notebooks/solutions/01-ex02-solutions.py). # + # # %load solutions/01-ex02-solutions.py # - # ### Appendix: TimeSeriesSplit # + from sklearn.model_selection import TimeSeriesSplit import numpy as np X = np.arange(10) # - tscv = TimeSeriesSplit(n_splits=3) for train_index, test_index in tscv.split(X): print("TRAIN:", train_index, "TEST:", test_index) # With `gap=2`: tscv_gap = TimeSeriesSplit(n_splits=3, gap=2) for train_index, test_index in tscv_gap.split(X): print("TRAIN:", train_index, "TEST:", test_index)
notebooks/01-cross-validation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import pandas as pd import numpy as np # %matplotlib inline import matplotlib import matplotlib.pyplot as plt from IPython.display import set_matplotlib_formats set_matplotlib_formats('retina') # - # This notebook shows some basics stats about securities labeled as NC1 # ## Load Data data = pd.DataFrame([]) for n in range(2,8): file_name = 'trimmed_'+ str(2000+n) +'_v3_USE.csv' df = pd.read_csv(file_name) rows = df.shape[0] year = {'Year' : ([str(2000+n)]*rows)} year_df = pd.DataFrame(data=year) df = pd.concat([df, year_df], axis=1) data = data.append(df,ignore_index=True) #Get all rows with NC1 nc1 = data.loc[data['Label'] == 'NC1'] # ## Data Validation print('we have {} rows of data'.format(data.shape[0])) print('we have {} rows of NC1'.format(nc1.shape[0])) print('percentage: {:.2f}%'.format(nc1.shape[0]/data.shape[0]*100)) valid = nc1.groupby(by=['Year','Label'])['CUSIP','PID'].size().sum() == nc1.shape[0] print("Does nc1.groupby(by=['Year','Label'])['CUSIP','PID'] equal number of rows in nc1? {}".format(valid)) valid = data.groupby(by=['Year','Label'])['CUSIP','PID'].size().sum() == data.shape[0] print("Does data.groupby(by=['Year','Label'])['CUSIP','PID'] equal number of rows in data? {}".format(valid)) if (valid): print("This ensures ['CUSIP','PID'] shows uniqueness.") print('Number of NC1 in given year. Note:2008 does not have NC1') nc1.groupby(by=['Year','Label'])['CUSIP','PID'].size() print('Ratio of NC1/All in given year:') nc1.groupby(by=['Year','Label'])['CUSIP','PID'].size()/data.groupby(by=['Year'])['CUSIP','PID'].size() valid = (data.loc[data['Label'] != 'NC1'].shape[0]) == data.shape[0]-nc1.shape[0] print("Is data.loc[data['Label'] != 'NC1'] valid for geting non-NC1? {}".format(valid)) # ## Explore NC1 count = nc1.groupby('PID')['CUSIP'].nunique().count() print('There are ' + str(count) + ' of prospectus that have NC1 with unique CUSIP') print("On average {:.2f} NC1 per prospectus that has NC1".format(nc1.shape[0]/count)) # + #These two are different because CUSIP is not unique #nc1.groupby('PID')['CUSIP'].size().sum() #nc1.groupby('PID')['CUSIP'].nunique() # - show_top = 5 print('Top {} of the MTG_TRANCHE_TYP_LONG among NC1 are:'.format(show_top)) nc1.groupby(['MTG_TRANCHE_TYP_LONG'])['CUSIP','PID'].size().sort_values(ascending=False).head(show_top) print('Top {} of the MTG_TRANCHE_TYP_LONG among non-NC1s are:'.format(show_top)) data.loc[data['Label'] != 'NC1'].groupby(['MTG_TRANCHE_TYP_LONG'])['CUSIP','PID'].size().sort_values(ascending=False).head(show_top) # [See here for more info about MTG_TRANCHE_TYP](https://docs.google.com/spreadsheets/d/1MOwPnTr2owqPoJNy73U7UEc3z1RvtzELOCM0ZFxBJU8/edit?usp=sharing) nc1_total = nc1['MTG ORIG AMT'].sum() nonNC1_total = data.loc[data['Label'] != 'NC1']['MTG ORIG AMT'].sum() print('Sum of MTG ORIG AMT among NC1 = {:.2f}'.format(nc1_total)) print('Sum of MTG ORIG AMT among non-NC1 = {:.2f}'.format(nonNC1_total)) print('Sum of MTG ORIG AMT among all = {:.2f}'.format(nc1_total+nonNC1_total)) print('MTG ORIG AMT among NC1 / MTG ORIG AMT of all = {:.2f}%'.format(nc1_total/(nc1_total+nonNC1_total)*100)) print('Desciption of MTG ORIG AMT among NC1:') nc1['MTG ORIG AMT'].describe() # ## To do # - Look into Bloomberg (Paydown Infomation) <br> # API found, can actually use excel on Bloomberg terminal to get the HIST_UNSUPPORTED_RISK_SHORTFALL data quickly # - Look why payment just suddenly stops instead of gradually decreased and stoped # # ## Finding duplicatations # The CUSIP in dataset is duplicated. The uniqueness is determined by using both CUSIP and PID. The way of finding duplicated CUSIP is the following: # This line of code shows that CUSIP is not unique in the dataset. Using count is to count the total number of rows, but using nunique is to count unique. I think both method will be handy in different situations. The Falses in result shows that two ways of counting are different. data.groupby('Label')['CUSIP'].size() == data.groupby('Label')['CUSIP'].nunique() CUSIP_PID_count = data.groupby(by=['CUSIP','PID'])['CUSIP','PID'].nunique().sum() CUSIP_PID_count print('CUSIP and PID agree but does not equal to number of rows. We have {} rows of data'.format(data.shape[0])) print('The difference is {}'.format(data.shape[0]-CUSIP_PID_count[0])) # Duplicated rows are found below data.groupby(by=['CUSIP','PID']).size().sort_values(ascending=False).head() # Theese two rows are he same data.loc[data['CUSIP'] == '576434DB7'] # data.duplicated() helps us find duplicated rows and True means it is duplicated data.duplicated().sort_values(ascending=False).head() num_duplicated = data.loc[data.duplicated(keep=False)].shape[0] print('keep=false shows all duplicated instace so there are {} rows that are duplicated.'.format(num_duplicated)) num_to_delete = data.loc[data.duplicated()].shape[0] print('No keep parameter shows duplicated instace that we should delete so there are {} rows' 'that are duplications that should be deleted.'.format(num_to_delete)) print('That will give us {}'.format(num_duplicated-num_to_delete)) # Use new variable no_duplicated_data using drop_duplicates() no_duplicated_data = data.drop_duplicates() if (((data.shape[0]-CUSIP_PID_count[0])-(num_duplicated-num_to_delete))==0): print('No!! Data rows and CUSIP_PID still not match') else: print('Total Number Match!!!!') no_duplicated_data.groupby(by=['CUSIP','PID']).size().sort_values(ascending=False).head() no_duplicated_data.groupby(by=['CUSIP'])['PID'].nunique().sort_values(ascending=False).head() no_duplicated_data.loc[no_duplicated_data['CUSIP'] == '05948KXX2'] no_duplicated_data.loc[no_duplicated_data['CUSIP'] == '576434AH7'] no_duplicated_data.groupby(by=['CUSIP','PID','Current_Balance']).size().sort_values(ascending=False).head() no_duplicated_data.loc[no_duplicated_data['CUSIP'] == '81744Mar3'] no_duplicated_data.groupby(by=['CUSIP','PID','Current_Balance','norm_class']).size().sort_values(ascending=False).head() no_duplicated_data.loc[no_duplicated_data['CUSIP'] == '576434AE4'] no_duplicated_data.groupby(by=['CUSIP','PID','Current_Balance','norm_class','MTG_TRANCHE_TYP_LONG']).size().sort_values(ascending=False).head() # Here is the way to find what CUSIPs are duplicated. (Here only shows the top five and bottom five results which are all >1). The series can be exported using pandas function #Get series of CUSIP and get count > 1 series = data.groupby(by=['CUSIP']).size().sort_values(ascending=False) series = series.loc[series > 1] series.head() series.tail()
Notebooks/Securities Level Data/Label_Securities_v3_USE_Data_Validation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + def gcd(a, b): """Calcular el mayor divisor común de a y b. A menos que b==0, el resultado tendrá el mismo signo que b (de modo que cuando b se divide por ella, el resultado sale positivo). """ while b: a, b = b, a % b return a def fraccion_irreducible(numes): nume = str(numes) num = float(nume) if num > 0.9999: return "El número debe de estar comprendido entre 0.9999 y 0.0001" if num < 0.0001: return "El número debe de estar comprendido entre 0.9999 y 0.0001" numero = num denominador = 10000 numerador = numero*10000 denominador = round(denominador) numerador = round(numerador) common_divisor = gcd(numerador, denominador) (reduced_num, reduced_den) = (numerador / common_divisor, denominador / common_divisor) if reduced_den == 1: # return "%d/%d se simplifica a %d" % (numerador, denomominador, reduced_num) return "El Resultado es %d" % (reduced_num) elif common_divisor == 1: # return "%d/%d ya está en su estado más simplificado" % (numerador, denominador) return "El restulado es %d/%d" % (numerador, denominador) else: # return "%d/%d simplifica a %d/%d" % (numerador, denominador, reduced_num, reduced_den) return "El resultado es %d/%d" % (reduced_num, reduced_den) # - fraccion_irreducible(0.1687)
tarea_21/fraccion_irreducible.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # %matplotlib inline # %load_ext autoreload # %autoreload 2 import initdirs # + import cv2 import numpy as np from matplotlib import pyplot as plt from skimage import data import nxpd nxpd.nxpdParams['show'] = 'ipynb' # + from epypes import compgraph from visioncg import regions from visioncg import circles from visioncg import improc from visioncg import io from visioncg import viz # - im = data.coins() def get_circle_data_from_keypoints(keypoints): circles = [[p.pt[0], p.pt[1], p.size / 2.] for p in keypoints] return np.array(circles) # + func_dict = { 'threshold': regions.threshold_binary, 'invert': improc.invert, 'hough_circles': circles.hough_circles, 'blur': improc.gaussian_blur, 'find_blobs': circles.detect_circular_blobs, 'canny': cv2.Canny, 'get_circles_from_kp': get_circle_data_from_keypoints, 'dilate': improc.dilate, 'find_ccomp': regions.find_ccomp, } func_io = { 'threshold': (('image', 't_val'), 'image_t'), 'invert': ('image', 'image_inv'), 'hough_circles': (('edges', 'hough_dp', 'hough_min_dist'), 'hcircles'), 'blur': (('image', 'blur_kernel'), 'im_blurred'), 'find_blobs': ('image_inv', 'blobs_kp'), 'get_circles_from_kp': ('blobs_kp', 'blobs_circles'), 'canny': (('im_blurred', 'canny_lo', 'canny_hi'), 'edges'), 'dilate': (('image_t', 'dilate_kernel_size'), 'image_t_dilated'), 'find_ccomp': ('image_t_dilated', ('labels', 'ccomp_df')), } params = { 't_val': 120, 'hough_dp': 2, 'hough_min_dist': 5, 'blur_kernel': 13, 'canny_lo': 100, 'canny_hi': 150, 'dilate_kernel_size': 5, } cg = compgraph.CompGraph(func_dict, func_io) runner = compgraph.CompGraphRunner(cg, params) nxpd.draw(runner.to_networkx()) # - # + runner.run(image=im) plt.figure(figsize=(14, 11)) plt.subplot(3, 3, 1) _ = plt.imshow(runner['image'], vmin=0, vmax=255) _ = plt.axis('off') _ = plt.title('Original image') plt.subplot(3, 3, 2) _ = plt.imshow(runner['image_t']) _ = plt.axis('off') _ = plt.title('Thresholded image') plt.subplot(3, 3, 3) _ = plt.imshow(runner['image_inv']) _ = plt.axis('off') _ = plt.title('Original image inverted') plt.subplot(3, 3, 4) plt.imshow(runner['edges'], cmap='gray') viz.plot_circles(runner['hcircles'], color='yellow') _ = plt.axis('off') _ = plt.title('Canny edges and Hough circles') plt.subplot(3, 3, 5) _ = plt.imshow(runner['image'], cmap='gray') viz.plot_circles(runner['blobs_circles'], color='yellow') _ = plt.axis('off') _ = plt.title('Circular blobs') plt.subplot(3, 3, 6) _ = plt.imshow(runner['image_t_dilated']) _ = plt.axis('off') _ = plt.title('Thresholded dilated image') plt.subplot(3, 3, 7) _ = plt.imshow(runner['labels'], cmap='Paired') _ = plt.axis('off') viz.plot_ccomp(runner['ccomp_df'], color_centroids='blue') _ = plt.title('Connected components') plt.subplot(3, 3, 8) _ = plt.imshow(regions.ccomp_bbox_subimage(im, runner['ccomp_df'], 3)) _ = plt.axis('off') _ = plt.title('Connected component #3') # -
notebooks/demo_circles.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # + # #!/usr/bin/env python # vim:fileencoding=utf-8 import sys import numpy as np import matplotlib.pyplot as plt import soundfile as sf import matplotlib import pandas as pd #データセットの分割 from sklearn.model_selection import train_test_split # - #深層学習ライブラリ from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.layers.recurrent import SimpleRNN from keras.optimizers import Adam from keras.callbacks import EarlyStopping # + #音楽ファイル Music_file = './Input/01_Radio/NHKRadio.wav' Music_noise_file = './Input/01_Radio/NHKRadio_brownnoise.wav' MusicType = 'NHK Radio' MusicFileName = 'NHKRadio' NoiseType = 'Brownnoise' # - # + # wavファイル読み込み Music_wav, Music_fs = sf.read(Music_file) # ステレオ2chの場合、モノラル音源に変換(左右の各音を2で割った音を足して作成.) if(Music_wav.shape[1] == 1): Music_wavdata = Music_wav print(Music_wav.shape[1]) else: Music_wavdata = (0.5 * Music_wav[:, 1]) + (0.5 * Music_wav[:, 0]) # + # wavファイル読み込み Music_whitenoise_wav, Music_whitenoise_fs = sf.read(Music_noise_file) # ステレオ2chの場合、モノラル音源に変換(左右の各音を2で割った音を足して作成.) if(Music_whitenoise_wav.shape[1] == 1): Music_whitenoise_wavdata = Music_whitenoise_wav print(Music_whitenoise_wav.shape[1]) else: Music_whitenoise_wavdata = (0.5 * Music_whitenoise_wav[:, 1]) + (0.5 * Music_whitenoise_wav[:, 0]) # - # + #時間軸(信号の場合はLength) #x = range(300) x = range(500) #Y軸は信号データ #y = Music_whitenoise_wavdata[:300] y = Music_whitenoise_wavdata[:500] #学習のフレーム l = 150 #関数 #信号データと学習のフレームを使用 def make_dataset(y, l): data = [] target = [] for i in range(len(y)-l): data.append(y[i:i+l]) target.append(y[i + l]) return(data, target) #関数呼び出しでデータセットを作成 (data, target) = make_dataset(y, l) # - # + #1フレームのデータ #data[0] #len(data[0]) #len(data) #target #len(target) # - #RNN用のデータセットを作成 #ここで3次元データセットを作成しなくてはならない data = np.array(data).reshape(-1, l, 1) # + num_neurons = 1 n_hidden = 200 model = Sequential() model.add(SimpleRNN(n_hidden, batch_input_shape=(None, l, num_neurons), return_sequences=False)) model.add(Dense(num_neurons)) model.add(Activation('linear')) optimizer = Adam(lr = 0.001) model.compile(loss="mean_squared_error", optimizer=optimizer) #model.compile(loss="mean_squared_logarithmic_error", optimizer=optimizer) #model.compile(loss="mean_absolute_percentage_error", optimizer=optimizer) #model.compile(loss="cosine_similarity", optimizer=optimizer) #model.compile(loss="mean_absolute_error", optimizer=optimizer) #early_stopping = EarlyStopping(monitor='val_loss', mode='auto', patience=20) early_stopping = EarlyStopping(monitor='val_loss', mode='min', patience=20) # - #model.fit(data, target, batch_size=300, epochs=100, validation_split=0.1, callbacks=[early_stopping]) model.fit(data, target, batch_size=300, epochs=100, validation_split=0.1, callbacks=[early_stopping]) # + fig = plt.figure(1) #検証ではノイズがないデータを使用すること pred = model.predict(data) #Y軸のラベル Signal_Ylabel_str = MusicType + 'Signal' + NoiseType RNN_Ylabel_str = 'RNN Pred' + 'Signal' plt.figure(figsize=(15, 4)) plt.subplot(1, 2, 1) plt.xlim(0, 500) plt.plot(x, y, color='blue') plt.xlabel('Original Signal ' + MusicType) plt.ylabel(RNN_Ylabel_str) plt.subplot(1, 2, 2) plt.xlim(0, 500) plt.plot(x[:l], y[:l], color='blue', label=Signal_Ylabel_str) plt.plot(x[l:], pred, color='red', label=RNN_Ylabel_str, linestyle="dotted") plt.xlabel('RNN Prediction of Acoustic Signal(' + MusicType + ')') plt.legend(loc='lower left') #plt.savefig fig.set_tight_layout(True) plt.savefig('./Output/RNN_Pred_Signal/RNN_' + NoiseType + '_' + MusicFileName + '.png') plt.show() # - # + #シグナル値 pd_y = pd.DataFrame(y[:l],columns=["Signal"]) pd_pred = pd.DataFrame(pred,columns=["Signal"]) pd_concat_y = pd.concat([pd_y,pd_pred], axis=0) pd_concat_y = pd_concat_y.reset_index(drop=True) #時間軸 pd_pandas_x = pd.DataFrame(range(500),columns=["Time"]) #信号配列 pd_concat_Signal = pd.concat([pd_pandas_x,pd_concat_y], axis=1) #保存 pd_concat_Signal.to_csv('./Output/RNN_Pred_Signal/RNN_' + NoiseType + '_' + MusicFileName + '.csv') pd_concat_Signal # -
03_RNN_mean_squared_error/32_RNN_Brownnoise_NHKRadio(mean_squared_error).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Geonotebook (Python 2) # language: python # name: geonotebook2 # --- # ### Point annotations # %matplotlib inline from IPython.display import display, Image # + EXPECTED = 'https://data.kitware.com/api/v1/item/589761428d777f07219fcacb/download' M.layers.annotation.clear_annotations() M.set_center(0, 0, 5) M.add_annotation('point', [0, 0]) M.add_annotation('point', [10, 0], {'rgb': 'firebrick'}) M.add_annotation('point', [-10, 0]) M.add_annotation('point', [0, 10], {'rgb': '#295bb5', 'name': 'spam'}) M.add_annotation('point', [0, -10], {'rgb': '#23be1c', 'name': 'eggs'}) display(Image(EXPECTED, format="png")) # - # test drawing point annotations as svg M.layers.annotation.points[0] annotations = M.layers.annotation.serialize()['annotations'] assert annotations[0]['args'] == ([0, 0],) assert annotations[1]['kwargs']['rgb'] == 'firebrick' assert annotations[3]['kwargs']['name'] == 'spam' assert list(M.layers.annotation.points[0].data) == [] annotations # ### Rectangle annotations # + EXPECTED = 'https://data.kitware.com/api/v1/item/589765518d777f07219fcace/download' M.layers.annotation.clear_annotations() M.set_center(0, 0, 5) M.add_annotation('rectangle', [[0, 0], [0, -10], [-10, -10], [-10, 0]]) M.add_annotation('rectangle', [[10, 5], [10, 10], [20, 10], [20, 5]], {'rgb': 'lightgreen'}) M.add_annotation('rectangle', [[10, 0], [15, 0], [15, -15], [10, -15]], {'rgb': 'lightblue', 'name': 'parrot'}) display(Image(EXPECTED, format="png")) # - # test drawing rectangle annotations as svg M.layers.annotation.rectangles[0] annotations = M.layers.annotation.serialize()['annotations'] assert annotations[0]['args'][0] == [[0, 0], [0, -10], [-10, -10], [-10, 0]] assert annotations[1]['kwargs']['rgb'] == 'lightgreen' assert annotations[2]['kwargs']['name'] == 'parrot' assert list(M.layers.annotation.rectangles[0].data) == [] annotations # ### Polygon annotations # + EXPECTED = 'https://data.kitware.com/api/v1/item/589769ba8d777f07219fcad1/download' from math import sin, cos, radians M.layers.annotation.clear_annotations() M.set_center(0, 0, 5) r = 10 def point(angle): angle = radians(angle) return [r * cos(angle), r * sin(angle)] M.add_annotation('polygon', [ point(60 * i) for i in range(6) ], {'rgb': 'red', 'name': 'stop'}) display(Image(EXPECTED, format="png")) # - # test drawing polygon annotations as svg M.layers.annotation.polygons[0] annotations = M.layers.annotation.serialize()['annotations'] assert annotations[0]['args'][0][0] == [10.0, 0.0] assert annotations[0]['kwargs']['rgb'] == 'red' assert annotations[0]['kwargs']['name'] == 'stop' assert list(M.layers.annotation.polygons[0].data) == [] annotations
tests/integration/Annotations.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Este breve tutorial explica alguna de las herramientas básicas de Ciencia de Datos disponibles en Python # # ¿Qué es Python? # - Python es un lenguaje de programación interpretado. # - Su nombre proviene de la afición de su creador original, [Guido van Rossum](https://es.wikipedia.org/wiki/Guido_van_Rossum), por los humoristas británicos [Monty Python](https://es.wikipedia.org/wiki/Monty_Python). # - Características: # - Programación orientada a objetos # - Programación imperativa # - Programación funcional. # - Es multiplataforma y posee una licencia abierta. # # Para una introducción a Python, consulta el [taller de Python impartido en el ASL](https://aulasoftwarelibre.github.io/taller-de-python/) # # Entornos de desarrollo para Python # - Entornos de desarrollo para Python # - [PyCharm](https://www.jetbrains.com/pycharm/) # - [Spyder](https://github.com/spyder-ide/spyder) # - [Visual Studio Code](https://code.visualstudio.com/) # Jupyter Notebooks (libros de notas o cuadernos Jupyter) # ================== # # * Puedes ejecutar un `Cell` (celda) pulsando ``[shift] + [Enter]`` o presionando el botón `Play` en la barra de herramientas. # # ![](images/ipython_run_cell.png) # # * Puedes obtener ayuda sobre una función u objeto presionando ``[shift] + [tab]`` después de los paréntesis de apertura ``function(`` # # ![](images/ipython_help-1.png) # # * También puedes obtener la ayuda ejecutando ``function?`` # # ![](images/ipython_help-2.png) # # [NumPy](https://numpy.org/) # # Librería de cálculo numérico para Python. # - Escrita en C: operaciones muy rápidas # - Permite trabajar con arrays n-dimensionales (vectores, matrices, etc.) # - Contiene un amplio catálogo de operaciones numércias: creación de matrices, operaciones vectoriales, *slicing*, cálculo matricial, polinomios, tratamiento de señales... # # **Todas** las librerías de cálculo científico del ecosistema de Python se basan en NumPy. # # [`pandas`](https://pandas.pydata.org/) # # Herramienta de análisis de datos muy flexible construída sobre NumPy. # # Nos permite trabajar sobre "DataFrames" (datos tabulados) con indices de tipo arbitrario (pueden ser numéricos, etiquetas, fechas...) # # <img src="images/table_dataframe.svg" width="40%"> # # Incluye herramientas para cargar/guardar datos en distintos formatos (CSV, Calc/Excel, JSON...) # ### Carga de datos # # El método `read_csv()` de `pandas` permite dos modos de trabajo: que el propio fichero CSV tenga una fila con los nombres de las variables o que nosotros especifiquemos los nombres de las variables en la llamada. En este caso, vamos a utilizar la segunda aproximación. De esta forma, creamos un array con los nombres de las variables: # + import pandas as pd nombre_variables = ['longitud_sepalo', 'ancho_sepalo', 'longitud_petalo', 'ancho_petalo', 'clase'] # Carga de datos desde la web: descarga el CSV y lo carga como DataFrame iris = pd.read_csv('https://raw.githubusercontent.com/ayrna/tutorial-scikit-learn-IMC/master/data/iris.csv', names = nombre_variables) iris # - # Se trata del dataset ["iris"](https://es.wikipedia.org/wiki/Conjunto_de_datos_flor_iris), un ejemplo típico en *machine learning*. En esta base de datos hay tres clases a predecir, que son tres especies distintas del género *Iris*, de manera que, para cada flor, se extraen cuatro medidas o variables de entrada (longitud y ancho de los pétalos y los sépalos, en cm). Las tres especies a distinguir son *Iris setosa*, *Iris virginica* e *Iris versicolor*. # # Este dataset fue obtenido por el botanista <NAME> y utilizado y popularizado por el biólogo y estadista <NAME> en su artículo de 1936 "*The use of multiple measurements in taxonomic problems*" ("El uso de varias mediciones en problemas de taxonomía"). # # <figure> # <img src="images/iris-machinelearning.png" width="60%"> # <figcaption>Imagen extraída de <a href="https://www.datacamp.com/community/tutorials/machine-learning-in-r">Machine Learning in R for beginners</a></figcaption> # </figure> # ## Inspección de datos # Antes de nada, es conveniente realizar una pequeña **inspección** de los datos. Si simplemente queremos ver la cabecera del dataset, podemos utilizar el método `head(n)`, que devuelve un DataFrame incluyendo los primeros `n` patrones: iris.head(9) # ## Manejo de objetos `DataFrame` y matrices numpy (`ndarray`) # Los [`DataFrame`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) son objetos que representan a los *datasets* con los que vamos a operar. Permiten realizar muchas operaciones de forma automática, ayudando a transformar las variables de forma muy cómoda. Internamente, el dataset se guarda en un array bidimensional de `numpy` (clase [`ndarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html)). # `pandas` nos da la ventaja de poder utilizar las etiquetas de fila (`index`) y columna (`column`) para seleccionarlas de forma más explícita. # # Esto además permite **mezclar tipos de datos** (los array de NumPy deben ser homogéneos) en caso de que lo necesitemos. # # Para extraer columnas específicas podemos usar los corchetes `[]`: iris['ancho_sepalo'] # Las columnas son objetos de tipo "Series" iris[['ancho_sepalo', 'longitud_sepalo']] # Podemos extraer varias columnas a la vez # en formato DataFrame # Para seleccionar filas y columnas específicas de de un [`DataFrame`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) especificando sus etiquetas, utilizamos la propiedad `loc` de la siguiente manera: # - `df.loc[i,j]`: accede al valor de la fila con etiqueta `i` y columna con etiqueta `j`. # - `df.loc[[a, b, c], :]`: devuelve otro `DataFrame` sólo con las filas `a`, `b` y `c`. # - `df.loc[:, [d, e, f]]`: ídem, pero para las columnas. # - `df.loc[[a, b, c], [d, e, f]]`: podemos combinar filas y columnas. # # Si, en cambio, queremos utilizar índices enteros lo haríamos usando la propiedad `iloc` de la siguiente manera: # - `df.iloc[i,j]`: accede al valor de la fila `i` columna `j`. # - `df.iloc[i:j,k]`: devuelve otro `DataFrame` con la subtabla correspondiente a las filas desde la `i` hasta la `j-1` y a la columna `k`. # - `df.iloc[i:j,k:l]`: devuelve otro `DataFrame` con la submatriz correspondiente a las filas desde la `i` hasta la `j-1` y a las columnas desde la `k` hasta la `l-1`. # - `df.iloc[i:j,:]`: devuelve otro `DataFrame` con la submatriz correspondiente a las filas desde la `i` hasta la `j-1` y **todas** las columnas. # - `df.iloc[:,i:j]`: devuelve otro `DataFrame` con la submatriz correspondiente a **todas** las filas y a las columnas desde la `k` hasta la `l`. # # De esta forma: iris.loc[7, 'ancho_petalo'] # Esto seleccionará las filas cuya etiqueta es 1, 10 y 20 # y las columnas cuya etiqueta es 'ancho_petalo', 'longitud_sepalo' o 'clase' iris.loc[[1, 10, 20], ['ancho_petalo', 'longitud_sepalo', 'clase']] iris.iloc[10:20, 3:5] # El acceso a los elementos de un [`DataFrame`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html) con `iloc` es similar a obtener su [`ndarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) de NumPy subyacente, con la desventaja de no poder trabajar con datos mixtos (números y cadenas, por ejemplo). Para lo cual simplemente tenemos que utilizar el atributo `values`: iris.values # La sintaxis de indexación en un [`ndarray`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html) es la siguiente: # - `array[i,j]`: accede al valor de la fila `i` columna `j`. # - `array[i:j,k]`: devuelve otro `ndarray` con la submatriz correspondiente a las filas desde la `i` hasta la `j-1` y a la columna `k`. # - `array[i:j,k:l]`: devuelve otro `ndarray` con la submatriz correspondiente a las filas desde la `i` hasta la `j-1` y a las columnas desde la `k` hasta la `l`. # - `array[i:j,:]`: devuelve otro `ndarray` con la submatriz correspondiente a las filas desde la `i` hasta la `j-1` y **todas** las columnas. # - `array[:,i:j]`: devuelve otro `ndarray` con la submatriz correspondiente a **todas** las filas y a las columnas desde la `k` hasta la `l`. # De esta forma: iris_array = iris.values print(iris_array[:,0]) # Mostrar el array es menos bonito iris_array[0:2,2:4] iris_array[1:6,:] # Vemos que el acceso a través del `ndarray` es, por lo general, más cómodo, ya que no requerimos del nombre de las variables, aunque es menos explícito. Ahora vamos a manejar una matriz de valores aleatorios, para ver algunas características adicionales. # + import numpy as np # Semilla de números aleatorios (para reproducibilidad) rnd = np.random.RandomState(seed=123) # Generar una matriz aleatoria X = rnd.uniform(low=0.0, high=1.0, size=(3, 5)) # dimensiones 3x5 X # + # Acceder a los elementos # Obtener un único elemento # (primera fila, primera columna) print(X[0, 0]) # Obtener una fila # (segunda fila) print(X[1]) # Obtener una columna # (segunda columna) print(X[:, 1]) # - # $$\begin{bmatrix} # 1 & 2 & 3 & 4 \\ # 5 & 6 & 7 & 8 # \end{bmatrix}^T # = # \begin{bmatrix} # 1 & 5 \\ # 2 & 6 \\ # 3 & 7 \\ # 4 & 8 # \end{bmatrix} # $$ # # # Obtener la traspuesta print(X) print(X.T) # Crear un vector de números con la misma separación # sobre un intervalo prefijado y = np.linspace(start=0, stop=12, num=5) print(y) # Transformar el vector en un vector fila print(y[np.newaxis, :]) # Transformar el vector en un vector columna print(y[:, np.newaxis]) # Indexar según un conjunto de números enteros indices = np.array([3, 1, 0]) print(indices) X[:, indices] # ## Vectorización de operaciones # Cuando usamos NumPy en Python, al igual que en otros lenguajes de programación como R o Matlab, debemos intentar, siempre que sea posible, *vectorizar* las operaciones. Esto es utilizar operaciones matriciales en lugar de bucles que recorran los arrays. La razón es que este tipo de operaciones están muchos más optimizadas y que el proceso de referenciación de *arrays* puede consumir mucho tiempo. # Imaginemos que queremos imprimir el área de sépalo de todas las flores. Compara la diferencia entre hacerlo mediante un bucle `for` y mediante operaciones matriciales: # + # Generar un array con el área del sépalo (longitud*anchura), utilizando un for: # Crear un array vacío areaSepaloArray = np.empty(iris_array.shape[0], dtype=np.float32) # Bucle for for i in range(iris_array.shape[0]): areaSepaloArray[i] = iris_array[i,0] * iris_array[i,1] print(areaSepaloArray) # - # Generar un array con el área del sépalo (longitud*anchura), utilizando operaciones matriciales areaSepaloArray_2 = iris_array[:,0] * iris_array[:,1] areaSepaloArray_2 = areaSepaloArray_2.astype(np.float32) print(areaSepaloArray_2) np.arange(25) # + a1 = np.arange(25).reshape((5, 5)) a2 = np.arange(25, 50).reshape((5, 5)) print(a1) print(a2) a1 + a2 # Suma # - a1 * a2 # Producto elemento a elemento a1.sum() # Suma de todos los elementos a2.sum(axis=0) # Suma de todas las filas # Es más, los `ndarray` permiten aplicar operaciones lógicas, que devuelven otro `ndarray` con el resultado de realizar esas operaciones lógicas: # ¿Qué patrones tienen la longitud del pétalo (variable 2) mayor a 5 unidades? iris_array[:,2] > 5 # A su vez, este `ndarray` se puede usar para indexar el `ndarray` original: # ¿cuál es la clase de los patrones que tienen la longitud del pétalo mayor que 5 unidades? iris_array[iris_array[:,2] > 5,4] # Imagina que ahora queremos imprimir la longitud de sépalo de aquellas flores cuya longitud de sépalo es mayor que 2. Compara la versión con `for` y la versión "vectorizada": # Imprimir las longitudes de sépalo mayores que 3, utilizando un for iris_array = iris.values for i in range(iris_array.shape[0]): valorSepalo = iris_array[i,0] if valorSepalo > 5: print(valorSepalo) # Imprimir las longitudes de sépalo mayores que 2, utilizando operaciones matriciales print(iris_array[iris_array[:,0] > 5, 0].shape) # Podemos usar algunas funciones adicionales sobre objetos de tipo `ndarray`. Por ejemplo, las funciones [`numpy.mean`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.mean.html) y [`numpy.std`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html) nos sirven para calcular la media y la desviación típica, respectivamente, de los valores contenidos en el `ndarray` que se pasa como argumento. # # Por último, podemos realizar operaciones matriciales con los `ndarray` de forma muy simple y optimizada. La función [`numpy.dot`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html) multiplica dos `ndarray`, siempre que sus dimensiones sean compatibles. La función [`numpy.transpose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html) nos devuelve la traspuesta de la matriz. # + a = [[1, 0], [0, 1]] b = [[4, 1], [2, 2]] np.dot(a, b) # - # **Ejercicio**: Prueba a imprimir la media y la desviación típica del área de sépalo aquellas flores que son de tipo *virginica*. # # [Matplotlib](https://matplotlib.org/) # Una parte muy importante del aprendizaje automático es la visualización de datos. La herramienta más habitual para esto en Python es Matplotlib. Es un paquete extremadamente flexible y ahora veremos algunos elementos básicos. # # Ya que estamos usando los libros (*notebooks*) Jupyter, vamos a usar una de las [funciones mágicas](https://ipython.org/ipython-doc/3/interactive/magics.html) que vienen incluidas en IPython: el modo "*matoplotlib inline*", que dibujará los *plots* directamente en el cuaderno. # %matplotlib inline import matplotlib.pyplot as plt # Dibujar una línea x = np.linspace(0, 10, 100) plt.plot(x, np.sin(x)); # El ; evita que aparezca en la salida de la celda el objeto "plot" # Dibujar un scatter (dispersión) x = np.random.normal(size=500) y = np.random.normal(size=500) plt.scatter(x, y); # + # Mostrar imágenes usando imshow # - Tener en cuenta que el origen por defecto está arriba a la izquierda x = np.linspace(0, 4*np.pi, 100).reshape((1, 100)) y = np.linspace(0, 4*np.pi, 100).reshape((100, 1)) im = y * np.sin(x) * np.cos(y) print(im.shape) plt.imshow(im); # - # (Esta imagen no es más que [una proyección de la función y * sen(x) * cos(y)](https://www.google.es/search?q=y*sin%28x%29*cos%28y%29+from+-6+to+6&dcr=0&ei=rraXYJWIJIymaKDqs6AO&oq=y*sin%28x%29*cos%28y%29+from+-6+to+6&gs_lcp=Cgdnd3Mtd2l6EANQj1JYnFRgoFdoAXAAeACAAVKIAecBkgEBM5gBAKABAaoBB2d3cy13aXrAAQE&sclient=gws-wiz&ved=0ahUKEwiVl4a6r7zwAhUMExoKHSD1DOQQ4dUDCA0&uact=5)) # # Hacer un diagrama de curvas de nivel (contour plot) # - El origen aquí está abajo a la izquierda plt.contour(im); # El modo "widget" en lugar de inline permite que los plots sean interactivos # %matplotlib widget # Plot en 3D from mpl_toolkits.mplot3d import Axes3D ax = plt.axes(projection='3d') xgrid, ygrid = np.meshgrid(x[0,:], y[:,0]) ax.plot_surface(xgrid, ygrid, im, cmap=plt.cm.viridis, cstride=2, rstride=2, linewidth=0); # Hay muchísimos tipos de gráficos disponibles. Una forma útila de explorarlos es mirar la [galería de matplotlib](https://matplotlib.org/stable/gallery/index.html). # # Prueba alguno de estos ejemplos. Por ejemplo, [`path_patch_demo.py`](https://matplotlib.org/mpl_examples/shapes_and_collections/path_patch_demo.py): # + """ Demo of a PathPatch object. """ import matplotlib.path as mpath import matplotlib.patches as mpatches import matplotlib.pyplot as plt fig, ax = plt.subplots() Path = mpath.Path path_data = [ (Path.MOVETO, (1.58, -2.57)), (Path.CURVE4, (0.35, -1.1)), (Path.CURVE4, (-1.75, 2.0)), (Path.CURVE4, (0.375, 2.0)), (Path.LINETO, (0.85, 1.15)), (Path.CURVE4, (2.2, 3.2)), (Path.CURVE4, (3, 0.05)), (Path.CURVE4, (2.0, -0.5)), (Path.CLOSEPOLY, (1.58, -2.57)), ] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) # plot control points and connecting lines x, y = zip(*path.vertices) line, = ax.plot(x, y, 'go-') ax.grid() ax.axis('equal') plt.show() # - # Vamos a utilizar lo que hemos aprendido para visualizar el dataset `iris`. Vamos a extraer los nombres de las clases y asignarles un color colors = ['blue', 'red', 'green'] # Color para cada clase iris_target_names = np.unique(iris['clase']) iris_target_names # + # %matplotlib inline variable = 'longitud_petalo' for nombre, color in zip(iris_target_names, colors): #¿qué hace zip? #Separamos el conjunto en las distintas clases patrones = (iris['clase'] == nombre) plt.hist(iris.loc[patrones, variable], label=nombre, color=color) plt.xlabel(variable) plt.legend(loc='upper right') # - # Recuerda que las variables de entrada eran *['longitud_sepalo', 'ancho_sepalo', 'longitud_petalo', 'ancho_petalo', 'clase']*, sabiendo esto, ¿qué debemos modificar en el código superior para mostrar la longitud del sépalo? # A continuación vamos a representar en un gráfico la relación entre dos variables de entrada, así podremos ver si los patrones tienen algunas características que nos ayuden a crear un modelo lineal. Prueba distintas combinaciones de variables que se representan en los ejes, para ello modifica los valores de *vairable_x* y *variable_y*. # + variable_x = 'ancho_sepalo' variable_y = 'longitud_sepalo' for nombre, color in zip(iris_target_names, colors): patrones = (iris['clase'] == nombre) plt.scatter(iris.loc[patrones, variable_x], iris.loc[patrones, variable_y], label=nombre, c=color) plt.xlabel(variable_x) plt.ylabel(variable_y) plt.legend(loc='upper left'); # - # ¿Has encontrado alguna combinación que haga que los datos sean linealmente separables? # Es un poco tedioso probar todas las posibles combinaciones, ¡y eso que en este ejemplo tenemos pocas variables! # ### Matrices scatterplot # # En lugar de realizar los plots por separado, una herramienta común que utilizan los analistas son las **matrices scatterplot**. # # Estas matrices muestran los scatter plots entre todas las características del dataset, así como los histogramas para ver la distribución de cada característica. # + import pandas as pd clases_numeros, clases_nombres = pd.factorize(iris['clase']) clases_numeros, clases_nombres # - pd.plotting.scatter_matrix(iris, c=clases_numeros, figsize=(8, 8)); # # [`scikit-learn`](https://scikit-learn.org/stable/modules/classes.html) # - Librería que proporciona un amplio conjunto de algoritmos de aprendizaje supervisado y no supervisado a través de una consistente interfaz en Python. # - Publicado bajo licencia BSD y distribuido en muchos sistemas Linux, favorece el uso comercial y educacional. # - Esta librería se ha construido sobre [`SciPy`](http://www.scipy.org/) (*Scientific Python*), la cual ofrece funcionalidad adicional sobre NumPy (algoritmos de grafos, árboles, distancias...) # - Se centra en el modelado de datos y no en cargar y manipular los datos, para lo que utilizaríamos NumPy y `pandas`. Algunas cosas que podemos hacer con `scikit-learn` son: # - Agrupamiento (*clustering*) # - Validación cruzada # - *Datasets* de prueba # - Reducción de la dimensionalidad # - Métodos *ensemble* # - Selección de características (*feature selection*) # - Ajuste de parámetros (*parameter tuning*) # - Las principales ventajas de `scikit-learn` son las siguientes: # - Interfaz consistente ante modelos de aprendizaje automático. # - Proporciona muchos parámetros de configuración. # - Documentación excepcional. # - Desarrollo muy activo. # - Comunidad. # ## División de datos en entrenamiento y test # Aunque a veces nos proporcionan los datos ya divididos en los conjuntos de entrenamiento y test, conviene saber como podríamos realizar esta división. El siguiente código muestra una función que divide los datos de forma aleatoria, utilizando operaciones *vectorizadas*: def dividir_ent_test(dataframe, porcentaje=0.6): """ Función que divide un DataFrame aleatoriamente en entrenamiento y en test. Recibe los siguientes argumentos: - dataframe: DataFrame que vamos a utilizar para extraer los datos - porcentaje: porcentaje de patrones en entrenamiento Devuelve: - train: DataFrame con los datos de entrenamiento - test: DataFrame con los datos de test """ mascara = np.random.rand(len(dataframe)) < porcentaje train = dataframe[mascara] test = dataframe[~mascara] #¿para qué sirve ~? return train, test iris_train, iris_test = dividir_ent_test(iris) iris_train iris_test # Ahora, podemos quedarnos con las columnas correspondientes a las variables de entrada (todas salvo la última) y la correspondiente a la variable de salida (en este caso, la última): # + train_inputs_iris = iris_train.values[:,0:-1] train_outputs_iris = iris_train.values[:,-1] print(train_inputs_iris.shape) print(train_outputs_iris.shape) test_inputs_iris = iris_test.values[:,0:-1] test_outputs_iris = iris_test.values[:,-1] print(test_inputs_iris.shape) print(test_outputs_iris.shape) # - # Si nos proporcionan la base de datos completa para que hagamos nosotros las particiones, todas las clases y funciones del módulo [`sklearn.model_selection`](https://scikit-learn.org/stable/modules/classes.html#module-sklearn.model_selection) de `scikit-learn` nos pueden facilitar mucho la labor. # + from sklearn.model_selection import train_test_split inputs_iris = iris.values[:,0:-1] outputs_iris = iris.values[:,-1] train_inputs_iris, test_inputs_iris, train_outputs_iris, test_outputs_iris = \ train_test_split(inputs_iris, outputs_iris, test_size=0.33, random_state=42, stratify=outputs_iris) print(train_inputs_iris.shape) print(test_inputs_iris.shape) print([sum(train_outputs_iris==etiqueta)/train_outputs_iris.shape[0] for etiqueta in np.unique(outputs_iris)]) # - # ## Labores de preprocesamiento # Sin embargo, `scikit-learn` no acepta cadenas como parámetros de las funciones, todo deben de ser números. Para ello, nos podemos valer del objeto [`sklearn.preprocessing.LabelEncoder`](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html), que nos transforma automáticamente las cadenas a números. La forma en que se utiliza es la siguiente: # + from sklearn.preprocessing import LabelEncoder #Creación del método label_encoder = LabelEncoder() #Entrenamiento del método label_encoder.fit(train_outputs_iris) print(label_encoder.classes_) #Obtención de salidas train_outputs_iris_encoded = label_encoder.transform(train_outputs_iris) test_outputs_iris_encoded = label_encoder.transform(test_outputs_iris) print(train_outputs_iris) print(train_outputs_iris_encoded) # - # Como podéis observar, primero se crea el `LabelEncoder` y luego se "entrena" mediante el método `fit`. Para un `LabelEncoder`, "entrenar" el modelo es decidir el mapeo que vimos anteriormente, en este caso: # - `Iris-setosa` -> 0 # - `Iris-versicolor` -> 1 # - `Iris-virginica` -> 2 # Una vez entrenado, utilizando el método `transform` del `LabelEncoder`, podremos transformar cualquier `ndarray` que queramos (hubiéramos tenido un error si alguna de las etiquetas de test no estuviera en train). Esta estructura (método `fit` más método `transform` o `predict`) se repite en muchos de los objetos de `scikit-learn`. # Hay muchas más tareas de preprocesamiento que se pueden hacer en `scikit-learn`. Consulta el paquete [`sklearn.preprocessing`](http://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing). # ## Crear y evaluar un clasificador # A continuación, vamos a crear un modelo de clasificación y a obtener su matriz de confusión. Vamos a utilizar el clasificador [KNeighborsClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html), que clasifica cada patrón asignándole la clase mayoritaria según los `k` vecinos más cercanos al patrón a clasificar. Consulta siempre la documentación de cada objeto para ver los parámetros del algoritmo (en este caso, el parámetro decisivo es `n_neighbors`). Veamos como se realizaría el entrenamiento: # + from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=3) knn.fit(train_inputs_iris, train_outputs_iris_encoded) print(knn) # - # Ya tenemos el modelo entrenado. Este modelo es de tipo *lazy*, en el sentido de que no existen parámetros a ajustar durante el entrenamiento. Lo único que hacemos es acomodar las entradas en una serie de estructuras de datos que faciliten el cálculo de distancias a la hora de predecir la etiqueta de datos nuevos. Si ahora queremos predecir las etiquetas de test, podemos hacer uso del método `predict`, que aplica el modelo ya entrenado a datos nuevos: prediccion_test = knn.predict(test_inputs_iris) print(prediccion_test) print(test_outputs_iris_encoded) # Si queremos saber cómo de buena ha sido la clasificación, todo modelo de clasificación o regresión en `scikit-learn` tiene un método `score` que nos devuelve la bondad del modelo con respecto a los valores esperados, a partir de las entradas suministradas. La medida por defecto utilizada en [KNeighborsClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html) es el porcentaje de patrones bien clasificados (CCR o *accuracy*). La función se utiliza de la siguiente forma (internamente, esta función llama a `predict`): precision = knn.score(test_inputs_iris, test_outputs_iris_encoded) precision # Esto sería similar a hacer la comparación a mano y calcular la media: np.mean(prediccion_test == test_outputs_iris_encoded) # Para imprimir la matriz de confusión de unas predicciones, podemos utilizar la función [`sklearn.metrics.confusion_matrix`](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix), que nos va devolver la matriz ya formada: from sklearn.metrics import confusion_matrix cm = confusion_matrix(test_outputs_iris_encoded, prediccion_test) print(cm) from sklearn.metrics import plot_confusion_matrix plot_confusion_matrix(knn, test_inputs_iris, test_outputs_iris_encoded)#, display_labels=label_encoder.classes_) # ## Configurar los parámetros de un clasificador # Imagina que quieres configurar el número de vecinos más cercanos (`n_neighbors`), de forma que la precisión en entrenamiento sea lo más alta posible. Lo podríamos hacer de la siguiente forma: for nn in range(1,15): knn = KNeighborsClassifier(n_neighbors=nn) knn.fit(train_inputs_iris, train_outputs_iris_encoded) precisionTrain = knn.score(train_inputs_iris, train_outputs_iris_encoded) precisionTest = knn.score(test_inputs_iris, test_outputs_iris_encoded) print("%d vecinos: \tCCR train = %.2f%%, \tCCR test = %.2f%%" % (nn, precisionTrain*100, precisionTest*100)) # # Ejercicio propuesto para realizar # # La base de datos `german` contiene datos bancarios de crédito de distintos clientes de un banco. El problema que presenta consiste en predecir si se debe o no otorgar un crédito a un cliente específico (decisión binaria). # # Utiliza la base de datos `german` para entrenar dos modelos supervisados de clasificación: # - Uno basado en los k vecinos más cercanos: [KNeighborsClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html). # - Otro basado en un modelo lineal. Vamos a utilizar el modelo de regresión logística: [LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html). # # La base de datos está disponible en la UCI, bajo el nombre [*Statlog (German Credit Data) Data Set*](https://archive.ics.uci.edu/ml/datasets/Statlog+%28German+Credit+Data%29). Bájala y preprocésala para realizar el entrenamiento (utiliza la versión numérica, `german.data-numeric`, observa que los datos no tienen cabecera y utiliza el método `read_csv` de `pandas` especificando correctamente el separador, que en este caso es el uno o más espacios, es decir, `'\s+'`). Divide los datos en 60% de entrenamiento y 40% de test (utiliza la función [train_test_split](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html#sklearn.model_selection.train_test_split)). Tienes que normalizar todas las variables de entrada para que queden en el intervalo `[0,1]` (consulta información sobre [MinMaxScaler](http://scikit-learn.org/stable/modules/preprocessing.html#scaling-features-to-a-range)). Intenta ajustar lo mejor posibles los parámetros de los clasificadores. # # *Corrección*: a fecha de 9/5/2021 el sitio de la UCI está caído, así que en caso de que siga siendo así, tienes el CSV con estos mismos datos en el fichero `resources/german.csv` de este mismo repositorio. En este caso el fichero SÍ tiene cabeceras y el separador es una coma en lugar de espacios. # # Referencias # Este tutorial se ha basado en gran parte en el siguiente material: # - Python como alternativa a R en *machine learning*. <NAME>. [Enlace a Github](https://github.com/MarioPerezEsteso/Python-Machine-Learning). [Enlace a Youtube](https://www.youtube.com/watch?v=8yz4gWt7Klk). # - Tutorial de <NAME> y <NAME> [[Github]](https://github.com/amueller/scipy-2017-sklearn)[[Youtube1]](https://www.youtube.com/watch?v=2kT6QOVSgSg)[[Youtube2]](https://www.youtube.com/watch?v=WLYzSas511I) # # Se recomiendan los siguientes tutoriales adicionales para aprender más sobre el manejo de la librería: # - *An introduction to machine learning with scikit-learn*. Documentación oficial de `scikit-learn`. [http://scikit-learn.org/stable/tutorial/basic/tutorial.html](http://scikit-learn.org/stable/tutorial/basic/tutorial.html). # - *A tutorial on statistical-learning for scientific data processing*. Documentación oficial de `scikit-learn`. [http://scikit-learn.org/stable/tutorial/statistical_inference/index.html](http://scikit-learn.org/stable/tutorial/statistical_inference/index.html). # # Por último, para aprender la sintaxis básica de Python en menos de 13 horas, se recomienda el siguiente curso de *CodeAcademy*: # - Curso de Python de CodeAcademy. [https://www.codecademy.com/es/learn/python](https://www.codecademy.com/es/learn/python)
tutorial.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Bus # # This bus has a passenger entry and exit control system to monitor the number of occupants it carries and thus detect when there is too high a capacity. # # At each stop the entry and exit of passengers is represented by a tuple consisting of two integer numbers. # ``` # bus_stop = (in, out) # ``` # The succession of stops is represented by a list of these tuples. # ``` # stops = [(in1, out1), (in2, out2), (in3, out3), (in4, out4)] # ``` # # ## Goals: # * lists, tuples # * while/for loops # * minimum, maximum, length # * average, standard deviation # # ## Tasks # 1. Calculate the number of stops. # 2. Assign to a variable a list whose elements are the number of passengers at each stop (in-out), # 3. Find the maximum occupation of the bus. # 4. Calculate the average occupation. And the standard deviation. # # variables import statistics stops = [(10, 8), (2, 1), (3, 4), (2, 1)] # 1. Calculate the number of stops. nr_stops = len(stops) print(nr_stops) # 2. Assign a variable a list whose elements are the number of passengers in each stop: # Each item depends on the previous item in the list + in - out. passengers_stop = [] x = 1 passengers_stop.append(stops[0][0] - stops[0][1]) while x < len(stops): passengers_stop.append((stops[x][0] - stops[x][1]) + passengers_stop [x -1] ) x += 1 print(passengers_stop) # 3. Find the maximum occupation of the bus. print(max(passengers_stop)) # 4. Calculate the average occupation. And the standard deviation. avg = sum(passengers_stop)/nr_stops print("The average is ", round(avg,2)) standar_diviation = statistics.stdev(passengers_stop) print("The standar deviation is ", standar_diviation)
bus/bus.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="HicMAaNSY1G4" # # Introduction to Python # # ### Control Flow (solutions) # + colab={} colab_type="code" id="TfihR0LvY1Gz" import time import random # + [markdown] colab_type="text" id="KE1AozqoY1G6" # A brief note about measuring time to run a cell # + colab={} colab_type="code" id="C9BUYrnqY1G7" outputId="2ebe9ec7-7f84-49a4-8ce1-2e2b359286bb" print(time.time()/((3600*24*365)+13)) # The Unix time started in 1970... # + [markdown] colab_type="text" editable=true id="ULDZ9mbMY1HE" # ### 1- Create a script that prints the numbers from 1 to 100, following these rules: # # 1. in those that are multiples of 3, print "Fizz" instead of the number. # 2. in those that are multiples of 5 print "Buzz" instead of the number. # 3. For numbers that are multiples of both 3 and 5, print "FizzBuzz". # + colab={"base_uri": "https://localhost:8080/", "height": 806} colab_type="code" editable=true executionInfo={"elapsed": 807, "status": "ok", "timestamp": 1598109331076, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15890310536056247381"}, "user_tz": 180} id="ySaJy9tqY1HF" outputId="9d0183bf-3675-4200-96d0-200806185125" for i in range(1,101): if i % 3 == 0 and i % 5 == 0: print(i,'FizzBuzz') elif i % 5 == 0: print(i,'Fizz') elif i % 3 == 0: print(i,'Buzz') # + [markdown] colab_type="text" editable=true id="pCdoRHCJY1G_" # ### 2 - Given the list: # + colab={} colab_type="code" editable=true id="4luwSOVzY1G_" list1 = [1,2,3,'4',5,6.3,7.4 + 2j,"123",[1.2,2.5,3.4], 93, "98"] # + [markdown] colab_type="text" editable=true id="xgPrm4WrY1HC" # ### Create a script or function to print each element of a list, along with its predecessor and its successor. Follow these rules: # # 1. If this element is numeric or a string, print its representational value; and # 2. If the element is a container but not a string (tuple, list, dict, set, frozenset), print each element of the sequence. # - for element in list1: if isinstance(element, tuple) or \ isinstance(element, list) or \ isinstance(element, dict) or \ isinstance(element, set) or \ isinstance(element, frozenset): for subelement in element: print(subelement) else: print(element) # + [markdown] colab_type="text" editable=true id="k8ZCuj-dY1HH" # ### 3- Using the "random" library, create a script to average the sum of two 6-sided dice (D6) in 10,000 releases. # + colab={} colab_type="code" id="Rz74LRnQw36W" help(random.randrange) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" executionInfo={"elapsed": 848, "status": "ok", "timestamp": 1598109619778, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15890310536056247381"}, "user_tz": 180} id="b1FZULthY1HM" outputId="1279f72a-e966-4ac3-d37e-65a5c2e90a13" sum_two_dice = [] for i in range(100000): dice1 = random.randint(1,6) dice2 = random.randint(1,6) sum_two_dice.append(dice1 + dice2) print(sum(sum_two_dice)/len(sum_two_dice)) # + [markdown] colab_type="text" id="NcBZiP5CY1HO" # ### 4 - [Project Euler - Problem 3](https://projecteuler.net/problem=3) # # The prime factors of 13195 are 5, 7, 13 and 29. # What is the largest prime factor of the number 600851475143 ? # + [markdown] colab_type="text" id="H-0HvC5p3B6l" # Very slow version # + colab={} colab_type="code" editable=true id="Vjtc6XnYY1HR" def largest_prime(n): #generating primes until n/2 seq = range(3,int(n/2.)+1) primes = [2] for candidate in seq: is_primo = True for prime in primes: if candidate%prime == 0: is_primo = False if is_primo: primes.append(candidate) factors = [] for prime in primes: if n%prime == 0: factors.append(prime) print(factors) return factors # + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" editable=true executionInfo={"elapsed": 623, "status": "ok", "timestamp": 1597532735610, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15890310536056247381"}, "user_tz": 180} id="goRYfUvbY1HS" jupyter={"outputs_hidden": false} outputId="fdf2778d-cf36-4480-8fe8-f64f387384f1" t0 = time.time() largest_prime(13195) print(time.time() - t0) # + colab={} colab_type="code" editable=true id="LmVJ3KLhY1HV" def largest_prime_2(n): primes = [2] prime_candidate = 3 factors = [] while prime_candidate < (int(n/2.)+1): is_primo = True for prime in primes: if prime_candidate%prime == 0: is_primo = False if is_primo: primes.append(prime_candidate) if n%prime_candidate == 0: factors.append(prime_candidate) prime_candidate +=1 print(factors) return factors # + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" editable=true executionInfo={"elapsed": 662, "status": "ok", "timestamp": 1597532738167, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15890310536056247381"}, "user_tz": 180} id="9_UBUN-3Y1HX" outputId="7be98a2f-f042-45f9-efd9-9f78db2d5662" t0 = time.time() largest_prime_2(13195) print(time.time() - t0) # + colab={} colab_type="code" editable=true id="BJ23Zb86Y1HZ" def is_prime(n): if n <= 3: return n >= 2 if n % 2 == 0 or n % 3 == 0: return False for i in range(5, int(n ** 0.5) + 1, 6): if n % i == 0 or n % (i + 2) == 0: return False return True # + colab={} colab_type="code" editable=true id="B2Koy6OcY1Hc" def largest_prime_3(n): factors = [] prime_candidate = 2 while prime_candidate < (int(n/2.)+1): if is_prime(prime_candidate) and n%prime_candidate == 0: factors.append(prime_candidate) prime_candidate +=1 print(factors) return factors # + colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="code" editable=true executionInfo={"elapsed": 217699, "status": "ok", "timestamp": 1597534560527, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "15890310536056247381"}, "user_tz": 180} id="DY3Odr_CY1He" jupyter={"outputs_hidden": false} outputId="508bdfce-5231-4fcb-9d43-bbf8eb020252" t0 = time.time() largest_prime_3(60085131) print(time.time() - t0) # + [markdown] colab_type="text" id="UvTDXLdXvjq2" # ### 5 - [Project Euler - Problem 4](https://projecteuler.net/problem=4) # # #### Largest palindrome product # # "A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99." # # **Find the largest palindrome made from the product of two 3-digit numbers.** # + [markdown] colab_type="text" id="qazTN5OQvjq2" # ###### Hint: How to reverse a string? # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="3LkF9RTxvjq3" jupyter={"outputs_hidden": false} outputId="dcfc0524-67bd-4bc5-dec9-6ef81fa27e87" 'A random string'[-1::-1] # + colab={} colab_type="code" id="extTmjtIvjq8" #storing every product with 3-digit numbers products = set([]) for i in range(100,1000): for j in range(100,1000): products.add(i*j) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="5gnJuhXrF0W5" outputId="4fa1e024-9e3b-439d-9a9e-1b81980bf5a0" len(products) # + colab={} colab_type="code" id="KNjnfejpCTyd" #Testing whether they are palindromes largest_palindrome = 0 for number in products: #transforming the integer into a string (to reverse it!) string_number = str(number) #two logic tests: is it a palindrome? and is it the largest one? if string_number == string_number[-1::-1] and int(string_number) > largest_palindrome: largest_palindrome = int(string_number) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="RnqBYR0MHHwe" outputId="6f6a2355-ae83-45d4-ae95-422efce1f888" print(largest_palindrome) # + [markdown] colab_type="text" id="kMgDWqUovjq_" # ### 6 - [Project Euler - Problem 14](https://projecteuler.net/problem=14) # # #### Longest Collatz sequence # # # The following iterative sequence is defined for the set of positive integers: # # n → n/2 (n is even) # n → 3n + 1 (n is odd) # # Using the rule above and starting with 13, we generate the following sequence: # # 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1 # It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1. # # **Which starting number, under one million, produces the longest chain?** # # NOTE: Once the chain starts the terms are allowed to go above one million. # + colab={} colab_type="code" id="OhW4mTEILN87" # First example seq = [] num = 13 while num != 1: # rule for even numbers if num%2 == 0: num /= 2 else: # rule for odd numbers num = (3*num) + 1 seq.append(int(num)) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="dGZb6UhELRh3" outputId="410f614d-f54f-4f76-8f10-10f32a0e44d5" seq # + colab={} colab_type="code" id="X_9NPZDzvjq_" sequences = [] for i in range(2,1000001): seq = [] num = i # here it is computed the Collatz sequence while num != 1: # rule for even numbers if num%2 == 0: num /= 2 else: # rule for odd numbers num = (3*num) + 1 seq.append(int(num)) #for every number, this list is storing a tuple with the number and the length of its Collatz sequence sequences.append((i,len(seq)+1)) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="vzUaxWulIt5j" outputId="2e265d9f-471f-43ed-94e6-4f530fc4908e" len(sequences) # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" id="S7qQvBIxMJ46" outputId="1db75778-4574-4f14-fb6f-c772fc4219c4" # Same idea of sorting a dictionary sorted(sequences, key = lambda x:x[1], reverse=True)[:1]
Exercises/Exercise_2_Control_Flow_Solutions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # MaD - Macromolecular Descriptors # # This notebook contains all the necessary information to run MaD. If you want to try it fast, just check the code within the minimal examples. You'll find the solutions in the "individual_solutions" and "assembly_models" subfolders within the folder created for your assembly, which is in the main "results" folder. # # Explanations of the basic output is explained in section 1A. # # For the main parameters that has been tweaked at some point for predictions and why, check section 2 C, D E and F. One assembly in the simulated dataset has a different value for one parameter as well. # # All examples apart from the 5 mentioned use default parameters. Meaning, MaD is as plug-and-play as it gets. # # 1. **Minimal examples** # 1. Homomultimer: VAT complex (7 Å) + output explanation # 1. Heteromultimers: NMDA receptor (6 Å) # 1. **Other examples and tweaking parameters** # 1. RAG complex (5 Å) # 1. Actin:tropomyosin (8 Å) # 1. Microtubule and kinesin (9 Å) (tweak) # 1. MecA-ClpC complex (10 Å) (tweak) # 1. Kainate receptor GluK2 (11.6 Å) (tweak) # 1. Beta-galactosidase (13 Å) (tweak) # 1. Simulated assemblies (10 Å) # 1. **Ensemble docking with GroEL** # 1. **Anchor files** # # The testing data may be found on our website: https://www.epfl.ch/labs/lbm/resources/ # Note that you may need to adjust the path to structure files depending on how you downloaded/arranged the software and the testing data. # ## 1. Minimal examples # ### <NAME>: VAT complex # # This minimal code predicts the assembly of the VAT complex, with an experimental map at a resolution of 7 A. A single monomer is considered and the assembly is predicted despite conformational differences between protomers between 1 and 3.5 A of RMSD-Ca, and missing densities in the experimental map. # # For homomultimeric assemblies or repeted components in general, only a single copy of the repeated structure is required. # # Results are saved in the "results" folder. The name of the results folder is built from the filename of the map and those of the components, along with the resolution, number of copies for each component, and isovalue. New attempts on the same system will create folders with an incremented path, e.g. "..._1", "..._2", and so on. # # * Individual component solutions are stored in the "individual_solutions" subfolder. # * Assembly models, if generated, are stored in the "assembly_models" subfolder. # * To look at the files used for docking, a copy is available in the "initial_files" folder for better reproducibility. # * For explanations about the "anchor_files" folder within individual_solutions, please see section 4 "anchor files" # # In general, descriptors will be stored in the "dsc_db" folder. Restarting this example will be faster, as all descriptors have been computed and will only be loaded. # # # + from mad import MaD # Make instance mad = MaD.MaD() # Add map (specify resolution after path), then add components mad.add_map("experimental_data/5g4f/emd_3436_processed.mrc", 7) # Add component and specify number of copies (VAT complex is hexameric) mad.add_subunit("experimental_data/5g4f/5g4f_subunit.pdb", n_copies=6) # Get solutions mad.run() # Build assembly mad.build_assembly() # - # #### Explanation of output # # 1. Descriptors are generated for all structures (anchor detection, orientation, and description). If they're available in the database (dsc_db folder), descriptors are loaded instead. # 1. Matching occurs: # 1. Local descriptor matching: identifies pair that may yield a valid transformation of the subunit into the density. # 1. Filtering: ranking according to global anchor matching, then clustering. One solution per cluster is kept. # 1. Local rigid refinement to fix inaccuracies from anchor coordinates and orientation. # 1. Scoring includes: # 1. Repeat: the repeatability, or percentage of anchors that have a correspondence in the target density. # 1. Weight: the size of the corresponding cluster. The cluster includes the descriptor pairs that agree with that particular localization within the target cryo-EM map. # 1. mCC: map cross-correlation. # 1. RWmCC: the product of the previous scores. It considers structural similarity at all 3 levels considered in our procedure. # 1. Assembly building is simply a combinatorial exploration of the different assemblies respecting the target assembly's stoichiometry. # 1. Pairwise overlap (i.e. structural clashes estimated from non-zero voxel values at same point in space) are computed. The table is shown. Columns are not labelled for visualization purposes but are in the same order as the rows, each one corresponding to a solution in the individual_solutions subfolder. In the case of a heteromultimeric assembly, another folder called "subcomplexes" will be created. It will contain either a copy of the component solutions if a single copy is expected, otherwise it will contain subcomplexes of that component alone at the expected stoichiometry (as defined by the n_copies parameter, see section 2A for an example). # 1. Relevant values are summed depending on the combination of solutions. # 1. Output models are ranked in order of increasing overlap (either sum, standard deviations, or maximum value). # 1. For each model, the cross-correlation (CC) with the target cryo-EM map is reported. The overlap sum, standard deviation and maximum are reported as well. The composition column refers to the individual component solutions that have been combined for the model. Each number corresponds to the index of that solution both in the overlap table and in the individual_solutions folder (or subcomplexes folder if the assembly is heteromultimeric). # ### <NAME>: NMDA receptor # # This starts an example on the NMDA receptor, with an experimental map at a resolution of 6 A. All 5 components are added separately. # # Results are saved in the "results" folder. The name of the results folder is built from the filename of the map and those of the components, along with the resolution, number of copies for each component, and isovalue. New attempts on the same system will create folders with an incremented path, e.g. "..._1", "..._2", and so on. # # * Individual component solutions are stored in the "individual_solutions" subfolder. # * The **"subcomplexes" folder contain the final components used to build heteromultimeric assemblies**. It contains either a copy of the individual solutions if the component is not repeated in the assembly, otherwise, it will contain subcomplexes of that component containing the requested number of copies. This is skipped in the case of homomultimeric assemblies, which was the case in the previous example. # * Assembly models, if generated, are stored in the "assembly_models" subfolder. The "composition" will refer to the files in the subcomplexes folder. # * To look at the files used for docking, a copy is available in the "initial_files" folder for better reproducibility. # * For explanations about the "anchor_files" folder within individual_solutions, please see section 4 "anchor files" # # In general, descriptors will be stored in the "dsc_db" folder. Restarting this example will be faster, as all descriptors have been computed and will only be loaded. # # ##### Notes about output models in this case # 4 models are generated. The first one is the expected model. The second one has two subunits swapped; they correspond to the two GluN1 subunits, which may be swapped despite a slight conformational difference between them. The third shows an inverted position of the Fab domain. This assembly has a lower score than the first two, and the scores of the individual solutions of the Fab clearly clear out any uncertainty (424 vs 6). The fourth model has the swapped GluN1 subunits and the inverted Fab domains. # + from mad import MaD # Make instance mad = MaD.MaD() # Add map (specify resolution after path), then add components mad.add_map("experimental_data/5up2/emd_8581_processed.mrc", 6) mad.add_subunit("experimental_data/5up2/5up2_subA.pdb") mad.add_subunit("experimental_data/5up2/5up2_subB.pdb") mad.add_subunit("experimental_data/5up2/5up2_subC.pdb") mad.add_subunit("experimental_data/5up2/5up2_subD.pdb") mad.add_subunit("experimental_data/5up2/5up2_Fab.pdb") # Get solutions per component mad.run() # Build assembly mad.build_assembly() # - # ## 2. Other examples and tweaking parameters # #### RAG complex at 5 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # # In this case, subB is present in 2 copies. When building the assembly, a subcomplex will be made from its solutions alone before considering the resulting sub-assemblies for final building. This is to minimize the combinatorial cost. Subcomplexes are found in the "subcomplexes" subfolder. # # **Pay attention when looking at the composition of the final model: the index shown refers to subcomplexes for the repeated components.** SubB, for example, has been merged into a subcomplex. # # Subunits A and C are mostly similar, except for a major difference in their Zinc-finger domain's orientation. Both localizations are found from either, but model building highlights the best model through structural clashes. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/6dbl/emd_7845_processed.mrc", 5) mad.add_subunit("experimental_data/6dbl/6dbl_subA.pdb", 1) mad.add_subunit("experimental_data/6dbl/6dbl_subB.pdb", 2) mad.add_subunit("experimental_data/6dbl/6dbl_subC.pdb", 1) mad.run() mad.build_assembly() # - # #### Actin:tropomyosin at 8 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/3j4k/emd_5751_processed.mrc", 8) mad.add_subunit("experimental_data/3j4k/3j4k_subunit.pdb", 5) mad.run() mad.build_assembly() # - # #### Microtubule and kinesin at 9 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # # In this case, the density of the kinesin is poorly resolved, the voxel spacing is large (2 A) and the tubulin protomers have residual densities from nearby subunits. To make sure the solutions are highlighted, a lower cross-correlation threshold for descriptor matching is set (0.5 instead of the default 0.6), and more descriptor pairs are processed during clustering. There is some residual structural clashes after the refinement, probably due to a different docking procedures adopted when the assembly was first published. # # The first model built is the expected model. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/2p4n/emd_1340_processed.mrc", 9) mad.add_subunit("experimental_data/2p4n/2p4n_subA.pdb") mad.add_subunit("experimental_data/2p4n/2p4n_subB.pdb") mad.add_subunit("experimental_data/2p4n/2p4n_subC.pdb") mad.run(cc_threshold=0.5, n_samples=80) mad.build_assembly() # - # #### MecA-ClpC at 10 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # # At these resolutions, secondary structure starts to merge into more uniform densities. This is where a minimum size requirement for components need to be imposed. While the ClpC monomers are fitted successfully, there is not enough information for reliable descriptor to be built for the smaller (~25 kDa) MecA subunits (see figure below) # # The lower resolution requires to tweak the descriptor cross-correlation threshold to 0.5 (down from 0.6 by default) and the number of descriptor pairs for clustering (100, up from 60 by default). # # Regardless, the first model built is the expected model (minus MecA subunits) # <div> # <img src="attachment:Plot_min_MW_per_resolution.png" width="200"/> # </div> # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/3j3u/emd_5609_processed.mrc", 10) mad.add_subunit("experimental_data/3j3u/3j3u_subunit.pdb", 6) mad.run(n_samples=100, cc_threshold=0.5) mad.build_assembly() # - # #### Kainate receptor GluK2 at 11.6 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # # Here, the lower resolution means that individuals secondary elements are not distinguishable and are, instead, merged. As a result, a larger patch diameter needs to be considered in order to build reliable descriptors. As a result, a 24-voxel diameter patch (the voxel spacing at 1.324, yielding a patch of 32 A in diameter). A patch of 20 voxels (26.5 A in diameter) also yields the expected assembly, but more false positives are also highlighted. # # Subunit B is also alternatively located at the positions of subunit A, but the conformational differences makes these locations score lower. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/5kuh/emd_8290_processed.mrc", 11.6) mad.add_subunit("experimental_data/5kuh/5kuh_subA.pdb", 2) mad.add_subunit("experimental_data/5kuh/5kuh_subB.pdb", 2) mad.run(patch_size=24) mad.build_assembly() # - # #### Beta-galactosidase at 13 A # # Do not forget to create a new MaD instance to avoid issues with previously added structures. # # In this assembly, we have 4 copies of B-galactosidase monomers along with small Fab domains. For similar reasons as in the MecA-ClpC complex, the Fab domains cannot be docked using our method due to their small sizes (we estimate a minimum size of 90 to 100 kDa for reliable docking with a resolution of 13 A) (see figure in the section of the MecA-ClpC example). # # Indeed, at these resolutions, only smaller domains may be reliably observed in a density map. This usually means that descriptors should cover a larger volume to be reliable, but not too large to go beyond the size of the subunit. In this case, the voxel spacing is at 3 A, meaning that a subvolume of 3 * 16 voxels = 48 A of diamater is considered. To reduce it to a more manageable volume with less bias, we set the patch_size to 12 voxels instead (36 A in diameter). Other sizes may work as well, but not necessarily find all the expected localizations of the B-galactosidase. # # The lower resolution requires to tweak the descriptor cross-correlation threshold to 0.5 (down from 0.6 by default) and the number of descriptor pairs for clustering (100, up from 60 by default). # # Regardless, the first model built is the expected model (minus Fab domains). # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/4ckd/emd_2548_processed.mrc", 13) mad.add_subunit("experimental_data/4ckd/4ckd_subunit.pdb", 4) mad.run(n_samples=120, patch_size=12) mad.build_assembly() # - # #### Simulated assemblies # # This section covers a set of 21 assemblies simulated at a resolution of 10 Å. # # In general, if the file given to the add_map() function is a PDB file, it will be converted to a density map at the specified resolution. The resulting map is available in the "initial_files" folder of the results folder. # + import os from mad import MaD # Chose assembly in the list ################## assembly_list = ['1cs4','1gpq','1mda','1suv','1tyq','1vcb','1z5s', '2bbk','2bo9','2dqj','2gc7','2uzx','2wvy','2y7h', '3lu0','3nvq','3pdu','3puv','3r5d','3sfd','3v6d'] assembly = "1cs4" ################## # Explore folder to get files and stoichiometry path = "../Simulated_dataset" ref = os.path.join(path, assembly, "%s.pdb"%assembly) components = [] for c in os.listdir(os.path.join(path, assembly)): if len(c) == 8: continue else: n_copies = int(c.split("_")[-1].split(".")[0]) components.append([os.path.join(os.path.join(path, assembly, c)), n_copies]) for c in components: print("%i x %s"%(c[1], c[0])) print() # Build MaD instance mad = MaD.MaD() # Add map and components mad.add_map(ref, 10) for c in components: sub, n_copies = c mad.add_subunit(sub, n_copies=n_copies) # Run docking and assembly making # > EXCEPTION: 1mda requires a lower descriptor CC threshold for one subunit. # > Make sure to TRANSFORM subunits away from their fitted positions. if assembly == "1mda": mad.run(transform_subunits=True, cc_threshold=0.5) # rotate/translate subunits out of assembly else: mad.run(transform_subunits=True) # rotate/translate subunits out of assembly # Build assembly mad.build_assembly() # - # # 3. Ensemble docking with GroEL # # Here, we show how to process a structural ensemble with an example from GroEL. # # This ensemble was generated using molecular dynamics, and reduced to a set of unique structures using our clustering software CLoNe (see our lab's website and GitHub page). # # An ensemble is passed just like any other structure. Instead of specifying a filename, specify the folder that contains the PDB files (make sure only the required PDB files are in the folder, without other files, to make sure everything runs smoothly). # # In this particular case, it is advised not to build an assembly. GroEL has 14 copies of its subunit, and exploring combinations is going to take a very long time. Instead, use the score_ensembles() function to highlight the best candidates. # # Then, you can rerun MaD on the best candidate alone and build the assembly. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/GroEL/EMD-5338_denoised.mrc", 7) mad.add_subunit("experimental_data/GroEL/CLoNe_ensemble/", n_copies=14) mad.run() mad.score_ensembles() # - # Showing the plots again in case they were lost in the output of the previous cell mad.score_ensembles() # The plot above report: # # * R is the repeatability or percentage of corresponding anchors between component and cryo-EM map # * |clust| the size of the clusters (i.e. the number of descriptor pairs agreeing with a localization) # * CC the cross-correlation with the experimental cryo-EM data # * S the merged score from their product # # # From the above plots, it is clear that GroEL_CLoNeCenters_4 is the best conformational fit with the cryo-EM data. # # # Let's build an assembly from that structure. The descriptors have been computed for both the map and the structure, making this relatively faster. # + from mad import MaD mad = MaD.MaD() mad.add_map("experimental_data/GroEL/EMD-5338_denoised.mrc", 7) mad.add_subunit("experimental_data/GroEL/CLoNe_ensemble/GroEL_CLoNeCenters_4.pdb", n_copies=14) mad.run() mad.build_assembly() # - # GroEL has 14 subunits, all highlighted and accounted for by using the highlighted frame in the structural ensemble. # # In such a situation, the assembly process is thus as easy as it gets. # # 4. Anchor files # # Within "results/your_system_results/individual_solutions", you will find a folder named "anchor_files". This folder contains the information about the anchors and descriptors that were generated during the docking procedure. # # * Filenames in the form: "anchor_cor_COMPONENT_NAME_SOLUTION_IDX.bld": # * To be visualized in ChimeraX. These files contain the correspondences between the component COMPONENT_NAME and map anchors that yielded the solution of index SOLUTION_IDX. Better visualized with the files described in the next bullet point. # * Filenames in the form: "anchor_HI/LO_COMPONENT_NAME_SOLUTION_IDX.pdb": # * These PDB files contain the coordinates of the anchors that generated valid descriptors for a given component and solution. "hi" refers to the anchors of the component; "lo" refers to those of the cryo-EM map. # * Filenames in the form: "anchor_ori_HI/LO_COMPONENT_NAME_SOLUTION_IDX.bld": # * To be visualized in ChimeraX. These files contain the dominant orientation (only the first one) of the anchors that generated valid descriptors. # * Filenames in the form of "corresp_anchors_COMPONENT_NAME_SOLUTION_IDX.pdb": # * These PDB files contain the coordinates of the corresponding anchors between COMPONENT_NAME and the cryo-EM data for a specific solution. These anchors may not have generated valid descriptors but their location was still useful during the global matching step.
MaD_notebook_instructions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import os import json # ### This function is used to load the correct labels of each and every parent tweets veracity and the stance of the reply tweets. def load_true_labels(): tweet_label_dict = {} veracity_label_dict = {} #path of the validation data's labels path_dev = "rumoureval2019_data/rumoureval-2019-training-data/dev-key.json" with open(path_dev, 'r') as f: dev_key = json.load(f) #path of the training data's labels path_train = "rumoureval2019_data/rumoureval-2019-training-data/train-key.json" with open(path_train, 'r') as f: train_key = json.load(f) tweet_label_dict['dev'] = dev_key['subtaskaenglish'] tweet_label_dict['train'] = train_key['subtaskaenglish'] veracity_label_dict['dev'] = dev_key['subtaskbenglish'] veracity_label_dict['train'] = train_key['subtaskbenglish'] return tweet_label_dict, veracity_label_dict # ### Load labels and split for task A and task B # + def load_dataset(): tweet_label_dict, veracity_label_dict = load_true_labels() dev = tweet_label_dict['dev'] train = tweet_label_dict['train'] dev_tweets = dev.keys() train_tweets = train.keys() # Load folds and conversations path_to_folds = 'rumoureval2019_data/rumoureval-2019-training-data/twitter-english' folds = sorted(os.listdir(path_to_folds)) newfolds = [i for i in folds if i[0] != '.'] folds = newfolds cvfolds = {} allconv = [] train_dev_split = {} train_dev_split['dev'] = [] train_dev_split['train'] = [] train_dev_split['test'] = [] for nfold, fold in enumerate(folds): path_to_tweets = os.path.join(path_to_folds, fold) tweet_data = sorted(os.listdir(path_to_tweets)) newfolds = [i for i in tweet_data if i[0] != '.'] tweet_data = newfolds conversation = {} for foldr in tweet_data: flag = 0 conversation['id'] = foldr tweets = [] path_repl = path_to_tweets+'/'+foldr+'/replies' files_t = sorted(os.listdir(path_repl)) newfolds = [i for i in files_t if i[0] != '.'] files_t = newfolds if files_t!=[]: for repl_file in files_t: with open(os.path.join(path_repl, repl_file)) as f: for line in f: tw = json.loads(line) tw['used'] = 0 replyid = tw['id_str'] if replyid in dev_tweets: tw['set'] = 'dev' tw['label'] = dev[replyid] # train_dev_tweets['dev'].append(tw) if flag == 'train': print ("The tree is split between sets", foldr) flag='dev' elif replyid in train_tweets: tw['set'] = 'train' tw['label'] = train[replyid] # train_dev_tweets['train'].append(tw) if flag == 'dev': print ("The tree is split between sets", foldr) flag='train' else: print ("Tweet was not found! ID: ", foldr) tweets.append(tw) if tw['text'] is None: print ("Tweet has no text", tw['id']) conversation['replies'] = tweets path_src = path_to_tweets+'/'+foldr+'/source-tweet' files_t = sorted(os.listdir(path_src)) with open(os.path.join(path_src, files_t[0])) as f: for line in f: src = json.loads(line) src['used'] = 0 scrcid = src['id_str'] src['set'] = flag src['label'] = tweet_label_dict[flag][scrcid] conversation['source'] = src conversation['veracity'] = veracity_label_dict[flag][scrcid] if src['text'] is None: print ("Tweet has no text", src['id']) path_struct = path_to_tweets+'/'+foldr+'/structure.json' with open(path_struct) as f: for line in f: struct = json.loads(line) if len(struct) > 1: # I had to alter the structure of this conversation if foldr=='553480082996879360': new_struct = {} new_struct[foldr] = struct[foldr] new_struct[foldr]['553495625527209985'] = struct['553485679129534464']['553495625527209985'] new_struct[foldr]['553495937432432640'] = struct['553490097623269376']['553495937432432640'] struct = new_struct else: new_struct = {} new_struct[foldr] = struct[foldr] struct = new_struct # Take item from structure if key is same as source tweet id conversation['structure'] = struct # branches = tree2branches(conversation['structure']) # conversation['branches'] = branches train_dev_split[flag].append(conversation.copy()) allconv.append(conversation.copy()) else: flag='train' path_src = path_to_tweets+'/'+foldr+'/source-tweet' files_t = sorted(os.listdir(path_src)) with open(os.path.join(path_src, files_t[0])) as f: for line in f: src = json.loads(line) src['used'] = 0 scrcid = src['id_str'] src['set'] = flag src['label'] = tweet_label_dict[flag][scrcid] conversation['source'] = src conversation['veracity'] = veracity_label_dict[flag][scrcid] if src['text'] is None: print ("Tweet has no text", src['id']) path_struct = path_to_tweets+'/'+foldr+'/structure.json' with open(path_struct) as f: for line in f: struct = json.loads(line) if len(struct) > 1: # print "Structure has more than one root" new_struct = {} new_struct[foldr] = struct[foldr] struct = new_struct # Take item from structure if key is same as source tweet id conversation['structure'] = struct # branches = tree2branches(conversation['structure']) # conversation['branches'] = branches train_dev_split[flag].append(conversation.copy()) allconv.append(conversation.copy()) print (foldr) cvfolds[fold] = allconv allconv = [] #%% # load testing data path_to_folds = 'rumoureval2019_data/rumoureval-2019-test-data/twitter-en-test-data' folds = sorted(os.listdir(path_to_folds)) newfolds = [i for i in folds if i[0] != '.'] folds = newfolds for nfold, fold in enumerate(folds): path_to_tweets = os.path.join(path_to_folds, fold) tweet_data = sorted(os.listdir(path_to_tweets)) newfolds = [i for i in tweet_data if i[0] != '.'] tweet_data = newfolds # print (tweet_data) conversation = {} for foldr in tweet_data: conversation['id'] = foldr tweets = [] path_repl = path_to_tweets+'/'+foldr+'/replies' files_t = sorted(os.listdir(path_repl)) newfolds = [i for i in files_t if i[0] != '.'] files_t = newfolds if files_t!=[]: for repl_file in files_t: with open(os.path.join(path_repl, repl_file)) as f: for line in f: tw = json.loads(line) tw['used'] = 0 tweets.append(tw) if tw['text'] is None: print ("Tweet has no text", tw['id']) conversation['replies'] = tweets path_src = path_to_tweets+'/'+foldr+'/source-tweet' files_t = sorted(os.listdir(path_src)) with open(os.path.join(path_src, files_t[0])) as f: for line in f: src = json.loads(line) src['used'] = 0 scrcid = src['id_str'] conversation['source'] = src if src['text'] is None: print ("Tweet has no text", src['id']) path_struct = path_to_tweets+'/'+foldr+'/structure.json' with open(path_struct) as f: for line in f: struct = json.loads(line) if len(struct) > 1: print ("Structure has more than one root") new_struct = {} new_struct[foldr] = struct[foldr] struct = new_struct # Take item from structure if key is same as source tweet id conversation['structure'] = struct # branches = tree2branches(conversation['structure']) # conversation['branches'] = branches train_dev_split['test'].append(conversation.copy()) allconv.append(conversation.copy()) else: path_src = path_to_tweets+'/'+foldr+'/source-tweet' files_t = sorted(os.listdir(path_src)) with open(os.path.join(path_src, files_t[0])) as f: for line in f: src = json.loads(line) src['used'] = 0 scrcid = src['id_str'] conversation['source'] = src if src['text'] is None: print ("Tweet has no text", src['id']) path_struct = path_to_tweets+'/'+foldr+'/structure.json' with open(path_struct) as f: for line in f: struct = json.loads(line) if len(struct) > 1: # print "Structure has more than one root" new_struct = {} new_struct[foldr] = struct[foldr] struct = new_struct # Take item from structure if key is same as source tweet id conversation['structure'] = struct # branches = tree2branches(conversation['structure']) # conversation['branches'] = branches train_dev_split['test'].append(conversation.copy()) allconv.append(conversation.copy()) # print (foldr) #% cvfolds[fold] = allconv allconv = [] #%% return train_dev_split
preprocessing_tweets.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## <div style="text-align:center;"><b>Ordinary Differential Equation</b></div> # ### <b><NAME> 4</b><br><br> # # ${{dy(t)} \over {dt}} = y'(t) = f(y(t),t), \quad \quad {\rm{with\;}} y(t_0)=y_0$ <br><br> # # $\eqalign{ # & {k_1} = f\left( {t_0},{y}({t_0})\right) \cr # & {k_2} = f\left( {{t_0} + {h \over 2}, {y}({t_0}) + {k_1}{h \over 2}} \right) \cr # & {k_3} = f\left( {{t_0} + {h \over 2}, {y}({t_0}) + {k_2}{h \over 2}} \right) \cr # & {k_4} = f\left( {{t_0} + h,{y}({t_0}) + {k_3}h} \right) \cr}$ <br> # # $\eqalign{ # {y}({t_0} + h) &= {y}({t_0}) + {{{k_1} + 2{k_2} + 2{k_3} + {k_4}} \over 6}h = {y}({t_0}) + \left( {{1 \over 6}{k_1} + {1 \over 3}{k_2} + {1 \over 3}{k_3} + {1 \over 6}{k_4}} \right)h \cr # &= {y}({t_0}) + mh\quad \quad {\rm{where\;}}m{\rm{\;is\;a\;weighted\;average\; slope\; approximation}} \cr}$<br> # # + #Import module import math import matplotlib.pyplot as plt #Set the differential equation def dydx(x, y): return 4-0.3*y-0.1*4*math.exp(-0.5*x) #Function declaration for Fourth Order Runge Kutta Method def rungeKuttaFourthOrder(xi, yi, xn, h): matrix_x = [] matrix_y = [] n = int((xn - xi)/h) for i in range(0, n+1): k1 = dydx(xi, yi) k2 = dydx(xi+h/2, yi+(k1*h/2)) k3 = dydx(xi+h/2, yi+(k2*h/2)) k4 = dydx(xi+h, yi+k3*h ) yn = yi + (h/6)*(k1 + 2*k2 + 2*k3 + k4) #Save x and y value into Matrix matrix_x.append(xi) matrix_y.append(yi) #Update value xi and yi xi = xi + h yi = yn return(matrix_x, matrix_y) #Set the initial value xi = 0 yi = 6 xn = 2 h = 0.25 n = int((xn - xi)/h) #Calling function, then save the return value into x and y matrix x_value, y_value = rungeKuttaFourthOrder(xi, yi, xn, h) #Print the value for each x print("x\t\t y") for i in range(0, n+1): print(x_value[i],'\t\t', y_value[i]) #Show graph using matplotlib plt.xlabel('x') plt.ylabel('y') plt.title('ODE Graph Approximation Using 4th Order RK') plt.plot(x_value, y_value) plt.show #Print the result print("\nThe value of y when x = ", xn, "is", y_value[n]) # - # ### <b>Euler's Method</b><br> # ## $y_1 = y_0 + f(x_0,y_0)h$ <br> # + #Import module import matplotlib.pyplot as plt #Set the differential equation def dydx(x, y): return (1+2*x)*y**0.5 #Function declaration for Euler's Method def eulerMethod(xi, yi, xn, h): matrix_x = [] matrix_y = [] n = int((xn - xi)/h) for i in range(0, n+1): yn = yi + dydx(xi, yi)*h #Save x and y value into matrix matrix_x.append(xi) matrix_y.append(yi) #Update value xi and yi xi = xi + h yi = yn return(matrix_x, matrix_y) #Set the initial value xi = 0 yi = 1 xn = 1 h = 0.125 n = int((xn - xi)/h) #Calling eulerMethod function, then save the return value into x and y matrix x_value, y_value = eulerMethod(xi, yi, xn, h) #Print the value for each x print("x\t\t y") for i in range(0, n+1): print(x_value[i],'\t\t', y_value[i]) #Show graph using matplotlib plt.xlabel('x') plt.ylabel('y') plt.title("ODE Graph Approximation Using Euler's Method") plt.plot(x_value, y_value) plt.show #Print the result print("\nThe value of y when x = ", xn, "is", y_value[n])
Ordinary Differential Equation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Applied Data Science Capstone Assignment 2 : Segmenting and Clustering Neighborhoods in Toronto - Part 3 # # Exploring and clustering the neighborhoods in Toronto. # Explore and cluster the neighborhoods in Toronto. You can decide to work with only boroughs that contain the word Toronto and then replicate the same analysis we did to the New York City data. It is up to you. # # Just make sure: # # - to add enough Markdown cells to explain what you decided to do and to report any observations you make. # - to generate maps to visualize your neighborhoods and how they cluster together. # # Once you are happy with your analysis, submit a link to the new Notebook on your Github repository. (3 marks) # I will be using the Foursquare API to explore neighborhoods in selected cities in toronto. The Foursquare explore function will be used to get the most common venue categories in each neighborhood, and then use this feature to group the neighborhoods into clusters. The k-means clustering algorithm will be used for the analysis. Fnally, use the Folium library to visualize the neighborhoods in Toronto and their emerging clusters. # + import numpy as np # library to handle data in a vectorized manner import pandas as pd # library for data analsysis import json # library to handle JSON files from geopy.geocoders import Nominatim GeoLocator = Nominatim(user_agent='My-Notebook')# convert an address into latitude and longitude values import requests # library to handle requests from pandas.io.json import json_normalize # tranform JSON file into a pandas dataframe # import k-means from clustering stage from sklearn.cluster import KMeans # Matplotlib and associated plotting modules import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.colors as colors import folium #Library for maps rendering # - toronto_neighborhoods = pd.read_csv('data/Toronto_part_2.csv') toronto_neighborhoods.head() # #### Use geopy library to get the latitude and longitude values of Toronto Canada. address = 'Toronto, Ontario Canada' geolocator = Nominatim() location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The geograpical coordinate of Toronto Canada are {}, {}.'.format(latitude, longitude)) # + # create map of Toronto using latitude and longitude values map_toronto = folium.Map(location=[latitude, longitude], zoom_start=11) # adding markers to map for lat, lng, borough, neighborhood in zip(toronto_neighborhoods['Latitude'], toronto_neighborhoods['Longitude'], toronto_neighborhoods['Borough'], toronto_neighborhoods['Neighbourhood']): label = '{}, {}'.format(neighborhood, borough) label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=4, popup=label, color='blue', fill=True, fill_color='#87cefa', fill_opacity=0.5, parse_html=False).add_to(map_toronto) map_toronto # - # For this task, I will just reduce the our target analysis to Neighbohoods in East,West and Central Toronto only. Lets just take portion of dataframe where Boroughs contain word Toronto. toronto_data = toronto_neighborhoods[toronto_neighborhoods['Borough'].str.contains("Toronto")].reset_index(drop=True) print(toronto_data.shape) toronto_data.head() # **Re-create the map with new markers for Toronto Neighborhoods** # + # I will be using the same coordinates for the previous view map_toronto = folium.Map(location=[latitude, longitude], zoom_start=11) # add markers to map for lat, lng, label in zip(toronto_data['Latitude'], toronto_data['Longitude'], toronto_data['Neighbourhood']): label = folium.Popup(label, parse_html=True) folium.CircleMarker( [lat, lng], radius=5, popup=label, color='blue', fill=True, fill_color='#3186cc', fill_opacity=0.7, parse_html=False).add_to(map_toronto) map_toronto # - # **Utilizing the Foursquare API to explore and segment neighborhoods** CLIENT_ID = 'CLIENT_ID'# your Foursquare ID CLIENT_SECRET = 'CLIENT_SECRET' # your Foursquare Secret VERSION = '20191004' LIMIT = 30 # # 1. Exploring Neighbourhood in Toronto # # **Using the following foursquare api query url, search venues on all boroughs in selected Toronto neighborhoods** # # https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&ll=LATITUDE,LONGITUDE&v=VERSION&query=QUERY&radius=RADIUS&limit=LIMIT # # The following function retrieves the venues given the names and coordinates and stores it into dataframe. # def getNearbyVenues(names, latitudes, longitudes, radius=500): venues_list=[] for name, lat, lng in zip(names, latitudes, longitudes): print(name) # create the API request URL url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format( CLIENT_ID, CLIENT_SECRET, VERSION, lat, lng, radius, LIMIT) # make the GET request results = requests.get(url).json()["response"]['groups'][0]['items'] # return only relevant information for each nearby venue venues_list.append([( name, lat, lng, v['venue']['name'], v['venue']['location']['lat'], v['venue']['location']['lng'], v['venue']['categories'][0]['name']) for v in results]) nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list]) nearby_venues.columns = ['Neighbourhood', 'Neighborhood Latitude', 'Neighborhood Longitude', 'Venue', 'Venue Latitude', 'Venue Longitude', 'Venue Category'] return(nearby_venues) # **Retrieving all venues given the Addresses** toronto_neighborhoods = toronto_data toronto_venues = getNearbyVenues(names=toronto_neighborhoods['Neighbourhood'], latitudes=toronto_neighborhoods['Latitude'], longitudes=toronto_neighborhoods['Longitude'] ) # #### Shape of resulting DataFrame toronto_venues.shape toronto_venues.head() # **Count of venues were returned for each Borough** toronto_venues.groupby('Neighbourhood').count() # ***Finding out unique categories can be curated from all the returned venues*** print('{} uniques categories.'.format(len(toronto_venues['Venue Category'].unique()))) # ## 2. Analyzing Borough Neighborhood # # + # one hot encoding toronto_onehot = pd.get_dummies(toronto_venues[['Venue Category']], prefix="", prefix_sep="") # add neighborhood column back to dataframe toronto_onehot['Neighbourhood'] = toronto_venues['Neighbourhood'] # move neighborhood column to the first column fixed_columns = [toronto_onehot.columns[-1]] + list(toronto_onehot.columns[:-1]) toronto_onehot = toronto_onehot[fixed_columns] toronto_onehot.head() # - toronto_onehot.shape # **Next, let's group rows by neighborhood and by taking the mean of the frequency of occurrence of each category** toronto_group = toronto_onehot.groupby('Neighbourhood').mean().reset_index() toronto_group toronto_group.shape # **Making a dataframe of all these vensues** num_top_venues = 5 for neigh in toronto_group['Neighbourhood']: print("----"+neigh+"----") temp = toronto_group[toronto_group['Neighbourhood'] == neigh].T.reset_index() temp.columns = ['venue','freq'] temp = temp.iloc[1:] temp['freq'] = temp['freq'].astype(float) temp = temp.round({'freq': 2}) print(temp.sort_values('freq', ascending=False).reset_index(drop=True).head(num_top_venues)) print('\n') # **Function to Sort the venues** def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues] # + num_top_venues = 10 indicators = ['st', 'nd', 'rd'] # create columns according to number of top venues columns = ['Neighbourhood'] for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'.format(ind+1)) # create a new dataframe neighborhoods_venues_sorted = pd.DataFrame(columns=columns) neighborhoods_venues_sorted['Neighbourhood'] = toronto_group['Neighbourhood'] for ind in np.arange(toronto_group.shape[0]): neighborhoods_venues_sorted.iloc[ind, 1:] = return_most_common_venues(toronto_group.iloc[ind, :], num_top_venues) neighborhoods_venues_sorted.shape # - # ## 3. Clustering Neighborhoods # ### K-Means # + # set number of clusters kclusters = 10 toronto_group_clustering = toronto_group.drop('Neighbourhood', 1) # run k-means clustering kmeans = KMeans(n_clusters=kclusters, random_state=1).fit(toronto_group_clustering) # check cluster labels generated for each row in the dataframe print(kmeans.labels_[0:10]) print(len(kmeans.labels_)) # + toronto_merged = toronto_neighborhoods # add clustering labels toronto_merged['Cluster Labels'] = kmeans.labels_ # merge toronto_grouped with toronto_data to add latitude/longitude for each neighborhood toronto_merged = toronto_merged.join(neighborhoods_venues_sorted.set_index('Neighbourhood'), on='Neighbourhood') toronto_merged.head() # check the last columns! # - # ## Visualizaing the Clusters # + # create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(kclusters) ys = [i+x+(i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers to the map markers_colors = [] for lat, lon, poi, cluster in zip(toronto_merged['Latitude'], toronto_merged['Longitude'], toronto_merged['Neighbourhood'],kmeans.labels_): label = folium.Popup(str(poi) + ' Cluster ' + str(cluster), parse_html=True) folium.CircleMarker( [lat, lon], radius=5, popup=label, color=rainbow[cluster-1], fill=True, fill_color=rainbow[cluster-1], fill_opacity=0.7).add_to(map_clusters) map_clusters # -
Week 2 - Segmentation and Clustering of Neighborhoods in Toronto_Part 3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import networkx import numpy as np import matplotlib.pyplot as plt import pickle import operator graph = pickle.load(open('bbva.pickle', 'rb')) graphb = pickle.load(open('../BA/graph_ba.pickle', 'rb')) graph_er = pickle.load(open('../ER/graph_er.pickle', 'rb')) dict(sorted(graphb.degree, key=operator.itemgetter(1), reverse=True)[:3]) dict(sorted(graph_er.degree, key=operator.itemgetter(1), reverse=True)[:3]) dict(sorted(graph.degree, key=operator.itemgetter(1), reverse=True)[:3]) for node in graphb.nodes: if graphb.degree[node]==26: print(node) ba_bc = networkx.betweenness_centrality(graphb) er_bc = networkx.betweenness_centrality(graph_er) bbva_er = networkx.betweenness_centrality(graph) max(ba_bc, key=ba_bc.get),ba_bc[max(ba_bc, key=ba_bc.get)] max(er_bc, key=er_bc.get),er_bc[max(er_bc, key=er_bc.get)] max(bbva_er, key=bbva_er.get),bbva_er[max(bbva_er, key=bbva_er.get)] # node 2 has the heighest betwenness # + aux_a = [] aux_b = [] for i in range(len(prob)): if prob[i] !=0: aux_a.append(prob[i]) aux_b.append(mean_value_interval[i]) # - soll = np.polyfit(np.log(aux_b),np.log(aux_a),1) soll # + degr = [val for (node, val) in graph.degree()] prob = [] mean_value_interval = [] for k in range(0,75): p = 0 for d in degr: if 1.05**k < d and d < 1.05**(k+1): p+=1 p = 1/n * p prob.append(p) aux = (1.05**k-1.05**(k+1))/(np.log(1.05**k)-np.log(1.05**(k+1))) mean_value_interval.append(aux) plt.figure(figsize=(7,8)) plt.xscale('log') plt.yscale('log') plt.scatter(mean_value_interval,prob,marker='o',c = 'b') #plt.plot(powerlaw(np.arange(1,max(degrees)),*sol1[0])) plt.ylim(10**(-5)) plt.xlim(1,10**(2)) plt.xlabel('k') plt.ylabel('P(k)') plt.title('K, gamma %s'%round(soll[0],2)) plt.savefig('metabbva-dd.png') plt.show() # + degr = [val for (node, val) in graphb.degree()] prob = [] mean_value_interval = [] for k in range(0,75): p = 0 for d in degr: if 1.05**k < d and d < 1.05**(k+1): p+=1 p = 1/n * p prob.append(p) aux = (1.05**k-1.05**(k+1))/(np.log(1.05**k)-np.log(1.05**(k+1))) mean_value_interval.append(aux) plt.figure() plt.xscale('log') plt.yscale('log') plt.scatter(mean_value_interval,prob,marker='o',c = 'b') #plt.plot(powerlaw(np.arange(1,max(degrees)),*sol1[0])) plt.ylim(10**(-4)) plt.xlim(1,10**(2)) plt.xlabel('k') plt.ylabel('P(k)') plt.title('K') plt.show() # + aux_a = [] aux_b = [] for i in range(len(prob)): if prob[i] !=0: aux_a.append(prob[i]) aux_b.append(mean_value_interval[i]) # - np.polyfit(np.log(aux_b),np.log(aux_a),1) # # Hubs selection # + #Hubs are really bad placed in our network need to create a new one # + #hubs_rank = [17,14,13,11,2,6,1,12,5,9,10,8,3,15,7,4,16] # - hubs_rank = [6,4,12,15,8,5,14,11,9,10,3,7,2,1,13,16,0] import operator max(graphb.degree,key=operator.itemgetter(1)) higher5 = dict(sorted(graphb.degree, key=operator.itemgetter(1), reverse=True)[:5]) higher5 j = 0 for node in higher5: graphb.nodes[node]['sector']=j j+=1 pickle.dump(graphb, open('Barabasi-with-sectors.pickle', 'wb')) # # Creation new one new_ba = networkx.barabasi_albert_graph(10000,2) higher17 = dict(sorted(new_ba.degree, key=operator.itemgetter(1), reverse=True)[:17]) higher17 j = 0 for node in higher17: new_ba.nodes[node]['sector'] = hubs_rank[j] j+=1 for node in new_ba.nodes not in higher17:
BBVA/Analyzing power law.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt import pandas as pd from matplotlib import rcParams from matplotlib import pyplot # # %matplotlib notebook data= pd.read_excel("density.xlsx") data plt.figure(figsize=(10,10)) plt.style.use('classic') pyplot.scatter(x=data.Scanspeed, y=data.Power, s=100, edgecolor ='b', alpha=0.8) plt.xlabel('Scan Speed(mm/s)', size = 15) plt.ylabel('Power(W)', size = 15) for i in range(data.shape[0]): plt.text(data.Scanspeed[i],data.Power[i],(data.SampleNum[i]), position=(data.Scanspeed[i], data.Power[i]+5), fontsize='medium', ha='left') plt.savefig("graph01.jpg") # plt.savefig('fgraph01.pdf') plt.figure(figsize=(15,15)) plt.style.use('classic') plt.xlabel('Scan Speed(mm/s)', size = 25) plt.ylabel('Power(W)', size = 25) plt.scatter(data.Scanspeed,data.Power, c = data.Porosity, cmap ='jet' , s=250) for i in range(data.shape[0]): plt.text(data.Scanspeed[i],data.Power[i],("S"+str(data.SampleNum[i]),round(data.Porosity[i],1)), position=(data.Scanspeed[i], data.Power[i]+5), fontsize='medium',va='bottom', ha='center') cbar=plt.colorbar(orientation = 'vertical'); cbar.set_label("Porosity%",size = 25) plt.savefig("graph02.jpg") plt.savefig('fgraph02.jpg')
Microscopy/ImageJ_75um-200C_anaylsis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # A very short introduction to Linux # This lecture is about programming, but it would be a big mistake to forget to talk about Linux here, at least a short introduction. # # Every student in (geo-)sciences should know about the existence of Linux and know the basics of it. Atmospheric Sciences students in particular will have to use it sooner or later, since most of the tools and data they are using are running or have been created on Linux systems. # + [markdown] toc=true # <h1>Table of Contents<span class="tocSkip"></span></h1> # <div class="toc"><ul class="toc-item"><li><span><a href="#A-very-short-introduction-to-Linux" data-toc-modified-id="A-very-short-introduction-to-Linux-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>A very short introduction to Linux</a></span><ul class="toc-item"><li><span><a href="#What-is-Linux?" data-toc-modified-id="What-is-Linux?-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>What is Linux?</a></span></li><li><span><a href="#Should-I-use-it?" data-toc-modified-id="Should-I-use-it?-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Should I use it?</a></span></li><li><span><a href="#Testing-Linux" data-toc-modified-id="Testing-Linux-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Testing Linux</a></span></li><li><span><a href="#The-linux-command-line" data-toc-modified-id="The-linux-command-line-1.4"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>The linux command line</a></span><ul class="toc-item"><li><span><a href="#Listing-files-and-directories" data-toc-modified-id="Listing-files-and-directories-1.4.1"><span class="toc-item-num">1.4.1&nbsp;&nbsp;</span>Listing files and directories</a></span></li><li><span><a href="#The-directory-structure" data-toc-modified-id="The-directory-structure-1.4.2"><span class="toc-item-num">1.4.2&nbsp;&nbsp;</span>The directory structure</a></span></li><li><span><a href="#Making-Directories" data-toc-modified-id="Making-Directories-1.4.3"><span class="toc-item-num">1.4.3&nbsp;&nbsp;</span>Making Directories</a></span></li><li><span><a href="#Changing-to-a-different-directory" data-toc-modified-id="Changing-to-a-different-directory-1.4.4"><span class="toc-item-num">1.4.4&nbsp;&nbsp;</span>Changing to a different directory</a></span></li><li><span><a href="#The-directories-.-and-.." data-toc-modified-id="The-directories-.-and-..-1.4.5"><span class="toc-item-num">1.4.5&nbsp;&nbsp;</span>The directories . and ..</a></span></li><li><span><a href="#Copying-files" data-toc-modified-id="Copying-files-1.4.6"><span class="toc-item-num">1.4.6&nbsp;&nbsp;</span>Copying files</a></span></li><li><span><a href="#Using-[TAB]" data-toc-modified-id="Using-[TAB]-1.4.7"><span class="toc-item-num">1.4.7&nbsp;&nbsp;</span>Using [TAB]</a></span></li><li><span><a href="#Moving-files" data-toc-modified-id="Moving-files-1.4.8"><span class="toc-item-num">1.4.8&nbsp;&nbsp;</span>Moving files</a></span></li><li><span><a href="#Removing-files-and-directories" data-toc-modified-id="Removing-files-and-directories-1.4.9"><span class="toc-item-num">1.4.9&nbsp;&nbsp;</span>Removing files and directories</a></span></li><li><span><a href="#Displaying-the-contents-of-a-file-on-the-screen" data-toc-modified-id="Displaying-the-contents-of-a-file-on-the-screen-1.4.10"><span class="toc-item-num">1.4.10&nbsp;&nbsp;</span>Displaying the contents of a file on the screen</a></span></li><li><span><a href="#Searching-the-contents-of-a-file" data-toc-modified-id="Searching-the-contents-of-a-file-1.4.11"><span class="toc-item-num">1.4.11&nbsp;&nbsp;</span>Searching the contents of a file</a></span></li><li><span><a href="#Take-home-points" data-toc-modified-id="Take-home-points-1.4.12"><span class="toc-item-num">1.4.12&nbsp;&nbsp;</span>Take home points</a></span></li></ul></li><li><span><a href="#Executable-scripts" data-toc-modified-id="Executable-scripts-1.5"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Executable scripts</a></span><ul class="toc-item"><li><span><a href="#A-simple-script" data-toc-modified-id="A-simple-script-1.5.1"><span class="toc-item-num">1.5.1&nbsp;&nbsp;</span>A simple script</a></span></li><li><span><a href="#Make-a-file-executable" data-toc-modified-id="Make-a-file-executable-1.5.2"><span class="toc-item-num">1.5.2&nbsp;&nbsp;</span>Make a file executable</a></span></li><li><span><a href="#Take-home-points" data-toc-modified-id="Take-home-points-1.5.3"><span class="toc-item-num">1.5.3&nbsp;&nbsp;</span>Take home points</a></span></li></ul></li><li><span><a href="#The-linux-PATH" data-toc-modified-id="The-linux-PATH-1.6"><span class="toc-item-num">1.6&nbsp;&nbsp;</span>The linux PATH</a></span><ul class="toc-item"><li><span><a href="#Locate-linux-programs" data-toc-modified-id="Locate-linux-programs-1.6.1"><span class="toc-item-num">1.6.1&nbsp;&nbsp;</span>Locate linux programs</a></span></li><li><span><a href="#The-PATH-variable" data-toc-modified-id="The-PATH-variable-1.6.2"><span class="toc-item-num">1.6.2&nbsp;&nbsp;</span>The PATH variable</a></span></li><li><span><a href="#Take-home-points" data-toc-modified-id="Take-home-points-1.6.3"><span class="toc-item-num">1.6.3&nbsp;&nbsp;</span>Take home points</a></span></li></ul></li><li><span><a href="#What's-next?" data-toc-modified-id="What's-next?-1.7"><span class="toc-item-num">1.7&nbsp;&nbsp;</span>What's next?</a></span></li></ul></li></ul></div> # - # ## What is Linux? # The [web](https://www.google.co.uk/search?q=What+is+Linux) is going to give a better answer than me to this question. # ## Should I use it? # My very personal answer is a clear: **yes**! I can't force you to it though, and most of the exercises of this lecture can be done on a Windows computer too. If you are running Mac OS X then you have access to a linux terminal anyway and you can ignore my recommendation (even if I don't like Apple for several other reasons - totally subjective opinion again). # # Linux has always been an environment for programmers and has the reputation of being "geeky" and "complicated". This is less true today, with many Linux distributions becoming mainstream and easy to use (my personal favorite is [Linux Mint](http://linuxmint.com), but you probably mostly heard of [Ubuntu](http://ubuntugnome.org/) which I also recommend). # # I believe that Linux is *much* more user-friendly than Windows: once some of the particularities of Linux are understood (which can be frustrating in the beginning since it works *quite* differently than windows), it appears that there is much less "hidden" in Linux than in Windows (especially when it comes to installing/deinstalling software, using the command line, or protecting yourself from viruses and intruders). # # **As a scientist and programmer** there are many reasons to prefer Linux (or Mac OS X) to Windows. Let me list some reasons here: # - **Linux comes with many tools for scientists and programmers** ("batteries included"). For historical reasons, Linux and its command line tools have been used by scientists and programmers since decades. It is not a surprise then that Linux comes with many (many) useful utilities to make programming and working with data easier. # - **Linux is fast and reliable**. Linux is extremely stable and more lightweight than Windows. I've never seen a Linux machine becoming *slower* with time, as I was used to see in my time using Windows (I have to admit: it was more than 10 years ago). # - **Linux is the operating system of the huge majority of the super computers and web servers worldwide**. Because of its efficiency, security, and multiple user management tools, Linux has taken over the web: [99.4%](https://en.wikipedia.org/wiki/Linux_adoption#Supercomputers) of the super computers and [67.5%](https://en.wikipedia.org/wiki/Linux_adoption#Servers) of the web servers run Linux, while [79.3%](https://en.wikipedia.org/wiki/Linux_adoption#Mobile_devices) of the mobile devices run Linux via Android. # - **Linux is at the heart of the open-source philosophy**. Linux is free and open-source, and it is not surprising that people who embraced the open-source philosophy also prefer Linux to Windows or Mac. # # There are also some reasons **not** to use Linux of course. For one, Linux can be surprising at first and you'll need some time to get used to it. Also, it doesn't come pre-installed on most computers and you'll have to do it yourself (this is going to change: several retailers are already selling cheaper Ubuntu laptops to students). It is possible (but unlikely) that some of your hardware will not be compatible with Linux. Finally, some programs simply aren't available on Linux: Microsoft Office, the Adobe Suite, and games are the most prominent examples. The free and open-source alternatives (LibreOffice and GIMP) are good, but not *as* good as their commercial counterpart. I used Linux exclusively for more than 10 years now, and I never regretted it. Recently I had to install Windows in a virtual machine in order to use the MS Office software provided by the University, and it works perfectly. Another option is to use [wine](https://www.winehq.org/). # ## Testing Linux # Here are a few ways you can use Linux and make an idea by yourself: # # - **At the University of Innsbruck**: In order to use Linux in the computer room you have to register for an account [here](http://orawww.uibk.ac.at/public_prod/owa/uvw$web$10.p001). After an hour or so you will be able to connect to any computer using your username and password. The Linux distribution used at the university is [CentOS](https://www.centos.org/) (not my favorite I have to admit). If you are a student of another university, it is likely that you have access to Linux environments, too. # - **On your laptop, with a live CD (or USB)**: this is the [best way to try it at no risk](https://tutorials.ubuntu.com/tutorial/try-ubuntu-before-you-install#0) and get a feeling for the general usage of a linux distribution. This is not permanent though. # - **On your laptop, in a virtual machine**: This is a relatively easy and non-destructive way to try Linux. There are tons of tutorials online, [this one](https://helpdeskgeek.com/linux-tips/how-to-install-ubuntu-in-virtualbox/) seems OK. # - **On your laptop, alongside Windows (dual boot)**: this is a bit more engaged, but the best way if you want to use both operating systems at full capacity. See [here](https://help.ubuntu.com/community/WindowsDualBoot) for the official instructions. Be careful however: it is possible that things get a bit complicated going this way: secure your data first, and be prepared for some unexpected events. # - **On your laptop, without Windows**: Congratulations, this is the best solution! Please check that your hardware is [compatible](https://certification.ubuntu.com/desktop/) first, and follow the install instructions of your chosen OS. If you want to use Windows afterwards you can still re-install it or install it in a virtual machine. # ## The linux command line # *Copyright notice: this section was largely inspired from the first parts of <NAME>'s [UNIX tutorial](http://www.ee.surrey.ac.uk/Teaching/Unix/index.html)* # To open a terminal window, click on the "Terminal" icon from the ``Applications/System Tools`` menu. You can add an icon to your "quick launch" taskbar simply by dragging the icon to it. # # A terminal window should appear with a ``$`` prompt, waiting for you to start entering commands. The command line has a very important role in linux (as compared to windows where nobody uses it) since many tasks can be done much more efficiently with simple commands. # ### Listing files and directories # **ls (list)** # # When you first login, your current working directory is your home directory. Your home directory has the same name as your username, for example, c7071047, and it is where your personal files and subdirectories are saved. # # To find out what is in your home directory, type: # # ``` # $ ls # ``` # # The ``ls`` command lists the contents of your current working directory. # # ``ls`` does not, in fact, cause all the files in your home directory to be listed, but only those ones whose name does not begin with a dot (.) Files beginning with a dot (.) are known as hidden files and usually contain important program configuration information. They are hidden because you should not change them unless you know what you do. # # To list all files in your home directory including those whose names begin with a dot, type: # # ``` # $ ls -a # ``` # # As you can see, ``ls -a`` lists files that are normally hidden. # # ``ls`` is an example of a command which can take options: ``-a`` is an example of an option. The options change the behaviour of the command. There are online manual pages that tell you which options a particular command can take, and how each option modifies the behaviour of the command. ``ls -lh`` is an other way to call ``ls`` with two options, ``l`` for "listing format" and ``h`` for "human readable". # # **Note:** linux file names and commands are *case sensitive*, i.e. ``Test.txt`` is different from ``test.txt``, and both names could coexist in the same directory. # ### The directory structure # All the files are grouped together in the directory structure. The file-system is arranged in a hierarchical structure, like an inverted tree. The top of the hierarchy is traditionally called root (written as a slash ``/`` ) # # ![image](../img/unix-tree.png) # # When loging in we are automatically located in our personal ``home`` directory, which is aptly named because: # # - we won't need to leave ``home`` during our exercises # - we are allowed to do whatever we want in our ``home``, while we are not allowed to write, delete or change things in the other directories. # # To know where we are in the directory structure, there is a useful command: # # ``` # $ pwd # ``` # # which prints the path of the current working directory. # # ### Making Directories # **mkdir (make directory)** # # We will now make a subdirectory in your home directory to hold the files you will be creating and using in the course of this tutorial. To make a subdirectory called ``unixstuff`` in your current working directory type: # # ``` # $ mkdir unixstuff # ``` # # To see the directory you have just created, type: # # ``` # $ ls # ``` # ### Changing to a different directory # **cd (change directory)** # # The command ``cd directory`` means change the current working directory to "directory". The current working directory may be thought of as the directory you are in, i.e. your current position in the file-system tree. # # To change to the directory you have just made, type: # # ``` # $ cd unixstuff # ``` # # Type ``ls`` to see the contents (which should be empty) # # <img src="../img/logo_ex.png" align="left" style="width:1em; height:1em;"> **Exercise**: make a directory called ``backup`` in the ``unixstuff`` directory # ### The directories . and .. # Still in the ``unixstuff`` directory, type: # # ``` # $ ls -a # ``` # # As you can see, in the unixstuff directory (and in all other directories), there are two special directories called (.) and (..) # # **The current directory (.)** # # In linux, (.) means the current directory, so typing: # # ``` # $ cd . # ``` # # means "stay where you are" (the unixstuff directory). # # This may not seem very useful at first, but using (.) as the name of the current directory will save a lot of typing, as we shall see. # # **The parent directory (..)** # # (..) means the parent of the current directory, so typing: # # ``` # $ cd .. # ``` # # will take you one directory up the hierarchy (back to your home directory). Try it now. # # **Note**: typing cd with no argument always returns you to your home directory. This is very useful if you are lost in the file system. # # **~ (your home directory)** # # Home directories can also be referred to by the tilde ``~`` character. It can be used to specify paths starting at your home directory. So typing: # # ``` # $ ls ~/unixstuff # ``` # # will list the contents of your unixstuff directory, no matter where you currently are in the file system. # ### Copying files # **cp (copy)** # # ``cp file1 file2`` is the command which makes a copy of ``file1`` in the current working directory and calls it ``file2`` # # What we are going to do now, is to take a file stored in an open access area of the file system, and use the ``cp`` command to copy it to your unixstuff directory. # # First, ``cd`` to your unixstuff directory: # # ``` # $ cd ~/unixstuff # ``` # # Then type: # # ``` # $ cp /scratch/c707/c7071047/tuto/science.txt . # ``` # # **Note**: Don't forget the dot . at the end. Remember, in linux, the dot means the current directory. # # The above command means "copy the file science.txt to the current directory, keeping the name the same". # # **Note**: The directory ``/scratch/c707/c7071047/tuto`` is an area to which everyone in the University has read and copy access. If you are from outside the University, you can grab a copy of the file from the internet. For this, you can use another very useful command, ``wget``: # # ``` # $ wget http://www.ee.surrey.ac.uk/Teaching/Unix/science.txt # ``` # # This will download the file ``science.txt`` to your current directory # # <img src="../img/logo_ex.png" align="left" style="width:1em; height:1em;"> **Exercise**: Create a backup of your ``science.txt`` file by copying it to a file called ``science.bak`` # # # **Note:** directories can also be copied with the ``-r`` option added to ``cp``. # ### Using [TAB] # ``[TAB]`` is very useful in the Linux (and other) command line: it use an automated completion algorithm to complete the commands you are typing. For example, try to type ``$ cd ~/uni`` and then ``TAB``. This is also going to make suggestions in case of multiple choices, or for commands. # ### Moving files # **mv (move)** # # ``mv file1 file2`` moves (or renames) ``file1`` to ``file2`` # # To move a file from one place to another, use the ``mv`` command. This has the effect of moving rather than copying the file, so you end up with only one file rather than two. # # It can also be used to rename a file, by moving the file to the same directory, but giving it a different name. # # We are now going to move the file ``science.bak`` to your ``backup`` directory. # # First, change directories to your ``unixstuff`` directory. Then type: # # ``` # $ mv science.bak backup/ # ``` # # Type ``ls`` and ``ls backup`` to see if it has worked. # ### Removing files and directories # **rm (remove), rmdir (remove directory)** # # To delete (remove) a file, use the ``rm`` command. As an example, we are going to create a copy of the ``science.txt`` file and then delete it. # # Inside your ``unixstuff`` directory, type: # # ``` # $ cp science.txt tempfile.txt # $ ls # $ rm tempfile.txt # $ ls # ``` # # You can use the ``rmdir`` command to remove a directory (make sure it is empty first). Try to remove the ``backup`` directory. You will not be able to since linux will not let you remove a non-empty directory. To delete a non-empty directory with all its subdirectories you can use the option ``-r`` (r for recursive): # # ``` # $ rm -r /path/to/some/directory # ``` # # This command will then ask you confirmation for certain files judged important. If you are very sure of what you do, you can add a ``-f`` to the command (f for force): # # ``` # $ rm -rf /path/to/some/directory/that/i/am/very/sure/to/delete # ``` # # **Note:** directories deleted with ``rm`` are lost *forever*. They don't go to the trash, they are just deleted. # ### Displaying the contents of a file on the screen # **clear (clear screen)** # # Before you start the next section, you may like to clear the terminal window of the previous commands so the output of the following commands can be clearly understood. # # At the prompt, type: # # ``` # $ clear # ``` # # This will clear all text and leave you with the ``$`` prompt at the top of the window. # # # **cat (concatenate)** # # The command ``cat`` can be used to display the contents of a file on the screen. Type: # # ``` # $ cat science.txt # # ``` # # As you can see, the file is longer than than the size of the window. You can scroll back but this is not very useful. # # # **less** # # The command ``less`` writes the contents of a file onto the screen a page at a time. Type: # # ``` # $ less science.txt # ``` # # Press the ``[space-bar]`` if you want to see another page, and type ``[q]`` if you want to quit reading. As you can see, ``less`` is used in preference to ``cat`` for long files. # # # **head** # # The ``head`` command writes the first ten lines of a file to the screen. # # First clear the screen then type: # # ``` # $ head science.txt # ``` # # Then type: # # ``` # $ head -5 science.txt # ``` # # What difference did the ``-5`` do to the head command? # # # **tail** # # The tail command writes the last ten lines of a file to the screen. # # Clear the screen and type: # # ``` # $ tail science.txt # ``` # # <img src="../img/logo_ex.png" align="left" style="width:1em; height:1em;"> **Exercise**: How can you view the last 15 lines of the file? # ### Searching the contents of a file # **Simple searching using ``less``** # # Using ``less``, you can search though a text file for a keyword (pattern). For example, to search through ``science.txt`` for the word "science", type: # # ``` # $ less science.txt # ``` # # then, still in ``less``, type a forward slash ``[/]`` followed by the word to search: # # ``` # /science # ``` # # And tape ``[enter]``. Type ``[n]`` to search for the next occurrence of the word. # # # **grep** # # ``grep`` is one of many standard linux utilities. It searches files for specified words or patterns. First clear the screen, then type: # # ``` # $ grep science science.txt # ``` # # As you can see, ``grep`` has printed out each line containg the word science. # # Or has it ???? # # Try typing: # # ``` # $ grep Science science.txt # ``` # # The ``grep`` command is case sensitive; it distinguishes between Science and science. # # To ignore upper/lower case distinctions, use the ``-i`` option, i.e. type: # # ``` # $ grep -i science science.txt # ``` # # To search for a phrase or pattern, you must enclose it in single quotes (the apostrophe symbol). For example to search for spinning top, type: # # ``` # $ grep -i 'spinning top' science.txt # ``` # # Some of the other options of ``grep`` are: # - ``-v`` display those lines that do NOT match # - ``-n`` precede each matching line with the line number # - ``-c`` print only the total count of matched lines # # Try some of them and see the different results. Don't forget, you can use more than one option at a time. For example, the number of lines without the words science or Science is: # # ``` # $ grep -ivc science science.txt # ``` # ### Take home points # We have only shown some examples of how to navigate in the linux directory structure and use some simple commands. This is by far not sufficient to demonstrate its usefulness: the ``grep`` command for example is extremely powerful to help you find files that you thought you had lost, and ``wget`` a file to a current directory is often much faster than downloading it in firefox and copy it afterwards. For the time being, this short tutorial should help get you started. # # **To go further**, I recommend to follow [Ryan's linux tutorials](https://ryanstutorials.net/linuxtutorial/), they are excellent! # ## Executable scripts # Now that you are familiar with the command line, you must have noticed that linux commands have some similarities with the **statements** you used in your bachelor programming course: by typing them in, the computer does things for you and gives you information back (often printed on screen, but not always). When you want to **automate** a series of commands you just typed in (for example renaming and moving files), a natural thing would be to write a **script** to do so. # # Scripts are the simplest type of program one can write, and this can be seen as your first programming experience in this course. We are going to write a **bash script** and execute it: why we want to do this in a python scientific programming course may be not clear right now, but it will make more sense later I promise. # ### A simple script # In your ``unixstuff`` directory, create a new file name ``myscript.sh``. You can do this using the default (graphical) text editor in linux, ``gedit``. At the command line: # # ```` # $ gedit myscript.sh # ``` # # Just type one simple line in the file: # # ``` # # echo Hello World! # # ``` # # Quit your editor and go back to the command line again. You can execute your script with the following command: # # ``` # $ bash myscript.sh # ``` # # **Bash** is a so-called "interpreter". It reads your file and understands how to execute the commands in it. # ### Make a file executable # List the files in your directory, but whith the option ``-l`` for more information. Here is how it looks like on my computer: # # ``` # mowglie@flappi-top ~/Documents/unixstuff $ ls -l # total 28 # drwxrwxr-x 2 <NAME> 4096 Feb 22 18:05 backup # -rw-rw-r-- 1 <NAME> 19 Feb 22 18:44 myscipt.sh # -rw-rw-r-- 1 mow<NAME>owglie 7767 Sep 1 2000 science.txt # ``` # # The first list of characters indicate the file's **permissions**. Now read the first section of [Ryan's tutorial about permissions](https://ryanstutorials.net/linuxtutorial/permissions.php). So what do we learn from the above? That the file's owner (myself) is allowed to read and write the ``myscript.sh`` file, but not to execute it. Let's change this: # # ``` # $ chmod a+x myscipt.sh # ``` # # Now everybody (including me) is allowed to execute this file. It is a quite harmless script, so I'm not too worried. Now we can execute it: # # ``` # $ ./myscript.sh # ``` # # Nice! We could add much more commands to our script (possibly making it more useful), but this was enough to illustrate the point I wanted to make: files can be executable in Linux, and a whole new world opens to us. # # **Note:** Most often, it is recommended to add a specific first line to your script, called a **shebang**. This line tells the computer which interpreter should be used to run the file. In our case it is the default interpreter (bash), but this may not always be the case. To be entirely explicit, we recommend to always add a shebang to your script. In this case, we should add ``#!/bin/bash`` to our script: # # ``` # # #!/bin/bash # # Maybe some comment line about the purpose of this script # # # echo Hello World! # ``` # ### Take home points # It is possible to write simple programs in linux called "scripts". These scripts can be executed by the default interpreter, and be made "executable" very easily. If you want to know more about bash scripts, read [Ryan's tutorial about the subject](https://ryanstutorials.net/bash-scripting-tutorial/)! # ## The linux PATH # ### Locate linux programs # You may have asked yourself: how does the linux command line know about the commands we are using? Where do I find them? A nice program helping us to find out is **which**. Let's use it: # # ``` # $ which less # /usr/bin/less # ``` # # Now we can use another command, **whatis**, to tell us what we just did: # # ``` # $ whatis which # ``` # # # The ``which`` command tells us that the ``less`` program is located in ``/usr/bin``. We can also ask ``which`` where to find ``which``: # # ``` # $ which which # /usr/bin/which # $ ls -l /usr/bin/which # lrwxrwxrwx 1 root root 10 Nov 19 14:42 /usr/bin/which -> /bin/which # ``` # # As expected, ``which`` is an executable file. Some executables are binary files (i.e. not human readable), but in this case ``which`` is actually a script: # # ``` # $ less which # ``` # # # <img src="../img/logo_ex.png" align="left" style="width:1em; height:1em;"> **Exercise**: scroll through the script. Can you locate the shebang line? How does the code look like to you: easily understandable, or rather cryptic? # ### The PATH variable # The linux command line knows so-called **environmental variables**. The ``echo`` command can display their value: # # ``` # $ echo $PATH # ``` # # (the ``$`` tells echo to display the value of the variable PATH rather than its name). The [PATH](http://www.linfo.org/path_env_var.html) variable contains a list of paths, separated by semicolons. It is an extremely important variable: it tells linux *where* to look for executables and programs. Each time you type a command, linux will look in the PATH and see if it finds it. This is an extremely flexible and powerful system, as we are going to see in the next chapter (Installing Python). # # The PATH can be extended to contain any other directory you find useful to add. Let's do it: # # ``` # $ mkdir ~/myprograms # $ export PATH=$PATH:~/myprograms # ``` # # ``export`` creates a new variable called PATH (in this case, it overwrites the existing PATH). # # <img src="../img/logo_ex.png" align="left" style="width:1em; height:1em;"> **Exercise**: now move your executable script ``myscript.sh`` in the ``myprograms`` directory. Verify that you can now execute the ``myscript.sh`` program from any directory. # # **Note:** we have extended the ``PATH`` variable in *this session* only. If you close and reopen the terminal the changes will be lost. There are ways to make these changes permanent, we will learn them in the next chapter. # # **Note:** if a program is listed in several path directories, linux takes the first instance. Directories can be prepended and appended, as we will see in the next chapter. # ### Take home points # The ``PATH`` variable tells linux where to look for programs and scripts. This is a very simple and powerful way to customize linux with your own scripts and programs. We are going to use this feature to install Python in the next chapter. # ## What's next? # Back to the [table of contents](00-Introduction.ipynb#ctoc), or [jump to the next chapter](02-Installation.ipynb).
notebooks/01-Linux.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from shapely.geometry import LineString, Polygon, Point, MultiPoint import pandas as pd from pathlib import Path import seaborn as sns from pprint import pprint import random import numpy as np from itertools import combinations, count, chain import matplotlib.pyplot as plt from functools import lru_cache import geopandas as gpd from shapely.affinity import affine_transform, scale import fractopo_subsampling.utils as utils # + boldstyle = dict(fontsize=14) def pcircle(point, radius): return point.buffer(radius) def row_y(vals, sim_row_y): return tuple((val[0], val[1] + sim_row_y) for val in vals) def circle_srs(coords, radii): return gpd.GeoSeries( [pcircle(Point(x, y), rad) for (x, y), rad in zip(coords, radii)] ) def backround_circles(base_coords, base_radii, sim_row_y): background_base = circle_srs(row_y(base_coords, sim_row_y=sim_row_y), base_radii) return background_base def boundary_plot(ax, circles): assert all(isinstance(geom, Polygon) for geom in circles.geometry.values) circles.boundary.loc[ [not geom.is_empty for geom in circles.boundary.geometry.values] ].plot(ax=ax, color="black") return ax def backround_plot(ax, circles): circles.plot(ax=ax, alpha=0.1, color="black") return ax def area_coords(coords, row_y, base_y): return tuple((coord[0], coord[1] + row_y + base_y) for coord in coords) def boldtext(ax, x, y, s): ax.text(x, y, s, rotation=90, va="center", **boldstyle) # - all_traces, all_areas, all_area_radii = [], [], [] for trace_path, area_path in zip( [ "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_traces_1.gpkg", "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_traces_2.gpkg", "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_traces_3.gpkg", ], [ "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_area_1.gpkg", "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_area_2.gpkg", "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/data/simulation_diagram_area_3.gpkg", ], ): traces, area_poly = gpd.read_file(trace_path), gpd.read_file(area_path) area_poly_radius = sum(np.sqrt(area_poly.area / np.pi)) - 1.2 all_traces.append(traces) all_area_radii.append(area_poly_radius) def transform_to_xy(x, y, geoms, area_poly_radius): geoms = geoms.copy() center = MultiPoint([p for p in geoms.representative_point()]).centroid affine_matrix = [1, 0, 0, 1, -center.x + x, -center.y + y] center_af = affine_transform(center, matrix=affine_matrix) factor = 25 / area_poly_radius geoms_transformed = geoms.affine_transform(affine_matrix).scale( xfact=factor, yfact=factor, origin=center_af ) return geoms_transformed # + fig, ax = plt.subplots(figsize=utils.paper_figsize(0.5)) base_circle_radii = 25, 25, 15 base_circle_areas = [np.pi * rad ** 2 for rad in base_circle_radii] base_circle_coords = (0, 0), (70, 0), (140, 0) base_circles = circle_srs(base_circle_coords, base_circle_radii) ax = boundary_plot(ax=ax, circles=base_circles) ax.tick_params( which="both", axis="both", bottom=False, top=False, left=False, labelleft=False, labelbottom=False, ) # Sim 1 sim_1_row_y = -70 sim_1_circle_radii = 5, 0, 10 sim_1_circle_coords = row_y(((10, 10), (70, 0), (140, -5)), sim_row_y=sim_1_row_y) sim_1_circles = circle_srs(sim_1_circle_coords, sim_1_circle_radii) background_base_1 = backround_circles( base_circle_coords, base_circle_radii, sim_1_row_y ) ax = backround_plot(ax=ax, circles=background_base_1) ax = boundary_plot(ax=ax, circles=sim_1_circles) # sim_1_circles.boundary.plot(ax=ax) # Sim 2 sim_2_row_y = sim_1_row_y * 2 sim_2_circle_radii = 15, 20, 0 sim_2_circle_coords = row_y(((-10, 5), (71, -5), (140, -5)), sim_row_y=sim_2_row_y) sim_2_circles = circle_srs(sim_2_circle_coords, sim_2_circle_radii) background_base_2 = backround_circles( base_circle_coords, base_circle_radii, sim_2_row_y ) ax = backround_plot(ax=ax, circles=background_base_2) ax = boundary_plot(ax=ax, circles=sim_2_circles) y_negator = count(0, step=sim_1_row_y) # Traces for coords, circles, true_coords in zip( (base_circle_coords, base_circle_coords, base_circle_coords), (base_circles, sim_1_circles, sim_2_circles), (base_circle_coords, sim_1_circle_coords, sim_2_circle_coords), ): y_minus = next(y_negator) for (x, y), circle, traces, area_poly_radius, true_coord in zip( coords, circles, all_traces, all_area_radii, true_coords ): y += y_minus assert isinstance(x, (int, float)) assert isinstance(circle, Polygon) assert isinstance(traces, (gpd.GeoSeries, gpd.GeoDataFrame)) assert isinstance(area_poly_radius, float) assert area_poly_radius > 0 transformed = transform_to_xy(x, y, traces, area_poly_radius) if circle.area > 0: clipped = gpd.clip(transformed, circle) clipped.plot(ax=ax) p21 = round(sum(clipped.length) / (circle.area * 0.1), 1) true_rad = np.sqrt(circle.area / np.pi) + 10 true_a = true_rad / np.sqrt((23 / 19) ** 2 + 1) ax.text( true_coord[0] - true_a, true_coord[1] + (true_a * (19 / 23)), s=f"P21={p21}", rotation=45, style="italic", ha="center", va="center", ) # Texts text_x_base = -42 boldtext(ax, text_x_base, 0, s="Base Circles") boldtext(ax, text_x_base, sim_1_row_y, s="I") boldtext(ax, text_x_base, sim_2_row_y, s="II") boldtext(ax, text_x_base - 10, -105, s="Subsampling Iterations") all_radii = chain(base_circle_radii, sim_1_circle_radii, sim_2_circle_radii) # identify iteration or lack of iteration = {0: None, sim_1_row_y: "I", sim_2_row_y: "II"} # Areas y_move = -32 for row_y_val in (0, sim_1_row_y, sim_2_row_y): for idx, (x, y) in enumerate(area_coords(base_circle_coords, row_y_val, y_move)): idx += 1 radius = next(all_radii) area_val = round(np.pi * radius ** 2, 1) identity = lambda var: f"${var}_{idx}" + ( "$" if iteration[row_y_val] is None else ("^{" + f"{iteration[row_y_val]}" + "}$") ) area_identity = identity("A") rad_identity = identity("r") ax.text( x, y, f"{rad_identity}={radius} $m$, {area_identity}={area_val} $m^2$", ha="center", style="italic", ) if area_val > 0 else None ax.text( x, y - y_move + 28, f"Probability {round(100 *(area_val / sum(base_circle_areas)), 1)} %", ha="center", style="italic", ) if row_y_val == 0 else None # IDs for base circles ider = count(1) for x, _ in base_circle_coords: ax.text(x, 37, s=str(next(ider)), **boldstyle) # Horizontal lines ax.axhline(-35, color="black", linestyle="-", linewidth=1.2) ax.axhline(-105, color="black", linestyle="dashed", linewidth=1.2) # Final setup fig.set_size_inches(*utils.paper_figsize(1)) fig.savefig( "/mnt/f/Users/nikke/Documents/projects/Academic_projects/gtk_ahvenanmaa/sampling_simulation/visualizations/subsampling_diagram.svg", bbox_inches="tight", ) # -
scripts_and_notebooks/notebooks/Subsampling_Diagram_Figure_4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Table of Contents # # <div class="alert alert-block alert-info" style="margin-top: 20px"> # # 1. [Exploring Datasets with *p*andas](#0)<br> # 2. [Downloading and Prepping Data](#2)<br> # 3. [Visualizing Data using Matplotlib](#4) <br> # 4. [Waffle Charts](#6) <br> # </div> # <hr> # + [markdown] button=false new_sheet=false run_control={"read_only": false} # # Exploring Datasets with *pandas* and Matplotlib<a id="0"></a> # # Toolkits: The course heavily relies on [*pandas*](http://pandas.pydata.org/) and [**Numpy**](http://www.numpy.org/) for data wrangling, analysis, and visualization. The primary plotting library we will explore in the course is [Matplotlib](http://matplotlib.org/). # # Dataset: Immigration to Canada from 1980 to 2013 - [International migration flows to and from selected countries - The 2015 revision](http://www.un.org/en/development/desa/population/migration/data/empirical2/migrationflows.shtml) from United Nation's website # # The dataset contains annual data on the flows of international migrants as recorded by the countries of destination. The data presents both inflows and outflows according to the place of birth, citizenship or place of previous / next residence both for foreigners and nationals. In this lab, we will focus on the Canadian Immigration data. # + [markdown] button=false new_sheet=false run_control={"read_only": false} # # Downloading and Prepping Data <a id="2"></a> # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Import Primary Modules: # + button=false new_sheet=false run_control={"read_only": false} import numpy as np # useful for many scientific computing in Python import pandas as pd # primary data structure library from PIL import Image # converting images into arrays # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Let's download and import our primary Canadian Immigration dataset using *pandas* `read_excel()` method. Normally, before we can do that, we would need to download a module which *pandas* requires to read in excel files. This module is **xlrd**. For your convenience, we have pre-installed this module, so you would not have to worry about that. Otherwise, you would need to run the following line of code to install the **xlrd** module: # ``` # # # !conda install -c anaconda xlrd --yes # ``` # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Download the dataset and read it into a *pandas* dataframe: # + button=false new_sheet=false run_control={"read_only": false} df_can = pd.read_excel('https://ibm.box.com/shared/static/lw190pt9zpy5bd1ptyg2aw15awomz9pu.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20), skip_footer=2) print('Data downloaded and read into a dataframe!') # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Let's take a look at the first five items in our dataset # + button=false new_sheet=false run_control={"read_only": false} df_can.head() # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Let's find out how many entries there are in our dataset # + button=false new_sheet=false run_control={"read_only": false} # print the dimensions of the dataframe print(df_can.shape) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Clean up data. We will make some modifications to the original dataset to make it easier to create our visualizations. Refer to *Introduction to Matplotlib and Line Plots* and *Area Plots, Histograms, and Bar Plots* for a detailed description of this preprocessing. # + button=false new_sheet=false run_control={"read_only": false} # clean up the dataset to remove unnecessary columns (eg. REG) df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis = 1, inplace = True) # let's rename the columns so that they make sense df_can.rename (columns = {'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace = True) # for sake of consistency, let's also make all column labels of type string df_can.columns = list(map(str, df_can.columns)) # set the country name as index - useful for quickly looking up countries using .loc method df_can.set_index('Country', inplace = True) # add total column df_can['Total'] = df_can.sum (axis = 1) # years that we will be using in this lesson - useful for plotting later on years = list(map(str, range(1980, 2014))) print ('data dimensions:', df_can.shape) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # # Visualizing Data using Matplotlib<a id="4"></a> # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Import `matplotlib`: # + button=false new_sheet=false run_control={"read_only": false} # %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.patches as mpatches # needed for waffle Charts mpl.style.use('ggplot') # optional: for ggplot-like style # check for latest version of Matplotlib print ('Matplotlib version: ', mpl.__version__) # >= 2.0.0 # + [markdown] button=false new_sheet=false run_control={"read_only": false} # # Waffle Charts <a id="6"></a> # # # A `waffle chart` is an interesting visualization that is normally created to display progress toward goals. It is commonly an effective option when you are trying to add interesting visualization features to a visual that consists mainly of cells, such as an Excel dashboard. # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Let's revisit the previous case study about Denmark, Norway, and Sweden. # + button=false new_sheet=false run_control={"read_only": false} # let's create a new dataframe for these three countries df_dsn = df_can.loc[['Denmark', 'Norway', 'Sweden'], :] # let's take a look at our dataframe df_dsn # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Unfortunately, unlike R, `waffle` charts are not built into any of the Python visualization libraries. Therefore, we will learn how to create them from scratch. # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 1.** The first step into creating a waffle chart is determing the proportion of each category with respect to the total. # + button=false new_sheet=false run_control={"read_only": false} # compute the proportion of each category with respect to the total total_values = sum(df_dsn['Total']) category_proportions = [(float(value) / total_values) for value in df_dsn['Total']] # print out proportions for i, proportion in enumerate(category_proportions): print (df_dsn.index.values[i] + ': ' + str(proportion)) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 2.** The second step is defining the overall size of the `waffle` chart. # + button=false new_sheet=false run_control={"read_only": false} width = 40 # width of chart height = 10 # height of chart total_num_tiles = width * height # total number of tiles print ('Total number of tiles is ', total_num_tiles) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 3.** The third step is using the proportion of each category to determe it respective number of tiles # + button=false new_sheet=false run_control={"read_only": false} # compute the number of tiles for each catagory tiles_per_category = [round(proportion * total_num_tiles) for proportion in category_proportions] # print out number of tiles per category for i, tiles in enumerate(tiles_per_category): print (df_dsn.index.values[i] + ': ' + str(tiles)) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Based on the calculated proportions, Denmark will occupy 129 tiles of the `waffle` chart, Norway will occupy 77 tiles, and Sweden will occupy 194 tiles. # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 4.** The fourth step is creating a matrix that resembles the `waffle` chart and populating it. # + button=false new_sheet=false run_control={"read_only": false} # initialize the waffle chart as an empty matrix waffle_chart = np.zeros((height, width)) # define indices to loop through waffle chart category_index = 0 tile_index = 0 # populate the waffle chart for col in range(width): for row in range(height): tile_index += 1 # if the number of tiles populated for the current category is equal to its corresponding allocated tiles... if tile_index > sum(tiles_per_category[0:category_index]): # ...proceed to the next category category_index += 1 # set the class value to an integer, which increases with class waffle_chart[row, col] = category_index print ('Waffle chart populated!') # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Let's take a peek at how the matrix looks like. # + button=false new_sheet=false run_control={"read_only": false} waffle_chart # + [markdown] button=false new_sheet=false run_control={"read_only": false} # As expected, the matrix consists of three categories and the total number of each category's instances matches the total number of tiles allocated to each category. # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 5.** Map the `waffle` chart matrix into a visual. # + button=false new_sheet=false run_control={"read_only": false} # instantiate a new figure object fig = plt.figure() # use matshow to display the waffle chart colormap = plt.cm.coolwarm plt.matshow(waffle_chart, cmap=colormap) plt.colorbar() # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 6.** Prettify the chart. # + button=false new_sheet=false run_control={"read_only": false} # instantiate a new figure object fig = plt.figure() # use matshow to display the waffle chart colormap = plt.cm.coolwarm plt.matshow(waffle_chart, cmap=colormap) plt.colorbar() # get the axis ax = plt.gca() # set minor ticks ax.set_xticks(np.arange(-.5, (width), 1), minor=True) ax.set_yticks(np.arange(-.5, (height), 1), minor=True) # add gridlines based on minor ticks ax.grid(which='minor', color='w', linestyle='-', linewidth=2) plt.xticks([]) plt.yticks([]) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # **Step 7.** Create a legend and add it to chart. # + button=false new_sheet=false run_control={"read_only": false} # instantiate a new figure object fig = plt.figure() # use matshow to display the waffle chart colormap = plt.cm.coolwarm plt.matshow(waffle_chart, cmap=colormap) plt.colorbar() # get the axis ax = plt.gca() # set minor ticks ax.set_xticks(np.arange(-.5, (width), 1), minor=True) ax.set_yticks(np.arange(-.5, (height), 1), minor=True) # add gridlines based on minor ticks ax.grid(which='minor', color='w', linestyle='-', linewidth=2) plt.xticks([]) plt.yticks([]) # compute cumulative sum of individual categories to match color schemes between chart and legend values_cumsum = np.cumsum(df_dsn['Total']) total_values = values_cumsum[len(values_cumsum) - 1] # create legend legend_handles = [] for i, category in enumerate(df_dsn.index.values): label_str = category + ' (' + str(df_dsn['Total'][i]) + ')' color_val = colormap(float(values_cumsum[i])/total_values) legend_handles.append(mpatches.Patch(color=color_val, label=label_str)) # add legend to chart plt.legend(handles=legend_handles, loc='lower center', ncol=len(df_dsn.index.values), bbox_to_anchor=(0., -0.2, 0.95, .1) ) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # And there you go! What a good looking *delicious* `waffle` chart, don't you think? # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Now it would very inefficient to repeat these seven steps every time we wish to create a `waffle` chart. So let's combine all seven steps into one function called *create_waffle_chart*. This function would take the following parameters as input: # # > 1. **categories**: Unique categories or classes in dataframe. # > 2. **values**: Values corresponding to categories or classes. # > 3. **height**: Defined height of waffle chart. # > 4. **width**: Defined width of waffle chart. # > 5. **colormap**: Colormap class # > 6. **value_sign**: In order to make our function more generalizable, we will add this parameter to address signs that could be associated with a value such as %, $, and so on. **value_sign** has a default value of empty string. # + button=false new_sheet=false run_control={"read_only": false} def create_waffle_chart(categories, values, height, width, colormap, value_sign=''): # compute the proportion of each category with respect to the total total_values = sum(values) category_proportions = [(float(value) / total_values) for value in values] # compute the total number of tiles total_num_tiles = width * height # total number of tiles print ('Total number of tiles is', total_num_tiles) # compute the number of tiles for each catagory tiles_per_category = [round(proportion * total_num_tiles) for proportion in category_proportions] # print out number of tiles per category for i, tiles in enumerate(tiles_per_category): print (df_dsn.index.values[i] + ': ' + str(tiles)) # initialize the waffle chart as an empty matrix waffle_chart = np.zeros((height, width)) # define indices to loop through waffle chart category_index = 0 tile_index = 0 # populate the waffle chart for col in range(width): for row in range(height): tile_index += 1 # if the number of tiles populated for the current category # is equal to its corresponding allocated tiles... if tile_index > sum(tiles_per_category[0:category_index]): # ...proceed to the next category category_index += 1 # set the class value to an integer, which increases with class waffle_chart[row, col] = category_index # instantiate a new figure object fig = plt.figure() # use matshow to display the waffle chart colormap = plt.cm.coolwarm plt.matshow(waffle_chart, cmap=colormap) plt.colorbar() # get the axis ax = plt.gca() # set minor ticks ax.set_xticks(np.arange(-.5, (width), 1), minor=True) ax.set_yticks(np.arange(-.5, (height), 1), minor=True) # add dridlines based on minor ticks ax.grid(which='minor', color='w', linestyle='-', linewidth=2) plt.xticks([]) plt.yticks([]) # compute cumulative sum of individual categories to match color schemes between chart and legend values_cumsum = np.cumsum(values) total_values = values_cumsum[len(values_cumsum) - 1] # create legend legend_handles = [] for i, category in enumerate(categories): if value_sign == '%': label_str = category + ' (' + str(values[i]) + value_sign + ')' else: label_str = category + ' (' + value_sign + str(values[i]) + ')' color_val = colormap(float(values_cumsum[i])/total_values) legend_handles.append(mpatches.Patch(color=color_val, label=label_str)) # add legend to chart plt.legend( handles=legend_handles, loc='lower center', ncol=len(categories), bbox_to_anchor=(0., -0.2, 0.95, .1) ) # + [markdown] button=false new_sheet=false run_control={"read_only": false} # Now to create a `waffle` chart, all we have to do is call the function `create_waffle_chart`. Let's define the input parameters: # + button=false new_sheet=false run_control={"read_only": false} width = 40 # width of chart height = 10 # height of chart categories = df_dsn.index.values # categories values = df_dsn['Total'] # correponding values of categories colormap = plt.cm.coolwarm # color map class # + [markdown] button=false new_sheet=false run_control={"read_only": false} # And now let's call our function to create a `waffle` chart. # + button=false new_sheet=false run_control={"read_only": false} create_waffle_chart(categories, values, height, width, colormap) # - # This notebook is part of the free course on **Cognitive Class** called *Data Visualization with Python*. If you accessed this notebook outside the course, you can take this free self-paced course online by clicking [here](https://cocl.us/DV0101EN_Lab4).
Waffle Charts.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Evaluating 2015-2018 Model on 2019 data import matplotlib import matplotlib.pyplot as plt import seaborn matplotlib.rcParams.update({'font.size': 22}) # ## Overall RMSE # The RMSE (to 3 decimal places) is 0.200, so worse than the 0.198 we get when we train and evaluate on subsets of 2015 data. # %%bigquery SELECT SQRT(SUM( (CAST(ontime AS FLOAT64) - predicted_ontime.scores[OFFSET(0)])* (CAST(ontime AS FLOAT64) - predicted_ontime.scores[OFFSET(0)]) )/COUNT(*)) AS rmse FROM dsongcp.ch10_automl_evaluated # ## Confusion matrix # # Let's find the fraction of true on-time flights at some threshold: # %%bigquery SELECT *, num_pred_ontime / num_ontime AS frac_1_as_1, num_pred_late / num_ontime AS frac_1_as_0, num_pred_ontime / num_late AS frac_0_as_1, num_pred_late / num_late AS frac_0_as_0 FROM ( SELECT 0.7 AS thresh, SUM(IF(CAST(ontime AS FLOAT64) > 0.5, 1, 0)) AS num_ontime, SUM(IF(CAST(ontime AS FLOAT64) <= 0.5, 1, 0)) AS num_late, SUM(IF(predicted_ontime.scores[OFFSET(0)] > 0.7, 1, 0)) AS num_pred_ontime, SUM(IF(predicted_ontime.scores[OFFSET(0)] <= 0.7, 1, 0)) AS num_pred_late, FROM dsongcp.ch10_automl_evaluated ) # + # %%bigquery WITH counts AS ( SELECT thresh, COUNTIF(CAST(ontime AS FLOAT64) > 0.5 AND predicted_ontime.scores[OFFSET(0)] > thresh) AS num_1_as_1, COUNTIF(CAST(ontime AS FLOAT64) > 0.5 AND predicted_ontime.scores[OFFSET(0)] <= thresh) AS num_1_as_0, COUNTIF(CAST(ontime AS FLOAT64) <= 0.5 AND predicted_ontime.scores[OFFSET(0)] > thresh) AS num_0_as_1, COUNTIF(CAST(ontime AS FLOAT64) <= 0.5 AND predicted_ontime.scores[OFFSET(0)] <= thresh) AS num_0_as_0 FROM UNNEST([0.5, 0.7, 0.8]) AS thresh, dsongcp.ch10_automl_evaluated GROUP BY thresh ) SELECT *, ROUND(num_1_as_1 / (num_1_as_1 + num_1_as_0), 2) AS frac_1_as_1, ROUND(num_1_as_0 / (num_1_as_1 + num_1_as_0), 2) AS frac_1_as_0, ROUND(num_0_as_1 / (num_0_as_1 + num_0_as_0), 2) AS frac_0_as_1, ROUND(num_0_as_0 / (num_0_as_1 + num_0_as_0), 2) AS frac_0_as_0 FROM counts ORDER BY thresh ASC # + # %%bigquery df WITH counts AS ( SELECT thresh, COUNTIF(CAST(ontime AS FLOAT64) > 0.5 AND predicted_ontime.scores[OFFSET(0)] > thresh) AS num_1_as_1, COUNTIF(CAST(ontime AS FLOAT64) > 0.5 AND predicted_ontime.scores[OFFSET(0)] <= thresh) AS num_1_as_0, COUNTIF(CAST(ontime AS FLOAT64) <= 0.5 AND predicted_ontime.scores[OFFSET(0)] > thresh) AS num_0_as_1, COUNTIF(CAST(ontime AS FLOAT64) <= 0.5 AND predicted_ontime.scores[OFFSET(0)] <= thresh) AS num_0_as_0 FROM UNNEST(GENERATE_ARRAY(0.0, 1.0, 0.01)) AS thresh, dsongcp.ch10_automl_evaluated GROUP BY thresh ) SELECT *, ROUND(num_1_as_1 / (num_1_as_1 + num_1_as_0), 2) AS frac_1_as_1, ROUND(num_1_as_0 / (num_1_as_1 + num_1_as_0), 2) AS frac_1_as_0, ROUND(num_0_as_1 / (num_0_as_1 + num_0_as_0), 2) AS frac_0_as_1, ROUND(num_0_as_0 / (num_0_as_1 + num_0_as_0), 2) AS frac_0_as_0 FROM counts ORDER BY thresh ASC # - df.head() ax = df.plot(x='thresh', y='frac_1_as_1', label='on-time', ylabel='fraction correct', style='r--'); df.plot(x='thresh', y='frac_0_as_0', label='late', ax=ax); # ## Impact of different variables # # Let's see how the model behaves with respect to specific feature values # %%bigquery df SELECT ROUND(predicted_ontime.scores[OFFSET(0)], 2) AS prob_ontime, AVG(CAST(dep_delay AS FLOAT64)) AS dep_delay, STDDEV(CAST(dep_delay AS FLOAT64)) AS std_dep_delay, AVG(CAST(taxi_out AS FLOAT64)) AS taxi_out, STDDEV(CAST(taxi_out AS FLOAT64)) AS std_taxi_out FROM dsongcp.ch10_automl_evaluated GROUP BY prob_ontime ORDER BY prob_ontime ASC df.plot(x='prob_ontime', y='dep_delay', ylabel='seconds'); # %%bigquery df2 SELECT ROUND(CAST(dep_delay AS FLOAT64), 0) AS dep_delay, AVG(predicted_ontime.scores[OFFSET(0)]) AS prob_ontime, FROM dsongcp.ch10_automl_evaluated GROUP BY dep_delay ORDER BY dep_delay ASC df2.plot(x='dep_delay', y='prob_ontime', xlim=[-10,100]); df.plot(x='prob_ontime', y='dep_delay', yerr='std_dep_delay', ylabel='seconds'); df.plot(x='prob_ontime', y='taxi_out', yerr='std_taxi_out', ylabel='seconds'); # ## Analyzing mistakes # # Looking at correct vs. wrong predictions # + # %%bigquery df WITH preds AS ( SELECT CAST(ontime AS FLOAT64) AS ontime, ROUND(predicted_ontime.scores[OFFSET(0)], 2) AS prob_ontime, CAST(dep_delay AS FLOAT64) AS var, FROM dsongcp.ch10_automl_evaluated ) SELECT prob_ontime, AVG(IF((ontime > 0.5 and prob_ontime <= 0.5) or (ontime <= 0.5 and prob_ontime > 0.5), var, NULL)) AS wrong, AVG(IF((ontime > 0.5 and prob_ontime > 0.5) or (ontime <= 0.5 and prob_ontime <= 0.5), var, NULL)) AS correct FROM preds GROUP BY prob_ontime ORDER BY prob_ontime # - ax = df.plot(x='prob_ontime', y='wrong', ylim=(0, 50), ylabel='dep_delay', style='r--'); df.plot(x='prob_ontime', y='correct', ax=ax, ylim=(0, 50)); # + # %%bigquery df WITH preds AS ( SELECT CAST(ontime AS FLOAT64) AS ontime, ROUND(predicted_ontime.scores[OFFSET(0)], 2) AS prob_ontime, CAST(taxi_out AS FLOAT64) AS var, FROM dsongcp.ch10_automl_evaluated ) SELECT prob_ontime, AVG(IF((ontime > 0.5 and prob_ontime <= 0.5) or (ontime <= 0.5 and prob_ontime > 0.5), var, NULL)) AS wrong, AVG(IF((ontime > 0.5 and prob_ontime > 0.5) or (ontime <= 0.5 and prob_ontime <= 0.5), var, NULL)) AS correct FROM preds GROUP BY prob_ontime ORDER BY prob_ontime # - ax = df.plot(x='prob_ontime', y='wrong', ylim=(0, 30), ylabel='taxi_out', style='r--'); df.plot(x='prob_ontime', y='correct', ax=ax, ylim=(0, 30)); # ## Categorical Features # # %%bigquery df2 SELECT ROUND(CAST(dep_delay AS FLOAT64), 0) AS dep_delay, AVG(IF(origin='JFK', predicted_ontime.scores[OFFSET(0)], NULL)) AS JFK, AVG(IF(origin='SEA', predicted_ontime.scores[OFFSET(0)], NULL)) AS SEA, FROM dsongcp.ch10_automl_evaluated GROUP BY dep_delay ORDER BY dep_delay ASC ax = df2.plot(x='dep_delay', y='JFK', xlim=[-10,100], style='r--'); df2.plot(x='dep_delay', y='SEA', xlim=[-10,100], ax=ax); # %%bigquery df2 SELECT carrier, ROUND(CAST(dep_delay AS FLOAT64), 0) AS dep_delay, AVG(predicted_ontime.scores[OFFSET(0)]) AS prob_ontime FROM dsongcp.ch10_automl_evaluated GROUP BY carrier, dep_delay ORDER BY carrier ASC, dep_delay ASC df = df2.copy() df.head() df = df2.set_index('dep_delay') df.head() dfg = df2[df2['dep_delay'] == 20.0].sort_values(by='prob_ontime').reset_index(drop=True) dfg print(dfg.loc[0]['carrier']) print(dfg.loc[0]['prob_ontime']) # + fig, ax = plt.subplots(figsize=(15,15)) df.groupby('carrier')['prob_ontime'].plot(xlim=[-10,60], legend=True, ax=ax, lw=4); ax.annotate(dfg.loc[0]['carrier'], xy=(20.0, dfg.loc[0]['prob_ontime']), xycoords='data', xytext=(-50, -30), textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.2')); ax.annotate(dfg.loc[4]['carrier'], xy=(20.0, dfg.loc[4]['prob_ontime']), xycoords='data', xytext=(-80, -60), textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.2')); ax.annotate(dfg.loc[11]['carrier'], xy=(20.0, dfg.loc[11]['prob_ontime']), xycoords='data', xytext=(50, 60), textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.2')); ax.annotate(dfg.loc[16]['carrier'], xy=(20.0, dfg.loc[16]['prob_ontime']), xycoords='data', xytext=(50, 30), textcoords='offset points', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.2')); # - # Copyright 2021 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
11_realtime/evaluation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Beberapa bagian yang paling penting di Jupyter Notebook yang kita akan pakai di buku ini adalah menu dan cell. Di Menu ada beberapa tombol untuk membantu kita melakukan macem-macem hal seperti save, restart session, convert, insert cell dan lain-lainnya. Jika anda sudah sering pakai Jupyter Notebook lama-lama akan lebih sering pakai *short-cut* daripada menu. Namun untuk awal-awal, ada baiknya sering lihat fungsi-fungsi yang ada di menu. # # Di Jupyter Notebook, anda akan mengetik kode-kode yang diperlukan di sebuah kotak yang bernama "cell". Di buku ini, kita hanya memerlukan dua tipe cell yaitu "code" dan "markdown". Anda memerlukan tipe cell "code" untuk mengetik kode yang akan dijalankan oleh python. Jika kode yang anda masukkan dapat dibaca oleh pyton, maka hasilnya akan muncul di output. Output itu bukan sesuatu yang anda ketik, tapi sesuatu yang muncul setelah anda menjalankan (*run*) kode anda di cell code. # # Untuk menjalankan sebuah kode, anda ketik kode-nya di cell , lalu klik tombol {{< icon name="play" pack="fas" >}} run, atau dengan *short-cut* `ctrl+enter` atau `shift+enter`. # # Sementara itu, anda dapat menggunakan cell "markdown" untuk tujuan mengetik. Cell markdown tidak bisa di-jalankan dan tidak akan mengeluarkan output apapun. # # Setiap cell sendiri memiliki dua mode, yaitu command mode dan edit mode. ketika cell anda berwarna hijau, artinya anda sedang di mode edit. Anda dapat mengetik di cell yang sedang aktif. Ketika cell berwarna biru, artinya anda sedang di mode command. Mode command membuat *keyboard* anda mengaktifkan *shortcut* dan bukan mengetik. # # Untuk masuk ke edit mode, anda cukup me-klik cell yang ingin anda edit. Jika anda klik area lain di luar cell, maka anda akan masuk ke command mode. *Short-cut* untuk masuk ke edit mode adalah `enter`, sementara untuk ke command mode adalah `escape`. # # ## menyimpan jupyter notebook # # #### .ipnyb # File jupyter notebook akan secara otomatis tersimpan dengan ekstensi <nama>.ipnyb. Anda baru bisa buka file dengan ekstensi .ipynb jika anda memulai anaconda. Jadi jangan lupa untuk membuka jupyter notebook melalui anaconda navigation atau anaconda prompt terlebih dahulu. # # #### pdf # Untuk menyimpannya dalam bentuk pdf, gunakan # # `file -> download as -> .html` # # anda akan memiliki file <nama>.html. Buka file tersebut dengan browser anda (chrome, edge, safari, mozila) lalu tekan `ctrl+p` lalu pilih "print to pdf". # # #### Word (docx) # Jika anda sudah menginstall [pandoc](https://pandoc.org/installing.html), anda bisa menyimpan `<nama>.ipynb` dalam wujud word (docx). Anda pertama perlu file `<nama>.html` terlebih dahulu dengan melakukan # # `file -> download as -> .html` (sama seperti mau membuat pdf). # # Setelah punya file `<nama>.html`, anda tinggal membuka anaconda prompt atau cmd prompt, lalu ketik: # # ``` # pandoc -s <nama>.html -o <nama>.docx # ``` # # ## Kode-kode Sederhana # ###### beberapa hal yang dapat anda lakukan # Silakan coba-cobain nge-run sembarangan. Anda dapat mendelete cell dengan tekan tombol d dua kali di command mode. # Menulis angka 1 # fungsi tambah-tambahan 1+1 # menulis kalimat harus menggunakan tanda petik "apa kabar dunia?" # tes logika (boolean) 1 > 2 # ###### menempelkan informasi ke dalam sebuah obyek # Salah satu kelebihan python adalah betapa mudahnya melekatkan informasi (dalam bentuk kode/ekspresi/data) kepada sebuah obyek. Anda melekatkan informasi dengan menggunakan tanda `=` # lekatkan '1+1' kepada obyek bernama 'x' x=1+1 # seperti anda lihat di atas, jika 1+1 kita lekatkan ke sebuah obyek, maka outputnya tidak langsung dicetak. anda harus panggil dulu obyek tersebut dengan mengetik namanya, atau menggunakan fungsi `print()` # memunculkan output x x # memunculkan output x dengan fungsi print print(x) # Dalam hal ini, menggunakan fungsi `print()` menghasilkan output yang sama persis dengan mengetik langsung nama obyeknya. Tapi nanti kita akan melihat beberapa kegunaan `print()` yg lain ketika obyek kita isinya lebih ribet daripada sekedar `1+1` # # Anda juga dapat memanipulasi obyek x dengan operasi matematika sepert `+` dan `-` dan lainnya. # Menambahkan x dengan 3 x+3 # menempelkan x+3 ke obyek lain dan langsung mencetaknya y=x+3 y # menambahkan 2 obyek dan melekatkannya ke obyek ke-3 z = x + y z # ketikan setelah tanda `#`pagar akan diabaikan oleh python. Peneliti biasanya menggunakan tanda `#`pagar untuk memberi komentar atau keterangan tentang kode yang mereka jalankan. Jika anda menggunakan Jupyter Notebook untuk mengerjakan skripsi atau tugas kuliah, saya sangat merekomendasikan menggunakan tanda `#`pagar untuk memberi keterangan tentang kode anda kepada teman atau pemeriksa. # # Jadi jika anda ingin menulis komentar atau keterangan tentang kode yang anda tulis, gunakan tanda `#`pagar z = z-6 # mengubah Z, sebelumnya z=5 z # y sudah diupdate dengan mengurangkan dengan 6 # ## Tentang fungsi # # kita akan menggunakan banyak sekali fungsi ketika memanipulasi obyek di python, seperti `print()`. Seiring dengan mengikuti buku ini, kita akan melihat beberapa fungsi lain yang esensial untuk melakukan analisis statistika. # # Jika anda tidak mengerti sebuah fungsi tuh sebenernya melakukan apa, anda dapat menggunakan tanda `?` setelah mengetik fungsi. Pastikan anda terhubung dengan internet. # # Coba anda jalankan kode `print?` dan lihat apa yang terjadi. # ## Tentang paket / modul # # Di python ada yang disebut "package" atau "module", saya bahasa Indonesiakan menjadi paket atau modul. Paket-paket ini berisi fungsi-fungsi yang aslinya tidak ada di python, tapi setelah dipanggil / diimpor, jadi bisa kita gunakan. Beberapa paket ini sangat esensial untuk *data science*, seperti `pandas` dan `matplotlib`. # # kita memanggil paket ini dengan kode import. Contoh, mari kita gunakan paket `sys` untuk melihat versi python yang kita gunakan di komputer kita import sys sys.version # fungsi `sys.version` tidak ada di python original. Kita harus memanggilnya terlebih dahulu dengan menggunakan `import sys` supaya dapat menggunakan fungsi-fungsi yang ada `sys`-nya. Import paket tidak perlu dilakukan di setiap cell. Cukup sekali saja untuk setiap sesi. Tapi jika anda buka python baru, anda harus import lagi untuk sesi tersebut. # ## Tentang tipe (type) obyek # # Obyek di python dapat digolongkan menjadi beberapa tipe. anda dapat mengetahui tipe sebuah obyek dengan menggunakan fungsi `type('obyek')`. Contohnya: type(x) type([x,y,z]) type("apa kabar dunia?") type(1<2) # seperti dapat anda lihat di atas, ada setidaknya 4 tipe obyek yang dikenali oleh python. X, sebuah obyek yang berisi sebuah angka 2, dikenali sebagai `int`, kependekan dari integer. susunan obyek yang terdiri dari x, y, dan z, dikenali sebagai `list`. Sementara itu, frasa "apa kabar dunia?" dikenali sebagai `str`, atau kependekan dari string. Sementara yang terakhir, `bool` kependekan dari boolean, adalah logika. # # Tipe-tipe ini sangat penting untuk diketahui karena kita akan memanipulasi mereka dengan cara yang berbeda-beda. # # #### Angka (integer dan float) # # Di python, ada dua tipe untuk angka, yaitu integer (int) dan floating (float). Integer adalah bilangan cacah, yaitu bilangan yang terdiri dari angka tanpa koma koma. Float adalah bilangan bulat, yaitu bilangan yang ada koma-koma nya. # # Misalnya, Pak Tedjo punya tiga orang anak. artinya, anak pak tedjo adalah obyek bilangan cacah (integer). Di desa Pak Tedjo, kepala keluarganya memiliki rata-rata 2,3 orang anak. Rata-rata anak di desa Pak Tedjo adalah obyek bilangan bulat (float). Tipe yang akan kita gunakan akan tergantung dari jenis data yang kita miliki. # # Di Python, kita akan gunakan `.` sebagai koma. Kenapa? Yah orang barat pakai titik sebagai koma jadi kita ikut aja. Kita gunakan `_` untuk pemisah ribuan. a=3 type(a) b=2.3 type(b) # interaksi antara integer dan float akan menjadi float type(a+b) # #### Huruf (Strings) # # Di python, obyek yang berisi huruf disebut `str` atau `string`. Misalnya data yang isinya nama, maka data tersebut akan dikategorikan sebagai string. Namun demikian, angka juga dapat dikategorikan sebagai `string` jika angka tersebut tidak memiliki makna hitung apapun. Maksudnya, nomor yang bertipe `str` tidak dapat dibandingkan maupun ditambah atau dikurangi. Misalnya, orang yang punya nomor rekening 1234 tidak berarti duitnya lebih banyak daripada orang yang nomor rekeningnya 1235. Untuk menyimpan data string, anda harus menggunakan tanda petik. Boleh `'`, boleh juga `"`. type(3) type('3') # angka 3 akan menjadi string jika dikelilingi dengan tanda petik. type("3") 3+3 "3" + 3 # angka bertipe string tidak dapat ditambah dengan angka bertipe integer. # Anda dapat menambahkan string dengan string di python. Tapi di R tidak bisa yaa "nama saya adalah" + "<NAME>" # ups. harusnya dikasih spasi. anda juga bisa menambahkan dua obyek string a = "nama <NAME>alah " # lihat saya nambahin spasi setelah adalah b = "<NAME>" a+b # string dapat dikali dengan integer untuk mengulang string tersebut a+b*3 # apa yang terjadi kalau b yg isinya "<NAME>" dikali 3? (a+b)*3 # bagaimana jika (a+b) yang dikali 3? # Manipulasi string bisa lebih keren lagi dengan contoh berikut ini: # + nama="<NAME>" usia=50 pekerjaan="Pak RT" tentang_Tedjo=f"{nama} adalah seorang bapak-bapak berusia {usia} tahun yang bekerja sebagai {pekerjaan}" print(tentang_Tedjo) # - # dapatkah anda memahami apa yang terjadi di atas? Apa fungsi dari {}? di tahun depan, usia <NAME> akan bertambah 1 tahun. Bagaimana mengubah "tentang_Tedjo" yang paling mudah dan cepat? # # #### Boolean (logika) # Boolean adalah tipe yang bentuknya logika. Biasanya kita menggunakan ini untuk fungsi `if`, `else` dan kombinasinya. t=True f=False type(t) type(f) # Boolean hanya terdiri dari dua ekspresi, yaitu `True` dan `False`. Jangan lupa untuk **tidak** menggunakan tanda petik. Boolean dapat ditambahkan, di mana `True` bernilai 1 sementara `False` bernilai 0. Hasilnya akan menjadi `int` atau `float` Kita akan lebih jauh mengeksplorasi ini nanti. t+f type(t+f)
content/id/courses/pystat/.ipynb_checkpoints/Jupyter-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # <h1>Slicing Arrays</h1> import numpy as np my_vector = np.array ([-17, -4, 0, 2, 21, 37, 105]) my_vector my_vector[0] my_vector[0] = -102 my_vector my_vector[-3] my_vector[305] 305 % 7 my_vector[305 % 7] my_vector.size my_vector[305 % my_vector.size] # <h2>Two Dimensional Arrays</h2> my_array= np.arange(35) my_array.shape = (7,5) my_array my_array[2] my_array[-2] my_array[5,2] row = 5 column = 2 my_array[row, column] my_array[5][2] # <h2>Three Dimensional Arrays</h2> my_3D_array = np.arange(70) my_3D_array.shape = (2, 7, 5) my_3D_array my_3D_array[1] my_3D_array[1,3] my_3D_array[1,3,2] =1111 my_3D_array
numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 3/03_01/Finish/Slicing.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn import metrics # **Choose input file** # + comp_file = "gen_descriptors" comp_sheet = "Sheet1" num_par = 190 par_start_col = 2 comp_num_samples = 1560 y_label_col_comp = 0 exp_file = "gen_rxn_data" exp_sheet = "Phosphines" exp_num_samples = 1776 response_col = 3 y_label_col_exp = 2 # - # **Sort data** # + code_folding=[] compinp = pd.read_excel(comp_file+".xlsx",comp_sheet,header=0,index_col=y_label_col_comp,nrows=comp_num_samples+1,usecols=list(range(0,(num_par+par_start_col))),engine='openpyxl') compinp = compinp.drop(['smiles'],axis=1) par_start_col = 1 compinp.index = compinp.index.map(str) expinp = pd.read_excel(exp_file+".xlsx",exp_sheet,header=2,index_col=y_label_col_exp,nrows=exp_num_samples,usecols=list(range(0,response_col+1)),engine='openpyxl') X_names = list(compinp.iloc[0,par_start_col-1:num_par+par_start_col-1]) X_labels = list(compinp.columns)[par_start_col-1:num_par+par_start_col-1] compinp.drop(index=compinp.index[0],inplace=True) X_all = np.asarray(compinp[X_labels],dtype=np.float) y_labels_comp = np.asarray(list(compinp.index),dtype=str) compnan = np.isnan(X_all).any(axis=1) y_labels_comp,X_all = y_labels_comp[~compnan],X_all[~compnan] X_labelname = [" ".join(i) for i in zip(X_labels,X_names)] X_labelname_dict = dict(zip(X_labels,X_names)) resp_label = list(expinp.columns)[response_col-1] y = np.asarray(expinp.iloc[:,response_col-1],dtype=np.float) y_labels_exp = np.asarray(list(expinp.index),dtype=str) mask_y = y.nonzero()[0] mask_y = ~np.isnan(y) mask_X = np.array([True if i in y_labels_comp else False for i in y_labels_exp]) mask = mask_y&mask_X print("Number of entries in experimental file before removing empty cells: {}".format(len(y))) print("Removing {} entries with empty cells".format(len(y)-sum(mask))) y = y[np.array(mask)] y_labels = y_labels_exp[np.array(mask)] X = np.asarray(compinp.loc[y_labels],dtype=np.float) print("Shape of descriptors file for all ligands: {}".format(X_all.shape)) print("Last three ids in the descriptor file: {}".format(y_labels_comp[-3:])) print("Shape of descriptors file for ligands with experimental results: {}".format(X.shape)) print("Shape of results file results (only ligands with experimental results): {}".format(y.shape)) print("Shape of results file labels (only ligands with experimental results): {}".format(y_labels.shape)) print("First descriptor cell (for ligands with experimental results): {}".format(X[0,0])) print('Ligands with results:',y_labels) print('Experimental results:',y) # - # **Standard threshold analysis (single-node decision tree)** # + #features = range(len(X_labels)) # test all features features = [86] # test single feature (Vmin (Boltz) = 0, Vbur (min) = 86) y_cut = 10.0 y_class = np.array([0 if i < y_cut else 1 for i in y]) n_classes = 2 plot_colors = "rg" plot_step = 0.02 # originally 0.02 accuracy_cutoff = 0.0 # filter thresholds based on accuracy cutoff for f_ind in features: feature = X_labels[f_ind] dt = DecisionTreeClassifier(max_depth=1).fit(X[:,f_ind].reshape(-1, 1), y_class) if dt.score(X[:,f_ind].reshape(-1, 1), y_class) >= accuracy_cutoff: print(feature, X_names[f_ind]) print("Decision threshold = {:.2f}\nAccuracy: {:.2f}\nf1_score: {:.2f}\nNumber datapoints = {}".format( dt.tree_.threshold[0],dt.score(X[:,f_ind].reshape(-1, 1), y_class),metrics.f1_score(y_class,dt.predict(X[:,f_ind].reshape(-1, 1))),len(y))) dt_plt = DecisionTreeClassifier(max_depth=1).fit(X[:,f_ind].reshape(-1, 1), y_class) x_min, x_max = X[:,f_ind].min(), X[:,f_ind].max() y_min, y_max = y.min(), y.max() dx,dy = x_max-x_min,y_max-y_min xx, yy = np.meshgrid(np.arange(x_min-0.04*dx, x_max+0.04*dx, plot_step), np.arange(y_min-0.04*dy, y_max+0.04*dy, plot_step)) plt.figure(figsize=(6, 6)) Z = dt_plt.predict(xx.ravel().reshape(-1, 1)) Z = Z.reshape(xx.shape) cs = plt.contourf(xx, yy, Z,colors=['#ffb8b8','#FF000000','#FF000000','#FF000000']) pltlabel = X_labels[f_ind] + " " + X_names[f_ind] plt.xlabel(pltlabel,fontsize=14) plt.ylabel("yield (%)",fontsize=14) plt.xticks(fontsize=12.5) plt.yticks(fontsize=12.5) for i, color in zip(range(n_classes), plot_colors): idx = np.where(y_class == i) plt.scatter(X[idx, f_ind], y[idx], c=color,cmap=plt.cm.RdYlBu, edgecolor='black', s=50) plt.show() # - # **Plot two descriptors with a colormap of reaction output** # *Set up for HTE 3aa THF/H2O selectivity results* plt.figure(figsize=(12, 8)) plt.xlabel("Vmin (Boltz)",fontsize=18) plt.ylabel('Vbur (min., Å3)',fontsize=18) plt.xticks(fontsize=18) plt.xlim(-0.07, -0.035) plt.locator_params(axis='x', nbins=4) plt.ylim(40, 70) plt.yticks(fontsize=18) plt.locator_params(axis='y', nbins=5) plt.scatter(X[:,0],X[:,86], c=y,cmap="bwr", edgecolor='black', s=200) cbar = plt.colorbar() cbar.set_label("Selectivity (ddG)",rotation=90,size=18) cbar.ax.locator_params(nbins=5) plt.clim(vmin=-1, vmax=1) plt.show() # *Set up for HTE 3aa THF/H2O yield results* plt.figure(figsize=(12, 8)) plt.xlabel("Vmin (Boltz)",fontsize=18) plt.ylabel('Vbur (min., Å3)',fontsize=18) plt.xticks(fontsize=18) plt.xlim(-0.088, 0) plt.locator_params(axis='x', nbins=5) plt.yticks(fontsize=18) plt.ylim(37, 104) plt.locator_params(axis='y', nbins=4) plt.scatter(X[:,0],X[:,86], c=y,cmap="Oranges", edgecolor='black', s=200) cbar = plt.colorbar() cbar.set_label("Yield (%)", rotation=90,size=18) plt.clim(vmin=0, vmax=100) plt.show()
gen_threshold_and_multidescriptor_plot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import tkinter from tkinter import messagebox def main(): def confirm_to_quit(): if messagebox.askokcancel('Message', 'Sure to exit?'): top.quit() def change_label_text(): label.config(text='Goodbye, world1', fg='blue') top = tkinter.Tk() top.geometry('240x160') top.title('Game') label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red') label.pack(expand=1) panel = tkinter.Frame(top) button_exit = tkinter.Button(panel, text='exit', command=confirm_to_quit) button_exit.pack(side='right') button1 = tkinter.Button(panel, text='Change', command=change_label_text) button1.pack(side='left') panel.pack(side='bottom') tkinter.mainloop() main() import pygame from enum import Enum, unique from math import sqrt from random import randint # + @unique class Color(Enum): """颜色""" RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (242, 242, 242) @staticmethod def random_color(): """获得随机颜色""" r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) return (r, g, b) class Ball(object): """球""" def __init__(self, x, y, radius, sx, sy, color=Color.RED): """初始化方法""" self.x = x self.y = y self.radius = radius self.sx = sx self.sy = sy self.color = color self.alive = True def move(self, screen): """移动""" self.x += self.sx self.y += self.sy if self.x - self.radius <= 0 or \ self.x + self.radius >= screen.get_width(): self.sx = -self.sx if self.y - self.radius <= 0 or \ self.y + self.radius >= screen.get_height(): self.sy = -self.sy def eat(self, other): """吃其他球""" if self.alive and other.alive and self != other: dx, dy = self.x - other.x, self.y - other.y distance = sqrt(dx ** 2 + dy ** 2) if distance < self.radius + other.radius \ and self.radius > other.radius: other.alive = False self.radius = self.radius + int(other.radius * 0.146) def draw(self, screen): """在窗口上绘制球""" pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius, 0) def main(): # 定义用来装所有球的容器 balls = [] # 初始化导入的pygame中的模块 pygame.init() # 初始化用于显示的窗口并设置窗口尺寸 screen = pygame.display.set_mode((800, 600)) # 设置当前窗口的标题 pygame.display.set_caption('大球吃小球') running = True # 开启一个事件循环处理发生的事件 while running: # 从消息队列中获取事件并对事件进行处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 处理鼠标事件的代码 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: # 获得点击鼠标的位置 x, y = event.pos radius = randint(10, 100) sx, sy = randint(-10, 10), randint(-10, 10) color = Color.random_color() # 在点击鼠标的位置创建一个球(大小、速度和颜色随机) ball = Ball(x, y, radius, sx, sy, color) # 将球添加到列表容器中 balls.append(ball) screen.fill((255, 255, 255)) # 取出容器中的球 如果没被吃掉就绘制 被吃掉了就移除 for ball in balls: if ball.alive: ball.draw(screen) else: balls.remove(ball) pygame.display.flip() # 每隔50毫秒就改变球的位置再刷新窗口 pygame.time.delay(50) for ball in balls: ball.move(screen) # 检查球有没有吃到其他的球 for other in balls: ball.eat(other) # - main()
Tkinter-GUI & Pygame.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Setting up + Problem Solving in Python # ### [y3l2n](http://twitter.com/y3l2n) # + [markdown] slideshow={"slide_type": "slide"} # # Outline # * Development environment # * Writing/running code # * Useful python modules for data anaylsis # * Basic data analysis without any modules # + [markdown] slideshow={"slide_type": "slide"} # # Development Environment # * Caveat: Linux/Mac OS X oriented # * Distributions of python (python2 vs. python3; conda vs. system python) # * Isolating your development environment (virtualenvs + conda environments + pipenv) # * How to install modules (pip, conda) # # + [markdown] slideshow={"slide_type": "slide"} # # What should I use to write code? # <br> # #### Writing + running code are separate # * Command line text editor (vim, emacs, nano) # * Desktop text editor (Notepad++, Kate, Atom) # # <br> # # #### Writing and running code are packaged together # * IDE (PyCharm, Eclipse, IDLE) # * Jupyter notebook # # + [markdown] slideshow={"slide_type": "slide"} # # Useful Python modules for data analytics # * Pandas # * scipy # * numpy # * scikit-learn # * nltk # * gensim # * matplotlib # * bokeh # # + [markdown] slideshow={"slide_type": "slide"} # # Problem Solving & good practices # * type, dir, and inspect # * Reading other source code # * Tests!! # * [Learn to love errors](https://docs.python.org/3/library/exceptions.html) # + [markdown] slideshow={"slide_type": "slide"} # # Vocabulary # # You won't remember all of this, but it's good to know about # # * Memory considerations # * Run time considerations # * Python documentation about its own data structures # * vectorization + optimization # - # # My favorite things # * collections, itertools # * inspect, sys (sys.getsizeof) # * reading beautiful code # + [markdown] slideshow={"slide_type": "slide"} # # Live Demo # - type(3) type("hello") type(3.14159) type(str) # what happens when I try to import? import pandas as pd # + slideshow={"slide_type": "slide"} # let's try again import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline # + slideshow={"slide_type": "slide"} df = pd.read_csv("College.csv") # + slideshow={"slide_type": "slide"} # let's do a bit of exploration type(df) # + slideshow={"slide_type": "slide"} # exploring this dataframe dir(df) # + slideshow={"slide_type": "slide"} # real quick understanding of the top couple rows df.head() # + slideshow={"slide_type": "slide"} # how do I find the columns? df.columns # + slideshow={"slide_type": "slide"} # accessing and subsetting data # this is zero-indexed df.iloc[1:3] # + slideshow={"slide_type": "slide"} # because I like plots axes = pd.tools.plotting.scatter_matrix(df.iloc[1:3], alpha=0.2) plt.tight_layout() # + [markdown] slideshow={"slide_type": "slide"} # # The inspect module # - import inspect inspect.getsourcelines(df.drop_duplicates) # + [markdown] slideshow={"slide_type": "slide"} # # Data analysis from the Python standard library # - import csv college2 = list(csv.DictReader(open('College.csv'))) # + slideshow={"slide_type": "slide"} type(college2) # - len(college2) college2[0] # + slideshow={"slide_type": "slide"} # how many are private? list_of_private = [item['private'] for item in college2] # - list_of_private = [item['Private'] for item in college2] # + slideshow={"slide_type": "slide"} type(list_of_private) # - list_of_private[:2] # + slideshow={"slide_type": "slide"} from collections import Counter Counter(list_of_private) # + slideshow={"slide_type": "slide"} student_fac_ratio = Counter([item['S.F.Ratio'] for item in college2]) # - dir(student_fac_ratio) student_fac_ratio.most_common(3)
notebooks/Setting up and Problem Solving in Python - with a DS Bias.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set_style('whitegrid') # %matplotlib inline train = "//home//vinicius//Data_Science//Notebooks//Kaggle//DataSets//titanic//train.csv" test = "//home//vinicius//Data_Science//Notebooks//Kaggle//DataSets//titanic//test.csv" df1 = pd.read_csv(train) df2 = pd.read_csv(test) df1.head() df1.info() # ## Train DataSet # #### Total of rows: 891 # #### Total of Columns: 12 df2.head() df2.info() # ## Test DataSet # #### Total Rows: 418 # #### Total Columns: 11 ## Checking NULL values plt.figure(figsize=(8,6)) sns.heatmap(df1.isnull(), yticklabels=False, cbar=False, cmap='viridis') ## Analysis by sex sns.countplot(x='Survived', hue='Sex', data=df1) ## Analysis by class sns.countplot(x='Survived', hue='Pclass',data=df1) ## Economic class was the one who most died # + ## what means cabin letter? If your cabin is deep your chance to die increase? # - sns.countplot(x='SibSp', data = df1) # # Dealing with missing values ## Checking Age/Class (what do with missing values on age?) plt.figure(figsize=(12,8)) sns.boxplot(x='Pclass',y='Age', data=df1) # **Better class, older person mean** # **Fill missing values on age with class mean** print("Age Mean Class 1: ", df1[df1['Pclass']==1]['Age'].mean()) print("Age Mean Class 2: ", df1[df1['Pclass']==2]['Age'].mean()) print("Age Mean Class 3: ", df1[df1['Pclass']==3]['Age'].mean()) def fill_ages(data): age = data[0] pclass = data[1] if pd.isnull(age): if pclass==1: return 38 elif pclass==2: return 30 elif pclass==3: return 25 else: return age df1['Age'] = df1[['Age', 'Pclass']].apply(fill_ages,axis=1) df2['Age'] = df2[['Age', 'Pclass']].apply(fill_ages,axis=1) plt.figure(figsize=(6,4)) sns.heatmap(df1.isnull()) plt.figure(figsize=(6,4)) sns.heatmap(df2.isnull()) df1['Name'] # + train_test = [df1, df2] for dataset in train_test: dataset['Title'] = dataset['Name'].str.extract('([A-Za-z]+)\.', expand=False) # - df1['Title'].value_counts() # ## Title Map # **Mr=0 # Miss=1 # Mrs=2 # Others=3** df2[df2['Title'].isnull()] = df2.replace(np.nan,'Miss') df2[df2['Title'].isnull()]['Title'] title_map = {'Mr':0, 'Miss':1,'Mrs':2,'Master':3,'Dr':3,'Rev':3,'Major':3,'Col':3,'Mlle':3,'Sir':3,'Ms':3,'Don':3, 'Lady':3,'Capt':3,'Mme':3,'Jonkheer':3,'Countess':3} for dataset in train_test: dataset['Title']= dataset['Title'].map(title_map) df2[df2['Title'].isnull()] = df2.replace(np.nan,1) df1['Title'].value_counts() df2['Title'].value_counts() # **Analysis by Title** sns.countplot(x='Title',hue='Survived',data=df1) # **Mr died more than rest** # **Miss and Mrs more chance to live** # ## Gender Map # **Male=1 # Female=0** ## Train DataSet sex = pd.get_dummies(df1['Sex'],drop_first=True) df1['Sex']=sex df1.head() ## Test Data Set sex = pd.get_dummies(df2['Sex'],drop_first=True) df2['Sex']=sex df2.head() # ## Age Mapping # **age<=16=0 # 16<age<=26=1 # 26<age<=36=2 # 36<age<=62=3 # age>62 = 4** facet = sns.FacetGrid(df1,hue='Survived',aspect=4) facet.map(sns.kdeplot,'Age',shade=True) facet.set(xlim=(0,df1['Age'].max())) facet.add_legend() for dataset in train_test: dataset.loc[dataset['Age']<=16,'Age']=0, dataset.loc[(dataset['Age']>16) & (dataset['Age']<=26),'Age']=1, dataset.loc[(dataset['Age']>26) & (dataset['Age']<=36),'Age']=2, dataset.loc[(dataset['Age']>36) & (dataset['Age']<=62),'Age']=3, dataset.loc[dataset['Age']>62, 'Age']=4 df1 sns.countplot(x='Age', hue='Survived',data=df1) # **16<AGE<26 biggest dead rate** # + Pclass1 = df1[df1['Pclass']==1]['Embarked'].value_counts() ## Class 1 embarked values Pclass2 = df1[df1['Pclass']==2]['Embarked'].value_counts() ## CLass 2 embarked values Pclass3 = df1[df1['Pclass']==3]['Embarked'].value_counts() ## Class 3 embarked values df3 = pd.DataFrame([Pclass1,Pclass2,Pclass3],index=['1 class','2 Class', '3 Class']) df3.head() # - df3.plot(kind='bar',stacked=True,figsize=(8,6)) # **Most passangers embarked on S** # **Passangers from Q are just on 3 class** sns.heatmap(df1.isnull()) df1[df1.Embarked.isnull()] ##Pclass = 1, add to S because S has the most shipments df1[df1.Embarked.isnull()] = df1.replace(np.nan, 'S') ## Replace NaN to 'S' df2[df2.Embarked.isnull()] = df2.replace(np.nan, 'S') sns.heatmap(df1.isnull()) sns.heatmap(df2.isnull()) # ## No more NaN values on Embarked # ## Now clean the NaN value on df2 to Fare df2.loc[df2['Fare'].isnull()] ## Passanger Class = 3 ## Lets take the mean value of fare for pclass = 3 and age = 3 df2[(df2.Pclass==3) & (df2.Age==3)]['Fare'].mean() df2.loc[df2['Fare'].isnull(), 'Fare']=13.75 ## Replace NaN to 13.75 sns.heatmap(df2.isnull()) # # Now we have NaN values only on "Cabin" # ## Embarked Mapping # ### S = 0 # ### C = 1 # ### Q = 2 embarked_mapping = {'S':0, 'C':1, 'Q':2} for dataset in train_test: dataset['Embarked'] = dataset['Embarked'].map(embarked_mapping) ## Apply embarked mapping on datasets df1.Embarked.value_counts() facet = sns.FacetGrid(df1,hue='Survived',aspect=4,palette='inferno') facet.map(sns.kdeplot,'Fare',shade=True) facet.set(xlim=(0,df1['Fare'].max())) facet.add_legend() # ## Fare Mapping # **Fare <17 = 0 # 17<Fare<=30 = 1 # 30<Fare<=100 = 2 # Fare > 100 = 3** ## Divides Fare in categories for dataset in train_test: dataset.loc[dataset['Fare']<=17,'Fare']=0, dataset.loc[(dataset['Fare']>17) & (dataset['Fare']<=30),'Fare']=1, dataset.loc[(dataset['Fare']>30) & (dataset['Fare']<=100),'Fare']=2, dataset.loc[dataset['Fare']>100, 'Fare']=3 df1.head() for dataset in train_test: dataset['Cabin'] = dataset['Cabin'].str[:1] df1['Cabin'] Pclass1 = df1[df1['Pclass']==1]['Cabin'].value_counts() ## Class 1 cabin values Pclass2 = df1[df1['Pclass']==2]['Cabin'].value_counts() ## CLass 2 cabin values Pclass3 = df1[df1['Pclass']==3]['Cabin'].value_counts() ## Class 3 cabin values df4 = pd.DataFrame([Pclass1,Pclass2, Pclass3], index=['1 Class','2 Class','3 Class']) df4.head() df4.plot(kind='bar',stacked=True,figsize=(10,6)) # ## First Class Cabins: # **A,B,C,D,E** # ## Second Class Cabins: # **D, E, F** # ## Third Class Cabins # **E, F, G** # + ## Use or not Cabin values? to many NaN values ## Will replace by Pclass Cabin mean but maybe have to delete all column # - cabin_mapping = {'A':0, 'B':0.4, 'C': 0.8,'D':1.2,'E':1.6,'F':2.0,'G':2.4,'T':2.8} ##Feature Scaling values for dataset in train_test: dataset['Cabin']=dataset['Cabin'].map(cabin_mapping) ## Fill Null Values with mean of class train_cabin = df1['Cabin'].fillna(df1.groupby('Pclass')['Cabin'].transform('median')) test_cabin = df2['Cabin'].fillna(df2.groupby('Pclass')['Cabin'].transform('median')) df1['Cabin'] = train_cabin df2['Cabin'] = test_cabin print(df1['Cabin'].isnull().sum()) print(df2['Cabin'].isnull().sum()) # ## Family Size df1['Family Size'] = df1['SibSp']+df1['Parch']+1 ## Family + Self df2['Family Size'] = df2['SibSp']+df2['Parch']+1 df1.head() facet = sns.FacetGrid(df1,hue='Survived',aspect=4) facet.map(sns.kdeplot,'Family Size',shade=True) facet.set(xlim=(0,df1['Family Size'].max())) facet.add_legend() # ## Family Mapping family_mapping = {1:0, 2:0.4, 3:0.8, 4:1.2, 5:1.6, 6:2.0, 7:2.4, 8:2.8, 9:3.2, 10:3.6, 11:4} for dataset in train_test: dataset['Family Size'] = dataset['Family Size'].map(family_mapping) df1.head() # ## Create Train Data and Target df1.head() #Train Data features_drop = ['Name','PassengerId','Ticket','SibSp', 'Parch', 'Survived'] train_data = df1.drop(features_drop, axis=1) train_data.head(10) # Test Data features_drop = ['Name', 'SibSp','Parch','Ticket'] test_data = df2.drop(features_drop, axis=1) test_data.head() test_data.Title target = df1.Survived target.head() # # Modelling from sklearn.neighbors import KNeighborsClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report,confusion_matrix # ## Cross Validation (K-fold) from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score k_fold = KFold(n_splits=10, shuffle=True, random_state=0) # ### KNN clf = KNeighborsClassifier(n_neighbors=12) score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=1, scoring='accuracy') print(score) ## KNN score round(np.mean(score)*100, 2) # ## SVC clf = SVC() score = cross_val_score(clf, train_data, target, cv=k_fold, n_jobs=2, scoring='accuracy') print(score) ## SVC Score round(np.mean(score)*100, 2) # ### Logistic Regression x_train, x_test, y_train, y_test = train_test_split(train_data,df1['Survived'], test_size=0.3) logmodel = LogisticRegression() logmodel.fit(x_train,y_train) predictions = logmodel.predict(x_test) print(classification_report(y_test,predictions)) # **Here we have a 84%, but dont with the test data** # # Testing # + ## Ver como usar no Logistic model os modelos de treino e teste que criei # - clf = SVC() clf.fit(train_data, target) prediction = clf.predict(test_data) submission = pd.DataFrame({ 'PassengerId':test['PassengerId'], 'Survived':prediction }) submision.to_csv('submission.csv',index=False)
Kaggle/.ipynb_checkpoints/Titanic-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Contents: # # 1. Lists - Creation, deletion, length, append, insert, remove, extend, reverse, sorted, list having multiple references, list indexing, list slicing, list count, list looping, list comprehensions, nested lists, matrix transpose using lists. # # 2. Tuples - Creation, Accessing tuple elements, Immutable tuple, Deletion, Count, Index, Membership, Length, Sort. # # 3. Sets - Creation, Add element to a set, remove elements, set operations, frozen sets # # 4. Dictionary - Creation, Accessing a dictionary in Python, Add or Modify Dicttionary elements, delete or remove elements, Dictionary methods, Dictionary comprehensions # # 5. Strings - Create, Access elements, Chnage or delete a string, operations - concatenation, iteration, membership, string functions, Python Program to Check where a String is Palindrome or not, Python Program to Sort Words in Alphabetic Order? # + [markdown] colab_type="text" id="NdXy-T5zaAaF" # # 1.0 Lists # + [markdown] colab_type="text" id="d2abr_4DaAaG" # Data Structure: # # A data structure is a collection of data elements (such as numbers or characters—or even other data structures) that is structured in some way, for example, by numbering the elements. The most basic data structure in Python is the "sequence". # + [markdown] colab_type="text" id="_OkL1n_saAaI" # -> List is one of the Sequence Data structure # # -> Lists are collection of items (Strings, integers or even other lists) # # -> Lists are enclosed in [ ] # # -> Each item in the list has an assigned index value. # # -> Each item in a list is separated by a comma # # -> Lists are mutable, which means they can be changed. # # + [markdown] colab_type="text" id="y6E87CNkaAaI" # # List Creation # + colab={} colab_type="code" id="3xDIU3qfaAaJ" outputId="95be36e3-6048-4231-8b84-86ed03f92eb8" emptyList = [] lst = ['one', 'two', 'three', 'four'] # list of strings lst2 = [1, 2, 3, 4] #list of integers lst3 = [[1, 2], [3, 4]] # list of lists lst4 = [1, 'ramu', 24, 1.24] # list of different datatypes print(lst4) # + [markdown] colab_type="text" id="6CEa5juJaAaP" # # List Length # + colab={} colab_type="code" id="ELTxkoZAaAaQ" outputId="779b1f15-3461-4704-ebd3-5b587166297e" lst = ['one', 'two', 'three', 'four'] #find length of a list print(len(lst)) # + [markdown] colab_type="text" id="BWtzSHqEaAaT" # # List Append # + colab={} colab_type="code" id="lgxkiUKRaAaU" outputId="eb163944-cceb-4943-8494-f879111f1773" lst = ['one', 'two', 'three', 'four'] lst.append('five') # append will add the item at the end print(lst) # + [markdown] colab_type="text" id="Yk3hugoCaAaX" # # List Insert # + colab={} colab_type="code" id="hxFmwInfaAaY" outputId="40675a3c-2fb6-42e1-d4f1-fc5cc518a1ed" #syntax: lst.insert(x, y) lst = ['one', 'two', 'four'] lst.insert(2, "three") # will add element y at location x print(lst) # + [markdown] colab_type="text" id="YcGKZ45BaAab" # # List Remove # + colab={} colab_type="code" id="Qz9E9r6IaAac" outputId="fcdf5357-8ebb-491d-8fa9-bf0d7e45011d" #syntax: lst.remove(x) lst = ['one', 'two', 'three', 'four', 'two'] lst.remove('two') #it will remove first occurence of 'two' in a given list print(lst) # + [markdown] colab_type="text" id="gP3lb_hlaAai" # # List Append & Extend # + colab={} colab_type="code" id="AhQZ_S5WaAaj" outputId="3e023a9c-0291-4264-8c49-3d32d2a685e9" lst = ['one', 'two', 'three', 'four'] lst2 = ['five', 'six'] #append lst.append(lst2) print(lst) # + colab={} colab_type="code" id="-eDRYerEaAan" outputId="dc992ec1-df5e-4190-c096-8f7b9e3b889c" lst = ['one', 'two', 'three', 'four'] lst2 = ['five', 'six'] #extend will join the list with list1 lst.extend(lst2) print(lst) # + [markdown] colab_type="text" id="HRsgFVblaAar" # # List Delete # + colab={} colab_type="code" id="E0TcvgzCaAas" outputId="6337a874-61a3-495a-9d07-8eebe66def35" #del to remove item based on index position lst = ['one', 'two', 'three', 'four', 'five'] del lst[1] print(lst) #or we can use pop() method a = lst.pop(1) print(a) print(lst) # + colab={} colab_type="code" id="QZy8YqvraAav" outputId="41c18ac6-f55f-4a81-f949-8af520202363" lst = ['one', 'two', 'three', 'four'] #remove an item from list lst.remove('three') print(lst) # + [markdown] colab_type="text" id="B3taZUwqaAax" # # List realted keywords in Python # + colab={} colab_type="code" id="KnvMpRFCaAay" outputId="0645c347-1c9c-44e4-aacb-20649a09234f" #keyword 'in' is used to test if an item is in a list lst = ['one', 'two', 'three', 'four'] if 'two' in lst: print('AI') #keyword 'not' can combined with 'in' if 'six' not in lst: print('ML') # + [markdown] colab_type="text" id="ikBpRbI9aAa2" # # List Reverse # + colab={} colab_type="code" id="RQqzW-mEaAa3" outputId="781e6007-4649-4640-adde-8f4afde602d6" #reverse is reverses the entire list lst = ['one', 'two', 'three', 'four'] lst.reverse() print(lst) # + [markdown] colab_type="text" id="o9lI--gRaAa7" # # List Sorting # + [markdown] colab_type="text" id="lUTiW5mcaAa8" # The easiest way to sort a List is with the sorted(list) function. # # That takes a list and returns a new list with those elements in sorted order. # # The original list is not changed. # # The sorted() optional argument reverse=True, e.g. sorted(list, reverse=True), # makes it sort backwards. # + colab={} colab_type="code" id="LegBovHtaAa9" outputId="ce14fea3-fbd0-4858-b19d-f4066e000ee5" #create a list with numbers numbers = [3, 1, 6, 2, 8] sorted_lst = sorted(numbers) print("Sorted list :", sorted_lst) #original list remain unchanged print("Original list: ", numbers) # + colab={} colab_type="code" id="qT_4cI63aAbB" outputId="c67d0b88-24c6-4cd4-c63e-7d64ae66c5c3" #print a list in reverse sorted order print("Reverse sorted list :", sorted(numbers, reverse=True)) #orginal list remain unchanged print("Original list :", numbers) # + colab={} colab_type="code" id="7YLaz7thaAbF" outputId="ed2b0657-3ddb-4390-8f3f-0a4c8c34db77" lst = [1, 20, 5, 5, 4.2] #sort the list and stored in itself lst.sort() # add element 'a' to the list to show an error print("Sorted list: ", lst) # + colab={} colab_type="code" id="WfPzBE_-aAbI" outputId="bbbf76f2-169f-4875-953b-d224feb0f0c5" lst = [1, 20, 'b', 5, 'a'] print(lst.sort()) # sort list with element of different datatypes. # + [markdown] colab_type="text" id="eI34dleeaAbK" # # List Having Multiple References # + colab={} colab_type="code" id="BcmPLhR6aAbM" outputId="bdfc1ccb-6af9-416a-c1a3-53823789de67" lst = [1, 2, 3, 4, 5] abc = lst abc.append(6) #print original list print("Original list: ", lst) # + [markdown] colab_type="text" id="nsmc6A1YaAbP" # # String Split to create a list # + colab={} colab_type="code" id="YPLVh4TjaAbP" outputId="dc4b1445-3c8b-4aff-892b-cb1306c36499" #let's take a string s = "one,two,three,four,five" slst = s.split(',') print(slst) # + colab={} colab_type="code" id="PBYLi_UjaAbS" outputId="222b6691-9adf-4194-b9c9-c3acb65b5509" s = "This is applied AI Course" split_lst = s.split() # default split is white-character: space or tab print(split_lst) # + [markdown] colab_type="text" id="i0FJbejqaAbU" # # List Indexing # + [markdown] colab_type="text" id="_ZJom4VxaAbW" # Each item in the list has an assigned index value starting from 0. # # Accessing elements in a list is called indexing. # + colab={} colab_type="code" id="_vYi0oRbaAbW" outputId="359ac752-72c9-47c3-df99-ffff292a088d" lst = [1, 2, 3, 4] print(lst[1]) #print second element #print last element using negative index print(lst[-2]) # + [markdown] colab_type="text" id="ihTfiGnGaAba" # # List Slicing # + [markdown] colab_type="text" id="HJ6BnCxJaAba" # Accessing parts of segments is called slicing. # # The key point to remember is that the :end value represents the first value that # is not in the selected slice. # + colab={} colab_type="code" id="yadzqSHAaAbc" outputId="89b39b80-69a2-4f01-9436-bbe9bf2b4f05" numbers = [10, 20, 30, 40, 50,60,70,80] #print all numbers print(numbers[:]) #print from index 0 to index 3 print(numbers[0:4]) # + colab={} colab_type="code" id="ESlZQ2aNaAbf" outputId="b62f05e9-031d-40de-d785-043d59160e45" print (numbers) #print alternate elements in a list print(numbers[::2]) #print elemnts start from 0 through rest of the list print(numbers[2::2]) # + [markdown] colab_type="text" id="69BXgb4YaAbh" # # List extend using "+" # + colab={} colab_type="code" id="paZsLKU7aAbh" outputId="4882a753-1daa-4357-c02c-d1c889ace73f" lst1 = [1, 2, 3, 4] lst2 = ['Saugata', 'MSD', 'Dravid', 'Rony'] new_lst = lst1 + lst2 print(new_lst) # + [markdown] colab_type="text" id="zR8AY0YCaAbk" # # List Count # + colab={} colab_type="code" id="xLWcn0TcaAbl" outputId="ba7168f7-a97f-45d7-b123-38df8cc7c1ae" numbers = [1, 2, 3, 1, 3, 4, 2, 5] #frequency of 1 in a list print(numbers.count(1)) #frequency of 3 in a list print(numbers.count(3)) # + [markdown] colab_type="text" id="Ttuq4WbPaAbn" # # List Looping # + colab={} colab_type="code" id="gGBIUhMvaAbn" outputId="b09c4261-5dd9-4bf0-f94f-a0590670d7cf" #loop through a list lst = ['one', 'two', 'three', 'four'] for ele in lst: print(ele) # + [markdown] colab_type="text" id="-EZO9D31aAbq" # # List Comprehensions # + [markdown] colab_type="text" id="y8DXRBM_aAbq" # List comprehensions provide a concise way to create lists. # # Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition. # + colab={} colab_type="code" id="-rHP7zw_aAbr" outputId="5adc1c49-9633-47bb-a83a-bf144dd1bbbb" # without list comprehension squares = [] for i in range(10): squares.append(i**2) #list append print(squares) # + colab={} colab_type="code" id="CS6fvT8daAbu" outputId="87959059-b9d0-41bc-bb7d-3e9f3ed14995" #using list comprehension squares = [i**2 for i in range(10)] print(squares) # + colab={} colab_type="code" id="N-v4Y9KDaAbw" outputId="f13d09a5-f6fd-41f7-b6d0-2af43f040afd" #example lst = [-10, -20, 10, 20, 50] #create a new list with values doubled new_lst = [i*2 for i in lst] print(new_lst) #filter the list to exclude negative numbers new_lst = [i for i in lst if i >= 0] print(new_lst) #create a list of tuples like (number, square_of_number) new_lst = [(i, i**2) for i in range(10)] print(new_lst) # + [markdown] colab_type="text" id="Sp6JeODZaAb5" # # Nested List Comprehensions # + colab={} colab_type="code" id="I7FzVx3CaAb5" outputId="20d171d1-25eb-4f5d-b01f-30639b8e0df6" #let's suppose we have a matrix matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] #transpose of a matrix without list comprehension transposed = [] for i in range(4): lst = [] for row in matrix: lst.append(row[i]) transposed.append(lst) print(transposed) # + colab={} colab_type="code" id="bc0Ij-kaaAb8" outputId="1005a34e-8982-46ab-9357-f7be29e16f61" #with list comprehension transposed = [[row[i] for row in matrix] for i in range(4)] print(transposed) # + [markdown] colab={} colab_type="code" id="__DT4BWEaAb_" # # Matrix Transpose # + #https://ideone.com/Z21ysE matrix = [ [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]] transposed = [] for i in range(4): print("we are going to take the ",i,"th element of each row") lst = [] for row in matrix: print("the row we are considering :", row, "and we are going to add", row[i],"to a temporary list") lst.append(row[i]) print("the ",i,"th column elements = ", i ,"th elements in every row are =", lst) transposed.append(lst) print("="*50) print(transposed) # - # # 2.0 Tuples # -> A tuple is similar to list # # -> The diffence between the two is that we can't change the elements of tuple once it is assigned whereas in the list, elements can be changed # # Tuple creation # + #empty tuple t = () #tuple having integers t = (1, 2, 3) print(t) #tuple with mixed datatypes t = (1, 'raju', 28, 'abc') print(t) #nested tuple t = (1, (2, 3, 4), [1, 'raju', 28, 'abc']) print(t) # - #only parenthesis is not enough t = ('satish') type(t) #need a comma at the end t = ('satish',) type(t) # + #parenthesis is optional t = "satish", print(type(t)) print(t) # - # # Accessing Elements in Tuple # + t = ('satish', 'murali', 'naveen', 'srinu', 'brahma') print(t[1]) # - #negative index print(t[-1]) #print last element in a tuple # + #nested tuple t = ('ABC', ('satish', 'naveen', 'srinu')) print(t[1]) # - print(t[1][2]) # + #Slicing t = (1, 2, 3, 4, 5, 6) print(t[1:4]) #print elements from starting to 2nd last elements print(t[:-2]) #print elements from starting to end print(t[:]) # - # # Changing a Tuple # #unlike lists, tuples are immutable # #This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed. # + #creating tuple t = (1, 2, 3, 4, [5, 6, 7]) t[2] = 'x' #will get TypeError # - t[4][1] = 'satish' print(t) # + #concatinating tuples t = (1, 2, 3) + (4, 5, 6) print(t) # - #repeat the elements in a tuple for a given number of times using the * operator. t = (('satish', ) * 4) print(t) # # Tuple Deletion # + #we cannot change the elements in a tuple. # That also means we cannot delete or remove items from a tuple. #delete entire tuple using del keyword t = (1, 2, 3, 4, 5, 6) #delete entire tuple del t # - # # Tuple Count # + t = (1, 2, 3, 1, 3, 3, 4, 1) #get the frequency of particular element appears in a tuple t.count(1) # - # # Tuple Index # + t = (1, 2, 3, 1, 3, 3, 4, 1) print(t.index(3)) #return index of the first element is equal to 3 #print index of the 1 # - # # Tuple Membership # + #test if an item exists in a tuple or not, using the keyword in. t = (1, 2, 3, 4, 5, 6) print(1 in t) # - print(7 in t) # # Built in Functions # # Tuple Length t = (1, 2, 3, 4, 5, 6) print(len(t)) # # Tuple Sort # + t = (4, 5, 1, 2, 3) new_t = sorted(t) print(new_t) #Take elements in the tuple and return a new sorted list #(does not sort the tuple itself). # + #get the largest element in a tuple t = (2, 5, 1, 6, 9) print(max(t)) # - #get the smallest element in a tuple print(min(t)) #get sum of elments in the tuple print(sum(t)) # # 3.0 Sets # -> A set is an unordered collection of items. Every element is unique (no duplicates). # # -> The set itself is mutable. We can add or remove items from it. # # -> Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. # # Set Creation # + #set of integers s = {1, 2, 3} print(s) #print type of s print(type(s)) # - #set doesn't allow duplicates. They store only one instance. s = {1, 2, 3, 1, 4} print(s) #we can make set from a list s = set([1, 2, 3, 1]) print(s) # + #initialize a set with set() method s = set() print(type(s)) # - # # Add element to a Set # + #we can add single element using add() method and #add multiple elements using update() method s = {1, 3} #set object doesn't support indexing print(s[1]) #will get TypeError # - #add element s.add(2) print(s) #add multiple elements s.update([5, 6, 1]) print(s) #add list and set s.update([8, 9], {10, 2, 3}) print(s) # # Remove elements from a Set # + #A particular item can be removed from set using methods, #discard() and remove(). s = {1, 2, 3, 5, 4} print(s) s.discard(4) #4 is removed from set s print(s) # + #remove an element s.remove(2) print(s) # - #remove an element not present in a set s s.remove(7) # will get KeyError #discard an element not present in a set s s.discard(7) print(s) # + #we can remove item using pop() method s = {1, 2, 3, 5, 4} s.pop() #remove random element print(s) # - s.pop() print(s) # + s = {1, 5, 2, 3, 6} s.clear() #remove all items in set using clear() method print(s) # - # # Python Set Operations # + set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7} #union of 2 sets using | operator print(set1 | set2) # - #another way of getting union of 2 sets print(set1.union(set2)) #intersection of 2 sets using & operator print(set1 & set2) #use intersection function print(set1.intersection(set2)) # + #set Difference: set of elements that are only in set1 but not in set2 print(set1 - set2) # - #use differnce function print(set1.difference(set2)) # + """symmetric difference: set of elements in both set1 and set2 #except those that are common in both.""" #use ^ operator print(set1^set2) # - #use symmetric_difference function print(set1.symmetric_difference(set2)) # + #find issubset() x = {"a","b","c","d","e"} y = {"c","d"} print("set 'x' is subset of 'y' ?", x.issubset(y)) #check x is subset of y #check y is subset of x print("set 'y' is subset of 'x' ?", y.issubset(x)) # - # # Frozen Sets # Frozen sets has the characteristics of sets, but we can't be changed once it's assigned. While tuple are immutable lists, frozen sets are immutable sets # Frozensets can be created using the function frozenset() # Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand, frozensets are hashable and can be used as keys to a dictionary. # This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have method that add or remove elements. # + set1 = frozenset([1, 2, 3, 4]) set2 = frozenset([3, 4, 5, 6]) #try to add element into set1 gives an error set1.add(5) # - print(set1[1]) # frozen set doesn't support indexing print(set1 | set2) #union of 2 sets # + #intersection of two sets print(set1 & set2) #or print(set1.intersection(set2)) # + #symmetric difference print(set1 ^ set2) #or print(set1.symmetric_difference(set2)) # - # # 4.0 Dictionary # Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. # # Dict Creation # + #empty dictionary my_dict = {} #dictionary with integer keys my_dict = {1: 'abc', 2: 'xyz'} print(my_dict) #dictionary with mixed keys my_dict = {'name': 'satish', 1: ['abc', 'xyz']} print(my_dict) #create empty dictionary using dict() my_dict = dict() my_dict = dict([(1, 'abc'), (2, 'xyz')]) #create a dict with list of tuples print(my_dict) # - # # Dict Access # + my_dict = {'name': 'saugata', 'age': 27, 'address': 'kolkata'} #get name print(my_dict['name']) # - #if key is not present it gives KeyError print(my_dict['degree']) #another way of accessing key print(my_dict.get('address')) #if key is not present it will give None using get method print(my_dict.get('degree')) # # Dict Add or Modify Elements # + my_dict = {'name': 'satish', 'age': 27, 'address': 'guntur'} #update name my_dict['name'] = 'raju' print(my_dict) # + #add new key my_dict['degree'] = 'M.Tech' print(my_dict) # - # # Dict Delete or Remove Element # + #create a dictionary my_dict = {'name': 'satish', 'age': 27, 'address': 'guntur'} #remove a particular item print(my_dict.pop('age')) print(my_dict) # + my_dict = {'name': 'satish', 'age': 27, 'address': 'guntur'} #remove an arbitarty key my_dict.popitem() print(my_dict) # + squares = {2: 4, 3: 9, 4: 16, 5: 25} #delete particular key del squares[2] print(squares) # + #remove all items squares.clear() print(squares) # + squares = {2: 4, 3: 9, 4: 16, 5: 25} #delete dictionary itself del squares print(squares) #NameError because dict is deleted # - # # Dictionary Methods # + squares = {2: 4, 3: 9, 4: 16, 5: 25} my_dict = squares.copy() print(my_dict) # - #fromkeys[seq[, v]] -> Return a new dictionary with keys from seq and value equal to v (defaults to None). subjects = {}.fromkeys(['Math', 'English', 'Hindi'], 0) print(subjects) subjects = {2:4, 3:9, 4:16, 5:25} print(subjects.items()) #return a new view of the dictionary items (key, value) subjects = {2:4, 3:9, 4:16, 5:25} print(subjects.keys()) #return a new view of the dictionary keys subjects = {2:4, 3:9, 4:16, 5:25} print(subjects.values()) #return a new view of the dictionary values #get list of all available methods and attributes of dictionary d = {} print(dir(d)) # # Dict Comprehension # + #Dict comprehensions are just like list comprehensions but for dictionaries d = {'a': 1, 'b': 2, 'c': 3} for pair in d.items(): print(pair) # - #Creating a new dictionary with only pairs where the value is larger than 2 d = {'a': 1, 'b': 2, 'c': 3, 'd': 4} new_dict = {k:v for k, v in d.items() if v > 2} print(new_dict) #We can also perform operations on the key value pairs d = {'a':1,'b':2,'c':3,'d':4,'e':5} d = {k + 'c':v * 2 for k, v in d.items() if v > 2} print(d) # + [markdown] colab_type="text" id="2R97ADiFQ0Qq" # # 5.0 Strings # + [markdown] colab_type="text" id="eVUSlgdsQ0Qs" # A string is a sequence of characters. # # Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's. # # This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encoding used. # # In Python, string is a sequence of Unicode character. # + [markdown] colab_type="text" id="G_fSxHayQ0Qu" # For more details about unicode # # https://docs.python.org/3.3/howto/unicode.html # + [markdown] colab_type="text" id="d2ZdcRphQ0Qv" # # How to create a string? # + [markdown] colab_type="text" id="kVww6WnaQ0Qw" # Strings can be created by enclosing characters inside a single quote or double quotes. # # Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings. # # + colab={} colab_type="code" id="8OM3IOK2Q0Qy" outputId="01582439-98f6-42aa-814d-9b6fc38ebafd" myString = 'Hello' print(myString) myString = "Hello" print(myString) myString = '''Hello''' print(myString) # + [markdown] colab_type="text" id="8yQfoUnGQ0Q4" # # How to access characters in a string? # + [markdown] colab_type="text" id="lj884ZrtQ0Q6" # We can access individual characters using indexing and a range of characters using slicing. # # Index starts from 0. # # Trying to access a character out of index range will raise an IndexError. # # The index must be an integer. We can't use float or other types, this will result into TypeError. # # Python allows negative indexing for its sequences. # + colab={} colab_type="code" id="dECRrHU9Q0Q6" outputId="53102267-40e2-4cfd-aec2-e5a13050778b" myString = "Hello" #print first Character print(myString[0]) #print last character using negative indexing print(myString[-1]) #slicing 2nd to 5th character print(myString[2:5]) # + [markdown] colab_type="text" id="rYjjmAwVQ0RA" # If we try to access index out of the range or use decimal number, we will get errors. # + colab={} colab_type="code" id="sDdAkqPOQ0RB" outputId="62af85cf-1cd5-4cdb-9d70-85c9e3a310ef" print(myString[15]) # + colab={} colab_type="code" id="df79qTM1Q0RF" outputId="fa826bc9-01bf-47d9-9aef-8a2d283e49ae" print(myString[1.5]) # + [markdown] colab_type="text" id="l24m79F7Q0RI" # # How to change or delete a string ? # + [markdown] colab_type="text" id="82PqjvORQ0RK" # Strings are immutable. This means that elements of a string cannot be changed once it has been assigned. # # We can simply reassign different strings to the same name. # + colab={} colab_type="code" id="iV3SYntmQ0RL" outputId="ad24277c-3aee-442d-8e61-eab288303ec8" myString = "Hello" myString[4] = 's' # strings are immutable # + [markdown] colab_type="text" id="aMWgpS3pQ0RP" # We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del. # + colab={} colab_type="code" id="k43jqNSwQ0RQ" del myString # delete complete string # + colab={} colab_type="code" id="3gpZMAFtQ0RT" outputId="1d4f5a0d-45e9-4a40-dab8-2419a46cd293" print(myString) # + [markdown] colab_type="text" id="_I6JAqk7Q0RX" # # String Operations # + [markdown] colab_type="text" id="AdXL8ZfrQ0RY" # # Concatenation # + [markdown] colab_type="text" id="UEqPy2mBQ0Ra" # Joining of two or more strings into a single one is called concatenation. # # The + operator does this in Python. Simply writing two string literals together also concatenates them. # # The * operator can be used to repeat the string for a given number of times. # + colab={} colab_type="code" id="I02mfOxIQ0Rb" outputId="4f2a2f69-d794-494e-c911-ac9bbcf7905d" s1 = "Hello " s2 = "Satish" #concatenation of 2 strings print(s1 + s2) #repeat string n times print(s1 * 3) # + [markdown] colab_type="text" id="JUHt8GFjQ0Rf" # # Iterating Through String # + colab={} colab_type="code" id="jDRQiFQVQ0Rg" outputId="f1e1c6a6-612b-41e1-db98-bbb5313958d2" count = 0 for l in "Hello World": if l == 'o': count += 1 print(count, ' letters found') # + [markdown] colab_type="text" id="HJ_EXB0sQ0Rk" # # String Membership Test # + colab={} colab_type="code" id="YCOI93eMQ0Rm" outputId="7f106a6e-9e7e-4583-a23c-7cfc5483d294" print('l' in 'Hello World') #in operator to test membership # + colab={} colab_type="code" id="v-Gc3e9pQ0Ru" outputId="704345a3-9ebc-4554-a983-e8a76a3b8024" print('or' in 'Hello World') # + [markdown] colab_type="text" id="kWW3wSRzQ0Rz" # # String Methods # + [markdown] colab_type="text" id="1Us5mMCkQ0R0" # Some of the commonly used methods are lower(), upper(), join(), split(), find(), replace() etc # + colab={} colab_type="code" id="SkMrD20MQ0R3" outputId="5d60d748-6ca0-44ba-87b3-92f868e7c754" "Hello".lower() # + colab={} colab_type="code" id="nz3r0uJiQ0R7" outputId="0050d3bf-c665-4b21-8208-6b60c1c25d2e" "Hello".upper() # + colab={} colab_type="code" id="wY5zUXlnQ0R_" outputId="ab0de61c-dc47-4cc4-c898-4d297eb3a0a0" "This will split all words in a list".split() # + colab={} colab_type="code" id="y8DCwXIBQ0SC" outputId="b57a1fc4-7191-4071-971f-acef6617928f" ' '.join(['This', 'will', 'split', 'all', 'words', 'in', 'a', 'list']) # + colab={} colab_type="code" id="Rp2Kj-qkQ0SF" outputId="390b72be-bd82-4903-bc08-285f87faa4c0" "Good Morning".find("Mo") # + colab={} colab_type="code" id="GWLYw7alQ0SI" outputId="e842a03d-1836-460e-c5e3-a3cf80984803" s1 = "Bad morning" s2 = s1.replace("Bad", "Good") print(s1) print(s2) # + [markdown] colab_type="text" id="i_H-coiDQ0SL" # # Python Program to Check where a String is Palindrome or not ? # + colab={} colab_type="code" id="PhIi2cEqQ0SM" outputId="230eeef0-534f-4e65-9602-14b990cf2a51" myStr = "Madam" #convert entire string to either lower or upper myStr = myStr.lower() #reverse string revStr = reversed(myStr) #check if the string is equal to its reverse if list(myStr) == list(revStr): print("Given String is palindrome") else: print("Given String is not palindrome") # + [markdown] colab_type="text" id="TLQRLF-_Q0SQ" # # Python Program to Sort Words in Alphabetic Order? # + colab={} colab_type="code" id="8c75-LV9Q0SS" outputId="1c220dee-b732-426d-938d-51308151ab72" myStr = "python Program to Sort words in Alphabetic Order" #breakdown the string into list of words words = myStr.split() #sort the list words.sort() #print Sorted words are for word in words: print(word)
04. Python - Common Data Structures in Python.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # TQDB API 範例 (Python版) # 首先我們自定義連結TQDB取出報價資料的函數 # * 預設Series作為資料輸出格式,也可以選擇DataFrame # * 資料主機的位置,我們先預設為本機IP:127.0.0.1 # # + slideshow={"slide_type": "slide"} # %matplotlib inline import math import matplotlib.pyplot as plt import requests import datetime import urllib from pandas import DataFrame,Series # Define function to fetch remote data # demonstartion only # def TQDB(symbol='DEMO1',startDate='2014-6-30',endDate='2035-7-01',type='Series',server='127.0.0.1'): querystr={'symbol':symbol, 'BEG':startDate, 'END': endDate} url = "http://"+server+"/cgi-bin/q1min.py?"+urllib.urlencode(querystr) r = requests.get(url) lines = r.content.split('\n') x = [] H=[] L=[] C=[] O=[] Vol=[] i=0 for line in lines: i=i+1 items=line.split(',') if len(items) < 5: continue dt=datetime.datetime.strptime(items[0]+items[1], '%Y%m%d%H%M%S') x.append(dt) C.append(float(items[5])) L.append(float(items[4])) H.append(float(items[3])) O.append(float(items[2])) Vol.append(float(items[6])) d = {'O' :O,'H':H,'L':L,'C':C,'Vol':Vol} if len(O)==0: print "no data available. Please select different date" return if type=="DataFrame": return DataFrame(d,index=x, columns=['O','H','L','C','Vol']) elif type=="Series": return Series(C,index=x) else: print 'type is not defined' # - s='2015-07-1' e='2035-12-1' a=TQDB("DEMO1",type='Series',startDate=s,endDate=e) b=TQDB("DEMO2",type='Series',startDate=s,endDate=e) c=TQDB("DEMO3",type='Series',startDate=s,endDate=e) # (a)['C'].plot()#blue ee="2016-2-18" a[ee].plot() b[ee].plot() c[ee].plot() #a.plot() #a.to_csv('SPY.csv') # b.plot()#Green # c.plot()#red (a-b).plot()#blue #b.plot()#Green s='2014-5-2' e='2035-7-3' stw=TQDB("DEMO1",type='Series',startDate=s,endDate=e) tx=TQDB("DEMO2",type='Series',startDate=s,endDate=e) p=1.5*30*stw-tx*2 p p.plot()
for_ipython/QnP_WTX.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + from os import makedirs from os.path import join, dirname, exists from collections import defaultdict from tqdm import tqdm import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from librosa import get_duration from cac.utils.io import save_yml # - data_root = '/data/coswara-15-03-21/processed/' annotation = pd.read_csv(join(data_root, 'annotation.csv')) attributes = pd.read_csv(join(data_root, 'attributes.csv')) tasks = { 'classification': { 'valid_labels': ['cough'] } } annotation.head() annotation['classification'] = annotation['classification'].apply(lambda x: eval(x)) annotation['classification'] = annotation['classification'].apply(lambda x: [x[0].split('-')[0]]) files = [ join(data_root, 'audio', '{}-{}-{}'.format(date, _id, file)) \ for date, _id, file in zip(annotation['date'], annotation['id'], annotation['file']) ] annotation.head() # + labels = [] for _ in files: labels.append(dict()) for task in tasks: valid_values = tasks[task]['valid_labels'] for i, _values in enumerate(annotation[task]): _labels = [] for valid_value in valid_values: if valid_value in _values: _labels.append(valid_value) labels[i][task] = _labels # - starts = [0.0 for _ in files] ends = [get_duration(filename=x) for x in tqdm(files)] df = pd.DataFrame({'file': files, 'label': labels, 'start': starts, 'end': ends}) len(df) df['label'].astype(str).value_counts() df.head().values indices = list(range(len(df))) train_indices, val_test_indices = train_test_split(indices, test_size=0.2, random_state=20) val_indices, test_indices = train_test_split(val_test_indices, test_size=0.5, random_state=20) len(train_indices), len(val_indices), len(test_indices) df_train = df.loc[train_indices].reset_index(drop=True) df_val = df.loc[val_indices].reset_index(drop=True) df_test = df.loc[test_indices].reset_index(drop=True) version = 'v1.0' save_path = join(data_root, 'versions', '{}.yml'.format(version)) # + description = dict() description['tasks'] = tasks description['description'] = 'cough vs non-cough with random split' for name, _df in zip(['all', 'train', 'val', 'test'], [df, df_train, df_val, df_test]): description[name] = { 'file': _df['file'].values.tolist(), 'label': _df['label'].values.tolist(), } # - # save description makedirs(dirname(save_path), exist_ok=True) save_yml(description, save_path)
datasets/versioning/cough-detection/coswara/v1.0.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Training a model with `traffic_last_5min` feature # # # ## Introduction # # In this notebook, we'll train a taxifare prediction model but this time with an additional feature of `traffic_last_5min`. # + import os import shutil from datetime import datetime import pandas as pd import tensorflow as tf from google.cloud import aiplatform from matplotlib import pyplot as plt from tensorflow import keras from tensorflow.keras.callbacks import TensorBoard from tensorflow.keras.layers import Dense, DenseFeatures from tensorflow.keras.models import Sequential print(tf.__version__) # %matplotlib inline # + # Change below if necessary # PROJECT = !gcloud config get-value project # noqa: E999 PROJECT = PROJECT[0] BUCKET = PROJECT REGION = "us-central1" # %env PROJECT=$PROJECT # %env BUCKET=$BUCKET # %env REGION=$REGION # + language="bash" # gcloud config set project $PROJECT # gcloud config set ai/region $REGION # - # ## Load raw data # !ls -l ../data/taxi-traffic* # !head ../data/taxi-traffic* # ## Use tf.data to read the CSV files # # These functions for reading data from the csv files are similar to what we used in the Introduction to Tensorflow module. Note that here we have an addtional feature `traffic_last_5min`. # + CSV_COLUMNS = [ "fare_amount", "dayofweek", "hourofday", "pickup_longitude", "pickup_latitude", "dropoff_longitude", "dropoff_latitude", "traffic_last_5min", ] LABEL_COLUMN = "fare_amount" DEFAULTS = [[0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0], [0.0]] def features_and_labels(row_data): label = row_data.pop(LABEL_COLUMN) features = row_data return features, label def create_dataset(pattern, batch_size=1, mode=tf.estimator.ModeKeys.EVAL): dataset = tf.data.experimental.make_csv_dataset( pattern, batch_size, CSV_COLUMNS, DEFAULTS ) dataset = dataset.map(features_and_labels) if mode == tf.estimator.ModeKeys.TRAIN: dataset = dataset.shuffle(buffer_size=1000).repeat() # take advantage of multi-threading; 1=AUTOTUNE dataset = dataset.prefetch(1) return dataset # + INPUT_COLS = [ "dayofweek", "hourofday", "pickup_longitude", "pickup_latitude", "dropoff_longitude", "dropoff_latitude", "traffic_last_5min", ] # Create input layer of feature columns feature_columns = { colname: tf.feature_column.numeric_column(colname) for colname in INPUT_COLS } # - # ## Build a simple keras DNN model # Build a keras DNN model using Sequential API def build_model(dnn_hidden_units): model = Sequential(DenseFeatures(feature_columns=feature_columns.values())) for num_nodes in dnn_hidden_units: model.add(Dense(units=num_nodes, activation="relu")) model.add(Dense(units=1, activation="linear")) # Create a custom evaluation metric def rmse(y_true, y_pred): return tf.sqrt(tf.reduce_mean(tf.square(y_pred - y_true))) # Compile the keras model model.compile(optimizer="adam", loss="mse", metrics=[rmse, "mse"]) return model # Next, we can call the `build_model` to create the model. Here we'll have two hidden layers before our final output layer. And we'll train with the same parameters we used before. # + HIDDEN_UNITS = [32, 8] model = build_model(dnn_hidden_units=HIDDEN_UNITS) # + BATCH_SIZE = 1000 NUM_TRAIN_EXAMPLES = 10000 * 6 # training dataset will repeat, wrap around NUM_EVALS = 60 # how many times to evaluate NUM_EVAL_EXAMPLES = 10000 # enough to get a reasonable sample trainds = create_dataset( pattern="../data/taxi-traffic-train*", batch_size=BATCH_SIZE, mode=tf.estimator.ModeKeys.TRAIN, ) evalds = create_dataset( pattern="../data/taxi-traffic-valid*", batch_size=BATCH_SIZE, mode=tf.estimator.ModeKeys.EVAL, ).take(NUM_EVAL_EXAMPLES // 1000) # + # %%time steps_per_epoch = NUM_TRAIN_EXAMPLES // (BATCH_SIZE * NUM_EVALS) LOGDIR = "./taxi_trained" history = model.fit( x=trainds, steps_per_epoch=steps_per_epoch, epochs=NUM_EVALS, validation_data=evalds, callbacks=[TensorBoard(LOGDIR)], ) # + RMSE_COLS = ["rmse", "val_rmse"] pd.DataFrame(history.history)[RMSE_COLS].plot() # - model.predict( x={ "dayofweek": tf.convert_to_tensor([6]), "hourofday": tf.convert_to_tensor([17]), "pickup_longitude": tf.convert_to_tensor([-73.982683]), "pickup_latitude": tf.convert_to_tensor([40.742104]), "dropoff_longitude": tf.convert_to_tensor([-73.983766]), "dropoff_latitude": tf.convert_to_tensor([40.755174]), "traffic_last_5min": tf.convert_to_tensor([114]), }, steps=1, # Total number of steps (batches of samples) before declaring the prediction round finished. ) # ## Export and deploy model OUTPUT_DIR = "./export/savedmodel" shutil.rmtree(OUTPUT_DIR, ignore_errors=True) EXPORT_PATH = os.path.join(OUTPUT_DIR, datetime.now().strftime("%Y%m%d%H%M%S")) model.save(EXPORT_PATH) # with default serving function os.environ["EXPORT_PATH"] = EXPORT_PATH # Note that the last `gcloud` call below, which deploys the model, can take a few minutes, and you might not see the earlier `echo` outputs while that job is still running. If you want to make sure that your notebook is not stalled and your model is actually getting deployed, view your models in the console at https://console.cloud.google.com/vertex-ai/models, click on your model, and you should see your endpoint listed with an "in progress" icon next to it. # + tags=["flake8-noqa-cell"] language="bash" # TIMESTAMP=$(date -u +%Y%m%d_%H%M%S) # MODEL_DISPLAYNAME=taxifare_$TIMESTAMP # ENDPOINT_DISPLAYNAME=taxifare_endpoint_$TIMESTAMP # IMAGE_URI="us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-5:latest" # ARTIFACT_DIRECTORY=gs://${BUCKET}/${MODEL_DISPLAYNAME}/ # echo $ARTIFACT_DIRECTORY # # gsutil cp -r ${EXPORT_PATH}/* ${ARTIFACT_DIRECTORY} # # # Model # MODEL_RESOURCENAME=$(gcloud ai models upload \ # --region=$REGION \ # --display-name=$MODEL_DISPLAYNAME \ # --container-image-uri=$IMAGE_URI \ # --artifact-uri=$ARTIFACT_DIRECTORY \ # --format="value(model)") # # MODEL_ID=$(echo $MODEL_RESOURCENAME | cut -d"/" -f6) # # echo "MODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}" # echo "MODEL_RESOURCENAME=${MODEL_RESOURCENAME}" # echo "MODEL_ID=${MODEL_ID}" # # # Endpoint # ENDPOINT_RESOURCENAME=$(gcloud ai endpoints create \ # --region=$REGION \ # --display-name=$ENDPOINT_DISPLAYNAME \ # --format="value(name)") # # ENDPOINT_ID=$(echo $ENDPOINT_RESOURCENAME | cut -d"/" -f6) # # echo "ENDPOINT_DISPLAYNAME=${ENDPOINT_DISPLAYNAME}" # echo "ENDPOINT_RESOURCENAME=${ENDPOINT_RESOURCENAME}" # echo "ENDPOINT_ID=${ENDPOINT_ID}" # # # Deployment # DEPLOYEDMODEL_DISPLAYNAME=${MODEL_DISPLAYNAME}_deployment # MACHINE_TYPE=n1-standard-2 # MIN_REPLICA_COUNT=1 # MAX_REPLICA_COUNT=3 # # gcloud ai endpoints deploy-model $ENDPOINT_RESOURCENAME \ # --region=$REGION \ # --model=$MODEL_RESOURCENAME \ # --display-name=$DEPLOYEDMODEL_DISPLAYNAME \ # --machine-type=$MACHINE_TYPE \ # --min-replica-count=$MIN_REPLICA_COUNT \ # --max-replica-count=$MAX_REPLICA_COUNT \ # --traffic-split=0=100 # - # Take note of the `ENDPOINT_RESOURCENAME` printed above, as you will need it in the next lab. # The above model deployment can be initiated from the Vertex AI Python SDK as well, as seen below. In this case, we do not need to create the Endpoint ourselves (we could though), but it is implicitly created during the `model.deploy()` call. # + active="" # TIMESTAMP = datetime.strftime(datetime.now(), "%Y%m%d_%H%M%S") # MODEL_DISPLAYNAME = f"taxifare_{TIMESTAMP}" # ENDPOINT_NAME = f"taxifare_endpoint_{TIMESTAMP}" # ARTIFACT_DIRECTORY = f"gs://{BUCKET}/{MODEL_DISPLAYNAME}/" # print(ARTIFACT_DIRECTORY) # IMAGE_URI = "us-docker.pkg.dev/vertex-ai/prediction/tf2-cpu.2-5:latest" # # !gsutil cp -r $EXPORT_PATH/* $ARTIFACT_DIRECTORY # # aiplatform.init(project=PROJECT, location=REGION) # # # Model # model = aiplatform.Model.upload( # display_name=MODEL_DISPLAYNAME, # artifact_uri=ARTIFACT_DIRECTORY, # serving_container_image_uri=IMAGE_URI, # ) # # model.wait() # # print(model.display_name) # print(model.resource_name) # # # Deployment # DEPLOYED_MODEL_NAME = f"{MODEL_DISPLAYNAME}_deployment" # MACHINE_TYPE = "n1-standard-2" # MIN_REPLICA_COUNT = 1 # MAX_REPLICA_COUNT = 3 # # model = aiplatform.Model(model_name=model.resource_name) # # endpoint = model.deploy( # deployed_model_display_name=DEPLOYED_MODEL_NAME, # traffic_split={"0": 100}, # machine_type=MACHINE_TYPE, # min_replica_count=MIN_REPLICA_COUNT, # max_replica_count=MAX_REPLICA_COUNT, # ) # # model.wait() # # print(endpoint.display_name) # print(endpoint.resource_name) # print(f"Model {model.display_name} deployed to Endpoint {endpoint.display_name}.") # print(f"ENDPOINT_ID={endpoint.resource_name.split('/')[-1]}") # - # Copyright 2021 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
notebooks/building_production_ml_systems/labs/4a_streaming_data_training_vertex.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import keras keras.__version__ # # Understanding recurrent neural networks # # This notebook contains the code samples found in Chapter 6, Section 2 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments. # # --- # # [...] # # ## A first recurrent layer in Keras # # The process we just naively implemented in Numpy corresponds to an actual Keras layer: the `SimpleRNN` layer: # from keras.layers import SimpleRNN # There is just one minor difference: `SimpleRNN` processes batches of sequences, like all other Keras layers, not just a single sequence like # in our Numpy example. This means that it takes inputs of shape `(batch_size, timesteps, input_features)`, rather than `(timesteps, # input_features)`. # # Like all recurrent layers in Keras, `SimpleRNN` can be run in two different modes: it can return either the full sequences of successive # outputs for each timestep (a 3D tensor of shape `(batch_size, timesteps, output_features)`), or it can return only the last output for each # input sequence (a 2D tensor of shape `(batch_size, output_features)`). These two modes are controlled by the `return_sequences` constructor # argument. Let's take a look at an example: # + from keras.models import Sequential from keras.layers import Embedding, SimpleRNN model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32)) model.summary() # - model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32, return_sequences=True)) model.summary() # It is sometimes useful to stack several recurrent layers one after the other in order to increase the representational power of a network. # In such a setup, you have to get all intermediate layers to return full sequences: model = Sequential() model.add(Embedding(10000, 32)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32, return_sequences=True)) model.add(SimpleRNN(32)) # This last layer only returns the last outputs. model.summary() # Now let's try to use such a model on the IMDB movie review classification problem. First, let's preprocess the data: # + from keras.datasets import imdb from keras.preprocessing import sequence max_features = 10000 # number of words to consider as features maxlen = 500 # cut texts after this number of words (among top max_features most common words) batch_size = 32 print('Loading data...') (input_train, y_train), (input_test, y_test) = imdb.load_data(num_words=max_features) print(len(input_train), 'train sequences') print(len(input_test), 'test sequences') print('Pad sequences (samples x time)') input_train = sequence.pad_sequences(input_train, maxlen=maxlen) input_test = sequence.pad_sequences(input_test, maxlen=maxlen) print('input_train shape:', input_train.shape) print('input_test shape:', input_test.shape) # - # Let's train a simple recurrent network using an `Embedding` layer and a `SimpleRNN` layer: # + from keras.layers import Dense model = Sequential() model.add(Embedding(max_features, 32)) model.add(SimpleRNN(32)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model.fit(input_train, y_train, epochs=10, batch_size=128, validation_split=0.2) # - # Let's display the training and validation loss and accuracy: # + import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() # - # As a reminder, in chapter 3, our very first naive approach to this very dataset got us to 88% test accuracy. Unfortunately, our small # recurrent network doesn't perform very well at all compared to this baseline (only up to 85% validation accuracy). Part of the problem is # that our inputs only consider the first 500 words rather the full sequences -- # hence our RNN has access to less information than our earlier baseline model. The remainder of the problem is simply that `SimpleRNN` isn't very good at processing long sequences, like text. Other types of recurrent layers perform much better. Let's take a look at some # more advanced layers. # [...] # # ## A concrete LSTM example in Keras # # Now let's switch to more practical concerns: we will set up a model using a LSTM layer and train it on the IMDB data. Here's the network, # similar to the one with `SimpleRNN` that we just presented. We only specify the output dimensionality of the LSTM layer, and leave every # other argument (there are lots) to the Keras defaults. Keras has good defaults, and things will almost always "just work" without you # having to spend time tuning parameters by hand. # + from keras.layers import LSTM model = Sequential() model.add(Embedding(max_features, 32)) model.add(LSTM(32)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) history = model.fit(input_train, y_train, epochs=10, batch_size=128, validation_split=0.2) # + acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc)) plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.legend() plt.figure() plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show()
6.2-understanding-recurrent-neural-networks.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd import csv import gurobipy as gp from gurobipy import GRB #makes a dictionary for parcels parcels = {} with open ('Parcels.txt', mode = 'r') as csv_file: for line in csv_file: line.rstrip('\n') (key,val, val2) = line.split(',') parcels[int(key)] = [float(val), float(val2)] parcels #type(parcels) pars, areas, costs = gp.multidict(parcels) #turns dictionary into multidict, specifying what each column is budg = 1000000 #sets the limit for the budget constraint #makes list of tuples for adjacency--can't be dictionary because not unique keys adjacents = [] with open ('Adjacency.txt', mode = 'r') as csv_file: adjacents = [tuple(line) for line in csv.reader(csv_file)] for idx, (x,y) in enumerate(adjacents): #converting to integers adjacents[idx] = (int(x), int(y)) adjacents #type(adjacents) m = gp.Model('ParcelModel') #starts a model "m" x = m.addVars(pars, obj = areas, vtype = GRB.BINARY, name = "X") #sets decision variable X, binary, indexed by parcel ID,with area as the coefficient in the objective function y = m.addVars(adjacents, vtype = GRB.BINARY, name = "Y") #sets variable Y, binary, indexed by [i,j] in adjacents file B = m.addConstr(sum(costs[i]*x[i]for i in pars) <= budg, name = "budget") #budget constraint core = m.addConstr(x[23] == 1, name = "core") #parcel 23 must be included in the reserve for j in parcels: A = [item[0] for item in adjacents #finds all parcels adjacent to parcel j if item[1]==j] if not A: #skips this constraint if there are no parcels adjacent to j pass else: m.addConstr(sum(y[i,j] for i in A) <= len(A)*x[j], name = "no_flow" + str(j)) #no flow for parcel J constraint for i in parcels: A = [item[1] for item in adjacents #finds all parcels adjacent to parcel i if item[0]==i] if not A: pass #skips this constraint if there are no parcels adjacent to i else: m.addConstr(sum(y[i,j] for j in A) <= x[i], name = "one_flow" + str(i)) #one flow constraint for each parcel i #sum of all flow variables is 1 less than the sum of all parcels selected connected = m.addConstr(y.sum()== x.sum() - 1, name = "connected") z = m.addVars(adjacents, vtype = GRB.INTEGER, name = "Z") #tail length contribution variable w = m.addVars(parcels, vtype = GRB.INTEGER, name = "W") #tail length variable M = len(parcels) + 1 #set the value of M in tail length constraint (upper bound on flow) #tail length functions for i in parcels: A = [item[1] for item in adjacents #finds all parcels adjacent to i if item[0]==i] if not A: #if there are no parcels adjacent to i, skips this constraint pass else: for j in A: if j != i: #for each j where j does not equal i, calculates tail contribution m.addConstr(z[i,j] >= w[i] + 1 - M*(1 - y[i,j]), name = "tail" + str(i)+str(j)) #tail length W for j in parcels: A = [item[0] for item in adjacents #finds all parcels adjacent to j if item[1] == j] if not A: pass #skips this constraint if there are no parcels adjacent to j else: m.addConstr(w[j] == z.sum('*',j), name = "wtail" + str(j)) #calculates w[j] m.setObjective(x.prod(areas), GRB.MAXIMIZE) #set objective function to maximize m.write('ParcelModel.lp') #write lp file
Zoe_Final_Lab4.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .r # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: R # language: R # name: ir # --- x<- rnorm (100,0,1) y<- runif(100,min=0,max=1) df <- data.frame (x=sort(x), y=sort(y)) plot (df$y ~ df$x, main="Scatterplot Price vs Mleage", xlab="Mileage (mi.)", ylab="Price ($)") lm1 <- lm ( df$y ~ df$x) summary (lm1) lines (predict (lm1) ~ df$x, col="red") lm2 <- lm ( df$y ~ df$x) lines (predict (lm2) ~ df$x, col="blue") a=array(0,dim=c(50,16)) # a nrow(a) b=matrix(0, nrow = 50, ncol = 16) nrow(b) sine_wave<- function(x) { for(j in 1:3) { for (i in 1:nrow(x)/2) { } } }
Lab4_R/RExercise3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- from IPython.core.display import Image Image('https://www.python.org/static/community_logos/python-logo-master-v3-TM-flattened.png') print("Welcome to Academic!") # ## Install Python and Jupyter # # [Install Anaconda](https://www.anaconda.com/distribution/#download-section) which includes Python 3 and Jupyter notebook. # # Otherwise, for advanced users, install Jupyter notebook with `pip3 install jupyter`. # ## Create a new blog post [as usual](https://sourcethemes.com/academic/docs/managing-content/#create-a-blog-post) # # Run the following commands in your Terminal, substituting `<MY_WEBSITE_FOLDER>` and `my-post` with the file path to your Academic website folder and a name for your blog post (without spaces), respectively: # ```bash # # cd <MY_WEBSITE_FOLDER> # hugo new --kind post post/my-post # # cd <MY_WEBSITE_FOLDER>/content/post/my-post/ # ``` # ## Create or upload a Jupyter notebook # # Run the following command to start Jupyter within your new blog post folder. Then create a new Jupyter notebook (*New > Python Notebook*) or upload a notebook. # ```bash # jupyter notebook # ``` # ## Convert notebook to Markdown # ```bash # jupyter nbconvert Untitled.ipynb --to markdown --NbConvertApp.output_files_dir=. # # # Copy the contents of Untitled.md and append it to index.md: # # cat Untitled.md | tee -a index.md # # # Remove the temporary file: # # rm Untitled.md # ``` # ## Edit your post metadata # # Open `index.md` in your text editor and edit the title etc. in the [front matter](https://sourcethemes.com/academic/docs/front-matter/) according to your preference. # # To set a [featured image](https://sourcethemes.com/academic/docs/managing-content/#featured-image), place an image named `featured` into your post's folder. # # For other tips, such as using math, see the guide on [writing content with Academic](https://sourcethemes.com/academic/docs/writing-markdown-latex/).
content/post/jupyter/.ipynb_checkpoints/academic-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] slideshow={"slide_type": "slide"} # # Geochronology Calculations # + hide_input=true slideshow={"slide_type": "slide"} tags=["hide-input"] import matplotlib.pyplot as plt from bokeh.plotting import figure, output_notebook, show from bokeh.layouts import column from bokeh.models import Range1d, LinearAxis, ColumnDataSource, LabelSet, Span, Slope, Label, Legend from scipy.interpolate import CubicSpline import pandas as pd import numpy as np from IPython.core.display import display, HTML import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) output_notebook() import geochron_apps as gc # + [markdown] slideshow={"slide_type": "fragment"} # <center><img src="images/geochronology.png" align="center"> # https://www.explainxkcd.com/wiki/index.php/1829:_Geochronology # </center> # + [markdown] slideshow={"slide_type": "notes"} # The following presentation shows some of the geochronology calculations learned in the Advanced Geochronology class at University of Saskatchewan taught by <NAME> and <NAME>, 2021. Some of the images in this presentation are taken from lectures given by the instructor. # + [markdown] slideshow={"slide_type": "slide"} # This notebook contains sample calculations typically used in geochronology. It can be obtained at https://git.cs.usask.ca/msv275/advanced-geochronology. # It can be cloned through the git command: # * git clone https://git.cs.usask.ca/msv275/advanced-geochronology.git # # + [markdown] slideshow={"slide_type": "slide"} # ## Rb-Sr Calculations # + [markdown] slideshow={"slide_type": "subslide"} # Assume an initial 87Sr/86Sr starting composition of **0.704** and 87Rb/86Sr values of **500.0** for a minerals (let’s say it is biotite) formed at **2000** Ma. # Calculate the present day 87Sr/86Sr composition. # + [markdown] slideshow={"slide_type": "fragment"} # For this question, we simply need to call our calc_isochron function with different parameters. # * initial = 0.704 # * pd_ratio = 500 # * decay_const = 1.42 x 10<sup>-11</sup> # * t1 = 2000 # * t2 = 0 # + slideshow={"slide_type": "fragment"} initial = 0.704 pd_ratio = 500.0 decay_const = 1.42*10**-11 t1 = 2000 print("The present day 87Sr/86Sr composition is {}.".format(gc.calc_t2_daughter(initial, pd_ratio, decay_const, t1))) # + [markdown] slideshow={"slide_type": "subslide"} # Assume you have measured present day 87Sr/86Sr and 87Rb/86Sr compositions of **0.73** and **1000.0**, respectively in a mineral like biotite. # Say you also have an estimate of the initial 87Sr/86Sr composition of the rock from some high-Sr concentration mineral like apatite with a value of **0.704**. # Calculate the apparent age of the biotite. # + [markdown] slideshow={"slide_type": "fragment"} # In order to calculate age, we just rework the isochron equation to: # # # ln(present day/parent-daughter - initial/parent-daughter + 1) / λ # # Now we need a new function: # + [markdown] slideshow={"slide_type": "subslide"} # And we know our paramters: # * est_initial = 0.704 # * pd_ratio = 1000 # * present_day = 0.73 # * decay_const = 1.42 x 10<sup>-11</sup> # + slideshow={"slide_type": "fragment"} est_t1_daughter = 0.704 t2_parent = 1000 t2_daughter = 0.73 decay_const = 1.42*10**-11 print("The apparent age of the biotite is {} Ma.".format(gc.calc_age(est_t1_daughter, t2_parent, t2_daughter, decay_const))) # + [markdown] slideshow={"slide_type": "subslide"} # Repeat this calculation assuming the initial 87Sr/86Sr composition was **0.0**. # Compare the two ages. # Is there much difference in age? # + [markdown] slideshow={"slide_type": "fragment"} # For this we simply need to change the value of our initial composition to 0.0. # + slideshow={"slide_type": "fragment"} est_initial = 0.0 print("The apparent age of the biotite is {} Ma.".format(gc.calc_age(est_initial, pd_ratio, present_day, decay_const))) # + [markdown] slideshow={"slide_type": "notes"} # This is about a 50 Ma year difference! The issue is there is little difference between the initial and present day daughter isotopes. # + [markdown] slideshow={"slide_type": "subslide"} # Take the first bullet and calculate 87Sr/86Sr at **500 Ma**. # # Note: I wasn't sure if this implied the minerals formed at 500 Ma, or the minerals formed at 2000 Ma and the calculation is asking for the ratio at 500 Ma (instead of present day), so I did both! # + slideshow={"slide_type": "fragment"} print("If formed 500 Ma the present day 87Sr/86Sr composition is {}.".format(gc.calc_t2_daughter(est_initial,500,decay_const,500, 0))) print("If formed 2000 Ma the 500 Ma 87Sr/86Sr composition is {}.".format(gc.calc_t2_daughter(est_initial,500,decay_const,2000,500))) # + [markdown] slideshow={"slide_type": "subslide"} # Assume an initial 87Sr/86Sr starting composition of **0.704** and 87Rb/86Sr values of **0.1, 10, 100 and 500.0** for a set of rocks and minerals formed at **2000 Ma**. # Calculate the present day 87Sr/86Sr compositions. # + [markdown] slideshow={"slide_type": "fragment"} # Again, we now have a function for this, so we calculate it in the same we did for Pb/Pb # + slideshow={"slide_type": "fragment"} initial = 0.704 pd_list = [0.1,10,100,500.0] Rb_Sr = [] decay_const = 1.42*10**-11 t1 = 2000 for pd_ratio in pd_list: Rb_Sr.append(gc.calc_t2_daughter(initial, pd_ratio, decay_const, t1,)) RbSr_df = pd.DataFrame() RbSr_df['87Sr/86Sr'] = pd_list RbSr_df['87Rb/86Sr'] = Rb_Sr RbSr_df # + [markdown] slideshow={"slide_type": "subslide"} # Assume the pluton was metamorphosed at **1000 Ma** and the various rocks and minerals were homogenised. # Take a simple average of the calculated 87Sr/86Sr at this time as the start of growth of the new mineral systems. # Assume the newly formed minerals have 87Rb/86Sr values of **1.0, 5.0, 50.0 and 400.0.** # * Calculate present day values. # * Calculate the slope of the original minerals and rocks and do the same for the metamorphic minerals. # * Express these slopes in terms of age. # * What are the initial ratios of the regression lines? # + [markdown] slideshow={"slide_type": "subslide"} # First we build our dataframe for the original minerals, and calculate the composition of 87Sr/86Sr at 1000 Ma. # + slideshow={"slide_type": "fragment"} df1 = pd.DataFrame() initial1 = 0.704 decay_const = 1.42*10**-11 t1, t2 = 2000, 1000 df1['1000_Ma_87Rb_86Sr'] = [0.1,10,100,500.0] df1['1000_Ma_87Sr_86Sr'] = gc.calc_t2_daughter(initial1, df1['1000_Ma_87Rb_86Sr'], decay_const, t1, t2) print(df1) # + [markdown] slideshow={"slide_type": "subslide"} # The average 87Sr/86Sr at 1000 Ma is easy to calculate (which will be used for the metamorphic minerals): # + slideshow={"slide_type": "fragment"} avg = df1["1000_Ma_87Sr_86Sr"].mean() print(avg) # + [markdown] slideshow={"slide_type": "subslide"} # We calculate our slope from the isochron equation, where the slope = *e*<sup>λ x t1</sup> - *e*<sup>λ x t2</sup> # + slideshow={"slide_type": "fragment"} slope1 = np.exp(1.42*10**-11*t1*1000000) - np.exp(1.42*10**-11*t2*1000000) print(slope1) # + [markdown] slideshow={"slide_type": "subslide"} # Finally let's plot the data in Bokeh! # + slideshow={"slide_type": "skip"} figure3 = gc.get_figure("Rubidium Strontium Isochron", "87Sr/86Sr", "87Rb/86Sr", [0,550], [0,9]) figure3.circle(df1['1000_Ma_87Rb_86Sr'], df1['1000_Ma_87Sr_86Sr'], color="red") reg_line = Slope(gradient=slope1, y_intercept=initial1, line_color="red", line_dash="dashed") figure3.add_layout(reg_line) hline = Span(location=initial, dimension='width', line_color="grey") figure3.renderers.extend([hline]) t_text = " t = {} Ma ".format(t2) i_text = " 87Sr/86Sr initial = {} ".format(initial1) t_label = Label(x=25, y=8, text=t_text, border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) i_label = Label(x=25, y=7.6, text=i_text, border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) figure3.add_layout(t_label) figure3.add_layout(i_label) # + slideshow={"slide_type": "subslide"} show(figure3) # + [markdown] slideshow={"slide_type": "subslide"} # We'll repeat the same methods for the metamorphic minerals with the average 87Sr/86Sr calculated above. # + slideshow={"slide_type": "fragment"} df2 = pd.DataFrame() t1, t2 = 1000, 0 initial2 = avg df2['0_Ma_87Rb_86Sr'] = [1.0,5.0,50.0,400.0] df2['0_Ma_87Sr_86Sr'] = gc.calc_t2_daughter(initial2, df2['0_Ma_87Rb_86Sr'], decay_const, t1) df2 # + [markdown] slideshow={"slide_type": "subslide"} # We calculate our slope. # + slideshow={"slide_type": "fragment"} slope2 = np.exp(1.42*10**-11*t1*1000000) - np.exp(1.42*10**-11*t2*1000000) slope2 # + slideshow={"slide_type": "skip"} figure4 = gc.get_figure("Rubidium Strontium Isochron", "87Sr/86Sr", "87Rb/86Sr", [0,550], [2,9]) figure4.circle(df2['0_Ma_87Rb_86Sr'], df2['0_Ma_87Sr_86Sr'], color="red") reg_line = Slope(gradient=slope2, y_intercept=initial2, line_color="red", line_dash="dashed") figure4.add_layout(reg_line) hline = Span(location=initial2, dimension='width', line_color="grey") figure4.renderers.extend([hline]) t_text = " t = {} Ma ".format(t2) i_text = " 87Sr/86Sr initial = {} ".format(round(initial2,4)) t_label = Label(x=25, y=8, text=t_text, border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) i_label = Label(x=25, y=7.6, text=i_text, border_line_color='black', border_line_alpha=1.0, background_fill_color='white', background_fill_alpha=1.0) figure4.add_layout(t_label) figure4.add_layout(i_label) # + slideshow={"slide_type": "subslide"} show(figure4) # + [markdown] slideshow={"slide_type": "subslide"} # What is the MSWD for each of these lines? # + [markdown] slideshow={"slide_type": "fragment"} # There is no information on the weights of each of these samples, so we assume an equal weighting for each sample. Our first step is to calculate what our best fit line predicts our 87Sr/86Sr to be with our given 87Rb/86Sr. This can be done by using the calculation for y with our slope, intercept, and x known. y=mx+b. # We will also add a column for weights, but for this example we are assuming equal weighting so this will not effect our results. # + slideshow={"slide_type": "fragment"} df1['predicted_1000_Ma_87Sr_86Sr'] = slope1*df1['0_Ma_87Rb_86Sr'] + initial1 df1['weights'] = 1 df1 # + [markdown] slideshow={"slide_type": "subslide"} # We then calculate the weighted, squared distance from each predicted point to its actual point. # - df1['chi_squared'] = ((df1['predicted_1000_Ma_87Sr_86Sr'] - df1['1000_Ma_87Sr_86Sr']) / df1['weights'])**2 df1 # And the MSWD is the cumulative sum of these values. mswd1 = sum(df1['chi_squared']) mswd1 # Now we just repeat the calculations for the second line. df2['predicted_0_Ma_87Sr_86Sr'] = slope2*df2['0_Ma_87Rb_86Sr'] + initial2 df2['weights'] = 1 df2['chi_squared'] = ((df2['predicted_0_Ma_87Sr_86Sr'] - df2['0_Ma_87Sr_86Sr']) / df2['weights'])**2 df2 mswd2 = sum(df2['chi_squared']) mswd2 # This shows that there the MSWD for both lines are 0. This is not unexpected as it is a perfect line.
Geochron_Calculations_SrRb.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernel_info: # name: python3 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # # WeatherPy # ---- # # #### Note # * 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 time # Import API key from api_keys import api_key # Incorporated citipy to determine city based on latitude and longitude from citipy import citipy # Output File (CSV) output_data_file = "output_data/cities.csv" # Range of latitudes and longitudes lat_range = (-90, 90) lng_range = (-180, 180) # - # ## Generate Cities List # + # List for holding lat_lngs and cities lat_lngs = [] cities = [] # Create a set of random lat and lng combinations lats = np.random.uniform(low=-90.000, high=90.000, size=1500) lngs = np.random.uniform(low=-180.000, high=180.000, size=1500) lat_lngs = zip(lats, lngs) # Identify nearest city for each lat, lng combination for lat_lng in lat_lngs: city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name # If the city is unique, then add it to a our cities list if city not in cities: cities.append(city) # Print the city count to confirm sufficient count len(cities) # - # ### Perform API Calls # * Perform a weather check on each city using a series of successive API calls. # * Include a print log of each city as it'sbeing processed (with the city number and city name). # # ### Convert Raw Data to DataFrame # * Export the city data into a .csv. # * Display the DataFrame # ### Plotting the Data # * Use proper labeling of the plots using plot titles (including date of analysis) and axes labels. # * Save the plotted figures as .pngs. # #### Latitude vs. Temperature Plot # #### Latitude vs. Humidity Plot # #### Latitude vs. Cloudiness Plot # #### Latitude vs. Wind Speed Plot
06-Python-APIs/HW/Instructions/starter_code/WeatherPy.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # First BigQuery ML models for Taxifare Prediction # # In this notebook, we will use BigQuery ML to build our first models for taxifare prediction.BigQuery ML provides a fast way to build ML models on large structured and semi-structured datasets. # # ## Learning Objectives # 1. Choose the correct BigQuery ML model type and specify options # 2. Evaluate the performance of your ML model # 3. Improve model performance through data quality cleanup # 4. Create a Deep Neural Network (DNN) using SQL # # Each learning objective will correspond to a __#TODO__ in the [student lab notebook](../labs/first_model.ipynb) -- try to complete that notebook first before reviewing this solution notebook. # # # We'll start by creating a dataset to hold all the models we create in BigQuery # + language="bash" # export PROJECT=$(gcloud config list project --format "value(core.project)") # echo "Your current GCP Project Name is: "$PROJECT # + import os PROJECT = "qwiklabs-gcp-bdc77450c97b4bf6" # REPLACE WITH YOUR PROJECT NAME REGION = "us-central1" # REPLACE WITH YOUR BUCKET REGION e.g. us-central1 # Do not change these os.environ["PROJECT"] = PROJECT os.environ["REGION"] = REGION os.environ["BUCKET"] = PROJECT # DEFAULT BUCKET WILL BE PROJECT ID if PROJECT == "your-gcp-project-here": print("Don't forget to update your PROJECT name! Currently:", PROJECT) # - # ## Create a BigQuery Dataset and Google Cloud Storage Bucket # # A BigQuery dataset is a container for tables, views, and models built with BigQuery ML. Let's create one called __serverlessml__ if we have not already done so in an earlier lab. We'll do the same for a GCS bucket for our project too. # + language="bash" # # ## Create a BigQuery dataset for serverlessml if it doesn't exist # datasetexists=$(bq ls -d | grep -w serverlessml) # # if [ -n "$datasetexists" ]; then # echo -e "BigQuery dataset already exists, let's not recreate it." # # else # echo "Creating BigQuery dataset titled: serverlessml" # # bq --location=US mk --dataset \ # --description 'Taxi Fare' \ # $PROJECT:serverlessml # echo "\nHere are your current datasets:" # bq ls # fi # # ## Create GCS bucket if it doesn't exist already... # exists=$(gsutil ls -d | grep -w gs://${PROJECT}/) # # if [ -n "$exists" ]; then # echo -e "Bucket exists, let's not recreate it." # # else # echo "Creating a new GCS bucket." # gsutil mb -l ${REGION} gs://${PROJECT} # echo "\nHere are your current buckets:" # gsutil ls # fi # - # ## Model 1: Raw data # # Let's build a model using just the raw data. It's not going to be very good, but sometimes it is good to actually experience this. # # The model will take a minute or so to train. When it comes to ML, this is blazing fast. # + # %%bigquery CREATE OR REPLACE MODEL serverlessml.model1_rawdata OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg') AS SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 # - # Once the training is done, visit the [BigQuery Cloud Console](https://console.cloud.google.com/bigquery) and look at the model that has been trained. Then, come back to this notebook. # Note that BigQuery automatically split the data we gave it, and trained on only a part of the data and used the rest for evaluation. We can look at eval statistics on that held-out data: # %%bigquery SELECT * FROM ML.EVALUATE(MODEL serverlessml.model1_rawdata) # Let's report just the error we care about, the Root Mean Squared Error (RMSE) # %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model1_rawdata) # We told you it was not going to be good! Recall that our heuristic got 8.13, and our target is $6. # Note that the error is going to depend on the dataset that we evaluate it on. # We can also evaluate the model on our own held-out benchmark/test dataset, but we shouldn't make a habit of this (we want to keep our benchmark dataset as the final evaluation, not make decisions using it all along the way. If we do that, our test dataset won't be truly independent). # %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model1_rawdata, ( SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 2 AND trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 )) # ## Model 2: Apply data cleanup # # Recall that we did some data cleanup in the previous lab. Let's do those before training. # # This is a dataset that we will need quite frequently in this notebook, so let's extract it first. # + # %%bigquery CREATE OR REPLACE TABLE serverlessml.cleaned_training_data AS SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 100000) = 1 AND trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 # - # %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM serverlessml.cleaned_training_data LIMIT 0 # + # %%bigquery CREATE OR REPLACE MODEL serverlessml.model2_cleanup OPTIONS(input_label_cols=['fare_amount'], model_type='linear_reg') AS SELECT * FROM serverlessml.cleaned_training_data # - # %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model2_cleanup) # ## Model 3: More sophisticated models # # What if we try a more sophisticated model? Let's try Deep Neural Networks (DNNs) in BigQuery: # ### DNN # To create a DNN, simply specify __dnn_regressor__ for the model_type and add your hidden layers. # + # %%bigquery -- This model type is in alpha, so it may not work for you yet. This training takes on the order of 15 minutes. CREATE OR REPLACE MODEL serverlessml.model3b_dnn OPTIONS(input_label_cols=['fare_amount'], model_type='dnn_regressor', hidden_units=[32, 8]) AS SELECT * FROM serverlessml.cleaned_training_data # - # %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model3b_dnn) # Nice! # ## Evaluate DNN on benchmark dataset # # Let's use the same validation dataset to evaluate -- remember that evaluation metrics depend on the dataset. You can not compare two models unless you have run them on the same withheld data. # %%bigquery SELECT SQRT(mean_squared_error) AS rmse FROM ML.EVALUATE(MODEL serverlessml.model3b_dnn, ( SELECT (tolls_amount + fare_amount) AS fare_amount, pickup_datetime, pickup_longitude AS pickuplon, pickup_latitude AS pickuplat, dropoff_longitude AS dropofflon, dropoff_latitude AS dropofflat, passenger_count*1.0 AS passengers, 'unused' AS key FROM `nyc-tlc.yellow.trips` WHERE MOD(ABS(FARM_FINGERPRINT(CAST(pickup_datetime AS STRING))), 10000) = 2 AND trip_distance > 0 AND fare_amount >= 2.5 AND pickup_longitude > -78 AND pickup_longitude < -70 AND dropoff_longitude > -78 AND dropoff_longitude < -70 AND pickup_latitude > 37 AND pickup_latitude < 45 AND dropoff_latitude > 37 AND dropoff_latitude < 45 AND passenger_count > 0 )) # Wow! Later in this sequence of notebooks, we will get to below $4, but this is quite good, for very little work. # In this notebook, we showed you how to use BigQuery ML to quickly build ML models. We will come back to BigQuery ML when we want to experiment with different types of feature engineering. The speed of BigQuery ML is very attractive for development. # 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.
quests/serverlessml/02_bqml/solution/first_model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Set and Booleans # # There are two other object types in Python that we should quickly cover. Sets and Booleans. # # ##Sets # # Sets are an unordered collection of *unique* elements. We can construct them by using the set() function. Let's go ahead and make a set to see how it works x = set() # We add to sets with the add() method x.add(1) #Show x # Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as a set being a dictionary with only keys. # # We know that a set has only unique entries. So what happens when we try to add something that is already in a set? # Add a different element x.add(2) #Show x # Try to add the same element x.add(1) #Show x # Notice how it won't place another 1 there. That's because a set is only concerned with unique elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For example: # Create a list with repeats l = [1,1,2,2,3,4,5,6,1,1] # Cast as set to get unique values set(l) # ## Booleans # # Python comes with Booleans (with predefined True and False displays that are basically just the integers 1 and 0). It also has a placeholder object called None. Let's walk through a few quick examples of Booleans (we will dive deeper into them later in this course). # Set object to be a boolean a = True #Show a # We can also use comparison operators to create booleans. We will go over all the comparison operators later on in the course. # Output is boolean 1 > 2 # We can use None as a placeholder for an object that we don't want to reassign yet: # None placeholder b = None # Thats it! You should now have a basic understanding of Python objects and data structure types. Next, go ahead and do the assessment test!
others/resources/python/intro-to-python-jupyter-notebooks-master/7-Sets and Booleans.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import cv2 import matplotlib.pyplot as plt # ## Load Image pic = cv2.imread('./pic/1.bmp') plt.imshow(pic) # ## Image Thinning class FingerprintProcessor(): def __init__(self, pic): # change to grayscale if pic.shape[2] == 3: pic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY) pic = cv2.equalizeHist(pic) self.pic = pic def preprocess(self): ret, self.pic = cv2.threshold(self.pic, 110, 255, cv2.THRESH_BINARY_INV) # self.thinning() self.pic = cv2.ximgproc.thinning(self.pic, cv2.ximgproc.THINNING_GUOHALL) rect = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) self.pic = cv2.dilate(self.pic, rect, iterations = 1) def thinning(self): rect = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)) self.pic = cv2.morphologyEx(self.pic, cv2.MORPH_OPEN, rect) rect = cv2.getStructuringElement(cv2.MORPH_RECT, (2,2)) self.pic = cv2.erode(self.pic, rect, iterations = 1) temp = FingerprintProcessor(pic) temp.preprocess() plt.title('INV thinning d after open operation') plt.imshow(temp.pic, cmap='gray')
.ipynb_checkpoints/Traditional-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Temporal association in assymetric neural networks # This is an attempt to reproduce this paper. # # https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.57.2861 # + import pprint import subprocess import sys sys.path.append('../') import numpy as np import matplotlib.pyplot as plt import matplotlib import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable import seaborn as sns # %matplotlib inline plt.rcParams['figure.figsize'] = (12.9, 12) np.set_printoptions(suppress=True, precision=2) sns.set(font_scale=3.5) # - # Let's first create some random pattenrs with 1 and -1 # + n_network = 500 # The size of the network n_patterns = 10 n_sequence = 10 l = 2.5 patterns_to_store = np.random.choice([-1, 1], size=(n_patterns, n_network), replace=True) # - # Let's build the connectivity matrices # + J1 = np.zeros((n_network, n_network)) for pattern in patterns_to_store: J1 += np.outer(pattern, pattern) J1 /= n_network # + J2 = np.zeros((n_network, n_network)) for index in range(n_patterns - 1): J2 += np.outer(patterns_to_store[index + 1], patterns_to_store[index]) J2 *= (l / n_network) # - # Now let's make the system evolve # + T = 50 tau = 8 S_initial = np.array([patterns_to_store[0] for i in range(tau)]) S_aux = np.zeros((T, n_network)) S = np.vstack((S_initial, S_aux)) for t in range(tau, T + tau - 1): h1 = J1 @ S[t, :] S_avg = (1 / tau) * S[(t - tau):t, :].sum(axis=0) h2 = J2 @ S_avg S[t + 1, :] = np.sign(h1 + h2) # - # Now we need to calculate the overlaps to see the evolution of the system. # + m = np.zeros(((tau + T), n_patterns)) for t in range(tau + T): for index, pattern in enumerate(patterns_to_store): m[t, index] = (1 / n_network) * (S[t, :] @ pattern) # + cmap = sns.color_palette("Reds_r", n_colors=n_patterns) for index, overlap in enumerate(m.T): plt.plot(overlap, color=cmap[index], lw=5) # - plt.matshow(S) S[-4, ...]
notebooks/2018-03-22(Sompolinsky Draft).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.metrics import roc_curve, auc from sklearn.model_selection import train_test_split from sklearn.preprocessing import label_binarize from sklearn.multiclass import OneVsRestClassifier # ROC curves are typically used in binary classification to study the output of a classifier. In order to extend ROC curve and ROC area to multi-class or multi-label classification, it is necessary to binarize the output. One ROC curve can be drawn per label, but one can also draw a ROC curve by considering each element of the label indicator matrix as a binary prediction (micro-averaging). # Import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target X.shape # Binarize the output # multi-class classification case is to one-vs-all scheme y = label_binarize(y, classes=[0, 1, 2]) n_classes = y.shape[1] n_classes # Add noisy features to make the problem harder random_state = np.random.RandomState(0) n_samples, n_features = X.shape X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] # np,c_ - Translates slice objects to concatenation along the second axis X.shape # shuffle and split training and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0) X_train.shape # Learn to predict each class against the other classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state)) y_score = classifier.fit(X_train, y_train).decision_function(X_test) # decision_function - Distance of the samples X to the separating hyperplane # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) len(fpr[0]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) roc_auc plt.figure() plt.plot(fpr['micro'], tpr['micro'], color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc[2]) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show()
Model_Evaluation-Iris.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import sys sys.path.append("..") # Adds higher directory to python modules path. # + tuples = [(0.7,48000,1),(1.9,48000,0),(2.5,60000,1),(4.2,63000,0),(6,76000,0),(6.5,69000,0),(7.5,76000,0),(8.1,88000,0),(8.7,83000,1),(10,83000,1),(0.8,43000,0),(1.8,60000,0),(10,79000,1),(6.1,76000,0),(1.4,50000,0),(9.1,92000,0),(5.8,75000,0),(5.2,69000,0),(1,56000,0),(6,67000,0),(4.9,74000,0),(6.4,63000,1),(6.2,82000,0),(3.3,58000,0),(9.3,90000,1),(5.5,57000,1),(9.1,102000,0),(2.4,54000,0),(8.2,65000,1),(5.3,82000,0),(9.8,107000,0),(1.8,64000,0),(0.6,46000,1),(0.8,48000,0),(8.6,84000,1),(0.6,45000,0),(0.5,30000,1),(7.3,89000,0),(2.5,48000,1),(5.6,76000,0),(7.4,77000,0),(2.7,56000,0),(0.7,48000,0),(1.2,42000,0),(0.2,32000,1),(4.7,56000,1),(2.8,44000,1),(7.6,78000,0),(1.1,63000,0),(8,79000,1),(2.7,56000,0),(6,52000,1),(4.6,56000,0),(2.5,51000,0),(5.7,71000,0),(2.9,65000,0),(1.1,33000,1),(3,62000,0),(4,71000,0),(2.4,61000,0),(7.5,75000,0),(9.7,81000,1),(3.2,62000,0),(7.9,88000,0),(4.7,44000,1),(2.5,55000,0),(1.6,41000,0),(6.7,64000,1),(6.9,66000,1),(7.9,78000,1),(8.1,102000,0),(5.3,48000,1),(8.5,66000,1),(0.2,56000,0),(6,69000,0),(7.5,77000,0),(8,86000,0),(4.4,68000,0),(4.9,75000,0),(1.5,60000,0),(2.2,50000,0),(3.4,49000,1),(4.2,70000,0),(7.7,98000,0),(8.2,85000,0),(5.4,88000,0),(0.1,46000,0),(1.5,37000,0),(6.3,86000,0),(3.7,57000,0),(8.4,85000,0),(2,42000,0),(5.8,69000,1),(2.7,64000,0),(3.1,63000,0),(1.9,48000,0),(10,72000,1),(0.2,45000,0),(8.6,95000,0),(1.5,64000,0),(9.8,95000,0),(5.3,65000,0),(7.5,80000,0),(9.9,91000,0),(9.7,50000,1),(2.8,68000,0),(3.6,58000,0),(3.9,74000,0),(4.4,76000,0),(2.5,49000,0),(7.2,81000,0),(5.2,60000,1),(2.4,62000,0),(8.9,94000,0),(2.4,63000,0),(6.8,69000,1),(6.5,77000,0),(7,86000,0),(9.4,94000,0),(7.8,72000,1),(0.2,53000,0),(10,97000,0),(5.5,65000,0),(7.7,71000,1),(8.1,66000,1),(9.8,91000,0),(8,84000,0),(2.7,55000,0),(2.8,62000,0),(9.4,79000,0),(2.5,57000,0),(7.4,70000,1),(2.1,47000,0),(5.3,62000,1),(6.3,79000,0),(6.8,58000,1),(5.7,80000,0),(2.2,61000,0),(4.8,62000,0),(3.7,64000,0),(4.1,85000,0),(2.3,51000,0),(3.5,58000,0),(0.9,43000,0),(0.9,54000,0),(4.5,74000,0),(6.5,55000,1),(4.1,41000,1),(7.1,73000,0),(1.1,66000,0),(9.1,81000,1),(8,69000,1),(7.3,72000,1),(3.3,50000,0),(3.9,58000,0),(2.6,49000,0),(1.6,78000,0),(0.7,56000,0),(2.1,36000,1),(7.5,90000,0),(4.8,59000,1),(8.9,95000,0),(6.2,72000,0),(6.3,63000,0),(9.1,100000,0),(7.3,61000,1),(5.6,74000,0),(0.5,66000,0),(1.1,59000,0),(5.1,61000,0),(6.2,70000,0),(6.6,56000,1),(6.3,76000,0),(6.5,78000,0),(5.1,59000,0),(9.5,74000,1),(4.5,64000,0),(2,54000,0),(1,52000,0),(4,69000,0),(6.5,76000,0),(3,60000,0),(4.5,63000,0),(7.8,70000,0),(3.9,60000,1),(0.8,51000,0),(4.2,78000,0),(1.1,54000,0),(6.2,60000,0),(2.9,59000,0),(2.1,52000,0),(8.2,87000,0),(4.8,73000,0),(2.2,42000,1),(9.1,98000,0),(6.5,84000,0),(6.9,73000,0),(5.1,72000,0),(9.1,69000,1),(9.8,79000,1),] data = [list(row) for row in tuples] xs = [[1.0] + row[:2] for row in data] # [1, experience, salary] ys = [row[2] for row in data] # paid_account # - from matplotlib import pyplot as plt def logistic(x: float) -> float: return 1.0 / (1 + math.exp(-x)) def logistic_prime(x: float) -> float: y = logistic(x) return y * (1 - y) import math from scratch.linear_algebra import Vector, dot def _negative_log_likelihood(x: Vector, y: float, beta: Vector) -> float: """The negative log likelihood for one data point""" if y == 1: return -math.log(logistic(dot(x, beta))) else: return -math.log(1 - logistic(dot(x, beta))) from typing import List def negative_log_likelihood(xs: List[Vector], ys: List[float], beta: Vector) -> float: return sum(_negative_log_likelihood(x, y, beta) for x, y in zip(xs, ys)) from scratch.linear_algebra import vector_sum def _negative_log_partial_j(x: Vector, y: float, beta: Vector, j: int) -> float: """ The j-th partial derivative for one data pont here i is the index of the data point """ return -(y - logistic(dot(x, beta))) * x[j] def _negative_log_gradient(x: Vector, y: float, beta: Vector) -> Vector: """ The gradient for one data point """ return [_negative_log_partial_j(x, y, beta, j) for j in range(len(beta))] def negative_log_gradient(xs: List[Vector], ys: List[float], beta: Vector) -> Vector: return vector_sum([_negative_log_gradient(x, y, beta) for x, y in zip(xs, ys)]) # + def main(): from matplotlib import pyplot as plt plt.close() plt.clf() plt.gca().clear() from matplotlib import pyplot as plt from scratch.working_with_data import rescale from scratch.multiple_regression import least_squares_fit, predict from scratch.gradient_descent import gradient_step learning_rate = 0.001 rescaled_xs = rescale(xs) beta = least_squares_fit(rescaled_xs, ys, learning_rate, 1000, 1) # [0.26, 0.43, -0.43] predictions = [predict(x_i, beta) for x_i in rescaled_xs] plt.scatter(predictions, ys) plt.xlabel("predicted") plt.ylabel("actual") plt.show() # plt.savefig('im/linear_regression_for_probabilities.png') # plt.close() from scratch.machine_learning import train_test_split import random import tqdm random.seed(0) x_train, x_test, y_train, y_test = train_test_split(rescaled_xs, ys, 0.33) learning_rate = 0.01 # pick a random starting point beta = [random.random() for _ in range(3)] with tqdm.trange(5000) as t: for epoch in t: gradient = negative_log_gradient(x_train, y_train, beta) beta = gradient_step(beta, gradient, -learning_rate) loss = negative_log_likelihood(x_train, y_train, beta) t.set_description(f"loss: {loss:.3f} beta: {beta}") from scratch.working_with_data import scale means, stdevs = scale(xs) beta_unscaled = [(beta[0] - beta[1] * means[1] / stdevs[1] - beta[2] * means[2] / stdevs[2]), beta[1] / stdevs[1], beta[2] / stdevs[2]] # [8.9, 1.6, -0.000288] assert (negative_log_likelihood(xs, ys, beta_unscaled) == negative_log_likelihood(rescaled_xs, ys, beta)) true_positives = false_positives = true_negatives = false_negatives = 0 for x_i, y_i in zip(x_test, y_test): prediction = logistic(dot(beta, x_i)) if y_i == 1 and prediction >= 0.5: # TP: paid and we predict paid true_positives += 1 elif y_i == 1: # FN: paid and we predict unpaid false_negatives += 1 elif prediction >= 0.5: # FP: unpaid and we predict paid false_positives += 1 else: # TN: unpaid and we predict unpaid true_negatives += 1 precision = true_positives / (true_positives + false_positives) recall = true_positives / (true_positives + false_negatives) print(precision, recall) assert precision == 0.75 assert recall == 0.8 plt.clf() plt.gca().clear() predictions = [logistic(dot(beta, x_i)) for x_i in x_test] plt.scatter(predictions, y_test, marker='+') plt.xlabel("predicted probability") plt.ylabel("actual outcome") plt.title("Logistic Regression Predicted vs. Actual") plt.show() # plt.savefig('im/logistic_regression_predicted_vs_actual.png') # plt.gca().clear() if __name__ == "__main__": main() # -
notebooks/16_logistic_regression.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Getting familiar with the API using Python # # In this section I explore the Trundler API using Python. # I convert the response of the requests into a Pandas DataFrame, then I get the names of the columns and shape in order to know the type of data I am dealing with. # ## Requests and responses # I write the following script to get the desired information: # + import requests import json import pandas as pd headers = { 'accept': 'application/json', 'X-Api-Key': {my_API_key}, } retailer_id = {retailer_id} product_id = {product_id} endpoints = ['/retailer', '/retailer/'+ str(retailer_id), '/retailer/'+ str(retailer_id) +'/product', '/product', '/product/'+ str(product_id), '/product/'+ str(product_id) +'/price' ] for end in endpoints: response = requests.get('https://api.trundler.dev/'+end, headers=headers) j_response = json.loads(response.text) df = pd.DataFrame(pd.json_normalize(j_response)) print("--Endpoint--", end) print("Shape: ",df.shape) print("Columns: ",df.columns,"\n")
notebooks/APIpython.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 # language: python # name: python2 # --- # # Sparse Autoencoder # # 當在訓練一個普通的 `autoenoder` 時,如果嘗試丟入一些輸入,會看到中間許多的神經元 (hidden unit) 大部分都會有所反應 (activate).反應的意思是這個神經元的輸出不會等於零,也不會很接近零,而是大於零許多.白話的意思就是神經元說:「咦!這個輸入我認識噢~」 # # 然而我們是不想要看到這樣的情形的!我們想要看到的情形是每個神經元只對一些些訓練輸入有反應.例如手寫數字 0-9,那神經元 A 只對數字 5 有反應,神經元 B 只對 7 有反應 ... 等.為什麼要這樣的結果呢?在 [Quora](https://www.quora.com/Why-are-sparse-autoencoders-sparse) 上面有一個解說是這樣的 # # > 如果一個人可以做 A, B, C ... 許多的工作,那他就不太可能是 A 工作的專家,或是 B 工作的專家. # > 如果一個神經元對於每個不同的訓練都會有反應,那有它沒它好像沒有什麼差別 # # 所以接下來要做的事情就是加上稀疏的限制條件 (sparse constraint),來訓練出 `Sparse Autoencoder`.而要在哪裡加上這個限制呢?就是要在 loss 函數中做手腳.在這裡我們會加上兩個項,分別是: # # * Sparsity Regularization # * L2 Regularization # # ## Sparsity Regularization # # 這一項我們想要做的事就是讓 autoencoder 中每個神經元的輸出變小,而實際上的做法則是如下 # **先設定一個值,然後讓平均神經元輸出值 (average output activation vlue) 越接近它越好,如果偏離這個值,cost 函數就會變大,達到懲罰的效果** # # $$ # \hat{\rho_{i}} = \frac{1}{n} \sum_{j = 1}^{n} h(w_{i}^{T} x_{j} + b_{i}) \\ # \hat{\rho_{i}} : \text{ average output activation value of a neuron i} \\ # n: \text{ total number of training examples} \\ # x_{j}: \text{jth training example} \\ # w_{i}^{T}: \text{ith row of the weight matrix W} \\ # b_{i}: \text{ith entropy of the bias vector} \\ # $$ # # ### Kullback-Leibler divergence (relative entropy) # # $$ # \Omega_{sparsity} = \sum_{i=1}^{D}\rho\log(\frac{\rho}{\hat{\rho_{i}}})+(1-\rho)\log(\frac{1-\rho}{1-\hat{\rho_{i}}}) \\ # \hat{\rho_{i}} : \text{ average output activation value of a neuron i} # $$ # # Kullback-Leibler divergence 是用來計算兩個機率分佈接近的程度,如果兩個一樣的話就為 0.我們可以看以下的例子,設定值 rho_hat 為 0.2,而 rho 等於 0.2 的時候 kl_div = 0,rho 等於其他值時 kl_div 大於 0. # # 而在實例上,就讓 rho 以 average output activation 取代. # # + # %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot = True) rho_hat = np.linspace(0 + 1e-2, 1 - 1e-2, 100) rho = 0.2 kl_div = rho * np.log(rho/rho_hat) + (1 - rho) * np.log((1 - rho) / (1 - rho_hat)) plt.plot(rho_hat, kl_div) plt.xlabel("rho_hat") plt.ylabel("kl_div") # - # ### L2 Regularization # 經過了 Sparsity Regularization 這一項,理想上神經元輸出會接近我們所設定的值.而這裡想要達到的目標就是讓 weight 盡量的變小,讓整個模型變得比較簡單,而不是 weight 變大,使得 bias 要變得很大來修正. # $$ # \Omega_{weights} = \frac{1}{2}\sum_{l}^{L}\sum_{j}^{n}\sum_{i}^{k}(w_{ji}^{(l)})^{2} \\ # L : \text{number of the hidden layers} \\ # n : \text{number of observations} \\ # k : \text{number of variables in training data} # $$ # # ### cost 函數 # # cost 函數就是把這幾項全部加起來,來 minimize 它. # # $$ # E = \Omega_{mse} + \beta * \Omega_{sparsity} + \lambda * \Omega_{weights} # $$ # # 在 tensorflow 裡面有現成的函數 `tf.nn.l2_loss` 可以使用,把單一層的 l2_loss 計算出來,舉個例子,如果有兩層隱層權重 `w1`, `w2`,則要把兩個加總:`tf.nn.l2_loss(w1) + tf.nn.l2_loss(w2)` def weight_variable(shape, name): return tf.Variable(tf.truncated_normal(shape = shape, stddev = 0.1), name) def bias_variable(shape, name): return tf.Variable(tf.zeros(shape = shape), name) def plot_n_reconstruct(origin_img, reconstruct_img, n = 10): plt.figure(figsize=(2 * 10, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(origin_img[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction ax = plt.subplot(2, n, i + 1 + n) plt.imshow(reconstruct_img[i].reshape(28, 28)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() # ## 實作 # 我們會先建立一個一般的 autoencoder,之後再建立一個 sparse autoencoder,並比較它輸出的影像以及 average activation output value. # ### Normal Autoencoder # 建立 784 -> 300 -> 30 -> 300 -> 784 Autoencoder, def build_sae(): W_e_1 = weight_variable([784, 300], "w_e_1") b_e_1 = bias_variable([300], "b_e_1") h_e_1 = tf.nn.sigmoid(tf.add(tf.matmul(x, W_e_1), b_e_1)) W_e_2 = weight_variable([300, 30], "w_e_2") b_e_2 = bias_variable([30], "b_e_2") h_e_2 = tf.nn.sigmoid(tf.add(tf.matmul(h_e_1, W_e_2), b_e_2)) W_d_1 = weight_variable([30, 300], "w_d_1") b_d_1 = bias_variable([300], "b_d_1") h_d_1 = tf.nn.sigmoid(tf.add(tf.matmul(h_e_2, W_d_1), b_d_1)) W_d_2 = weight_variable([300, 784], "w_d_2") b_d_2 = bias_variable([784], "b_d_2") h_d_2 = tf.nn.sigmoid(tf.add(tf.matmul(h_d_1, W_d_2), b_d_2)) return [h_e_1, h_e_2], [W_e_1, W_e_2, W_d_1, W_d_2], h_d_2 # + tf.reset_default_graph() sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape = [None, 784]) h, w, x_reconstruct = build_sae() loss = tf.reduce_mean(tf.pow(x_reconstruct - x, 2)) optimizer = tf.train.AdamOptimizer(0.01).minimize(loss) init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(20000): batch = mnist.train.next_batch(60) if i < 1500: if i%100 == 0: print("step %d, loss %g"%(i, loss.eval(feed_dict={x:batch[0]}))) else: if i%1000 == 0: print("step %d, loss %g"%(i, loss.eval(feed_dict={x:batch[0]}))) optimizer.run(feed_dict={x: batch[0]}) print("final loss %g" % loss.eval(feed_dict={x: mnist.test.images})) # - # #### average output activation value # 印出 encoder 中第一層以及第二層的 `average output activation value` for h_i in h: print("average output activation value %g" % tf.reduce_mean(h_i).eval(feed_dict={x: mnist.test.images})) test_size = 10 test_origin_img = mnist.test.images[0:test_size, :] test_reconstruct_img = x_reconstruct.eval(feed_dict = {x: test_origin_img}) plot_n_reconstruct(test_origin_img, test_reconstruct_img) # ## Sparse Autoencoder # ### KL divergence function # 依照公式建立 kl_div 函數 # + def kl_div(rho, rho_hat): invrho = tf.sub(tf.constant(1.), rho) invrhohat = tf.sub(tf.constant(1.), rho_hat) logrho = tf.add(logfunc(rho,rho_hat), logfunc(invrho, invrhohat)) return logrho def logfunc(x, x2): return tf.mul( x, tf.log(tf.div(x,x2))) # - # ### loss function # 把三個 loss 全部加起來,並乘以對應的係數 # + tf.reset_default_graph() sess = tf.InteractiveSession() x = tf.placeholder(tf.float32, shape = [None, 784]) h, w, x_reconstruct = build_sae() alpha = 5e-6 beta = 7.5e-5 kl_div_loss = reduce(lambda x, y: x + y, map(lambda x: tf.reduce_sum(kl_div(0.02, tf.reduce_mean(x,0))), h)) #kl_div_loss = tf.reduce_sum(kl_div(0.02, tf.reduce_mean(h[0],0))) l2_loss = reduce(lambda x, y: x + y, map(lambda x: tf.nn.l2_loss(x), w)) loss = tf.reduce_mean(tf.pow(x_reconstruct - x, 2)) + alpha * l2_loss + beta * kl_div_loss optimizer = tf.train.AdamOptimizer(0.01).minimize(loss) init_op = tf.global_variables_initializer() sess.run(init_op) for i in range(20000): batch = mnist.train.next_batch(60) if i < 1500: if i%100 == 0: print("step %d, loss %g"%(i, loss.eval(feed_dict={x:batch[0]}))) else: if i%1000 == 0: print("step %d, loss %g"%(i, loss.eval(feed_dict={x:batch[0]}))) optimizer.run(feed_dict={x: batch[0]}) print("final loss %g" % loss.eval(feed_dict={x: mnist.test.images})) # - # #### average output activation value # 印出 encoder 中第一層以及第二層的 `average output activation value` for h_i in h: print("average output activation value %g" % tf.reduce_mean(h_i).eval(feed_dict={x: mnist.test.images})) test_size = 10 test_origin_img = mnist.test.images[0:test_size, :] test_reconstruct_img = x_reconstruct.eval(feed_dict = {x: test_origin_img}) plot_n_reconstruct(test_origin_img, test_reconstruct_img) # 圖片結果可以看到它和普通的 autoencoder 差不多,但是稍微糊了一點,而第一層的 average output activation value 從 0.19 降到了 0.05,第二層的值反而上升了一點點.這個部分的調整跟 hyperparameter 有很大的關係,如果我把 beta 調大,第一第二層的 average output activation value 會接近 0.02,但是輸出的圖像會變模糊.`beta = 7.5e-5` 是我試了幾次以後比較平衡兩者的結果. # # ## 小結 # # 我們實現了 KL Divergence 以及 L2 loss,並把這兩個項加入了 loss,成為了 sparse autoencoder.最後的結果會看到 average output activation value 是有明顯下降的. # # 而整個過程需要花比較多時間的地方是在 hyperparameter 的調整,調太大或者調太小,都會沒辦法達到預期的效果. # # #### 問題 # # * 如果改用 L1 loss 的結果? # * 有沒有更好的方法來決定 hyperparameter? # * 這裡的 activation function 都是 sigmoid,如果用 ReLU? # ## 學習資源連結 # # * [Matlab Autoencoder Doc](https://www.mathworks.com/help/nnet/ref/trainautoencoder.html#buythqy) # * [Sparse Autoencoder in Keras](https://blog.keras.io/building-autoencoders-in-keras.html)
notebooks/6_Sparse_Autoencoder.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import pickle as pkl from fuzzywuzzy import process, fuzz from matplotlib import pyplot as plt import matplotlib import seaborn as sns import re from collections import defaultdict from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve, auc # %matplotlib inline matplotlib.rcParams['font.family'] = 'Arial' with open("../data/pp_1000_models.pkl", 'rb') as picklefile: models = pkl.load(picklefile) with open("../data/pp_1000_models_scores.pkl", 'rb') as picklefile: scores = pkl.load(picklefile) models[1]['l2'].best_estimator_.named_steps['standardscaler'].var_ # + CC = [] l_test = [] l_diff = [] for x in range(100): CC.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].C) l_test.append(scores[x]['l2'][1]) l_diff.append(scores[x]['l2'][1]-scores[x]['l2'][0]) sns.boxplot(CC) # + uni_public = [] acceptance_rate = [] male = [] caucasian = [] african_american = [] latino = [] asian = [] chi_school = [] chi_home = [] financial_aid = [] median_income = [] private_hs = [] chipub_hs = [] for x in range(1000): chipub_hs.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][0]) private_hs.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][1]) uni_public.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][2]) acceptance_rate.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][3]) male.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][4]) caucasian.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][5]) african_american.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][6]) latino.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][7]) asian.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][8]) chi_school.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][9]) chi_home.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][10]) financial_aid.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][11]) median_income.append(models[x]['l2'].best_estimator_.named_steps['logisticregression'].coef_[0][12]) coefficients = pd.DataFrame({'Public University' : uni_public, 'Private University' : np.multiply(-1,uni_public), 'University Acceptance Rate' : acceptance_rate, 'City of Chicago - School' : chi_school, 'Suburban Chicago - School' : np.multiply(-1,chi_school), 'School outside City of Chicago' : np.multiply(-1,chi_school), 'City of Chicago - Home' : chi_home, 'Home outside City of Chicago' : np.multiply(-1,chi_home), 'CYSO Financial Aid' : financial_aid, 'Home Median Income' : median_income, 'Male' : male, 'Female' : np.multiply(-1,male), 'African American' : african_american, 'Caucasian' : caucasian, 'Latinx' : latino, 'Asian' : asian, 'Public HS' : np.multiply(-1,private_hs), 'Private HS' : private_hs, 'Chicago Public School' : chipub_hs, 'Suburban Public School' : np.multiply(-1,chipub_hs) }) coefficients.to_csv('../data/model_coefficients.csv') # + ''' boxplots ''' #sns.set(rc={'figure.figsize':(10,5)}) coefficients_plot = coefficients.mean().values coefficients_std = coefficients.std().values features_plot = coefficients.columns coefficients_inds = coefficients_plot.argsort() sorted_coefficients = coefficients_plot[coefficients_inds[::-1]] sorted_std = coefficients_std[coefficients_inds[::-1]] sorted_features = features_plot[coefficients_inds[::-1]] plot_colors = ['gainsboro','gainsboro','firebrick','firebrick', 'firebrick','firebrick','gainsboro','darkgrey', 'darkgrey','darkgrey','darkgrey','darkgrey', 'firebrick','royalblue'] plt.subplots(figsize=(10,10)) plt.axvline(x=0,c='k',linewidth=0.5) ax = sns.boxplot(data=coefficients, orient = 'h', order = sorted_features, showfliers=False, color='gainsboro')#, #whis=0) plt.axvline(x=0,c='k',linewidth=0.5) #plt.style.use('ggplot') space_string = ' ' ax.set_xlabel(r'$\leftarrow$'+'non-music major'+space_string+'music major'+r'$\rightarrow$',fontsize=18) #ax.set_ylabel('Student Attribute',fontsize=18) plt.title('Educational Attributes',fontsize=18) plt.tick_params(labelsize=15) ax.get_xaxis().set_ticks([]) fig = ax.get_figure() fig.savefig('../plots/allfactors_withwhisker_highlights.pdf',bbox_inches='tight') # + ''' ROC Plot ''' df = pd.read_csv('../data/fitting_data.csv') df.drop(['Unnamed: 0'],axis=1,inplace=True) df = df.fillna(0) y = df.pop('music').values stratification_columns = df.pop('stratification_column').values X = df.values logit_num = 6 #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42,stratify=X[:,9]) datapointers = { 'l1' : 'logistic', 'l2' : 'logistic', 'rf' : 'not_logistic', 'gb' : 'not_logistic', 'linsvc' : 'not logistic', 'rbfsvc' : 'not logistic' } # Initialize figure fig = plt.figure(figsize=(8,8)) plt.title('Receiver Operating Characteristic',fontsize=20) name = 'l2' for x in range(1000): if datapointers[name] == 'logistic': pred = models[x][name].predict_proba(X[:,logit_num:]) else: pred = models[x][name].predict_proba(X) pred = [p[1] for p in pred] fpr, tpr, thresholds = roc_curve(y, pred) # Plot ROC curve plt.plot(fpr, tpr, c='silver',linewidth=1,alpha=0.2) pred = models[52][name].predict_proba(X[:,logit_num:]) pred = [p[1] for p in pred] fpr, tpr, thresholds = roc_curve(y, pred) plt.plot(fpr, tpr, label='model suite', c='silver',linewidth=3) plotnum = 55 pred = models[plotnum][name].predict_proba(X[:,logit_num:]) pred = [p[1] for p in pred] fpr, tpr, thresholds = roc_curve(y, pred) plt.plot(fpr, tpr, label = 'AUC = {:0.2f}'.format(scores[plotnum]['l2'][1]), c='royalblue',linewidth=4) # Diagonal 45 degree line plt.plot([0,1],[0,1],'k--',linewidth=3) plt.legend(loc='lower right',fontsize=16) # Axes limits and labels plt.xlim([-0.1, 1.1]) plt.ylim([-0.1, 1.1]) plt.ylabel('True Positive Rate',fontsize=18) plt.xlabel('False Positive Rate',fontsize=18) plt.tick_params(labelsize=16) plt.grid(True) plt.show() fig.savefig('../plots/ROC_pp.pdf',bbox_inches='tight') fig.savefig('../plots/ROC_pp.png',bbox_inches='tight') # - with open("../data/all_models.pkl", 'rb') as picklefile: models = pkl.load(picklefile) with open("../data/all_models_scores.pkl", 'rb') as picklefile: scores = pkl.load(picklefile) # + ''' ROC Plot - multimodel ''' df = pd.read_csv('../data/fitting_data.csv') df.drop(['Unnamed: 0'],axis=1,inplace=True) df = df.fillna(0) y = df.pop('music').values stratification_columns = df.pop('stratification_column').values X = df.values logit_num = 6 #X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42,stratify=X[:,9]) datapointers = { 'l1' : 'logistic', 'l2' : 'logistic', 'rf' : 'not_logistic', 'gb' : 'not_logistic', 'linsvc' : 'not logistic', 'rbfsvc' : 'not logistic' } long_names = { 'l1' : 'logistic regression - L1 norm', 'l1' : 'logistic regression - L1 norm', 'rf' : 'random forest', 'gb' : 'gradient boost', 'linsvc' : 'SVC - linear kernel', 'rbfsvc' : 'SVC - rbf kernel' } # Initialize figure fig = plt.figure(figsize=(8,8)) plt.title('Receiver Operating Characteristic',fontsize=20) model_names = ['l1','l2','rf','gb','linsvc','rbfsvc'] for name in model_names: if datapointers[name] == 'logistic': pred = models[0][name].predict_proba(X[:,logit_num:]) else: pred = models[0][name].predict_proba(X) pred = [p[1] for p in pred] fpr, tpr, thresholds = roc_curve(y, pred) # Plot ROC curve plt.plot(fpr, tpr,linewidth=3,label=name) # pred = models[52][name].predict_proba(X[:,logit_num:]) # pred = [p[1] for p in pred] # fpr, tpr, thresholds = roc_curve(y, pred) # plt.plot(fpr, tpr, label='model suite', c='silver',linewidth=3) # plotnum = 55 # pred = models[plotnum][name].predict_proba(X[:,logit_num:]) # pred = [p[1] for p in pred] # fpr, tpr, thresholds = roc_curve(y, pred) # plt.plot(fpr, tpr, label = 'AUC = {:0.2f}'.format(scores[plotnum]['l2'][1]), c='royalblue',linewidth=4) # Diagonal 45 degree line plt.plot([0,1],[0,1],'k--',linewidth=3) plt.legend(loc='lower right',fontsize=16) # Axes limits and labels plt.xlim([-0.1, 1.1]) plt.ylim([-0.1, 1.1]) plt.ylabel('True Positive Rate',fontsize=18) plt.xlabel('False Positive Rate',fontsize=18) plt.tick_params(labelsize=16) plt.grid(True) plt.show() fig.savefig('../plots/ROC_all.pdf',bbox_inches='tight') fig.savefig('../plots/ROC_all.png',bbox_inches='tight') # + long_names = { 'l1' : 'logistic regression - L1 norm', 'l1' : 'logistic regression - L1 norm', 'rf' : 'random forest', 'gb' : 'gradient boost', 'linsvc' : 'SVC - linear kernel', 'rbfsvc' : 'SVC - rbf kernel' } model_names = ['l1','l2','rf','gb','linsvc','rbfsvc'] l_train = [] l_test = [] for names in model_names: l_train.append(scores[0][names][0]) l_test.append(scores[0][names][1]) df = pd.DataFrame(scores[0]) df['type']=['train','test'] df = pd.melt(df, id_vars="type", var_name="model", value_name="ROC-AUC score") #sns.set(font_scale=1.3) ax = sns.catplot(x='model', y='ROC-AUC score', hue='type', data=df, kind='bar') ax.set(ylim=(0.5, 1.0)) ax.set(title='CV scores') #fig = ax.get_figure() ax.savefig('../plots/multimodel_scores.pdf',bbox_inches='tight') # - df df df
workbooks/.ipynb_checkpoints/plot_data-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/rezapci/ML-facial-recognition/blob/master/05_14_Image_Features.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="9Zc4EDbV4vjs" colab_type="text" # <!--BOOK_INFORMATION--> # <img align="left" style="padding-right:10px;" src="https://github.com/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/figures/PDSH-cover-small.png?raw=1"> # # *This notebook contains an excerpt from the [Python Data Science Handbook](http://shop.oreilly.com/product/0636920034919.do) by <NAME>; the content is available [on GitHub](https://github.com/jakevdp/PythonDataScienceHandbook).* # # *The text is released under the [CC-BY-NC-ND license](https://creativecommons.org/licenses/by-nc-nd/3.0/us/legalcode), and code is released under the [MIT license](https://opensource.org/licenses/MIT). If you find this content useful, please consider supporting the work by [buying the book](http://shop.oreilly.com/product/0636920034919.do)!* # + [markdown] id="SpMsmOR94vjt" colab_type="text" # <!--NAVIGATION--> # < [In-Depth: Kernel Density Estimation](05.13-Kernel-Density-Estimation.ipynb) | [Contents](Index.ipynb) | [Further Machine Learning Resources](05.15-Learning-More.ipynb) > # # <a href="https://colab.research.google.com/drive/1Xd3qrj_eRIhHd38vZzM4wSy62dTpj1Bi"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a> # # + [markdown] id="JSQVXPNM4vju" colab_type="text" # # Application: A Face Detection Pipeline # + [markdown] id="XAAcV4BB4vjv" colab_type="text" # This chapter has explored a number of the central concepts and algorithms of machine learning. # But moving from these concepts to real-world application can be a challenge. # Real-world datasets are noisy and heterogeneous, may have missing features, and data may be in a form that is difficult to map to a clean ``[n_samples, n_features]`` matrix. # Before applying any of the methods discussed here, you must first extract these features from your data: there is no formula for how to do this that applies across all domains, and thus this is where you as a data scientist must exercise your own intuition and expertise. # # One interesting and compelling application of machine learning is to images, and we have already seen a few examples of this where pixel-level features are used for classification. # In the real world, data is rarely so uniform and simple pixels will not be suitable: this has led to a large literature on *feature extraction* methods for image data (see [Feature Engineering](05.04-Feature-Engineering.ipynb)). # # In this section, we will take a look at one such feature extraction technique, the [Histogram of Oriented Gradients](https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients) (HOG), which transforms image pixels into a vector representation that is sensitive to broadly informative image features regardless of confounding factors like illumination. # We will use these features to develop a simple face detection pipeline, using machine learning algorithms and concepts we've seen throughout this chapter. # # We begin with the standard imports: # + id="riGDbxFq4vjv" colab_type="code" colab={} # %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns; sns.set() import numpy as np # + [markdown] id="dOKSs_sa4vjy" colab_type="text" # ## HOG Features # # The Histogram of Gradients is a straightforward feature extraction procedure that was developed in the context of identifying pedestrians within images. # HOG involves the following steps: # # 1. Optionally pre-normalize images. This leads to features that resist dependence on variations in illumination. # 2. Convolve the image with two filters that are sensitive to horizontal and vertical brightness gradients. These capture edge, contour, and texture information. # 3. Subdivide the image into cells of a predetermined size, and compute a histogram of the gradient orientations within each cell. # 4. Normalize the histograms in each cell by comparing to the block of neighboring cells. This further suppresses the effect of illumination across the image. # 5. Construct a one-dimensional feature vector from the information in each cell. # # A fast HOG extractor is built into the Scikit-Image project, and we can try it out relatively quickly and visualize the oriented gradients within each cell: # + id="OGfSD6yQ4vjy" colab_type="code" outputId="88ac0181-2778-4dff-c1f0-7a46e4fb4553" colab={"base_uri": "https://localhost:8080/", "height": 310} from skimage import data, color, feature import skimage.data image = color.rgb2gray(data.chelsea()) hog_vec, hog_vis = feature.hog(image, visualise=True) fig, ax = plt.subplots(1, 2, figsize=(12, 6), subplot_kw=dict(xticks=[], yticks=[])) ax[0].imshow(image, cmap='gray') ax[0].set_title('input image') ax[1].imshow(hog_vis) ax[1].set_title('visualization of HOG features'); # + [markdown] id="CcVsrGgf4vj1" colab_type="text" # ## HOG in Action: A Simple Face Detector # # Using these HOG features, we can build up a simple facial detection algorithm with any Scikit-Learn estimator; here we will use a linear support vector machine (refer back to [In-Depth: Support Vector Machines](05.07-Support-Vector-Machines.ipynb) if you need a refresher on this). # The steps are as follows: # # 1. Obtain a set of image thumbnails of faces to constitute "positive" training samples. # 2. Obtain a set of image thumbnails of non-faces to constitute "negative" training samples. # 3. Extract HOG features from these training samples. # 4. Train a linear SVM classifier on these samples. # 5. For an "unknown" image, pass a sliding window across the image, using the model to evaluate whether that window contains a face or not. # 6. If detections overlap, combine them into a single window. # # Let's go through these steps and try it out: # + [markdown] id="l7Z9mbnB4vj2" colab_type="text" # ### 1. Obtain a set of positive training samples # # Let's start by finding some positive training samples that show a variety of faces. # We have one easy set of data to work with—the Labeled Faces in the Wild dataset, which can be downloaded by Scikit-Learn: # + id="ScUV3Def4vj3" colab_type="code" outputId="68996203-6aef-4c5f-8c7c-4dab80b9f889" colab={"base_uri": "https://localhost:8080/", "height": 104} from sklearn.datasets import fetch_lfw_people faces = fetch_lfw_people() positive_patches = faces.images positive_patches.shape # + [markdown] id="aELspjmB4vj5" colab_type="text" # This gives us a sample of 13,000 face images to use for training. # + [markdown] id="czG1eqM24vj6" colab_type="text" # ### 2. Obtain a set of negative training samples # # Next we need a set of similarly sized thumbnails which *do not* have a face in them. # One way to do this is to take any corpus of input images, and extract thumbnails from them at a variety of scales. # Here we can use some of the images shipped with Scikit-Image, along with Scikit-Learn's ``PatchExtractor``: # + id="eAcQgDzR4vj6" colab_type="code" colab={} from skimage import data, transform imgs_to_use = ['camera', 'text', 'coins', 'moon', 'page', 'clock', 'immunohistochemistry', 'chelsea', 'coffee', 'hubble_deep_field'] images = [color.rgb2gray(getattr(data, name)()) for name in imgs_to_use] # + id="4cPzNu8w4vj8" colab_type="code" outputId="bf4ef7d8-9b6a-4618-f693-73ab6cc0ae16" colab={"base_uri": "https://localhost:8080/", "height": 35} from sklearn.feature_extraction.image import PatchExtractor def extract_patches(img, N, scale=1.0, patch_size=positive_patches[0].shape): extracted_patch_size = tuple((scale * np.array(patch_size)).astype(int)) extractor = PatchExtractor(patch_size=extracted_patch_size, max_patches=N, random_state=0) patches = extractor.transform(img[np.newaxis]) if scale != 1: patches = np.array([transform.resize(patch, patch_size) for patch in patches]) return patches negative_patches = np.vstack([extract_patches(im, 1000, scale) for im in images for scale in [0.5, 1.0, 2.0]]) negative_patches.shape # + [markdown] id="B06SNWso4vj-" colab_type="text" # We now have 30,000 suitable image patches which do not contain faces. # Let's take a look at a few of them to get an idea of what they look like: # + id="qQoZKk504vj-" colab_type="code" outputId="ef7c1290-baf9-4414-ac07-171edd58b39c" colab={"base_uri": "https://localhost:8080/", "height": 272} fig, ax = plt.subplots(6, 10) for i, axi in enumerate(ax.flat): axi.imshow(negative_patches[500 * i], cmap='gray') axi.axis('off') # + [markdown] id="INe2e6vq4vkA" colab_type="text" # Our hope is that these would sufficiently cover the space of "non-faces" that our algorithm is likely to see. # + [markdown] id="0QmeHyKN4vkB" colab_type="text" # ### 3. Combine sets and extract HOG features # # Now that we have these positive samples and negative samples, we can combine them and compute HOG features. # This step takes a little while, because the HOG features involve a nontrivial computation for each image: # + id="FRtY3NJ74vkD" colab_type="code" colab={} from itertools import chain X_train = np.array([feature.hog(im) for im in chain(positive_patches, negative_patches)]) y_train = np.zeros(X_train.shape[0]) y_train[:positive_patches.shape[0]] = 1 # + id="Unlrn9bu4vkF" colab_type="code" outputId="4b6278c7-7a20-42d1-9027-0bfd87f89543" colab={"base_uri": "https://localhost:8080/", "height": 35} X_train.shape # + [markdown] id="H5Bo4Tb24vkG" colab_type="text" # We are left with 43,000 training samples in 1,215 dimensions, and we now have our data in a form that we can feed into Scikit-Learn! # + [markdown] id="Papq209m4vkH" colab_type="text" # ### 4. Training a support vector machine # # Next we use the tools we have been exploring in this chapter to create a classifier of thumbnail patches. # For such a high-dimensional binary classification task, a Linear support vector machine is a good choice. # We will use Scikit-Learn's ``LinearSVC``, because in comparison to ``SVC`` it often has better scaling for large number of samples. # # First, though, let's use a simple Gaussian naive Bayes to get a quick baseline: # + id="dWfPfMmM4vkH" colab_type="code" outputId="a6d3ff6c-fce0-4f59-beef-ee4ae0b9b911" colab={"base_uri": "https://localhost:8080/", "height": 89} from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split cross_val_score(GaussianNB(), X_train, y_train) # + [markdown] id="_wmBoIRm4vkK" colab_type="text" # We see that on our training data, even a simple naive Bayes algorithm gets us upwards of 90% accuracy. # Let's try the support vector machine, with a grid search over a few choices of the C parameter: # + id="NloorzlP4vkL" colab_type="code" outputId="632e5dd3-d48c-478d-cf42-f6600b242f05" colab={"base_uri": "https://localhost:8080/", "height": 297} from sklearn.svm import LinearSVC from sklearn.model_selection import learning_curve, GridSearchCV grid = GridSearchCV(LinearSVC(), {'C': [1.0, 2.0, 4.0, 8.0]}) grid.fit(X_train, y_train) grid.best_score_ # + id="O2MxpZOZ4vkN" colab_type="code" outputId="37f47fce-e2c5-4671-8149-92982549f91b" colab={"base_uri": "https://localhost:8080/", "height": 35} grid.best_params_ # + [markdown] id="2ifQlsB54vkP" colab_type="text" # Let's take the best estimator and re-train it on the full dataset: # + id="m5Q8nITW4vkP" colab_type="code" outputId="fdb0451c-0125-40a1-bf7b-dbecc18826e8" colab={"base_uri": "https://localhost:8080/", "height": 87} model = grid.best_estimator_ model.fit(X_train, y_train) # + [markdown] id="Bzy7_No44vkR" colab_type="text" # ### 5. Find faces in a new image # # Now that we have this model in place, let's grab a new image and see how the model does. # We will use one portion of the astronaut image for simplicity (see discussion of this in [Caveats and Improvements](#Caveats-and-Improvements)), and run a sliding window over it and evaluate each patch: # + id="STGHquxf4vkS" colab_type="code" outputId="aef421c3-2608-40cf-fa21-33dfb0625def" colab={"base_uri": "https://localhost:8080/", "height": 326} test_image = skimage.data.astronaut() test_image = skimage.color.rgb2gray(test_image) test_image = skimage.transform.rescale(test_image, 0.5) test_image = test_image[:160, 40:180] plt.imshow(test_image, cmap='gray') plt.axis('off'); # + [markdown] id="ODF2Y0ST4vkU" colab_type="text" # Next, let's create a window that iterates over patches of this image, and compute HOG features for each patch: # + id="xSC2RQop4vkU" colab_type="code" outputId="f78f82a1-45ac-4433-f305-cc71cefd0f45" colab={"base_uri": "https://localhost:8080/", "height": 35} def sliding_window(img, patch_size=positive_patches[0].shape, istep=2, jstep=2, scale=1.0): Ni, Nj = (int(scale * s) for s in patch_size) for i in range(0, img.shape[0] - Ni, istep): for j in range(0, img.shape[1] - Ni, jstep): patch = img[i:i + Ni, j:j + Nj] if scale != 1: patch = transform.resize(patch, patch_size) yield (i, j), patch indices, patches = zip(*sliding_window(test_image)) patches_hog = np.array([feature.hog(patch) for patch in patches]) patches_hog.shape # + [markdown] id="Wyw36MMf4vkX" colab_type="text" # Finally, we can take these HOG-featured patches and use our model to evaluate whether each patch contains a face: # + id="XweaTm994vka" colab_type="code" outputId="7c4ae0a7-f215-407c-d2a9-6fa9f44fb72d" colab={"base_uri": "https://localhost:8080/", "height": 35} labels = model.predict(patches_hog) labels.sum() # + [markdown] id="DXnD-qXq4vkf" colab_type="text" # We see that out of nearly 2,000 patches, we have found 30 detections. # Let's use the information we have about these patches to show where they lie on our test image, drawing them as rectangles: # + id="NBtRNat84vkg" colab_type="code" outputId="2f763e8e-75a8-4345-b75f-7374f3474799" colab={"base_uri": "https://localhost:8080/", "height": 271} fig, ax = plt.subplots() ax.imshow(test_image, cmap='gray') ax.axis('off') Ni, Nj = positive_patches[0].shape indices = np.array(indices) for i, j in indices[labels == 1]: ax.add_patch(plt.Rectangle((j, i), Nj, Ni, edgecolor='red', alpha=0.3, lw=2, facecolor='none')) # + [markdown] id="HnVUI_TX4vki" colab_type="text" # All of the detected patches overlap and found the face in the image! # Not bad for a few lines of Python. # + [markdown] id="IQbqoKgh4vki" colab_type="text" # ## Caveats and Improvements # # If you dig a bit deeper into the preceding code and examples, you'll see that we still have a bit of work before we can claim a production-ready face detector. # There are several issues with what we've done, and several improvements that could be made. In particular: # # ### Our training set, especially for negative features, is not very complete # # The central issue is that there are many face-like textures that are not in the training set, and so our current model is very prone to false positives. # You can see this if you try out the above algorithm on the *full* astronaut image: the current model leads to many false detections in other regions of the image. # # We might imagine addressing this by adding a wider variety of images to the negative training set, and this would probably yield some improvement. # Another way to address this is to use a more directed approach, such as *hard negative mining*. # In hard negative mining, we take a new set of images that our classifier has not seen, find all the patches representing false positives, and explicitly add them as negative instances in the training set before re-training the classifier. # # ### Our current pipeline searches only at one scale # # As currently written, our algorithm will miss faces that are not approximately 62×47 pixels. # This can be straightforwardly addressed by using sliding windows of a variety of sizes, and re-sizing each patch using ``skimage.transform.resize`` before feeding it into the model. # In fact, the ``sliding_window()`` utility used here is already built with this in mind. # # ### We should combine overlapped detection patches # # For a production-ready pipeline, we would prefer not to have 30 detections of the same face, but to somehow reduce overlapping groups of detections down to a single detection. # This could be done via an unsupervised clustering approach (MeanShift Clustering is one good candidate for this), or via a procedural approach such as *non-maximum suppression*, an algorithm common in machine vision. # # ### The pipeline should be streamlined # # Once we address these issues, it would also be nice to create a more streamlined pipeline for ingesting training images and predicting sliding-window outputs. # This is where Python as a data science tool really shines: with a bit of work, we could take our prototype code and package it with a well-designed object-oriented API that give the user the ability to use this easily. # I will leave this as a proverbial "exercise for the reader". # # ### More recent advances: Deep Learning # # Finally, I should add that HOG and other procedural feature extraction methods for images are no longer state-of-the-art techniques. # Instead, many modern object detection pipelines use variants of deep neural networks: one way to think of neural networks is that they are an estimator which determines optimal feature extraction strategies from the data, rather than relying on the intuition of the user. # An intro to these deep neural net methods is conceptually (and computationally!) beyond the scope of this section, although open tools like Google's [TensorFlow](https://www.tensorflow.org/) have recently made deep learning approaches much more accessible than they once were. # As of the writing of this book, deep learning in Python is still relatively young, and so I can't yet point to any definitive resource. # That said, the list of references in the following section should provide a useful place to start! # + [markdown] id="9IftdvJL4vkj" colab_type="text" # <!--NAVIGATION--> # < [In-Depth: Kernel Density Estimation](05.13-Kernel-Density-Estimation.ipynb) | [Contents](Index.ipynb) | [Further Machine Learning Resources](05.15-Learning-More.ipynb) > # # <a href="https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/05.14-Image-Features.ipynb"><img align="left" src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab" title="Open and Execute in Google Colaboratory"></a> #
05_14_Image_Features.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/ShinAsakawa/2019seminar_info/blob/master/notebooks/2019si_activaton_functions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="MRbRgeWlpnVG" colab_type="text" # <center> # <h1>[Python で 超実習ディープラーニング](https://www.seminar-info.jp/entry/seminars/view/1/4174)</h1> # <h3><strong>実践! 強化学習・画像認識・自然言語処理・ロボティクス</strong></h3> # </center> # # <center> # ![](https://www.seminar-info.jp/entry/img/logo_ov.jpg) # </center> # # <div align='right'> # <a href='mailto:<EMAIL>'><NAME></a>, all rights reserved.<br> # Date: 15/Mar/2019<br> # MIT license # </div> # + id="HAKBgu4xu4Pw" colab_type="code" colab={} import numpy as np import matplotlib.pyplot as plt # %matplotlib inline ## [Original](https://github.com/alrojo/tensorflow-tutorial/blob/master/lab1_FFN/lab1_FFN.ipynb) # PLOT OF DIFFERENT OUTPUT USNITS x = np.linspace(-6, 6, 100) relu = lambda x: np.maximum(0, x) leaky_relu = lambda x: np.maximum(0, x) + 0.1*np.minimum(0, x) elu = lambda x: (x > 0)*x + (1 - (x > 0))*(np.exp(x) - 1) sigmoid = lambda x: (1+np.exp(-x))**(-1) def softmax(w, t = 1.0): e = np.exp(w) dist = e / np.sum(e) return dist x_softmax = softmax(x) plt.figure(figsize=(6,6)) plt.plot(x, relu(x), label='ReLU', lw=2) plt.plot(x, leaky_relu(x), label='Leaky ReLU',lw=2) plt.plot(x, elu(x), label='Elu', lw=2) plt.plot(x, sigmoid(x), label='Sigmoid',lw=2) plt.plot(x, np.tanh(x), label='tanh', lw=2) # added by Asakawa plt.legend(loc=2, fontsize=16) plt.title('Non-linearities', fontsize=20) plt.ylim([-2, 5]) plt.xlim([-6, 6]) # softmax # assert that all class probablities sum to one print(np.sum(x_softmax)) assert abs(1.0 - x_softmax.sum()) < 1e-8 # + id="J4L47MM5u9Xb" colab_type="code" colab={}
notebooks/2019si_activaton_functions.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + jupyter={"source_hidden": true} import itertools import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from gs_quant.instrument import FXBinary, FXMultiCrossBinary, FXMultiCrossBinaryLeg from gs_quant.markets import PricingContext from gs_quant.risk import FXSpot from gs_quant.session import GsSession # + jupyter={"source_hidden": true} pycharm={"name": "#%%\n"} GsSession.use(client_id=None, client_secret=None, scopes=('run_analytics')) # - # In this notebook, we will screen for attractive dual binaries in FX to express a leveraged view on a potential vaccine led COVID recovery. This is an example of the GS Quant functionalities and it is not a recommendation of a trade in the instruments discussed, please follow up with your salesperson to discuss specific implementations # ## 1 - Define a few functions and inputs # # Let's start by defining a few functions and inputs to improve the readability of the notebook. # # First, let's define a tenor and our targets for various FX crosses. In this example, we are leveraging GS GIR's work for analyzing FX price targets in the event of an approved EUA of a COVID vaccine by the end of the year ([source](https://marquee.gs.com/content/research/en/reports/2020/11/08/e8589bbb-cc23-4480-859a-000a8014bd1d.html)). However, the framework we build in this notebook could be deployed to your own targets on vaccine developments (or any other relevant themes). # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} # note that we are representing FX crosses as strings in mathematical notation (e.g. USD per GBP) targets = { 'USD/GBP': (1.34, 'call'), 'USD/AUD': (0.75, 'call'), 'USD/EUR': (1.20, 'call'), 'CAD/USD': (1.28, 'put'), 'JPY/USD': (104.1, 'call'), 'KRW/USD': (1099, 'put'), 'BRL/USD': (5.26, 'put'), 'MXN/USD': (19.87, 'put') } tenor = '2m' crosses = targets.keys() # - # Next, we'll define a few utility functions we'll use throughout the notebook. # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} def build_binary(tenor, cross, strike, opt_type, size=10e6, denominated='USD', buy_sell='Buy'): ''' utility method to construct a FXBinaryBuilder ''' return FXBinary( buy_sell=buy_sell, expiration_date=tenor, option_type=opt_type, notional_currency=denominated, pair=cross, strike_price=strike, premium=0, notional_amount=size, payment_date=tenor ) def build_dual_binary(tenor, legs, size=10e6, denominated='USD', buy_sell='Buy'): ''' utility method to construct an MCB builder ''' built_legs = [] for leg in legs: built_legs.append(FXMultiCrossBinaryLeg( strike_price=leg['strike'], pair=leg['cross'], option_type='Binary %s' % leg['opt_type'] )) return FXMultiCrossBinary(buy_sell, tenor, legs=tuple(built_legs), premium=0, notional_amount=size, notional_currency=denominated) def plot_heatmap(data, cmap, ylabel, xlabel, title): ''' Utility function to build a heatmap ''' plt.subplots(figsize=(16, 10)) vmax = data.max().max() vmin = data.min().min() ax = sns.heatmap(data, annot=True, vmin=vmin, vmax=vmax, fmt='.2f', cmap=cmap) ax.set(ylabel=ylabel, xlabel=xlabel, title=title) ax.xaxis.tick_top() ax.xaxis.set_label_position('top') def corr(mcb_price, p1, p2): ''' compute the correlation implied by the dual binary price and individuals the sign is just the correlation between the payouts (so negative always indicates higher savings regardless of call/put combo) ''' return (mcb_price - p1 * p2) / np.sqrt(p1 * (1 - p1) * p2 * (1 - p2)) # - # ## 2 - Vanilla Binaries # # First, a quick example that shows how to compute the percent price of a binary: binary = build_binary('2m', 'JPY/USD', 104, 'Put') binary.price() / 10e6 # Let's calculate the vanilla binary prices for each of our individual targets to get a sense of the probability the market is assigning to these targets. # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} vanilla_binaries = pd.DataFrame(index=crosses, columns=['spot_ref', 'target', 'price', 'price_future', 'risk_future']) with PricingContext(is_batch=True): for cross, (strike, opt_type) in targets.items(): binary = build_binary(tenor, cross, strike, opt_type) vanilla_binaries.loc[cross, 'price_future'] = binary.price() vanilla_binaries.loc[cross, 'risk_future'] = binary.calc(FXSpot) vanilla_binaries.loc[cross, 'target'] = strike # + # once all results are computed summarize relevant details for cross in crosses: vanilla_binaries.loc[cross, 'price'] = vanilla_binaries.loc[cross, 'price_future'].result() / 10e6 vanilla_binaries.loc[cross, 'spot_ref'] = vanilla_binaries.loc[cross, 'risk_future'].result() vanilla_binaries[['spot_ref', 'target', 'price']].sort_values('price') # + [markdown] pycharm={"name": "#%% md\n"} # ## 3 - Dual Binaries # # Now calculate the price for ever combination of dual binaries struck at the targets defined above. The top row displays the cheapest dual binary by price, with the right column indicating the savings to the cheapest digi. Darker colors indicate potentially higher savings and therefore potentially more attractive dual digis. # # Please note that the payout of dual binaries is not guaranteed and is dependent on the level of FX spot in both crosses at the time of expiry. # - dual_binary_dict = [] with PricingContext(is_batch=True): # iterate over all 2-cross combinations for idx, (cross1, cross2) in enumerate(itertools.combinations(crosses, 2)): # build the dual binary legs = [ {'cross': cross1, 'strike': targets[cross1][0], 'opt_type': targets[cross1][1]}, {'cross': cross2, 'strike': targets[cross2][0], 'opt_type': targets[cross2][1]} ] mcb = build_dual_binary(tenor, legs) dual_binary_dict.append({ 'cross1': cross1, 'cross2': cross2, 'price_future': mcb.price(), }) # + for row in dual_binary_dict: row['price'] = row['price_future'].result() / 10e6 # individual prices row['individual_1'] = vanilla_binaries.loc[row['cross1'], 'price'] row['individual_2'] = vanilla_binaries.loc[row['cross2'], 'price'] row['corr'] = corr(row['price'], row['individual_1'], row['individual_2']) # define savings as the % savings from the cheapest individual binary row['savings'] = 1 - row['price'] / min(row['individual_1'], row['individual_2']) dual_binaries = pd.DataFrame(dual_binary_dict)[['cross1', 'cross2', 'price', 'savings', 'corr', 'individual_1', 'individual_2']] # - # Format the results, showing only the 10 dual binaries with the absolute cheapest mid prices # + display_table = dual_binaries.sort_values('price').head(10) display_table['price'] = pd.Series(['{0:.1f}%'.format(val * 100) for val in display_table['price']], index=display_table.index) display_table['savings'] = pd.Series([int(val * 100) for val in display_table['savings']], index=display_table.index) display_table['corr'] = pd.Series(['{0:.1f}%'.format(val * 100) for val in display_table['corr']], index=display_table.index) display_table['individual_1'] = pd.Series(['{0:.1f}%'.format(val * 100) for val in display_table['individual_1']], index=display_table.index) display_table['individual_2'] = pd.Series(['{0:.1f}%'.format(val * 100) for val in display_table['individual_2']], index=display_table.index) display_table.style.background_gradient(subset=['savings']) # - # ## 4 - Dual Binary Grids # + [markdown] pycharm={"name": "#%% md\n"} # We will now consider a wider range of strikes for the cheapest dual binary in # the table above. Let us consider strikes within a 3% range from the targets # defined above. The tables below show both the mid price and the implied correlation. Optimizing both of these outputs allows us to determine # our preferable strikes for the trade. # + jupyter={"outputs_hidden": false} pycharm={"name": "#%%\n"} min_price_index = dual_binaries['price'].idxmin() cross1 = dual_binaries.iloc[min_price_index]['cross1'] cross2 = dual_binaries.iloc[min_price_index]['cross2'] # % from target strikes to compute for the grid strikes = [-3, -2.5, -2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3] mcb_ppct_future = pd.DataFrame(index=strikes, columns=strikes) indiv_ppct_future = pd.DataFrame(index=strikes, columns=[cross1, cross2]) with PricingContext(is_batch=True): # loop over all dual binary combinations for (i, j) in itertools.product(strikes, strikes): strike1 = targets[cross1][0] * (1 + i / 100) strike2 = targets[cross2][0] * (1 + j / 100) # build the dual binary legs = [ {'cross': cross1, 'strike': strike1, 'opt_type': targets[cross1][1]}, {'cross': cross2, 'strike': strike2, 'opt_type': targets[cross2][1]} ] mcb = build_dual_binary(tenor, legs) mcb_ppct_future.loc[i, j] = mcb.price() # loop over all indvidual binary combinations for both crosses # we'll use these to compute savings later as well for cross in [cross1, cross2]: for i in strikes: strike = targets[cross][0] * (1 + i / 100) binary = build_binary(tenor, cross, strike, targets[cross][1]) indiv_ppct_future.loc[i, cross] = binary.price() # + price_matrix = pd.DataFrame(index=strikes, columns=strikes, dtype='float64') savings_matrix = pd.DataFrame(index=strikes, columns=strikes, dtype='float64') corr_matrix = pd.DataFrame(index=strikes, columns=strikes, dtype='float64') for (i, j) in itertools.product(strikes, strikes): # price pct of the mcb price_pct = mcb_ppct_future.loc[i, j].result() / 10e6 price_matrix.loc[i, j] = price_pct * 100 # calc savings p_1 = indiv_ppct_future.loc[i, cross1].result() / 10e6 p_2 = indiv_ppct_future.loc[j, cross2].result() / 10e6 savings_matrix.loc[i, j] = 1 - (price_pct / min(p_1, p_2)) # calc correlation corr_matrix.loc[i, j] = 100 * corr(price_pct, p_1, p_2) # - # Quickly sanity check the percent prices of the individual binaries at the different strike combinations: round(indiv_ppct_future.applymap(lambda x: x.result() / 10e6) * 100, 1) # First, let's plot the mid price of the dual binary for all of the strike combinations: # + jupyter={"source_hidden": true} pycharm={"name": "#%%\n"} plot_heatmap(price_matrix, "coolwarm", cross2 + " " + targets[cross2][1], cross1 + " " + targets[cross1][1], "MCB Price (%) By Strikes") # - # Then, let's plot the savings vs. the cheapest inividual binary for all of the combinations on the grid. Negative numbers indicate correlations that provide more savings. # + jupyter={"source_hidden": true} plot_heatmap(savings_matrix, "Blues", cross2 + " " + targets[cross2][1], cross1 + " " + targets[cross1][1], "Savings (%) By Strikes" ) # - # ## Appendix - Dual Binary Carry with PricingContext(is_batch=True): for row in dual_binary_dict: # build the dual binary legs = [ {'cross': row['cross1'], 'strike': targets[row['cross1']][0], 'opt_type': targets[row['cross1']][1]}, {'cross': row['cross2'], 'strike': targets[row['cross2']][0], 'opt_type': targets[row['cross2']][1]} ] mcb = build_dual_binary('1m', legs) # simple static carry, just reduce tenor to 1m row['price_fwd_future'] = mcb.price() # + for row in dual_binary_dict: row['price_fwd'] = row['price_fwd_future'].result() / 10e6 row['static_carry_1m'] = row['price_fwd'] - row['price'] carry_table = pd.DataFrame(dual_binary_dict).sort_values('static_carry_1m', ascending=False) carry_table.head(10)[['cross1', 'cross2', 'price', 'savings', 'static_carry_1m']] # - # ### Disclaimers # # Indicative Terms/Pricing Levels: This material may contain indicative terms only, including but not limited to pricing levels. There is no representation that any transaction can or could have been effected at such terms or prices. Proposed terms and conditions are for discussion purposes only. Finalized terms and conditions are subject to further discussion and negotiation. # www.goldmansachs.com/disclaimer/sales-and-trading-invest-rec-disclosures.html If you are not accessing this material via Marquee ContentStream, a list of the author's investment recommendations disseminated during the preceding 12 months and the proportion of the author's recommendations that are 'buy', 'hold', 'sell' or other over the previous 12 months is available by logging into Marquee ContentStream using the link below. Alternatively, if you do not have access to Marquee ContentStream, please contact your usual GS representative who will be able to provide this information to you. # Backtesting, Simulated Results, Sensitivity/Scenario Analysis or Spreadsheet Calculator or Model: There may be data presented herein that is solely for illustrative purposes and which may include among other things back testing, simulated results and scenario analyses. The information is based upon certain factors, assumptions and historical information that Goldman Sachs may in its discretion have considered appropriate, however, Goldman Sachs provides no assurance or guarantee that this product will operate or would have operated in the past in a manner consistent with these assumptions. In the event any of the assumptions used do not prove to be true, results are likely to vary materially from the examples shown herein. Additionally, the results may not reflect material economic and market factors, such as liquidity, transaction costs and other expenses which could reduce potential return. # OTC Derivatives Risk Disclosures: # Terms of the Transaction: To understand clearly the terms and conditions of any OTC derivative transaction you may enter into, you should carefully review the Master Agreement, including any related schedules, credit support documents, addenda and exhibits. You should not enter into OTC derivative transactions unless you understand the terms of the transaction you are entering into as well as the nature and extent of your risk exposure. You should also be satisfied that the OTC derivative transaction is appropriate for you in light of your circumstances and financial condition. You may be requested to post margin or collateral to support written OTC derivatives at levels consistent with the internal policies of Goldman Sachs. # # Liquidity Risk: There is no public market for OTC derivative transactions and, therefore, it may be difficult or impossible to liquidate an existing position on favorable terms. Transfer Restrictions: OTC derivative transactions entered into with one or more affiliates of The Goldman Sachs Group, Inc. (Goldman Sachs) cannot be assigned or otherwise transferred without its prior written consent and, therefore, it may be impossible for you to transfer any OTC derivative transaction to a third party. # # Conflict of Interests: Goldman Sachs may from time to time be an active participant on both sides of the market for the underlying securities, commodities, futures, options or any other derivative or instrument identical or related to those mentioned herein (together, "the Product"). Goldman Sachs at any time may have long or short positions in, or buy and sell Products (on a principal basis or otherwise) identical or related to those mentioned herein. Goldman Sachs hedging and trading activities may affect the value of the Products. # # Counterparty Credit Risk: Because Goldman Sachs, may be obligated to make substantial payments to you as a condition of an OTC derivative transaction, you must evaluate the credit risk of doing business with Goldman Sachs or its affiliates. # # Pricing and Valuation: The price of each OTC derivative transaction is individually negotiated between Goldman Sachs and each counterparty and Goldman Sachs does not represent or warrant that the prices for which it offers OTC derivative transactions are the best prices available, possibly making it difficult for you to establish what is a fair price for a particular OTC derivative transaction; The value or quoted price of the Product at any time, however, will reflect many factors and cannot be predicted. If Goldman Sachs makes a market in the offered Product, the price quoted by Goldman Sachs would reflect any changes in market conditions and other relevant factors, and the quoted price (and the value of the Product that Goldman Sachs will use for account statements or otherwise) could be higher or lower than the original price, and may be higher or lower than the value of the Product as determined by reference to pricing models used by Goldman Sachs. If at any time a third party dealer quotes a price to purchase the Product or otherwise values the Product, that price may be significantly different (higher or lower) than any price quoted by Goldman Sachs. Furthermore, if you sell the Product, you will likely be charged a commission for secondary market transactions, or the price will likely reflect a dealer discount. Goldman Sachs may conduct market making activities in the Product. To the extent Goldman Sachs makes a market, any price quoted for the OTC derivative transactions, Goldman Sachs may differ significantly from (i) their value determined by reference to Goldman Sachs pricing models and (ii) any price quoted by a third party. The market price of the OTC derivative transaction may be influenced by many unpredictable factors, including economic conditions, the creditworthiness of Goldman Sachs, the value of any underlyers, and certain actions taken by Goldman Sachs. # # Market Making, Investing and Lending: Goldman Sachs engages in market making, investing and lending businesses for its own account and the accounts of its affiliates in the same or similar instruments underlying OTC derivative transactions (including such trading as Goldman Sachs deems appropriate in its sole discretion to hedge its market risk in any OTC derivative transaction whether between Goldman Sachs and you or with third parties) and such trading may affect the value of an OTC derivative transaction. # # Early Termination Payments: The provisions of an OTC Derivative Transaction may allow for early termination and, in such cases, either you or Goldman Sachs may be required to make a potentially significant termination payment depending upon whether the OTC Derivative Transaction is in-the-money to Goldman Sachs or you at the time of termination. Indexes: Goldman Sachs does not warrant, and takes no responsibility for, the structure, method of computation or publication of any currency exchange rates, interest rates, indexes of such rates, or credit, equity or other indexes, unless Goldman Sachs specifically advises you otherwise. # Risk Disclosure Regarding futures, options, equity swaps, and other derivatives as well as non-investment-grade securities and ADRs: Please ensure that you have read and understood the current options, futures and security futures disclosure document before entering into any such transactions. Current United States listed options, futures and security futures disclosure documents are available from our sales representatives or at http://www.theocc.com/components/docs/riskstoc.pdf, http://www.goldmansachs.com/disclosures/risk-disclosure-for-futures.pdf and https://www.nfa.futures.org/investors/investor-resources/files/security-futures-disclosure.pdf, respectively. Certain transactions - including those involving futures, options, equity swaps, and other derivatives as well as non-investment-grade securities - give rise to substantial risk and are not available to nor suitable for all investors. If you have any questions about whether you are eligible to enter into these transactions with Goldman Sachs, please contact your sales representative. Foreign-currency-denominated securities are subject to fluctuations in exchange rates that could have an adverse effect on the value or price of, or income derived from, the investment. In addition, investors in securities such as ADRs, the values of which are influenced by foreign currencies, effectively assume currency risk. # Options Risk Disclosures: Options may trade at a value other than that which may be inferred from the current levels of interest rates, dividends (if applicable) and the underlier due to other factors including, but not limited to, expectations of future levels of interest rates, future levels of dividends and the volatility of the underlier at any time prior to maturity. Note: Options involve risk and are not suitable for all investors. Please ensure that you have read and understood the current options disclosure document before entering into any standardized options transactions. United States listed options disclosure documents are available from our sales representatives or at http://theocc.com/publications/risks/riskstoc.pdf. A secondary market may not be available for all options. Transaction costs may be a significant factor in option strategies calling for multiple purchases and sales of options, such as spreads. When purchasing long options an investor may lose their entire investment and when selling uncovered options the risk is potentially unlimited. Supporting documentation for any comparisons, recommendations, statistics, technical data, or other similar information will be supplied upon request. # This material is for the private information of the recipient only. This material is not sponsored, endorsed, sold or promoted by any sponsor or provider of an index referred herein (each, an "Index Provider"). GS does not have any affiliation with or control over the Index Providers or any control over the computation, composition or dissemination of the indices. While GS will obtain information from publicly available sources it believes reliable, it will not independently verify this information. Accordingly, GS shall have no liability, contingent or otherwise, to the user or to third parties, for the quality, accuracy, timeliness, continued availability or completeness of the data nor for any special, indirect, incidental or consequential damages which may be incurred or experienced because of the use of the data made available herein, even if GS has been advised of the possibility of such damages. # iTraxx® is a registered trade mark of International Index Company Limited. # iTraxx® is a trade mark of International Index Company Limited and has been licensed for the use by Goldman Sachs Japan Co., Ltd. International Index Company Limited does not approve, endorse or recommend Goldman Sachs Japan Co., Ltd. or iTraxx® derivatives products. # iTraxx® derivatives products are derived from a source considered reliable, but neither International Index Company Limited nor any of its employees, suppliers, subcontractors and agents (together iTraxx Associates) guarantees the veracity, completeness or accuracy of iTraxx® derivatives products or other information furnished in connection with iTraxx® derivatives products. No representation, warranty or condition, express or implied, statutory or otherwise, as to condition, satisfactory quality, performance, or fitness for purpose are given or assumed by International Index Company Limited or any of the iTraxx Associates in respect of iTraxx® derivatives products or any data included in such iTraxx® derivatives products or the use by any person or entity of iTraxx® derivatives products or that data and all those representations, warranties and conditions are excluded save to the extent that such exclusion is prohibited by law. # None of International Index Company Limited nor any of the iTraxx Associates shall have any liability or responsibility to any person or entity for any loss, damages, costs, charges, expenses or other liabilities whether caused by the negligence of International Index Company Limited or any of the iTraxx Associates or otherwise, arising in connection with the use of iTraxx® derivatives products or the iTraxx® indices. # Standard & Poor's ® and S&P ® are registered trademarks of The McGraw-Hill Companies, Inc. and S&P GSCI™ is a trademark of The McGraw-Hill Companies, Inc. and have been licensed for use by the Issuer. This Product (the "Product") is not sponsored, endorsed, sold or promoted by S&P and S&P makes no representation, warranty or condition regarding the advisability of investing in the Product. #
gs_quant/content/events/00_gsquant_meets_markets/01_ideas_for_risk_re_rating/fx_covid19_recovery_trade.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/lisaong/stackup-workshops/blob/master/mask-or-not/mask_or_not.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="bI9Ra2NxlVZ2" colab_type="text" # ## Mask or Not # # Trains a Neural Network Classifier to predict whether a face image is wearing a mask or not. # # Converts the Neural Network Classifier into a Tensorflow-Lite model for deployment to an embedded device (such as an Arduino). # # Instructions on how to run on an ESP32 are here: https://github.com/lisaong/stackup-workshops/tree/master/mask-or-not # + id="EgdZQtHRa77s" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 72} outputId="f027599a-632f-47db-a3bf-347787ffb520" import numpy as np import cv2 import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from pathlib import Path from sklearn.decomposition import PCA from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.preprocessing import LabelEncoder, StandardScaler import tensorflow as tf import pickle import os import random as rn os.environ['PYTHONHASHSEED'] = '0' tf.random.set_seed(42) np.random.seed(42) rn.seed(1254) # + id="17Rx4yqXNsev" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="dc89aa9d-1fed-4292-d32e-5a546e4f334b" tf.__version__ # + id="6ha4WLbmbWc8" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 416} outputId="e1abf541-2e25-4b3f-dbe7-f2b306accb1f" # !wget -q https://github.com/lisaong/stackup-workshops/raw/master/mask-or-not/data.zip -O data.zip # !unzip -o data.zip # + id="3ZuFNqyibAEq" colab_type="code" colab={} # https://pythonprogramming.net/haar-cascade-face-eye-detection-python-opencv-tutorial/ # https://docs.opencv.org/3.4/db/d28/tutorial_cascade_classifier.html face_cascade = cv2.CascadeClassifier(f'{cv2.data.haarcascades}haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(f'{cv2.data.haarcascades}haarcascade_eye.xml') # + id="9r_vqsPkbk08" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 269} outputId="ed3e78a2-cf40-4974-b847-9ce24cc8bbcb" def detect(detector, path): img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = detector.detectMultiScale(img) for (x,y,w,h) in faces: face = img[y:y+h, x:x+w] plt.imshow(face, cmap='gray') plt.show() detect(face_cascade, './data/no_mask/1.jpg') # + id="BGGuItS-gElm" colab_type="code" colab={} detect(face_cascade, './data/mask/1.jpg') # + id="LnAdqXftdc5y" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="eaba7d3b-12c8-4331-c9f3-c267664c62f5" detect(eye_cascade, './data/mask/1.jpg') # + id="Lifzzt7qeLXE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 268} outputId="320d5714-ada6-4e82-8eb9-869ce66bd464" def crop_face(detector, eye_detector, path, output_size=(120, 120)): img = cv2.imread(path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) height, width, channels = img.shape # use the colour version for detection, but the # grayscale version for result faces = detector.detectMultiScale(img) eyes = eye_detector.detectMultiScale(img) face = None if len(faces) > 0: x,y,w,h = faces[0] face = gray[y:y+h, x:x+w] elif len(eyes) > 0: # mask is stumping haar face detection # approximate face by detecting the left eye x,y,w,h = eyes[0] # approximate face dimensions using the # left eye as reference face = gray[max(0, y-2*h):min(y+4*h, height), max(0, x-3*w):min(x+2*w, width)] else: # nothing detected, just return original image face = gray face = cv2.resize(face, output_size) plt.imshow(face, cmap='gray') plt.show() return face crop_face(face_cascade, eye_cascade, './data/mask/1.jpg'); # + id="2fsJh8BAi_cu" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 268} outputId="d96f96a7-cf98-4e6b-ff80-cc7b6b6d9fe8" crop_face(face_cascade, eye_cascade, './data/no_mask/1.jpg'); # + id="DWsxoHbEjAhd" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="5a4a1105-7871-45ca-816f-06aac284563d" # Reduce to a small data size so that PCA and the model can fit on ESP32's memory OUTPUT_SIZE = (20, 20) def get_image_data(label): images = [] for path in Path(f'./data/{label}').rglob('*.jpg'): print(path.name) images.append(np.array(crop_face(face_cascade, eye_cascade, f'./data/{label}/{path.name}', output_size=OUTPUT_SIZE))) return np.array(images) images_mask = get_image_data('mask') images_mask.shape # + id="KmX1g392p-Yk" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="7567c21b-434c-4b63-8483-e5284d5de5c7" images_nomask = get_image_data('no_mask') images_nomask.shape # + id="JiN7yTTerEf-" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 399} outputId="e573087a-b389-4b55-a212-ca65f70dfae0" labels = ['nomask'] * images_nomask.shape[0] + ['mask'] * images_mask.shape[0] labels # + id="D0ehTU4O05NZ" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="498d3a35-2fbe-4754-e53e-b6aa207a8db9" images = np.vstack([images_nomask, images_mask]) images.shape # + id="hCdJk5rA0iDV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="9f8b1f9a-8382-4c7d-e790-37a49ce17781" # flatten X = images.reshape(-1, images.shape[1]*images.shape[2]) X.shape # + id="a6HDPhLt0iY0" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="0578d05d-924a-4797-858b-dca740b9080e" # can we get it back? plt.imshow(X[0].reshape(images.shape[1], images.shape[2]), cmap='gray') plt.show() # + id="26qMkG2Y1jtr" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 86} outputId="61d47218-3417-434b-b944-70b8c7ac4a23" pca = PCA(n_components=.95) scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # tune PCA pca.fit(X_scaled) pca.explained_variance_ratio_ # + id="fUdsyu_41w6z" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="786c352c-82fd-4a73-90af-c91cfc81b1d1" np.arange(1, pca.n_components_+1) # + id="y53Di86u1978" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="0c53d1f7-95bf-4a89-ff08-0f950655b95d" plt.plot(np.arange(1, pca.n_components_+1), pca.explained_variance_ratio_.cumsum(), marker='x') plt.show() # + id="E1gpH8tf2aKY" colab_type="code" colab={} # choose 7 features pca = PCA(n_components=7) Z = pca.fit_transform(X_scaled) # + id="GT2MteWt7gyA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0b7eaeba-bab3-4c6e-d3c4-1026e77357b2" le = LabelEncoder() y = le.fit_transform(labels) le.classes_ # mask=0, nomask=1 # + id="PJH7FBEu5zGE" colab_type="code" colab={} X_train, X_test, y_train, y_test = train_test_split(Z, y, random_state=42, stratify=y) # + id="AVOtoWkc4TkV" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="5446cb02-a72d-4122-b6c3-4839b3a81ba8" lr = LogisticRegression(random_state=42) lr.fit(X_train, y_train) lr.score(X_test, y_test) # + id="RLP7uVnoA1ST" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="cfc57ae8-5dff-46df-e1b8-b90170d3ce17" y_pred = lr.predict(X_test) print(classification_report(y_test, y_pred)) # + [markdown] id="Za_AROLRA5yc" colab_type="text" # ## Neural Networks # + id="Tr-usF4n3qpU" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 260} outputId="c5914fd8-ac5f-4c83-994c-991d019921a3" from tensorflow.keras import layers mlp = tf.keras.Sequential() mlp.add(layers.Dense(X_train.shape[1], input_shape=(X_train.shape[1],), activation='relu')) mlp.add(layers.Dense(X_train.shape[1], activation='relu')) mlp.add(layers.Dense(1, activation='sigmoid')) mlp.summary() # + id="VKZwzybOgHiA" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 422} outputId="77600388-f8a5-44ca-90f5-aa9a54422fcf" tf.keras.utils.plot_model(mlp, show_shapes=True) # + id="XC9FcNsR7Iyg" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="c88020ee-8ca2-4449-8872-86c925dd3853" early_stop = tf.keras.callbacks.EarlyStopping(patience=3) checkpoint = tf.keras.callbacks.ModelCheckpoint('mlp.h5', save_best_only=True) mlp.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy']) history = mlp.fit(X_train, y_train, batch_size=5, epochs=80, validation_data=(X_test, y_test), callbacks=[checkpoint, early_stop]) # + id="529jRH_h7Yh9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="1082e8c5-970a-41ad-fc9d-22494ac38eee" # learning curve plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.title('Learning curve') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend() plt.show() # + id="mYvWnJYw6BDm" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="47695abf-0414-42bd-e3ba-7fe81317b566" y_pred = lr.predict(X_test) baseline_metrics = classification_report(y_test, y_pred) print(baseline_metrics) # + id="yPJ7U0qKAWzx" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="a3549d26-787d-48b9-e56a-82466307f940" y_pred_mlp = mlp.predict(X_test) >= 0.5 mlp_metrics = classification_report(y_test, y_pred_mlp) print(mlp_metrics) # + [markdown] id="4sG8phGV9aAH" colab_type="text" # ## Convolutional Neural Networks # + id="SXr5NX5ALBy7" colab_type="code" tags=[] colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="1d5f0373-ba3a-41ba-f5c8-9240be13328b" OUTPUT_SIZE = (10, 10) images_nomask = get_image_data('no_mask') images_mask = get_image_data('mask') X_cnn = np.vstack([images_nomask, images_mask]) # + id="GjxOLXXEgVg_" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="4b369844-8e65-43d5-e8d7-661e2be7b724" # test image without mask plt.imshow(X_cnn[6].reshape(OUTPUT_SIZE), cmap='gray') plt.show() # + id="mnd_IO3UzF5S" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 156} outputId="86b1fa39-aec2-49e7-e904-ac21f8af8672" X_cnn[6].flatten() # + id="AedoYBNnh0d7" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 265} outputId="6a8843f9-374d-4462-e723-116933e67614" # test image with mask plt.imshow(X_cnn[17].reshape(OUTPUT_SIZE), cmap='gray') plt.show() # + id="G8BJO9nBh0qe" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 156} outputId="621d2b88-b321-40ba-a4ab-b1d3e3c190b2" X_cnn[17].flatten() # + id="_PXJZL8YLB-D" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="84a78132-1b05-4241-fb5a-4a5653d339ec" # add channel dimension X_cnn = np.expand_dims(X_cnn, axis=3) X_cnn.shape # + id="8GSNUrDbdb05" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="8549e684-788e-4b0a-d77c-b6dd2ac42d12" # scale X_cnn_scaled = (X_cnn - 127.0)/128 # split X_train, X_test, y_train, y_test = train_test_split(X_cnn_scaled, y, random_state=42, stratify=y) X_train.shape # + id="Wkgq6dY4NDlX" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 260} outputId="00703ea6-3fd6-427d-a6d8-3702f8aa867e" # https://towardsdatascience.com/a-basic-introduction-to-separable-convolutions-b99ec3102728 cnn = tf.keras.Sequential() cnn.add(layers.SeparableConv2D(5, 3, input_shape=(X_train.shape[1],X_train.shape[2], X_train.shape[3]), activation='relu')) cnn.add(layers.Flatten()) cnn.add(layers.Dense(1, activation='sigmoid')) cnn.summary() # + id="ETp6XRXogDx1" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 422} outputId="ab9ee6ec-a044-47e3-bc9e-57440ff01357" tf.keras.utils.plot_model(cnn, show_shapes=True) # + id="U9f4CT9mw8o5" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 156} outputId="06e3d84d-0853-4420-8d50-143079979809" early_stop = tf.keras.callbacks.EarlyStopping(patience=3) checkpoint = tf.keras.callbacks.ModelCheckpoint('cnn.h5', save_best_only=True) cnn.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy']) history = cnn.fit(X_train, y_train, batch_size=5, epochs=80, validation_data=(X_test, y_test), callbacks=[checkpoint, early_stop]) # + id="J1ED5rW31Hig" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 260} outputId="1dbc5ae4-6e1e-47e8-d58c-19e235955d14" # warm start cnn = tf.keras.Sequential() cnn.add(layers.SeparableConv2D(5, 3, input_shape=(X_train.shape[1],X_train.shape[2], X_train.shape[3]), activation='relu')) cnn.add(layers.Flatten()) cnn.add(layers.Dense(1, activation='sigmoid')) cnn.summary() # + id="z7GKdgCA1KHq" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 156} outputId="1ebff43b-4969-42e6-a824-3a7aac921b09" early_stop = tf.keras.callbacks.EarlyStopping(patience=3) checkpoint = tf.keras.callbacks.ModelCheckpoint('cnn.h5', save_best_only=True) cnn.compile(optimizer='Adam', loss='binary_crossentropy', metrics=['accuracy']) history = cnn.fit(X_train, y_train, batch_size=5, epochs=80, validation_data=(X_test, y_test), callbacks=[checkpoint, early_stop]) # + id="xZBJ3lPzOIOA" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 295} outputId="38484718-4ae6-4097-c9bd-2cfc543df61a" # learning curve plt.plot(history.history['loss'], label='loss') plt.plot(history.history['val_loss'], label='val_loss') plt.title('Learning curve') plt.ylabel('Loss') plt.xlabel('Epochs') plt.legend() plt.show() # + id="yUQPwrJtHdiC" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="e6b7b7cd-b7df-4ca2-d910-56fe2eb78b36" y_pred_cnn = cnn.predict(X_test) >= 0.5 cnn_metrics = classification_report(y_test, y_pred_cnn) print(cnn_metrics) # + id="HqlnoVFMNC1r" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="268d7daf-4143-4dcd-fee9-d94e9e8b6cea" print(mlp_metrics) # + id="DskiuNzygitS" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="635c6645-5d69-4790-d408-58f0689e9986" print(baseline_metrics) # + [markdown] id="YVyKvBk7n0WI" colab_type="text" # ## Quantization to TFLite # # https://www.tensorflow.org/lite/microcontrollers/build_convert # + id="FlgSn2epQYqM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="0c20fa81-7562-4664-9d05-01b5425056de" converter = tf.lite.TFLiteConverter.from_keras_model(cnn) converter.optimizations = [tf.lite.Optimize.OPTIMIZE_FOR_SIZE] tflite_model = converter.convert() open('cnn.tflite', 'wb').write(tflite_model) # + id="yFLXv6dbvc3S" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 173} outputId="f4f7e5c9-00bb-4d02-d0d2-6bb05c6ba305" # Test model loading # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpreter(model_path='cnn.tflite') interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() input_shape = input_details[0]['shape'] y_pred_tflite = [] # Test model on input data. # Loop through each row of test_data and perform inference for i in range(X_test.shape[0]): # add batch dimension input_data = np.expand_dims(X_test[i], axis=0).astype('float32') interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() # The function `get_tensor()` returns a copy of the tensor data. # Use `tensor()` in order to get a pointer to the tensor. output_data = interpreter.get_tensor(output_details[0]['index']) y_pred_tflite.append(output_data[0][0]) print(classification_report(y_test, np.array(y_pred_tflite) >= 0.5)) # + id="KQ_7cYsu23kP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 714} outputId="a3bdd03e-f334-4ec6-81c6-8b770022a64c" # !pip install tinymlgen # + id="wOVyljes255L" colab_type="code" colab={} # https://github.com/eloquentarduino/tinymlgen import tinymlgen c_code = tinymlgen.port(cnn) # input should be flattened like this: # image_width * image_height * channels # Ref: https://github.com/tensorflow/tensorflow/blob/59c06b9016700dbf1ab0cefc062d247345cdd0f0/tensorflow/lite/micro/examples/person_detection/image_provider.cc input_shape = OUTPUT_SIZE[0]*OUTPUT_SIZE[1]*1 with open('cnn.h', 'w') as f: f.write(c_code) # add defines that will be used by application code f.write(f'\n\n#define NUMBER_OF_INPUTS {input_shape}\n') f.write(f'#define NUMBER_OF_OUTPUTS {cnn.get_output_shape_at(0)[1]}\n') # + id="3nOBPS6O475B" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 350} outputId="7b2c779b-fbc3-4abf-b88f-2b564c46104b" with open('cnn.h', 'r') as f: print(f.read()) # + [markdown] id="7Emu2e0LNYTd" colab_type="text" # ## Port PCA to Arduino # # https://eloquentarduino.github.io/2020/06/arduino-dimensionality-reduction-pca-for-machine-learning-projects/ # + id="o5WbSxf2EUzs" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 139} outputId="dfd970a8-d4d9-4f3a-b2eb-6a9ec93f18fb" # !pip install micromlgen # + id="Jyk94DLxNgGg" colab_type="code" colab={} import micromlgen c_code = micromlgen.port(pca) with open('pca.h', 'w') as f: f.write(c_code) # add defines that will be used by application code f.write(f'\n\n#define PCA_INPUT_SIZE {OUTPUT_SIZE[0]*OUTPUT_SIZE[1]}\n') # + id="LVwY-edeNIii" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 819} outputId="647d5cff-2c3d-45dd-c063-8ad0623928a8" with open('pca.h', 'r') as f: print(f.read()) # + id="m0ss3yBuzb2-" colab_type="code" colab={} # Continuous integration is enabled on this notebook # store artifacts for CI testing ci_artifacts = { 'inputs' : { 'X' : X, 'X_cnn' : X_cnn_scaled }, 'target' : { 'y' : y, 'encoder' : le }, 'preprocessors' : { 'scaler' : scaler, 'pca' : pca }, 'baseline' : { 'input' : 'X', 'model' : lr, 'preprocessors' : [ 'scaler', 'pca' ], }, # model1 spec 'mlp' : { 'input' : 'X', 'scaler' : scaler, 'preprocessors' : [ 'scaler', 'pca' ], 'h5' : 'mlp.h5' }, # model2 spec 'cnn' : { 'input' : 'X_cnn', 'preprocessors' : [ ], 'h5' : 'cnn.h5', 'tflite' : 'cnn.tflite', 'h' : 'cnn.h' } } pickle.dump(ci_artifacts, open('ci_artifacts.pkl', 'wb')) # + id="Q-8RD7aLXGOd" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000} outputId="d4ffc444-7cae-4a88-97e3-80b8b219fe01" # tests for continuous integration of the model import unittest import numpy as np import pickle import tensorflow as tf from sklearn.metrics import classification_report class ModelTestcase(unittest.TestCase): def setUp(self): """Called before every test case.""" with open('ci_artifacts.pkl', 'rb') as f: ci_artifacts = pickle.load(f) self.inputs = ci_artifacts['inputs'] self.target = ci_artifacts['target'] self.preprocessors = ci_artifacts['preprocessors'] self.baseline = ci_artifacts['baseline'] self.mlp = ci_artifacts['mlp'] self.cnn = ci_artifacts['cnn'] def tearDown(self): """Called after every test case.""" pass def _testSkLearnModel(self, model_spec): model = model_spec['model'] X = self.inputs[model_spec['input']] for p in model_spec['preprocessors']: X = self.preprocessors[p].transform(X) y_pred = model.predict(X) print(model) print(classification_report(self.target['y'], y_pred)) def _testTFModel(self, model_spec): model = tf.keras.models.load_model(model_spec['h5']) X = self.inputs[model_spec['input']] for p in model_spec['preprocessors']: X = self.preprocessors[p].transform(X) y_pred = model.predict(X) >= 0.5 print(model.summary()) print(classification_report(self.target['y'], y_pred)) def testBaseline(self): print('Testing Baseline') self._testSkLearnModel(self.baseline) def testMLP(self): print('Testing MLP') self._testTFModel(self.mlp) def testCNN(self): print('Testing CNN') self._testTFModel(self.cnn) def testCNNTFLite(self): print('Testing TFLite Model') self._testTFLiteModel(self.cnn) def _testTFLiteModel(self, model_spec): y_pred = [] # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpreter(model_path=model_spec['tflite']) interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() input_shape = input_details[0]['shape'] # Test model on input data. # Loop through each row of test_data and perform inference model_input = self.inputs[model_spec['input']] for i in range(model_input.shape[0]): # add batch dimension input_data = np.expand_dims(model_input[i], axis=0).astype('float32') interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() # The function `get_tensor()` returns a copy of the tensor data. # Use `tensor()` in order to get a pointer to the tensor. output_data = interpreter.get_tensor(output_details[0]['index']) y_pred.append(output_data[0][0]) print(classification_report(self.target['y'], np.array(y_pred) >= 0.5)) if __name__ == '__main__': # run all tests, the argument is for running on Jupyter, # but needs to be removed for the CI test as it will hide failures. unittest.main(argv=['first-arg-is-ignored'], exit=False) # + id="gK_s6kJ9XrQc" colab_type="code" colab={}
mask-or-not/mask_or_not.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Programming in 209 # # # In 209 we won't require you to use a specific programming language, or a specific platform. In fact, there will be little programming of any form required. However during the course I will be mentioning some numerical techniques that are used in electromagnetism (and elsewhere!) and illustrating some of these techniques with "fake" problem sets worth 0 points. The distribution format will be Jupyter notebooks. While many students will be familiar with this approach, for those who aren't I've copied below a notebook developed at Berkeley to introduce undergraduates to Python and the Jupyter platform. # # You can find other introduction to the Python language at e.g. https://www.py4e.com/book or the handy cheat sheets [here](https://github.com/michaelJwilson/DESI-HighSchool/tree/master/cheatsheets). # # Introduction to Python # # If you are viewing this notebook on `datahub.berkeley.edu`, you should have everything you need. If you are running this anywhere else, you will need Python 3 and the core Jupyter packages, as well as `numpy`, `scipy`, and `matplotlib`, which are standard packages that should come with your Jupyter installation. # # ### Contents # - [Introduction](#intro) # - [A glorified calculator](#calc) # - [Types of things](#types) # - [Functions and variables](#fn) # - [Lists, tuples, etc.](#lists) # - [Classes](#classes) # - [Control flow](#cflow) # - [NumPy](#numpy) # - [Jupyter notebooks](#jupyter) # # <a name="intro"></a> # ### Introduction # #### Welcome to programming # An integral part of the physicist's toolkit is the computer. A computer is a physical device designed in such a way that the physical states of the system, and the relationships between them, can be mapped to those of any other physical systems. Thus we can simulate physical systems by identifying them with that of a computer. This mapping is so powerful in fact that it is more effective to think of the computer as a mathematical system rather than a physical one. The mathematics of computers, called computer science, is a rich field which connects seamlessly with physics in areas like (quantum and classical) information theory and complexity theory. Many physicists subscribe to some kind of notion of digital philosophy, in which the primary entities of the universe, the physical things, are nothing more than information ("it from bit/qubit"). In this viewpoint, computer science and physics are literally identical. It is not surprising then, that people interested in physics are often also interested in mathematics and computer science. However here we use computers only as tools that enable greater physical insight and understanding, and so for us right now they are a means to an end rather than an end itself. # # You will be learning programming for physics in a language called Python. As such we will only teach you what you're likely to need to know. Thus while we won't talk about Turing machines or complexity classes, we recommend that you take some CS classes or use some of the extensive resources available online to learn more about this rich and interesting field of study. # # Computers are mathematical systems which we can program. We can create mathematical objects, and define the rules that determine how they behave. Physical systems also follow rules. By encoding those rules into a program, we can use the physical system that is a computer to simulate a vast array of other physical systems. # # If we compute things exactly using abstract mathematical objects as we would on paper, this is called __symbolic__ computing. We'd recommend [Mathematica](https://software.berkeley.edu/mathematica) for symbolic computing, but Python also has [a package](https://www.sympy.org/en/index.html) for it. Symbolic computing basically does the math for you because some mathematicians have codified into a program the usual rules of manipulation of mathematical expressions. # # While you are welcome to use symbolic computation, this is not the kind of computing we shall be doing here. We shall be doing __numerical__ computing, in which we approximate numbers to representations on a computer. Since a digital computer only has a finite level of accuracy (discussed further below), this process is not exact and does contain error. Sometimes one must be careful that the errors do not propagate and that our answers are not affected by it. # # #### Motivation # Why use computers? Can't we use good old-fashioned pen and paper to get exact answers instead of numerical approximations? Here are some things that are easy numerically, but extremely tedious if not untractable analytically: # # - transcendental equations # - high-dimensional statistics # - solving differential equations (Navier-Stokes: is fluid dynamics solved?) # - data analysis # - series expansions # - evaluating functions # - integration # - basic arithmetic (what's $67+313^{344}-13*12 \mod 235$?) # # In this series of introductory notebooks, we shall do all of the above using standard packages in Python. # # The rest of this notebook is an introduction to programming in Python. Each section introduces you to programming concepts and/or shows you how to efficiently implement schemes in Python. If you are familiar with Python, you might want to skip this notebook and move on to the next one which introduces you to scientific computing in Python. If you are familiar with programming but not Python, we'd recommend that you go through the relevant parts of the notebook to get familiar with Python quirks and syntax. # # #### Python vs other languages # The Physics department has decided to use Python since it is the most commonly used language for applications in physics. Python is a _high-level_ language, which means that Python itself is written in a _low-level language_ like C, which itself is written in the binary instruction language understood by the computer. Thus when you run a Python program, it is first compiled to a C program. This C program is then compiled to machine instructions, which are then executed. A higher-level language allows you to do more things without having to write as much code, and not worry about the details of how things work under the hood. A lower-level language will be more verbose, but it gives you the ability to choose exactly how things are implemented, and thus allows you to make your code run faster. Since we use Python, our code will typically be shorter but slower than the equivalent code in a lower-level language. # # <a name="calc"></a> # ### A glorified calculator # # You can do all the usual arithmetic operations with Python. You can edit and press `shift` + `enter` to evaluate each of the cells below. Feel free to create a new notebook or additional cells using the + icon in the taskbar on top of the page to play around. # # Addition 5+2 # Subtraction 6-8 # Multiplication 4*2.5 # Division 32/6 #this is a comment # Integer division (quotient) 32//6. #everything after the '#' is ignored by Python # Modulus (remainder) 32%6. # Exponentiation (be careful not to use `^`, that means [bitwise `XOR`](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)) 2**10 # You can also compare objects 3 < 4, 5 == 5.0, 32 >= 33 # It follows the usual order of operations 4**3/2+1%5, (4**(3/2)+1)%5 #use parentheses where required. # The full list of in-built Python operators can be found in the [relavant Python documentation](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex). In general, whenever you are using something written by somebody else, you should make sure you know what it is doing, e.g. what inputs to give a function and what outputs to expect. This is the purpose of __documentation__, and using documentation is an essential programming skill. Documentation and [stack overflow](https://stackoverflow.com/) will be your greatest friends in your quest to learn Python. Since we introduce you to all of Python in one notebook, we mention a lot of things without explaining them in depth. We will at first provide links to documentation, but later will expect you to use the extensive materials available online by yourself. # # <a name="eqn"></a> # ### Types of things # These are many different types of primitive objects in Python. As you saw above, the most commonly used built-in types are integers (`int`) and floating-point numbers (`float`). Other commonly used types are pieces of text, called strings (`str`), and binary true/false objects called [Booleans](https://en.wikipedia.org/wiki/Boolean_algebra) (`bool`). Python has a built-in function called `type()` that tells you the type of a given object. type(1), type(1.), type(True), type("hello") # `int`s are exact and Python 3 automatically resizes the data allotted to each int so that it can store an arbitrarily large positive or negative integer. On the other hand, `float`s are __not exact__. Essentially floating-point numbers are binary fractions multiplied by a scale. Typically Python uses 64 bits for floats, which are represented as $n=\text{(53-bit integer)}\times 2^{\text{(11-bit integer)}-52}$. Thus there are 53 bits of precision, meaning that the float $f$ represents all numbers in a range of $2^{-53}f$. When subtracting floats that are very close to each other (e.g. taking derivatives), error that was intially a factor of $10^{-16}$ might scale up dramatically. The largest and smallest numbers floats can store are $2^{-2^{10}-52}$ and $2^{2^{10}-1}$ (we lose 1 bit to the sign of each integer). Trying to store smaller or larger numbers results in underflow or overflow respectively (but sometimes you can work in log space). Ultimately, since they are represented using 64 bits, there are only $2^{64}$ floats. This kind of thing is unavoidable when using a discrete system like a digital computer to model or represent a continuous system like the number line. Since these representational errors can compound, comparing floats is a bit tricky. For more information, read the [Python tutorial](https://docs.python.org/3/tutorial/floatingpoint.html). 2**1024 #python ints rescale as much as memory allows # When a number becomes too large or too small to be a represented by a float, e.g. when performing repeated multiplications or divisions, this is known as _overflow_ or _underflow_ respectively. 2.**1024 #overflow 1.999999*2.**1023, 2*2.**1023 2**-1074, 1.99999999*2**-1075 2**-53, 1.+2**-52, 1.+2**-53 #float precision 2**64 #total number of floats 3*0.1, 3*0.1 == 0.3 #in practice, we can check if 2 floats are within some small tolerance from each other; more on this later. # Here's a handy way to input large or small `float`s: 1e-2, 1.4e3, 1.8e0 #use e to set an integer exponent, e.g. 3.3e-5 = 3.3 * 10**-5 # Python automatically casts one type to another when required. Typically the casting heirarchy preserves information. For more information, read the [docs](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex). type(5*2), type(5*2.), type(5/2), type(5//2), type(1.+False) # Of course, this doesn't always work: 1+"2" # You can also explicitly convert some types to others using built-in functions that are rather intuitively named: str(5.4), bool(-45.2), float(6), int(6.9), float("587e-10") # Of course, this doesn't always work. # # Python also has complex numbers, initialised by the special letter `j` written at the end of a number (`int` or `float`), which plays the role of $i\equiv\sqrt{-1}$. type(1j), abs(.4+.3j), 1==1+0j, (3+2j).real, (3+2j).imag # There's also a special constant called `None` that is sometimes used to denote a lack of information. type(None) # <a name="fn"></a> # ### Functions and variables # # Functions are types of objects which return objects when given objects. They are functions as we think of them mathematically. Python has several built-in functions, like `type()` and the ones to convert type that we saw in the previous section. We can also define our own functions. Here's the function definition for $f(x)=x^2$. def f(x): #this is the function definition """Returns the square of x""" #this is the docstring. it is documentation that specifies what the function does. #this is the body of the function. you can use any of the arguments (in this case, x) here #the function ends when the indented block ends or when it hits a return #the editor will automatically indent after a valid function declaration, but you will sometimes have to unindent manually. return x**2 #function execution ends and x**2 is passed on to the thing that called the function #function definition ended. no longer indented #to learn how functions are executed, google 'call stack' f(4) #this is a function call. The code written in the function definition is only executed when it is called # To obtain information about a function, use `?`. # + # f? # + # str? # - # In most programming languages, one has to specify the type of each argument accepted by the function. For example, we would have to specify that `x` in the function above is e.g. a `float`. However, Python is __untyped__. In Python, anything can be passed on to the function, and so one has to be careful that the function works as expected for all the types it is called on. One common beginners' mistake is for people to pass lists to functions expecting single values. If other people are going to be using your code, you can enforce preconditions on your arguments using the statements `assert` and/or `raise`. f(True) f("a") #Since python is untyped, python functions differ from mathematical functions in that they lack explicit domains and ranges # Keep in mind that functions don't have to return anything. If Python sees an unindented block before a `return`, it will end the function execution and implicitly return `None`. # # We can also create variables that can take on temporary values. Again, in Python, unlike most other languages, variables are untyped. Thus a variable that starts off as an `int`, for example, might get reassigned to a `str`. x = 5 #this is an assignment. The variable x now has the value 5 x #can access variable in any cell executed after the one it was defined in x = "ab"+"cd" #assign new value. old value lost. x del x #delete variable x # Variables like `x` in the cell above are _global_ variables. They can be referenced anywhere in the notebook. However, variables defined inside function definitions are called _local_ variables. They can only be accessed within the body of the function, and are lost when the function execution ends. If a global variable has the same name as the argument to a function or to a local variable, the global variable cannot be accessed within the body of the function. In general, try to avoid namespace collisions. # + x = 5 #global variables z = 6 y = -1 def g(x,y): #global variables x and y cannot be accessed here because they have same names as arguments z = x + y #defines new local variable in terms of arguments. now global variable z is unchanged but cannot be accessed return f(z) #uses local variable g(1,2), z, f(z), x, y, f(x+y) #this is outside body of function. global vriables can be accessed. # - # While functions can access global variables, this is considered bad programming practice. One should pass the function everything it needs as an argument, so that the function can run in any environment and no global variables need to be defined. Similarly, one can change global variables by scoping it using `global`, but one should instead return everything required. # + def bad_fn(x): return x + z #using global variable z and argument x bad_fn(1), x, z # - z = None #this breaks the function bad_fn(1) # While we have only shown you functions with 1 or 2 arguments so far, you can define functions with 0 or more arguments. In Python you can also define some arguments to be optional, and assign it a default value in the function definition. These arguments are known as keywords. As an example, let's consider the problem of testing two `float`s for equality. # + def float_equal(float1, float2, tolerance=1e-6): return abs(float1-float2) <= tolerance float_equal(0.1*3, 0.3), float_equal(3, 3+5e-7), float_equal(3, 3+5e-7, 1e-7) # - # Arguments can be given using the name of the argument, in which case the order of arguments doesn't matter. Keywords must always follow the regular arguments though. float_equal(0.1*3, 0.3, 1e-10), float_equal(0.1*3, 0.3, tolerance=1e-10), float_equal(tolerance=1e-10, float2=0.3, float1=0.1*3) #these are all equivalent. # Functions are just another type of object. Thus we can use functions as arguments to functions, or have functions that return functions. Here is one that does both: type(f) # + def add_five(fn): def g(x): return fn(x)+5 return g h = add_five(f) add_five, h, f(3), h(3) # - # A popular computer science paradigm is functional programming, in which all data types are functions. The analogous field of math is known as $\lambda$-calculus. In this spirit, Python offers a way to create anonymous functions in one line using the `lambda` command. For example, the command `lambda arg1, arg2: arg1+arg2` creates a function that takes two arguments and returns their sum. We can assign this object to a variable, e.g. `f = lambda arg: value`, which is equivalent to `def f(arg): return value`. # + f = lambda x: x**2 #this is equivlent to the previous definition of f def add_five(fn): #this is equivalent to the previous definition of add_five return lambda x: fn(x)+5 add_five = lambda fn: lambda x: fn(x)+5 #this is also equivalent to the previous definition of add_five # - # <a name="lists"></a> # ### Lists, tuples, etc. # # Lists are ordered collections of objects. Lists are demarcated by `[]` and entries are separated by `,`. type([]) #empty list # Since Python is untyped, different entries of the same list can have different types. a = [1, "a", None, 0.7+7j, False] # Python has an in-built function `len()` which returns the number of entries (length) in a list (or list-like object). len(a) # You can access entries using the index of each entry. In Python indices start from `0` and go to `n-1` for a list of length `n`. You can also index backwards, so `-x` is equivalent to `n-x`. a[1], a[-2] a[1] = "b" #change entry in list a # One of Python's most useful features is list slicing, which generates sublists from a given list. `x[start:end:step]` returns a list containing every `step`th entry of `x` starting at `start` upto but not including `end`. The defaults for a list of length `n` are `start = 0`, `end = n`, and `step = 1`. (If `step < 0` then the defaults for `start` and `end` are changed accordingly.) a[:] #all default: whole list a[::] #same as above a[1:3] #entries 1 through 3 (i.e. entries 1 and 2) a[1::3] #every third entry starting at 1 a[-1] #last entry a[-1:] #list of last entry onwards a[:-1] #exclude last entry a[::-1] #whole list backwards a #original list is unchanged # Since a string is essentially a list of characters, slicing also works on strings. b = "hello world" b[2:-2] #without 2 characters each from front and back # You might find the following methods useful. Consult documentation for more information. a.append("a") #add entry to end of list a #list is changed del a[3] #remove entry by index a a.insert(2,"3") #add entry at specified index a a.index("a") #find (first) index of a value #this also works on strings a.remove("a") #remove (first matching) entry by value a # You can add (concatenate) lists, which also generalises to integer multiplication. [1,2] + [3,4] 5*[1,2] # The `in` keywords allows you to test for inclusion in a list-like object or string. a = [1,2,3,4] b = "abcd" 4 in a, "c" in b, [1,2,3] in a, "abc" in b # Python has an in-built function called `map()`, which allows you to conveniently execute a function on each element of a list. You might also want to look at `zip()`. list(map(f, [1,2,3,4])) # When a variable stores a primitive data type (like a float or bool), it stores it directly. However, when it stores a list, it stores a _pointer_ to a location in memory where the list is stored. Thus copying e.g. a float is easy, but copying a list involves copying each entry of the list. It also makes comparing objects difficult. x = 5 y = x x += 1 #shorthand for x = x + 1. Similar shorthands exist for -,*,/ x, y a = [1,2] b = a a.append("this is a not b") a, b # The `is` statement can be used to check if two variables point to the same object. c = [1,2,"this is a not b"] a == b, a == c, a is b, a is c # _Packages_ are libraries of code made public for people to use, so that people don't have to solve problems that have been solved before or write code that someone else has already written. Packages contain `.py` file(s) called _modules_ that can be imported using the `import` command. You can also write your own modules and import them in other pieces of Python code. You can also download packages from the internet. It is common to use a _package manager_ like [pip](https://pip.pypa.io/en/stable/quickstart/) or [conda](https://docs.conda.io/projects/conda/en/latest/user-guide/getting-started.html). It is also quite easy to [publish](https://pypi.org/) a package that can can be downloaded using pip, or to publish your code to [GitHub](https://github.com/). # # In addition to external packages that you can download, Python has several in-built modules. The in-built module `copy` provides tools to copy objects instead of pointers. The function `deepcopy()` works with lists of any depth (i.e. lists of lists of lists of...). Before using it, however, we must import it. # + import copy a = [1,2] b = copy.deepcopy(a) a.append("this is a not b") a, b # - a = [1,2] b = a[:] #easy way using slicing (only for lists of primitives) a.append("this is a not b") a, b # Since we're only importing one function, it is better to use the following syntax to only import the function we need instead of the entire module. # + from copy import deepcopy a = [1,2] b = deepcopy(a) a.append("this is a not b") a, b # - # Above, if we had written `from copy import *`, it would have imported everything from `copy` but without adding the name of the package to their names. This is known as a wildcard import, and it is dangerous because it can cause namespace collisions which can overwrite functions and variables that are already defined. You can also alias anything you import using `as`. For example, if you use `import copy as cp` you would then use `cp.deepcopy()`, or if you use `from copy import deepcopy as dc` you would then simply use `dc()`. You can also specify multiple objects to import by separating them with commas. # Tuples are essentially the same thing as lists, except they are immutable (can't be changed). They are demarcated by `()`. type(()) #empty tuple # Tuples can be indexed and sliced like lists. They are the preferred data type of Python, since any comma-separated input automatically gets converted to tuples. t = 1, None, "x" type(t) t t[1], t[::-1] t[1] = True #immutable, have to create new tuple to edit # The `*` keyword can also be used to pass a tuple of arguments in a function, or retrieve any number of optional arguments to a function. # + def example1(arg1, arg2): print(arg1, arg2) args = "a","b" example1(*args) # + def example2(arg, *args): print("arg:", arg) print("args:", args) print("args:", *args) example2(1) example2(2, *args) example2(3, *t) # - # Python also supports tuple assignment, where you can economically set a tuple of variables to a tuple of values. a, b, c = 1, None, "x" type(a), type(b), type(c) # In fact, we have been using tuples implicitly in almost all of the cells above. When you evaluate each cell (`shift`+`enter`), the Python kernel executes all the code in the cell, and returns the evaluation of the expression in the last line of the cell. Thus all the cells in which the last line is a list of things have returned tuples. However (and this was probably bad design to tell you this so late) we don't have to put things on the last line to see their output. We can display things at any point using the in-built function `print()`. print("this is printed") "this is returned" #note the difference between the two below # Python supports a [string formatting mini-language](https://docs.python.org/3/library/string.html#format-specification-mini-language) which enables you to conveniently output information in a readable format. Especially when debugging code, being able to easily read the values of variables is essential. x = 1.2351 y = 1.2349 z = 4.9e-3 print(f"The value of x is {x:.2f}") print("The value of y is {0:.2f}".format(y)) print("The value of z is %.2f"%z) # Dictionaries (`dict`s) are another commonly-used data type. Dictionaries consist of unordered pairs of objects, called _keys_ and _values_. They follow the format `{key1: value1, key2: value2, ...}`. Values can be accessed using the key similarly to how one may use an index for a list. type({}) d = {"a": f, 2: "f", True: ("j", "k")} d["a"], d[2] d[54.35332] = [5,0,-7,9] #adding a new entry d # Dictionaries are useful to store data that consists of multiple fields, e.g. a university could be represented by `{"name": "UC Berkeley", location: (37.8719, -122.2585), "students": 42519, "private": False, "good departments": ["Physics", "EECS", "Political correctness"]}`. list(d.keys()) #list of keys d.pop(True) #remove entry corresponding to key and return value removed d # `**` does for dicts what `*` does for tuples, for keyword arguments to functions. # + def example3(a, b): print(a, b) a = None, (5,-6) b = {"b": (5,-6), "a": None} example3(*a) example3(**b) # + def example4(arg, *args, **kwargs): print("arg:", arg) print("args:", args) print("kwargs:", kwargs) example4(1) example4(2, "abc", True, "def", keyword1="value1", k2="v2") # - # <a name="classes"></a> # ### Classes # # Lists and dicts are examples of complex data types, which can hold multiple pieces of information. These data types are useful generally, but different problems have different solutions. Lists are implemented as automatically-resizing arrays of contiguous memory. This means that (looking only at the [asysmptotic scaling](https://en.wikipedia.org/wiki/Big_O_notation) of the cost of operations) acessing elements is $\mathcal{O}(1)$ (i.e. is constant with array size), and inserting or removing items changes with the index, from $\mathcal{O}(1)$ at the end of the list to $\mathcal{O}(n)$ at the start. If you only need to insert and access things at the ends of a list, you might want to use one of the native Python `queue`s that are optimised for that. Dicts are implemented as hash tables, so accessing, inserting and removing is $\mathcal{O}(1)$, and so is checking for inclusion (which is $\mathcal{O}(n)$ for lists). Python also has native `set`s, which are essentially dicts with only keys. # # Other data structures exist such as sorted lists (self-balancing binary trees), neural networks, decision trees, blockchain, etc. that are more efficient or convenient for different applications. A large part of CS is finding the most efficient way to solve a problem. # # You can define data structures that are convenient for you by defining a `class`. Then you can create objects, which are _instances_ of the class. Using this paradigm is known as object-oriented programming. The class, as well as each object, may have associated variables and functions. These associated functions are called _methods_. If you get the hang of creating and using the classes you need, you will be able to program much more efficiently as you be less likely to have to write the same piece of code twice. # # For example, if you wanted to create a class to store a 2D circle (e.g. for graphing purposes), you could do something like: class Circle2D: pi = 3.14159 #class variable. of course, Python has a more accurate pi in the math module def __init__(self, centre=(0,0), radius=1): #constructor: this creates an instance given the arguments. self refers to instance #names like __this__ are special. consult docs if curious. names like _this are hidden (accessible only to methods of instance) self.x = centre[0] #these are instance variables self.y = centre[1] self.r = radius def centre_distance(self, point): return ((point[0]-self.x)**2+(point[1]-self.y)**2)**.5 def contains_point(self, point): #instance method return self.centre_distance(point) <= self.r def area(self): return self.pi*self.r**2 def shape(): #class method. note no reference to self return "round" Circle2D.pi #accessing class variable Circle2D.shape() #class method c = Circle2D(centre=(-8,4.5), radius=5) #creating instance type(c) print(c.x, c.y) #accessing instance variables c.x, c.y = 0, 0 #changing them print(c.x, c.y) c.centre_distance((-5,12)), c.contains_point((4,-3)), c.contains_point((5,.1)), c.area() #instance methods c.pi #instance also has class variables c.shape() type(c).shape() # All the data types we've seen so far are classes, and we've seen quite a few of their methods and instance variables already. You can extend these, or any other, classes by defining a class that inherits the methods and properties of another class, using `class SubClass(ParentClass):`. # # <a name="cflow"></a> # ### Control flow # # You can also change the way in which the code you write is executed. One example of this is an `if` statement. It executes code conditional on a Boolean. if .38 == 1.9*.2: #play around with this condition print("true") #the indented block gets executed conditionally. print("done") #this is always executed def float_compare(float1, float2, tolerance=1e-10): if float_equal(float1, float2, tolerance): return "=" elif float1 < float2: #else-if return "<" else: #since the function would have returned already we can replace the elif with an if and get rid of the else entirely return ">" float_compare(6/9.003, 2/3.001) # Python also has a _ternery operator_, which does an if-else in one line. The following example first checks if the point is in the circle. If it is, it returns zero, otherwise it computes and returns the distance. distance_to_circle = lambda point, circle: 0 if circle.contains_point(point) else circle.centre_distance(point) - circle.r distance_to_circle((-5,12),c), distance_to_circle((4,-3),c), distance_to_circle((0,1),c) # The `not` keyword negates a Boolean, so the above function is equivalent to: distance_to_circle = lambda point, circle: (not circle.contains_point(point)) * (circle.centre_distance(point) - circle.r) #true=1 and false=0 for casting distance_to_circle((-5,12),c), distance_to_circle((4,-3),c), distance_to_circle((0,1),c) # Using the in-built `max()` function, we can shorten the definition to: distance_to_circle = lambda point, circle: max(circle.centre_distance(point) - circle.r, 0) distance_to_circle((-5,12),c), distance_to_circle((4,-3),c), distance_to_circle((0,1),c) # You can also execute a piece of code multiple times if you put it in a __loop__. The `while` statement repeats a block of code until a Boolean turns `False`. i = 0 while i < 10: i += 1 print(i) print("over") # For example, we can implement [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method) with the following code: def newton_method(fn, x, epsilon=1e-5, tolerance=1e-10): while abs(fn(x)) >= tolerance: #while we are not at zero df = (fn(x+epsilon/2) - fn(x-epsilon/2))/epsilon #numerical estimate of derivative at x x -= fn(x)/df #change x #while loop ended, this means we are at zero return x newton_method(f,3), newton_method(lambda x: x**2-1,3), newton_method(lambda x: x**2-1, -2) # The statement `break` stops the execution of the loop, and `continue` skips the rest of the block only for the current iteration. i = 0 while i < 10: i += 1 if i%3 == 0: continue print(i) print("over") i = 0 while i < 10: i += 1 if i == 5: break print(i) print("over") # One has to be careful not to get caught in infinite loops. One will have to interrupt the kernel using `ctrl`+`D`, the right-click menu, or the button on the top of the window in such a situation. (There are several inputs that break Newton's method as well.) i = 0 while i < 10000: if i**2 % 4 == 3: #curiosity: which numbers pass this if clause? print(i) #remember to increment! # Sometimes it is more convenient to use `for` loops, which are essentially `while` loops with different syntax. This allows one to iterate through any `Iterator`, which is an object that enables iteration by implementing a method that returns the next item in iteration (in the example above it would increment `i`). List-like objects are _iterable_, which means they automatically support iteration. (Here the method automatically returns the next element of the list-like object.) a = [1, "a", True, None, 4.5] for item in a: print(item) # Iterating through a dict is equivalent to iterating through its keys. # + d = {1: 3, "a": "b"} for k in d: print(k,d[k]) # - # The inbuilt function `range(start, end, step)` creates an iterator with syntax that has the same meaning as in the context of slicing. This makes it easy to iterate a set number of times: for i in range(10): print(i) # A range is not quite a list, though it can be converted to one. Iterators are better for loops because the entire list need never be created or stored in memory. range(10), list(range(10)) type(range(10)) # You can create your own iterator by defining a _generator_, which is a function that returns an iterator that runs code before and after `yield`ing values for iteration. # + def myGenerator(x): y=x**2 yield 45 if y==0: return 0 #stop iterating (return doesn't do anything) yield "x" yield x z=x-y while z<0: yield z z+=1 yield y,x**z iterator = myGenerator(3) for i in iterator: print(i) myGenerator, iterator, list(myGenerator(0)) # - iter = myGenerator(2) next(iter) #run this a few times # Python also offers a one-line way to create lists using one-line loops, called _list comprehension_. It is often faster than writing out a proper loop. For example, if we wanted to create a list of every number squared from 0 to 10, we could do the following: a = [] for i in range(10): a.append(i**2) a a = [i**2 for i in range(10)] #equivalent to the above loop a # To see that list comprehensions are indeed slightly faster, you can import the `time()` function from the `time` module, which is useful for benchmarking code. from time import time #is this bad? can we still access the time module? #time() is function that gives current OS clock time in seconds #we will use this to time executions to compare code time() #run this a few times n = 10**6 #this is size of list, try changing this start = time() a = [] #first time the regular loop for i in range(n): a.append(i**2) checkpoint1 = time() a = [i**2 for i in range(n)] #then time list comps checkpoint2 = time() a = list(map(f, range(n))) #lastly time the map() function end = time() print("List comprehension: %.4f sec\nLoop: %.4f sec\nMap function: %.4f sec" % (checkpoint2-checkpoint1, checkpoint1-start, end-checkpoint2)) # List comprehensions also support an `if` clause (as well as ternery operators described above). #function that, given a Circle2D instance and a list of points, returns the sublist of points within the circle. points_in_circle = lambda points, circle: [point for point in points if circle.contains_point(point)] c = Circle2D() #circle has radius 1 and centre at (0,0) by default points = [(1,0), (3,1), (-1,0.1), (0,0), (-0.5,0.5), (98,-23), (0.4, -0.3)] points_in_circle(points, c) # You might also find the in-built function `enumerate()` useful. a_list = [4, "a", (7,8,9), {3: 5, "g": None}, True] for index, value in enumerate(a_list): print(index, value) # Another useful control method is _recursion_, where a function calls itself. Here is a recursive implementation of Newton's method: def newton_recursive(fn, x, epsilon=1e-5, tolerance=1e-10): if abs(fn(x)) < tolerance: #termination case return x #no need for else since function would have returned already otherwise df = (fn(x+epsilon/2) - fn(x-epsilon/2))/epsilon #numerical estimate of derivative at x x -= fn(x)/df #change x return newton_recursive(fn, x, epsilon, tolerance) newton_recursive(f,3), newton_recursive(lambda x: x**2-1,3), newton_recursive(lambda x: x**2-1, -2) # Again, it is easy to get stuck with infinite loops. To avoid this, remember to code a termination clause (i.e. a case where it returns something without calling itself), and to make progress towards termination at each function call. Recursion is usually aesthetically more pleasing than a loop, but is slightly slower due to the time taken to call each function. There are some problems for which recursion is better suited, particularly when the function calls itself multiple times per execution. Recursion is best suited for problems with self-similarity, which ties into concepts like fractals, scale invariance, and conformal symmetry in physics and mathematics. Such problems can typically be solved in $\mathcal{O}(\log(n))$ time. For example, if we wanted to create a simple discrete version of the [Cantor set](https://en.wikipedia.org/wiki/Cantor_set), we could use the following recursive function: def cantor(level): if level == 0: return [1] #base unit level -= 1 return cantor(level) + 3**level*[0] + cantor(level) start = time() print(cantor(3), len(cantor(15)), 3**15) time()-start # Note that the above function can be implemented more efficiently using a loop as follows, but there are other problems where recursion is better. def cantor(level): c = [1] for i in range(level): c = c + 3**i*[0] + c return c start = time() print(cantor(3), len(cantor(15)), 3**15) time()-start # Recursion is usually slower becuase calling a function takes a certain amount of time, known as _function overhead_. Here is an example of two algorithms that both scale as $\mathcal{O}(n)$, but recursion is slower. # + from random import shuffle #used to make random test case: more about this in next notebook def recursive_max(arr): if len(arr)==1: return arr[0] x = len(arr)//2 l = recursive_max(arr[:x]) r = recursive_max(arr[x:]) return l if l>r else r def loop_max(arr): m=arr[0] for a in arr[1:]: if a>m: m=a return m for i in range(0,6): test_array = list(range(10**i)) shuffle(test_array) #mix up the order start=time() recursive_max(test_array) cp=time() loop_max(test_array) cp2=time() max(test_array) end=time() print("length: %d\trecursive: %.6f s loop: %.6f s python: %.6f"%(10**i,cp-start,cp2-cp,end-cp2)) # - # Sorting can be done recursively in $\mathcal{O}(n\log n)$ time. We compare our implementation to the default Python implementation, which is significantly faster because it isn't written in Python. The Python mantra of "don't reinvent the wheel" is a paradigm enforced by necessity. (If you want speed, don't use Python. Python is for convenience and not having to reimplement everything.) # + def recursive_sort(arr): if len(arr)==0: return [] x=[arr[0]] l=[] r=[] for a in arr[1:]: if a>x[0]: r.append(a) elif x[0]==a: x.append(a) else: l.append(a) return recursive_sort(l)+x+recursive_sort(r) def loop_sort(arr): #try beating the recursive solution return sorted(arr) #currently returns Python's native (recursive) implementation for i in range(0,6): test_array = list(range(10**i)) shuffle(test_array) start=time() recursive_sort(test_array) cp=time() loop_sort(test_array) #default Python implementation, but feel free to test your own sort function end=time() print("length: %d\trecursive time: %.6f s\tloop time: %.6f s"%(10**i,cp-start,end-cp)) # - # As you learn Python, you might want to solve a few problems to get you familiar with things. We recommend doing the first ~30 problems on [Project Euler](https://projecteuler.net/) for this purpose. # # There are a few other useful control structures. `try`-`except` lets you rescue a piece of code from an error, and `with` executes code between pre-defined code snippets. Consult docs for more info. # # <a name="numpy"></a> # ### NumPy # # NumPy is one of the most commonly used packages in Python, and is the basis for most of the numerics in Python. import numpy as np # NumPy has mathematical constants (which are also in the in-built `math` module). np.pi, np.e #for physical constants, see scipy.constants # The most useful feature of NumPy is the `ndarray` data type. This is a generalisation of a list to higher dimensions (a nested list). A list is essentially a vector, a list of lists, or a 2-D array, is a matrix. In general, an `ndarray` is nothing but a rank $n$ tensor. The function `array()` converts a list-like object to a NumPy array. a = np.array([1]) type(a) # There are many ways to construct arrays. np.ones(5) np.zeros((3,3,3)) np.empty((20,3)) #uses whatever values happen to be in memory. be careful! np.eye(2) #identity matrix np.arange(10) #numpy version of range np.diag(np.arange(4,-5,-2)) #diagonal matrix from 1d array np.linspace(0,1,21) #21 points evenly spaced between 0 and 1 # We can perform operations on arrays as if they were just numbers, and these operations are applied element-wise on the arrays. np.arange(10) + 5 np.linspace(-3, 4, 50) * (np.arange(50)+1) # Each `ndarray` has an a `shape` attribute, which is a tuple that specifies the length of the array in each axis. The first axis corresponds to the outermost list of a nested list. You can change the shape of an array using `reshape()`. a = np.arange(100) print(a.shape) a.reshape((-1,5,5)) #the -1 fills in for whatever value keeps the same total number of entries # NumPy arrays are indexed and sliced just like lists, except now indices can be specified for multiple axes at once. a = [[1,2], [3,4]] #nested list b = np.array(a) #convert list to ndarray a[1][0], b[1,0] a[0][::-1], b[0,::-1] # You can also slice arrays using an array of booleans, and using a list of indices. a = np.arange(10) a > 5 a[a>5] a = np.arange(16).reshape((4,4)) a[[1,0,3],2:] # Since arrays can be indices, one may chain indexing arrays ad infinitum. # + N = 15 #try changing these and running the next few cells x = 10 a = np.cos(np.linspace(0,x,N))**2 p = np.argsort(a) #this is a permutation array p # - a, a[p] #p is the permutation that sorts a p_inv = np.argsort(p) #inverse of permutation p_inv p_inv[p], p[p_inv] #identity permutation p[p][p][p][p][p][p][p] #p^8 # + #find period of permutation by brute force period = 1 identity = p[p_inv] power = p while np.any(power != identity): power = power[p] period += 1 period # - p[p][p][p][p][p][p][p][p][p][p][p][p][p][p][p][p][p] #checking # `ndarrays` are more restrictive than Python arrays. They are __typed__, which means all the entries must be of the same type. (The data type is implicitly understood when creating the array, but can be explicitly set using the `dtype` keyword.) Also the shape of an array is immutable, so the length of each axis is fixed, whereas nested lists have no such restriction in native Python. a.dtype # Higher-dimensional lists aren't stored contiguously in memory, whereas ndarrays are, which makes them faster. Another thing to keep in mind when iterating over multi-dimensional arrays is that the arrays are stored in a 1-dimensional representation (flattened), so looping over the last axis is faster since adjacent values are adjacent in memory. a.flatten() n = 100 a = np.arange(n**3).reshape((n,n,n)) start=time() for i in range(n):#loop last axis first for j in range(n): for k in range(n): a[k,j,i] check = time() for i in range(n):#loop last axis last for j in range(n): for k in range(n): a[i,j,k] end = time() print("Last axis first: %.3f sec\nLast axis last: %.3f sec"%(check-start, end-check)) # NumPy is written in C, which is a lower-level programming language than Python. This makes it much more efficient than Python. Lower-level languages give one more control while higher-level languages give convenience by hiding things in __black boxes__, i.e. by allowing you to use functions without knowing how they're implemented. If you're interested in making things run as efficiently as possible so that you can simulate larger systems more accurately, you might want to open these black boxes and maybe implement some things yourself. However the convenience of Python comes from the large number of packages that efficiently solve a lot of problems in the large variety of fields in which Python is widely used. Thus the Python paradigm is to not to reinvent the wheel, but we also recommend being aware of how things work under the hood so that you know which tool is best for a given problem. It's a fine line, and it's up to you to decide how you want to code. If you find yourself re-implementing things to make them faster, you might want to use a lower-level language like C. (You can also use your own implementations of things in other languages within Python for the best of both worlds.) # # Since NumPy data types are the same as those in C, they are different from native Python. Python resizes ints so that they can be arbitrarily large, whereas the default size of NumPy ints are 64 bits, which means they can store any value in `range(-2**63, 2**63)`. As for `float`s, NumPy also uses 64 bits by default, but has more options for precision (you can use 16, 32, 64, or 128 bits for floats or integers). a=np.array([2]) a[0]**63, int(a[0])**63, a**64, 2**64 #signed integers in C wrap around at the half-way point, so it effectively implements modular/periodic arithmetic # To see just how much faster NumPy is, let's compare the same task as we did earlier with list comprehensions: n = 10**6 #this is size of list, try changing this start = time() a = [i**2 for i in range(n)] #first time list comp checkpoint = time() a = np.arange(n)**2 #then time numpy end = time() print("List comprehension: %.4f sec\nNumPy: %.4f sec" % (checkpoint-start, end-checkpoint)) # Since NumPy is a lot faster, it is more efficient to reprogram all loops and list comprehensions into operations using NumPy arrays wherever possible. NumPy has implementations of standard functions like `exp()`, `log()`, `sin()`, `sqrt()`, etc. that work efficiently on arrays. NumPy and SciPy have virtually every tool that one might need, and have optimised these to work well with NumPy arrays. In order to rewrite all your loops into operations involving NumPy arrays to make your code more consistent, you might need to multiply arrays of different sizes. NumPy automatically handles this to some degree with a process known as _broadcasting_, which repeats an array of size 1 in a given dimension to match another array. We already saw an example of this when we added an `ndarray` to a scalar quantity. Consult docs for more info. print(np.arange(16).reshape((4,4))+np.arange(4)) print(np.arange(16).reshape((4,4))+np.arange(4).reshape((4,1))) print(np.arange(4).reshape((1,-1))+np.arange(4).reshape((-1,1))) # Once you get more familiar with NumPy, you might find that [the `einsum()` function](https://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html) is an easy way to input any array compuation. # <a name="jupyter"></a> # ### Jupyter notebooks # # The file you're interacting with is called a Jupyter notebook. Jupyter notebooks allow you to write, edit, and execute code in an interactive environemnt. A notebook is essentially a collection of cells. These cells can be executed in any order, but it is good practice, especially when sharing notebooks, to ensure that the cells are meant to be executed in order. You may want to familiarise yourself with the tools in the menus and toolbars. # # You can also press `tab` while typing to have the editor suggest names of standard functions, methods, modules, etc. It will also suggest keywords when entering the arguments to a function from a standard package, which is helpful if you don't remember how to supply the arguments required. np.li #press tab np.linspace( # Jupyter also uses IPython [_magics_](https://ipython.readthedocs.io/en/stable/interactive/magics.html), which are special functions accessed with `%`. For example, `%timeit` lets you time the execution of a line or cell of code without needing to import the `time` module. (Also see `%time`.) # %timeit np.sin(np.linspace(0,1,10**5)) #times execution of line # %%timeit #times execution of cell a = np.sin(np.linspace(0,1,10**5)) b = np.exp(a)+a**2 # In addition to cells containing code, there are also `Markdown` cells, which allow you to typeset text. This cell is a Markdown cell, for example. Double-click to edit and press `shift`+`enter` to display these cells, just like code cells. You can change the type of a cell using the dropdown menu in the toolbar above. Markdown cells also support $\LaTeX$, which is used for typesetting equations like $f(x) = \int_0^x e^{-t^2}\:dt$. If you're planning to do physics or mathematics, you'd probably want to learn it at some point. [Overleaf](https://www.overleaf.com/) is an online LaTeX editor which also has tutorials (and Berkeley students also get free Pro accounts that make it easier to collaborate). Markdown has a variety of formatting options, and is a superset of HTML so supports all HTML formatting abilities. # This notebook really just scratched the surface of what you can do with Jupyter. The web is full of useful information about using Jupyter notebooks in various ways, but knowing the information above (or its equivalent in another language) is more than enough for 209. If you'd like to look at another tutorial, [this one is quite good](https://www.dataquest.io/blog/jupyter-notebook-tutorial/). # # Finally, the kernels which run the code can be changed without changing the notebook, and while Jupyter was created for Julia, Python and R (hence the name), [many languages](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels) now have Jupyter kernels. Jupyter notebooks are an effective method of working and sharing small pieces of interactive code, which is why I will distribute some "extension material" in this form.
IntroToPython.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- # ## Calculate correlation between NEMO and TAO zonal averages # + import sys sys.path.append('../') import matplotlib.pyplot as plt import numpy as np import xarray as xr from numpy import pi import scipy.io as sio import matplotlib.colors as Colors # %matplotlib inline import warnings import numpy.polynomial as poly from tools.transform_tools import * from tools.data_processing_tools import * from tools.theoretical_tools import * warnings.filterwarnings('ignore') plt.rcParams.update({'font.size': 16}) plt.rcParams['figure.figsize'] = (10, 5) plt.rcParams['text.usetex'] = False # %load_ext autoreload # %autoreload 2 # + # ---------------- load in TAO and NEMO data ----------------- # Load in TAO dynamic height data t_TAO, lat_TAO, lon_TAO, lon_TAO_midpoints, D_TAO, ds_TAO = load_TAO(NEMO_year=True) # Load in all NEMO data, sampled to TAO locations, at the equator t, lat_NEMO, lon_NEMO, D_NEMO, ds_NEMO= load_NEMO(daily_mean=True,lats=lat_TAO,lons=lon_TAO, winds=False) # Remove datapoints in dynamic height and wind stress where TAO data is missing D_NEMO = np.where(np.isnan(D_TAO),np.nan,D_NEMO) # + # Two stage high pass filter, then zonal average of dynamic height. First pass at 20 days smooth_N = 21 # Rolling mean window length for first high pass NSR = 35 # Noise to signal ratio cutoff = 20 # Cutoff period in days for low pass filter # First remove a rolling mean of length smooth_N D_NEMO_hf1 = D_NEMO - smooth(D_NEMO,smooth_N) D_TAO_hf1 = D_TAO - smooth(D_TAO,smooth_N) # Then fit temporal modes to this and cutoff at 20 days to give a low pass filter D_NEMO_lf = least_squares_spectrum_t_multi(D_NEMO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_NEMO_hf = D_NEMO_hf1 - D_NEMO_lf D_NEMO_hf -= np.nanmean(D_NEMO_hf,axis=0) D_TAO_lf = least_squares_spectrum_t_multi(D_TAO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_TAO_hf = D_TAO_hf1 - D_TAO_lf D_TAO_hf -= np.nanmean(D_TAO_hf,axis=0) # Zonally average D_NEMO_hf_za = np.nanmean(D_NEMO_hf,axis=2) D_TAO_hf_za = np.nanmean(D_TAO_hf,axis=2) # - corr_20day = np.zeros_like(lat_TAO) for i in range(corr_20day.shape[0]): corr_20day[i] = np.corrcoef(D_NEMO_hf_za[:,i], D_TAO_hf_za[:,i])[0,1] # + # Two stage high pass filter, then zonal average of dynamic height. Now pass at 50 days smooth_N = 51 # Rolling mean window length for first high pass NSR = 35 # Noise to signal ratio cutoff = 50 # Cutoff period in days for low pass filter # First remove a rolling mean of length smooth_N D_NEMO_hf1 = D_NEMO - smooth(D_NEMO,smooth_N) D_TAO_hf1 = D_TAO - smooth(D_TAO,smooth_N) # Then fit temporal modes to this and cutoff at 20 days to give a low pass filter D_NEMO_lf = least_squares_spectrum_t_multi(D_NEMO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_NEMO_hf = D_NEMO_hf1 - D_NEMO_lf D_NEMO_hf -= np.nanmean(D_NEMO_hf,axis=0) D_TAO_lf = least_squares_spectrum_t_multi(D_TAO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_TAO_hf = D_TAO_hf1 - D_TAO_lf D_TAO_hf -= np.nanmean(D_TAO_hf,axis=0) # Zonally average D_NEMO_hf_za = np.nanmean(D_NEMO_hf,axis=2) D_TAO_hf_za = np.nanmean(D_TAO_hf,axis=2) # - corr_50day = np.zeros_like(lat_TAO) for i in range(corr_50day.shape[0]): corr_50day[i] = np.corrcoef(D_NEMO_hf_za[:,i], D_TAO_hf_za[:,i])[0,1] # + # Two stage high pass filter, then zonal average of dynamic height. Now pass at 50 days smooth_N = 101 # Rolling mean window length for first high pass NSR = 35 # Noise to signal ratio cutoff = 100 # Cutoff period in days for low pass filter # First remove a rolling mean of length smooth_N D_NEMO_hf1 = D_NEMO - smooth(D_NEMO,smooth_N) D_TAO_hf1 = D_TAO - smooth(D_TAO,smooth_N) # Then fit temporal modes to this and cutoff at 20 days to give a low pass filter D_NEMO_lf = least_squares_spectrum_t_multi(D_NEMO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_NEMO_hf = D_NEMO_hf1 - D_NEMO_lf D_NEMO_hf -= np.nanmean(D_NEMO_hf,axis=0) D_TAO_lf = least_squares_spectrum_t_multi(D_TAO_hf1, t, NSR=NSR, reconstruct_min_period = cutoff)[2] D_TAO_hf = D_TAO_hf1 - D_TAO_lf D_TAO_hf -= np.nanmean(D_TAO_hf,axis=0) # Zonally average D_NEMO_hf_za = np.nanmean(D_NEMO_hf,axis=2) D_TAO_hf_za = np.nanmean(D_TAO_hf,axis=2) # - corr_100day = np.zeros_like(lat_TAO) for i in range(corr_100day.shape[0]): corr_100day[i] = np.corrcoef(D_NEMO_hf_za[:,i], D_TAO_hf_za[:,i])[0,1]
code/analysis_notebooks/correlation_stats.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # For dentro de For # # Quando temos listas dentro de listas, às vezes precisamos fazer um "for dentro de for" # + active="" # for item in lista: # for item2 in lista2: # codigo aqui # - # Vamos pegar um exemplo de nível mínimo de estoque. Em uma fábrica você tem vários produtos e não pode deixar que os produtos fiquem em falta. Para isso, foi definido uma quantidade mínima de estoque que os produtos precisam ter: # # Identifique quais fábricas tem algum produto abaixo do nível de estoque # # - Agora ao invés de analisar o estoque de apenas 1 fábrica, vamos analisar o estoque de várias fábricas # + estoque = [ [294, 125, 269, 208, 783, 852, 259, 371, 47, 102, 386, 87, 685, 686, 697, 941, 163, 631, 7, 714, 218, 670, 453], [648, 816, 310, 555, 992, 643, 226, 319, 501, 23, 239, 42, 372, 441, 126, 645, 927, 911, 761, 445, 974, 2, 549], [832, 683, 784, 449, 977, 705, 198, 937, 729, 327, 339, 10, 975, 310, 95, 689, 137, 795, 211, 538, 933, 751, 522], [837, 168, 570, 397, 53, 297, 966, 714, 72, 737, 259, 629, 625, 469, 922, 305, 782, 243, 841, 848, 372, 621, 362], [429, 242, 53, 985, 406, 186, 198, 50, 501, 870, 781, 632, 781, 105, 644, 509, 401, 88, 961, 765, 422, 340, 654], ] fabricas = ['Lira Manufacturing', 'Fábrica Hashtag', 'Python Manufaturas', 'Produções e Cia', 'Manufatura e Cia'] nivel_minimo = 50 fabricas_baixo = [] for i, lista in enumerate(estoque): #se dentro daquela lista tem alguem abaixo do nível minimo for qtde in lista: if qtde <= nivel_minimo: if fabricas[i] in fabricas_baixo: pass else: fabricas_baixo.append(fabricas[i]) print(fabricas_baixo)
Arquivo aulas/Modulo 6/MOD6-Aula6(listaauxiliar).ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Metrics # - measuring different phases # - panda: format, save, plotting # - clustering # %matplotlib inline import numpy as np from matplotlib import pyplot as plt import itk import itkwidgets from itkwidgets import view, compare # read one phase img = itk.imread('/Users/dani/Documents/data/synthetic/original/segmented_bead_pack_512.tif') # ## Measuring different phases myViewer = view(img, mode='z') #slicing over z myViewer import math import pandas as pd from skimage import io from skimage.measure import regionprops, label class MyMeasurements: def __init__(self,inputs,outputs): '''Input and output paths ''' self.inputp = inputs #path ???? self.outputp = outputs #path self.img = io.imread(inputs) def measurements(self,nslice=1): '''Extract area and circularity from binary input''' labeled = label(255-self.img[nslice,:,:]) regions = regionprops(labeled) pixelSize = 1 #check this with Tonya/Rana larea=[] lcircularity=[] labels = np.arange(np.max(labeled) + 1) for region in regions: area = float(region.area * pixelSize**2) circularity = 4*math.pi*(region.area/region.perimeter**2) if not (100 <= area <= 10000 and circularity > 0.5): labels[region.label] = 0 else: larea.append(area) lcircularity.append(circularity) finalMask = labels[labeled] >0 sampleMetr = pd.DataFrame({ 'area':larea, 'circularity':lcircularity }) self.sampleMetr =sampleMetr def histMeasurements(self,mybin=10): '''Show histogram of area and circularity''' fig = plt.figure(figsize = (15,2.5)) ax = fig.gca() self.sampleMetr.hist(bins=mybin,density=False,facecolor='g', alpha=0.75,ax = ax) myM = MyMeasurements('/Users/dani/Documents/data/synthetic/original/segmented_bead_pack_512.tif','/Users/dani/Documents/data/synthetic/original/') myDF = myM.measurements(nslice=10) myM.histMeasurements()
code/04_metricsML.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #As seen from the results below, this table is unwieldy and difficult to use for our requirments. #Therefore, this script/notebook contains scripts to convert the source data into a form we like and as described in our reports. #The data we get from this notebook is used to populate our database # - import pandas as pd df = pd.read_csv('sourcedata/data_from_source.csv') pdDF = pd.read_csv('tablepoliceDivision.csv') # + df.columns.tolist() # - df22 = df[[ "occurrencehour", "occurrenceday","occurrencemonth", "occurrenceyear", "occurrencedayofweek"]] df12 = df[["reportedhour", "reportedday","reportedmonth", "reportedyear", "reporteddayofweek"]] df12.rename(columns={"reportedhour":"occurrencehour","reportedday":"occurrenceday","reportedmonth":"occurrencemonth","reportedyear":"occurrenceyear","reporteddayofweek":"occurrencedayofweek"}, inplace=True) df2 = df22.append(df12) df2 = df2.drop_duplicates() df2 = df2.rename_axis('timeID').reset_index() df2['timeID'] += 600000 df2.to_csv("tableTime.csv") print(df2) # + df3 = df[["Hood_ID", "Neighbourhood", "Division"]] df3 = df3.drop_duplicates() df3 = df3.rename_axis('locationID').reset_index() df3['locationID'] += 300000 print(df3) # - df4 = df[[ "offence", "MCI"]] df4 = df4.drop_duplicates() df4 = df4.rename_axis('crimeID').reset_index() df4['crimeID'] += 100000 df4.to_csv("tableCrime.csv") print(df4) df5 = df.merge(df4, on=['offence','MCI'] ) df6 = df5.merge(df3, on=["Hood_ID", "Neighbourhood"]) df7 = df6.merge(df2, on=["occurrencehour", "occurrenceday","occurrencemonth", "occurrenceyear", "occurrencedayofweek"]) df13 = df2.copy() df13.rename(columns={'timeID': 'reportedTimeID',"occurrencehour":"reportedhour","occurrenceday":"reportedday","occurrencemonth":"reportedmonth","occurrenceyear":"reportedyear","occurrencedayofweek":"reporteddayofweek"}, inplace=True) df14 = df13.merge(df7, on=["reportedhour", "reportedday","reportedmonth", "reportedyear", "reporteddayofweek"]) df14 = df14[['event_unique_id','crimeID','locationID','timeID','reportedTimeID', "Long", "Lat","premisetype"]] print(df14) df14.to_csv("tableEvent.csv") df3['Neighbourhood'] = [i.split('(')[0] for i in df3['Neighbourhood']] df3.to_csv("tableNeighbourhood.csv") print(df3)
milestones/Milestone_2/data/scripts/DataParser.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 (ipykernel) # language: python # name: python3 # --- from datetime import date import numpy as np import pandas as pd import seaborn as sns DATA_DIR = '/home/ubuntu/data/' COVID_DATA_DIR = f'{DATA_DIR}/covid' ECON_DATA_DIR = f'{DATA_DIR}/patterns' # ### % of population with Covid-like symptoms in each location daily covidlike_pct = pd.read_csv(f'{COVID_DATA_DIR}/covidlike_pct.csv') covidlike_pct.head() states_count = covidlike_pct.geo_value.nunique() # #### Daily ranges covidlike_pct_daily_ranges = pd.DataFrame(columns=['min', 'median', 'mean', 'max']) covidlike_pct_daily_ranges['min'] = covidlike_pct.groupby('time_value').covidlike_pct.min() covidlike_pct_daily_ranges['median'] = covidlike_pct.groupby('time_value').covidlike_pct.median() covidlike_pct_daily_ranges['mean'] = covidlike_pct.groupby('time_value').covidlike_pct.mean() covidlike_pct_daily_ranges['max'] = covidlike_pct.groupby('time_value').covidlike_pct.max() ax = sns.lineplot(data=covidlike_pct_daily_ranges) ax.set_xticks([]) # #### Patterns by state covidlike_pct_state_means = covidlike_pct.groupby('geo_value').covidlike_pct.mean().sort_values() states = [covidlike_pct_state_means.index[0], covidlike_pct_state_means.index[int(states_count/4)], covidlike_pct_state_means.index[int(states_count/2)], covidlike_pct_state_means.index[int(states_count*0.75)], covidlike_pct_state_means.index[-1]] covidlike_pct_state_dailies = pd.DataFrame(columns=states) for s in states: covidlike_pct_state_dailies[s] = covidlike_pct.loc[covidlike_pct.geo_value == s].reset_index().covidlike_pct sns.lineplot(data=covidlike_pct_state_dailies) # ### Number of new confirmed COVID-19 cases per 100,000 population, daily cases_per_100k = pd.read_csv(f'{COVID_DATA_DIR}/cases_per_100k.csv') cases_per_100k.shape cases_per_100k.head() cases_per_100k.describe() (cases_per_100k.cases_per_100k < 0).sum() # ### Estimated percentage of people who wore a mask most or all the time in public in the past 7 days f'{DATA_DIR}/mask_pct.csv' # ### Estimated percentage of respondents who have already received a vaccine for COVID-19 f'{DATA_DIR}/vaxxed_pct.csv'
notebooks/yffl/EDA.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # <a href="https://qworld.net" target="_blank" align="left"><img src="../qworld/images/header.jpg" align="left"></a> # $$ # \newcommand{\set}[1]{\left\{#1\right\}} # \newcommand{\abs}[1]{\left\lvert#1\right\rvert} # \newcommand{\norm}[1]{\left\lVert#1\right\rVert} # \newcommand{\inner}[2]{\left\langle#1,#2\right\rangle} # \newcommand{\bra}[1]{\left\langle#1\right|} # \newcommand{\ket}[1]{\left|#1\right\rangle} # \newcommand{\braket}[2]{\left\langle#1|#2\right\rangle} # \newcommand{\ketbra}[2]{\left|#1\right\rangle\left\langle#2\right|} # \newcommand{\angleset}[1]{\left\langle#1\right\rangle} # \newcommand{\expected}[1]{\left\langle#1\right\rangle} # \newcommand{\dv}[2]{\frac{d#1}{d#2}} # \newcommand{\real}[0]{\mathfrak{Re}} # $$ # # Worked Example # # _prepared by <NAME>_ # Let # # \begin{equation*} # \begin{split} # B &= \set{\ket{0}, \ket{1}, \ket{2}} \enspace \text{(orthonormal base of } {}_\mathbb{C}\mathbb{C}^3)\\ # \hat{H} &= \ketbra{0}{0} + i\ketbra{1}{2} - i\ketbra{2}{1} \enspace \text{(hamiltonian)} \\ # \hat{A} &= \ketbra{0}{0} + \ketbra{1}{1} + 3\ketbra{2}{2} - 2\ketbra{0}{1} - 2\ketbra{1}{0} \enspace \text{(observable)} \\ # \ket{\psi(0)} &= N(\ket{0} - 2\ket{1} + i\ket{2}) \enspace \text{(initial state)} # \end{split} # \end{equation*} # # where an observable corresponds to a measurable physical magnitude of the system being modeled and $N$ is the normalization coefficient. These observables are self-adjoint operators and the Hamiltonian is one of those observables that corresponds to the energy of the system. # # Here, we want to know # # 1. What is the value of $N$? # 2. What are the possible values that we can get from measuring $\hat{A}$ and with what probability can we get them at time $t=0$? # 3. What is the value of $\ket{\psi(t)}$ at an arbitrary time $t$? # 4. What is the probability $P(a_i)_t$ of measuring each eigenvalue $a_i$ of $\hat{A}$ at time $t$? # 5. If when measuring $\hat{A}$ at time $t=0$ we get the eigenvalue $a_2$ (or $a_3$), what is the status of the system immediately after the measurement? # ### <a name="1">Normalization constant</a> # # 1. What is the value of $N$? # # Let us recall that by <a href="./Postulates.ipynb#definition_3_1">Postulate I</a> the states of the system are unit vectors and furthermore they are invariant with respcet to global phases. Thus # # \begin{equation*} # \begin{split} # 1 &= \braket{\psi(0)}{\psi(0)} \\ # &= N^*(\bra{0} - 2\bra{1} - i\bra{2}) N(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= N^*N(\braket{0}{0} + 4\braket{1}{1} + \braket{2}{2}) \\ # &= \abs{N}^2(1+4+1) \\ # &= 6\abs{N}^2 \\ # \implies \abs{N}^2 &= \frac{1}{6} \\ # \implies N &= \frac{1}{\sqrt{6}} # \end{split} # \end{equation*} # # Since by the global phase invariance we can think that $N \in \mathbb{R}$. Therefore # # \begin{equation}\label{fi_t0} # \ket{\psi(0)} = \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) # \end{equation} # ### <a name="2">Observables and their probabilities at the initial state</a> # # 2. What are the possible values that we can get from measuring $\hat{A}$ and with what probability can we get them at time $t=0$? # # Recall that by <a href="./Postulates.ipynb#definition_3_1">Postulate IV</a> the observables are self-adjoint operators and the results of measurements of that operator correspond to eigenvalues of the operator. # # Since $\hat{A} = \ketbra{0} + \ketbra{1} + 3\ketbra{2} - 2\ketbra{0}{1} - 2\ketbra{1}{0}$, we can view it in matrix form to calculate its eigenvalues more easily, using the method described <a href="../2-math/SpectralTheory.ipynb#examples">here</a> # # \begin{equation*} # \hat{A} = \begin{pmatrix} # 1 & -2 & 0 \\ # -2 & 1 & 0 \\ # 0 & 0 & 3 # \end{pmatrix} # \end{equation*} # # It is clear that $\hat{A}$ is self-adjoint since $A = A^\dagger = (A^\top)^*$, so the associated eigenvalues and eigenvectors are: # # \begin{equation*} # \begin{split} # a_1 = -1 \qquad&\qquad \ket{a_1} = \frac{1}{\sqrt{2}}(\ket{0} + \ket{1}) \\ # a_2 = 3 \qquad&\qquad \ket{a_2} = \frac{1}{\sqrt{2}}(\ket{0} - \ket{1}) \\ # a_3 = 3 \qquad&\qquad \ket{a_3} = \ket{2} # \end{split} # \end{equation*} # # From this, the possible values that we can get by measuring $\hat{A}$ are $-1$ and $3$. Now, by <a href="./Postulates.ipynb#definition_3_1">Postulate V</a>: # # - Since $a_1$ has multiplicity $1$, from the calculation for the normalization constant we have that # # \begin{equation}\label{prob_a1} # \begin{split} # P(a_1)_{t=0} &= \abs{\braket{a_1}{\psi(0)}}^2 \\ # &= \abs{\frac{1}{\sqrt{2}}(\bra{0} + \bra{1}) \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2})}^2 \\ # &= \abs{\frac{1}{\sqrt{12}}(\braket{0}{0} - 2\braket{1}{1})}^2 \\ # &= \abs{\frac{-1}{\sqrt{12}}}^2 = \frac{1}{12} # \end{split} # \end{equation} # # - Since eigenvalue $3$ has multiplicity $2$ we have # # \begin{equation}\label{prob_a2} # \begin{split} # P(a_2)_{t=0} = P(a_3)_{t=0} &= \abs{\braket{a_2}{\psi(0)}}^2 + \abs{\braket{a_3}{\psi(0)}}^2 \\ # &= \abs{\frac{1}{\sqrt{2}}(\bra{0} - \bra{1})\frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2})}^2 \\ # &+ \abs{\bra{2} \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2})}^2 \\ # &= \abs{\frac{1}{\sqrt{12}}(\braket{0}{0} + 2\braket{1}{1})}^2 + \abs{\frac{1}{\sqrt{6}}i\braket{2}{2}}^2 \\ # &= \abs{\frac{3}{\sqrt{12}}}^2 + \abs{\frac{i}{\sqrt{6}}}^2 \\ # &= \frac{9}{12} + \frac{1}{6} = \frac{11}{12} # \end{split} # \end{equation} # # Note that since we only have two different eigenvalues: $P(a_2)_{t=0} = P(a_3)_{t=0} = 1 - P(a_1)_{t=0}$. # ### <a name="3">Time evolution</a> # # 3. What is the value of $\ket{\psi(t)}$ at an arbitrary time $t$? # # Let us remember that by <a href="./Postulates.ipynb#definition_3_1">Postulate VII</a> and <a href="./TimeEvolution.ipynb#remark_3_4">Remark 3.4</a>, we need to apply the time evolution operator. Therefore we can write $\ket{\psi(t)}$ at time $t=0$ as # # \begin{equation*} # \ket{\psi(t)} = e^{-\frac{i}{\hbar}t\hat{H}}\ket{\psi(0)} # \end{equation*} # # We also know that # # \begin{equation*} # \hat{H} = \ketbra{0} + i\ketbra{1}{2} - i\ketbra{2}{1} # \end{equation*} # # Let's write $\hat{H}$ in its matrix form to calculate its eigenvalues and eigenvectors # # \begin{equation*} # \begin{pmatrix} # 1 & 0 & 0 \\ # 0 & 0 & i \\ # 0 &-i & 0 # \end{pmatrix} # \end{equation*} # # In this way, it is clear that $\hat{H}$ is self-adjoint since $\hat{H} = (\hat{H}^\top)^*$, so the associated eigenvalues and eigenvectors are: # # \begin{equation*} # \begin{split} # \varepsilon_1 = 1 \qquad&\qquad \ket{\varepsilon_1} = \ket{0} \\ # \varepsilon_2 = 1 \qquad&\qquad \ket{\varepsilon_2} = \frac{1}{\sqrt{2}}(\ket{1} + i\ket{2}) \\ # \varepsilon_3 = -1 \qquad&\qquad \ket{\varepsilon_3} = \frac{1}{\sqrt{2}}(\ket{1} - i\ket{2}) # \end{split} # \end{equation*} # # Note that $E=\set{\ket{\varepsilon_1}, \ket{\varepsilon_2}, \ket{\varepsilon_3}}$ is also an orthonormal basis for the space since $\hat{H}$ is self-adjoint. # # Now, in order to apply the time evolution operator we need to express $\ket{\psi(0)}$ in terms of the base $E$, that is, in terms of the eigenvectors of $\hat{H}$. For this, let's consider that by <a href="../2-math/SpectralTheory.ipynb#definition_2_21">Definition 2.21</a> we have that # # \begin{equation*} # \sum_{j=1}^{3}\ketbra{\varepsilon_j}{\varepsilon_j} = I # \end{equation*} # # So, if we apply this form of the identity operator to $\ket{\psi(0)}$ we have that # # \begin{equation*} # \ket{\psi(0)} = \sum_{j=1}^{3}\ket{\varepsilon_j}\braket{\varepsilon_j}{\psi(0)} # \end{equation*} # # Thus, we can express $\ket{\psi(0)}$ in terms of the base $E$ # # \begin{equation*} # \begin{split} # \braket{\varepsilon_1}{\psi(0)} &= \bra{0} \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= \frac{1}{\sqrt{6}}(\braket{0}{0}) = \frac{1}{\sqrt{6}} \\ # \braket{\varepsilon_2}{\psi(0)} &= \frac{1}{\sqrt{2}}(\bra{1} + i\bra{2}) \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= \frac{1}{\sqrt{12}}(-2\braket{1}{1} - \braket{2}{2}) = \frac{-3}{\sqrt{12}} \\ # \braket{\varepsilon_3}{\psi(0)} &= \frac{1}{\sqrt{2}}(\bra{1} - i\bra{2}) \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= \frac{1}{\sqrt{12}}(-2\braket{1}{1} + \braket{2}{2}) = \frac{-1}{\sqrt{12}} \\ # \implies \ket{\psi(0)} &= \frac{1}{\sqrt{6}}\ket{\varepsilon_1} - \frac{3}{\sqrt{12}}\ket{\varepsilon_2} - \frac{1}{\sqrt{12}}\ket{\varepsilon_3} # \end{split} # \end{equation*} # # From this expression we can see that $\ket{\psi(0)}$ is unitary, and with $\ket{\psi(0)}$ expressed as a linear combination of the eigenvectors of $\hat{H}$ we can apply the time evolution operator as we obtained it in <a href="./TimeEvolution.ipynb#remark_3_4">Remark 3.4</a> and in this way we have # # \begin{equation*} # \begin{split} # \ket{\psi(t)} &= e^{-\frac{i}{\hbar}t\hat{H}}\left(\frac{1}{\sqrt{6}}\ket{\varepsilon_1} - \frac{3}{\sqrt{12}}\ket{\varepsilon_2} - \frac{1}{\sqrt{12}}\ket{\varepsilon_3}\right) \\ # &= \frac{1}{\sqrt{6}}e^{-\frac{i}{\hbar}t\hat{H}}\ket{\varepsilon_1} - \frac{3}{\sqrt{12}}e^{-\frac{i}{\hbar}t\hat{H}}\ket{\varepsilon_2} - \frac{1}{\sqrt{12}}e^{-\frac{i}{\hbar}t\hat{H}}\ket{\varepsilon_3} # \end{split} # \end{equation*} # # Now, if we consider $f(x) = e^x$, from <a href="./TimeEvolution.ipynb#proposition_3_5">Proposition 3.5</a> we have that $e^{\hat{H}}\ket{\varepsilon_j} = e^{\varepsilon_j}\ket{\varepsilon_j}, j \in \set{1,2,3}$. Therefore # # \begin{equation}\label{estado_t} # \ket{\psi(t)} = \frac{1}{\sqrt{6}}e^{-\frac{i}{\hbar}t}\ket{\varepsilon_1} - \frac{3}{\sqrt{12}}e^{-\frac{i}{\hbar}t}\ket{\varepsilon_2} - \frac{1}{\sqrt{12}}e^{\frac{i}{\hbar}t}\ket{\varepsilon_3} # \end{equation} # # If necessary, we can rewrite $\ket{\psi(t)}$ in terms of base $B$, but this expression that we obtained already answers the question asked. # ### <a name="4">Observables and their probabilities at an arbitrary time</a> # # 4. What is the probability $P(a_i)_t$ of measuring each eigenvalue $a_i$ of $\hat{A}$ at time $t$? # # By <a href="./Postulates.ipynb#definition_3_1">Postulate V</a> and the calculation we just did for $\ket{\psi(t)}$ we know that # # \begin{equation*} # \begin{split} # P(a_1)_t &= \abs{\braket{a_1}{\psi(t)}}^2 \\ # &= \abs{\bra{a_1}\left(\frac{1}{\sqrt{6}}e^{-\frac{i}{\hbar}t}\ket{\varepsilon_1} - \frac{3}{\sqrt{12}}e^{-\frac{i}{\hbar}t}\ket{\varepsilon_2} - \frac{1}{\sqrt{12}}e^{\frac{i}{\hbar}t}\ket{\varepsilon_3}\right)}^2 \\ # &= \abs{\frac{1}{\sqrt{6}}e^{-\frac{i}{\hbar}t}\braket{a_1}{\varepsilon_1} - \frac{3}{\sqrt{12}}e^{-\frac{i}{\hbar}t}\braket{a_1}{\varepsilon_2} - \frac{1}{\sqrt{12}}e^{\frac{i}{\hbar}t}\braket{a_1}{\varepsilon_3}}^2 \\ # \end{split} # \end{equation*} # # Calculating the inner products # # \begin{equation*} # \begin{split} # \braket{a_1}{\varepsilon_1} &= \frac{1}{\sqrt{2}}(\bra{0} + \bra{1}) \ket{0} = \frac{1}{\sqrt{2}}(\braket{0}{0}) = \frac{1}{\sqrt{2}} \\ # \braket{a_1}{\varepsilon_2} &= \frac{1}{\sqrt{2}}(\bra{0} + \bra{1}) \frac{1}{\sqrt{2}}(\ket{1} + i\ket{2}) = \frac{1}{2}\braket{1}{1} = \frac{1}{2} \\ # \braket{a_1}{\varepsilon_3} &= \frac{1}{\sqrt{2}}(\bra{0} + \bra{1}) \frac{1}{\sqrt{2}}(\ket{1} - i\ket{2}) = \frac{1}{2}\braket{1}{1} = \frac{1}{2} # \end{split} # \end{equation*} # $\implies$ # \begin{equation*} # \begin{split} # P(a_1)_t &= \abs{\frac{1}{\sqrt{6}}\frac{1}{\sqrt{2}}e^{-\frac{i}{\hbar}t} - \frac{3}{\sqrt{12}}\frac{1}{2}e^{-\frac{i}{\hbar}t} - \frac{1}{\sqrt{12}}\frac{1}{2}e^{\frac{i}{\hbar}t})}^2 \\ # &= \abs{\frac{1}{\sqrt{12}}e^{-\frac{i}{\hbar}t} - \frac{3}{2\sqrt{12}}e^{-\frac{i}{\hbar}t} - \frac{1}{2\sqrt{12}}e^{\frac{i}{\hbar}t})}^2 \\ # &= \abs{\underbrace{-\frac{1}{2\sqrt{12}}e^{-\frac{i}{\hbar}t}}_{z} \underbrace{-\frac{1}{2\sqrt{12}}e^{\frac{i}{\hbar}t}}_{z^*}}^2 = \abs{\underbrace{-\frac{1}{\sqrt{12}}\cos\left(\frac{t}{\hbar}\right)}_{2\real(z)}}^2 \\ # &= \frac{1}{12}\cos^2\left(\frac{t}{\hbar}\right) # \end{split} # \end{equation*} # # Since $z + z^* = 2\real(z) \forall z \in \mathbb{C}$, that is # # \begin{equation*} # z = -\frac{1}{2\sqrt{12}}e^{-i\frac{t}{\hbar}} = -\frac{1}{2\sqrt{12}}\left(\cos\left(-\frac{t}{\hbar}\right) + i\sin\left(-\frac{t}{\hbar}\right)\right) \implies 2\real(z) = -\frac{1}{\sqrt{12}}\cos\left(\frac{t}{\hbar}\right) # \end{equation*} # # since cosine is an even function. Therefore # # \begin{equation}\label{pa1} # P(a_1)_t = \frac{1}{12}\cos^2\left(\frac{t}{\hbar}\right) # \end{equation} # # Which makes sense with what we find in <a href="#2">Observables and their probabilities at the initial state</a>, because if in this last equation we substitute $t=0$ we have # # \begin{equation*} # P(a_1)_{t=0} = \frac{1}{12}\cos^2(0) = \frac{1}{12} # \end{equation*} # # We can also observe that for certain values of $t$ this probability will be $0$ and the maximum value that it will have is precisely $\frac{1}{12}$. # # On the other hand, since we are calculating the probability of two different eigenvalues # # \begin{equation*} # P(a_2)_t = P(a_3)_t = 1-P(a_1)_t = 1 - \frac{1}{12}cos^2\left(\frac{t}{\hbar}\right) = \frac{11}{12} + \frac{1}{12}\sin^2\left(\frac{t}{\hbar}\right) # \end{equation*} # # Which is also congruent with what we found in <a href="#2">Observables and their probabilities at the initial state</a>, because if we substitute $t=0$ we have # # \begin{equation*} # P(a_2)_{t=0} = \frac{11}{12} + \frac{1}{12}\sin^2(0) = \frac{11}{12} # \end{equation*} # # Note that this is the minimum value that it can take and for certain values of $t$ this probability can be $1$. # ### <a name="5">Wave function collapse</a> # # 5. If when measuring $\hat{A}$ at time $t=0$ we get the eigenvalue $a_2$ (or $a_3$), what is the status of the system immediately after the measurement? # # By <a href="./Postulates.ipynb#definition_3_1">Postulate VI</a> we must calculate the normalized projection to the subspace generated by the eigenvectors associated with the eigenvalue. From the calculation of the <a href="#1">Normalization constant</a>, at time $t=0$ we know that # # \begin{equation*} # \ket{\psi(0)} = \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) # \end{equation*} # # We have to project this vector to the subspace generated by $\set{\ket{a_2}, \ket{a_3}}$ using the projection operator # # \begin{equation*} # \hat{P} = \ketbra{a_2}{a_2} + \ketbra{a_3}{a_3} # \end{equation*} # # Which is a particular case of the <a href="../2-math/SpectralTheory.ipynb#definition_2_21">Definition 2.21</a>, since in the Completeness Relation we project over the entire space or rather, over the vectors that make up an orthonormal basis of the space, hence obtain the identity, in this case we are interested in doing it only on the eigenvectors associated with the measured eigenvalue. # After that, we need to renormalize the resulting vector since the projection can change the size of the vector. In short, what we need to do is # # \begin{equation*} # \ket{\psi(0)} \xrightarrow{\text{after measurement}} \frac{\hat{P}\ket{\psi(0)}}{\sqrt{P(a_2)_{t=0}}} # \end{equation*} # # That is # # \begin{equation*} # \hat{P}\ket{\psi(0)} = \ket{a_2}\braket{a_2}{\psi(0)} + \ket{a_3}\braket{a_3}{\psi(0)} # \end{equation*} # # Calculating # # \begin{equation*} # \begin{split} # \braket{a_2}{\psi(0)} &= \frac{1}{\sqrt{2}}(\bra{0} - \bra{1}) \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= \frac{1}{\sqrt{12}}(\braket{0}{0} + 2\braket{1}{1}) = \frac{3}{\sqrt{12}} \\ # \braket{a_3}{\psi(0)} &= \bra{2} \frac{1}{\sqrt{6}}(\ket{0} - 2\ket{1} + i\ket{2}) \\ # &= \frac{1}{\sqrt{6}}(i\braket{2}{2}) = \frac{i}{\sqrt{6}} # \end{split} # \end{equation*} # # Where # # \begin{equation*} # \hat{P}\ket{\psi(0)} = \frac{3}{\sqrt{12}}\ket{a_2} + \frac{i}{\sqrt{6}}\ket{a_3} # \end{equation*} # # Renormalizing # # \begin{equation*} # \begin{split} # \frac{\hat{P}\ket{\psi(0)}}{\sqrt{P(a_2)_{t=0}}} &= \frac{\hat{P}\ket{\psi(0)}}{\sqrt{\frac{11}{12}}} \\ # &= \sqrt{\frac{12}{11}}\left(\frac{3}{\sqrt{12}}\ket{a_2} + \frac{i}{\sqrt{6}}\ket{a_3}\right) \\ # &= \frac{\sqrt{12}}{\sqrt{11}}\frac{3}{\sqrt{12}}\ket{a_2} + \frac{\sqrt{2}\sqrt{6}}{\sqrt{11}}\frac{i}{\sqrt{6}}\ket{a_3} \\ # &= \frac{3}{\sqrt{11}}\ket{a_2} + \frac{i\sqrt{2}}{\sqrt{11}}\ket{a_3} # \end{split} # \end{equation*} # # Therefore the state of the system immediately after having measured the eigenvalue $a_2$ (or $a_3$) is # # \begin{equation*} # \frac{3}{\sqrt{11}}\ket{a_2} + \frac{i\sqrt{2}}{\sqrt{11}}\ket{a_3} # \end{equation*} # ### Task 1. # # A physical system is described at time $t=0$ by the state # # \begin{equation*} # \ket{\psi(0)} = \frac{1}{\sqrt{2}}(\ket{01} + i\ket{10}) \in \mathbb{B}^{\otimes 2} # \end{equation*} # # The evolution of the system is given by the Hamiltonian # # \begin{equation*} # \mathcal{H} = \varepsilon(\sigma_x \otimes \sigma_z), \quad \varepsilon \in \mathbb{R} # \end{equation*} # # Let us consider the observable # # \begin{equation*} # \mathcal{A} = a(\sigma_y \otimes \sigma_x), \quad a \in \mathbb{R}^+ # \end{equation*} # # What are the possible values that can be obtained by measuring $\mathcal{A}$? # # <a href="./WorkedExample_Solutions.ipynb#task_1">Click here for solution</a> # ### Task 2. # # Find the probability of measuring at time $t=0$ each of the values found in **Task 1**. # # <a href="./WorkedExample_Solutions.ipynb#task_2">Click here for solution</a> # ### Task 3. # # Find the probability of measuring at an arbitrary time $t$ each of the values found in **Task 1**. # # <a href="./WorkedExample_Solutions.ipynb#task_3">Click here for solution</a> # ### Task 4. # # If at time $t=0 $ the observable $\mathcal{A}$ is measured and the positive value is obtained, what is the state of the system immediately after the measurement? # # <a href="./WorkedExample_Solutions.ipynb#task_4">Click here for solution</a>
3-qm/WorkedExample.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Mask R-CNN - Inspect Custom Trained Model # # Code and visualizations to test, debug, and evaluate the Mask R-CNN model. # + import os import cv2 import sys import random import math import re import time import numpy as np import tensorflow as tf import matplotlib import matplotlib.pyplot as plt import matplotlib.patches as patches import skimage import glob # Root directory of the project ROOT_DIR = os.getcwd() # Import Mask RCNN sys.path.append(ROOT_DIR) # To find local version of the library from mrcnn import utils from mrcnn import visualize from mrcnn.visualize import display_images import mrcnn.model as modellib from mrcnn.model import log import custom # %matplotlib inline # Directory to save logs and trained model MODEL_DIR = os.path.join(ROOT_DIR, "logs") custom_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_line_0500.h5") # TODO: update this path # - # ## Configurations config = custom.CustomConfig() custom_DIR = os.path.join(ROOT_DIR, "customImages") # + # Override the training configurations with a few # changes for inferencing. class InferenceConfig(config.__class__): # Run detection on one image at a time GPU_COUNT = 1 IMAGES_PER_GPU = 1 config = InferenceConfig() config.display() # - # ## Notebook Preferences # + # Device to load the neural network on. # Useful if you're training a model on the same # machine, in which case use CPU and leave the # GPU for training. DEVICE = "/gpu:1" # /cpu:0 or /gpu:0 # Inspect the model in training or inference modes # values: 'inference' or 'training' # TODO: code for 'training' test mode not ready yet TEST_MODE = "inference" # - def get_ax(rows=1, cols=1, size=16): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Adjust the size attribute to control how big to render images """ _, ax = plt.subplots(rows, cols, figsize=(size*cols, size*rows)) return ax # ## Load Validation Dataset # + # Load validation dataset dataset = custom.CustomDataset() dataset.load_custom(custom_DIR, "val") # Must call before using the dataset dataset.prepare() print("Images: {}\nClasses: {}".format(len(dataset.image_ids), dataset.class_names)) # - # ## Load Model # Create model in inference mode with tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) # + # load the last model you trained # weights_path = model.find_last()[1] # Load weights print("Loading weights ", custom_WEIGHTS_PATH) model.load_weights(custom_WEIGHTS_PATH, by_name=True) # - from importlib import reload # was constantly changin the visualization, so I decided to reload it instead of notebook reload(visualize) # # Run Detection on Images # + image_id = random.choice(dataset.image_ids) image, image_meta, gt_class_id, gt_bbox, gt_mask =\ modellib.load_image_gt(dataset, config, image_id, use_mini_mask=False) info = dataset.image_info[image_id] print("image ID: {}.{} ({}) {}".format(info["source"], info["id"], image_id, dataset.image_reference(image_id))) # Run object detection results = model.detect([image], verbose=1) # Display results ax = get_ax(1) r = results[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], dataset.class_names, r['scores'], ax=ax, title="Predictions") log("gt_class_id", gt_class_id) log("gt_bbox", gt_bbox) log("gt_mask", gt_mask) # -
inspect_custom_model.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit ###################### Inisiasi ################### file = 'DTVir.txt' t = np.loadtxt(file, usecols=0) m = np.loadtxt(file, usecols=1) ######################## Plot ##################### plt.figure(0,figsize=(15,5)) plt.plot(t, m, 'k.') plt.xlabel('JD (day)') plt.gca().invert_yaxis() plt.ylabel('mag') plt.title('Light Curve %s'%file) plt.grid(True) plt.show() ###################### Inisisasi 2 ########################### t0 = t[0] mulai = float(input('Input first day of the light curve plot (%f+)= '%t0)) selesai = float(input('Input last day of the light curve plot (max = %f) = '%(t[len(t)-1]))) t2 = [] m2 = [] count = 0 N = len(t) while mulai >= t[count]: count +=1 while selesai >= t[count]: t2.append(t[count]) m2.append(m[count]) count += 1 if count == N: break t = np.array(t2) m = np.array(m2) ######################## Plot ##################### plt.figure(0,figsize=(15,5)) plt.plot(t, m, 'k.') plt.xlabel('JD (%d+)'%t0) plt.ylabel('mag') plt.gca().invert_yaxis() plt.title('Light curve %s'%file) plt.grid(True) plt.show() ####################### Perhitungan ################## mr = np.mean(m) # Mag rata-rata f = m - mr # simpangan dari rerata Difdate = np.diff(t) # Mencari selisih antar pengamatan NP = 2*min(Difdate) # Periode Nyquist, 2xselisih minimum if NP == 0: fMax = float(input('Input maximum frequency (Nyquist frequency = undefined) = ')) else: fN = 1/NP #1/Day # Frekuensi Nyquist fMax = float(input('Input maximum frequency (Nyquist frequency = %f) = ' %fN)) Nfreq = int(input('Input number of partition (number of data points) = ')) Df = fMax/Nfreq #Selang frekuensi fMin = float(input('Input the minimum frequency [resolution in requency] (>%f) = '%Df)) DT = t[N-1]-t[0] #Lama observasi Nfreq = int(fMax//Df) # ######## Perhitungan konstanta ########## omega = np.linspace(fMin, fMax, Nfreq) #bikin array omega x = 2*np.pi*omega a0 = np.sqrt(1/N) S = np.zeros(Nfreq) C2 = [] C1 = [] A1 = [] A2 = [] for i in range(Nfreq): cos2x = np.sum(np.cos(x[i]*t)**2) cosx2 = np.sum(np.cos(x[i]*t))**2 sin2x = np.sum(np.sin(x[i]*t)**2) sinx2 = np.sum(np.sin(x[i]*t))**2 M = np.sum(np.cos(x[i]*t)*np.sin(x[i]*t)) - a0**2*np.sum(np.sin(x[i]*t))*np.sum(np.cos(x[i]*t)) a1 = np.sqrt(1./(cos2x - a0**2*cosx2)) a2 = np.sqrt(1./(sin2x - a0**2*sinx2 - a1**2*M**2)) A1.append(a1) A2.append(a2) c1 = a1*np.sum(f*np.cos(x[i]*t)) c2 = a2*np.sum(f*np.sin(x[i]*t)) - a1*a2*c1*M C2.append(c2) C1.append(c1) S[i] = (c1**2+c2**2)/np.sum(f**2) G = -(N-3)/2*np.log(1-S) H = (N-4)/(N-3)*(G+np.exp(-G)-1) alpha = 2*(N-3)*DT*fMax/(3*(N-4)) C = 100*(1-np.exp(-H))**alpha Period = 1/omega[np.argmax(H)] ############## Plot DCDFT ###################### fig, ax1 = plt.subplots(figsize=(15,5)) ax1.plot(omega, H, 'b-', label = 'H') ax1.plot(omega, S, 'g-', label = 'S') ax2 = ax1.twinx() ax2.plot(omega, C, 'r-.', label = 'Conf Lvl') fig.tight_layout() ax1.legend(loc='upper right') ax2.legend(loc='upper left') ax1.set_xlabel('Frekuensi (1/Day)') ax1.set_ylabel('Power') ax2.set_ylabel('Confidence Level (%)') ax1.set_title('DCDFT Kurva cahaya %s'%file) ax1.set_xlim(fMin,fMax) plt.gca().invert_yaxis() ax2.grid(color='k', linestyle='--', linewidth=.5, which='both', axis='y') ax2.set_ylim(0,100) ax1.set_ylim(0,max(H)*1.2) plt.show() ########### Menentukan fase dan plot kurva cahayanya ############## print('Period = %f days(s)'%Period) print('Frequency = %f /day'%omega[np.argmax(H)]) print('Confidence Interval = %f%%' %max(C)) Ya = input('Use the period to plot the light curve? (y/n) = ') if Ya == 'n': Period = float(input('Input the period = ')) fase = (t-t[0])/Period - (t-t[0])//Period plt.figure(0,figsize=(15,5)) plt.plot(fase, m, 'k.') plt.ylim(mr+min(f)*1.1,mr+max(f)*1.1) plt.gca().invert_yaxis() plt.xlabel('Phase)') plt.ylabel('mag') plt.xlim(0,1) plt.title('Light Curve %s'%file) plt.grid(True) plt.show() # - # + def light_curve(phase, mean, amplitude,phase0): return amplitude*np.sin(phase*2*np.pi+phase0*2*np.pi)+mean phase = np.linspace(0,1,1000) phase0 = 0.65 amplitude = 0.02 mean = 0.51 popt, pcov = curve_fit(light_curve, fase, m, p0=(mean, amplitude, phase0)) magnitude = light_curve(phase, popt[0], popt[1], popt[2]) plt.figure(figsize=(10,5)) plt.plot(phase, magnitude) plt.plot(fase, m, 'k.') plt.ylim(mr+min(f)*1.1,mr+max(f)*1.1) plt.xlabel('Phase)') plt.ylabel('mag') plt.xlim(0,1) plt.title('Light Curve %s'%file) plt.grid(True) plt.gca().invert_yaxis() plt.show() print('mean = ', popt[0]) print('amplitude = ', popt[1]) print('phase_0 = ', popt[2]) # + residual = light_curve(fase, popt[0], popt[1], popt[2]) - m plt.figure(figsize=(10,5)) plt.plot(fase, residual, 'o') # plt.ylim(mr+min(f)*1.1,mr+max(f)*1.1) plt.xlabel('Phase)') plt.ylabel('residual') plt.xlim(0,1) plt.title('Residual Light Curve %s'%file) plt.grid(True) plt.show() mean_residual = np.mean(residual) sigma_residual = np.std(residual) print('mean_residual =', mean_residual) print('sigma_residual =', sigma_residual) # -
DCDFTDTVIR.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Fully Convolutional Watershed Distance Transform for 2D Data # --- # Implementation of papers: # # [Deep Watershed Transform for Instance Segmentation](http://openaccess.thecvf.com/content_cvpr_2017/papers/Bai_Deep_Watershed_Transform_CVPR_2017_paper.pdf) # # [Learn to segment single cells with deep distance estimator and deep cell detector](https://arxiv.org/abs/1803.10829) # + import os import errno import numpy as np import deepcell # - # ## Load the data # # ### Download the data from `deepcell.datasets` # # `deepcell.datasets` provides access to a set of annotated live-cell imaging datasets which can be used for training cell segmentation and tracking models. # All dataset objects share the `load_data()` method, which allows the user to specify the name of the file (`path`), the fraction of data reserved for testing (`test_size`) and a `seed` which is used to generate the random train-test split. # Metadata associated with the dataset can be accessed through the `metadata` attribute. # + # Download the data (saves to ~/.keras/datasets) filename = 'HeLa_S3.npz' test_size = 0.1 # % of data saved as test seed = 0 # seed for random train-test split (X_train, y_train), (X_test, y_test) = deepcell.datasets.hela_s3.load_data(filename, test_size=test_size, seed=seed) print('X.shape: {}\ny.shape: {}'.format(X_train.shape, y_train.shape)) # - # ### Set up filepath constants # + # the path to the data file is currently required for `train_model_()` functions # change DATA_DIR if you are not using `deepcell.datasets` DATA_DIR = os.path.expanduser(os.path.join('~', '.keras', 'datasets')) # DATA_FILE should be a npz file, preferably from `make_training_data` DATA_FILE = os.path.join(DATA_DIR, filename) # confirm the data file is available assert os.path.isfile(DATA_FILE) # + # Set up other required filepaths # If the data file is in a subdirectory, mirror it in MODEL_DIR and LOG_DIR PREFIX = os.path.relpath(os.path.dirname(DATA_FILE), DATA_DIR) ROOT_DIR = '/data' # TODO: Change this! Usually a mounted volume MODEL_DIR = os.path.abspath(os.path.join(ROOT_DIR, 'models', PREFIX)) LOG_DIR = os.path.abspath(os.path.join(ROOT_DIR, 'logs', PREFIX)) # create directories if they do not exist for d in (MODEL_DIR, LOG_DIR): try: os.makedirs(d) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise # - # ## Create the Foreground/Background FeatureNet Model # # Here we instantiate two `FeatureNet` models from `deepcell.model_zoo` for foreground/background separation as well as the interior/edge segmentation. norm_method = 'std' # data normalization receptive_field = 61 # should be adjusted for the scale of the data n_skips = 1 # number of skip-connections (only for FC training) # watershed transform settings distance_bins = 4 erosion_width = 1 # erode edges, improves segmentation when cells are close watershed_kwargs = { 'distance_bins': distance_bins, 'erosion_width': erosion_width, } # + from deepcell import model_zoo fgbg_model = model_zoo.bn_feature_net_skip_2D( n_features=2, # segmentation mask (is_cell, is_not_cell) receptive_field=receptive_field, norm_method=norm_method, n_skips=n_skips, n_conv_filters=32, n_dense_filters=128, input_shape=tuple(X_train.shape[1:]), last_only=False) # - # ## Prepare for training # # ### Set up training parameters. # # There are a number of tunable hyper parameters necessary for training deep learning models: # # **model_name**: Incorporated into any files generated during the training process. # # **n_epoch**: The number of complete passes through the training dataset. # # **lr**: The learning rate determines the speed at which the model learns. Specifically it controls the relative size of the updates to model values after each batch. # # **optimizer**: The TensorFlow module [tf.keras.optimizers](https://www.tensorflow.org/api_docs/python/tf/keras/optimizers) offers optimizers with a variety of algorithm implementations. DeepCell typically uses the Adam or the SGD optimizers. # # **lr_sched**: A learning rate scheduler allows the learning rate to adapt over the course of model training. Typically a larger learning rate is preferred during the start of the training process, while a small learning rate allows for fine-tuning during the end of training. # # **batch_size**: The batch size determines the number of samples that are processed before the model is updated. The value must be greater than one and less than or equal to the number of samples in the training dataset. # + from tensorflow.keras.optimizers import SGD from deepcell.utils.train_utils import rate_scheduler fgbg_model_name = 'conv_fgbg_model' watershed_model_name = 'conv_watershed_model' n_epoch = 3 # Number of training epochs lr = 0.01 fgbg_optimizer = SGD(lr=lr, decay=1e-6, momentum=0.9, nesterov=True) watershed_optimizer = SGD(lr=lr, decay=1e-6, momentum=0.9, nesterov=True) lr_sched = rate_scheduler(lr=lr, decay=0.99) # FC training settings n_skips = 3 # number of skip-connections (only for FC training) batch_size = 1 # FC training uses 1 image per batch # - # ### Create the DataGenerators # # The `ImageFullyConvDataGenerator` outputs a raw image (`X`) with it's labeled annotation mask (`y`). Additionally, it can apply a transform to `y` to change the task the model learns. Below we generate 2 training and validation data sets for both the foreground/background model and the pixelwise model. # + from deepcell.image_generators import ImageFullyConvDataGenerator datagen = ImageFullyConvDataGenerator( rotation_range=180, zoom_range=(.8, 1.2), horizontal_flip=True, vertical_flip=True) datagen_val = ImageFullyConvDataGenerator() # + # Create the foreground/background data iterators if isinstance(fgbg_model.output_shape, list): skip = len(fgbg_model.output_shape) - 1 else: skip = None fgbg_train_data = datagen.flow( {'X': X_train, 'y': y_train}, seed=seed, skip=skip, transform='fgbg', batch_size=batch_size) fgbg_val_data = datagen_val.flow( {'X': X_test, 'y': y_test}, seed=seed, skip=skip, transform='fgbg', batch_size=batch_size) # + # Create the watershed data iterators watershed_train_data = datagen.flow( {'X': X_train, 'y': y_train}, seed=seed, skip=n_skips, transform='watershed', transform_kwargs=watershed_kwargs, batch_size=batch_size) watershed_val_data = datagen_val.flow( {'X': X_test, 'y': y_test}, seed=seed, skip=n_skips, transform='watershed', transform_kwargs=watershed_kwargs, batch_size=batch_size) # - # Visualize the data generator output. # + from matplotlib import pyplot as plt # Different data generators but same data and same seed img, fgbg_output = fgbg_train_data.next() _, watershed_output = watershed_train_data.next() if n_skips: fgbg_output = fgbg_output[0] watershed_output = watershed_output[0] fig, axes = plt.subplots(1, 3, figsize=(15, 15)) ax = axes.ravel() ax[0].imshow(img[0, ..., 0]) ax[0].set_title('Source Image') ax[1].imshow(np.argmax(fgbg_output[0, ...], axis=-1)) ax[1].set_title('Foreground/Background') ax[2].imshow(np.argmax(watershed_output[0, ...], axis=-1)) ax[2].set_title('Watershed Transform') plt.show() # - # ### Compile the model with a loss function # # Each model is trained with it's own loss function. `weighted_categorical_crossentropy` is often used for classification models, but `weighted_focal_loss` is also supported. The losses are passed to `model.compile` before training. # + from deepcell import losses def loss_function(y_true, y_pred): return losses.weighted_categorical_crossentropy( y_true, y_pred, n_classes=2, from_logits=False) fgbg_model.compile( loss=loss_function, optimizer=fgbg_optimizer, metrics=['accuracy']) # - # ## Train the foreground/background model # # Call `fit()` on the compiled model, along with a default set of callbacks. # + from deepcell.utils.train_utils import get_callbacks from deepcell.utils.train_utils import count_gpus model_path = os.path.join(MODEL_DIR, '{}.h5'.format(fgbg_model_name)) loss_path = os.path.join(MODEL_DIR, '{}.npz'.format(fgbg_model_name)) num_gpus = count_gpus() print('Training on', num_gpus, 'GPUs.') train_callbacks = get_callbacks( model_path, lr_sched=lr_sched, save_weights_only=num_gpus >= 2, monitor='val_loss', verbose=1) loss_history = fgbg_model.fit( fgbg_train_data, steps_per_epoch=fgbg_train_data.y.shape[0] // batch_size, epochs=n_epoch, validation_data=fgbg_val_data, validation_steps=fgbg_val_data.y.shape[0] // batch_size, callbacks=train_callbacks) # - # ## Create the `watershed` FeatureNet Model # # Here we instantiate two `FeatureNet` models from `deepcell.model_zoo` for foreground/background separation as well as the distance transform. watershed_model = model_zoo.bn_feature_net_skip_2D( fgbg_model=fgbg_model, n_features=distance_bins, receptive_field=receptive_field, norm_method=norm_method, n_skips=n_skips, n_conv_filters=32, n_dense_filters=128, last_only=False, input_shape=tuple(X_train.shape[1:])) # ### Compile the model with a loss function # # Just like the foreground/background model, the `watershed` model is compiled with the `weighted_categorical_crossentropy` loss function. # + from deepcell import losses def loss_function(y_true, y_pred): return losses.weighted_categorical_crossentropy( y_true, y_pred, n_classes=distance_bins, from_logits=False) watershed_model.compile( loss=loss_function, optimizer=watershed_optimizer, metrics=['accuracy']) # - # ## Train the `watershed` model # # Call `fit()` on the compiled model, along with a default set of callbacks. # + from deepcell.utils.train_utils import get_callbacks from deepcell.utils.train_utils import count_gpus model_path = os.path.join(MODEL_DIR, '{}.h5'.format(watershed_model_name)) loss_path = os.path.join(MODEL_DIR, '{}.npz'.format(watershed_model_name)) num_gpus = count_gpus() print('Training on', num_gpus, 'GPUs.') train_callbacks = get_callbacks( model_path, lr_sched=lr_sched, save_weights_only=num_gpus >= 2, monitor='val_loss', verbose=1) loss_history = watershed_model.fit( watershed_train_data, steps_per_epoch=watershed_train_data.y.shape[0] // batch_size, epochs=n_epoch, validation_data=watershed_val_data, validation_steps=watershed_val_data.y.shape[0] // batch_size, callbacks=train_callbacks) # - # ## Predict on test data # # Use the trained model to predict on new data and post-process the results into a label mask. # + # make predictions on testing data test_images = watershed_model.predict(X_test)[-1] test_images_fgbg = fgbg_model.predict(X_test)[-1] print('watershed transform shape:', test_images.shape) print('segmentation mask shape:', test_images_fgbg.shape) # - # #### Post-processing # + # Collapse predictions into semantic segmentation mask argmax_images = [] for i in range(test_images.shape[0]): max_image = np.argmax(test_images[i], axis=-1) argmax_images.append(max_image) argmax_images = np.array(argmax_images) argmax_images = np.expand_dims(argmax_images, axis=-1) print('watershed argmax shape:', argmax_images.shape) # + # threshold the foreground/background # and remove background from watershed transform threshold = 0.5 fg_thresh = test_images_fgbg[..., 1] > threshold fg_thresh = np.expand_dims(fg_thresh.astype('int16'), axis=-1) argmax_images_post_fgbg = argmax_images * fg_thresh # + # Apply watershed method with the distance transform as seed from skimage.measure import label from skimage.morphology import watershed from skimage.feature import peak_local_max watershed_images = [] for i in range(argmax_images_post_fgbg.shape[0]): image = fg_thresh[i, ..., 0] distance = argmax_images_post_fgbg[i, ..., 0] local_maxi = peak_local_max(test_images[i, ..., -1], min_distance=15, exclude_border=False, indices=False, labels=image) markers = label(local_maxi) segments = watershed(-distance, markers, mask=image) watershed_images.append(segments) watershed_images = np.array(watershed_images) watershed_images = np.expand_dims(watershed_images, axis=-1) # - # ### Plot the Results # + import matplotlib.pyplot as plt index = np.random.randint(low=0, high=X_test.shape[0]) print('Image number:', index) fig, axes = plt.subplots(ncols=3, nrows=2, figsize=(15, 15), sharex=True, sharey=True) ax = axes.ravel() ax[0].imshow(X_test[index, ..., 0]) ax[0].set_title('Source Image') ax[1].imshow(test_images_fgbg[index, ..., 1]) ax[1].set_title('Segmentation Prediction') ax[2].imshow(fg_thresh[index, ..., 0], cmap='jet') ax[2].set_title('FGBG Threshold {}%'.format(threshold * 100)) ax[3].imshow(argmax_images[index, ..., 0], cmap='jet') ax[3].set_title('Distance Transform') ax[4].imshow(argmax_images_post_fgbg[index, ..., 0], cmap='jet') ax[4].set_title('Distance Transform w/o Background') ax[5].imshow(watershed_images[index, ..., 0], cmap='jet') ax[5].set_title('Watershed Segmentation') fig.tight_layout() plt.show() # -
notebooks/training/featurenets/Watershed Transform 2D Fully Convolutional.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: 'Python 3.8.9 64-bit (''iguanas_os_dev'': venv)' # name: python3 # --- # # Direct Search Optimiser (unlabelled) Example # The Direct Search Optimiser module is used to optimise the thresholds of an existing set of rules, given an **unlabelled** dataset, using Direct Search-type Optimisation algorithms. # ## Requirements # To run, you'll need the following: # # * A rule set stored in the standard Iguanas lambda expression format, along with the keyword arguments for each lambda expression (more information on how to do this later) # * An unlabelled dataset containing the features present in the rule set. # ---- # ## Import packages # + from iguanas.rule_optimisation import DirectSearchOptimiser from iguanas.rules import Rules from iguanas.rule_application import RuleApplier from iguanas.metrics.unsupervised import AlertsPerDay import pandas as pd from sklearn.model_selection import train_test_split # - # ## Read in data # Firstly, we need to read in the raw data containing the features: data = pd.read_csv( 'dummy_data/dummy_pipeline_output_data.csv', index_col='eid' ) # Then we can split the dataset into training and test sets: X_train, X_test = train_test_split( data, test_size=0.33, random_state=0 ) # ## Read in the rules # In this example, we'll read in the rule conditions from a pickle file, where they are stored in the standard Iguanas string format. However, you can use any Iguanas-ready rule format - see the example notebook in the `rules` module. import pickle with open('dummy_data/rule_strings.pkl', 'rb') as f: rule_strings = pickle.load(f) # Now we can instantiate the `Rules` class with these rules: rules = Rules(rule_strings=rule_strings) # We now need to convert the rules into the standard Iguanas lambda expression format. This format allows new threshold values to be injected into the rule condition before being evaluated - this is how the Bayesian Optimiser finds the optimal threshold values: rule_lambdas = rules.as_rule_lambdas( as_numpy=False, with_kwargs=True ) # By converting the rule conditions to the standard Iguanas lambda expression format, we also generate a dictionary which gives the keyword arguments to each lambda expression (this dictionary is saved as the class attribute `lambda_kwargs`). Using these keyword arguments as inputs to the lambda expressions will convert them into the standard Iguanas string format. # ---- # ## Optimise rules # ### Set up class parameters # Now we can set our class parameters for the Direct Search Optimiser. Here we're using the `fit` method from the `AlertsPerDay` class, which calculates the negative squared difference between the daily number of records a rule flags vs the targetted daily number of records flagged. This means that when the Direct Search Optimiser comes to maximise this metric, it will try to minimise the difference between the actual number of records flagged and the targetted number of records flagged. # # See the `metrics.unsupervised` module for more information on additional optimisation functions that can be used on unlabelled datasets. # # We're also using the `Nelder-Mead` algorithm, which often benefits from setting the optional `initial_simplex` parameter. This is set through the `options` keyword argument. Here, we'll generate the initial simplex of each rule using the `create_initial_simplexes` method (but you can create your own if required). # # **Please see the class docstring for more information on each parameter.** apd = AlertsPerDay( n_alerts_expected_per_day=10, no_of_days_in_file=10 ) initial_simplexes = DirectSearchOptimiser.create_initial_simplexes( X=X_train, lambda_kwargs=rules.lambda_kwargs, shape='Minimum-based' ) params = { 'rule_lambdas': rule_lambdas, 'lambda_kwargs': rules.lambda_kwargs, 'metric': apd.fit, 'method': 'Nelder-Mead', 'options': initial_simplexes, 'verbose': 1, } # ### Instantiate class and run fit method # Once the parameters have been set, we can run the `fit` method to optimise the rules. ro = DirectSearchOptimiser(**params) X_rules = ro.fit(X=X_train) # + [markdown] tags=[] # ### Outputs # - # The `fit` method returns a dataframe giving the binary columns of the optimised rules as applied to the training dataset. See the `Attributes` section in the class docstring for a description of each attribute generated: X_rules.head() ro.opt_rule_performances # --- # ## Apply rules to a separate dataset # Use the `transform` method to apply the optimised rules to a separate dataset: X_rules_applied = ro.transform(X=X_test) # ### Outputs # The `transform` method returns a dataframe giving the binary columns of the rules as applied to the given dataset: X_rules_applied.head() # --- # ## Plotting the performance uplift # We can visualise the performance uplift of the optimised rules using the `plot_performance_uplift` and `plot_performance_uplift_distribution` methods: # # * `plot_performance_uplift`: Generates a scatterplot showing the performance of each rule before and after optimisation. # * `plot_performance_uplift_distribution`: Generates a boxplot showing the distribution of performance uplifts (original rules vs optimised rules). # ### On the training set # To visualise the uplift on the training set, we can use the class attributes `orig_rule_performances` and `opt_rule_performances` in the plotting methods, as these were generated as part of the optimisation process: ro.plot_performance_uplift( orig_rule_performances=ro.orig_rule_performances, opt_rule_performances=ro.opt_rule_performances, figsize=(10, 5) ) ro.plot_performance_uplift_distribution( orig_rule_performances=ro.orig_rule_performances, opt_rule_performances=ro.opt_rule_performances, figsize=(3, 7) ) # ### On the test set # To visualise the uplift on the test set, we first need to generate the `orig_rule_performances` and `opt_rule_performances` parameters used in the plotting methods as these aren't created as part of the optimisation process. To do this, we need to apply both the original rules and the optimised rules to the test set. # # **Note:** before we apply the original rules, we need to remove those that either have no optimisable conditions, have zero variance features or have features that are missing in `X_train`: # Original rules rules_to_exclude = ro.rule_names_missing_features + ro.rule_names_no_opt_conditions + ro.rule_names_zero_var_features rules.filter_rules(exclude=rules_to_exclude) orig_X_rules = rules.transform(X_test) orig_apds = apd.fit(orig_X_rules) orig_rule_performances_test = dict(zip(orig_X_rules.columns.tolist(), orig_apds)) # Optimised rules opt_X_rules = ro.transform(X_test) opt_apds = apd.fit(opt_X_rules) opt_rule_performances_test = dict(zip(opt_X_rules.columns.tolist(), opt_apds)) ro.plot_performance_uplift( orig_rule_performances=orig_rule_performances_test, opt_rule_performances=opt_rule_performances_test, figsize=(10, 5) ) ro.plot_performance_uplift_distribution( orig_rule_performances=orig_rule_performances_test, opt_rule_performances=opt_rule_performances_test, figsize=(3, 7) ) # ----
docs/examples/rule_optimisation/direct_search_optimiser_unlabelled_example.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (bayes) # language: python # name: bayes # --- # # Alternative Models # # This notebook considers some alternative models to handle the outliers found in the Leinhardt data in the [previous notebook](http://localhost:8888/notebooks/w03-07c-model-checking.ipynb). # # Simplest approach is to get rid of the outliers if we believe they are not representative of the data. Here we assume that the outliers belong in the model, and we want to update our model to explain these outliers. # # This notebook covers the videos **Alternative Models** and **Deviance Information Criteria (DIC)** in Lesson 7 of the course. import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc3 as pm import scipy.stats as stats import statsmodels.api as sm # %matplotlib inline import warnings warnings.filterwarnings("ignore") # ## Load Data # + try: leinhardt_df = pd.read_csv("Leinhardt.csv") except: leinhardt_df = pd.read_csv("https://vincentarelbundock.github.io/Rdatasets/csv/carData/Leinhardt.csv") leinhardt_df.to_csv("Leinhardt.csv") leinhardt_df.head() # + leinhardt_df["log_income"] = np.log(leinhardt_df["income"]) leinhardt_df["log_infant"] = np.log(leinhardt_df["infant"]) leinhardt_df.dropna(subset=["log_income", "log_infant"], inplace=True) # - x = leinhardt_df["log_income"].values y = leinhardt_df["log_infant"].values x.shape, y.shape # ## Baseline Model (from previous notebook) # + init_params = { "mu_0": 0, "sigma_0": 1e6, "alpha_0": 2.5, "beta_0": 0.04 } n_tune = 1000 n_iter = 5000 n_chains = 3 baseline_model = pm.Model() with baseline_model: beta = pm.Normal("beta", mu=init_params["mu_0"], sigma=init_params["sigma_0"], shape=2) sigma2 = pm.InverseGamma("sigma2", alpha=init_params["alpha_0"], beta=init_params["beta_0"]) sigma = np.sqrt(sigma2) mu = beta[0] + beta[1] * x y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y) trace_b = pm.sample(n_iter, tune=n_tune, chains=n_chains) # - _ = pm.traceplot(trace_b, combined=True) pm.gelman_rubin(trace_b) _ = pm.autocorrplot(trace_b, combined=True) pm.effective_n(trace_b) pm.summary(trace_b) # + beta = np.mean(trace_b.get_values("beta", combine=True), axis=0) preds = beta[0] + beta[1] * x resids = y - preds plt.xlabel("index") plt.ylabel("residuals") plt.scatter(np.arange(len(resids)), resids) _ = plt.show() plt.xlabel("predictions") plt.ylabel("residuals") plt.scatter(preds, resids) _ = plt.show() _ = sm.qqplot(resids) # - # ## Alternative Model 1 # # # In this alternative model, we look for additional covariates / explanatory variables that explain the outliers. # # We know that one of our explanatory variables is `oil`, yes if country is oil-exporting and no if it is not. Both our outliers, Saudi Arabia and Libya, are oil exporting countries, so including this variable in the model might explain the outliers better. # # ### Findings: # # * There is a positive correlation between oil production and infant mortality. # * Residual plots show improvement -- outliers are closer to the rest of the distribution than it was in the baseline model. # + leinhardt_df.loc[leinhardt_df["oil"] == 'no', 'oil_i'] = 0 leinhardt_df.loc[leinhardt_df["oil"] == 'yes', 'oil_i'] = 1 leinhardt_df.head() # + x0 = np.ones(len(leinhardt_df)) x1 = leinhardt_df["log_income"].values x2 = leinhardt_df["oil_i"].values X = np.vstack((x0, x1, x2)).T y = leinhardt_df["log_infant"].values X.shape, y.shape # + init_params = { "mu_0": 0, "sigma_0": 1e6, "alpha_0": 2.5, "beta_0": 0.04 } n_tune = 1000 n_iter = 5000 n_chains = 3 alt_model_1 = pm.Model() with alt_model_1: beta = pm.Normal("beta", mu=init_params["mu_0"], sigma=init_params["sigma_0"], shape=3) sigma2 = pm.InverseGamma("sigma2", alpha=init_params["alpha_0"], beta=init_params["beta_0"]) sigma = np.sqrt(sigma2) mu = beta[0] * X[:, 0] + beta[1] * X[:, 1] + beta[2] * X[:, 2] y_obs = pm.Normal("y_obs", mu=mu, sigma=sigma, observed=y) trace_a1 = pm.sample(n_iter, tune=n_tune, chains=n_chains) # - _ = pm.traceplot(trace_a1, combined=True) pm.gelman_rubin(trace_a1) _ = pm.autocorrplot(trace_a1, combined=True) pm.effective_n(trace_a1) pm.summary(trace_a1) # + beta = np.mean(trace_a1.get_values("beta", combine=True), axis=0) preds = beta[0] * X[:, 0] + beta[1] * X[:, 1] + beta[2] * X[:, 2] resids = y - preds plt.xlabel("index") plt.ylabel("residuals") plt.scatter(np.arange(len(resids)), resids) _ = plt.show() plt.xlabel("predictions") plt.ylabel("residuals") plt.scatter(preds, resids) _ = plt.show() _ = sm.qqplot(resids) # - # ## Alternative Model 2 # # We will change the distribution of likelihood from Normal to T distribution. The T distribution has a heavier tail and greater ability to accomodate outliers in the distribution. # + xs = np.arange(-3, 3, 0.1) plt.plot(xs, stats.norm.pdf(xs, loc=0, scale=1), label="Normal") plt.plot(xs, stats.t.pdf(xs, 1, loc=0, scale=1), label="Student t") plt.legend(loc="best") _ = plt.show() # + init_params = { "mu_0": 0, "sigma_0": 1e6, "alpha_0": 2.5, "beta_0": 0.04, "df_0": 1.0 } n_tune = 1000 n_iter = 5000 n_chains = 3 alt_model_2 = pm.Model() with alt_model_2: beta = pm.Normal("beta", mu=init_params["mu_0"], sigma=init_params["sigma_0"], shape=3) tau = pm.InverseGamma("tau", alpha=init_params["alpha_0"], beta=init_params["beta_0"]) df = pm.Exponential("df", lam=init_params["df_0"]) sigma = np.sqrt((tau * df) / (df - 2)) mu = beta[0] * X[:, 0] + beta[1] * X[:, 1] + beta[2] * X[:, 2] y_obs = pm.StudentT("y_obs", nu=df, mu=mu, sigma=tau, observed=y) trace_a2 = pm.sample(n_iter, tune=n_tune, chains=n_chains) # - _ = pm.traceplot(trace_a2, combined=True) pm.gelman_rubin(trace_a2) _ = pm.autocorrplot(trace_a2, combined=True) pm.effective_n(trace_a2) pm.summary(trace_a2) # + beta = np.mean(trace_a2.get_values("beta", combine=True), axis=0) preds = beta[0] * X[:, 0] + beta[1] * X[:, 1] + beta[2] * X[:, 2] resids = y - preds plt.xlabel("index") plt.ylabel("residuals") plt.scatter(np.arange(len(resids)), resids) _ = plt.show() plt.xlabel("predictions") plt.ylabel("residuals") plt.scatter(preds, resids) _ = plt.show() _ = sm.qqplot(resids) # - # ## Comparing Models # # ### Widely Applicable Information Criteria (WAIC) # # The course video talks about the [Deviance Information Criteria (DIC)](https://en.wikipedia.org/wiki/Deviance_information_criterion) which is the posterior mean of the log likelihood with an added penalty for model complexity. # # The PyMC3 analog is the Widely Applicable Information Criteria (WAIC), [attributed to Watanabe (2010)](https://docs.pymc.io/notebooks/model_comparison.html), and defined as a fully Bayesian criterion for estimating out-of-sample expectation, using the computed log pointwise posterior predictive density (LPPD) and correcting for the effective number of parameters to adjust for overfitting. The description of WAIC sounds very similar to DIC. Difference between the two is [described here](http://watanabe-www.math.dis.titech.ac.jp/users/swatanab/dicwaic.html), and appears that the main difference is that WAIC has theoretical support but DIC does not. # # #### Findings # # * In terms of WAIC, `alt_model_2` performs the best (lowest WAIC). # * Results of compare # * models are ranked by `waic` (lowest WAIC == best model) # * `p_waic` is the estimated effective number of parameters # * `weights` are the probability of each model given the data # * Results of compareplot # * unfilled circle is the WAIC value, showing `alt_model_2` has lowest WAIC # * filled circles show the deviance in WAIC value. pm.waic(trace_b, baseline_model) pm.waic(trace_a1, alt_model_1) pm.waic(trace_a2, alt_model_2) compare_dict = { "baseline_model": trace_b, "alt_model_1": trace_a1, "alt_model_2": trace_a2 } waic_comps = pm.compare(compare_dict) waic_comps _ = pm.compareplot(waic_comps) # ### Leave One Out Cross-Validation (LOO) # # Available in PyMC3, not covered in course video. This provides an estimate of out-of-sample predictive fit. As before `alt_model_2` has the best performance. pm.loo(trace_b, baseline_model) pm.loo(trace_a1, alt_model_1) pm.loo(trace_a2, alt_model_2) loo_comps = pm.compare(compare_dict, ic="LOO") loo_comps _ = pm.compareplot(loo_comps)
techniques-and-models/w03-07d-alternative-models.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: rscube # language: python # name: rscube # --- # In this notebook, we demonstrate how to: # # 1. reproject the ASF radiometric and terrain corrected data into a single coordinate reference system. # 2. crop the data to a smaller area # 3. filter the time series according to month if relevant import rasterio from pathlib import Path from tqdm import tqdm import lxml.etree as etree import datetime import numpy as np import matplotlib.pyplot as plt from rscube import (get_cropped_profile, reproject_arr_to_match_profile, reproject_arr_to_match_profile) # # Setting Data Paths # # You should have all the data downloaded using the example from the previous notebook in the directory: # # ``` # ./data/asf_data/ # ``` DATA_DIR_NAME = f'data/asf_data/' DATA_DIR = Path(DATA_DIR_NAME) DATA_DIR.exists() hh_paths = sorted(list(DATA_DIR.glob('*/*HH.tif'))) hv_paths = sorted(list(DATA_DIR.glob('*/*HV.tif'))) dem_paths = sorted(list(DATA_DIR.glob('*/*dem*.tif'))) metadata_paths = sorted(list(DATA_DIR.glob('*/*iso.xml'))) metadata_paths, dem_paths # # Inspect Profiles def get_profile(path): with rasterio.open(path) as ds: p = ds.profile return p profiles = [get_profile(p) for p in hh_paths] profiles # # Get Dates # # The ASF data is distributed with an xml file and we have determined which item contains the date and we extract that. This will work with ASF RTC ALOS-1 images only. Each sensor will have data stored in a different file and in a different format. def get_alos_date(metadata_xml_path): tree = etree.parse(open(metadata_xml_path)) root = tree.getroot() dataAcquisition_elements = root.xpath('//gml:beginPosition', namespaces=root.nsmap) assert(len(dataAcquisition_elements) == 1) element = dataAcquisition_elements[0].text date = datetime.date(int(element[:4]), int(element[5:7]), int(element[8:10])) return date dates = list(map(get_alos_date, metadata_paths)) dates # # Filter by Date # # We only want the spring and summer months (April - September). # This means we only reserve months 4, ..., 9 MONTHS_TO_USE = list(range(4, 10)) MONTHS_TO_USE indices = [k for k, date in enumerate(dates) if date.month in MONTHS_TO_USE] indices metadata_paths_filtered = [metadata_paths[k] for k in indices] dem_paths_filtered = [dem_paths[k] for k in indices] hv_paths_filtered = [hv_paths[k] for k in indices] hh_paths_filtered = [hh_paths[k] for k in indices] profiles = [get_profile(p) for p in hh_paths_filtered] profiles # # Get Cropped Subset # # We are going to view one area and get a subset and reproject all the other images into that frame. with rasterio.open(hv_paths[1]) as ds: X = ds.read(1) mask = ~ds.read_masks(1).astype(bool) X[mask] = np.nan # + sy = np.s_[:] sx = np.s_[:] plt.figure(figsize=(10, 10)) plt.imshow(10* np.log10(X[sy, sx])) plt.colorbar(label='$\gamma^0$') # + with rasterio.open(hv_paths[0]) as ds: PROFILE = ds.profile CROPPED_PROFILE = get_cropped_profile(PROFILE, sx, sy) CROPPED_PROFILE['nodata'] = np.nan CROPPED_PROFILE # - REFERENCE_PROFILE = CROPPED_PROFILE.copy() REFERENCE_PROFILE['nodata'] = np.nan # + def read_one(tif_path): with rasterio.open(tif_path) as ds: img = ds.read(1) profile = ds.profile mask = (img == 0) img[mask] = np.nan profile['nodata'] = np.nan return img, profile def reproject_one(tif_path): img_src, profile_src = read_one(tif_path) img_r, profile_r = reproject_arr_to_match_profile(img_src, profile_src, REFERENCE_PROFILE, resampling='bilinear') # Clips image to between -30 and 0 db. img_r = np.clip(img_r, 1e-3, 1) return img_r, profile_r def write_reprojected(img_r, original_tif_path, metadata_path, pol): date = get_alos_date(metadata_path) dest_dir = Path(f'{DATA_DIR}_reprojected/{pol}') dest_dir.mkdir(exist_ok=True, parents=True) dest_path = dest_dir/f'ALOS1_RTC_{pol}_{date.year}{date.month:02d}{date.day:02d}.tif' with rasterio.open(dest_path, 'w', **REFERENCE_PROFILE) as ds: ds.write(img_r.astype(REFERENCE_PROFILE['dtype'])) return dest_path # - reprojected_data_hh = list(map(reproject_one, tqdm(hh_paths_filtered))) reprojected_images_hh, _ = zip(*reprojected_data_hh) reprojected_data_hv = list(map(reproject_one, tqdm(hv_paths_filtered))) reprojected_images_hv, _ = zip(*reprojected_data_hv) mask_ts = list(map(np.isnan, reprojected_images_hh + reprojected_images_hv )) ts_mask = np.logical_or.reduce(mask_ts) plt.imshow(ts_mask[0, ...]) def apply_mask(img): img_ = img.copy() (img_)[ts_mask] = np.nan return img_ reprojected_images_hh = list(map(apply_mask, tqdm(reprojected_images_hh))) reprojected_images_hv = list(map(apply_mask, tqdm(reprojected_images_hv))) # + from itertools import starmap N = len(metadata_paths_filtered) list(starmap(write_reprojected, tqdm(zip(reprojected_images_hh, hh_paths_filtered, metadata_paths_filtered, ['hh'] * N), total=N))) # + from itertools import starmap N = len(metadata_paths_filtered) list(starmap(write_reprojected, tqdm(zip(reprojected_images_hv, hv_paths_filtered, metadata_paths_filtered, ['hv'] * N), total=N))) # - # # Cropping the DEM # # We'll copy the dem from the first RTC image into this directory because this will be useful for filtering by slope. dest_dir = Path(f'{DATA_DIR}_reprojected') dest_dir.exists(), dest_dir # + with rasterio.open(dem_paths_filtered[0]) as ds: dem = ds.read(1) dem = dem[sy, sx] dem_profile = REFERENCE_PROFILE.copy() dem_profile['dtype'] = 'float32' with rasterio.open(dest_dir/'dem.tif', 'w', **dem_profile) as ds: ds.write(dem.astype(np.float32), 1)
notebooks/change_detection/ALOS1_Borreal_Forest_Quebec/1 - Rename and Reproject Time Series.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [default] # language: python # name: python3 # --- # + language="javascript" # require.config({ # paths: {cytoscape: 'http://localhost:8099/js/cytoscape-2.7.10'} # }) # - import ipywidgets as widgets import time from IPython.display import display, HTML from traitlets import Int, Unicode, observe class TabsWidget(widgets.DOMWidget): _view_name = Unicode('TabsView').tag(sync=True) _view_module = Unicode('tabsDemo').tag(sync=True) frameHeight = Int(300).tag(sync=True) def setHeight(self, height): print("setHeight(%d) "% height) self.frameHeight = height display(HTML(data=""" <style> div#notebook-container { width: 97%; } div#menubar-container { width: 65%; } div#maintoolbar-container { width: 99%; } </style> """)) # + language="javascript" # "use strict"; # require.undef('tabsDemo') # # define('tabsDemo', ["jupyter-js-widgets"], function(widgets) { # # var TabsView = widgets.DOMWidgetView.extend({ # # initialize: function() { # this.options = {} # console.log("constructing TabsView"); # this.frameHeight = "800px"; # }, # # resizeHandler: function(){ # console.log("TabsView resizeHandler") # }, # # createMasterTabsDiv: function(){ # var masterTabsDiv = $("<div id='masterTabsDiv' style='border:1px solid gray; height: 400px; width: 97%'></div>"); # var list = $("<ul/>"); // .appendTo(masterTabsDiv); # list.append("<li><a href='#tab-1'>one</a></li>"); # list.append("<li><a href='#tab-2'>two</a></li>"); # list.append("<li><a href='#tab-3'>three</a></li>"); # masterTabsDiv.append(list); # var tab1 = $("<div id='tab-1'>contents 1</div>"); # var tab2 = $("<div id='tab-2'>contents 2</div>"); # var tab3 = $("<div id='tab-3'>contents 3</div>"); # masterTabsDiv.append(tab1); # masterTabsDiv.append(tab2); # masterTabsDiv.append(tab3); # return(masterTabsDiv); # }, # # render: function() { # console.log("entering render"); # this.masterTabsDiv = this.createMasterTabsDiv(); # this.$el.append(this.masterTabsDiv); # this.listenTo(this.model, 'change:frameHeight', this.frameDimensionsChanged, this); # setTimeout(function(){ # console.log("about to call tabs()"); # $("#masterTabsDiv").tabs(); # }, 0); # }, # # # frameDimensionsChanged: function(){ # console.log("frameDimensionsChanged"); # var oldHeight = $("#mainDiv").height() # var oldWidth = $("#mainDiv").width() # var newHeight = this.model.get("frameHeight"); # var msg = "<center>tabs demo, height: " + oldHeight + " -> " + newHeight + "</center>"; # $("#mainDiv").html(msg); # $("#masterTabsDiv").height(newHeight); # }, # # # }); # return { # TabsView: TabsView # }; # }); # - app = TabsWidget() display(app) app.setHeight(500)
standalone/devel/tabs.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # You are given an integer N. Can you find the least positive integer X made up of only 9's and 0's, such that, X is a multiple of N? # # X is made up of one or more occurences of 9 and zero or more occurences of 0. # # + import os import sys import itertools #itertools and functools - permutations and combinations modules def solve(n): for k in itertools.count(1): v = int(bin(k)[2:].replace('1', '9')) if not v%n: break return(str(v)) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') t = int(input()) for t_itr in range(t): n = int(input()) result = solve(n) fptr.write(result + '\n') fptr.close() # + # another soln from itertools import product def special(n): i = 0 while True: for j in product(*[[0,9]]*i) or [9]: s = "9"+"".join(map(str,j)) if not int(s)%n: return s i+=1 for _ in range(int(input())): n = int(input()) print(special(n)) # - # **Sample Input** # # 3 # 5 # 7 # 1 # # **Sample Output** # # 90 # 9009 # 9 # # **Explanation** # # 90 is the smallest number made up of 9's and 0's divisible by 5. Similarly, you can derive for other cases.
Mathematics/1. fundamentals/17. special multiple.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] heading_collapsed=true # # Imports # + hidden=true import os import sys import numpy as np import random import time # %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt import PIL from PIL import Image from IPython import display import cv2 from google.colab.patches import cv2_imshow import torch import torchvision.transforms as transforms from copy import deepcopy from portraitsegmenter import PortraitSegmenter from datasets_portraitseg import PortraitSegDatasetAug from segment_trainer import SegmentTrainer # + [markdown] heading_collapsed=true # # Set-up # + hidden=true x_train = np.load("data/img_uint8.npy") y_train = np.load("data/msk_uint8.npy") x_test = np.load("data/test_xtrain.npy") y_test = np.load("data/test_ytrain.npy") # + hidden=true datavals = PortraitSegDatasetAug(x_train, y_train, angle_range=30, zoom=0.5, noise_scale=10.0) valvals = PortraitSegDatasetAug(x_test, y_test, aug=False) port_seg = PortraitSegmenter(down_depth=[1, 2, 2, 2], up_depth=[1, 1, 1], filters=[16, 24, 32, 48]) trainer = SegmentTrainer(port_seg) iiii = 0 # + hidden=true iiii += 1 x, y, z, w = valvals[iiii] cv2_imshow(np.moveaxis(((x + 1) * 127.5), 0, -1)[:, :, ::-1]) cv2_imshow(np.expand_dims(z * 255., axis=2)) cv2_imshow(np.expand_dims(w * 255., axis=2)) with torch.no_grad(): a1, a2 = port_seg(torch.tensor(x).unsqueeze(0).to(torch.device("cuda"))) print(a1.shape) print(a2.shape) thresh = 1.64872 print( trainer.calcIOU(torch.tensor(w), torch.tensor(a1.to(torch.device("cpu"))))) a1[a1 < thresh] = 0 a1[a1 >= thresh] = 1 a2[a2 < thresh] = 0 a2[a2 >= thresh] = 1 cv2_imshow(a2.detach().squeeze().to(torch.device("cpu")).numpy() * 255.) cv2_imshow(a1.detach().squeeze().to(torch.device("cpu")).numpy() * 255.) # - # # Train history = trainer.train(datavals, valvals, batch_size=128, epochs=50, lr=0.001, es_patience=30, mask_weight=10, mask_loss='CE', edge_loss=None) trainer.segmenter.load_state_dict(torch.load("best.pth")) torch.save(trainer.segmenter.state_dict(), "portraitCE.pth")
scripts/SegmenterTraining.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import cv2 import numpy as np import matplotlib.pyplot as plt imagen = cv2.imread("img/boy.png") rgb= cv2.cvtColor(imagen, cv2.COLOR_BGR2RGB) plt.imshow(rgb) plt.title('Original') # + # Filtro gaussiano # sigma= 17, hsize = 1,3,50 blur1 = cv2.GaussianBlur(rgb,(17,17),1) blur2 = cv2.GaussianBlur(rgb,(17,17),3) blur3 = cv2.GaussianBlur(rgb,(17,17),50) plt.subplot(131),plt.imshow(blur1),plt.axis('off') plt.subplot(132),plt.imshow(blur2),plt.axis('off') plt.subplot(133),plt.imshow(blur3),plt.axis('off') # + # filtro de la mediana median1 = cv2.medianBlur(rgb,5) median2 = cv2.medianBlur(rgb,11) median3 = cv2.medianBlur(rgb,17) plt.subplot(131),plt.imshow(median1),plt.axis('off') plt.subplot(132),plt.imshow(median2),plt.axis('off') plt.subplot(133),plt.imshow(median3),plt.axis('off') # + # filtro de la media blur1 = cv2.blur(rgb,(3,3)) blur2 = cv2.blur(rgb,(11,11)) blur3 = cv2.blur(rgb,(17,17)) plt.subplot(131),plt.imshow(blur1),plt.axis('off') plt.subplot(132),plt.imshow(blur2),plt.axis('off') plt.subplot(133),plt.imshow(blur3),plt.axis('off') # -
filtros.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score from sklearn import preprocessing df = pd.read_csv("sonar.all-data.csv", header=None) df.head() X = df.iloc[:,:-1] print(X.shape) y=df.iloc[:,-1] y.shape le = preprocessing.LabelEncoder() le.fit(["R","M"]) list(le.classes_) y=le.transform(y) #Lets split our data in train and test X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=1) print(X_train.shape) print(y_train.shape) print(X_test.shape) print(y_test.shape) def Stacking(model,train,y,test,n_fold): folds=StratifiedKFold(n_splits=n_fold,random_state=1) test_pred=np.empty((0,1),float) train_pred=np.empty((0,1),float) for train_indices,val_indices in folds.split(train,y): x_train,x_val=train.iloc[train_indices,:],train.iloc[val_indices,:] y_train,y_val=y[train_indices],y[val_indices] model.fit(X=x_train,y=y_train) train_pred=np.append(train_pred,model.predict(x_val)) test_pred=model.predict(test) return test_pred.reshape(-1,1),train_pred # + model1 = DecisionTreeClassifier(random_state=1) test_pred1 ,train_pred1=Stacking(model=model1,n_fold=10, train=X_train,test=X_test,y=y_train) train_pred1=pd.DataFrame(train_pred1) test_pred1=pd.DataFrame(test_pred1) # - print(test_pred1.shape) print(train_pred1.shape) # + model2 = KNeighborsClassifier() test_pred2 ,train_pred2=Stacking(model=model2,n_fold=10,train=X_train,test=X_test,y=y_train) train_pred2=pd.DataFrame(train_pred2) test_pred2=pd.DataFrame(test_pred2) # + validation_prediction = pd.concat([train_pred1, train_pred2], axis=1) test_prediction = pd.concat([test_pred1, test_pred2], axis=1) model = LogisticRegression(random_state=1) model.fit(validation_prediction,y_train) model.score(test_prediction, y_test) # -
Ensembling methods/Stacking.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # Given a string s, find the length of the longest substring without repeating characters. def lengthOfLongestSubstring(self, s: str) -> int: if len(s) < 2: return len(s) d = dict() longest = 0 memory = 0 for i, c in enumerate(s): try: longest = max(longest, i - d[c]) memory = max(memory, d[c]) except: pass d[c] = i return max(longest, len(s) - memory) def lengthOfLongestSubstring(s: str) -> int: if len(s) < 2: return len(s) position = dict() # position of letters and their latest occurrence longest = 0 # length of longest string start = 0 # starting at 0 end = 0 for i, c in enumerate(s): if c not in position: position[c] = i else: # c has been encountered before # its last position is position[c] if i - position[c] > longest: longest = i - position[c] - 1 start = position[c] position[c] = i # return longest return s[start-1:start+longest-1] lengthOfLongestSubstring('abcabcbb') # g is not in position # position[g] = 0 # # e is not in position # position[e] = 1 # # e is in position # 2 - position[e] - 1 #
leetcode/longest-substring-without-repeating-characters.ipynb
try: import openmdao.api as om import dymos as dm except ImportError: # !python -m pip install openmdao[notebooks] # !python -m pip install dymos[docs] import openmdao.api as om import dymos as dm # # Variables # # An Optimal Control problem in Dymos consists of the following variable types. # # ## Time # # Optimal control problems in Dymos assume a system that is evolving in time. State variables # typically obey some ordinary differential equation that provides the derivative of the states # w.r.t. time. # # Users can specify various options relating to time with the `set_time_options` method of Phase. # # In Dymos, the phase time is controlled by two inputs: # # - `t_initial` - The initial time of the phase # - `t_duration` - The duration of the phase # # The bounds, scaling, and units of these variables may be set using `set_time_options`. In addition, # the user can specify that the initial time or duration of a phase is to be connected to some # external output by specifying `input_initial = True` or `input_duration = True`. In the case of # fixed initial time or duration, or input initial time or duration, the optimization-related options # have no effect and a warning will be raised if they are used. # # The variables `t_initial` and `t_duration` are converted to time values at the nodes within the phase. # Dymos computes the following time values, which can be used inside the ODE: # # - `time` - The canonical time. At the start of the phase `time = t_initial`, and `time = t_initial + t_duration` at the end of the phase. # - `time_phase` - The elapsed time since the beginning of the phase. `time_phase = time - t_initial` # - `t_initial` - The initial time of the current phase (this value is the same at all nodes within the phase). # - `t_duration` - The phase time duration of the current phase (this value is the same at all nodes within the phase). # # ### Options for Time Variables om.show_options_table("dymos.phase.options.TimeOptionsDictionary") # ## States # # States are variables that define the current condition of the system. For instance, in trajectory # optimization they are typically coordinates that define the position and velocity of the vehicle. # They can also be things like component bulk temperatures or battery state-of-charge. In most # dynamic systems, states obey some ordinary differential equation. As such, these are defined # in an `ODE` object. # # At the phase level, we assume that states evolve continuously such that they can be modeled as a # series of one or more polynomials. The phase duration is broken into one or more *segments* on # which each state (and each dynamic control) is modeled as a polynomial. The order of the # polynomial is specified using the *transcription_order* method. **In Dymos, the minimum state # transcription order is 3.** # # Users can specify bounds and scaling of the state variables with the phase method `add_state`. # The units and shape arguments are not required, as dymos will pull that information from the rate_source when # possible. You may still add units if you would like the driver or the timeseries to see a different unit than # what is defined in the rate source. There are two exceptions: # - If the rate_source references a control that has no targets, shape is required. # - If the rate_source is another state, that state needs to be declared first. If the relationship is circular, shape is required. # # Settings on a previously-added state variable may be changed using the `set_state_options` method. # The following options are valid: # # ### Options for State Variables om.show_options_table("dymos.phase.options.StateOptionsDictionary") # The Radau Pseudospectral and Gauss Lobatto phases types in Dymos use differential defects to # approximate the evolution of the state variables with respect to time. In addition to scaling # the state values, scaling the defect constraints correctly is important to good performance of # the collocation algorithms. This is accomplished with the `defect_scaler` or `defect_ref` options. # As the name implies, `defect_scaler` is multiplied by the defect value to provide the defect # constraint value to the optimizer. Alternatively, the user can specify `defect_ref`. If provided, # `defect_ref` overrides `defect_scaler` and is the value of the defect seen as `1` by the optimizer. # # If the ODE is explicitly depending on a state's value (for example, the brachistochrone ODE is a function of the bead's speed), then the user specifies those inputs in the ODE to which the state is to be connected using the `targets` option. # It can take the following values: # # - (default) # If left unspecified, targets assumes a special `dymos.utils.misc._unspecified` value. # In this case, dymos will attempt to connect to an input of the same name at the top of the ODE (either promoted there, or there because the ODE is a single component). # # - None # The state is explicitly not connected to any inputs in the ODE. # - str or sequence of str # The state values are connected to inputs of the given name or names in the ODE. # These targets are specified by their path relative to the top level of the ODE. # # To simplify state specifications, using the first option (not specifying targets) and promoting targets of the state to inputs of the same name at the top-level of the ODE. # ## Controls # # Typically, an ODE will have inputs that impact its values but, unlike states, don't define the # system itself. Such inputs include things like throttle level, elevator deflection angle, # or spring constants. In Dymos, dynamic inputs are referred to as controls, while # static inputs are called parameters. # # Dynamic controls are values which we might expect to vary continuously throughout a trajectory, like an elevator deflection angle for instance. # The value of these controls are often determined by an optimizer. # # ```{Note} # The order of a dynamic control polynomial in a segment is one less than the state # transcription order (i.e. a dynamic control in a phase with `transcription_order=3` will # be represented by a second-order polynomial. # ``` # # ### Options for Control Variables om.show_options_table("dymos.phase.options.ControlOptionsDictionary") # Control values are connected to the ODE using the `targets` argument. # The values of this argument obey the same rules as those for states. # # The control first and second derivatives w.r.t. time may also be connected to the ODE. # First derivatives of controls in Dymos assume the name `<control_name>_rate`. # Second derivatives of controls in Dymos assume the name `<control_name>_rate2`. # Control rates are automatically connected if a top-level input of the ODE is named `<control_name>_rate` or `<control_name>_rate2`. # These variables are available in the timeseries output as `timeseries.control_rates.<control_name>_rate` and `timeseries.control_rates.<control_name>_rate2`, respectively. # ## Polynomial Controls # # Sometimes it can be easier to optimize a problem by reducing the freedom in the controls. # For instance, one might want the control to be linearly or quadratically varying throughout a phase, rather than having a different value specified at each node. # In Dymos, this role is filled by the PolynomialControl. # Polynomial controls are specified at some limited number of points throughout a _phase_, and then have their values interpolated to each node in each segment. # # ### Options for Polynomial Control Variables om.show_options_table("dymos.phase.options.PolynomialControlOptionsDictionary") # Polynomial values are connected to the ODE using the `targets` argument. # The values of this argument obey the same rules as those for states. # # The polynomial control first and second derivatives w.r.t. time may also be connected to the ODE. # First derivatives of controls in Dymos assume the name `<control_name>_rate`. # Second derivatives of controls in Dymos assume the name `<control_name>_rate2`. # Control rates are automatically connected if a top-level input of the ODE is named `<control_name>_rate` or `<control_name>_rate2`. # These variables are available in the timeseries output as `timeseries.polynomial_control_rates.<control_name>_rate` and `timeseries.polynomial_control_rates.<control_name>_rate2`, respectively. # ## Parameters # # Some inputs impact the system but have one set value throughout the trajectory. # We refer to these non-time-varying inputs as *parameters*, since they typically involve parameters which define a system. # Parameters could include things like the wingspan of a vehicle or the mass of a heatsink. # In Dymos, parameters can be optimized (by providing argument `opt = True`). # If not optimized they can be targets for connections from outside of the Phase or Trajectory. # # ### Options for Parameters om.show_options_table("dymos.phase.options.ParameterOptionsDictionary") # Parameters can have their values determined by the optimizer, or they can be passed in from an external source. # # Parameters obey the same connection rules as other variables, if targets is left unspecified. # # Parameters are available in the timeseries output as `timeseries.parameters.<parameter_name>`. # Since parameters are constant throughout a trajectory, some users may want to prevent them from inclusion in the timeseries. # This can be done by specifying `include_timeseries = False` in the parameter options.
docs/features/phases/variables.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + #default_exp examples00 # - #hide #test_flag_colab from google.colab import drive drive.mount('/content/drive') #hide # !pip install nbdev # !pip install fastcore #hide # %cd /content/drive/My\ Drive/fa_convnav #hide # not deps but we need them to use nbdev and run tests from nbdev import * from nbdev.showdoc import * from fastcore.test import * # # Tests # # > Test fa_convnav working as expected with all supported models. # # #hide try: import fastai2.basics except: # !pip install fastai2 else: print('fastai2 already installed') from fastai2.basics import * from fastai2.callback.all import * from fastai2.vision.all import * from torch import torch from fa_convnav.navigator import * from pandas import DataFrame # + #hide import gzip def get_test_vars(): #load test_vars from file if not already downloaded try: test_learner except: with gzip.open("test_learner_resnet18", "rb") as f: test_learner = pickle.load(f) with gzip.open("test_summary_resnet18", "rb") as f: test_summary = pickle.load(f) try: test_df except: with gzip.open("test_df_resnet18", "rb") as f: test_df = pickle.load(f) return test_learner, test_summary, test_df test_learner, test_summary, test_df = get_test_vars() # + pets = DataBlock(blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, splitter=RandomSplitter(), get_y=RegexLabeller(pat = r'/([^/]+)_\d+.jpg$'), item_tfms=Resize(460), batch_tfms=[*aug_transforms(size=224, max_rotate=30, min_scale=0.75), Normalize.from_stats(*imagenet_stats)]) dls = pets.dataloaders(untar_data(URLs.PETS)/"images", bs=128) # - # %%capture def run_tests(cn_test, i): test_df = cn_test._cndf test_eq(type(cn_test._cndf), res[0]) test_eq(len(cn_test._cndf), res[1]) # rows test_eq(len(cn_test._cndf.columns), res[2]) # columns test_df['lyr_obj'] = None test_eq(len(cndf_search(test_df, 12)), res[3]) test_eq(len(cndf_search(test_df, ['0.6.1.conv2', '0.0.6', '0.0.6', '0.0.6', '0.0.4', '0.6'][i])), res[4]) test_eq(len(cndf_search(test_df, ['0.6', '0.0.6', '0.0.6', '0.0.6', '0.0.4.2', '0.6'][i], exact=False)), res[5]) test_eq(len(cndf_search(test_df, [{'Module_name': '0.6', 'Layer_description':'Conv2d'}, \ {'Module_name': '1.0', 'Container_child':'AdaptiveConcatPool2d'}, \ {'Module_name': '1.0', 'Container_child':'AdaptiveConcatPool2d'}, \ {'Module_name': '0.0.6', 'Layer_description':'Conv2d'}, \ {'Module_name': '0.0.4.2', 'Layer_description':'Conv2d'}, \ {'Module_name': '0.6', 'Layer_description':'Conv2d'}, \ ][i], exact=True)), res[6]) test_eq(len(cndf_search(test_df, ['0.6', '0.5'], exact=False)), res[7]) test_eq(cndf_search(test_df, ('0.6', '0.5'), exact=False), res[8]) cn_test.view() cn_test.head cn_test.body cn_test.divs test_eq(len(cn_test.linear_layers), res[9]) test_eq(len(cn_test.dim_transitions), res[10]) test_eq(len(cn_test.find_block('0.4.1')), res[11]) test_eq(len(cn_test.find_block('0.4.1', layers=False)), res[12]) test_eq(len(cn_test.find_conv('first', 5)), res[13]) #revise to 5 ater importing chnages from core.ipynb+ below 3 -> 5 test_eq(len(cn_test.children), res[14]) test_eq(len(cn_test.blocks), res[15]) test_eq(len(cn_test.spread('conv', 8)), res[16]) del(cn_test) models_to_test = [ ('resnet18', resnet18, [DataFrame, 79, 22, 1, 1, 16, 1, 32, None, 2, 5, 6, 1, 5, 8, 8, 7]), ('vgg13', vgg13_bn, [DataFrame, 50, 22, 1, 1, 1, 1, 2, None, 2, 5, 0, 0, 5, 1, 0, 5]), ('alexnet', alexnet, [DataFrame, 28, 22, 1, 1, 1, 1, 2, None, 2, 3, 0, 0, 4, 1, 0, 5]), ('squeezenet1_0', squeezenet1_0, [DataFrame, 76, 22, 1, 1, 1, 1, 8, None, 2, 4, 0, 0, 5, 1, 8, 7]), ('densenet161', densenet161, [DataFrame, 585, 22, 1, 1, 42, 1, 9, None, 2, 6, 7, 1, 5, 12, 78, 8]), # 11, 12 revise values after imorting cahnges from core.ipynb ('xresnet34', xresnet34, [DataFrame, 219, 22, 1, 1, 71, 1, 120, None, 2, 5, 11, 1, 5, 8, 16, 8]) ] # %%capture for i, model in enumerate(models_to_test): _, m, res = model print(m) learn = cnn_learner( dls, m, opt_func=partial(Adam, lr=slice(3e-3), wd=0.01, eps=1e-8), metrics=error_rate, config=cnn_config(ps=0.33)).to_fp16() run_tests(ConvNav(learn, learn.summary()), i)
05_tests.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Bus # # This bus has a passenger entry and exit control system to monitor the number of occupants it carries and thus detect when there is too high a capacity. # # At each stop the entry and exit of passengers is represented by a tuple consisting of two integer numbers. # ``` # bus_stop = (in, out) # ``` # The succession of stops is represented by a list of these tuples. # ``` # stops = [(in1, out1), (in2, out2), (in3, out3), (in4, out4)] # ``` # # ## Goals: # * lists, tuples # * while/for loops # * minimum, maximum, length # * average, standard deviation # # ## Tasks # 1. Calculate the number of stops. # 2. Assign to a variable a list whose elements are the number of passengers at each stop (in-out), # 3. Find the maximum occupation of the bus. # 4. Calculate the average occupation. And the standard deviation. # # + # variables import random random.seed() stops = [( random.randint(0, 30), random.randint(0,30) ) for i in range(4)] # list containing random tuples stops[0] = (random.randint(0,30), 0) print(stops) # 1. Calculate the number of stops. numStops = len(stops) print("Number of stops: ", numStops) # + # 2. Assign a variable a list whose elements are the number of passengers in each stop: # Each item depends on the previous item in the list + in - out. passengers_per_stop = [0] i = 0 while i < numStops: net_passengers = stops[i][0] - stops[i][1] + passengers_per_stop[i] passengers_per_stop.append(net_passengers) i += 1 # Print number of passengers at each stop print(passengers_per_stop[1:]) # + # 3. Find the maximum occupation of the bus. max_occupation = max(passengers_per_stop) print(max_occupation) # + # 4. Calculate the average occupation. And the standard deviation. import statistics as stats average_occupation = sum(passengers_per_stop[1:]) / numStops std_dev = round(stats.stdev(passengers_per_stop[1:]), 2) print("Average occupation: ", average_occupation) print("Standard deviation: ", std_dev) # -
bus/bus.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from ipywidgets import interact, interactive, FloatSlider, IntSlider, ToggleButtons from geoscilabs.em.TDEMGroundedSource import choose_model, load_or_run_results, PlotTDEM # %matplotlib inline # # Exploring fields from a grounded source # ## Purpose # # We explore time-domain electromagnetic (EM) simulation results from a grounded source. Both electric currents and magnetic flux will be visualized to undertand physics of grounded source EM. Both charge buildup (galvanic) and EM induction (inductive) will occur at different times. # ## Load simulation results (or run) # # Three models are considered here. # # - Halfspace (0.01 S/m) # - Conductive block in halfspace (1 S/m) # - Resitive block in halfspace (10$^{-4}$ S/m) # # Using below widget, you can choose a model that you want to explore. Q = interact(choose_model, model=ToggleButtons( options=["halfspace", "conductor", "resistor"], value="halfspace" ) ) # Then here we are going to load results. If you want to rerun, you can set `re_run` as `True`. # With that option, you can change conductivity value of the block and halfspace you can alter values for `sigma_halfspace` and `sigma_block`. import matplotlib matplotlib.rcParams['font.size']=16 options = load_or_run_results( re_run=False, fname=choose_model(Q.widget.kwargs['model']), sigma_block=0.01, sigma_halfspace=0.01 ) tdem = PlotTDEM(**options) interact( tdem.show_3d_survey_geometry, elev=FloatSlider(min=-180, max=180, step=10, value=30), azim=FloatSlider(min=-180, max=180, step=10, value=-45), ) # + interact( tdem.plot_input_currents, itime=IntSlider(min=15, max=50, step=1, value=15, continuous_update=False), scale=ToggleButtons( options=["linear", "log"], value="linear" ), ) # - interact( tdem.plot_electric_currents, itime=IntSlider(min=15, max=50, step=1, value=15, continuous_update=False) ) interact( tdem.plot_magnetic_flux, itime=IntSlider(min=15, max=50, step=1, value=15, continuous_update=False) )
notebooks/em/TDEM_Groundedsource.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python (dev) # language: python # name: dev # --- # # Create a Web Application for an ETF Analyzer # # In this Challenge assignment, you’ll build a financial database and web application by using SQL, Python, and the Voilà library to analyze the performance of a hypothetical fintech ETF. # # Instructions: # # Use this notebook to complete your analysis of a fintech ETF that consists of four stocks: GOST, GS, PYPL, and SQ. Each stock has its own table in the `etf.db` database, which the `Starter_Code` folder also contains. # # Analyze the daily returns of the ETF stocks both individually and as a whole. Then deploy the visualizations to a web application by using the Voilà library. # # The detailed instructions are divided into the following parts: # # * Analyze a single asset in the ETF # # * Optimize data access with Advanced SQL queries # # * Analyze the ETF portfolio # # * Deploy the notebook as a web application # # #### Analyze a Single Asset in the ETF # # For this part of the assignment, you’ll use SQL queries with Python, Pandas, and hvPlot to analyze the performance of a single asset from the ETF. # # Complete the following steps: # # 1. Write a SQL `SELECT` statement by using an f-string that reads all the PYPL data from the database. Using the SQL `SELECT` statement, execute a query that reads the PYPL data from the database into a Pandas DataFrame. # # 2. Use the `head` and `tail` functions to review the first five and the last five rows of the DataFrame. Make a note of the beginning and end dates that are available from this dataset. You’ll use this information to complete your analysis. # # 3. Using hvPlot, create an interactive visualization for the PYPL daily returns. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # 4. Using hvPlot, create an interactive visualization for the PYPL cumulative returns. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # #### Optimize Data Access with Advanced SQL Queries # # For this part of the assignment, you’ll continue to analyze a single asset (PYPL) from the ETF. You’ll use advanced SQL queries to optimize the efficiency of accessing data from the database. # # Complete the following steps: # # 1. Access the closing prices for PYPL that are greater than 200 by completing the following steps: # # - Write a SQL `SELECT` statement to select the dates where the PYPL closing price was higher than 200.0. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # - Select the “time” and “close” columns for those dates where the closing price was higher than 200.0. # # 2. Find the top 10 daily returns for PYPL by completing the following steps: # # - Write a SQL statement to find the top 10 PYPL daily returns. Make sure to do the following: # # * Use `SELECT` to select only the “time” and “daily_returns” columns. # # * Use `ORDER` to sort the results in descending order by the “daily_returns” column. # # * Use `LIMIT` to limit the results to the top 10 daily return values. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # #### Analyze the ETF Portfolio # # For this part of the assignment, you’ll build the entire ETF portfolio and then evaluate its performance. To do so, you’ll build the ETF portfolio by using SQL joins to combine all the data for each asset. # # Complete the following steps: # # 1. Write a SQL query to join each table in the portfolio into a single DataFrame. To do so, complete the following steps: # # - Use a SQL inner join to join each table on the “time” column. Access the “time” column in the `GDOT` table via the `GDOT.time` syntax. Access the “time” columns from the other tables via similar syntax. # # - Using the SQL query, read the data from the database into a Pandas DataFrame. Review the resulting DataFrame. # # 2. Create a DataFrame that averages the “daily_returns” columns for all four assets. Review the resulting DataFrame. # # > **Hint** Assuming that this ETF contains equally weighted returns, you can average the returns for each asset to get the average returns of the portfolio. You can then use the average returns of the portfolio to calculate the annualized returns and the cumulative returns. For the calculation to get the average daily returns for the portfolio, use the following code: # > # > ```python # > etf_portfolio_returns = etf_portfolio['daily_returns'].mean(axis=1) # > ``` # > # > You can use the average daily returns of the portfolio the same way that you used the daily returns of a single asset. # # 3. Use the average daily returns in the `etf_portfolio_returns` DataFrame to calculate the annualized returns for the portfolio. Display the annualized return value of the ETF portfolio. # # > **Hint** To calculate the annualized returns, multiply the mean of the `etf_portfolio_returns` values by 252. # > # > To convert the decimal values to percentages, multiply the results by 100. # # 4. Use the average daily returns in the `etf_portfolio_returns` DataFrame to calculate the cumulative returns of the ETF portfolio. # # 5. Using hvPlot, create an interactive line plot that visualizes the cumulative return values of the ETF portfolio. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # #### Deploy the Notebook as a Web Application # # For this part of the assignment, complete the following steps: # # 1. Use the Voilà library to deploy your notebook as a web application. You can deploy the web application locally on your computer. # # 2. Take a screen recording or screenshots to show how the web application appears when using Voilà. Include the recording or screenshots in the `README.md` file for your GitHub repository. # # ## Review the following code which imports the required libraries, initiates your SQLite database, popluates the database with records from the `etf.db` seed file that was included in your Starter_Code folder, creates the database engine, and confirms that data tables that it now contains. # + # Importing the required libraries and dependencies import numpy as np import pandas as pd import hvplot.pandas import sqlalchemy from sqlalchemy import inspect # Create a temporary SQLite database and populate the database with content from the etf.db seed file database_connection_string = 'sqlite:///etf.db' # Create an engine to interact with the SQLite database engine = sqlalchemy.create_engine(database_connection_string) # Confirm that table names contained in the SQLite database. inspect(engine).get_table_names() # - # ## Analyze a single asset in the FinTech ETF # # For this part of the assignment, you’ll use SQL queries with Python, Pandas, and hvPlot to analyze the performance of a single asset from the ETF. # # Complete the following steps: # # 1. Write a SQL `SELECT` statement by using an f-string that reads all the PYPL data from the database. Using the SQL `SELECT` statement, execute a query that reads the PYPL data from the database into a Pandas DataFrame. # # 2. Use the `head` and `tail` functions to review the first five and the last five rows of the DataFrame. Make a note of the beginning and end dates that are available from this dataset. You’ll use this information to complete your analysis. # # 3. Using hvPlot, create an interactive visualization for the PYPL daily returns. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # 4. Using hvPlot, create an interactive visualization for the PYPL cumulative returns. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # # ### Step 1: Write a SQL `SELECT` statement by using an f-string that reads all the PYPL data from the database. Using the SQL `SELECT` statement, execute a query that reads the PYPL data from the database into a Pandas DataFrame. # Write a SQL query to SELECT all of the data from the PYPL table query = f""" SELECT * FROM PYPL """ engine.execute(query) # Use the query to read the PYPL data into a Pandas DataFrame pypl_dataframe = pd.read_sql_query(query, con= engine, index_col ='time', parse_dates= True) # ### Step 2: Use the `head` and `tail` functions to review the first five and the last five rows of the DataFrame. Make a note of the beginning and end dates that are available from this dataset. You’ll use this information to complete your analysis. # View the first 5 rows of the DataFrame. # YOUR CODE HERE pypl_dataframe.head() # View the last 5 rows of the DataFrame. # YOUR CODE HERE pypl_dataframe.tail() # ### Step 3: Using hvPlot, create an interactive visualization for the PYPL daily returns. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # Create an interactive visualization with hvplot to plot the daily returns for PYPL. pypl_dataframe.index= pd.to_datetime(pypl_dataframe.index) pypl_dataframe.hvplot.line(x= 'time', y= 'daily_returns', ylabel= 'Daily Returns', xlabel='Date', title= 'PYPL Cumulative Returns over the period of 2016/12/16 till 2020/12/04 ', size= (15,7) ).opts(yformatter="%.2f", hover_color='green', xticks= 10) # Create an interactive visaulization with hvplot to plot the cumulative returns for PYPL. # YOUR CODE HERE pypl_dataframe['cumulative_return']= (1 + pypl_dataframe['daily_returns']).cumprod() pypl_dataframe.hvplot.line(x= 'time', y= 'cumulative_return', ylabel= 'Cumulative Returns', xlabel='Date', title= 'PYPL Cumulative Returns over the period of 2016/12/16 till 2020/12/04 ', size= (15,7) ).opts(yformatter="%.2f", hover_color='green', xticks= 10) # ## Optimize the SQL Queries # # For this part of the assignment, you’ll continue to analyze a single asset (PYPL) from the ETF. You’ll use advanced SQL queries to optimize the efficiency of accessing data from the database. # # Complete the following steps: # # 1. Access the closing prices for PYPL that are greater than 200 by completing the following steps: # # 1. Access the closing prices for PYPL that are greater than 200 by completing the following steps: # # - Write a SQL `SELECT` statement to select the dates where the PYPL closing price was higher than 200.0. # # - Select the “time” and “close” columns for those dates where the closing price was higher than 200.0. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # 2. Find the top 10 daily returns for PYPL by completing the following steps: # # - Write a SQL statement to find the top 10 PYPL daily returns. Make sure to do the following: # # * Use `SELECT` to select only the “time” and “daily_returns” columns. # # * Use `ORDER` to sort the results in descending order by the “daily_returns” column. # # * Use `LIMIT` to limit the results to the top 10 daily return values. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # ### Step 1: Access the closing prices for PYPL that are greater than 200 by completing the following steps: # # - Write a SQL `SELECT` statement to select the dates where the PYPL closing price was higher than 200.0. # # - Select the “time” and “close” columns for those dates where the closing price was higher than 200.0. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # + # Write a SQL SELECT statement to select the time and close columns # where the PYPL closing price was higher than 200.0. query = """ SELECT time, close FROM PYPL WHERE close > 200.0 """ # Using the query, read the data from the database into a Pandas DataFrame pypl_higher_than_200 = pd.read_sql_query(query, con= engine) # Review the resulting DataFrame # YOUR CODE HERE pypl_higher_than_200 # - # ### Step 2: Find the top 10 daily returns for PYPL by completing the following steps: # # - Write a SQL statement to find the top 10 PYPL daily returns. Make sure to do the following: # # * Use `SELECT` to select only the “time” and “daily_returns” columns. # # * Use `ORDER` to sort the results in descending order by the “daily_returns” column. # # * Use `LIMIT` to limit the results to the top 10 daily return values. # # - Using the SQL statement, read the data from the database into a Pandas DataFrame, and then review the resulting DataFrame. # # + # Write a SQL SELECT statement to select the time and daily_returns columns # Sort the results in descending order and return only the top 10 return values query = """ SELECT time, daily_returns FROM PYPL ORDER BY daily_returns DESC LIMIT 10 """ # Using the query, read the data from the database into a Pandas DataFrame pypl_top_10_returns = pd.read_sql_query(query , con=engine) # Review the resulting DataFrame # YOUR CODE HERE pypl_top_10_returns # - # ## Analyze the Fintech ETF Portfolio # # For this part of the assignment, you’ll build the entire ETF portfolio and then evaluate its performance. To do so, you’ll build the ETF portfolio by using SQL joins to combine all the data for each asset. # # Complete the following steps: # # 1. Write a SQL query to join each table in the portfolio into a single DataFrame. To do so, complete the following steps: # # - Use a SQL inner join to join each table on the “time” column. Access the “time” column in the `GDOT` table via the `GDOT.time` syntax. Access the “time” columns from the other tables via similar syntax. # # - Using the SQL query, read the data from the database into a Pandas DataFrame. Review the resulting DataFrame. # # 2. Create a DataFrame that averages the “daily_returns” columns for all four assets. Review the resulting DataFrame. # # > **Hint** Assuming that this ETF contains equally weighted returns, you can average the returns for each asset to get the average returns of the portfolio. You can then use the average returns of the portfolio to calculate the annualized returns and the cumulative returns. For the calculation to get the average daily returns for the portfolio, use the following code: # > # > ```python # > etf_portfolio_returns = etf_portfolio['daily_returns'].mean(axis=1) # > ``` # > # > You can use the average daily returns of the portfolio the same way that you used the daily returns of a single asset. # # 3. Use the average daily returns in the `etf_portfolio_returns` DataFrame to calculate the annualized returns for the portfolio. Display the annualized return value of the ETF portfolio. # # > **Hint** To calculate the annualized returns, multiply the mean of the `etf_portfolio_returns` values by 252. # > # > To convert the decimal values to percentages, multiply the results by 100. # # 4. Use the average daily returns in the `etf_portfolio_returns` DataFrame to calculate the cumulative returns of the ETF portfolio. # # 5. Using hvPlot, create an interactive line plot that visualizes the cumulative return values of the ETF portfolio. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # # ### Step 1: Write a SQL query to join each table in the portfolio into a single DataFrame. To do so, complete the following steps: # # - Use a SQL inner join to join each table on the “time” column. Access the “time” column in the `GDOT` table via the `GDOT.time` syntax. Access the “time” columns from the other tables via similar syntax. # # - Using the SQL query, read the data from the database into a Pandas DataFrame. Review the resulting DataFrame. # + # Wreate a SQL query to join each table in the portfolio into a single DataFrame # Use the time column from each table as the basis for the join query = """ SELECT * FROM PYPL JOIN GDOT ON PYPL.time= GDOT.time JOIN GS ON GDOT.time= GS.time JOIN SQ ON GS.time= SQ.time """ # Using the query, read the data from the database into a Pandas DataFrame etf_portfolio = pd.read_sql_query(query, con=engine) # Review the resulting DataFrame # YOUR CODE HERE etf_portfolio # - # ### Step 2: Create a DataFrame that averages the “daily_returns” columns for all four assets. Review the resulting DataFrame. # Create a DataFrame that displays the mean value of the “daily_returns” columns for all four assets. etf_portfolio_returns= pd.DataFrame(data= etf_portfolio.iloc[:,[0]]) etf_portfolio_returns["average_daily_return"] = pd.DataFrame(etf_portfolio['daily_returns'].mean(axis=1)) etf_portfolio_returns['time']= pd.to_datetime(etf_portfolio_returns['time']) # Review the resulting DataFrame etf_portfolio_returns.head() # ### Step 3: Use the average daily returns in the etf_portfolio_returns DataFrame to calculate the annualized returns for the portfolio. Display the annualized return value of the ETF portfolio. # + # Use the average daily returns provided by the etf_portfolio_returns DataFrame # to calculate the annualized return for the portfolio. annualized_etf_portfolio_returns = etf_portfolio_returns["average_daily_return"].mean() * 252 # Display the annualized return value of the ETF portfolio. # YOUR CODE HERE annualized_etf_portfolio_returns # - # ### Step 4: Use the average daily returns in the `etf_portfolio_returns` DataFrame to calculate the cumulative returns of the ETF portfolio. # Use the average daily returns provided by the etf_portfolio_returns DataFrame # to calculate the cumulative returns etf_cumulative_returns= pd.DataFrame(data= etf_portfolio.iloc[:,[0]]) etf_cumulative_returns['cumulative_return'] = (1 + etf_portfolio_returns['average_daily_return']).cumprod() etf_cumulative_returns['time']= pd.to_datetime(etf_cumulative_returns['time']) # Display the final cumulative return value # YOUR CODE HERE etf_cumulative_returns.tail(1) # ### Step 5: Using hvPlot, create an interactive line plot that visualizes the cumulative return values of the ETF portfolio. Reflect the “time” column of the DataFrame on the x-axis. Make sure that you professionally style and format your visualization to enhance its readability. # Using hvplot, create an interactive line plot that visualizes the ETF portfolios cumulative return values. # YOUR CODE HERE etf_cumulative_returns.hvplot(x= 'time', y='cumulative_return',ylabel= 'Cumulative Return', xlabel='Date', title= 'PYPL Cumulative Returns over the period of 2016/12/16 till 2020/12/04 ', size= (15,7) ).opts(yformatter="%.2f", hover_color='green', xticks= 10) # STEP 6: # Deploy the notebook as web application using voila
Starter_Code-7/etf_analyzer.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler as mms from GA_functions import fitness, select_parents, crossover, mutation, GA_algorithm, GA_algorithm_unnormalized, conc_to_spectra, perform_iteration, set_seed #normalize_and_pca from tree_search_functions import zeroth_iteration, nth_iteration, plot_fitness, plot_spectra, plot_DLS from SAXS_model import model, model2 from spectroscopy import obtain_spectra # ## Define Emulator # Define the emulator as a function. def perform_simulations(conc_array, wavelength_1, wavelength_2): for i in range(conc_array.shape[0]): #Emulator 1: SAXS curve spectra_1_row = model(wavelength_1, 10*conc_array[i,0], 3*conc_array[i,1]).reshape(1,-1) #Emulator 2: SAXS curve spectra_2_row = model2(wavelength_1, 10*conc_array[i,0], 3*conc_array[i,1]).reshape(1,-1) if i == 0: spectra_array_1 = spectra_1_row spectra_array_2 = spectra_2_row else: spectra_array_1 = np.vstack((spectra_array_1, spectra_1_row)) spectra_array_2 = np.vstack((spectra_array_2, spectra_2_row)) return spectra_array_1, spectra_array_2 # ### Initialize first iteration of Input parameters and Output parameters np.random.seed(2) conc_array = np.random.dirichlet((1, 1), 30) q1 = np.linspace(1e-1, 1, 81) q2 = np.linspace(1e-1, 1, 81) spectra_array_1, spectra_array_2 = perform_simulations(conc_array, q1, q2) # ### Initialize Targets # These are the spectra that are the targets of the optimization. The algorithm will try to find the best input parameters to create a sample that has a spectra closest to the two targets. desired_spectra_1 = model(q1, 5,2).reshape(1,-1) desired_spectra_2 = model2(q2, 2,.5).reshape(1,-1) # ## Zeroth Iteration # These cells initialize the experiment by plotting the fitness score of the initial sample's spectra/ scattering curve compared to the target spectra/ scattering curve. It will also plot all the spectra/ scattering curve. desired_spectra_1 = desired_spectra_1.reshape(-1,1) desired_spectra_2 = desired_spectra_2.reshape(-1,1) loaded_dict = zeroth_iteration(conc_array = conc_array, spectra_array_1 = spectra_array_1, desired_spectra_1 = desired_spectra_1, spectra_array_2 = spectra_array_2, desired_spectra_2 = desired_spectra_2) plot_spectra(loaded_dict, wavelength_1 = q1, wavelength_2 = q2, savefig = False) # ## Nth Iteration # Run the cells starting from here all the way to the end of the notebook to perform an additional iteration. A plot of the maximum and median fitness over the iterations will be created and plots of all the sample's spectra/scattering curve compared to the target spectra/scattering curve will be generated. Iterations = 25 #sample size for GA Moves_ahead = 3 #moves ahead that are calculated GA_iterations = 8 #times per move that the GA is used n_samples = 30 #sample size seed = 2 loaded_dict = nth_iteration(loaded_dict, seed = seed, Iterations = Iterations, Moves_ahead = Moves_ahead, GA_iterations = GA_iterations, n_samples = n_samples) loaded_dict['next_gen_conc'][-1,:] = loaded_dict['best_conc_array'][:-1] loaded_dict['next_gen_conc'][-2,:] = loaded_dict['best_candidate_array'][-1, 0:-1] spectra_array_1, spectra_array_2 = perform_simulations(loaded_dict['next_gen_conc'], q1, q2) loaded_dict['conc_array_actual'] = np.vstack((loaded_dict['conc_array_actual'],loaded_dict['next_gen_conc'])) loaded_dict['spectra_array_actual_1'] = np.vstack((loaded_dict['spectra_array_actual_1'], spectra_array_1)) loaded_dict['spectra_array_actual_2'] = np.vstack((loaded_dict['spectra_array_actual_2'], spectra_array_2)) loaded_dict['spectra_array_1'] = spectra_array_1 loaded_dict['spectra_array_2'] = spectra_array_2 median_fitness_list, max_fitness_list, iteration, best_candidate_array = plot_fitness(loaded_dict, savefig = False) loaded_dict['best_candidate_array'] = best_candidate_array loaded_dict['median_fitness_list'] = median_fitness_list loaded_dict['max_fitness_list'] = max_fitness_list plot_spectra(loaded_dict, wavelength_1 = q1, wavelength_2 = q2, savefig = False)
genetic_algorithm/.ipynb_checkpoints/GA_final_version_testing-Emulator-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + pycharm={"name": "#%%\n", "is_executing": false} # + pycharm={"name": "#%%\n", "is_executing": false} import os import pprint from collections import defaultdict, namedtuple, UserList from copy import deepcopy import abc from typing import Set, Any import lxml import lxml.html import lxml.etree from graphviz import Digraph from similarity.normalized_levenshtein import NormalizedLevenshtein normalized_levenshtein = NormalizedLevenshtein() NODE_NAME_ATTRIB = '___tag_name___' HIERARCHICAL = 'hierarchical' SEQUENTIAL = 'sequential' class WithBasicFormat(object): def _extra_format(self, format_spec): raise NotImplementedError() def __format__(self, format_spec): if format_spec == "!s": return str(self) elif format_spec in ("!r", ""): return repr(self) else: try: return self._extra_format(format_spec) except NotImplementedError: raise TypeError("unsupported format string passed to {}.__format__".format(type(self).__name__)) class GNode(namedtuple("GNode", ["parent", "start", "end"]), WithBasicFormat): """Generalized Node - start/end are indexes of sibling nodes relative to their parent node.""" def __str__(self): return "GN({start:>2}, {end:>2})".format(start=self.start, end=self.end) def __len__(self): return self.size def _extra_format(self, format_spec): if format_spec == '!S': return "GN({parent}, {start:>2}, {end:>2})".format(parent=self.parent, start=self.start, end=self.end) else: raise NotImplementedError() @property def size(self): return self.end - self.start class GNodePair(namedtuple("GNodePair", ["left", "right"]), WithBasicFormat): """Generalized Node Pair - pair of adjacent GNodes, used for stocking the edit distances between them.""" def __str__(self): return "{left:!s} - {right:!s}".format(left=self.left, right=self.right) # noinspection PyArgumentList class DataRegion( namedtuple("DataRegion", ["parent", "gnode_size", "first_gnode_start_index", "n_nodes_covered"]), WithBasicFormat ): """Data Region - a continuous sequence of GNode's.""" def __str__(self): return "DR({0}, {1}, {2})".format(self.gnode_size, self.first_gnode_start_index, self.n_nodes_covered) def __contains__(self, child_index): msg = "DataRegion contains the indexes of a node relative to its parent list of children. " \ "Type `{}` not supported.".format(type(child_index).__name__) assert isinstance(child_index, int), msg return self.first_gnode_start_index <= child_index <= self.last_covered_tag_index def __iter__(self): self._iter_i = 0 return self def __next__(self): if self._iter_i < self.n_gnodes: start = self.first_gnode_start_index + self._iter_i * self.gnode_size end = start + self.gnode_size gnode = GNode(self.parent, start, end) self._iter_i += 1 return gnode else: raise StopIteration def _extra_format(self, format_spec): if format_spec == '!S': return "DR({0}, {1}, {2}, {3})".format( self.parent, self.gnode_size, self.first_gnode_start_index, self.n_nodes_covered ) else: raise NotImplementedError() @classmethod def empty(cls): return cls(None, None, None, 0) @classmethod def binary_from_last_gnode(cls, gnode): gnode_size = gnode.end - gnode.start return cls(gnode.parent, gnode_size, gnode.start - gnode_size, 2 * gnode_size) @property def is_empty(self): return self[0] is None @property def n_gnodes(self): return self.n_nodes_covered // self.gnode_size @property def last_covered_tag_index(self): return self.first_gnode_start_index + self.n_nodes_covered - 1 def extend_one_gnode(self): return self.__class__( self.parent, self.gnode_size, self.first_gnode_start_index, self.n_nodes_covered + self.gnode_size ) class DataRecord(UserList, WithBasicFormat): def __hash__(self): return hash(tuple(self)) def __repr__(self): return "DataRecord({})".format(", ".join([repr(gn) for gn in self.data])) def __str__(self): return "DataRecord({})".format(", ".join([str(gn) for gn in self.data])) def open_html_document(directory, file): directory = os.path.abspath(directory) filepath = os.path.join(directory, file) with open(filepath, 'r') as file: html_document = lxml.html.fromstring( lxml.etree.tostring(lxml.html.parse(file), method='html') ) return html_document def html_to_dot_sequential_name(html, with_text=False): graph = Digraph(name='html') tag_counts = defaultdict(int) def add_node(html_node): tag = html_node.tag tag_sequential = tag_counts[tag] tag_counts[tag] += 1 node_name = "{}-{}".format(tag, tag_sequential) graph.node(node_name, node_name) if len(html_node) > 0: for child in html_node.iterchildren(): child_name = add_node(child) graph.edge(node_name, child_name) elif with_text: child_name = "-".join([node_name, "txt"]) graph.node(child_name, html_node.text) graph.edge(node_name, child_name) return node_name add_node(html) return graph def html_to_dot_hierarchical_name(html, with_text=False): graph = Digraph(name='html') def add_node(html_node, parent_suffix, brotherhood_index): tag = html_node.tag if parent_suffix is None and brotherhood_index is None: node_suffix = "" node_name = tag else: node_suffix = ( "-".join([parent_suffix, str(brotherhood_index)]) if parent_suffix else str(brotherhood_index) ) node_name = "{}-{}".format(tag, node_suffix) graph.node(node_name, node_name, path=node_suffix) if len(html_node) > 0: for child_index, child in enumerate(html_node.iterchildren()): child_name = add_node(child, node_suffix, child_index) graph.edge(node_name, child_name) elif with_text: child_name = "-".join([node_name, "txt"]) child_path = "-".join([node_suffix, "txt"]) graph.node(child_name, html_node.text, path=child_path) graph.edge(node_name, child_name) return node_name add_node(html, None, None) return graph def html_to_dot(html, name_option='hierarchical', with_text=False): if name_option == SEQUENTIAL: return html_to_dot_sequential_name(html, with_text=with_text) elif name_option == HIERARCHICAL: return html_to_dot_hierarchical_name(html, with_text=with_text) else: raise Exception('No name option `{}`'.format(name_option)) class FormatPrinter(pprint.PrettyPrinter): def __init__(self, formats): super(FormatPrinter, self).__init__() self.formats = formats def format(self, obj, ctx, max_lvl, lvl): obj_type = type(obj) if obj_type in self.formats: type_format = self.formats[obj_type] return "{{0:{}}}".format(type_format).format(obj), 1, 0 return pprint.PrettyPrinter.format(self, obj, ctx, max_lvl, lvl) # + pycharm={"name": "#%%\n", "is_executing": false} class MDRVerbosity( namedtuple("MDRVerbosity", "compute_distances find_data_regions identify_data_records") ): @classmethod def absolute_silent(cls): return cls(None, None, None) @property def is_absolute_silent(self): return any(val is None for val in self) @classmethod def silent(cls): return cls(False, False, False) @classmethod def only_compute_distances(cls): return cls(True, False, False) @classmethod def only_find_data_regions(cls): return cls(False, True, False) @classmethod def only_identify_data_records(cls): return cls(False, False, True) class UsedMDRException(Exception): default_message = "This MDR instance has already been used. Please instantiate another one." def __init__(self, *args, **kwargs): if not (args or kwargs): args = (self.default_message,) super(Exception, self).__init__(*args, **kwargs) # noinspection PyArgumentList class MDR: """ Notation: gn = gnode = generalized node dr = data region """ MINIMUM_DEPTH = 3 def __init__(self, max_tag_per_gnode, edit_distance_threshold, verbose=None, keep_all_data_regions=False): self.max_tag_per_gnode = max_tag_per_gnode self.edit_distance_threshold = edit_distance_threshold self.keep_all_data_regions = keep_all_data_regions self._verbose = verbose if verbose is not None else MDRVerbosity.silent() self._phase = None self._used = False def _debug(self, msg, tabs=0, force=False): if self._verbose.is_absolute_silent: return if self._verbose[self._phase] or force: if type(msg) == str: print(tabs * '\t' + msg) else: FormatPrinter({float: ".2f", GNode: "!s", GNodePair: "!s", DataRegion: "!s"}).pprint(msg) def _debug_phase(self, phase): if self._phase is not None: title = " END PHASE {} ({}) ".format(MDRVerbosity._fields[self._phase].upper(), self._phase) self._debug(">" * 20 + title + "<" * 20 + "\n\n", force=True) self._phase = phase if self._phase <= 2: title = " START PHASE {} ({}) ".format(MDRVerbosity._fields[self._phase].upper(), self._phase) self._debug(">" * 20 + title + "<" * 20, force=True) @staticmethod def depth(node): d = 0 while node is not None: d += 1 node = node.getparent() return d @staticmethod def gnode_to_string(list_of_nodes): return " ".join([ lxml.etree.tostring(child).decode('utf-8') for child in list_of_nodes ]) def __call__(self, root): if self._used: raise UsedMDRException() self._used = True # todo(improvement) change the other naming method to use this class NodeNamer(object): def __init__(self): self.tag_counts = defaultdict(int) self.map = {} def __call__(self, node, *args, **kwargs): if NODE_NAME_ATTRIB in node.attrib: return node.attrib[NODE_NAME_ATTRIB] # each tag is named sequentially tag = node.tag tag_sequential = self.tag_counts[tag] self.tag_counts[tag] += 1 node_name = "{0}-{1:0>5}".format(tag, tag_sequential) node.set(NODE_NAME_ATTRIB, node_name) return node_name @staticmethod def cleanup_tag_name(node): del node.attrib[NODE_NAME_ATTRIB] self._debug_phase(0) self.distances = {} self.node_namer = NodeNamer() self._compute_distances(root) # todo(prod): remove this self._debug("\n\nself.distances\n", force=True) self._debug(self.distances, force=True) self._debug("\n\n", force=True) self._debug_phase(1) self.data_regions = {} # {node_name(str): set(GNode)} only retains the max data regions self._all_data_regions_found = defaultdict(set) # retains all of them for debug purposes self._checked_gnode_pairs = defaultdict(set) self._find_data_regions(root) self._checked_gnode_pairs = dict(self._checked_gnode_pairs) self._all_data_regions_found = dict(self._all_data_regions_found) # todo(prod): remove this self._debug("\n\nself.data_regions\n", force=True) self._debug(self.data_regions, force=True) self._debug("\n\n", force=True) self._debug_phase(2) self.data_records = set() def get_node(node_name): tag = node_name.split("-")[0] # todo add some security stuff here??? node = root.xpath("//{tag}[@___tag_name___='{node_name}']".format(tag=tag, node_name=node_name))[0] return node self._find_data_records(get_node) # todo(prod): remove this self._debug("\n\nself.data_records\n", force=True) self.data_records = sorted(self.data_records) self._debug(self.data_records, force=True) self._debug("\n\n", force=True) self._debug_phase(3) # tdod cleanup aattrb ??? return self.data_records def _compute_distances(self, node): # !!! ATTENTION !!! this modifies the input HTML element by adding an attribute # todo: remember, in the last phase, to clear the `TAG_NAME_ATTRIB` from all tags node_name = self.node_namer(node) node_depth = MDR.depth(node) self._debug("in _compute_distances of `{}` (depth={})".format(node_name, node_depth)) if node_depth >= MDR.MINIMUM_DEPTH: # get all possible distances of the n-grams of children # {gnode_size: {GNode: float}} distances = self._compare_combinations(node.getchildren()) # todo(prod): remove this self._debug("`{}` distances".format(node_name)) self._debug(distances) else: self._debug("skipped (less than min depth = {})".format(self.MINIMUM_DEPTH), 1) distances = None self.distances[node_name] = distances # todo(prod): remove this self._debug("\n\n") for child in node: self._compute_distances(child) def _compare_combinations(self, node_list): """ Notation: gnode = "generalized node" :returns {gnode_size: {GNode: float}} """ self._debug("in _compare_combinations") if not node_list: self._debug("empty list --> return {}") return {} # {gnode_size: {GNode: float}} distances = defaultdict(dict) n_nodes = len(node_list) parent = node_list[0].getparent() parent_name = self.node_namer(parent) self._debug("n_nodes: {}".format(n_nodes)) # 1) for (i = 1; i <= K; i++) /* start from each node */ for starting_tag in range(1, self.max_tag_per_gnode + 1): self._debug('starting_tag (i): {}'.format(starting_tag), 1) # 2) for (j = i; j <= K; j++) /* comparing different combinations */ for gnode_size in range(starting_tag, self.max_tag_per_gnode + 1): # j self._debug('gnode_size (j): {}'.format(gnode_size), 2) # 3) if NodeList[i+2*j-1] exists then there_are_pairs_to_look = (starting_tag + 2 * gnode_size - 1) < n_nodes + 1 if there_are_pairs_to_look: # +1 for pythons open set notation self._debug(" ") # todo(prod): remove this self._debug(">>> if 1: there_are_pairs_to_look <<<", 3) # 4) St = i; left_gnode_start = starting_tag - 1 # st # 5) for (k = i+j; k < Size(NodeList); k+j) for right_gnode_start in range(starting_tag + gnode_size - 1, n_nodes, gnode_size): # k self._debug('left_gnode_start (st): {}'.format(left_gnode_start), 4) self._debug('right_gnode_start (k): {}'.format(right_gnode_start), 4) # 6) if NodeList[k+j-1] exists then right_gnode_exists = right_gnode_start + gnode_size < n_nodes + 1 if right_gnode_exists: self._debug(" ") # todo(prod): remove this self._debug(">>> if 2: right_gnode_exists <<<", 5) # todo(improvement): avoid recomputing strings? # todo(improvement): avoid recomputing edit distances? # todo(improvement): check https://pypi.org/project/strsim/ ? # NodeList[St..(k-1)] left_gnode = GNode(parent_name, left_gnode_start, right_gnode_start) left_gnode_nodes = node_list[left_gnode.start:left_gnode.end] left_gnode_str = MDR.gnode_to_string(left_gnode_nodes) # NodeList[St..(k-1)] right_gnode = GNode(parent_name, right_gnode_start, right_gnode_start + gnode_size) right_gnode_nodes = node_list[right_gnode.start:right_gnode.end] right_gnode_str = MDR.gnode_to_string(right_gnode_nodes) # 7) EditDist(NodeList[St..(k-1), NodeList[k..(k+j-1)]) edit_distance = normalized_levenshtein.distance(left_gnode_str, right_gnode_str) gnode_pair = GNodePair(left_gnode, right_gnode) self._debug( 'gnode pair = dist: {0:!s} = {1:.2f}'.format(gnode_pair, edit_distance), 5 ) # {gnode_size: {GNode: float}} distances[gnode_size][gnode_pair] = edit_distance # 8) St = k+j left_gnode_start = right_gnode_start else: self._debug("skipped, right node doesn't exist", 5) self._debug(' ') # todo(prod): remove this self._debug(' ') # todo(prod): remove this else: self._debug("skipped, there are no pairs to look", 3) self._debug(' ') # todo(prod): remove this self._debug(' ') return dict(distances) def _find_data_regions(self, node): node_name = self.node_namer(node) node_depth = MDR.depth(node) self._debug("in _find_data_regions of `{}`".format(node_name)) # 1) if TreeDepth(Node) => 3 then if node_depth >= MDR.MINIMUM_DEPTH: # 2) Node.DRs = IdenDRs(1, Node, K, T); data_regions = self._identify_data_regions(start_index=0, node=node) self.data_regions[node_name] = data_regions self._debug("`{}`: data regions found:".format(node_name), 1) self._debug(self.data_regions[node_name]) # 3) tempDRs = ∅; temp_data_regions = set() # 4) for each Child ∈ Node.Children do for child in node.getchildren(): # 5) FindDRs(Child, K, T); self._find_data_regions(child) # 6) tempDRs = tempDRs ∪ UnCoveredDRs(Node, Child); uncovered_data_regions = self._uncovered_data_regions(node, child) temp_data_regions = temp_data_regions | uncovered_data_regions self._debug("`{}`: temp data regions: ".format(node_name), 1) self._debug(temp_data_regions) # 7) Node.DRs = Node.DRs ∪ tempDRs self.data_regions[node_name] |= temp_data_regions self._debug("`{}`: data regions found (FINAL):".format(node_name), 1) self._debug(self.data_regions[node_name]) else: self._debug( "skipped (less than min depth = {}), calling recursion on children...\n".format(self.MINIMUM_DEPTH), 1 ) for child in node.getchildren(): self._find_data_regions(child) def _identify_data_regions(self, start_index, node): # tag_name = node.attrib[TAG_NAME_ATTRIB] # todo(prod): remove this if not needed anymore node_name = self.node_namer(node) self._debug("in _identify_data_regions node: {}".format(node_name)) self._debug("start_index:{}".format(start_index), 1) node_distances = self.distances.get(node_name) if not node_distances: self._debug("no distances, returning empty set") return set() # 1 maxDR = [0, 0, 0]; max_dr = DataRegion.empty() current_dr = DataRegion.empty() # 2 for (i = 1; i <= K; i++) /* compute for each i-combination */ for gnode_size in range(1, self.max_tag_per_gnode + 1): self._debug('gnode_size (i): {}'.format(gnode_size), 2) # 3 for (f = start; f <= start+i; f++) /* start from each node */ # for start_gnode_start_index in range(start_index, start_index + gnode_size + 1): for first_gn_start_idx in range(start_index, start_index + gnode_size): self._debug('first_gn_start_idx (f): {}'.format(first_gn_start_idx), 3) # 4 flag = true; dr_has_started = False # 5 for (j = f; j < size(Node.Children); j+i) # for left_gnode_start in range(start_node, len(node) , gnode_size): for last_gn_start_idx in range( # start_gnode_start_index, len(node) - gnode_size + 1, gnode_size first_gn_start_idx + gnode_size, len(node) - gnode_size + 1, gnode_size ): self._debug('last_gn_start_idx (j): {}'.format(last_gn_start_idx), 4) # 6 if Distance(Node, i, j) <= T then gn_last = GNode(node_name, last_gn_start_idx, last_gn_start_idx + gnode_size) gn_before_last = GNode(node_name, last_gn_start_idx - gnode_size, last_gn_start_idx) gn_pair = GNodePair(gn_before_last, gn_last) distance = node_distances[gnode_size][gn_pair] self._checked_gnode_pairs[node_name].add(gn_pair) self._debug("gn_pair (bef last, last): {!s} = {:.2f}".format(gn_pair, distance), 5) if distance <= self.edit_distance_threshold: self._debug('dist passes the threshold!'.format(distance), 6) # 7 if flag=true then if not dr_has_started: self._debug('it is the first pair, init the `current_dr`...'.format(distance), 6) # 8 curDR = [i, j, 2*i]; # current_dr = DataRegion(gnode_size, first_gn_start_idx - gnode_size, 2 * gnode_size) # current_dr = DataRegion(gnode_size, first_gn_start_idx, 2 * gnode_size) current_dr = DataRegion.binary_from_last_gnode(gn_last) self._debug('current_dr: {}'.format(current_dr), 6) # 9 flag = false; dr_has_started = True # 10 else curDR[3] = curDR[3] + i; else: self._debug('extending the DR...'.format(distance), 6) # current_dr = DataRegion( # current_dr[0], current_dr[1], current_dr[2] + gnode_size # ) current_dr = current_dr.extend_one_gnode() self._debug('current_dr: {}'.format(current_dr), 6) # 11 elseif flag = false then Exit-inner-loop; elif dr_has_started: self._debug('above the threshold, breaking the loop...', 6) break self._debug(" ") # todo(prod): remove this if self.keep_all_data_regions and not current_dr.is_empty: self._all_data_regions_found[node_name].add(current_dr) # 13 if (maxDR[3] < curDR[3]) and (maxDR[2] = 0 or (curDR[2]<= maxDR[2]) then # todo add a criteria that checks the avg distance when n_nodes_covered is the same and it starts at # the same node current_is_strictly_larger = max_dr.n_nodes_covered < current_dr.n_nodes_covered current_starts_at_same_node_or_before = ( max_dr.is_empty or current_dr.first_gnode_start_index <= max_dr.first_gnode_start_index ) if current_is_strictly_larger and current_starts_at_same_node_or_before: self._debug('current DR is bigger than max! replacing...', 3) # 14 maxDR = curDR; self._debug('old max_dr: {}, new max_dr: {}'.format(max_dr, current_dr), 3) max_dr = current_dr self._debug('max_dr: {}'.format(max_dr), 2) self._debug(" ") # todo(prod): remove this self._debug("max_dr: {}\n".format(max_dr)) # 16 if ( maxDR[3] != 0 ) then if not max_dr.is_empty: # 17 if (maxDR[2]+maxDR[3]-1 != size(Node.Children)) then last_covered_idx = max_dr.last_covered_tag_index self._debug("max_dr.last_covered_tag_index: {}".format(last_covered_idx)) if last_covered_idx < len(node) - 1: self._debug("calling recursion! \n") # 18 return {maxDR} ∪ IdentDRs(maxDR[2]+maxDR[3], Node, K, T) return {max_dr} | self._identify_data_regions(last_covered_idx + 1, node) # 19 else return {maxDR} else: self._debug("returning {{max_dr}}") return {max_dr} # 21 return ∅; self._debug("max_dr is empty, returning empty set") return set() def _uncovered_data_regions(self, node, child): node_name = self.node_namer(node) node_drs = self.data_regions[node_name] children_names = [self.node_namer(c) for c in node.getchildren()] child_name = self.node_namer(child) child_idx = children_names.index(child_name) # 1) for each data region DR in Node.DRs do for dr in node_drs: # 2) if Child in range DR[2] .. (DR[2] + DR[3] - 1) then if child_idx in dr: # 3) return null return set() # 4) return Child.DRs return self.data_regions[child_name] def _find_data_records(self, get_node_by_name: callable): self._debug("in _find_data_records") all_data_regions: Set[DataRegion] = set.union(*self.data_regions.values()) self._debug("total nb of data regions to check: {}".format(len(all_data_regions))) for dr in all_data_regions: self._debug("data region: {:!S}".format(dr), 1) method = self._find_records_1 if dr.gnode_size == 1 else self._find_records_n self._debug("selected method: `{}`".format(method.__name__), 2) self._debug(" ") # todo(prod) remove me gnode: GNode for gnode in dr: method(gnode, get_node_by_name) self._debug(" ") # todo(prod) remove me def _find_records_1(self, gnode: GNode, get_node_by_name: callable): """Finding data records in a one-component generalized node.""" self._debug('in `_find_records_1` for gnode `{:!S}`'.format(gnode), 2) parent_node = get_node_by_name(gnode.parent) node = parent_node[gnode.start] node_name = self.node_namer(node) node_children_distances = self.distances[node_name].get(1, None) if node_children_distances is None: self._debug("node doesn't have children distances, returning...", 3) return # 1) If all children nodes of G are similar # it is not well defined what "all .. similar" means - I consider that "similar" means "edit_dist < TH" # hyp 1: it means that every combination 2 by 2 is similar # hyp 2: it means that all the computed edit distances (every sequential pair...) is similar # for the sake of practicality and speed, I'll choose the hypothesis 2 all_children_are_similar = all(d <= self.edit_distance_threshold for d in node_children_distances.values()) # 2) AND G is not a data table row then node_is_table_row = node.tag == "tr" if all_children_are_similar and not node_is_table_row: self._debug("its children are data records", 3) # 3) each child node of R is a data record for i in range(len(node)): self.data_records.add(DataRecord([GNode(node_name, i, i + 1)])) # 4) else G itself is a data record. else: self._debug("it is a data record itself", 3) self.data_records.add(DataRecord([gnode])) # todo: debug this implementation with examples in the technical paper def _find_records_n(self, gnode: GNode, get_node_by_name: callable): """Finding data records in an n-component generalized node.""" self._debug('in `_find_records_n` for gnode `{:!S}`'.format(gnode), 2) parent_node: lxml.html.HtmlElement = get_node_by_name(gnode.parent) nodes = parent_node[gnode.start:gnode.end] numbers_children = [len(n) for n in nodes] childrens_distances = [self.distances[self.node_namer(n)].get(1, None) for n in nodes] all_have_same_nb_children = len(set(numbers_children)) == 1 childrens_are_similar = None not in childrens_distances and all( all(d <= self.edit_distance_threshold for d in child_distances) for child_distances in childrens_distances ) # 1) If the children nodes of each node in G are similar # 1...) AND each node also has the same number of children then if not (all_have_same_nb_children and childrens_are_similar): # 3) else G itself is a data record. self.data_records.add(DataRecord([gnode])) else: # 2) The corresponding children nodes of every node in G form a non-contiguous object description n_children = numbers_children[0] for i in range(n_children): self.data_records.add(DataRecord([ GNode(self.node_namer(n), i, i + 1) for n in nodes ])) # todo check a case like this # todo: debug this implementation def get_data_records_as_node_lists(self, root): def get_node(node_name): tag = node_name.split("-")[0] # todo add some security stuff here??? node = root.xpath("//{tag}[@___tag_name___='{node_name}']".format(tag=tag, node_name=node_name))[0] return node # return [[get_node(gn.parent)[gn.start:gn.end] for gn in dr] for dr in self.data_records] return [[get_node(gn.parent)[gn.start:gn.end] for gn in data_record] for data_record in self.data_records] # + pycharm={"name": "#%%\n", "is_executing": false} type(doc) # + pycharm={"name": "#%%\n", "is_executing": false} # %load_ext autoreload # %autoreload 2 folder = '.' filename = 'tables-1.html' # filename = 'tables-1-bis.html' # filename = 'tables-1-bisbis.html' doc = open_html_document(folder, filename) dot = html_to_dot(doc, name_option=SEQUENTIAL) edit_distance_threshold = 0.5 mdr = MDR( max_tag_per_gnode=3, edit_distance_threshold=edit_distance_threshold, verbose=MDRVerbosity.only_identify_data_records() # verbose=MDRVerbosity.silent() ) mdr(doc) # + pycharm={"name": "#%%\n", "is_executing": false} mdr.get_data_records_as_node_lists(doc) # + pycharm={"name": "#%%\n", "is_executing": false} import copy import random def gen_colors(n): ret = [] r = int(random.random() * 256) g = int(random.random() * 256) b = int(random.random() * 256) step = 256 / n for i in range(n): r += step + int(random.random() * 256 * 0.3) g += 2 * step + int(random.random() * 256 * 0.3) b += 3 * step + int(random.random() * 256 * 0.3) r = int(r) % 256 g = int(g) % 256 b = int(b) % 256 ret.append("{:0>2X}{:0>2X}{:0>2X}".format(r,g,b)) return ret def paint_data_records(mdr, doc): doc_copy = copy.deepcopy(doc) data_records = mdr.get_data_records_as_node_lists(doc_copy) colors = gen_colors(len(data_records)) for record, color in zip(data_records, colors): for gnode in record: for e in gnode: e.set("style", e.attrib.get("style", "") + " background-color: #{}!important;".format(color)) return doc_copy # + pycharm={"name": "#%%\n", "is_executing": false} gen_colors(3)[0] # + pycharm={"name": "#%%\n", "is_executing": false} painted_str = lxml.etree.tostring(paint_data_records(mdr, doc), pretty_print=True).decode("utf-8") with open("painted.html", "w") as f: f.write(painted_str) # + pycharm={"name": "#%%\n", "is_executing": false} # + pycharm={"name": "#%%\n", "is_executing": false}
dev/first_sketch/dev-8.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ### confusion matrix # $= \begin{bmatrix}TP & FN \\ FP & TN \end{bmatrix}$ # # ```python # sk.metrics.confusion_matrix(y_test, y_predict) # # # ``` # # - precision # - ${TP} \over {TP + FP}$ # - True라고 예측한 것 중 실제 True의 비율 # - 모델 입장에서 정답이라고 맞춘 경우 # # - recall # - ${TP} \over {TP + FN}$ # - 실제 True인 것 중에 True라고 예측한 것의 비율 # - 데이터 입장에서 정답이라고 맞춘경우 # # - 아직도 잘 모르겠다.. # + url = 'https://raw.githubusercontent.com/PinkWink/ML_tutorial/master/dataset/wine.csv' wine = pd.read_csv(url, index_col=0) wine['taste'] = [1. if grade > 5 else 0. for grade in wine['quality']] X = wine.drop(['taste', 'quality'], axis=1) y = wine['taste'] # 데이터 분리 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=13) # 로지스틱 회귀 from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score lr = LogisticRegression(solver='liblinear', random_state=13) lr.fit(X_train, y_train) y_pred_train = lr.predict(X_train) y_pred_test = lr.predict(X_test) print(f'Train Acc : {accuracy_score(y_train, y_pred_train)}') print(f'Test Acc : {accuracy_score(y_test, y_pred_test)}') # - # classificaion report from sklearn.metrics import classification_report print(classification_report(y_test, lr.predict(X_test))) # confusion matrix sk.metrics.confusion_matrix(y_test, lr.predict(X_test)) # precision_recall curve # %matplotlib inline plt.figure(figsize=(10, 8)) pred = lr.predict_proba(X_test)[:, 1] precisions, recalls, thresholds = sk.metrics.precision_recall_curve(y_test, pred) plt.plot(thresholds, precisions[:len(thresholds)], label='precision') plt.plot(thresholds, recalls[:len(thresholds)], label='recall') plt.grid(True); plt.legend(); plt.show(); # ## Boosting Algorithm # ### 앙상블 기법 # - voting, bagging, boosting, stacking 등 # - voting, bagging : 여러개의 분류가기 투표를 통해 최종 예측 결과를 결정하는 방식 # - voting : 각각 다른 분류기 사용 # --- # - bagging : 같은 분류기 사용 (ex) RandomForest # - Bootstrap AGGregatING # - 한번에 병렬적으로 결과를 얻음(parallel) # - boosting # - 여러개의 약한 분류기가 순차적으로 학습을 하면서, 앞에서 학습한 분류기가 예측이 틀린 데이터에 대해 다음 분류기가 가중치를 인가해서 학습을 이어 진행하는 방식 # - 예측 성능이 뛰어나 앙상블 학습을 주도 # - 순차적으로 진행(sequential) # # - gradient boost, XGBoost(eXtra), LightGBM 등 # # #### AdaBoost # - 순차적으로 가중치를 부여해서 최종 결과를 얻음. # - DecisionTree 기반 알고리즘 # - Steps # - 예측하여 +와 -의 경계를 설정 # - 틀린 + 에 가중치를 인가하고 경계를 다시 결정 # - 다시 놓친 - 에 가중치를 인가하고 경계를 다시 결정 # - 앞서 결정한 경계들을 합침 # --- # #### 부스팅 기법 # # - GBM(grdient boost machine): # - 가중치를 업데이트할 때 경사하강법을 사용, AdaBoost와 비슷 # - 부스팅 알고리즘은 여러 개의 약한 학습기를 순차적으로 **학습-예측**하면서 잘못 예측한 데이터에 가중치를 부여해서 오류를 개선해가는 방식 # - XGBoost # - GBM에서 PC의 파워를 효율적으로 사용하기 위한 다양한 기법에 채택되어 빠른 속도와 효율을 가짐 # - 트리기반의 앙상블 학습 중에 가장 각광받는 알고리즘 # - GBM의 느린 속도를 다양한 규제를 통해 해결 # - 병렬 학습이 가능하도록 설계 # - 반복 수행시마다 내부적으로 학습데이터와 검증데이터를 교차검증 # - 교차검증을 통해 최적화되면 반복을 중단하는 조기중단 기능이 있음 # # - LightGBM # - XGBoost보다 빠른 속도를 가짐 # - XGBoost와 함께 부스팅 계열에서 가장 각광받는 알고리즘 # - 적은 수의 데이터는 X (일반적으로 10000건 이상의 데이터가 필요하다고 함) # - GPU 버전 존재
machine_learning/datascienceschool/0402-preview3.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + # %pylab inline import pandas as pd import numpy as np import seaborn as sns sns.set_style('ticks') sns.set_context('paper') from matplotlib.colors import LogNorm from glob import glob import os, sys, pickle, requests from sklearn.metrics import r2_score from arnie.free_energy import free_energy from arnie.mfe import mfe from scipy.stats import pearsonr, spearmanr def corrfunc(x,y, ax=None, **kws): r, pval = spearmanr(x, y) ax = ax or plt.gca() m, b = np.poly1d(np.polyfit(x, y, 1)) xmin, xmax = ax.get_xlim() plt.plot([xmin,xmax],[xmin*m+b,xmax*m+b],c='k',linestyle=':') ax.set_xlim([xmin,xmax]) rho = '\u03C1' ax.annotate(f'R:{r:.2f}', xy=(.65, .9), xycoords=ax.transAxes) # + df = pd.read_csv('posthoc_nr_collated_predictions_233x.csv') df['k_deg_full_length_normalize'] = df['k_deg_per_hour']/df['length'] df_filter = df.loc[df['single_exp_fit_ok']==1][df['k_deg_per_hour'] > 0] df_filter = df_filter.loc[df_filter['Expt type']!='COV2 Eterna'] df_filter = df_filter.loc[df_filter['k_deg_err_per_hour'] < 0.15] #remove one spurious high error point df_filter['half_life'] = np.log(2)/df_filter['k_deg_per_hour'] df_filter['half_life_err'] = df_filter['half_life']*df_filter['k_deg_err_per_hour']/df_filter['k_deg_per_hour'] df_filter['half_life_normalize'] = df_filter['half_life']*df_filter['RT_PCR_length'] df_filter['half_life_err_normalize'] = df_filter['half_life_err']*df_filter['RT_PCR_length'] # - sns.swarmplot(x='Expt type', y='k_deg_err_per_hour', data=df_filter) # + predictor_list = ['EternaFold', 'DegScore2.1', 'Degscore-XGB','nullrecurrent','kazuki2'] labels = ['p(unpaired)', 'DegScore (Leppek, 2021)', 'DegScore-XGBoost', 'Kaggle 1st (nullrecurrent)','Kaggle 2nd (kazuki2)'] def rmse(x, y): return np.sqrt(np.mean(np.square(x-y))) figure(figsize=(12,2)) nrows, ncols= 1,5 for i, k in enumerate(predictor_list): subplot(nrows, ncols,i+1) errorbar(df_filter['half_life_normalize'], df_filter['AUP %s PCR'% k], xerr = df_filter['half_life_err_normalize'],fmt='.', color='k', zorder=0, markersize=0 ) sns.scatterplot(x='half_life_normalize', y='AUP %s PCR'% k, hue='Expt type', data = df_filter, linewidth=0) sns.scatterplot(x='half_life_normalize', y='AUP %s PCR'% k, data = df_filter.loc[df_filter['Human readable name'].str.contains('Yellowstone')], edgecolor='k', marker='*',color='red', s=150,zorder=10) sns.scatterplot(x='half_life_normalize', y='AUP %s PCR'% k, data = df_filter.loc[df_filter['Human readable name'].str.contains('jiabei')], edgecolor='k', marker='*',color='red', s=150,zorder=10) ylabel(labels[i]) #xlim([0,0.0015]) #xticks([0,0.0005, 0.001,0.0015], ['0','0.5', '1','1.5']) corrfunc(df_filter['half_life_normalize'], df_filter['AUP %s PCR'% k]) #ylim([0,0.7]) xlabel('Half life per nt (hr)') if i!=4: legend([],frameon=False) else: legend(bbox_to_anchor=(1,1),frameon=False) tight_layout() # savefig('scatterplot_half_lives_233x_24Sep2021.pdf', bbox_inches='tight') # savefig('scatterplot_half_lives_233x_24Sep2021.png', dpi=300, bbox_inches='tight') # + tmp = np.loadtxt('formatted_predictions/nullrecurrent_FULL_233x.csv',delimiter=',') example_vec = tmp[109] imshow(example_vec[:928].reshape(1,-1), aspect=50, cmap='gist_heat_r') yticks([]) # - # ## Estimate experimental error upper limit on half-life - degradation rate spearman correlation # + r_list=[] for _ in range(100): tmp = df_filter.sample(frac=1) resampled_kdegs = np.random.normal(list(tmp['k_deg_per_hour'].values), list(tmp['k_deg_err_per_hour'].values)) r, p = spearmanr(tmp['half_life'], resampled_kdegs) r_list.append(r) np.mean(r_list) # - # Not taking into account PCR start/end locations results in lower correlations overall, but with same trends. # + corr_df = pd.DataFrame() corr_df_norm = pd.DataFrame() for typ2 in ['FULL','PCR']: for pred in predictor_list: r, _ = pearsonr(df_filter["SUP %s %s" % (pred, typ2)], df_filter['k_deg_per_hour']) corr_df = corr_df.append({'Region':typ2, 'Pearson R': r,'Predictor':pred},ignore_index=True) if typ2=='FULL': r, _ = pearsonr(df_filter["AUP %s %s" % (pred, typ2)], df_filter['k_deg_full_length_normalize']) else: r, _ = pearsonr(df_filter["AUP %s %s" % (pred, typ2)], df_filter['k_deg_normalize']) corr_df_norm = corr_df_norm.append({'Region':typ2, 'Pearson R': r,'Predictor':pred},ignore_index=True) figure(figsize=(6,3)) subplot(1,2,1) sns.barplot(x='Region',y='Pearson R', data=corr_df, hue='Predictor') title('Not length-normalized') ylim([0,1]) legend([],frameon=False) subplot(1,2,2) title('length-normalized') sns.barplot(x='Region',y='Pearson R', data=corr_df_norm, hue='Predictor') ylim([0,1]) legend(title='Predictor', frameon=False) tight_layout() # -
data/mRNA_233x_data/.ipynb_checkpoints/RegenerateFigure5_posthoc-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## dash_oil_and_gas # #### show the use of dashapp in building the Dash Oil and Gas Gallery app # + import sys,os if not os.path.abspath('./') in sys.path: sys.path.append(os.path.abspath('./')) if not os.path.abspath('../') in sys.path: sys.path.append(os.path.abspath('../')) import dashapp # import dash import dash_html_components as html import dash_core_components as dcc import pandas as pd import pdb import copy pn = dashapp.pn pnnc = dashapp.pnnc # - # ### First define a url_base_pathname, used later in the app definition. # The url_base_pathname is useful if you are accessing the app via something like an nginx proxy. url_base_pathname = None # url_base_pathname = '/oilgas/' logger = dashapp.init_root_logger() # ### dash oil and gas # #### Get Data # + df_well_info = pd.read_csv('oil_gas_data/df_well_info.csv',low_memory=False) df_well_production_by_year = pd.read_csv('oil_gas_data/df_well_production_by_year.csv') df_well_status = df_well_info[['Well_Status','wstatus']].drop_duplicates().sort_values('Well_Status') df_well_status.index = list(range(len(df_well_status))) df_well_type = df_well_info[['Well_Type','wtype']].drop_duplicates().sort_values('Well_Type') df_well_type.index = list(range(len(df_well_type))) df_well_color = df_well_info[['Well_Type','wcolor']].drop_duplicates().sort_values('Well_Type') df_well_color.index = list(range(len(df_well_color))) well_status_options = [{"label": wt[1], "value": wt[0]} for wt in df_well_status.values] well_type_options = [{"label": wt[1], "value": wt[0]} for wt in df_well_type.values] well_color_options = [{"label": wt[1], "value": wt[0]} for wt in df_well_color.values] # - # ### Define a method to aggregate well data for panel and graph display def get_well_aggregates(df_in,year_array,well_status_list=None,well_type_list=None): df_temp = df_in[(df_in.Year_Well_Completed>=year_array[0]) & (df_in.Year_Well_Completed<=year_array[1])] df_ptemp = df_well_production_by_year[(df_well_production_by_year.year>=year_array[0])&(df_well_production_by_year.year<=year_array[1])] df_ptemp = df_ptemp[df_ptemp.API_WellNo.isin(df_temp.API_WellNo.unique())] if well_status_list is not None: valid_status_ids = df1[df1.Well_Status.isin(well_status_list)].API_WellNo.values df_ptemp = df_ptemp[df_ptemp.API_WellNo.isin(valid_status_ids)] if well_type_list is not None: valid_type_ids = df1[df1.Well_Type.isin(well_type_list)].API_WellNo.values df_ptemp = df_ptemp[df_ptemp.API_WellNo.isin(valid_type_ids)] wells = len(df_temp.API_WellNo.unique()) agg_data = { 'wells':wells, 'gas':round(df_ptemp.gas.sum()/1000000,1), 'water':round(df_ptemp.water.sum()/1000000,1), 'oil':round(df_ptemp.oil.sum()/1000000,1) } return agg_data # ### Define Row 1 def define_r1(): # Define the static components # ********************** plotly logo **************************** imgfolder = '' if url_base_pathname is None else url_base_pathname img_logo = html.Img(id='img_logo',src=imgfolder + "/assets/dash-logo.png",className='plogo') # ********************** title div ******************************** title = html.Div( [html.H3("New York Oil And Gas",className='ogtitle'), html.H5("Production Overview",className='ogtitle')],id='title') # *****You ************* link to plotly info *********************** adiv = html.A([html.Button(["Learn More"],className='ogabutton')],id='adiv',href="https://plot.ly/dash/pricing",className='adiv') r1 = dashapp.multi_column_panel([img_logo,title,adiv],grid_template='1fr 4fr 1fr', parent_class=None,child_class=pnnc) return r1 # ## Define Row 2 # ### Define Row 2 Column 1 # + def define_r2c1(): slider = dashapp.make_slider(df_well_info,'yr_slider','Year_Well_Completed',className='oil_gas_r2_margin') slider_div = html.Div([ 'Filter by construction date (or select range in histogram):', html.P(),slider],id='slider_div') # ********************* well status radio ***************************** df_radio_status = pd.DataFrame({'label':['All','Active only','Customize'], 'value':['all','active','custom']}) radio_status = dashapp.make_radio(df_radio_status,'radio_status','value',label_column='label', current_value='all') radio_status_div = html.Div([radio_status,'Filter by well status:',html.P()], id='radio_status_div',className='oil_gas_r2_margin') # ********************* well status dropdown ***************************** dropdown_status = dashapp.make_dropdown(df_well_status,'dropdown_status', 'Well_Status',label_column='wstatus', current_value = df_well_status.Well_Status.unique(), multi=True) dropdown_status_div = html.Div(dropdown_status,className='oil_gas_d1_margin',id='dropdown_status_div') # ********************* link well status radio to dropdown ***************************** def link_radio_status_dropdown_status_options_callback(radio_status): if radio_status.lower()=='all': ret = well_status_options elif radio_status.lower()=='active': ret = [wso for wso in well_status_options if wso['value']=='AC'] else: ret = {} return ret link_radio_status_dropdown_status_options = dashapp.radio_to_dropdown_options_link( radio_status, dropdown_status, link_radio_status_dropdown_status_options_callback) lambda_rsds_value = lambda radio_value:[wso['value'] for wso in link_radio_status_dropdown_status_options_callback(radio_value)] link_radio_status_dropdown_status_value_callback = lambda_rsds_value link_radio_status_dropdown_status_value = dashapp.radio_to_dropdown_value_link( radio_status, dropdown_status, link_radio_status_dropdown_status_value_callback) # ********************* well type radio ***************************** df_radio_type = pd.DataFrame({'label':['All','Productive only','Customize'], 'value':['all','productive','custom']}) radio_type = dashapp.make_radio(df_radio_type,'radio_type','value',label_column='label', current_value='all') radio_type_div = html.Div([radio_type,'Filter by well status:',html.P()], id='radio_type_div',className='oil_gas_r2_margin') # ********************* well type dropdown ***************************** dropdown_type = dashapp.make_dropdown(df_well_type,'dropdown_type', 'Well_Type',label_column='wtype', current_value = df_well_type.Well_Type.unique(), multi=True,className='oil_gas_d1_margin') dropdown_type_div = html.Div(dropdown_type,id='dropdown_type_div') # ********************* link well status radio to dropdown ***************************** def link_radio_type_dropdown_type_options_callback(radio_type): if radio_type.lower()=='all': ret = well_type_options elif radio_type.lower()=='productive': ret = [wto for wto in well_type_options if wto['value'] in ["GD", "GE", "GW", "IG", "IW", "OD", "OE", "OW"]] else: ret = {} return ret link_radio_type_dropdown_type_options = dashapp.radio_to_dropdown_options_link( radio_type, dropdown_type, link_radio_type_dropdown_type_options_callback) lambda_rtdt_value = lambda radio_value:[wso['value'] for wso in link_radio_type_dropdown_type_options_callback(radio_value)] link_radio_type_dropdown_type_value_callback = lambda_rtdt_value link_radio_type_dropdown_type_value = dashapp.radio_to_dropdown_value_link( radio_type, dropdown_type, link_radio_type_dropdown_type_value_callback) # link_radio_status_dropdown_status_options,link_radio_status_dropdown_status_value, # link_radio_type_dropdown_type_options,link_radio_type_dropdown_type_value divs = [slider_div,radio_status_div,dropdown_status_div,radio_type_div,dropdown_type_div] links = [link_radio_status_dropdown_status_options,link_radio_status_dropdown_status_value, link_radio_type_dropdown_type_options,link_radio_type_dropdown_type_value] return divs,links # - # ### Define Row 2 Column 2 # # #### Define r2c2_store # + r2c2_store = dcc.Store(id='r2c2_store',data={}) def _build_df_from_input_list(input_list,logger=None): year_list = input_list[0] year_low = int(str(year_list[0])) year_high = int(str(year_list[1])) df_temp = df_well_info[(df_well_info.Year_Well_Completed>=year_low) & (df_well_info.Year_Well_Completed<=year_high)] status_list = input_list[1] type_list = input_list[2] try: df_temp = df_temp[df_temp.Well_Status.isin(status_list)] df_temp = df_temp[df_temp.Well_Type.isin(type_list)] except Exception as e: if logger is not None: logger.warn(f'EXCEPTION: _build_main_data_dictionary {str(e)}') return df_temp def build_link_r2c2_store(input_list): # print(f"build_link_r2c2_store input_list: {input_list}") year_list = input_list[0] year_low = int(str(year_list[0])) year_high = int(str(year_list[1])) df_temp = _build_df_from_input_list(input_list,logger) df_temp2 = df_temp[["API_WellNo", "Year_Well_Completed"]].groupby(['Year_Well_Completed'],as_index=False).count() #{'wells': 14628, 'gas': 865.4, 'water': 15.8, 'oil': 3.8} aggs = get_well_aggregates(df_temp,[year_low,year_high]) ret = { 'data':df_temp2.to_dict('rows'), 'year_list':year_list, 'status_list':input_list[1], 'type_list':input_list[2], 'no_wells':f"{aggs['wells']} No of", 'gas_mcf':f"{aggs['gas']}mcf", 'oil_bbl':f"{aggs['oil']}M bbl", 'water_bbl':f"{aggs['water']}M bbl" } return [ret] link_r2c2_store = dashapp.DashLink( [('yr_slider','value'),('dropdown_status','value'),('dropdown_type','value')], [(r2c2_store,'data')],build_link_r2c2_store) # - # #### Define Row 2 Column 2 Row 1 def define_r2c2r1(r2c2_store): r2c2r1_no_wells = html.Div(id='no_wells') r2c2r1_gas_mcf = html.Div(id='gas_mcf') r2c2r1_oil_bbl = html.Div(id='oil_bbl') r2c2r1_water_bbl = html.Div(id='water_bbl') # create an array of div id's that you will use when creating DashLink instances below r2c2r1_panel_ids = ['no_wells','gas_mcf','oil_bbl','water_bbl'] def build_panel_link_closure(panel_id): def build_panel_link(input_list): # print(f'build_panel_link input_list: {input_list}') r2c2_store = input_list[0] if panel_id not in r2c2_store: dashapp.stop_callback(f'build_panel_link no data for panel_id {panel_id} with data {input_list}',logger) ret = r2c2_store[panel_id] return [ret] return build_panel_link # define array of links to store component, and the loop through r2c2r1_panel_ids to # create a DashLink instance for each panel (there are 4) r2c2r1_links = [] for panel_id in r2c2r1_panel_ids: r2c2r1_link = dashapp.DashLink( [(r2c2_store,'data')],[(panel_id,'children')], build_panel_link_closure(panel_id) ) r2c2r1_links.append(r2c2r1_link) r2c2r1_wells_div = html.Div([r2c2r1_no_wells,html.P('Wells')],id='wells_div') r2c2r1_gas_div = html.Div([r2c2r1_gas_mcf,html.P('Gas')],id='gas_div') r2c2r1_oil_div = html.Div([r2c2r1_oil_bbl,html.P('Oil')],id='oil_div') r2c2r1_water_div = html.Div([r2c2r1_water_bbl,html.P('Water')],id='water_div') r2c2r1_divs = [r2c2r1_wells_div,r2c2r1_gas_div, r2c2r1_oil_div,r2c2r1_water_div,r2c2_store] return r2c2r1_divs,r2c2r1_links # #### Define Row 2 Column 2 Row 2 (*the graph of wells per year, and given the values from the dropdowns in r2c1*) def define_r2c2r2(r2c2_store): def xygraph_fig(df_wells_per_year): xyfig = dashapp.plotly_plot( df_in=df_wells_per_year, x_column='Year_Well_Completed',bar_plot=True,number_of_ticks_display=10, plot_title='Completed Wells/Year') return xyfig df_wells_per_year = df_well_info[["API_WellNo", "Year_Well_Completed"]].groupby(['Year_Well_Completed'],as_index=False).count() init_fig = xygraph_fig(df_wells_per_year) xygraph = dcc.Graph(id='xygraph',figure=init_fig) # create the call back that will react to changes in r2c2_store, and modify the graph in r2c2r2 def build_link_store_xygraph(input_list): r2c2_store = input_list[0] if 'data' not in r2c2_store: dashapp.stop_callback(f'build_link_store_xygraph no DataFrame for graph {input_list}',logger) dict_df = r2c2_store['data'] df_wells_per_year = dashapp.make_df(dict_df) xyfig = xygraph_fig(df_wells_per_year) return [xyfig] link_store_xygraph = dashapp.DashLink([(r2c2_store,'data')],[(xygraph,'figure')],build_link_store_xygraph) return xygraph,link_store_xygraph # #### Define Row 3 (*the maps of wells per year, and given the values from the dropdowns in r2c1*) # + # ************* Build row 3: the map and pie charts ******************************** mapbox_access_token = "<KEY>" layout = dict( autosize=True, automargin=True, margin=dict(l=30, r=30, b=20, t=40), hovermode="closest", plot_bgcolor="#F9F9F9", paper_bgcolor="#F9F9F9", legend=dict(font=dict(size=10), orientation="h"), title="Satellite Overview", mapbox=dict( accesstoken=mapbox_access_token, style="light", center=dict(lon=-78.05, lat=42.54), zoom=7, ), ) def define_r3c1(): def _create_map_from_df(df_in): traces = [] for wtype, dfff in df_in.groupby("wtype"): trace = dict( type="scattermapbox", lon=dfff["Surface_Longitude"], lat=dfff["Surface_latitude"], text=dfff["Well_Name"], customdata=dfff["API_WellNo"], name=wtype, marker=dict(size=4, opacity=0.6), ) traces.append(trace) figure = dict(data=traces, layout=layout) return figure def build_map_figure(input_list): r2c2_store = input_list[0] if ('year_list' not in r2c2_store) or ('status_list' not in r2c2_store) or ('type_list' not in r2c2_store): dashapp.stop_callback(f'build_link_store_xygraph insufficient data for graph {input_list}',logger) yl = r2c2_store['year_list'] sl = r2c2_store['status_list'] tl = r2c2_store['type_list'] original_input_list = [yl,sl,tl] dff = _build_df_from_input_list(original_input_list) fig = _create_map_from_df(dff) return [fig] init_map_figure = _create_map_from_df(df_well_info) mapgraph = dcc.Graph(id='mapgraph',figure=init_map_figure) link_mapgraph = dashapp.DashLink( # [(slider,'value'),(dropdown_status,'value'),(dropdown_type,'value')], [(r2c2_store,'data')], [(mapgraph,'figure')],build_map_figure) return mapgraph,link_mapgraph def define_r3c2(): def _create_pie_figure_from_df(dff,years): layout_pie = copy.deepcopy(layout) selected = dff["API_WellNo"].values year_low = years[0] year_high = years[1] aggs = get_well_aggregates(dff,[year_low,year_high]) index = aggs['wells'] gas = aggs['gas'] oil = aggs['oil'] water = aggs['water'] # create a DataFrame that holds counts of wells by type, sorted by wtype df_well_count = dff[['wtype','wcolor']].sort_values("wtype").groupby(["wtype"],as_index=False).count() df_well_count = df_well_count.rename(columns={'wcolor':'type_count'}) # Create a DataFrame that holds unique combinations of type and color, sorted by wtype df_well_color = dff[['wtype','wcolor']].drop_duplicates().sort_values('wtype') data = [ dict( type="pie", labels=["Gas", "Oil", "Water"], values=[gas, oil, water], name="Production Breakdown", text=[ "Total Gas Produced (mcf)", "Total Oil Produced (bbl)", "Total Water Produced (bbl)", ], hoverinfo="text+value+percent", textinfo="label+percent+name", hole=0.5, marker=dict(colors=["#fac1b7", "#a9bb95", "#92d8d8"]), domain={"x": [0, 0.45], "y": [0.2, 0.8]}, ), dict( type="pie", labels=df_well_count.wtype.values, # this works b/c it's sorted by wtype values=df_well_count.type_count.values, # this works b/c it's sorted by wtype name="Well Type Breakdown", hoverinfo="label+text+value+percent", textinfo="label+percent+name", hole=0.5, marker=dict(colors=df_well_color.wcolor.values), # this works b/c it's sorted by wtype domain={"x": [0.55, 1], "y": [0.2, 0.8]}, ), ] layout_pie["title"] = "Production Summary: {} to {}".format( year_low, year_high ) layout_pie["font"] = dict(color="#777777") layout_pie["legend"] = dict( font=dict(color="#CCCCCC", size="10"), orientation="h", bgcolor="rgba(0,0,0,0)" ) figure = dict(data=data, layout=layout_pie) return figure def build_pie_figure(input_list): r2c2_store = input_list[0] if ('year_list' not in r2c2_store) or ('status_list' not in r2c2_store) or ('type_list' not in r2c2_store): dashapp.stop_callback(f'build_pie_figure insufficient data for graph {input_list}',logger) yl = r2c2_store['year_list'] sl = r2c2_store['status_list'] tl = r2c2_store['type_list'] original_input_list = [yl,sl,tl] dff = _build_df_from_input_list(original_input_list) fig = _create_pie_figure_from_df(dff,yl) return [fig] # piegraph = dgc.FigureComponent('piegraph',None,_create_pie_figure,input_tuple_list=input_component_list) init_years = [df_well_info.Year_Well_Completed.min(), df_well_info.Year_Well_Completed.max()] init_pie_figure = _create_pie_figure_from_df(df_well_info,init_years) piegraph = dcc.Graph(id='piegraph',figure=init_pie_figure) link_piegraph = dashapp.DashLink( # [(slider,'value'),(dropdown_status,'value'),(dropdown_type,'value')], [(r2c2_store,'data')], [(piegraph,'figure')],build_pie_figure) return piegraph,link_piegraph def define_r3(): mapgraph,link_mapgraph = define_r3c1() piegraph,link_piegraph = define_r3c2() chart_divs = [mapgraph,piegraph] chart_links = [link_mapgraph,link_piegraph] return chart_divs,chart_links # - # ## Define row 4, which displays the main DataFrame # + import importlib importlib.reload(dashapp) dt_title = html.Div( [html.P(),html.H3("All Data"),html.P()]) r4_title = dashapp.multi_column_panel([dt_title],child_class=pn,parent_class=None) init_display_columns = ['API_WellNo','Cnty','Completion','Well_Name','wstatus','wtype', 'Year_Well_Completed','Month_Well_Completed'] init_display_columns = df_well_info.columns.values df_wi_init = df_well_info[init_display_columns]#.iloc[0:20] dt_well_info,link_for_dynamic_paging = dashapp.make_dashtable('dt_well_info',df_in=df_wi_init,filtering=True) r4_dt = dashapp.nopanel_cell(dt_well_info) # - # ## Put all of the rows together if __name__=='__main__': dap = dashapp.DashApp() # define title row r1 = define_r1() # define r2c1 with slider 2 radios and 2 dropdowns r2c1_divs,r2c1_links = define_r2c1() r2c1 = dashapp.multi_row_panel(r2c1_divs,child_class=pnnc,parent_class='oil_gas_r2c1') # define r2c2r1, which has the well count panels r2c2r1_divs,r2c2r1_links = define_r2c2r1(r2c2_store) r2c2r1 = dashapp.multi_column_panel(r2c2r1_divs,grid_template=' '.join(['1fr']*4), parent_class=None,child_class=pn) # define the graph below the count panels in r2c2r2 xygraph,link_store_xygraph = define_r2c2r2(r2c2_store) r2c2r2 = dashapp.multi_column_panel([xygraph],grid_template='1fr') # combine r2c2r1 and r2c2r2 r2c2 = dashapp.multi_row_panel([r2c2r1,r2c2r2],grid_template='1fr 6fr',child_class=None) # combine r2c1 and r2c2 r2 = dashapp.multi_column_panel([r2c1,r2c2],grid_template='35fr 85fr',parent_class=None,child_class=None) # define row 3, the map and pie graphs chart_divs,chart_links = define_r3() r3 = dashapp.multi_column_panel(chart_divs,grid_template='1fr 1fr',parent_class=None, child_class = None) # define row 4, which holds dashtable r4 = dashapp.multi_row_panel([r4_title,r4_dt],grid_template='1fr 20fr',child_class=None) # combine all rows rows = [r1,r2,r3,r4] # combine all links links = r2c1_links+r2c2r1_links+[link_r2c2_store,link_store_xygraph,link_for_dynamic_paging]+chart_links # merge all rows into a single panel all_cols = dashapp.multi_row_panel(rows,grid_template='5fr 45fr',parent_class=None,child_class=None) # add the links to the DashApp instance dap.add_links(links) # run the app dap.create_app(all_cols,app_port=8801,app_title='Dash Oil Gas') # + # # !jupyter nbconvert --to script dash_oil_gas.ipynb # -
dashapp/dash_oil_gas.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 5 15:49:49 2018 DAE for Seismic Denoising @author: maihao """ 'This is an atuoencoder denoising application' __author__ = '<NAME>' from keras.layers import Input, Convolution2D, MaxPooling2D, UpSampling2D from keras.models import Model from keras.datasets import mnist from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets import numpy as np import matplotlib.pyplot as plt from keras.callbacks import TensorBoard # + import scipy.io as sio DATA = sio.loadmat( '/Users/maihao/Documents/MATLAB/Syn/mat/SynModel512/e.mat') #DATA = sio.loadmat('/Users/maihao/Documents/MATLAB/X1.mat') ascent = DATA['e'].copy() height, width = ascent.shape x_train = ascent.copy() x_test = ascent.copy() x_train = np.reshape(x_train, (1, height, width, 1)) x_test = np.reshape(x_test, (1, height, width, 1)) x_train = np.clip(x_train, 0., 1.) x_test = np.clip(x_test, 0., 1.) noise_factor = 0.5 x_train_noisy = x_train + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_train.shape) x_test_noisy = x_test + noise_factor * np.random.normal(loc=0.0, scale=1.0, size=x_test.shape) x_train_noisy = np.clip(x_train_noisy, 0., 1.) x_test_noisy = np.clip(x_test_noisy, 0., 1.) print(x_train.shape) print(x_test.shape) # + #training setteings input_img = Input(shape=(height, width, 1)) x = Convolution2D(64, (3, 3), activation='relu', padding='same')(input_img) x = MaxPooling2D((2, 2), padding='same')(x) x = Convolution2D(64, (3, 3), activation='relu', padding='same')(x) encoded = MaxPooling2D((2, 2), padding='same')(x) x = Convolution2D(64, (3, 3), activation='relu', padding='same')(encoded) x = UpSampling2D((2, 2))(x) x = Convolution2D(64, (3, 3), activation='relu', padding='same')(x) x = UpSampling2D((2, 2))(x) decoded = Convolution2D(1, (3, 3), activation='sigmoid', padding='same')(x) autoencoder = Model(inputs=input_img, outputs=decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') # + # 打开一个终端并启动TensorBoard,终端中输入 tensorboard --logdir=/autoencoder autoencoder.fit(x_train_noisy, x_train, epochs=30, batch_size=256, shuffle=True, validation_data=(x_test_noisy, x_test), callbacks=[TensorBoard(log_dir='autoencoder', write_graph=False)]) decoded_imgs = autoencoder.predict(x_test_noisy) # + n = 1 plt.figure(figsize=(50, 10)) for i in range(n): ax = plt.subplot(3, n, i + 1) plt.title('Orignal Image') plt.imshow(x_test[i].reshape(height, width)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(3, n, i + 1 + n) plt.title('Noised Image') plt.imshow(x_test_noisy[i].reshape(height, width)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax = plt.subplot(3, n, i + 1 + 2*n) plt.title('Denoised Image') plt.imshow(decoded_imgs[i].reshape(height, width)) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() # - # **The results figure dpi is bad . png format is shown in the filefolder.**
autoencoder/SeisAutoEncoder.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/lakshit2808/Machine-Learning-Notes/blob/master/ML_Models/Classification/KNearestNeighbor/KNN_first_try.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="9FOrUQ0CjOim" # # K-Nearest Neighbor # **K-Nearest Neighbors** is an algorithm for supervised learning. Where the data is 'trained' with data points corresponding to their classification. Once a point is to be predicted, it takes into account the 'K' nearest points to it to determine it's classification. # # + [markdown] id="RhdNqE-0jOip" # ### Here's an visualization of the K-Nearest Neighbors algorithm. # # <img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/Module%203/images/KNN_Diagram.png"> # # + [markdown] id="HPkHyqAzjOiq" # In this case, we have data points of Class A and B. We want to predict what the star (test data point) is. If we consider a k value of 3 (3 nearest data points) we will obtain a prediction of Class B. Yet if we consider a k value of 6, we will obtain a prediction of Class A.<br><br> # In this sense, it is important to consider the value of k. But hopefully from this diagram, you should get a sense of what the K-Nearest Neighbors algorithm is. It considers the 'K' Nearest Neighbors (points) when it predicts the classification of the test point. # # # + [markdown] id="MuOacnADjOir" # ## 1. Importing Libraries # + id="fxUz-xLzjOit" import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing # + [markdown] id="HU5JFn5sjOiu" # ## 2. Reading Data # + id="VLLNzzIrjOiu" outputId="1051674e-b20e-4a48-ca4c-df92efd5189f" df = pd.read_csv('teleCust.csv') df.head() # + [markdown] id="AqCwG2cfjOiw" # ## 3. Data Visualization and Analysis # #### Let’s see how many of each class is in our data set # # + id="VtdzVzISjOix" outputId="a7a1281f-8559-4218-95fc-48db36c35afa" df['custcat'].value_counts() # + [markdown] id="TIgBhlcnjOiy" # The target field, called **custcat**, has four possible values that correspond to the four customer groups, as follows: # 1. Basic Service # 2. E-Service # 3. Plus Service # 4. Total Service # # + id="sOmpXHqijOiz" outputId="ffcd065c-8716-47ee-9055-207a2987a6d6" df.hist(column='income' , bins=50) # + [markdown] id="O9d2o1kljOi0" # ### Feature Set # Let's Define a feature set: X # + id="SWvGiIY2jOi1" outputId="8d1fe388-7331-4d7e-ce40-8e0aa7528b88" df.columns # + [markdown] id="z2c8zbw1jOi2" # To use scikit-learn library, we have to convert the Pandas data frame to a Numpy array: # # + id="iN8q9uYcjOi2" outputId="2243517f-40ec-447b-bacc-f9b78fa84eff" X = df[['region', 'tenure', 'age', 'marital', 'address', 'income', 'ed', 'employ', 'retire', 'gender', 'reside']].values X[0:5] # + [markdown] id="pe8ZkP7KjOi3" # What are our labels? # + id="j3460ES-jOi4" outputId="a21484f4-08e1-4a2a-baae-8f462da69180" y = df['custcat'].values y[0:5] # + [markdown] id="9nzf2TdljOi4" # ### Normalize Data # Normalization in this case essentially means standardization. Standardization is the process of transforming data based on the mean and standard deviation for the whole set. Thus, transformed data refers to a standard distribution with a mean of 0 and a variance of 1.<br><br> # Data Standardization give data zero mean and unit variance, it is good practice, especially for algorithms such as KNN which is based on distance of cases: # # + id="EpOV4u8ZjOi5" outputId="1eb7dddc-f864-43a9-9fa3-dbaa99c6e6c0" X = preprocessing.StandardScaler().fit(X).transform(X.astype(float)) X[0:5] # + [markdown] id="Jns1y_vOjOi6" # ## 4. Train/Test Split # + id="h8kxRoQqjOi6" outputId="03d304d3-276c-4c39-87a5-75398ce61298" from sklearn.model_selection import train_test_split X_train , X_test , y_train , y_test = train_test_split(X , y , test_size= 0.2 , random_state = 4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape) # + [markdown] id="0fYWePt0jOi7" # ## 5. Classification(KNN) # + id="oalnJuwJjOi8" from sklearn.neighbors import KNeighborsClassifier # + [markdown] id="7BkmedOljOi8" # ### Training # Lets start the algorithm with k=4 for now: # + id="PGi0puICjOi9" all_acc = [] for i in range(1, 100): KNN = KNeighborsClassifier(n_neighbors=i).fit(X_train , y_train) all_acc.append(accuracy_score(y_test , KNN.predict(X_test))) best_acc = max(all_acc) best_k = all_acc.index(best_acc) + 1 KNN = KNeighborsClassifier(n_neighbors=best_k).fit(X_train , y_train) # + [markdown] id="oziM6qV2jOi-" # ### Prediction # + id="Sj1bSls-jOi-" outputId="37d9ce87-91c6-488e-c984-8ed987b02534" y_ = KNN.predict(X_test) y_[0:5] # + [markdown] id="lEnOuTfVjOi_" # ## 6. Accuracy Evaluation # In multilabel classification, **accuracy classification score** is a function that computes subset accuracy. This function is equal to the jaccard_score function. Essentially, it calculates how closely the actual labels and predicted labels are matched in the test set. # + id="_mkRPDgqjOjA" outputId="c717c7c4-c2cb-4150-ea6a-c71564fadcae" from sklearn.metrics import accuracy_score print('Train Set Accuracy: {}'.format(accuracy_score(y_train , KNN.predict(X_train)))) print('Ttest Set Accuracy: {}'.format(accuracy_score(y_test , KNN.predict(X_test)))) # + [markdown] id="cuDtIIKRjOjA" # #### What about other K? # # K in KNN, is the number of nearest neighbors to examine. It is supposed to be specified by the User. So, how can we choose right value for K? # The general solution is to reserve a part of your data for testing the accuracy of the model. Then chose k =1, use the training part for modeling, and calculate the accuracy of prediction using all samples in your test set. Repeat this process, increasing the k, and see which k is the best for your model. # # We can calculate the accuracy of KNN for different K. # # + id="8JDslpecjOjB" all_acc = [] for i in range(1, 100): KNN = KNeighborsClassifier(n_neighbors=i).fit(X_train , y_train) all_acc.append(accuracy_score(y_test , KNN.predict(X_test))) best_acc = max(all_acc) best_k = all_acc.index(best_acc) + 1
ML_Models/Classification/KNearestNeighbor/KNN_first_try.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="PZtRtMMUZHJS" colab_type="text" # ##### Copyright 2020 Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # + id="TouZL3JZZSQe" colab_type="code" cellView="both" colab={} #@title License header # Copyright 2020 Google LLC # # 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. # + [markdown] id="O6c3qfq5Zv57" colab_type="text" # # MNIST Model TensorFlow Training, IREE Execution # # ## Overview # # This notebook creates and trains a TensorFlow 2.0 model for recognizing handwritten digits using the [MNIST dataset](https://en.wikipedia.org/wiki/MNIST_database), then compiles and executes that trained model using IREE. # # ## Running Locally # # * Refer to [iree/docs/using_colab.md](https://github.com/google/iree/blob/main/docs/using_colab.md) for general information # * Ensure that you have a recent version of TensorFlow 2.0 [installed on your system](https://www.tensorflow.org/install) # * Enable IREE/TF integration by adding to your user.bazelrc: `build --define=iree_tensorflow=true` # * Start colab by running `python colab/start_colab_kernel.py` (see that file for additional instructions) # * Note: you may need to restart your runtime in order to re-run certain cells. Some of the APIs are not yet stable enough for repeated invocations # + [markdown] id="wBXlE69Ia2QU" colab_type="text" # # Setup Steps # + id="EPF7RGQDYK-M" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="fe0d703a-2ad7-4d14-9aef-c69b4c342a16" import os import numpy as np import tensorflow as tf from matplotlib import pyplot as plt from pyiree.tf import compiler as ireec from pyiree import rt as ireert tf.compat.v1.enable_eager_execution() SAVE_PATH = os.path.join(os.environ["HOME"], "saved_models") os.makedirs(SAVE_PATH, exist_ok=True) # Print version information for future notebook users to reference. print("TensorFlow version: ", tf.__version__) print("Numpy version: ", np.__version__) # + id="43BH_9YcsGs8" colab_type="code" cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="46a560cb-5947-4cfa-f71e-9065bf2c07ab" #@title Notebook settings { run: "auto" } #@markdown ----- #@markdown ### Configuration backend_choice = "GPU (vulkan-spirv)" #@param [ "GPU (vulkan-spirv)", "CPU (VMLA)" ] if backend_choice == "GPU (vulkan-spirv)": backend_name = "vulkan-spirv" driver_name = "vulkan" else: backend_name = "vmla" driver_name = "vmla" tf.print("Using IREE compiler backend '%s' and runtime driver '%s'" % (backend_name, driver_name)) #@markdown ----- #@markdown ### Training Parameters #@markdown <sup>Batch size used to subdivide the training and evaluation samples</sup> batch_size = 200 #@param { type: "slider", min: 10, max: 400 } #@markdown <sup>Epochs for training/eval. Higher values take longer to run but generally produce more accurate models</sup> num_epochs = 5 #@param { type: "slider", min: 1, max: 20 } #@markdown ----- # + [markdown] id="5vkQOMOMbXdy" colab_type="text" # # Create and Train MNIST Model in TensorFlow # # The specific details of the training process here aren't critical to the model compilation and execution through IREE. # + id="GXZIrReTbTHN" colab_type="code" cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 486} outputId="9c01fab1-f8cb-4a63-fff1-6b82a9b6b49d" #@title Load MNIST dataset, setup training and evaluation NUM_CLASSES = 10 # One per digit [0, 1, 2, ..., 9] IMG_ROWS, IMG_COLS = 28, 28 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() tf.print("Loaded MNIST dataset!") x_train = x_train.reshape(x_train.shape[0], IMG_ROWS, IMG_COLS, 1) x_test = x_test.reshape(x_test.shape[0], IMG_ROWS, IMG_COLS, 1) input_shape = (IMG_ROWS, IMG_COLS, 1) # Scale pixel values from [0, 255] integers to [0.0, 1.0] floats. x_train = x_train.astype("float32") / 255 x_test = x_test.astype("float32") / 255 steps_per_epoch = int(x_train.shape[0] / batch_size) steps_per_eval = int(x_test.shape[0] / batch_size) # Convert class vectors to binary class matrices. y_train = tf.keras.utils.to_categorical(y_train, NUM_CLASSES) y_test = tf.keras.utils.to_categorical(y_test, NUM_CLASSES) # Construct batched datasets for training/evaluation. train_dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train)) train_dataset = train_dataset.batch(batch_size, drop_remainder=True) test_dataset = tf.data.Dataset.from_tensor_slices((x_test, y_test)) test_dataset = test_dataset.batch(batch_size, drop_remainder=True) # Create a distribution strategy for the dataset (single machine). strategy = tf.distribute.experimental.CentralStorageStrategy() train_dist_ds = strategy.experimental_distribute_dataset(train_dataset) test_dist_ds = strategy.experimental_distribute_dataset(test_dataset) tf.print("Configured data for training and evaluation!") tf.print(" sample shape: %s" % str(x_train[0].shape)) tf.print(" training samples: %s" % x_train.shape[0]) tf.print(" test samples: %s" % x_test.shape[0]) tf.print(" epochs: %s" % num_epochs) tf.print(" steps/epoch: %s" % steps_per_epoch) tf.print(" steps/eval : %s" % steps_per_eval) tf.print("") tf.print("Sample image from the dataset:") SAMPLE_EXAMPLE_INDEX = 1 sample_image = x_test[SAMPLE_EXAMPLE_INDEX] sample_image_batch = np.expand_dims(sample_image, axis=0) sample_label = y_test[SAMPLE_EXAMPLE_INDEX] plt.imshow(sample_image.reshape(IMG_ROWS, IMG_COLS)) plt.show() tf.print("\nGround truth labels: %s" % str(sample_label)) # + id="tHq96SIJcNfx" colab_type="code" cellView="both" colab={} #@title Define MNIST model architecture using tf.keras API def simple_mnist_model(input_shape): """Creates a simple (multi-layer perceptron) MNIST model.""" model = tf.keras.models.Sequential() # Flatten to a 1d array (e.g. 28x28 -> 784) model.add(tf.keras.layers.Flatten(input_shape=input_shape)) # Fully-connected neural layer with 128 neurons, RELU activation model.add(tf.keras.layers.Dense(128, activation='relu')) # Fully-connected neural layer returning probability scores for each class model.add(tf.keras.layers.Dense(10, activation='softmax')) return model # + id="7Gdxh7qWcPSO" colab_type="code" cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 374} outputId="50b0aede-9a8f-4ce5-b340-783be5fbfc06" #@title Train the Keras model with strategy.scope(): model = simple_mnist_model(input_shape) tf.print("Constructed Keras MNIST model, training...") optimizer = tf.keras.optimizers.SGD(learning_rate=0.05) training_loss = tf.keras.metrics.Mean("training_loss", dtype=tf.float32) training_accuracy = tf.keras.metrics.CategoricalAccuracy( "training_accuracy", dtype=tf.float32) test_loss = tf.keras.metrics.Mean("test_loss", dtype=tf.float32) test_accuracy = tf.keras.metrics.CategoricalAccuracy( "test_accuracy", dtype=tf.float32) @tf.function def train_step(iterator): """Training StepFn.""" def step_fn(inputs): """Per-Replica StepFn.""" images, labels = inputs with tf.GradientTape() as tape: logits = model(images, training=True) loss = tf.keras.losses.categorical_crossentropy(labels, logits) loss = tf.reduce_mean(loss) / strategy.num_replicas_in_sync grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) training_loss.update_state(loss) training_accuracy.update_state(labels, logits) strategy.run(step_fn, args=(next(iterator),)) @tf.function def test_step(iterator): """Evaluation StepFn.""" def step_fn(inputs): images, labels = inputs logits = model(images, training=False) loss = tf.keras.losses.categorical_crossentropy(labels, logits) loss = tf.reduce_mean(loss) / strategy.num_replicas_in_sync test_loss.update_state(loss) test_accuracy.update_state(labels, logits) strategy.run(step_fn, args=(next(iterator),)) for epoch in range(0, num_epochs): tf.print("Running epoch #%s" % (epoch + 1)) train_iterator = iter(train_dist_ds) for step in range(steps_per_epoch): train_step(train_iterator) tf.print(" Training loss: %f, accuracy: %f" % (training_loss.result(), training_accuracy.result() * 100)) training_loss.reset_states() training_accuracy.reset_states() test_iterator = iter(test_dist_ds) for step in range(steps_per_eval): test_step(test_iterator) tf.print(" Test loss : %f, accuracy: %f" % (test_loss.result(), test_accuracy.result() * 100)) test_loss.reset_states() test_accuracy.reset_states() tf.print("Completed training!") tf.print("") # Run a single prediction on the trained model tf_prediction = model(sample_image_batch, training=False) tf.print("Sample prediction:") tf.print(tf_prediction[0] * 100.0, summarize=100) tf.print("") # + id="DmespEaFcSEL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 153} outputId="3c8579db-7b3c-4164-ff91-394346595107" #@title Export the trained model as a SavedModel, with IREE-compatible settings # Since the model was written in sequential style, explicitly wrap in a module. saved_model_dir = "/tmp/mnist.sm" inference_module = tf.Module() inference_module.model = model # Hack: Convert to static shape. Won't be necessary once dynamic shapes are in. dynamic_input_shape = list(model.inputs[0].shape) dynamic_input_shape[0] = 1 # Make fixed (batch=1) # Produce a concrete function. inference_module.predict = tf.function( input_signature=[ tf.TensorSpec(dynamic_input_shape, model.inputs[0].dtype)])( lambda x: model.call(x, training=False)) save_options = tf.saved_model.SaveOptions(save_debug_info=True) tf.print("Exporting SavedModel to %s" % saved_model_dir) tf.saved_model.save(inference_module, saved_model_dir, options=save_options) # + [markdown] id="nZdVUd_dgTtc" colab_type="text" # # Compile and Execute MNIST Model using IREE # + id="rqwIx4j4gS1a" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 836} outputId="24cded90-c436-47ce-b4f4-7a5da46ea38a" #@title Load the SavedModel into IREE's compiler as MLIR mhlo compiler_module = ireec.tf_load_saved_model( saved_model_dir, exported_names=["predict"]) tf.print("Imported MLIR:\n", compiler_module.to_asm(large_element_limit=100)) # Write to a file for use outside of this notebook. mnist_mlir_path = os.path.join(SAVE_PATH, "mnist.mlir") with open(mnist_mlir_path, "wt") as output_file: output_file.write(compiler_module.to_asm()) print("Wrote MLIR to path '%s'" % mnist_mlir_path) # + id="IDHI7h3khJr9" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 51} outputId="b8958b7f-c7bb-4fbd-b800-e58c46134086" #@title Compile the mhlo MLIR and prepare a context to execute it # Compile the MLIR module into a VM module for execution flatbuffer_blob = compiler_module.compile(target_backends=[backend_name]) vm_module = ireert.VmModule.from_flatbuffer(flatbuffer_blob) # Register the module with a runtime context config = ireert.Config(driver_name) ctx = ireert.SystemContext(config=config) ctx.add_module(vm_module) # + id="SKflpnLtkLYE" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 102} outputId="337ddf79-6746-4685-89f5-65787280c0af" #@title Execute the compiled module and compare the results with TensorFlow # Invoke the 'predict' function with a single image as an argument iree_prediction = ctx.modules.module.predict(sample_image_batch) tf.print("IREE prediction ('%s' backend, '%s' driver):" % (backend_name, driver_name)) tf.print(tf.convert_to_tensor(iree_prediction[0]) * 100.0, summarize=100) tf.print("") tf.print("TensorFlow prediction:") tf.print(tf_prediction[0] * 100.0, summarize=100)
colab/mnist_tensorflow.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + colab={} colab_type="code" id="5_wAO3emXGhe" def show_images(imgs, num_rows, num_cols, scale=2): figsize = (num_cols * scale, num_rows * scale) _, axes = plt.subplots(num_rows, num_cols, figsize=figsize) for i in range(num_rows): for j in range(num_cols): axes[i][j].imshow(imgs[i * num_cols + j]) axes[i][j].axes.get_xaxis().set_visible(False) axes[i][j].axes.get_yaxis().set_visible(False) return axes # + colab={} colab_type="code" id="VR8lr9WHEQWo" # Install TensorFlow try: # # %tensorflow_version only exists in Colab. # %tensorflow_version 2.x except Exception: pass import tensorflow as tf from tensorflow import keras import numpy as np import matplotlib.pyplot as plt import math # %matplotlib inline # + [markdown] colab_type="text" id="RXOQ6qzaXKD_" # # 9.9 语义分割和数据集 # + [markdown] colab_type="text" id="gPGR1YRsEjbL" # 在前几节讨论的目标检测问题中,我们一直使用方形边界框来标注和预测图像中的目标。本节将探讨语义分割(semantic segmentation)问题,它关注如何将图像分割成属于不同语义类别的区域。值得一提的是,这些语义区域的标注和预测都是像素级的。图9.10展示了语义分割中图像有关狗、猫和背景的标签。可以看到,与目标检测相比,语义分割标注的像素级的边框显然更加精细。 # + [markdown] colab_type="text" id="8Gyt1z6DF5Q4" # ![alt text](http://tangshusen.me/Dive-into-DL-PyTorch/img/chapter09/9.9_segmentation.svg) # # 图9.10 语义分割中图像有关狗、猫和背景的标签 # + [markdown] colab_type="text" id="aoXfJZwIF9zp" # ## 9.9.1 图像分割和实例分割 # + [markdown] colab_type="text" id="SVcaWb19GMSl" # 计算机视觉领域还有2个与语义分割相似的重要问题,即图像分割(image segmentation)和实例分割(instance segmentation)。我们在这里将它们与语义分割简单区分一下。 # + [markdown] colab_type="text" id="3nxQiHLSGbls" # * 图像分割将图像分割成若干组成区域。这类问题的方法通常利用图像中像素之间的相关性。它在训练时不需要有关图像像素的标签信息,在预测时也无法保证分割出的区域具有我们希望得到的语义。以图9.10的图像为输入,图像分割可能将狗分割成两个区域:一个覆盖以黑色为主的嘴巴和眼睛,而另一个覆盖以黄色为主的其余部分身体。 # * 实例分割又叫同时检测并分割(simultaneous detection and segmentation)。它研究如何识别图像中各个目标实例的像素级区域。与语义分割有所不同,实例分割不仅需要区分语义,还要区分不同的目标实例。如果图像中有两只狗,实例分割需要区分像素属于这两只狗中的哪一只。 # + [markdown] colab_type="text" id="mTwNjUjgG7LG" # ## 9.9.2 Pascal VOC2012语义分割数据集 # + [markdown] colab_type="text" id="CapnjjmNG8OA" # 语义分割的一个重要数据集叫作Pascal VOC2012 [1]。为了更好地了解这个数据集,我们先导入实验所需的包或模块。 # + colab={} colab_type="code" id="OJh8F9fcEZDN" import time from tqdm import tqdm import sys sys.path.append("..") # + [markdown] colab_type="text" id="0-hyqASnHYk-" # 我们先下载这个数据集的压缩包([下载地址](http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar))。压缩包大小是2 GB左右,下载需要一定时间。下载后解压得到VOCdevkit/VOC2012文件夹,然后将其放置在data文件夹下。 # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="ICIzu0JpHW67" outputId="1bd21164-eef1-4d9a-c48c-5a09818f492a" # 下载并解压文件到data目录 import requests import tarfile r = requests.get("http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar") with open("data/VOCtrainval_11-May-2012.tar", 'wb') as f: f.write(r.content) def extract(tar_path, target_path): try: t = tarfile.open(tar_path) t.extractall(path = target_path) return True except: return False extract("data/VOCtrainval_11-May-2012.tar", "data/") # + [markdown] colab_type="text" id="wWjTFETRMtoi" # 解压后包含: # # ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAARwAAAC6CAYAAAB8xvKnAAAgAElEQVR4Ae2d6a8URRfG/Vf8YMInQ2KCRo0Y931FxX2NgAbFBVTQgOCCihtxifuCghtGBRciggQ3cAFcEJVNMeBuUFQ0aL35lZ556/at7p65Pd1MzzyVzO2e7urq0091PffU6Z7n7OC6vLzzzjvuwgsvdL///nuXX6kuTwh0PgI7VG3iG2+84W644YZ+n5kzZ5ZiSiuE88UXX7ijjjrKsVQRAkKg/QhUSjhffvmlO/PMM1M/999/f9uvUITTdkjVoBAYMAKVEs6nn36aSjZZRGT78Izyyg8//OAuuOACt9NOO7mTTjrJ3XnnnX2mVF9//bXfP2jQIDdkyBD34IMPum3btrmnnnrK7bjjjo0P3ylp9fPs0H4hIAT6I1ArwoF4IK208ueff7oJEya46667zm3evNlt3LjRk4vFcH755Rd31llnuVmzZnmSYT+k9Prrr/smk1OqvPppdmi7EBACcQS6inAgjGHDhjmmblbefPPNhoeDJ/Pzzz97srH9eE0333yz/5oknLz61oaWQkAINIdAKuF8++23fjrClCTtQ51WStEpVZ6HQ7zm1FNP9d6N2ZWM4UBGTLmYUtkUyqZqScKhjaz6dg4thYAQaA6BVMLh8G+++cZdfvnl/<KEY>) # # ``` # Annotations JPEGImages SegmentationObject # ImageSets SegmentationClass # ``` # # # + [markdown] colab_type="text" id="5x8shqXUNB8P" # 进入data/VOCdevkit/VOC2012路径后,我们可以获取数据集的不同组成部分。其中ImageSets/Segmentation路径包含了指定训练和测试样本的文本文件,而JPEGImages和SegmentationClass路径下分别包含了样本的输入图像和标签。这里的标签也是图像格式,其尺寸和它所标注的输入图像的尺寸相同。标签中颜色相同的像素属于同一个语义类别。下面定义read_voc_images函数将输入图像和标签读进内存。 # + [markdown] colab_type="text" id="VenXeQKQP9R9" # train.txt文件内容如下: # # # # ``` # 2007_000032 # 2007_000039 # 2007_000063 # 2007_000068 # 2007_000121 # 2007_000170 # ... # ``` # # # + colab={} colab_type="code" id="JeU-vU0uMmBA" def read_voc_images(root="data/VOCdevkit/VOC2012", is_train=True, max_num=None): txt_fname = '%s/ImageSets/Segmentation/%s' % ( root, 'train.txt' if is_train else 'val.txt') with open(txt_fname, 'r') as f: images = f.read().split() if max_num is not None: images = images[:min(max_num, len(images))] features, labels = [None] * len(images), [None] * len(images) for i, fname in tqdm(enumerate(images)): feature_tmp = tf.io.read_file('%s/JPEGImages/%s.jpg' % (root, fname)) features[i] = tf.image.decode_jpeg(feature_tmp) label_tmp = tf.io.read_file('%s/SegmentationClass/%s.png' % (root, fname)) labels[i] = tf.image.decode_png(label_tmp) return features, labels #shape=(h, w, c) # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="C98kOwFzSLFW" outputId="62cfe181-a955-4a72-f856-0a4723d926ac" from PIL import Image root="data/VOCdevkit/VOC2012" fname="2007_000032" feature = Image.open('%s/JPEGImages/%s.jpg' % (root, fname)).convert("RGB") label = Image.open('%s/SegmentationClass/%s.png' % (root, fname)).convert("RGB") feature.size #(w, h) # + colab={"base_uri": "https://localhost:8080/", "height": 294} colab_type="code" id="HxLyodOoS_Qu" outputId="3aae6365-d401-4a33-ca01-7b863a44da25" feature = tf.io.read_file('%s/JPEGImages/%s.jpg' % (root, fname)) feature = tf.image.decode_jpeg(feature) print(feature.shape) #(h, w, c) label = tf.io.read_file('%s/SegmentationClass/%s.png' % (root, fname)) label = tf.image.decode_png(label) print(label.shape) plt.imshow(label) #(h, w, c) # + colab={"base_uri": "https://localhost:8080/", "height": 35} colab_type="code" id="jDUZpTezTiJM" outputId="5b0f84c7-f32d-4ef9-b7e0-c56eb51a857b" voc_dir = "data/VOCdevkit/VOC2012" train_features, train_labels = read_voc_images(voc_dir, max_num=100) # + [markdown] colab_type="text" id="il65YbCQWO7B" # 我们画出前5张输入图像和它们的标签。在标签图像中,白色和黑色分别代表边框和背景,而其他不同的颜色则对应不同的类别。 # + colab={"base_uri": "https://localhost:8080/", "height": 423} colab_type="code" id="h_1KTxmyWBkl" outputId="ac37cc56-abf5-47e4-9dc5-dc0f714a3a8c" n = 5 imgs = train_features[0:n] + train_labels[0:n] show_images(imgs, 2, n) # + [markdown] colab_type="text" id="lSMlL3PtXoR9" # 接下来,我们列出标签中每个RGB颜色的值及其标注的类别。 # + colab={} colab_type="code" id="dEJxCT6oXcQ3" VOC_COLORMAP = [[0, 0, 0], [128, 0, 0], [0, 128, 0], [128, 128, 0], [0, 0, 128], [128, 0, 128], [0, 128, 128], [128, 128, 128], [64, 0, 0], [192, 0, 0], [64, 128, 0], [192, 128, 0], [64, 0, 128], [192, 0, 128], [64, 128, 128], [192, 128, 128], [0, 64, 0], [128, 64, 0], [0, 192, 0], [128, 192, 0], [0, 64, 128]] VOC_CLASSES = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa', 'train', 'tv/monitor'] # + [markdown] colab_type="text" id="bs--H_hUa3VE" # 有了上面定义的两个常量以后,我们可以很容易地查找标签中每个像素的类别索引。 # + colab={} colab_type="code" id="PKzTVCGVYBUm" colormap2label = np.zeros(256 ** 3, dtype=np.uint8) for i, colormap in enumerate(VOC_COLORMAP): colormap2label[(colormap[0] * 256 + colormap[1]) * 256 + colormap[2]] = i colormap2label = tf.convert_to_tensor(colormap2label) # 本函数已保存在d2lzh_pytorch中方便以后使用(没) def voc_label_indices(colormap, colormap2label): """ convert colormap (tf image) to colormap2label (uint8 tensor). """ colormap = tf.cast(colormap, dtype=tf.int32) idx = tf.add(tf.multiply(colormap[:, :, 0], 256), colormap[:, :, 1]) idx = tf.add(tf.multiply(idx, 256), colormap[:, :, 2]) idx = tf.add(idx, colormap[:, :, 2]) # print(tf.gather_nd(colormap2label, tf.expand_dims(idx, -1))) return tf.gather_nd(colormap2label, tf.expand_dims(idx, -1)) # + [markdown] colab_type="text" id="TRDG7CjCd0M9" # 例如,第一张样本图像中飞机头部区域的类别索引为1,而背景全是0。 # + colab={"base_uri": "https://localhost:8080/", "height": 215} colab_type="code" id="tNW8GAETcPz7" outputId="07d6ede1-58ea-4725-87c9-1f317fcfbeb7" y = voc_label_indices(train_labels[0], colormap2label) y[105:115, 130:140], VOC_CLASSES[1] # + [markdown] colab_type="text" id="TJvxftWWe_fZ" # ## 9.9.2.1 预处理数据 # + [markdown] colab_type="text" id="5YIN2n6TfArl" # 在之前的章节中,我们通过缩放图像使其符合模型的输入形状。然而在语义分割里,这样做需要将预测的像素类别重新映射回原始尺寸的输入图像。这样的映射难以做到精确,尤其在不同语义的分割区域。为了避免这个问题,我们将图像裁剪成固定尺寸而不是缩放。具体来说,我们使用图像增广里的随机裁剪,并对输入图像和标签裁剪相同区域。 # + colab={} colab_type="code" id="23XIfJ7Se364" def voc_rand_crop(feature, label, height, width): """ Random crop feature (tf image) and label (tf image). 先将channel合并,剪裁之后再分开 """ combined = tf.concat([feature, label], axis=2) last_label_dim = tf.shape(label)[-1] last_feature_dim = tf.shape(feature)[-1] combined_crop = tf.image.random_crop(combined, size=tf.concat([(height, width), [last_label_dim + last_feature_dim]],axis=0)) return combined_crop[:, :, :last_feature_dim], combined_crop[:, :, last_feature_dim:] # + colab={"base_uri": "https://localhost:8080/", "height": 415} colab_type="code" id="D8yyAfLQmqaa" outputId="20fd00f9-e900-4819-cb8e-581c99e8887f" imgs = [] for _ in range(n): imgs += voc_rand_crop(train_features[0], train_labels[0], 200, 300) show_images(imgs[::2] + imgs[1::2], 2, n) # + [markdown] colab_type="text" id="wrDcMtoAqjjv" # ## 9.9.2.2 自定义语义分割数据集类 # + [markdown] colab_type="text" id="QiNoccxhq1eN" # 我们通过自定义了一个获取语义分割数据集函数getVOCSegDataset。由于数据集中有些图像的尺寸可能小于随机裁剪所指定的输出尺寸,这些样本需要通过自定义的filter函数所移除。此外,我们还对输入图像的RGB三个通道的值分别做标准化。 # + colab={} colab_type="code" id="TGzlMKhXqwFg" def getVOCSegDataset(is_train, crop_size, voc_dir, colormap2label, max_num=None): """ crop_size: (h, w) """ features, labels = read_voc_images(root=voc_dir, is_train=is_train, max_num=max_num) def _filter(imgs, crop_size): return [img for img in imgs if ( img.shape[0] >= crop_size[0] and img.shape[1] >= crop_size[1])] def _crop(features, labels): features_crop = [] labels_crop = [] for feature, label in zip(features, labels): feature, label = voc_rand_crop(feature, label, height=crop_size[0], width=crop_size[1]) features_crop.append(feature) labels_crop.append(label) return features_crop, labels_crop def _normalize(feature, label): rgb_mean = np.array([0.485, 0.456, 0.406]) rgb_std = np.array([0.229, 0.224, 0.225]) label = voc_label_indices(label, colormap2label) feature = tf.cast(feature, tf.float32) feature = tf.divide(feature, 255.) # feature = tf.divide(tf.subtract(feature, rgb_mean), rgb_std) return feature, label features = _filter(features, crop_size) labels = _filter(labels, crop_size) features, labels = _crop(features, labels) print('read ' + str(len(features)) + ' valid examples') dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.map(_normalize) return dataset # + [markdown] colab_type="text" id="FSgNBbw-VTHI" # ## 9.9.2.3 读取数据集 # + [markdown] colab_type="text" id="pilZQWe2VVD9" # 我们通过自定义的getVOCSegDataset来分别创建训练集和测试集的实例。假设我们指定随机裁剪的输出图像的形状为320×400。下面我们可以查看训练集和测试集所保留的样本个数。 # + colab={"base_uri": "https://localhost:8080/", "height": 89} colab_type="code" id="0Ty3SZgdUcwi" outputId="e220808c-c887-4aed-b378-87b1a1d851e1" crop_size = (320, 400) max_num = 100 voc_train = getVOCSegDataset(True, crop_size, voc_dir, colormap2label, max_num) voc_test = getVOCSegDataset(False, crop_size, voc_dir, colormap2label, max_num) # + [markdown] colab_type="text" id="hMltkHEBok7N" # 设批量大小为64,分别定义训练集和测试集的迭代器。 # + colab={} colab_type="code" id="IzKtBar4V4Ny" batch_size = 64 voc_train = voc_train.batch(batch_size) voc_test = voc_test.batch(batch_size) # + colab={"base_uri": "https://localhost:8080/", "height": 53} colab_type="code" id="r45P8h9boyEL" outputId="0b379766-29fe-4931-d845-24402a7495d0" for x, y in iter(voc_train): print(x.dtype, x.shape) print(y.dtype, y.shape) break # + [markdown] colab_type="text" id="AyTzRE0lpKUB" # ## 小结 # + [markdown] colab_type="text" id="0OrmGTjCpLna" # * 语义分割关注如何将图像分割成属于不同语义类别的区域。 # * 语义分割的一个重要数据集叫作Pascal VOC2012。 # * 由于语义分割的输入图像和标签在像素上一一对应,所以将图像随机裁剪成固定尺寸而不是缩放。
code/chapter09_computer-vision/9.9_semantic-segmentation-and-dataset.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # Include this line to make plots interactive # %matplotlib notebook # Dependencies import matplotlib.pyplot as plt import numpy as np # Set x axis to numerical value for month x_axis = np.arange(1,13,1) x_axis # Avearge weather temp points_F = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44] # Convert to Celsius C = (F-32) * 0.56 points_C = [(x-32) * 0.56 for x in points_F] points_C # Create a handle for each plot fahrenheit, = plt.plot(x_axis, points_F, marker="+",color="blue", linewidth=1, label="Fahreneit") celcius, = plt.plot(x_axis, points_C, marker="s", color="Red", linewidth=1, label="Celcius") # Set our legend to where the chart thinks is best plt.legend(handles=[fahrenheit, celcius], loc="best") # Create labels for the X and Y axis plt.xlabel("Months") plt.ylabel("Degrees") # Save and display the chart plt.savefig("../Images/avg_temp.png") plt.show()
05-Matplotlib/1/Activities/04-Stu_LegendaryTemperature/Solved/legendary_temp.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:571] # language: python # name: conda-env-571-py # --- # # Decision trees and machine learning fundamentals # ## Imports # + import re import sys import altair as alt import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.dummy import DummyClassifier from sklearn.model_selection import cross_val_score, cross_validate, train_test_split from sklearn.tree import DecisionTreeClassifier, export_graphviz # - # <br><br> # ## 1. Decision trees on Spotify Song Attributes dataset <a name="2"></a> # <hr> # + [markdown] slideshow={"slide_type": "slide"} # ### Introducing the dataset # # We will be using Kaggle's [Spotify Song Attributes](https://www.kaggle.com/geomack/spotifyclassification/home) dataset. The dataset contains a number of features of songs from 2017 and a binary variable `target` that represents whether the user liked the song (encoded as 1) or not (encoded as 0). See the documentation of all the features [here](https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-features/). # # + [markdown] nbgrader={"grade": false, "grade_id": "cell-d4d478b6cdc9bf88", "locked": true, "schema_version": 3, "solution": false} # ### 1.1 Reading the data CSV # # The first column of the .csv file is set as the index. # + nbgrader={"grade": true, "grade_id": "cell-4f3f14b59fd7e6b8", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false} spotify_df = pd.read_csv("../downloads/data.csv", index_col=0) spotify_df.head() # - # <br><br> # ### 1.2 Data splitting # train_df, test_df = train_test_split(spotify_df, test_size=0.2, random_state=123) test_df.shape # 1613 train examples and 404 test examples. # <br><br> # ### 1.3 `describe` and `info` # train_df.info() train_df.describe() train_df.head() train_df.tail() train_df.describe().loc["max"] - train_df.describe().loc["min"] # **speechiness is the feature with the smallest range with value of 0.79.** # <br><br> # + [markdown] nbgrader={"grade": false, "grade_id": "cell-b33320bcf667584a", "locked": true, "schema_version": 3, "solution": false} # ### 1.4 Plotting histograms # # The code below produces histograms for the `loudness` feature which shows the distribution of the feature values in the training set, separated for positive (target=1, i.e., user liked the song) and negative (target=0, i.e., user disliked the song) examples. There are two different histograms, one for target = 0 and one for target = 1, and they are overlaid on top of each other. The histogram shows that extremely quiet songs tend to be disliked (more blue bars than orange on the left) and very loud songs also tend to be disliked (more blue than orange on the far right). # # > Note: I am using pandas plotting here. # - feat = "loudness" ax = train_df.groupby("target")[feat].plot.hist(bins=50, alpha=0.5, legend=True) plt.xlabel(feat) plt.title("Histogram of " + feat) plt.show() # # I will create histograms for the following features in the order below. # - acousticness # - danceability # - tempo # - energy # - valence feat_list = ["acousticness", "danceability", "tempo", "energy", "valence"] for feat in feat_list: ax = train_df.groupby("target")[feat].plot.hist(bins=50, alpha=0.5, legend=True) plt.xlabel(feat) plt.title("Histogram of " + feat) plt.show() # <br><br> # ### 1.5 Decision stump by hand # # # Let's say we had to make a decision stump (decision tree with depth 1), _by hand_, to predict the target class. Just from looking at the plots above, a reasonable split would be to predict 0 if danceability is < 0.6 and predict 1 otherwise. For another example, in the loudness histogram provided earlier on, it seems that very large values of loudness are generally disliked (more blue on the right side of the histogram), so we could say reasonable split would be to predict 0 if loudness > -5 (and predict 1 otherwise). # # If for a particular feature, the histogram of the feature are identical for the two target classes it does not mean that the feature is not useful for predicting the target class. # <br><br> # + [markdown] nbgrader={"grade": false, "grade_id": "cell-86f9e0c649669daf", "locked": true, "schema_version": 3, "solution": false, "task": false} # ### 1.6 Which columns to include? # # # Note that the dataset includes two free text features labeled `song_title` and `artist`. These features will not be useful by themselves. There would be some difficulty using these two features in our model as they are neither categories nor numbers. It might be useful to do some transformation on these like counting the number of letters or words in each and see if that would cause any specific pattern to show up (e.g. people liking one-word-title songs better than longer ones.) # - # <br><br><br><br> # ## 2: Data splitting and model building <a name="3"></a> # <hr> # In machine learning we want to build models that generalize well on unseen examples. One way to approximate generalization error is by splitting the data into train and test splits, building and tuning the model only using the train split, and carrying out the final assessment on the test split. # # ### 2.1 Splitting with `train_test_split` # # # 1. We split the Spotify dataset into a 80% train and 20% test using [`train_test_split`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) with `random_state=123`. # 2. We then train `DummyClassifier` on the train set and score it on the train and test sets to get a baseline. # 3. Then we train the `DecisionTreeClassifier` with `random_state=123` on the train set and score it on the train and test sets. X_train, X_test, y_train, y_test = train_test_split(spotify_df.drop(['target', 'song_title', 'artist'], axis=1), spotify_df['target'], test_size=0.2, random_state=123) # Dummy Classifier dc = DummyClassifier() dc.fit(X_train, y_train) print("Training score: %0.3f" % (dc.score(X_train, y_train))) print("Test score: %0.3f" % (dc.score(X_test, y_test))) # Decision Tree Classifier dtc = DecisionTreeClassifier(random_state=123) dtc.fit(X_train, y_train) print("Training score: %0.3f" % (dtc.score(X_train, y_train))) print("Test score: %0.3f" % (dtc.score(X_test, y_test))) # <br><br> # ### 2.2 Cross-validation # # We carry out 10-fold cross validation using `cross_validate` by passing `return_train_score=True`. cv_results = pd.DataFrame(cross_validate(DecisionTreeClassifier(random_state=123), X_train, y_train, cv=10, return_train_score=True)) cv_results cv_results.mean() # <br><br> # # ### 2.3 Examining cross-validation scores # 1. Except for one outlier, the remaining cross validation sub-scores are close to 0.70 which is similar to the mean of cross validation sub-scores. This shows that this value (mean) could be a trustworthy representation of the score. # 2. Yes. The significant difference between training and CV sub-scores are mainly due to the fact that our models are overfitting in each iteration which causes them not being able to generalize well, and therefore, giving lower CV sub-scores. # <br><br><br><br> # ## Exercise 3: Hyperparameters # <hr> # + [markdown] nbgrader={"grade": false, "grade_id": "cell-4150979c1845a18c", "locked": true, "schema_version": 3, "solution": false, "task": false} # ### 3.1 Train and cross-validation plots # # We will experiment with the `max_depth` hyperparameter of the decision tree classifier. # # # 1. Just to start fresh, we split the Spotify dataset into a 80% train and 20% test subset using `sklearn.model_selection.train_test_split` and `random_state=123`. # 2. Run 10-fold cross-validation for trees with different values of `max_depth`. # 3. For each `max_depth`, get both the train accuracy and the cross-validation accuracy. # 4. Make a plot with `max_depth` on the *x*-axis and the train and cross-validation scores on the *y*-axis. # # - X = spotify_df.drop(["target", "song_title", "artist"], axis=1) y = spotify_df["target"] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123) # + results_tbl = pd.DataFrame() for i in range(1,26): results = cross_validate(DecisionTreeClassifier(random_state=123, max_depth=i), X_train, y_train, cv=10, return_train_score=True) results_tbl = pd.concat([results_tbl, pd.DataFrame(results).mean()], axis=1) results_tbl = results_tbl.T results_tbl["max_depth"] = range(1,26) results_tbl.rename(columns={"test_score" : "CV Score", "train_score" : "Train Score"}, inplace=True) results_tbl.head() # + reshaped_results = results_tbl.drop(["fit_time", "score_time"], axis=1).melt("max_depth") alt.Chart(reshaped_results).mark_line().encode( x = "max_depth", y = "value", color = "variable" ) # - # <br><br> # ### 3.2 `max_depth` and the fundamental tradeoff # # With increasing the max_depth from 1 we see an initial improvement in cross-validation accuracy, but this accuracy drops after max_depth=4 showing traits of overfitting. # <br><br> # ### 3.3 Picking the best value for `max_depth` # # # max_depth of 4 would be the optimal value according to the plot above. # <br><br> # ### 3.4 Final assessment on the test split # # We train a decision tree classifier using the optimal `max_depth` from above on the _entire training set_ and then compute the test score on the _test data set_. dt_model = DecisionTreeClassifier(max_depth=4, random_state=123) dt_model.fit(X_train, y_train) dt_model.score(X_test, y_test) # <br><br> # ### 3.5 Analysis # # - The test score (0.68) is very close to the mean cross validation score (0.70) but smaller which shows that our model has been able to generalize well give the max_depth we used for the model. # - As the complexity of our model grows in order to predict our train target perfectly, that model will only be trained to recognize the specific patterns within the train data it is given. This model will then not be able to generalize well and deal with the test data (and after that deployment data). # - This model will likely generalize well on the population that this sample was pulled from. However, an accuracy of 0.70 is not a high score and we could use other classification models to get better predictions with higher scores.
1.Spotify_ML_fundamentals_decision_tree/ML_fundamentals_decision_tree.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/williamlidberg/RIP-Nature/blob/main/RIP_Nature_Results.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="Dm-BSAc8O8eH" # ## Clone repository # + colab={"base_uri": "https://localhost:8080/"} id="F5tkQ0o6ElIo" outputId="582c2ff7-cce6-4c6b-8830-2b97871625f3" # !git clone https://github.com/williamlidberg/RIP-Nature # %cd /content/RIP-Nature/Results/ # !ls # + colab={"base_uri": "https://localhost:8080/"} id="eQwdR0DyE-5x" outputId="8c2a04e3-9d66-40fc-cb87-572d9a0cf780" # !pip install simpledbf # + id="4_9kXCZxMOCU" colab={"base_uri": "https://localhost:8080/", "height": 393} outputId="bcfe1641-5f7c-416d-bda8-44a769b861d1" from simpledbf import Dbf5 import pandas as pd # Sweden sweden_post_harvest = Dbf5('/content/RIP-Nature/Results/sweden_post_harvest_buffers_william.dbf') sweden_post_harvest = sweden_post_harvest.to_dataframe() sweden_pre_harvest = Dbf5('/content/RIP-Nature/Results/sweden_pre_harvest_buffers_william.dbf') sweden_pre_harvest = sweden_pre_harvest.to_dataframe() # NB nb_post_harvest = Dbf5('/content/RIP-Nature/Results/canada_post_harvest_buffers_william.dbf') nb_post_harvest = nb_post_harvest.to_dataframe() nb_pre_harvest = Dbf5('/content/RIP-Nature/Results/canada_pre_harvest_buffers_william.dbf') nb_pre_harvest = nb_pre_harvest.to_dataframe() # Finland finland_post_harvest = pd.read_csv('/content/RIP-Nature/Results/Finland_post_harvest_joined.dbf', sep = ';') finland_post_harvest = finland_post_harvest.to_dataframe() finland_pre_harvest = pd.read_csv('/content/RIP-Nature/Results/Finland_pre_harvest_joined.dbf', sep = ';') finland_pre_harvest = finland_pre_harvest.to_dataframe() # + colab={"base_uri": "https://localhost:8080/", "height": 206} id="6u1Ir4WcMUbS" outputId="43cccf9b-4c4d-48a3-b213-acc011f4265f" sweden_post_harvest.head() # + [markdown] id="92veX86ISE9i" # # # * COUNT is the number of 2 m x 2 m cells within the buffer polygon # * Area in square meters of the buffer polygon # * SUM is the number of canopy cells above 5 m. multiply it by to get area in square meters # # # # # # + colab={"base_uri": "https://localhost:8080/"} id="s2kd1C4GHwhD" outputId="2c304eb1-78a5-4016-ac7e-e6e75823a0ac" len(finland_post_harvest) # + colab={"base_uri": "https://localhost:8080/", "height": 456} id="IDMY_fc1s-Ff" outputId="377cf105-d03b-45d1-edb5-5559c2edb1f7" finland_post_harvest.head(10) # + [markdown] id="NX3Jz3GqtCXI" # The post harvest data needs to be selected based on scanning year and cutting year. # # * ASTA_ID is the Id of the buffer polygon # * vuosi = lidar scan year # * Cutting_ye = year of harvest # * 5m_sum = number of pixels over 5 m within the polygon # * sum_total = number of pixels within the polygon in total # * canopy cover in the polygon # # # For example ASTA_ID 0 were scanned 2009, 2015, 2017 and 2020 but were harvested 2017. # # # # + colab={"base_uri": "https://localhost:8080/"} id="2SiEVqUhVRkh" outputId="80b7d4d9-e682-4ac4-c94f-e8a8b54937a7" #finland_real_post_harvest = finland_post_harvest[finland_post_harvest.vuosi > finland_post_harvest.Cutting_ye] #finland_post_harvest_latest_scan = finland_post_harvest.groupby('ASTA_ID')['vuosi'].max() #finland_post_harvest_latest_scan = finland_real_post_harvest.loc[finland_real_post_harvest.groupby('ASTA_ID')['Cutting_ye'].idxmax()] #finland_post_harvest_latest_scan.head(10) test = finland_post_harvest.groupby('ASTA_ID') finland_post_harvest['ASTA_ID'].max() # + colab={"base_uri": "https://localhost:8080/"} id="IzfeBfICavM6" outputId="4b2edb9f-4542-469a-e149-b05a91472073" len(finland_post_harvest_latest_scan) # + id="Y2JGwXbASbD7" import numpy as np # Sweden sweden_post_harvest['canopy_coverage'] = ((sweden_post_harvest['SUM'] * 4) / sweden_post_harvest['AREA'])*100 sweden_pre_harvest['canopy_coverage'] = ((sweden_pre_harvest['SUM'] * 4) / sweden_pre_harvest['AREA'])*100 # New Brunswick nb_post_harvest['canopy_coverage'] = ((nb_post_harvest['SUM'] * 4) / nb_post_harvest['AREA'])*100 nb_pre_harvest['canopy_coverage'] = ((nb_pre_harvest['SUM'] * 4) / nb_pre_harvest['AREA'])*100 # + colab={"base_uri": "https://localhost:8080/", "height": 753} id="9QS_U2dCS_VB" outputId="8e4f12e1-3a06-4cfe-cbf8-9a8c447b6cad" import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter from matplotlib.pyplot import figure # post harvest nb_coverage = nb_post_harvest['canopy_coverage'] sweden_coverage = sweden_post_harvest['canopy_coverage'] finland_coverage = sweden_post_harvest['canopy_coverage'] # before harvest nb_before = nb_pre_harvest['canopy_coverage'] sweden_before = sweden_pre_harvest['canopy_coverage'] finland_before = sweden_pre_harvest['canopy_coverage'] nbins = 10 fig,ax = plt.subplots(1,3,figsize=(8,4),dpi=200,sharey=True) fig.text(0.5, 0.04, 'Distribution', ha='center') fig.text(0.04, 0.5, 'Canopy coverage', va='center', rotation='vertical') ax[0].hist(nb_coverage,density=False, weights=np.ones_like(nb_coverage)*100./ len(nb_coverage), color = 'red', edgecolor='black') ax[1].hist(sweden_coverage,density=False, weights=np.ones_like(sweden_coverage)*100./ len(sweden_coverage), color = 'yellow', edgecolor='black') #ax[2].hist(finland_coverage,density=False, weights=np.ones_like(finland_coverage)*100./ len(finland_coverage), color = 'blue', edgecolor='black') ax[1].set(yticklabels=[]) #ax[2].set(yticklabels=[]) ax[1].tick_params(left=False) #ax[2].tick_params(left=False) ax[0].yaxis.set_major_formatter(PercentFormatter(xmax=100)) #before lines # nb ax[0].axvline(nb_before.quantile(0.25),color='red',linestyle = 'dotted') ax[0].axvline(nb_before.mean(),color='black') ax[0].axvline(nb_before.quantile(0.75),color='red',linestyle = 'dotted') # sweden ax[1].axvline(sweden_before.quantile(0.25),color='red',linestyle = 'dotted') ax[1].axvline(sweden_before.mean(),color='black') ax[1].axvline(sweden_before.quantile(0.75),color='red',linestyle = 'dotted') # finland #ax[2].axvline(finland_before.quantile(0.25),color='red',linestyle = 'dotted') #ax[2].axvline(finland_before.mean(),color='black') #ax[2].axvline(finland_before.quantile(0.75),color='red',linestyle = 'dotted') # + id="JcEd27n2_NGu"
RIP_Nature_Results.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:root] * # language: python # name: conda-root-py # --- # # Solubility of common salts at ambient temperatures # # Solubility values are given in molality terms and temperature values in celsius. Reference: <NAME>. # _CRC Handbook of Chemistry and Physics_, 98th Edition, CRC Press LLC, 2017. # Please, run the following cell to import the python module written for this data set. # + import sys sys.path.insert(1, '../') from solutions import molality_salts # - # The module converts the data to a Pandas data frame that can be accessed: molality_salts.DF # One can use Pandas commands. E.g., let's see the data types: molality_salts.DF.dtypes # All chemical substances names can be seen: molality_salts.NAMES # As well as all the chemical formulas: molality_salts.FORMULAS # The available temperatures: molality_salts.TEMPERATURES # The module receives compounds names and/or formulas as a list of strings. # # So let's create a list of compounds: compounds = ['BaCl2', 'Sodium nitrate', 'KBr', 'NaBr', 'Zinc sulfate'] # As can be seen, there are formulas and names. If only one salt is wanted, pass it as a list with only one string. If no matches are found, an error will be raised. # Since the module wraps the data in a Pandas data frame, the data can be manipulated as the user's wish. The module has a function that returns the data frame indexes for each compound: molality_salts.salt_indexes(compounds) # With the indexes, the user can code its own plots and do all sorts of data manipulation. # # But some plot functionalities are available: molality_salts.plot(compounds) # As can be seen, if no data is available for some temperature it will be ignored. By default, the module does not plots an interpolation together with data points. It can be turned on, plotting a linear interpolation together with data points: molality_salts.plot(compounds, interpolation=True) # The colors are chosen based on [colormaps](https://matplotlib.org/3.1.1/gallery/color/colormap_reference.html). The default is the `Dark2` one but can be changed if the Matplotlib library [pyplot](https://matplotlib.org/tutorials/introductory/pyplot.html) is imported. Let's change it to `jet`: # + import matplotlib.pyplot as plt molality_salts.plot(compounds, colors=plt.cm.jet, interpolation=True) # - # The plot size can be adjusted. Let's plot only NaCl with a smaller figure: molality_salts.plot(['NaCl'], plot_size=(6,6)) # Just for reference, all the salts are plotted below: molality_salts.plot(molality_salts.FORMULAS.to_list(), interpolation=True) # Just for reference, all the salts are plotted below (except $NH_4NO_3$ and $LiCl$ due to their high solubility): # + all_salts_formulas = molality_salts.FORMULAS.to_list() salts_to_be_excluded = ['NH4NO3', 'LiCl'] salts_to_be_plotted = [salt for salt in all_salts_formulas if salt not in salts_to_be_excluded] molality_salts.plot(salts_to_be_plotted, interpolation=True) # -
tutorials/molality_salts_ambient_temperatures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Author(s): <NAME> (<EMAIL>) and <NAME> (<EMAIL>) # - # <a href="https://opensource.org/licenses/MIT" target="_parent"><img src="https://img.shields.io/github/license/probml/pyprobml"/></a> # <a href="https://colab.research.google.com/github/probml/pyprobml/blob/master/book1/figures/chapter19_figures.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ## Figure 19.1:<a name='19.1'></a> <a name='chollet-cat-crops'></a> # # Illustration of random crops, zooms and rotations of some cat images. From \cite kerasBook . Used with kind permission of Francois Chollet. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/chollet-cat-crops.png") # ## Figure 19.2:<a name='19.2'></a> <a name='transfer'></a> # # Illustration of transfer learning from dataset $ \mathcal D _p$ to $ \mathcal D _q$ using a neural network, in which the feature extractor is shared, but the final layer is domain specific. The parameters $\boldsymbol \theta _1$ are first trained on $ \mathcal D _p$, and then optionally fine-tuned on $ \mathcal D _q$. Thus the information in $ \mathcal D _p$ is used to help the model work well on $ \mathcal D _q$, but not vice versa. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/transfer.png") # ## Figure 19.3:<a name='19.3'></a> <a name='supervisedImputation'></a> # # (a) Context encoder for self-supervised learning. From <a href='#Pathak2016'>[Dee+16]</a> . Used with kind permission of Deepak Pathak. (b) Some other proxy tasks for self-supervised learning. From <a href='#LeCunSSL2018'>[LeC18]</a> . Used with kind permission of Yann LeCun. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/context-encoder.png") pmlt.show_image("/pyprobml/book1/figures/images/self-sup-lecun.png") # ## Figure 19.4:<a name='19.4'></a> <a name='simCLRcrop'></a> # # (a) Illustration of SimCLR training. $\mathcal T $ is a set of stochastic semantics-preserving transformations (data augmentations). (b-c) Illustration of the benefit of random crops. Solid rectangles represent the original image, dashed rectangles are random crops. On the left, the model is forced to predict the local view A from the global view B (and vice versa). On the right, the model is forced to predict the appearance of adjacent views (C,D). From Figures 2--3 of <a href='#chen2020simple'>[Tin+20]</a> . Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts # ## Figure 19.5:<a name='19.5'></a> <a name='simCLR'></a> # # Visualization of SimCLR training. Each input image in the minibatch is randomly modified in two different ways (using cropping (followed by resize), flipping, and color distortion), and then fed into a Siamese network. The embeddings (final layer) for each pair derived from the same image is forced to be close, whereas the embeddings for all other pairs are forced to be far. From https://ai.googleblog.com/2020/04/advancing-self-supervised-and-semi.html . Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/simCLRattract.png") pmlt.show_image("/pyprobml/book1/figures/images/simCLRrepel.png") # ## Figure 19.6:<a name='19.6'></a> <a name='MAML-PGM'></a> # # Graphical model corresponding to MAML. Left: generative model. Right: During meta-training, each of the task parameters $\boldsymbol \theta _j$'s are updated using their local datasets. The indices $j$ are over tasks (meta datasets), and $i$ are over instances within each task. Solid shaded nodes are always observed; semi-shaded (striped) nodes are only observed during meta training time (i.e., not at test time). From Figure 1 of <a href='#Finn2018'>[CKS18]</a> . Used with kind permission of Chelsea Finn. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/PMAML2.png") # ## Figure 19.7:<a name='19.7'></a> <a name='metaLearningFSL'></a> # # Illustration of meta-learning for few-shot learning. Here, each task is a 3-way-2-shot classification problem because each training task contains a support set with three classes, each with two examples. From https://www.borealisai.com/en/blog/tutorial-2-few-shot-learning-and-meta-learning-i . Copyright (2019) Borealis AI. Used with kind permission of <NAME> and <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/FSL-borealis-NC.png") # ## Figure 19.8:<a name='19.8'></a> <a name='matchingNetworks'></a> # # Illustration of a matching network for one-shot learning. From Figure 1 of <a href='#Vinyals2016'>[Ori+16]</a> . Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/matchingNetworks.png") # ## Figure 19.9:<a name='19.9'></a> <a name='cosineSim'></a> # # Illustration of the cosine similarity between a query vector $\mathbf q $ and two document vectors $\mathbf d _1$ and $\mathbf d _2$. Since angle $\alpha $ is less than angle $\theta $, we see that the query is more similar to document 1. From https://en.wikipedia.org/wiki/Vector_space_model . Used with kind permission of Wikipedia author Riclas. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/Vector_space_model.png") # ## Figure 19.10:<a name='19.10'></a> <a name='word2vec'></a> # # Illustration of word2vec model with window size $H=2$. (a) CBOW version. (b) Skip-gram version. . #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/cbow.png") pmlt.show_image("/pyprobml/book1/figures/images/skipgram.png") # ## Figure 19.11:<a name='19.11'></a> <a name='word2vecMath'></a> # # Visualization of arithmetic operations in word2vec embedding space. From https://www.tensorflow.org/tutorials/representation/word2vec . #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/word2vec-arithmetic.png.png") # ## Figure 19.12:<a name='19.12'></a> <a name='elmo'></a> # # Illustration of ELMo bidrectional language model. Here $y_t=x_ t+1 $ when acting as the target for the forwards LSTM, and $y_t = x_ t-1 $ for the backwards LSTM. (We add \text \em bos \xspace and \text \em eos \xspace sentinels to handle the edge cases.) From Weng2019LM. Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/ELMo-biLSTM.png") # ## Figure 19.13:<a name='19.13'></a> <a name='BERT'></a> # # Illustration of (a) GPT and (b) BERT. $E_t$ is the embedding vector for the input token at location $t$, and $T_t$ is the output target to be predicted. From Figure 3 of <a href='#bert'>[Jac+19]</a> . Used with kind permission of Ming-<NAME>ang. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/GPT-fig.png") pmlt.show_image("/pyprobml/book1/figures/images/BERT-fig.png") # ## Figure 19.14:<a name='19.14'></a> <a name='bert-tasks'></a> # # Illustration of how BERT can be used for different kinds of supervised NLP tasks. (a) Sentence-pair classification (e.g., entailment). (b) Single sentence classification (e.g., sentiment). (c) Sentence pair tagging (e.g., question answering). (d) Single sentence tagging (e.g., named entity recognition, where the tags are ``outside'', ``begin-person'', ``inside-person'', ``begin-place'', ``inside-place'', etc). From Figure 4 of <a href='#bert'>[Jac+19]</a> . Used with kind permission of Ming-Wei Chang. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/bert-tasks-A.png") pmlt.show_image("/pyprobml/book1/figures/images/bert-tasks-B.png") pmlt.show_image("/pyprobml/book1/figures/images/bert-tasks-C.png") pmlt.show_image("/pyprobml/book1/figures/images/bert-tasks-D.png") # ## Figure 19.15:<a name='19.15'></a> <a name='squad'></a> # # Question-answer pairs for a sample passage in the SQuAD dataset. Each of the answers is a segment of text from the passage. This can be solved using sentence pair tagging. The input is the paragraph text T and the question Q. The output is a tagging of the relevant words in T that answer the question in Q. From Figure 1 of <a href='#squad'>[Pra+16]</a> . Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts # ## Figure 19.16:<a name='19.16'></a> <a name='T5'></a> # # Illustration of how the T5 model (``Text-to-text Transfer Transformer'') can be used to perform multiple NLP tasks, such as translating English to German; determining if a sentence is linguistic valid or not ( \bf CoLA stands for ``Corpus of Linguistic Acceptability''); determining the degree of semantic similarity ( \bf STSB stands for ``Semantic Textual Similarity Benchmark''); and abstractive summarization. From Figure 1 of <a href='#T5'>[Col+19]</a> . Used with kind permission of <NAME>. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/T5.png") # ## Figure 19.17:<a name='19.17'></a> <a name='SSL'></a> # # Illustration of the benefits of semi-supervised learning for a binary classification problem. Labeled points from each class are shown as black and white circles respectively. (a) Decision boundary we might learn given only unlabeled data. (b) Decision boundary we might learn if we also had a lot of unlabeled data points, shown as smaller grey circles. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/SSL1.png") pmlt.show_image("/pyprobml/book1/figures/images/SSL2.png") # ## Figure 19.18:<a name='19.18'></a> <a name='emvsst'></a> # # Comparison of the entropy minimization, self-training, and ``sharpened'' entropy minimization loss functions for a binary classification problem. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/emvsst.png") # ## Figure 19.19:<a name='19.19'></a> <a name='emgoodbad'></a> # # Visualization demonstrating how entropy minimization enforces the cluster assumption. The classifier assigns a higher probability to class 1 (black dots) or 2 (white dots) in red or blue regions respectively. The predicted class probabilities for one particular unlabeled datapoint is shown in the bar plot. In (a), the decision boundary passes through high-density regions of data, so the classifier is forced to output high-entropy predictions. In (b), the classifier avoids high-density regions and is able to assign low-entropy predictions to most of the unlabeled data. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/embad.png") pmlt.show_image("/pyprobml/book1/figures/images/emgood.png") # ## Figure 19.20:<a name='19.20'></a> <a name='sevskl'></a> # # Comparison of the squared error and KL divergence lossses for a consistency regularization. This visualization is for a binary classification problem where it is assumed that the model's output for the unperturbed input is 1. The figure plots the loss incurred for a particular value of the logit (i.e.\ the pre-activation fed into the output sigmoid nonlinearity) for the perturbed input. As the logit grows towards infinity, the model predicts a class label of 1 (in agreement with the prediction for the unperturbed input); as it grows towards negative infinity, the model predictions class 0. The squared error loss saturates (and has zero gradients) when the model predicts one class or the other with high probability, but the KL divergence grows without bound as the model predicts class 0 with more and more confidence. #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/sevskl.png") # ## Figure 19.21:<a name='19.21'></a> <a name='ssgan'></a> # # Diagram of the semi-supervised GAN framework. The discriminator is trained to output the class of labeled datapoints (red), a ``fake'' label for outputs from the generator (yellow), and any label for unlabeled data (green). #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/ssgan.png") # ## Figure 19.22:<a name='19.22'></a> <a name='SimCLR2'></a> # # Combinng self-supervised learning on unlabeled data (left), supervised fine-tuning (middle), and self-training on pseudo-labeled data (right). From Figure 3 of <a href='#Chen2020nips'>[Tin+20]</a> . Used with kind permission of <NAME> #@title Setup { display-mode: "form" } # %%time # If you run this for the first time it would take ~25/30 seconds # !git clone https://github.com/probml/pyprobml /pyprobml &> /dev/null && git clone https://github.com/probml/colab_powertoys.git &> /dev/null # !pip3 install nbimporter -qqq # %cd -q /content/colab_powertoys from colab_powertoys.probml_toys import probml_toys as pmlt # %cd -q /pyprobml/scripts pmlt.show_image("/pyprobml/book1/figures/images/simCLR2.png") # ## References: # <a name='Finn2018'>[CKS18]</a> <NAME>, <NAME> and <NAME>. "Probabilistic Model-Agnostic Meta-Learning". (2018). # # <a name='T5'>[Col+19]</a> <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Exploring the Limits of Transfer Learning with a UnifiedText-to-Text Transformer". abs/1910.10683 (2019). arXiv: 1910.10683 # # <a name='Pathak2016'>[Dee+16]</a> <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Context Encoders: Feature Learning by Inpainting". (2016). # # <a name='bert'>[Jac+19]</a> <NAME>, <NAME>, <NAME> and <NAME>. "BERT: Pre-training of Deep Bidirectional Transformers forLanguage Understanding". (2019). # # <a name='LeCunSSL2018'>[LeC18]</a> <NAME>Cun "Self-supervised learning: could machines learn like humans?". (2018). # # <a name='Vinyals2016'>[Ori+16]</a> <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Matching Networks for One Shot Learning". (2016). # # <a name='squad'>[Pra+16]</a> <NAME>, <NAME>, <NAME> and <NAME>. "SQuAD: 100,000+ Questions for Machine Comprehension of Text". (2016). # # <a name='Chen2020nips'>[Tin+20]</a> <NAME>, <NAME>, <NAME>, <NAME> and <NAME>. "Big Self-Supervised Models are Strong Semi-SupervisedLearners". (2020). # #
book1/figures/chapter19_figures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Jacobian vs. Perturbation # Visualizing and Understanding Atari Agents | <NAME> | 2017 | MIT License # + from __future__ import print_function import warnings ; warnings.filterwarnings('ignore') # mute warnings, live dangerously import matplotlib.pyplot as plt import matplotlib as mpl ; mpl.use("Agg") import matplotlib.animation as manimation import torch from torch.autograd import Variable import torch.nn.functional as F import gym, os, sys, time, argparse sys.path.append('..') from visualize_atari import * # - # ## Load agent, build environment, play an episode # + env_name = 'Breakout-v0' save_dir = 'figures/' print("set up dir variables and environment...") load_dir = '{}/'.format(env_name.lower()) meta = get_env_meta(env_name) env = gym.make(env_name) ; env.seed(1) print("initialize agent and try to load saved weights...") model = NNPolicy(channels=1, num_actions=env.action_space.n) _ = model.try_load(load_dir, checkpoint='*.tar') ; torch.manual_seed(1) print("get a rollout of the policy...") history = rollout(model, env, max_ep_len=3e3) # - f = plt.figure(figsize=[3,3*1.3]) # frame_ix = 1404 frame_ix=1307 plt.imshow(history['ins'][frame_ix]) for a in f.axes: a.get_xaxis().set_visible(False) ; a.get_yaxis().set_visible(False) plt.show(f) # ## Get Jacobian saliency map # + def jacobian(model, layer, top_dh, X): global top_h_ ; top_h_ = None def hook_top_h(m, i, o): global top_h_ ; top_h_ = o.clone() hook1 = layer.register_forward_hook(hook_top_h) _ = model(X) # do a forward pass so the forward hooks can be called # backprop positive signal torch.autograd.backward(top_h_, top_dh.clone(), retain_variables=True) # backward hooks are called here hook1.remove() return X[0].grad.data.clone().numpy(), X[0].data.clone().numpy() # derivative is simply the output policy distribution top_dh_actor = torch.Tensor(history['logits'][frame_ix]).view(1,-1) top_dh_critic = torch.Tensor(history['values'][frame_ix]).view(1,-1).fill_(1) # get input tens_state = torch.Tensor(prepro(history['ins'][frame_ix])) state = Variable(tens_state.unsqueeze(0), requires_grad=True) hx = Variable(torch.Tensor(history['hx'][frame_ix-1]).view(1,-1)) cx = Variable(torch.Tensor(history['cx'][frame_ix-1]).view(1,-1)) X = (state, (hx, cx)) actor_jacobian, _ = jacobian(model, model.actor_linear, top_dh_actor, X) state.grad.mul_(0) ; X = (state, (hx, cx)) critic_jacobian, _ = jacobian(model, model.critic_linear, top_dh_critic, X) # - # ## Get perturbation saliency map # + radius = 5 density = 5 actor_saliency = score_frame(model, history, frame_ix, radius, density, interp_func=occlude, mode='actor') critic_saliency = score_frame(model, history, frame_ix, radius, density, interp_func=occlude, mode='critic') # + # upsample jacobian saliencies frame = history['ins'][frame_ix].squeeze().copy() frame = saliency_on_atari_frame((actor_jacobian**2).squeeze(), frame, fudge_factor=1, channel=2, sigma=0) jacobian_map = saliency_on_atari_frame((critic_jacobian**2).squeeze(), frame, fudge_factor=15, channel=0, sigma=0) # upsample perturbation saliencies frame = history['ins'][frame_ix].squeeze().copy() frame = saliency_on_atari_frame(actor_saliency, frame, fudge_factor=200, channel=2) perturbation_map = saliency_on_atari_frame(critic_saliency, frame, fudge_factor=100, channel=0) # - # ## Plot side-by-side # + f = plt.figure(figsize=[11, 5*1.3], dpi=75) plt.subplot(1,2,1) plt.imshow(jacobian_map) plt.title('Jacobian', fontsize=30) plt.subplot(1,2,2) plt.imshow(perturbation_map) plt.title('Ours', fontsize=30) for a in f.axes: a.get_xaxis().set_visible(False) ; a.get_yaxis().set_visible(False) plt.show() #; f.savefig('./figures/jacobian-vs-perturb.png', bbox_inches='tight') # -
visualize_atari/jacobian-vs-perturbation.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda env:pyvizenv2] # language: python # name: conda-env-pyvizenv2-py # --- # imports import panel as pn pn.extension('plotly') import plotly.express as px import pandas as pd import hvplot.pandas import matplotlib.pyplot as plt import numpy as np import os from pathlib import Path from dotenv import load_dotenv import warnings warnings.filterwarnings('ignore') from panel.interact import interact # + tags=[] pip install pandas # - # Read the census data into a Pandas DataFrame file_path = Path('sfo_neighborhoods_census_data.csv') sfo_data = pd.read_csv(file_path, index_col="year") sfo_data.head() # Calculate the mean number of housing units per year (hint: use groupby) housing_units= sfo_data.groupby('year').mean() housing_units.drop(['sale_price_sqr_foot', 'gross_rent'], axis=1) # + # Use the Pandas plot function to plot the average housing units per year. # Note: You will need to manually adjust the y limit of the chart using the min and max values from above min = housing_units.min()['housing_units'] max = housing_units.max()['housing_units'] housing_units.plot.bar(ylim =(min-1000, max+1000),title="Housing Units in San Francisco from 2010 to 2016",figsize=(10,5)) plt.show() plt.close('housing_units') # - # Calculate the average gross rent and average sale price per square foot average_rent_sqr_foot = sfo_data["gross_rent"].groupby([sfo_data.index]).mean() average_rent_sqr_foot # Plot the Average Gross Rent per Year as a Line Chart average_rent_sqr_foot.plot.line(title="Average Goss Rent per Year",figsize=(10,5)) # Plot the Average Sales Price per Year as a line chart average_price_per_sqr_foot = sfo_data["sale_price_sqr_foot"].groupby([sfo_data.index]).mean() average_price_per_sqr_foot.plot(title="Average Sales Price per Square Foot in San Francisco",figsize=(10,5)) # Group by year and neighborhood and then create a new dataframe of the mean values sfo_data_new = sfo_data.groupby([sfo_data.index, "neighborhood"]).mean() sfo_sales = sfo_data_new["sale_price_sqr_foot"] sfo_sales_df = pd.DataFrame(sfo_sales).reset_index() sfo_sales_df.head() sfo_data_new_gr = sfo_data.groupby([sfo_data.index, "neighborhood"]).mean() sfo_rent = sfo_data_new_gr["gross_rent"] sfo_rent_df = pd.DataFrame(sfo_rent).reset_index() sfo_rent_df.head() # + #Use hvplot to create an interactive line chart of the average price per sq. ft. #The plot should have a dropdown selector for the neigborhood def choose_neighborhood(neighborhood): return sfo_sales_df.loc[sfo_sales_df['neighborhood']==neighborhood,:].hvplot.line( x="year", y="sale_price_sqr_foot", colormap="viridis", title="SF Sale per Square foot per Year", ) neighborhood_choice = sfo_sales_df["neighborhood"] interact(choose_neighborhood, neighborhood=neighborhood_choice) # + #Use hyplot to create an interactive line chart of the average monthly rent. #The plot should have a dropdown selector for the neighorhood def choose_neighborhood(neighborhood): return sfo_rent_df.loc[sfo_rent_df['neighborhood']==neighborhood,:].hvplot.line( x="year", y="gross_rent", colormap="viridis", title="SF Average Monthly Rent", ) neighborhood_choice = sfo_rent_df["neighborhood"] interact(choose_neighborhood, neighborhood=neighborhood_choice) # - # Getting the data from the top 10 expensive neighborhoods top_10_most_expensive = sfo_data.sort_values(by='sale_price_sqr_foot', ascending=False).head(10) top_10_most_expensive avg_value_per_neighborhood = sfo_data.groupby([sfo_data["neighborhood"]]).mean() avg_value_per_neighborhood = avg_value_per_neighborhood.reset_index() avg_value_per_neighborhood.head(10) # Plotting the data from the top 10 expensive neighborhoods top_10_most_expensive.hvplot.bar( x="neighborhood", y="sale_price_sqr_foot", title="Top 10 Most Expensive Neighborhoods in San Francisco") # Load neighborhoods coordinates data file_path = Path('neighborhoods_coordinates.csv') sfo_neighborhood_locations = pd.read_csv(file_path) sfo_neighborhood_locations.head() # Calculate the mean values for each neighborhood file_path = Path('neighborhoods_coordinates.csv') sfo_neighborhood_location = pd.read_csv(file_path) # Join the average values with the neighborhood locations avg_value_location = pd.concat([avg_value_per_neighborhood, sfo_neighborhood_location], axis="columns", join="inner") avg_value_location.head() # Set the mapbox access token load_dotenv() map_box_api = os.getenv("mapbox") px.set_mapbox_access_token(map_box_api) # Create a scatter mapbox to analyze neighborhood info px.scatter_mapbox( avg_value_location, lat="Lat", lon="Lon", color="sale_price_sqr_foot")
PyViz Homework Rental Analysis.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Python 1+2 # 10-5 2*6 ''' hi there ''' x = 1 type(x) x = 1.0 type(x) x z = 1+2j type(z) a=True type(a) b = False type(b) c = 'string' type(c) d = "string" type(d) c= 'str\'ing' c print("Hello") print("You"re nice") 10/3 10//3 d=True print(d) f = 'Hello' type(f) c = 1+2j print(c.real) print(c.imag) f+'world' print(c.real,c.imag) g = f+"yo" print(g) g+'22May' g+22 True and True True or True True xor True True XAND True True or True True or False False or True False or False True and True True and False False and True False and False g = False and False ~g a=10 if a==10: print("True") else: print("False") i=10 if i<3: print("less than 3") elif i==3: print("Equal to 3") else: print("More than 3") # 22may '''22May 2019''' l=[] l = list() type(l) a = [13,78,345,78,8,1] type(a) a[0] a[7] a[8] a[10] a[1:6] a[1:7] a[1:6:2] a a[1:2:2] a[1:2:3] a[1:3:2] a[1:4:2] a[2:] a[:-1] a a[2:-2] a a[1:6] a[1:11] g = (True and (not False)) or ((not True) and (False)) g a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] a[10:20:2] a[0:2] a[10:26] a[10:25] # + # list is start,stop,step # - a = [10,123,32,43,24,55,26,47,68,79,210,411,612,413,414,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] len(a) b = [1,2,3,4,5] len(b) dir(b) dir(a) # to append a value to b b.append('6') b b.pop('6') b.remove('6') b b.append(6) b b.append(7,8) b.append(7) b.append(8) b b.remove(7,8) b.insert(3,10) b a = [1,2,3] b = [4,5,6] a.append(b) a a = [1,2] b = [3,4] c = a.append(b) # press Shift+Tab while placing the cursor on the function to know its syntax c # + # two lists can be appended by using '+' operator # c = append(b), c is empty as assignment operator cannot work here # + #To sort the elements in A.O # - a = [1,2,3] print(a) a = [1,2,3] a print(help(q.sort())) print(help(a.sort())) dir(a) a.sort() a = [1,2,3,4,5] a.sort(reverse=True) a clear() a a.clear() a a = [1,2,3] b = [] b.copy(a) b.copy() a.copy() b = a.copy() b c = a c a.count() a.count(1) a = [1,1,2,2,2,3,3,3,4,5,6,6,7] a.count(2) a = [] a.extend(1,2,3,4,5) a.extend(1) i = 1 a.extend(i) a.extend('1') a a = [6,2,4,1,5,2,3,4,1] a.index(2,0,10) a.index(2,2,10) dir(a) a = [5,4,3,2,1] a.sort() a a = [1,2,3,4,5] a.sort(reverse=True) a a.pop(/) a.pop() a = [1,3,5,7,9] a.pop() a a.reverse() a a = [1,9,2,8,3,7] a.reverse() a a = [1,2,3] b = [4,5,6] a.extend(b) a a.extend(1) a.extend(1,2,3,4,5) a.extend([1,2,3]) a dir(a) # # Day 4: Operators a = 10 b = 12 a==b a!=b a>b a<b a>=b a<=b a<>b #doesn't work in jupyter notebook c=a+b c+=a a = 24 b = 12 a-=b c=a print(c) a*=b d = a print(d) a//=b e = a print(e) a/=b f = a print(f) a**=b g = a print(g) a = [1,2,3,4,5] b = 4 c = b in a print(c) A = True B = False print(A and A) print(A and B) print(B and A) print(B and B) print(A or A) print(A or B) print(B or A) print(B or B) print(not A,not B) a = 4 #4 is 100 b = 5 #5 is 101 print(a & b) print(a | b) print(a ^ b) print(~a,~b) print(a<<b,a>>b) x = 100 y = 10 print(y is x,x is y,y is not x,x is not y) x = sanjay y = jay print(y is x,x is y,y is not x,x is not y) a = "helloworld" b = "hello" print(a in b,a not in b,b in a,b not in a) a=[1,0,0] b = [0] print(a in b,a not in b,b in a,b not in a) a = "100" b = "0" print(a in b,a not in b,b in a,b not in a) a = 100 b = 0 print(a in b,a not in b,b in a,b not in a) # # Day 6 bin(10) #bin() and int() int(0b1010) #0b is binary system a = 10<<1 b = 10<<2 c = 10<<3 print(a,b,c) a = 10>>1 b = 10>>2 c = 10>>3 print(a,b,c) l1 = [1,2,3] l2 = [2,3,4] matrix = [l1,l2] print(matrix) #indexing and slicing in this format of nested lists #indexing matrix[0][2] #slicing l1 = [1,2,3,4,5] l2 = [1,2,3,4,5,6,7,8,9,10] matrix1 = l1+l2 print(matrix1) matrix2 = [l1,l2] print(matrix2) matrix2[1][4:-2] matrix2[1][-9:-3] #forward order matrix2[1][-4:-10:-1] #reverse order type(x) l1 = [1,2,3] [x**2 for x in l1] type(x) #type of x is gettin displayed because we must have used x somehere above, usually there is an error in this type fo statement as x is dynamically created and destroyed once the list comprehension is done l1 = [1,2,3] l2 = [t*2 for t in l1] print(l2) type(t) #this variable t is created in run time, once the list is done, t is destroyed l1 = [1,2,3] l2 = [2,3,4] l3 = [4,5,6] matrix = [l1,l2,l3] print(matrix) first_col = [row[0] for row in matrix] print(first_col) first_col_op = [row[0]*2 for row in matrix] print(first_col_op) l = [1,2,3,4,5] for every_letter in l: print(every_letter) sum = 0 for val in l: sum+=val print("The sum is: ",sum) digits = [1,2,3] for i in digits: print(i) else: print("No more digits left") x = 5 sum = 0 while x>0: sum+=x; print("x value of: %d has the sum %d : " %(x,sum)) x-=1 x = 5 sum = 0 while x>0: sum+=x; print("x value of: {} has the sum {} : " .format(x,sum)) x-=1 type({}) #{} can be used for both intergers and strings for i in range(5): print(i) for i in range(1,5,2): print(i) # # Day 7 # + #other data types # + #String a = "hello" # - dir(a) #know the length of the string len('<NAME>') #indexing and slicing s = "hello world" s[6:11] s[1:2] s[1] s[::-1] #print in reverse order s[::-2] #strings are immutable s[1] = 'x' s = "sanjay" #concatentaion s + ' prabhu' # + #operations +,* s = "s" s*10 # - s = "sanjay" s.upper() s1 = "Sanjay" s2 = " Prabhu" #with space s3 = "Prabhu" #without space s1.upper() s2.lower() s3.lower() s = s1+s2 print(s) s.split() s = s1+s3 print(s) s.split() s = "<NAME>" print(s.count(a)) print(s.count('a')) sq = "<NAME>" print(sq.center(100)) #center can work as spaces print(sq.center(100,'Z')) #spaces can be replaced by letter or any other characters print(sq.center(12,'Z')) #the given width should be more than the length of the variable assigned\ len(sq) sq.expandtabs() "hello\tthis".expandtabs() #this is for the \t to work "hello\tthis" "hello\nworld".expandtabs() s = "hello" s.isalnum() # is alphabetic numeral (both alphabets and numbers) s = "hello123" s.isalnum() s = "hello12.3" s.isalnum() s.isalpha() s = "hello" s.isalpha() print(s.islower()) print(s.isupper()) s.istitle() s.endswith('o') s.endswith('p') print(s.split('e')) print(s.partition('e')) s = "hello world" print(s.split()) print(s.split('l')) type(s.partition('e')) list(s.partition('e')) tuple(s.partition('e')) # + #tuples # - #two ways for tuples like list: t = () tt = tuple() t = (1,2,3) t[0] t[0] = 2 #tuple is an immutable data type dir(t) s = "find me" s.find('f') #dicionary #two ways of creating an empty dictionary d = {} dd = dict() print(type(d)) print(type(dd)) my_dict = {'key1':'value1','key2':'value2'} my_dict['key1'] my_dict['key2'] # + #to put lists or tuples inside dictionary # - d = {'k1':123,'k2':'123','k3':[1,2,3],'k4':['1','2','3'],'k5':(1,2,3)} #indexing and slicing print(d['k1']) print(d['k2']) print(d['k3']) print(d['k4']) print(d['k5']) d = {1:'v1',2:'v2'} print(d[1]) print(d[0]) d = {'k1':123,'k2':'123','k3':[1,2,3],'k4':['1','2','3'],'k5':(1,2,3)} d['k2'][2] d['k4'][1:] #built in for dictionaries dir(d) d.keys() d.items() d.popitem() d.pop('k1') d d.pop('k3') d dir(d) d1 = {'k1':'v1'} d2 = {'k2':'v2'} d = d1 + d2 print(d) d = {d1,d2} d = [d1,d2] print(d) d = (d1,d2) print(d) dir(d) dir(d1) d = {'k1':123,'k2':'123','k3':[1,2,3],'k4':['1','2','3'],'k5':(1,2,3)} d.get('k2') d.setdefault('k6',('1','2','3')) d.get('k6') # # Day 8 #NESTED DICTIONARY d = {'k1':{'nestedk1':{'subnestedk1':'v1'}}} print(d['k1']) print(d['k1']['nestedk1']) print(d['k1']['nestedk1']['subnestedk1']) d = {'k1':{'k2':{'k3':[1,2,3]}}} print(d['k1']['k2']['k3'][1]) print(d.keys()) print(d['k1'].keys()) print(d['k1']['k2'].keys()) print(d['k1']['k2']['k3'].keys()) # + ### ----- Dictionary Comprehension ----- ### #Syntax for dictionray Comprehension ''' {key:value for item in list if condition} ''' {x:x**2 for x in range(10)} # - # # Sets #Creating empty sets #only 1 way x = set() type(x) #removes duplicates, this is the difference between list and a set s = {1,2,2,3,3,3} type(s) print(s) l = {1,2,2,3,3,3,4,4,4,4} s = set(l) print(s) # # Day 9 # + intab = 'aeiou' outab = "12345" trantab = str.maketrans(intab,outab) print(trantab) s = "Hello world, I am Sanjay" print(s.translate(trantab)) # - # ### Functions # + #The advantage of the functions is: Reproducibilty # + def hello(): print("Hello world") hello() # + def greeting(name): print("Hello: %s, how are you?"%name) greeting("Sanjay") # + def concat_strings(str1,str2): str3 = str1+str2 print(str3) concat_strings("Sanjay"," Prabhu") # + def is_prime(n): for i in range(2,n): if n%i==0: print("Not a prime") break else: print("The number %d is a prime."%n) is_prime(4) is_prime(13) # -
Data-Science-HYD-2k19/.ipynb_checkpoints/Day 1 - 10 (Classwork)-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.6 # language: python # name: python36 # --- # Copyright (c) Microsoft Corporation. All rights reserved. # # Licensed under the MIT License # ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/training/using-environments/using-environments.png) # # Using environments # # # ## Contents # # 1. [Introduction](#Introduction) # 1. [Setup](#Setup) # 1. [Create environment](#Create-environment) # 1. Add Python packages # 1. Specify environment variables # 1. [Submit run using environment](#Submit-run-using-environment) # 1. [Register environment](#Register-environment) # 1. [List and get existing environments](#List-and-get-existing-environments) # 1. [Other ways to create environments](#Other-ways-to-create-environments) # 1. From existing Conda environment # 1. From Conda or pip files # 1. [Docker settings](#Docker-settings) # 1. [Spark and Azure Databricks settings](#Spark-and-Azure-Databricks-settings) # 1. [Next steps](#Next-steps) # # ## Introduction # # Azure ML environments are an encapsulation of the environment where your machine learning training happens. They define Python packages, environment variables, Docker settings and other attributes in declarative fashion. Environments are versioned: you can update them and retrieve old versions to revist and review your work. # # Environments allow you to: # * Encapsulate dependencies of your training process, such as Python packages and their versions. # * Reproduce the Python environment on your local computer in a remote run on VM or ML Compute cluster # * Reproduce your experimentation environment in production setting. # * Revisit and audit the environment in which an existing model was trained. # # Environment, compute target and training script together form run configuration: the full specification of training run. # # ## Setup # # If you are using an Azure Machine Learning Notebook VM, you are all set. Otherwise, make sure you go through the [configuration notebook](../../../configuration.ipynb) first if you haven't. # # First, let's validate Azure ML SDK version and connect to workspace. # + active="" # import azureml.core # from azureml.core import Workspace # # print(azureml.core.VERSION) # - ws = Workspace.from_config() ws.get_details() # ## Create environment # # You can create an environment by instantiating ```Environment``` object and then setting its attributes: set of Python packages, environment variables and others. # # ### Add Python packages # # The recommended way is to specify Conda packages, as they typically come with complete set of pre-built binaries. # + from azureml.core import Environment from azureml.core.environment import CondaDependencies myenv = Environment(name="myenv") conda_dep = CondaDependencies() conda_dep.add_conda_package("scikit-learn") # - # You can also add pip packages, and specify the version of package conda_dep.add_pip_package("pillow==5.4.1") myenv.python.conda_dependencies=conda_dep # ### Specify environment variables # # You can add environment variables to your environment. These then become available using ```os.environ.get``` in your training script. myenv.environment_variables = {"MESSAGE":"Hello from Azure Machine Learning"} # ## Submit run using environment # # When you submit a run, you can specify which environment to use. # # On the first run in given environment, Azure ML spends some time building the environment. On the subsequent runs, Azure ML keeps track of changes and uses the existing environment, resulting in faster run completion. # + from azureml.core import ScriptRunConfig, Experiment myexp = Experiment(workspace=ws, name = "environment-example") # - # To submit a run, create a run configuration that combines the script file and environment, and pass it to ```Experiment.submit```. In this example, the script is submitted to local computer, but you can specify other compute targets such as remote clusters as well. # + runconfig = ScriptRunConfig(source_directory="example", script="example.py") runconfig.run_config.target = "local" runconfig.run_config.environment = myenv run = myexp.submit(config=runconfig) run.wait_for_completion(show_output=True) # - # ## Register environment # # You can manage environments by registering them. This allows you to track their versions, and reuse them in future runs. For example, once you've constructed an environment that meets your requirements, you can register it and use it in other experiments so as to standardize your workflow. # # If you register the environment with same name, the version number is increased by one. Note that Azure ML keeps track of differences between the version, so if you re-register an identical version, the version number is not increased. myenv.register(workspace=ws) # ## List and get existing environments # # Your workspace contains a dictionary of registered environments. You can then use ```Environment.get``` to retrieve a specific environment with specific version. # + for name,env in ws.environments.items(): print("Name {} \t version {}".format(name,env.version)) restored_environment = Environment.get(workspace=ws,name="myenv",version="1") print("Attributes of restored environment") restored_environment # - # ## Other ways to create environments # # ### From existing Conda environment # # You can create an environment from existing conda environment. This make it easy to reuse your local interactive environment in Azure ML remote runs. For example, if you've created conda environment using # ``` # conda create -n mycondaenv # ``` # you can create Azure ML environment out of that conda environment using # ``` # myenv = Environment.from_existing_conda_environment(name="myenv",conda_environment_name="mycondaenv") # ``` # # ### From conda or pip files # # You can create environments from conda specification or pip requirements files using # ``` # myenv = Environment.from_conda_specification(name="myenv", file_path="path-to-conda-specification-file") # # myenv = Environment.from_pip_requirements(name="myenv", file_path="path-to-pip-requirements-file") # ``` # # ## Docker settings # # Docker container provides an efficient way to encapsulate the dependencies. When you enable Docker, Azure ML builds a Docker image and creates a Python environment within that container, given your specifications. The Docker images are reused: the first run in a new environment typically takes longer as the image is build. # # **Note:** For runs on local computer or attached virtual machine, that computer must have Docker installed and enabled. Machine Learning Compute has Docker pre-installed. # # Attribute ```docker.enabled``` controls whether to use Docker container or host OS for execution. myenv.docker.enabled = True # You can specify custom Docker base image and registry. This allows you to customize and control in detail the guest OS in which your training run executes. whether to use GPU, whether to use shared volumes, and shm size. myenv.docker.base_image myenv.docker.base_image_registry # You can also specify whether to use GPU or shared volumes, and shm size. myenv.docker.gpu_support myenv.docker.shared_volumes myenv.docker.shm_size # ## Spark and Azure Databricks settings # # In addition to Python and Docker settings, Environment also contains attributes for Spark and Azure Databricks runs. These attributes become relevant when you submit runs on those compute targets. # ## Next steps # # Learn more about remote runs on different compute targets: # # * [Train on ML Compute](../../train-on-amlcompute) # # * [Train on remote VM](../../train-on-remote-vm)
how-to-use-azureml/training/using-environments/using-environments.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np df = pd.read_csv('cars.csv',delimiter=';') df.head(10) df.dtypes df.isnull().sum() import seaborn as sns import matplotlib.pyplot as plt # %matplotlib inline # <h2 style="color:blue" align="left"> 1. You can use heatmaps to visualize your data highlighting the missing data </h2> plt.figure(figsize=(10,9)) sns.heatmap(df.isnull()) plt.figure(figsize=(10,9)) sns.heatmap(df.isnull(), cbar=False) plt.figure(figsize=(10,9)) sns.heatmap(df.isnull(), yticklabels=False, cbar=False) plt.figure(figsize=(10,8)) sns.heatmap(df.isnull(), yticklabels=False, cbar=False, cmap='viridis') # <h2 style="color:blue" align="left"> 2. You can visualize each column of data in boxplots to find outliers </h2> df1 = df.iloc[1:] df1 plt.figure(figsize=(12, 7)) sns.boxplot(x='MPG', y='Cylinders', data=df, palette='winter')
10_Missing_Values/3_Graphs/1_Heat_map & Box_plot.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + [markdown] colab_type="text" id="D7QLH_oKs5mw" # ### Create a dataframe in pandas using list and series # + [markdown] colab_type="text" id="Av2DsC1QtCvZ" # #### create a data frame using list # # # list1 = ['I', 'Love', 'Data', 'Science'] # # # - import numpy as np import pandas as pd list1 = ['I', 'Love', 'Data', 'Science'] df = pd.DataFrame([list1]) df # # #### create dataframe from Dictionary # # city_state = {'Delhi': 'Delhi', 'Mumbai': 'Maharashtra', 'Kolkata': 'West Bengal', 'Banglore': 'Karnataka'} # # Write a code here import numpy as np import pandas as pd city_state = {'Delhi': 'Delhi', 'Mumbai': 'Maharashtra', 'Kolkata': 'West Bengal', 'Banglore': 'Karnataka'} #city_state2 = {'state':['Delhi', 'Maharashtra', 'West Bengal', 'Karnataka'],'city':['Delhi','Mumbai','Kolkata','Banglore']} pd.DataFrame(city_state, index=['state']) #pd.DataFrame(city_state2) # + import pandas as pd import numpy as np #Create a DataFrame df1 = { 'State':['Arizona AZ','Georgia GG','Newyork NY','Indiana IN','Florida FL'], 'Score':[62,47,55,74,31]} df1 = pd.DataFrame(df1,columns=['State','Score']) print(df1) # - df1.iloc[::-1,:]
Arvind/Introduction to Dataframes and Creating Dataframes.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Final Homework & In Class Assignment # ### This will be graded as a homework assignment, Due May 3, 2019 at 11:59pm # # Over the next 4 lectures you will develop a machine learning algorithm to # classify Gray, White and CSF segmentatoin maps from t1 and t2 weighted images. # # This assignment is an extension of the MIATT_INCLASS work that we have been performing over the past several lectures. Your challenge is to develop a medical imaging machine learning algorithm to segment brains into gray, white, and csf segmentations. A segmentation image is one where values greater to 0.5 are considered to be part of the segmentation, and values less or equal to 0.5 are not part of the segmentation. # # The files `HW8.ipynb` and `HW8functions.py` should be placed in your `inclass3-abpwrs/MIATT2019_ML` directory # # ## GRADING: # # | Points | Description | # |---------|-----------------------| # | 60 | The documentation that describes why and what you are attempting to do | # | 15 | Employing reproducable science techniques | # | 10 | Quality of the segmentations on the hidden data sets | # | 15 | Quality of the analytics used to evaluate the intermediate results | # | | | # | 33 | Extra credit for the best solutions | # | 20 | Extra credit for the second best solutions | # | 10 | Extra credit for the third place best solutions | # # There will be at least 3 extra credit prizes given to the best solutions. # # # ## Data # # A large data set has been organized in '/nfsscratch/opt/ece5490/data/MIATT_EYES' (This is too large to download) # # Within this directory there are subjectories named with a 4 digit subject identifier, followed by a session directory indicating the when the scan was collected (always '_hcpy1' in this assignment). # # | Image data paths for subject 0144 | # |------------------------------------| # |0144/0144_hcpy1/ACPCAlign/BCD_ACPC_Landmarks.fcsv| # |0144/0144_hcpy1/ACPCAlign/Cropped_BCD_ACPC_Aligned.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_BACKGROUND_TOTAL.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_CSF_TOTAL.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_GLOBUS_TOTAL.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_GM_TOTAL.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_VB_TOTAL.nii.gz| # |0144/0144_hcpy1/ACCUMULATED_POSTERIORS/POSTERIOR_WM_TOTAL.nii.gz| # |0144/0144_hcpy1/TissueClassify/t1_average_BRAINSABC.nii.gz| # |0144/0144_hcpy1/TissueClassify/t2_average_BRAINSABC.nii.gz| # # # The data shall be partitioned into the following sets: # # | Image Range | Description | # | ------------- | ------------- | # | 0001 - 0100 | Hidden Tests (You won't have access to these until class on May 2nd, they will be used for grading) | # | 0101 - 0200 | Test Data (Used for testing your models before submission)| # | 0201 - 0300 | Validation Data (Used for validating your models during training)| # | 0301 - 0804 | Trainging Data (Used for training your models) | # # # ## My model does not fit inside of a git repo, run the command below to download it. # !curl http://user.engineering.uiowa.edu/~abpwrs/RF.pickle -o RF.pickle # ## My Approach # I treated this as a classification problem and **NOT** a regression problem. # # # # My first attempt was a fully convolutional neural network consisting of 5 convolutional layers. I set the padding to `same` so that the image size wouldn't decrease with each `Conv3D`. I also used `Dropout` in an attempt to avoid overfitting of my model. I initially thought this model performed okay, but when I attempted to replicate the inference phase, I ran into lots of issues of inconsistent classifications and model loading failures. This model is **NOT** used for the inference below. You are welcome to look at the [STRAIGHT_CONV.ipynb](./STRAIGHT_CONV.ipynb), but it is a mess of me debugging the reproducibility error... This attempt is included to record my work on this hw. # # # # My second attempt was a pretty traditional feature engineering approach. I selected features (t1 pixel intensity, t1 neighborhood avg, edge image pixel intensity, edge image neighborhood avg). I then trained a random forest model on these engineered features. The code for this classifier training validation and saving can be found in [RF_voxelwise.ipynb](./RF_voxelwise.ipynb). # ## Label Mask Generation # The label mask is a 3D image of the same size, spacing, direction, and origin as the origional images, but each pixel intensity represents a class of tissue. # I arbitrarily chose the following scalars to represent each tissue class: # ```text # background -> 0 # gm -> 1 # wm -> 2 # csf -> 3 # ``` # # I created a `get_label_mask` method for my `Subject` class, so that retrieving the label mask would feel natural and be very intuitive (the same as `get_t1_image`). # Below is the method I used to generate a label mask from probability masks: # ```python # # generate a label mask of the image based on the probabilities # def get_label_mask(self): # """ # OUTPUTS: # label_mask where # background -> 0 # gm -> 1 # wm -> 2 # csf -> 3 # # Processing: # - highest probability wins the voxel # - background probability mask will be used to exclude extraneous labels # """ # # if the label mask as been computed, don't recompute # if self.label_mask: # return self.label_mask # # # threshold of acceptable background probability # bg_thresh = 0.0001 # less that 1/100 % probability of background # # # get numpy array versions of all probability masks as floating point # def get_im_as_float_arr(im): # return sitk.GetArrayFromImage(im).astype(np.float) # # gm = get_im_as_float_arr(self.get_gm_prob_mask()) # wm = get_im_as_float_arr(self.get_wm_prob_mask()) # csf = get_im_as_float_arr(self.get_csf_prob_mask()) # bg = get_im_as_float_arr(self.get_bg_prob_mask()) # # # mask where grey matter has the highest probability # gm_mask = sitk.GetImageFromArray((gm > 0.5) * 1) # # gm has a label value of 1 # # # mask where white matter has the highest probability # wm_mask = sitk.GetImageFromArray((wm > 0.5) * 2) # # wm has a label value of 2 # # # mask where csf has the highest probability # csf_mask = sitk.GetImageFromArray((csf > 0.5) * 3) # # csf has a label value of 3 # # # copy over information using t1 image # t1_im = self.get_t1_image() # gm_mask.CopyInformation(t1_im) # wm_mask.CopyInformation(t1_im) # csf_mask.CopyInformation(t1_im) # # # masks will not overlap because we created them based on the # # highest probability values # self.label_mask = sitk.Cast(gm_mask + wm_mask + csf_mask, sitk.sitkUInt8) # return self.label_mask # ``` # # First Attempt --> CNN w/ keras (reproducability failure) # ### The Model (purely convolutional network on the image level) # ``` text # _________________________________________________________________ # Layer (type) Output Shape Param # # ================================================================= # conv3d (Conv3D) (None, 128, 128, 128, 32) 896 # _________________________________________________________________ # conv3d_1 (Conv3D) (None, 128, 128, 128, 32) 27680 # _________________________________________________________________ # dropout (Dropout) (None, 128, 128, 128, 32) 0 # _________________________________________________________________ # conv3d_2 (Conv3D) (None, 128, 128, 128, 32) 27680 # _________________________________________________________________ # dropout_1 (Dropout) (None, 128, 128, 128, 32) 0 # _________________________________________________________________ # conv3d_3 (Conv3D) (None, 128, 128, 128, 32) 27680 # _________________________________________________________________ # dropout_2 (Dropout) (None, 128, 128, 128, 32) 0 # _________________________________________________________________ # conv3d_4 (Conv3D) (None, 128, 128, 128, 1) 865 # ================================================================= # Total params: 84,801 # Trainable params: 84,801 # Non-trainable params: 0 # _________________________________________________________________ # ``` # # ### Issues I Ran Into # * Memory Issues # * Can only load a limited number of images into RAM, which would force me to use a method that loads and cleans images right before the image is fed into the network. # # * Reproducable science issues # * I noticed inconsistent segmentations for the same image across multiple runs # * The model also failed to load depending on the run # * The model also gave lots of `out of memory` errors when it was nowhere near it's RAM limits # # # Due to these issues, I only used 100 images as my training data and 10 images as validation. In addition, this model is not used for my final classifcation, a much more naive sklearn model is used. # # ### Performance # **THIS MODEL PERFORMED POORLY!!!!!** # **AS THIS IS NOT REPRODUCIBLE ALL PERFORMANCE METRICS SHOULD BE TAKEN WITH A GRAIN OF SALT.** # It "achieved" 87% validation accuracy during training without actually learning the segmentations. # Around the $ {68}^{th} $ iteration the model training hit an error and I got unexpected behavior that plateaued the loss and accuracy at relatively bad values. This is likely due to a weight getting set to zero or some other fault in the network weights. # # #### Loss (Mean Squared Error) # ![](./imgs/e-loss-miatt-hw8.png) # ![](./imgs/e-val-loss-miatt-hw8.png) # # #### Accuracy # ![](./imgs/e-acc-miatt-hw8.png) # ![](./imgs/e-val-acc-miatt-hw8.png) # # #### The Segmentation at Iteration 65 # ![](./imgs/STRAIGHT_CONV_RESULT.png) # ### Quantitative Analysis of CNN Segmentation # These metrics however come from the **attempt** at reproducing these result. The reproductions labeled the majority of pixels as background, and I would image that this is what could have caused the flatline that I saw in my loss function above. # # $$ # \begin{bmatrix} # label & jaccard & dice & false\_negative & false\_positive \\ # bg & 0.634772 & 0.776588 & 0.360939 & 0.010464 \\ # gm & 0.213391 & 0.351727 & 0.044455 & 0.784469 \\ # wm & 0.000648 & 0.001295 & 0.999218 & 0.996244 \\ # csf & 0.016420 & 0.032310 & 0.976966 & 0.945908 \\ # \end{bmatrix} # $$ # # # # # Second Attempt --> sklearn RF classifier # ## Feature Engineering # * single pixel t1 intensities # * single pixel edge image intensities # * scalar for the **average** of a radius 4 region of intensities # * scalar for the **average** of a radius 4 region of edge image intensities # # NOTE: I wanted to do neighborhood extraction, but it wasn't going to work with my time management of other courses. # # # ## Expected Shapes # #### x_train.shape = (n_samples, 4) # #### y_train.shape = (n_samples, 1) --> These are not one hot encoded # ## Quantitative Analysis # # # # # #### Confusion Matrix (single image) # ![](./imgs/rf_confusion_matrix.png) # # # # # #### Classification Report (single image) # ![](./imgs/random_forest_clf_report.png) # # # # # #### Metrics on All TEST Data # $ # \begin{bmatrix} # label & jaccard & dice & false\_negative & false\_positive\\ # 0 & 0.877616 & 0.934522 & 0.042732 & 0.086233 \\ # 1 & 0.437436 & 0.592840 & 0.436986 & 0.368031 \\ # 2 & 0.567557 & 0.694469 & 0.275988 & 0.295521 \\ # 3 & 0.162507 & 0.275819 & 0.808682 & 0.464798 \\ # \end{bmatrix} # $ # # # # Plot of the above metrics: # # ![](./imgs/all-test-data-metrics.png) # # ### Interpretation of Quantitative results # The CSF is commonly being confused for the background of the image. This could be improved by providing a neighborhood feature to give insight about csf location within the image. I could also do a binary classification on the background first and then do categorical classification on CSF, GM, WM. # # ## Qualitative Analysis # # It's not bad. It isn't the quality of segmentation that I would want, but for just a random forest model on the voxel level it performs suprisingly well. # # # # # ![](./imgs/qualitative-analysis-rf.png) # # Future Considerations # If this problem were to be continued further I would do the following things: # * Histogram normalization across the entire dataset --> this would just be another preprocessing step # * Fix the Deep Learning model loading issue. --> this would open doors to more complex Deep Learning models # * Neighboorhood level feature extraction --> this would provide more spatial context to the traditional ML models # * Hierarchical learning --> this could help fix my CSF misclassification by first classifying the background, which has both high precision and recall and then moving on to the CSF as a secondary segmentation # for auto-reloading external modules # see http://stackoverflow.com/questions/1907993/autoreload-of-modules-in-ipython # %load_ext autoreload # %autoreload 2 # + import os import itk import glob import sys from itkwidgets import view import numpy as np from ipywidgets import interact, fixed from ipywidgets import interactive import ipywidgets as widgets import SimpleITK as sitk import pandas as pd from matplotlib import pyplot as plt # Place utility functions in the HW8functions.py file as you complete them # you may want to put them inline the in the notebook for initial testing # but only your HW8functions file will be used for final validation. from HW8functions import Subject, GLB_DATA_DIR, estimate_gray_white_csf, HCPData, ModeKeys, Evaluator, OverlapMeasures current_subject = Subject('0100') t1_fn = current_subject.get_t1_filename() t1_im = sitk.ReadImage(t1_fn, sitk.sitkFloat32) t2_fn = current_subject.get_t2_filename() t2_im = sitk.ReadImage(t1_fn, sitk.sitkFloat32) gray_matter_im, white_matter_im, csf_im = estimate_gray_white_csf(t1_im, t2_im) # sitk.WriteImage(t1_im,"/tmp/t1.nii.gz") # sitk.WriteImage(gray_matter_im,"/tmp/gm.seg.nii.gz") # sitk.WriteImage(white_matter_im,"/tmp/wm.seg.nii.gz") # sitk.WriteImage(csf_im,"/tmp/csf.seg.nii.gz") # sitk.WriteImage(((csf_im*3)+(white_matter_im*2)+(gray_matter_im*1)), "/tmp/pred.seg.nii.gz") # - dataset = HCPData() print("HCPData Overview:") print("{0} total subjects".format(len(dataset.get_subjects()))) print("{0} hidden test subjects".format(len(dataset.get_subjects(ModeKeys.HIDDEN_TEST)))) print("{0} test subjects".format(len(dataset.get_subjects(ModeKeys.TEST)))) print("{0} validation subjects".format(len(dataset.get_subjects(ModeKeys.VAL)))) print("{0} training subjects".format(len(dataset.get_subjects(ModeKeys.TRAIN)))) Evaluator.display_with_overlay(image=t1_im,segs=[gray_matter_im, white_matter_im, csf_im], slice_number=100, segmentation_number=1) lbl_mask = current_subject.get_label_mask() background = ((gray_matter_im + white_matter_im + csf_im) < 1) preds = [background, gray_matter_im, white_matter_im, csf_im] ground_truth = [lbl_mask==0, lbl_mask==1,lbl_mask==2,lbl_mask==3] Evaluator.get_segmentation_stats(ground_truth_segmentations=ground_truth, predicted_segmentations=preds, graph=True, latex=True) # ## Compute Average of all metrics across all subjects subs = dataset.get_subjects(ModeKeys.TEST) l = len(subs) avg_arr = np.zeros((4, 4)) for ind, sub in enumerate(subs): print("{0}%".format((ind/l)*100)) lbl_mask = sub.get_label_mask() gray_matter_im, white_matter_im, csf_im = estimate_gray_white_csf(sub.get_t1_image(), sub.get_t2_image()) background = ((gray_matter_im + white_matter_im + csf_im) < 1) preds = [background, gray_matter_im, white_matter_im, csf_im] ground_truth = [lbl_mask==0, lbl_mask==1,lbl_mask==2,lbl_mask==3] avg_arr += Evaluator.get_segmentation_stats(ground_truth_segmentations=ground_truth, predicted_segmentations=preds, graph=False, latex=False).values avg_arr = avg_arr / len(subs) overlap_results_df = pd.DataFrame(data=avg_arr, index=list(range(4)), columns=[name for name, _ in OverlapMeasures.__members__.items()]) overlap_results_df.plot(kind='bar').legend(bbox_to_anchor=(1.6, 0.9)) plt.show() overlap_results_df
hw/hw08-abpwrs/HW8.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import pandas as pd import numpy as np import numpy.random as nr # # Data Preparation # + # load example data raw = pd.read_csv("example.csv", index_col=0) # some column and index shuffleing raw["ENTITY"] = raw.index raw.index = raw.index.map(str) +"_"+ raw["TIME"].map(str) raw.rename(columns={"TIME.1":"TIME"}) del raw.index.name # + raw1 = raw[raw.DATASET == 1][::] raw2 = raw[raw.DATASET == 2][::] raw3 = raw[raw.DATASET == 3][::] datasets = [raw1, raw2, raw3] # normally distributed features means1 = [10, 12, 16] stds1 = [3, 3, 2] means2 = [10, 10, 10] stds2 = [1, 1, 1] means3 = [10, 20, 30] stds3 = [3, 3, 2] means4 = [20, 21, 20] stds4 = [4, 5, 4] # chi square features degs = [2,3,4] # categorical features vals1 = ["a", "b", "c"] probs1 = [[0.2, 0.7, 0.1], [0.3, 0.3, 0.4], [0.8, 0.1, 0.1]] vals2 = [1, 2, 3] vals3 = [1, 2] # batch effects batches1 = [0, 0, 5] b_means1 = [20, 20, 20] b_stds1 = [2, 1, 1] batches2 = [0, 0, 2] b_means2 = [20, 20, 20] b_stds2 = [1, 1, 1] #longitudinal long_m = [[10, 12, 15, 17, 19, 22, 25, 27, 29, 33], [12, 12, 16, 19, 23, 19, 28, 30, 31, 33], [10, 12, 14, 16, 18, 20, 22, 24, 26, 28]] long_s = [[2.1, 1.3, 1, 1.5, 1.7, 2, 2.5, 3, 3, 3.3], [2.2, 1.3, 1, 1.5, 1.7, 2, 2.5, 3, 3, 3.3], [2.1, 1.3, 1, 1.5, 1.7, 2, 2.5, 3, 3, 3.3]] # - # # Generate normally distributed features # + def fill_nd_feats(feat, datasets, means, stds): for df, mean, std in zip(datasets, means, stds): df[feat] = nr.normal(mean, std, size=len(df)) fill_nd_feats("NDSIG1", datasets, means1, stds1) fill_nd_feats("NDSIG2", datasets, means3, stds3) fill_nd_feats("NDNON1", datasets, means2, stds2) fill_nd_feats("NDNON2", datasets, means4, stds4) # - # # Chi² feats # + def fill_chi_feats(feat, datasets, degs): for df, deg in zip(datasets, degs): df[feat] = nr.chisquare(deg, size=len(df)) fill_chi_feats("CHIFEAT", datasets, degs) # - # # Categorical feats # + def fill_cat_feats(feat, datasets, vals, probs=None): if probs: for df, prob in zip(datasets, probs): df[feat] = nr.choice(vals, p=prob, size=len(df)) else: for df in datasets: df[feat] = nr.choice(vals, size=len(df)) fill_cat_feats("CATSIG1", datasets, vals1, probs1) fill_cat_feats("CATNON2", datasets, vals2) fill_cat_feats("CATDICHO", datasets, vals3) # - # # Batch # + def fill_batch_feats(feat, datasets, means, stds, batches): for df, mean, std, batch in zip(datasets, means, stds, batches): df[feat] = nr.normal(mean, std, size=len(df)) # add batch effect df[feat] = df[feat] + batch fill_batch_feats("BATCH1", datasets, b_means1, b_stds1, batches1) fill_batch_feats("BATCH2", datasets, b_means2, b_stds2, batches2) # - # # Longitudinal # + def fill_long_feat(feat, datasets, time, means, stds): times = datasets[0][time].unique() for df, mean, std in zip(datasets, means, stds): for t, m, s in zip(times, mean, std): inds = df[df[time]==t].index n_vals = nr.normal(m, s, size=len(inds)) df.loc[inds, feat] = n_vals fill_long_feat("LONG1", datasets, "TIME", long_m, long_s) # - # # NAN Features fill_nd_feats("NAN1", datasets, means1, stds1) datasets[0]["NAN1"] = np.nan # # Combine data = pd.concat(datasets) data pd.concat(datasets).to_csv("simulated.csv")
data/simulate_data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ## Notebook for producing vOTU table from raw sequencing reads as in "Minnesota peat viromes reveal terrestrial and aquatic niche partitioning for local and global viral populations" # <NAME> # # ## QC reads with trimmomatic # # - Trim the reads with trimmomatic, following Roux et al., 2017 # - minimum base quality threshold of 30 evaluated on sliding windows of 4 bases, and minimum read length of 50 # - As a rule of thumb newer libraries will use TruSeq3, but this really depends on your service provider. # - http://www.usadellab.org/cms/?page=trimmomatic # + # load modules module load java module load trimmomatic # use trimmomatic to trim adapters, make sure you have the correct adapterfile trimmomatic PE -threads 8 -phred33 $1 ${1%%_1*}_2.fastq.gz \ ../trimmed/${1%%_1*}_1_trimmed.fq.gz unpaired/${1%%_1*}_1_Unpaired.fq.gz \ ../trimmed/${1%%_1*}_2_trimmed.fq.gz unpaired/${1%%_1*}_2_Unpaired.fq.gz \ ILLUMINACLIP:/adapters/TruSeq3-PE.fa:2:30:10 \ SLIDINGWINDOW:4:30 MINLEN:50 # - # ## Remove PhiX174 with bbduk # - Phix174 is a phage sequence that is used to aid in sequencing. This needs to be removed from our sequencing data # - https://jgi.doe.gov/data-and-tools/bbtools/bb-tools-user-guide/bbduk-guide/ # + # load module module load java module load bbmap # use bbduk to remove phix contamination bbduk.sh in1=$1 in2=${1%%_1*}_2_trimmed.fq.gz \ out1=../remove_phix/${1%%_1*}_1_trimmed_bbduk.fq.gz out2=../remove_phix/${1%%_1*}_2_trimmed_bbduk.fq.gz \ ref=/bbduk/phix_genome.fa k=31 \ hdist=1 stats=../remove_phix/${1%%}_stats.txt # - # ## Assembly with MEGAHIT # - Assemble viromes following Roux et al., 2017: # # - Assemble total soil metagenomes following Sczyra et al., 2017 and Vollmer et al., 2017 # # - https://github.com/voutcn/megahit # + # MEGAHIT for single sample assembly megahit -1 $1 -2 ${1%%1_R1*}1_R2_trimmed_bbduk.fq.gz -o ../assemblies_persample/${1%%_R1*} \ --out-prefix ${1%%_R1*} --min-contig-len 10000 --continue # Co-assemly viromes READ1=*_R1_* READ2=*_R2_* READ1s=`ls $READ1 | python -c 'import sys; print ",".join([x.strip() for x in sys.stdin.readlines()])'` READ2s=`ls $READ2 | python -c 'import sys; print ",".join([x.strip() for x in sys.stdin.readlines()])'` megahit -1 ${READ1s} -2 ${READ2s} -o co_assembly_virome -t 64 -m 480e9 --mem-flag=2 \ --k-min 27 --out-prefix co_assembly_virome \ --min-contig-len 10000 --presets meta-large # total soil metagenomes megahit -1 $1 -2 ${1%%1_R1*}1_R2_trimmed_bbduk.fq.gz -o ../bact_assemblies_persample/${1%%_R1*} \ --out-prefix ${1%%_R1*} --min-contig-len 2000 # - # ## DeepVirfinder # - Only contigs that have a virFinder score => 0.9 and p <0.05 Gregory et al., 2019 # - https://github.com/jessieren/DeepVirFinder # + # run dvf python dvf.py -i $1 -l 10000 -o ${1%%.fna*}_virfinder -c 8 \ # use custom script to parse dvf data python parse_DVF.py $f/*.txt ${f%%_virfinder*}_seq_names.txt # Pull those sequences from the fasta files for f in *.fa; do awk -F'>' 'NR==FNR{ids[$0]; next} NF>1{f=($2 in ids)} f' \ ../virfinder/${f%%.fa*}_seq_names.txt $f \ > ../virfinder/${f%%contigs.fa*}virfinder.fa done # + """parse_dvf.py, <NAME>, September 2019 This script filters the deepVirfinder output to only keep entries with a virfinder score > 0.9 and a pvalue < 0.05""" # #! /usr/bin/env python # imports import pandas as pd import numpy as np import re import sys # open the coverage table df = pd.read_csv(sys.argv[1] ,sep='\t') df = df[df.score > 0.899] df = df[df.pvalue < 0.05] print(len(df)) df = df.name df.to_csv(sys.argv[2], sep='\t',index=False) # - # pull the sequences that have high enough score from the fasta file with all contigs for f in *.fna; do awk -F'>' 'NR==FNR{ids[$0]; next} NF>1{f=($2 in ids)} f' \ ${f%%.fna*}_seq_names.txt $f > ${f%%contigs.fna*}virfinder.fa done # ## VirSorter # - Use Virsorter as well to predict viral sequences # - Take only virsorter sequences from category 1,2,4 and 5 # - https://github.com/simroux/VirSorter # run virsorter wrapper_phage_contigs_sorter_iPlant.pl -f $f -ncpu 8 \ --data-dir virsorter-data/ -db 1 --wdir ${f%%.contigs.fa*}_virsorter --virome # Concatenate all virSorter output in said categories for f in *_virsorter; do # cat $f/Pr*/VIRSorter*cat-[1245].fasta >> $f/${f%%_virsorter*}_virsort_viralseqs.fa done # # Concatenate, rename and sort viral sequences with bbmap # - concatenate findings from Virsorter and Virfinder # - rename those sequences according to the dataset they came from # - Sort on lenght so we can cluster after # - https://jgi.doe.gov/data-and-tools/bbtools/bb-tools-user-guide/bbmap-guide/ # + # concatenate # cat *_virsorter_seqs.fa *_virfinder.fa >> *_all_found_viral_seqs.fa # rename (with bbmap rename.sh) rename.sh in=*_all_found_viral_seqs.fa out=*_all_found_viral_rename.fa prefix=SPRUCE_virome_ # sort on length (with bbmap sortbyname.sh) sortbyname.sh in=*_all_found_viral_rename.fa out=all_viral_seqs.sorted.fa length descending # - # # Clustering found sequences with CD-hit # - Clustering sequences at 95% ANI over 85% of the sequence, relative to the shorter sequence, following Roux et al., 2019 # - https://github.com/weizhongli/cdhit/wiki/2.-Installation # # + # use CD-hit to cluster found viral sequences cd-hit-est -i all_viral_seqs.sorted.fa -o all_viral_seqs.sorted.cluster.fa \ -c 0.95 -aS 0.85 -M 7000 -T 10 # use CD-hit to cluster those viral sequences with PIGEON cd-hit-est-2d -i all_viral_seqs.sorted.cluster.fa \ -i2 PIGEONv1.0.sorted.fa \ -o unique_viral_seqs.fa \ -c 0.95 -aS 0.85 -M 20000 -T 10 # make one database from PIGEON and the newly found unique viral sequences # cat PIGEONv1.0.sorted.fa unique_viral_seqs.fa >> PIGEON_and_new_SPRUCE.fa # - # # Mapping back with BBMAP and keep only contigs that are > 75% covered in lenght # - Use bbmap to map back clean reads to PIGEON database to see what viruses can be recovered via read mapping # - Do this at 90% nucleotide identity, following Roux et al., 2017 # - Do this at 75% of the contig lenght, following Roux et al., 2017 # - https://jgi.doe.gov/data-and-tools/bbtools/bb-tools-user-guide/bbmap-guide/ # + # produce reference mapping file bbmap.sh ref=PIGEON_and_new_SPRUCE.fa # map reads to the reference file (paired end reads) bbmap.sh in1=$f in2=${f%%_R1_*}_R2_bbduk.fq.gz \ out=${f%%_R1_*}.sam \ minid=0.90 threads=25 # make bam files from sam files samtools view -F 4 -bS file.sam | samtools sort > file_sortedIndexed.bam # index the bam file samtools index ${f%%R1_*}_sortedIndexed.bam # - # # Calculate coverage length using bedtools # - calculate for each bam file the coverage length # - bga makes sure that also regions with 0 coverage are reported # - max reports all reads with depth >10 as 10. Is faster. # - https://bedtools.readthedocs.io/en/latest/ # # + # run bedtools bedtools genomecov -ibam $f -bga -max 10 > ${f%.bam*}.tsv # use custom python script to filter out contigs that aren't covered > 75% for f in $(ls *.tsv); do python parse_bedtools.py $f ${f%%.tsv*}_under75.tsv ; done; # for each sample make a list of names that are not 75% covered for f in $(ls *75.tsv); do cat $f | cut -d$'\t' -f2 > ${f%%.tsv*}.txt ; done; # coverage table needs to be filtered based on the contigs that dont have 75% coverage for each sample # so make a csv with [header]=filename, thus will correspond to a name in the covtab for filename in $(ls *.txt) do sed "1s/^/${filename} \n/" ${filename} > $filename.new echo Done ${filename} done # move all these files into folders # mkdir under_75_csv # mv *75.tsv under_75_csv # mkdir under_75_txt # mv *75.txt under_75_txt # mkdir under_75_name_added # mv *.new under_75_name_added # make one giant file that contains what contig in which sample isn't covered 75% paste -d "|" *txt.new > ../SPRUCE_contigs_under75.csv # + # #! /usr/bin/env python ''' python parse_bedtools.py, <NAME>, September 2019 bedtools genomecov outputs a tsv that we will manipulate with pandas to obtain the average coverage per contig. If its more than 75%, we will discard the contig. ''' # imports from __future__ import division import sys import pandas as pd # open the file to read with pandas df = pd.read_csv(sys.argv[1],sep='\t', header=None) # add column names so we know what we are looking at df.columns = ['sequence', 'start_pos', 'stop_pos' , 'coverage'] # Add a column with the number of nucleotides that share the same coverage df['num_of_nucl'] = df['stop_pos'] - df['start_pos'] # for each sequence, add a extra column witht the sequences total length. Calculating percentages # becomes easier this way df['total_len_seq'] = df.groupby(['sequence'],sort=False)['stop_pos'].transform(max) # calculate percentage coverage for each mapping piece to the contig df['percentage_of_seq'] = df['num_of_nucl'] / df['total_len_seq'] # make a new df where only values with coverage not 0 are in df_no0 = df.loc[df['coverage'] != 0] # add up all the percentages for sequences with the same name # reset index to keep column names df_percentages = df_no0.groupby(['sequence'])['percentage_of_seq'].agg('sum').reset_index() # make it actual percentages by multiplying with 100 df_percentages['percentage_of_seq'] = df_percentages['percentage_of_seq']*100 # Select the cases where the percentage coverage is < 74.99 percentage_under_75 = df_percentages['percentage_of_seq'] < 74.99 # keep cases where perc coverage < 75, to new csv df_percentages[percentage_under_75].to_csv(sys.argv[2], sep='\t') # - # ## Use Bamm to make a coverage table from all bam files # - http://ecogenomics.github.io/BamM/ # Use bamm to create coverage table bamm parse -c output_file.tsv -b *.bam -m 'tpmean' # ## Filter the coverage table based on the 75% lenght coverage parameter # - This is done with custom python script # - Input is the coverage table and the SPRUCE_contigs_under75.csv file # + # #! /usr/bin/env python # imports import pandas as pd import numpy as np import re import sys # open the coverage table df = pd.read_csv('coverage_table.tsv',sep='\t') # open the under 75% coverage list per sample df_under_75= pd.read_csv('under_75_per_sample.csv',sep='|') # make the headers readable, cut from the _S# part df.columns = df.columns.str.split('_L006').str[0] + '' df_under_75.columns = df_under_75.columns.str.split('_L006').str[0] + '' #remove viral contigs with all 0s from the coverage file df_cov = remove_all_zeros(df) # check the lenght of the dataframe and the number of non zero values in each print 'before', len(df_cov), df_cov.astype(bool).sum(axis=0) #Do the function that checks each column(sample) for a coverage under 75%. for col in df_under_75.columns: df_cov[col] = df_cov[['#contig', col]].apply(lambda x: check_similarity(x['#contig'], df_under_75[col].values[1:], x[col]),axis=1) #after removing these under 75% coverage ones, remove the columns with all 0 again. df_cov = remove_all_zeros(df_cov) # check the len of df and num of viral contigs with > 75% coverage for each sample print 'after', len(df_cov), df_cov.astype(bool).sum(axis=0) #print df_cov df_cov.to_csv('filtered_coverage_table.csv', sep='|') def remove_all_zeros(df): # get a list of columns that could contain zero all_columns = list(df.columns)[2:] # check if all columns contain zero df["all_zeros"] = (df[all_columns] == 0).all(axis=1) # remove all that have only zeros df = df.loc[df["all_zeros"] == False] # remove all zeros column df.drop(['all_zeros'], axis=1, inplace=True) return df def check_similarity(contig_name, contig_names_to_check, curent_value): if contig_name in contig_names_to_check: return 0 else: return curent_value # -
200420_python_notebook_processing_SPRUCE_data.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab.research.google.com/github/stories2/Kangnam_ML/blob/main/HW5.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + colab={"base_uri": "https://localhost:8080/"} id="LFh8x9yEGdfq" outputId="023a9bff-70ee-43d9-fe8f-aaa8714779e9" # !pip install mglearn # + id="ytB2CGWnHK_-" from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import train_test_split import numpy as np import matplotlib.pyplot as plt import mglearn # %matplotlib inline # + id="fyZj276NHy1F" x, y = mglearn.datasets.make_wave(n_samples=50) # + colab={"base_uri": "https://localhost:8080/", "height": 283} id="u8Vb19KBH55m" outputId="9646fdcf-7fcb-4959-8ba8-6e96827cd348" plt.plot(x, y, 'o') plt.xlabel('X') plt.ylabel('y') plt.ylim(-3, 3) plt.show() # + id="pnB0eHalIe2V" train_input, test_input, train_target, test_target = train_test_split(x, y, train_size=0.7, random_state=1004) # + colab={"base_uri": "https://localhost:8080/"} id="ZZI9d5nfIoG4" outputId="ead87865-4fc6-4a3d-9835-9aee661c8f30" train_input[:2], train_target[:2] # + colab={"base_uri": "https://localhost:8080/"} id="CylghwhzIxkL" outputId="4d0919a1-8e86-429a-fb80-4fce816eddb0" knr = KNeighborsRegressor(n_jobs=3) knr.fit(train_input, train_target) # + colab={"base_uri": "https://localhost:8080/", "height": 281} id="Ex2mGFMrJ-1_" outputId="b36f0d1c-af08-4cbc-dd92-bb7133724720" xs = np.linspace(-3, 3, 1000) plt.plot(xs, knr.predict(xs.reshape(-1,1))) plt.plot(train_input,train_target, '^') plt.plot(test_input, test_target, 'v') plt.title("K={}. train score:{:.2f}, test score:{:.2f}".format( knr.n_neighbors, knr.score(train_input, train_target), knr.score(test_input, test_target))) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="YOlQPMByKSgI" outputId="3f834ca3-a954-4ab0-cf6f-ea73e0097e54" knr.predict(train_input[:10]), train_target[:10] # + id="nkoR_ZSaMBgs" # k 가 왜 높게 나왔을까 # + id="UMeIrJHltL6L" xs = np.linspace(-3, 3, 1000) xs_reshaped = xs.reshape(-1,1) # + id="9OgGO8uFtUX3" def neighborRegression(n, train_input, train_target, test_input, test_target, wave): knr = KNeighborsRegressor(n_jobs=3, n_neighbors=n) knr.fit(train_input, train_target) return (n, knr.score(train_input, train_target), knr.score(test_input, test_target), knr.predict(wave)) # + id="lLW33UAhC3uc" result = [] # + colab={"base_uri": "https://localhost:8080/", "height": 1000} id="ji8Vzx7GtFUG" outputId="3dfaa78f-4b3a-4323-dc00-17c43d08cc63" f, axes = plt.subplots(ncols=1, nrows=5, sharex=True, sharey=True) f.set_size_inches((30, 30)) n_neighbor_cnt = 0 for ax in axes: n_neighbor = n_neighbor_cnt * 2 + 1 _, train_score, test_score, wave_predict = neighborRegression(n_neighbor, train_input, train_target, test_input, test_target, xs_reshaped) # ax.plot([1, 2, 3], [1, 2, 3]) ax.plot(xs, wave_predict) ax.plot(train_input,train_target, '^') ax.plot(test_input, test_target, 'v') ax.set_title("K={}. train score:{:.2f}, test score:{:.2f}".format(n_neighbor, train_score, test_score)) ax.set(adjustable='box', aspect='equal') result.append((n_neighbor, train_score, test_score)) n_neighbor_cnt += 1 plt.subplots_adjust(wspace = 0.3, hspace = 0.3) plt.show() # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="eCR9EI93t5dM" outputId="58b704c8-10a7-435f-c594-1b68233e372d" plt.plot([val[0] for val in result], [val[1] for val in result]) plt.plot([val[0] for val in result], [val[2] for val in result]) plt.show() # + [markdown] id="qYdPqycgEP18" # K가 5일 때 가장 BEST # # 학습 데이터의 점수 결과와 테스트 데이터의 점수 결과가 각각 `0.78`, `0.71` 로 크게 차이 나지 않으면서 테스트 데이터의 점숫값이 1, 3, 5, 7, 9 중에서 가장 높습니다. # # 이런 결과가 나온 이유는 주변 이웃을 이용해 예측할 때 n_neighbors 값이 너무 작은 값을 가지면 가장 근접한 이웃들로만 계산해 과적합이 되어 테스트 점수가 낮고, 너무 높은 값이면 멀리 떨어진 이웃을 이용해 계산하므로 결과가 좋지 못한 문제가 있기 때문입니다.
HW5.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: '' # name: '' # --- # # Compare Compute Time for Tensor Density MAX_EPOCH = 5 RANK = 2 import scipy.io as spio import numpy as np from tqdm import tqdm from pyCP_APR import CP_APR # ## RUN CP-APR Numpy Sparse sparse_tensor_times = list() # + cp_apr = CP_APR(n_iters=MAX_EPOCH, verbose=0, method='numpy') for ii in tqdm(range(20)): X = np.ones((20, 20, 20)) X[:,list(range(0,ii))] = 0 np.random.shuffle(X) coords = np.argwhere(X != 0) values = X[np.nonzero(X)] _ = cp_apr.fit(coords=coords, values=values, rank=RANK, method='numpy') sparse_tensor_times.append(cp_apr.model.exec_time) # - # ## Run CP-APR PyTorch CPU sparse_pytorch_cpu_times = list() # + cp_apr = CP_APR(n_iters=MAX_EPOCH, verbose=0, method='torch', device='cpu') for ii in tqdm(range(20)): X = np.ones((20, 20, 20)) X[:,list(range(0,ii))] = 0 np.random.shuffle(X) coords = np.argwhere(X != 0) values = X[np.nonzero(X)] _ = cp_apr.fit(coords=coords, values=values, rank=RANK) sparse_pytorch_cpu_times.append(cp_apr.model.exec_time) # - # ## PyTorch GPU sparse_pytorch_gpu_times = list() # + cp_apr = CP_APR(n_iters=MAX_EPOCH, verbose=0, method='torch', device='gpu') for ii in tqdm(range(20)): X = np.ones((20, 20, 20)) X[:,list(range(0,ii))] = 0 np.random.shuffle(X) coords = np.argwhere(X != 0) values = X[np.nonzero(X)] _ = cp_apr.fit(coords=coords, values=values, rank=RANK) sparse_pytorch_gpu_times.append(cp_apr.model.exec_time) # - # # Plot # + # %matplotlib inline import matplotlib.pyplot as plt x = range(0, 20) plt.figure(figsize=(15,5), dpi=100) plt.plot(x, sparse_tensor_times, marker='o', label='Numpy - Sparse') plt.plot(x, sparse_pytorch_cpu_times, marker='o', label='PyTorch - CPU') plt.plot(x, sparse_pytorch_gpu_times, marker='o', label='PyTorch - GPU') plt.xticks(np.arange(min(x), max(x)+1, 1.0)) plt.xlabel('Sparsity', fontsize=18, labelpad=14) plt.ylabel('Time (seconds)', fontsize=18, labelpad=14) plt.legend(loc="upper right", prop={'size': 15}) plt.grid(True) plt.show() # -
examples/CP-APR_Compare_Density.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python [conda root] # language: python # name: conda-root-py # --- # # # Python graphics: Matplotlib fundamentals # # We illustrate three approaches to graphing data with Python's Matplotlib package: # # * [Approach 1](#Approach-1:--Apply-plot-methods-to-dataframes): Apply a `plot()` method to a dataframe # * [Approach 2](#Approach-2:--plt.plot): Use the `plot(x,y)` function from `matplotlib.pyplot` # * [Approach 3](#Approach-3:--Create-figure-objects-and-apply-methods): Create a figure object and apply methods to it # # The last one is the least intuitive but also the most useful. We work up to it gradually. This [book chapter](https://davebackus.gitbooks.io/test/content/graphs1.html) covers the same material with more words and fewer pictures. # ## Reminders # # * **Packages**: collections of tools that we access with `import` statements # * **Pandas**: Python's data package # * **Objects** and **methods**: we apply the method `justdoit` to the object `x` with `x.justdoit` # * **Dataframe**: a spreadsheet-like data structure # * **Series**: a single variable # * **Jupyter**: an environment for combining code with text and graphics # ## Preliminaries # # ### Jupyter # # Look around, what do you see? Check out the **menubar** at the top: File, Edit, etc. Also the **toolbar** below it. Click on Help -> User Interface Tour for a tour of the landscape. # # The **cells** below come in two forms. Those labeled Code (see the menu in the toolbar) are Python code. Those labeled Markdown are text. # # ### Markdown # # Simplified version of **html** (the language used to construct basic websites). Best way to learn about its rules is by clicking on a cell that contains text and try to imitate what you see. (More about it later and in the book.) # ### Import packages # # + # make plots show up in notebook # %matplotlib inline import pandas as pd # data package import matplotlib.pyplot as plt # pyplot module # - # **Comment.** When you run the code cell above, its output appears below it. # # **Exercise.** Enter `pd.read_csv?` in the empty cell below. Run the cell (Cell at the top, or shift-enter). Do you see the documentation? This is the Jupyter version of help in Spyder's IPython console. # ### Create dataframes to play with # # * US GDP and consumption # * World Bank GDP per capita for several countries # * Fama-French equity returns # ## Data input # # Last time we saw how to read # # * internet files using links # * files on your computer # * data sets through APIs # # For the first two we used `pandas` methods, `read_csv()` and `read_excel()`. # # APIs are "application program interfaces". # # The API is the set of rules for accessing the data. People have written easy-to-use code to access the APIs. # # The Pandas developers have created what they call a set of [Remote Data Access tools](https://pandas-datareader.readthedocs.io/en/latest/remote_data.html) and have put them into a package called `pandas_datareader`. # # ### FRED. # # The St Louis Fed has put together a large collection of time series data that they refer to as [FRED](https://research.stlouisfed.org/fred2/): Federal Reserve Economic Data. They started with the US, but now include data for many countries. # # The Pandas docs describe how to access FRED. Here's an example that reads in quarterly data for US real GDP and real consumption. # # * The variables `start` and `end` contain dates in (year, month, day) format using `datetime.datetime`. # * The variable `codes` -- not to be confused with "code" -- consists of FRED variable codes. Go to [FRED](https://research.stlouisfed.org/fred2/), use the search box to find the series you want, and look for the variable code at the end of the url in your browser. # + from pandas_datareader import data import datetime # package to handle dates start = datetime.datetime(2003, 1, 1) # start date -- year/month/day end = datetime.datetime(2013, 1, 1) # end date codes = ['GDPCA', 'PCECCA'] # real GDP, real consumption (from FRED website) us = data.DataReader(codes, 'fred', start, end) us.columns = ['gdp', 'pce'] #us.set_index = list(range(2003, 2014)) (we don't need it now) print(us.head(3)) # - # ### World Bank. # # The World Bank's [databank](http://data.worldbank.org/) covers economic and social statistics for most countries in the world. Variables include GDP, population, education, and infrastructure. Here's an example: # + from pandas_datareader import wb iso_codes = ['BRA', 'CHN', 'FRA', 'IND', 'JPN', 'MEX', 'USA'] var = ['NY.GDP.PCAP.PP.KD'] year = 2013 wbdf = wb.download(indicator=var, country=iso_codes, start=year, end=year) print(wbdf) # + # Change the index for iso codes wbdf.index = iso_codes print(wbdf) # + # Add country variable country = ['Brazil', 'China', 'France', 'India', 'Japan', 'Mexico', 'United States'] wbdf['country'] = country # Rename the variables wbdf.columns = ['gdppc', 'country'] # set the display precision in terms of decimal places pd.set_option('precision', 2) wbdf['gdppc'] = wbdf['gdppc']/1000 print(wbdf) # - # **Comment.** In the previous cell, we used the `print()` function to produce output. Here we just put the name of the dataframe. The latter displays the dataframe -- and formats it nicely -- **if it's the last statement in the cell**. # ### Fama-French. # # * <NAME>ama and Ken French post lots of data on equity returns on [Ken French’s website](http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html). # * The data are zipped text files, which we can easily read into Excel OR # * use the Pandas tool which is better. ff = data.DataReader('F-F_Research_Data_factors', 'famafrench') ff # What is this object? type(ff) # Learn about the structure ff.keys() ff['DESCR'] ff = ff[1] type(ff) ff ff.columns = ['xsm', 'smb', 'hml', 'rf'] ff['rm'] = ff['xsm'] + ff['rf'] ff = ff[['rm', 'rf']] # extract rm (market) and rf (riskfree) ff.head(5) # --------------------------------------------- # # ## Approach 1: Apply plot methods to dataframes # # The simplest way to produce graphics from a dataframe is to apply a plot method to it. # # We see that a number of things are preset for us: # # * Data. By default the data consists of the whole dataframe. # * Chart type. We have options for lines, bars, or other things, but the default is line # * `x` and `y` variables. By default, the `x` variable is the dataframe's index and the `y` variables are the columns of the dataframe -- all of them that can be plotted (e.g. columns with a numeric dtype). # # We can change all of these things, but that's always a good starting point. # ### US GDP and consumption # try this with US real GDP, real consumption us.plot() # do GDP alone us['gdp'].plot() us.plot(y="gdp") # bar chart us.plot(kind='bar') # scatter plot # we need to be explicit about the x and y variables: x = 'gdp', y = 'pce' us.plot.scatter('gdp', 'pce') us.plot('gdp', 'pce', kind='scatter') # **Exercise.** Add each of these arguments, one at a time, to `us.plot()`: # # * `kind='area'` # * `subplots=True` # * `sharey=True` # * `figsize=(3,6)` # * `ylim=(0,16000)` # # What do they do? # + # us.plot? # - us.plot(kind='area') # fill the area below us.plot(subplots=True) # make separate subplots for the variables in the dataframe us.plot(subplots=True, sharey = True) # make the y axis the same (transparency!) us.plot(figsize = (10, 2)) # first arg: width, second: height (inches) us.plot(ylim = (0, 16000)) # change the range of the y axis # ---------------------------------------- # ## Approach 2: `plt.plot(x, y)` # # Next up: the popular `plot(x,y)` function from the pyplot module of Matplotlib. We never use this and will go over it at high speed -- or perhaps not at all. # # This is a more explicit version of `Matplotlib` graphics in which we specify the `x` and `y` variables directly. plt.plot(us.index, us['gdp']) # try plt. + tab completion -- a lot of options # we can do two lines together plt.plot(us.index, us['gdp']) plt.plot(us.index, us['pce']) # + # we can also add things to plots plt.plot(us.index, us['gdp']) plt.plot(us.index, us['pce']) plt.title('US GDP', fontsize=14, loc='left') # add title plt.ylabel('Billions of 2009 USD') # y axis label plt.xlabel('Year') # y axis label plt.tick_params(labelcolor='red') # change tick labels to red #plt.legend(['GDP', 'Consumption'], loc='best') # - # **Comment.** All of these statements must be in the same cell for this to work. # # # **Comment.** This is overkill -- it looks horrible -- but it makes the point that we control everything in the plot. We recommend you do very little of this until you're more comfortable with the basics. # -------------------------------------------------- # ## Approach 3: Create figure objects and apply methods # # This approach is probably the most mysterious, but it's the **best**. # # The idea is to use the `matplotlib.pyplot` function `subplots()`, which creates two objects: # * `fig` : figure object -- blank canvas for creating a figure # * `ax` : axis object -- everything in the figure: axes, labels, legend # # apply methods on these objects to set the various elements of the graph. # # **Create objects.** We'll see this line over and over: fig, ax = plt.subplots() # create fig and ax objects # **Exercise.** What do we have here? What `type` are `fig` and `ax`? print('fig is ', type(fig)) print('ax is ', type(ax)) fig, ax = plt.subplots(2, 1) # (2, 1) -- > (number of rows, number of columns) print('fig is ', type(fig)) print('ax is ', type(ax)) print('ax[0] is ', type(ax[0])) # + # let's try that again, this time with content fig, ax = plt.subplots(figsize=(8, 4)) # add things to ax us.plot(ax=ax, color = ['r', 'g']) #plt.show() # - # **Comment.** Both of these statements must be in the same cell. # Fama-French example fig, ax = plt.subplots() ff.plot(ax=ax, kind='line', # line plot color=['blue', 'magenta'], # line color title='Fama-French market and riskfree returns') # + # Fama-French example fig, ax = plt.subplots(1, 2, figsize=(12, 4)) ff.plot(ax=ax[0], kind='hist', # line plot color=['blue', 'magenta'], # line color alpha=0.65, bins=20, title='Fama-French market and riskfree returns') ff.plot(ax=ax[1], kind='kde', # line plot color=['blue', 'magenta'], # line color title='Fama-French market and riskfree returns', alpha=0.65) fig.tight_layout() # - # ----------------------------------- # ## Quick review of the bidding # # We looked at three ways to use Matplotlib: # # * Approach #1: apply plot method to dataframe # * Approach #2: use `plot(x,y)` function # * Approach #3: create `fig, ax` objects, apply plot methods to them # # Same result, different syntax. This is what each of them looks like applied to US GDP: # # ```python # us['gdp'].plot() # Approach #1 # # plt.plot(us.index, us['gdp']) # Approach #2 # # fig, ax = plt.subplots() # Approach #3 # ax.plot(us.index, us['gdp']) # # # Or # fig, ax = plt.subplots() # Approach #3 # us['gdp'].plot(ax=ax) # # ``` # # Each one produces the same graph. # # Which one should we use? **Use Approach #3.** Really. This is a case where choice is confusing. # # We also suggest you not commit any of this to memory. If you end up using it a lot, you'll remember it. If you don't, it's not worth remembering. # ## Bells and whistles # # ### Adding things to graphs # # Axis methods offer us great flexibility. Here's an example. # + fig, ax = plt.subplots() us.plot(ax=ax) # Apply axis methods ax.set_title('US GDP and Consumption', fontsize=14, loc='left') ax.set_ylabel('Billions of 2013 USD') ax.legend(['Real GDP', 'Consumption'], loc=0) # more descriptive variable names ax.tick_params(labelcolor='purple') # change tick labels to red ax.set_ylim(0) # - # (Your results may differ, but we really enjoyed that.) # **Exercise.** Use the `set_xlabel()` method to add an x-axis label. What would you choose? Or would you prefer to leave it empty? # # **Exercise.** Enter `ax.legend?` to access the documentation for the `legend` method. What options appeal to you? # # **Exercise.** Change the line width to 2 and the line colors to blue and magenta. *Hint:* Use `us.plot?` to get the documentation. # # **Exercise (challenging).** Use the `set_ylim()` method to start the `y` axis at zero. *Hint:* Use `ax.set_ylim?` to get the documentation. # # **Exercise.** Create a line plot for the Fama-French dataframe `ff` that includes both returns. *Bonus points:* Add a title with the `set_title` method. # + fig, ax = plt.subplots() us.plot(ax=ax, lw=2) ax.set_title('US GDP and Consumption', fontsize=14, loc='left') ax.set_ylabel('Billions of 2013 USD') ax.set_xlabel('Date') ax.legend(['Real GDP', 'Consumption'], loc=2) # more descriptive variable names ax.tick_params(labelcolor='green') # change tick labels to green ax.set_ylim(0) # - # ### Multiple subplots # # Same idea, but we create a multidimensional `ax` and apply methods to each component. Here we redo the plots of US GDP and consumption. fig, ax = plt.subplots(nrows=2, ncols=2, sharex=True) print('Object ax has dimension', ax.shape) # + fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(10, 6), sharex=True, sharey=True) ax[0, 0].plot(us.index, us['pce']) ax[0, 1].plot(us.index, us['gdp']) ax[1, 0].plot(us.index, us['gdp']) ax[1, 1].plot(us.index, us['pce']) #plt.setp(ax[1, 0].xaxis.get_majorticklabels(), rotation=40) #plt.setp(ax[1, 1].xaxis.get_majorticklabels(), rotation=40) plt.show() # + # now add some content fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True) us['gdp'].plot(ax=ax[0], color='green') # first plot us['pce'].plot(ax=ax[1], color='red') # second plot # - # ---------------------------------------- # ## Examples # # We conclude with examples that take data from the previous chapter and make better graphs than we did there. # ### World Bank data # # We'll use World Bank data for GDP, GDP per capita, and life expectancy to produce a few graphs and illsutrate some methods we haven't seen yet. # # * Bar charts of GDP and GDP per capita # * Scatter plot (bubble plot) of life expectancy v GDP per capita # + # variable list (GDP, GDP per capita, life expectancy) var = ['NY.GDP.PCAP.PP.KD', 'NY.GDP.MKTP.PP.KD', 'SP.DYN.LE00.IN'] # country list (ISO codes) iso = ['USA', 'FRA', 'JPN', 'CHN', 'IND', 'BRA', 'MEX'] year = 2013 # get data from World Bank df = wb.download(indicator=var, country=iso, start=year, end=year) # massage data df = df.reset_index(level='year', drop=True) df.columns = ['gdppc', 'gdp', 'life'] # rename variables df['pop'] = df['gdp']/df['gdppc'] # population df['gdp'] = df['gdp']/10**12 # convert to trillions df['gdppc'] = df['gdppc']/10**3 # convert to thousands df['order'] = [5, 3, 1, 4, 2, 6, 0] # reorder countries df = df.sort_values(by='order', ascending=False) df # - # We'll use this same basic graph a few times. # Let's make a function so we don't have to repeat the # code to create def gdp_bar(variable="gdp"): fig, ax = plt.subplots() df[variable].plot(ax=ax, kind='barh', alpha=0.5) ax.set_title('Real GDP', loc='left', fontsize=14) ax.set_xlabel('Trillions of US Dollars') ax.set_ylabel('') return fig, ax gdp_bar() # ditto for GDP per capita (per person) fig, ax = gdp_bar("gdppc") ax.set_title('GDP Per Capita', loc='left', fontsize=14) # And just because it's fun, here's an example of Tufte-like axes from [Matplotlib examples](http://matplotlib.org/examples/ticks_and_spines/spines_demo_dropped.html): # + fig, ax = gdp_bar() # Tufte-like axes ax.spines['left'].set_position(('outward', 7)) ax.spines['bottom'].set_position(('outward', 7)) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.yaxis.set_ticks_position('left') ax.xaxis.set_ticks_position('bottom') #ax.tick_params(direction='out') # - # **Exercise (challenging).** Make the ticks point out. # + # scatterplot of life expectancy vs gdp per capita fig, ax = plt.subplots() ax.scatter(df['gdppc'], df['life'], # x,y variables s=df['pop']/10**6, # size of bubbles alpha=0.4) ax.set_title('Life expectancy vs. GDP per capita', loc='left', fontsize=14) ax.set_xlabel('GDP Per Capita') ax.set_ylabel('Life Expectancy') ax.text(58, 66, 'Bubble size represents population', horizontalalignment='right') plt.show() # - # **Exercise.** Make the bubble a little larger. # **Exercise (challenging).** Add labels to the bubbles so we know which country they correspond to. # + # scatterplot of life expectancy vs gdp per capita fig, ax = plt.subplots() ax.scatter(df['gdppc'], df['life'], # x,y variables s=df['pop']/10**6, # size of bubbles alpha=0.4) ax.set_title('Life expectancy vs. GDP per capita', loc='left', fontsize=14) ax.set_xlabel('GDP Per Capita') ax.set_ylabel('Life Expectancy') ax.text(58, 66, 'Bubble size represents population', horizontalalignment='right') for (x, y, country) in zip(df['gdppc'], df['life'], df.index): ax.text(x, y, country) # - # ## Review # # Consider the data from <NAME>'s [blog post](http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/): import pandas as pd data = {'Food': ['French Fries', 'Potato Chips', 'Bacon', 'Pizza', 'Chili Dog'], 'Calories per 100g': [607, 542, 533, 296, 260]} cals = pd.DataFrame(data) # The dataframe `cals` contains the calories in 100 grams of several different foods. # # # **Exercise.** We'll create and modify visualizations of this data: # # * Set `'Food'` as the index of `cals`. # * Create a bar chart with `cals` using figure and axis objects. # * Add a title. # * Change the color of the bars. What color do you prefer? # * Add the argument `alpha=0.5`. What does it do? # * Change your chart to a horizontal bar chart. Which do you prefer? # * *Challenging.* Eliminate the legend. # * *Challenging.* Skim the top of Olson's [blog post](http://www.randalolson.com/2014/06/28/how-to-make-beautiful-data-visualizations-in-python-with-matplotlib/). What do you see that you'd like to imitate? # ## Where does that leave us? # # * We now have several ways to produce graphs. # * Next up: think about what we want to graph and why. The tools serve that higher purpose.
Code/notebooks/bootcamp_graphics_s17_UG.ipynb