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 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- from pymongo import MongoClient import constants import pandas as pd mongo = MongoClient(constants.mongo_conn_string) mongo_lt_source_col = mongo[constants.mongo_db][constants.mongo_lt_col] mongo_lt_destination_col = mongo[constants.mongo_db][constants.mongo_lt_annotated_col] from annotator import LTAnnotator anno = LTAnnotator() # + query = {} cursor = mongo_lt_source_col.find(query, {"text_paragraphs":0, "text_vectors":0}).limit(100) data = [i for i in cursor] df = pd.DataFrame(data) print(df.shape) df.head() # - dfl = df.to_dict(orient="records") df2 = anno.detect_entities(dfl) print(df2.shape) df2.head() df3 = anno.extend_data_datetime_vars(df2) print(df3.shape) df3.head() df4 = anno.extend_data_cabinet_vars(df3) print(df4.shape) df4.head()
1_data_enrichement/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 (ipykernel) # language: python # name: python3 # --- # # Modeling # # - 1. [Introduction](#1.-Introduction) # - 2. [Imports](#2.-Imports) # - 3. [Loading the data](#3.-Loading-the-data) # - 4. [Sampling](#4.-Sampling) # - 4.1 [Types of Sampling](#4.1-Types-of-Sampling) # - 4.2 [Validation and Testing Set Distributions](#4.2-Validation-and-Testing-Set-Distributions) # - 5. [Model Selection](#5.-Model-Selection) # - 5.1 [Baseline Models](#5.1-Baseline-Models) # - 5.2 [Linear Models](#5.2-Linear-Models) # - 5.3 [Tree Models](#5.3-Tree-Models) # - 5.4 [Ensemble Methods](#5.4-Ensemble-Methods) # # - 6. [Conclusion](#6.-Conclusion) # # # 1. Introduction # # In this notebook, we perform select and evaluate models in an attempt to predict early readmission in diabetic patients. Previously, we've split our pre-processed data into training and test sets, which we will be using to train and evaluate our models respectively. # # 2. Imports # + # %load_ext autoreload # %autoreload 2 from collections import Counter import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns sns.set() from functools import partial from imblearn.over_sampling import SMOTE, SMOTENC, RandomOverSampler from imblearn.under_sampling import RandomUnderSampler from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report from sklearn.model_selection import StratifiedKFold, train_test_split from sklearn.tree import DecisionTreeClassifier from src.data import load_dataset as ld from src.models.lace_index import LACEIndexClassifier from src.models.evaluate import classification_report_from_models, train_models_over_samples, classification_report_over_samples, plot_roc_over_folds, \ plot_roc_over_models, kfold_samples, plot_feature_importance pd.options.display.max_columns = 100 RANDOM_SEED = 0 # - # # 3. Loading the data training_data = ld.load_preprocessed_pickle('train.pkl') testing_data = ld.load_preprocessed_pickle('test.pkl') training_data_lace = ld.load_preprocessed_pickle('train_lace.pkl') X_train, y_train = ld.split_dataset(training_data) X_test, y_test = ld.split_dataset(testing_data) X_train.shape, y_train.shape, X_test.shape, y_test.shape X_train_lace, y_train_lace = ld.split_dataset(training_data_lace) X_train_lace.shape, y_train_lace.shape # # 4. Sampling # # ## 4.1 Types of Sampling # # The original dataset had a rough 9:1 ratio of negative to positive observations and with such few observations in our minority class, our model may not learn a useful decision boundary. To combat this class imbalance in our training data, we experiment with different oversampling and undersampling techniques: # - **Random Oversampling**: Duplicate minority observations in our dataset by randomly sampling the minority class with replacement # - **SMOTE (Synthetic Minority Oversampling Technique)**: Synthesize novel minority observations that are similar to other minority observations in the feature space # - **Random Undersampling**: Randomly omit observations from the majority class # # Other considerations: # - **SMOTE and Tomek Links**: SMOTE over-samples the minority class to create a more even representation between the two classes and Tomek Links, an undersampling technique, removes neighbors that are nearby in the feature space but belong to different classes, in order to increase the separation between the major and minor classes. imblearn's SMOTETomek implementation is very computationally intensive so it was not practical to experiment with this procedure for all models. Additionally, although increasing the separation between major and minor classes may improve generalization in theory, we observed in a reduced dimensional feature space that many positive observations were, in fact, near negative observations. Removing these pairs of neighbors may prevent our model from learning these nuances that differentiate these geometrically similar observations. # # Here we initialize our sampling methods and the stratified k-fold helper we will be using during model evaluation: # + smote = SMOTE(random_state=RANDOM_SEED, n_jobs=-1) random_oversampler = RandomOverSampler(sampling_strategy='minority', random_state=RANDOM_SEED) random_undersampler = RandomUnderSampler(random_state=RANDOM_SEED) sampling_methods = [ ('Initial data', None), ('SMOTE', smote), ('Random Oversampling', random_oversampler), ('Random Undersampling', random_undersampler) ] # - skf = StratifiedKFold(n_splits=3, random_state=RANDOM_SEED, shuffle=True) samples = kfold_samples(skf, X_train, y_train, sampling_methods) # + def roc_plots(estimator, sampling_methods=sampling_methods): _, axes = plt.subplots(2, 2, figsize=(15, 10)) axes_iter = iter(axes.flatten()) for name, sampler in sampling_methods: ax = next(axes_iter) plot_roc_over_folds(X_train, y_train, skf, estimator, sampler, ax=ax) ax.set_title(ax.get_title() + f' (sampling={name})') plt.tight_layout() def plot_model_roc(model_sample_pairs): _, axes = plt.subplots(2, 2, figsize=(15, 10)) axes_iter = iter(axes.flatten()) step = 3 for i in range(0, len(model_sample_pairs), step): ax = next(axes_iter) plot_roc_over_models(model_sample_pairs[i:i+step], ax=ax) plt.tight_layout() def plot_model_feature_importance(model_sample_pairs, figsize=(25, 20)): _, axes = plt.subplots(4, 3, figsize=figsize) axes_iter = iter(axes.flatten()) for i, (estimator, X_train, _, _, _) in enumerate(model_sample_pairs): ax = next(axes_iter) plot_feature_importance(estimator.feature_importances_, X_train.columns, max_num=10, title=f'{estimator.__sample__} (fold={i%3})', ax=ax) plt.suptitle(f'Feature Importances for {estimator.__class__.__name__}', y=1.025, fontsize='x-large', fontweight='bold') plt.tight_layout() # - # ## 4.2 Validation and Testing Set Distributions # An assumption that we're making about our validation set is that its observations come from the same distribution as the test set. If they come from different distributions, our validation set is useless and we don't expect our models to learn patterns that will generalize well to unseen data. # # In this offline learning project, we have created our own test set. Having access to both the validation and test set, we can manually verify that they are drawn from approximately distributions: # # - For each validation set that we constructed through stratified sampling, we construct a new dataset composed of the validation set, $V$, and a random stratified sample of the test set of size equal to that of the validation set, $T$. # - We set the target variables of the observations in $V$ to 1 and the target variables of the observations in $T$ to 0. # - We then train a classifier to differentiate between observations in $V$ and $T$ and generate a cross-validated accuracy score. If the score is approximately 50%, then our classifier was not able to sufficiently distinguish observations from $T$ and $V$, and, as a result, we can be more confident that they are drawn from approximately identical distributions. for i, (_, validation_indices) in enumerate(StratifiedKFold(n_splits=5, random_state=RANDOM_SEED, shuffle=True).split(X_train, y_train)): xv = X_train.iloc[validation_indices] yv = pd.Series(np.ones((len(xv),))) xt, _, yt, _ = train_test_split(X_test, y_test, stratify=y_test, test_size=1-len(xv)/len(X_test), random_state=RANDOM_SEED) yt = pd.Series(np.zeros((len(xt,)))) X = pd.concat([xv, xt], axis=0).reset_index(drop=True) y = pd.concat([yv, yt], axis=0).reset_index(drop=True) clf = RandomForestClassifier(random_state=RANDOM_SEED, n_jobs=-1) accuracies = [] for (_, (ti, vi)) in enumerate(StratifiedKFold(n_splits=3, random_state=RANDOM_SEED, shuffle=True).split(X, y)): clf.fit(X.iloc[ti], y.iloc[ti].to_numpy().flatten()) y_pred = clf.predict(X.iloc[vi]) accuracies.append(accuracy_score(y.iloc[vi], y_pred)) print(f'Fold {i}: Mean CV accuracy={sum(accuracies) / len(accuracies)}') # The mean average cross-validated accuracy oscillates around 0.5 across folds. Therefore, we can trust that the means by which we generate our validation set is representative of the testing set, which we'll eventually use to assess our model's final performance. # # 5. Model Selection # # Our learning task is to identify early readmission patient encounters. We experiment with a collection of candidate models and sampling methods to: # 1. Determine the sampling method that performs best during validation # 2. Identify a subset of candidate models that demonstrates promising results in order to reduce the scope of our hyperparameter tuning # 3. Begin to understand the subset of features that is most critical for learning # # Our evaluation of these candidate models are based on its utility in practice. A false negative (a patient who fails to be classified as someone who will likely re-admit within 30 days) has much more dire health and financial implications than those of a false positive. With that in mind, we primarily focus on metrics like recall, which tell us how accurately our learner classifies the positive class. # # We will evaluate each sampling method-model pair using $K$-fold cross-validation, mean-averaging the following metrics over $K$ folds: # - **Precision**: The number of patients that we correctly predicted would readmit early per the number of all patients that we predicted would readmit early # - **Recall**: The number of patients that we correctly predicted would readmit early per the number of all patients that readmitted early # # - **f2 Score**: The harmonic mean of both precision and recall. $\beta = 2$, meaning we place more emphasis on minimizing the presence of false negatives # - **ROC AUC Score**: The probability that the model ranks a random positive observation more highly than a random negative observation. # # # | Average Precision Score | Average Recall Score | Average f2-score ($\beta = 2$)| Average ROC AUC | # | ----------------- | --------------------- | ----------------------------- | --------------- | # $\frac{1}{K}\sum_{i=0}^{K}\frac{TP}{TP + FP}$ | $\frac{1}{K}\sum_{i=0}^{K} \frac{TP}{TP + FN}$ | $\frac{1}{K}\sum_{i=0}^{K} \frac{(1 + \beta^2) PR}{\beta^2 P + R}$ | $\frac{1}{K}\sum_{i=0}^{K} \int_{0}^{1} ROC$ # # # # ## 5.1 Baseline Models # # ### 5.1.1 Dummy Classifier # # We first train a dummy classifier, based on a basic heuristic of using the most frequently occurring label as a prediction. ld.load_data('../metrics/baseline/baseline_results_DummyClassifier.pkl') # ![DummyClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_DummyClassifier.png) # ### 5.1.2 LACE Index # # # + lace = LACEIndexClassifier() lace_sampling_methods = [ ('Initial data', None), ('SMOTE', SMOTENC(random_state=RANDOM_SEED, categorical_features=np.arange(2, len(X_train_lace.columns)))), ('Random Oversampling', random_oversampler), ('Random Undersampling', random_undersampler) ] lace_samples = kfold_samples(skf, X_train_lace, y_train_lace, lace_sampling_methods) lace_models = train_models_over_samples(lace, lace_samples) # - classification_report_from_models(lace_models) plot_model_roc(lace_models) del lace_models; del lace_samples; del lace; # ## 5.2 Linear Models # ### 5.2.1 Logistic Regression ld.load_data('../metrics/baseline/baseline_results_LogisticRegression.pkl') # ![LogisticRegression ROC AUC plot](../metrics/baseline/roc_auc_plot_LogisticRegression.png) # ## 5.3 Tree Models # # ### 5.3.1 Decision Tree ld.load_data('../metrics/baseline/baseline_results_DecisionTreeClassifier.pkl') # ![DecisionTreeClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_DecisionTreeClassifier.png) # ## 5.4 Ensemble Methods # # ### 5.4.1 Random Forest Classifier ld.load_data('../metrics/baseline/baseline_results_RandomForestClassifier.pkl') # ![RandomForestClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_RandomForestClassifier.png) # ### 5.4.2 Gradient Boosting Classifier ld.load_data('../metrics/baseline/baseline_results_GradientBoostingClassifier.pkl') # ![GradientBoostingClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_GradientBoostingClassifier.png) # ### 5.4.3 Light GBM Classifier ld.load_data('../metrics/baseline/baseline_results_LGBMClassifier.pkl') # ![LGBMClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_LGBMClassifier.png) # ### 5.4.4 XGBoost ld.load_data('../metrics/baseline/baseline_results_XGBClassifier.pkl') # ![XGBClassifier ROC AUC plot](../metrics/baseline/roc_auc_plot_XGBClassifier.png) # ## 5.5 Results ld.load_data('../metrics/baseline/mean_scores_by_sampler.pkl') # Above, we show the average scores for various metrics of each type of sampling method. Random undersampling method demonstrates the best performance in our key metrics (recall, ROC AUC, f2-score). Random oversampling also demonstrates a solid performance in the recall and ROC AUC metrics while also yielding a higher average precision score than random undersampling. Using our initial data, without any re-sampling method, yields the highest average precision and ROC AUC score, but de-prioritizes recall, resulting in the lowest average f2 score of all four categories. SMOTE consistently performs badly in all selected metrics. results = ld.load_data('../metrics/baseline/baseline_model_total_results.pkl') results results[results.index.get_level_values(1) == 'under_sampled'] # Logistic regression and the tree-based ensemble methods performed the best on average. The three gradient-boosted tree implementations, GradientBoostingClassifier, LightGBM, XGBoost, performed well and yielded comparable scores. The GradientBoostingClassifier implementation appeared to prioritize precision more than the others. LightGBM was the most time and resource efficient and yielded the highest recall score. Random forest yielded the highest recall score among all classifiers. # # Based on these initial results, we will be tuning the hyperparameters for logistic regression, random forest, and LGBM classifiers in the next section. # # 6. Conclusion # # In this notebook, we defined a suite of metrics that would be most useful in evaluating models with respect to our data. Our data is imbalanced, where early readmission patients only account for about 9% of our dataset. We decided to evaluate models with precision, recall, f2-score, and ROC AUC. We prioritize the recall score and weighted metrics like the f2-score, as we would like to minimize false negatives. # # Class imbalance risks biasing our models by exposing them to a disproportionate number of observations per class. We explored sampling methods to counteract this. We experimented with SMOTE (Synthetic Minority Oversampling Technique), random oversampling the minority class, and random undersampling the majority class. We then performed 3-fold cross-validation on each of these generated datasets to determine which method yielded the best overall performance and to also get a general idea of which types of models are most effective in learning from our data. Random undersampling yielded higher recall values on average, without sacrificing precision or ROC AUC. SMOTE performed the worst on average among all non-dummy models. # # We evaluated both a dummy classifier that predicted the most frequent class in our training data and a LACE index classifier, which predicts early readmission based on well-known features like the number of emergency visits the patient had in the past year or the kinds of comorbidities they have. The LACE index performed only marginally better than the dummy classifier, generating poor precision and recall scores and an ROC AUC score that was barely better than random. This indicates that the current heuristic for identifying early readmission is lacking and that there is room for improvement. # # Logistic regression and tree-based ensemble methods tend to perform better on average. We will consider logistic regression, random forest, LGBM classifiers to optimize given their effectiveness and their reasonable training speed. # # We plotted feature importances for each model, sampling method, fold combination. The number of in-patient visits, number of medications, number of lab procedures, days in the hospital, and transferring to a skilled nursing facility or an undefined health institution appear to be important features. # # With this in mind, we will try to improve our model through hyperparameter optimization in our next notebook.
notebooks/3_modeling.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 from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.manifold import TSNE crypto_data_to_load = "Resources/crypto_data.csv" crypto_data = pd.read_csv(crypto_data_to_load) crypto_data.head(9) # + # Removing rows that aren't being traded df = crypto_data[crypto_data["IsTrading"] == True].drop(columns = "IsTrading") # Dropping null values df = df.dropna() # Converting 'totalcoinsupply' column from string to float df["TotalCoinSupply"] = df["TotalCoinSupply"].astype(float) # Keeping only coins that were mined >0, removing all else df = df[df["TotalCoinsMined"] > 0] # Removing coin name and unnamed columns. Not necessary coins_df = df["CoinName"] df = df.drop(columns = ["Unnamed: 0", "CoinName"]) # - df.dtypes # Converting 'algorithm' and 'prooftype' columns into numerical data dummies = pd.get_dummies(df) dummies # Scaling data by using standard and minmax scalers crypto_scaled_m = MinMaxScaler().fit_transform(dummies) crypto_scaled_s = StandardScaler().fit_transform(dummies) # + # Reducing dimensions using PCA pca_m = PCA(n_components = 0.9).fit_transform(crypto_scaled_m) pca_s = PCA(n_components = 0.9).fit_transform(crypto_scaled_s) df_pca_m = pd.DataFrame(pca_m) df_pca_m.head() # - # PCA results with a higher amount of factors from using Standard Scaler df_pca_s = pd.DataFrame(pca_s) df_pca_s.head() # + # Creating TSNE learning rate graphs lr = [10, 50, 100, 200, 500, 1000] for z in lr: fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (12, 5)) fig.suptitle(f"The Learning Rate is: {z}") tsne_m = TSNE(learning_rate = z, random_state = 1).fit_transform(df_pca_m) ax1.scatter(tsne_m[:,0], tsne_m[:,1], c = "lightpink") ax1.set_title("MinMaxScaler Model") tsne_s = TSNE(learning_rate = z, random_state = 1).fit_transform(df_pca_s) ax2.scatter(tsne_s[:,0], tsne_s[:,1], c = "hotpink") ax2.set_title("StandardScaler Model") plt.show() # + # Finding the best model fit number of clusters using KMeans inertia = [] k = list(range(1, 11)) for i in k: km = KMeans(n_clusters=i, random_state=1) km.fit(df_pca_m) inertia.append(km.inertia_) elbow_data_m = {"k": k, "inertia": inertia} df_elbow_m = pd.DataFrame(elbow_data_m) inertia = [] for i in k: km = KMeans(n_clusters=i, random_state=1) km.fit(df_pca_s) inertia.append(km.inertia_) elbow_data_s = {"k": k, "inertia": inertia} df_elbow_s = pd.DataFrame(elbow_data_s) fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (12, 5)) ax1.plot(df_elbow_m['k'], df_elbow_m['inertia'], "o-", c = "lightpink") ax1.set_title("KMeans Elbow Plot - MinMaxScaler Model") ax2.plot(df_elbow_s['k'], df_elbow_s['inertia'], "o-", c = "hotpink") ax2.set_title("KMeans Elbow Plot - StandardScaler Model") for p in [ax1, ax2]: p.set_xticks(range(len(k) + 1)) p.set_xlabel('Number of clusters') p.set_xlim(0, len(k) + 1) p.set_ylabel('Inertia') plt.show() # - tsne_m = TSNE(learning_rate = 300, random_state = 1).fit_transform(df_pca_m) tsne_s = TSNE(learning_rate = 300, random_state = 1).fit_transform(df_pca_s) cl = [3, 5, 7, 9] for c in cl: fig, (ax1, ax2) = plt.subplots(1, 2, figsize = (8, 4)) fig.suptitle(f"The Number of Clusters is: {c}") predict_m = pd.DataFrame(KMeans(n_clusters=c, random_state=1).fit(df_pca_m).predict(df_pca_m)) ax1.scatter(tsne_m[:,0], tsne_m[:,1], c = predict_m, cmap = "gist_rainbow") ax1.set_title("MinMaxScaler Model") predict_s = pd.DataFrame(KMeans(n_clusters=c, random_state=1).fit(df_pca_s).predict(df_pca_s)) ax2.scatter(tsne_s[:,0], tsne_s[:,1], c = predict_s, cmap = "gist_rainbow") ax2.set_title("StandardScaler Model") plt.show()
.ipynb_checkpoints/crypto_final-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.3 # language: julia # name: julia-1.5 # --- # # Requirements # # - make sure you have Project.toml and Manifest.toml files in the working directory of the notebook # - set the directory containing source data files in next cell ## path to datasets datadir = "../Datasets/" using CSV using DataFrames using LightGraphs using Statistics using GraphPlot using PyPlot using StatsBase using GLM # Just looking at basic statistics on degree distribution, clustering coefficient and shortest paths, we can identify huge difference between different types of graphs. Here we look at a social-type graph, and a transportation-type (power grid) network. # ## GitHub Developers (undirected) # # Description # # A large social network of GitHub developers which was collected from the public API in June 2019. Nodes are developers who have starred at least 10 repositories and edges are mutual follower relationships between them. The vertex features are extracted based on the location, repositories starred, employer and e-mail address. The task related to the graph is binary node classification - one has to predict whether the GitHub user is a web or a machine learning developer. This target feature was derived from the job title of each user. # # + ## read the GitHub edge list into a graph D = CSV.read(datadir * "GitHubDevelopers/musae_git_edges.csv", DataFrame) .+ 1 max_node_id = max(maximum(D.id_1), maximum(D.id_2)) gh = SimpleGraph(max_node_id) foreach(row -> add_edge!(gh, row...), eachrow(D)) ## add some node features, here there are ## 2 class of nodes, 0: web developer (red), 1: ml developer (blue) X = CSV.read(datadir * "GitHubDevelopers/musae_git_target.csv", DataFrame) X.id .+= 1 @assert extrema(diff(X.id)) == (1, 1) && extrema(X.id) == (1, length(vertices(gh))) gh_target = X.ml_target gh_color = ifelse.(X.ml_target .== 0, "grey", "black") gh_lbl = ifelse.(X.ml_target .== 0, "web", "ml"); # - # ## Europe Electric Grid # # Network of high voltage grid in Europe. Details at: # https://zenodo.org/record/47317#.Xt6nzy3MxTY # # edge_list = split.(readlines(datadir * "GridEurope/gridkit_europe-highvoltage.edges")) vertex_ids = unique(reduce(vcat, edge_list)) vertex_map = Dict(vertex_ids .=> 1:length(vertex_ids)) gr = SimpleGraph(length(vertex_ids)) foreach(((from, to),) -> add_edge!(gr, vertex_map[from], vertex_map[to]), edge_list) X = CSV.read(datadir * "GridEurope/gridkit_europe-highvoltage.vertices", DataFrame) X.id = [get(vertex_map, string(v), missing) for v in X.v_id] dropmissing!(sort!(X, :id)) @assert extrema(diff(X.id)) == (1, 1) && extrema(X.id) == (1, length(vertices(gr))) gr_longitude = X.lon gr_latitude = X.lat gr_type = X.typ; # ## Features for 4 graphs # # - GitHub # - GitHub ml developers # - GitHub web developers # - Grid # + ## for github, 9739 are ml developers, and 27961 are web developers; ## build the subgraphs gh_ml = induced_subgraph(gh, findall(==("ml"), gh_lbl))[1] gh_web = induced_subgraph(gh, findall(==("web"), gh_lbl))[1] @show nv(gh_ml), nv(gh_web) # - ## github graph: count ml with connection to web only and vice-versa c_ml, c_web = 0, 0 for v in vertices(gh) if gh_lbl[v] == "ml" if count(i -> gh_lbl[i] == "ml", neighbors(gh, v)) == 0 c_ml += 1 end else if count(i -> gh_lbl[i] == "web", neighbors(gh, v)) == 0 c_web += 1 end end end print("$c_ml ml connected only to web and $c_web web connected only to ml") function igraph_diameter(G) ccs = connected_components(G) ccg = [induced_subgraph(G, cc)[1] for cc in ccs] maximum(maximum(maximum(gdistances(g, i)) for i in vertices(g)) for g in ccg) end # + ## compute and store basic stats in a table function baseStats(G) deg = degree(G) cc = connected_components(G) return Any[nv(G), ne(G), minimum(deg), mean(deg), median(deg), quantile(deg, 0.99), maximum(deg), length(cc), maximum(length, cc), count(==(0), deg), global_clustering_coefficient(G), mean(local_clustering_coefficient(G)[degree(G) .> 1])] end df = DataFrame(statistic=["nodes", "edges", "d_min", "d_mean", "d_median", "d_quant_99", "d_max", "components", "largest", "isolates", "C_glob", "C_loc"], GitHub=baseStats(gh), GitHub_ml=baseStats(gh_ml), GitHub_web=baseStats(gh_web), Grid=baseStats(gr)) ## this can take a few minutess so we disable it by default if false gh_diam = igraph_diameter(gh) gh_ml_diam = igraph_diameter(gh_ml) gh_web_diam = igraph_diameter(gh_web) gr_diam = igraph_diameter(gr) push!(df, ("diameter", gh_diam, gh_ml_diam, gh_web_diam, gr_diam)) end df # - # ## Visualize part of the Grid network gr_spain, spain_ids = induced_subgraph(gr, findall(@. (36 < gr_latitude < 44) & (-10 < gr_longitude < 4))) gplot(gr_spain, gr_longitude[spain_ids], -gr_latitude[spain_ids], NODESIZE=0.01, nodefillc="black", EDGELINEWIDTH=0.2, edgestrokec="black") # ## Visualize part of the GitHub (ml) graph # # Quite different from the Grid graph, with clumps (dense areas) and less regular edge distribution cc_ml = connected_components(gh_ml) giant_ml, giant_ml_idx = induced_subgraph(gh_ml, cc_ml[argmax(length.(cc_ml))]) # you can use other layuts if you want to experiment locs_x, locs_y = spring_layout(giant_ml, MAXITER=5) # + xmin, xmax = quantile(locs_x, [0.4, 0.6]) ymin, ymax = quantile(locs_y, [0.4, 0.6]) ml_zoom, ml_zoom_ids = induced_subgraph(giant_ml, findall(@. (xmin < locs_x < xmax) & (ymin < locs_y < ymax))) gplot(ml_zoom, locs_x[ml_zoom_ids], locs_y[ml_zoom_ids], NODESIZE=0.01, nodefillc="black", EDGELINEWIDTH=0.2, edgestrokec="gray") # - # ## Visualize part of the GitHub (web) graph cc_web = connected_components(gh_web) giant_web, giant_web_idx = induced_subgraph(gh_web, cc_web[argmax(length.(cc_web))]) # you can use other layuts if you want to experiment locs_x, locs_y = random_layout(giant_web) # + xmin, xmax = quantile(locs_x, [0.1, 0.3]) ymin, ymax = quantile(locs_y, [0.1, 0.3]) web_zoom, web_zoom_ids = induced_subgraph(giant_web, findall(@. (xmin < locs_x < xmax) & (ymin < locs_y < ymax))) gplot(web_zoom, locs_x[web_zoom_ids], locs_y[web_zoom_ids], NODESIZE=0.01, nodefillc="black", EDGELINEWIDTH=0.2, edgestrokec="gray") # - # ## Compare degree distributions # # We plot the (empirical) cumulative distribution functions (cdf) ## degree distribution - GitHub graph deg = degree(gh) e = ecdf(deg) x = range(extrema(e)..., step=1) y = e.(x) semilogx(x,y,"-",color="black",label="GitHub") xlabel("degree",fontsize=14) ylabel("empirical cdf",fontsize=14); ## degree distribution - Grid graph ## we see much lower degree here deg = degree(gr) e = ecdf(deg) x = range(extrema(e)..., step=1) y = e.(x) semilogx(x,y,"-",color="black",label="Grid") xlabel("degree",fontsize=14) ylabel("empirical cdf",fontsize=14); # ## Shortest paths distribution # # Histograms of shortest path lengths from 100 random nodes; # # again we see much different distributions # + ## shortest paths length from a given node, GitHub graph cc_gh = connected_components(gh) giant_gh, _ = induced_subgraph(gh, cc_gh[argmax(length.(cc_gh))]) V = sample(1:nv(giant_gh), 100, replace=false) sp = DataFrame(len=reduce(vcat, gdistances.(Ref(giant_gh), V))) histdata = combine(groupby(sp, :len, sort=true), nrow => :count) fig, ax = subplots() ax.bar(histdata.len, histdata.count, color="darkgrey") ax.set_yscale("log") ax.set_xlabel("path length",fontsize=14) ax.set_ylabel("number of paths (log scale)",fontsize=14); # + ## min path length from that node to other nodes, Grid network cc_gr = connected_components(gr) giant_gr, _ = induced_subgraph(gr, cc_gr[argmax(length.(cc_gr))]) V = sample(1:nv(giant_gr), 100, replace=false) V = 1:100 sp = DataFrame(len=reduce(vcat, gdistances.(Ref(giant_gr), V))) histdata = combine(groupby(sp, :len, sort=true), nrow => :count) fig, ax = subplots() ax.bar(histdata.len, histdata.count, color="darkgrey") ax.set_xlabel("path length",fontsize=14) ax.set_ylabel("number of paths (log scale)",fontsize=14); # - # ## Local clustering coefficient # # We compare the average local clustering coefficients as a function # of the degree. We consider degrees from 10 to 1000. # # + ## build dataframe with degrees and local clustering coefficients ## and compute mean values w.r.t. degree. ## GitHub graph mindeg = 10 maxdeg = 1000 D = DataFrame(CC=local_clustering_coefficient(gh, 1:nv(gh)), d=degree(gh)) D_mean = combine(groupby(D, :d, sort=true), :CC => mean => :CC) filter!(:d => x -> 10 <= x <= 1000, D_mean) transform!(D_mean, :d => ByRow(log) => :x, :CC => ByRow(log) => :y) model = lm(@formula(y~x), D_mean) # - ## plot on log-log scale b, a = coef(model) loglog(D_mean.d, D_mean.CC,".-",color="grey") plot([mindeg,maxdeg],[exp(b)*mindeg^a,exp(b)*maxdeg^a],color="black") xlabel("log(degree)",fontsize=14) ylabel("log(mean local clust. coef.)",fontsize=14); #plt.savefig('localCC.eps');
Julia_Notebooks/Chapter_1.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 # --- # # Estimation of Orbital Parameters of Extra-solar Planets from Radial Velocities using Markov Chain Monte Carlo (MCMC) # # # # # ## MCMC: A Conceptual Introduction # Monte Carlo (MC) methods have become a cornerstone of present-day scientific analyses by providing a simple approach for obtaining information about distributions, especially for estimating posterior distributions in Bayesian inference using samples from a continuous random variable. They comprise of a class of algorithms for sampling from a desired probability distribution. The sample of the distribution are obtained by constructing a chain that has the probability distribution as its stationary distribution followed by registering and saving the states from the chain. # # The samples created by the Markov chain have probability density proportional to a known function. These large number of samples drawn are used to estimate the properties of the distribution (such as its expected value or variance). Practically, different sets of samples are created using multiple chains (an ensemble of chains), starting from a set of points randomly chosen and sufficiently separated from each other in the sample space. # # These stochastic chains comprise of **walkers** which explores the parameter space in random directions according to an algorithm that looks for places with a reasonably high contribution to the properties of the probability distribution to move to the next, with higher probabilities than the direct predecessor. # # MCMC is essentially a *sampler* as it explores the parameter space. The fundamental process of running a Markov chain is to compare the **models** generated by the chains against the **data** while moving around the parameter space. The objective is to determine the set of parameters that produces the best fit model of our data. The process is inherently Bayesian as opposed to *frequentist* as it requires a prior knowledge of the system in terms of the parameters. For example, constructing a stellar model can contain temperature as a parameter with a prior that the temperature at the core is within a certain range, as fusion reactions can only occur above certain temperatures. # # ## Bayesian Inference # # We shall use the MCMC technique to know more about characteristics of the planetary system, 51 Pegasi (HD 217014). The radial velocity (RV) data was obtained from NASA Exoplanet Archive which is maintained by the [NASA Exoplanet Science](https://exoplanetarchive.ipac.caltech.edu/). Let the data be denoted by **D<sub>RV</sub>** of which we are interested to make inferences. # # We want to interpret the RV data in light of an underlying model **M** which is a function of a set of parameters, **$\Theta$<sub>M</sub>**, which can predict about the proximity of the data to the model. We can, therefore, estimate the conditional probability *P* (**D<sub>RV</sub>** | **$\Theta$<sub>M</sub>**, **M**) that we would obtain the data, **D<sub>RV</sub>**, from our model using a particular set of parameters, **$\Theta$<sub>M</sub>**. Alternatively, given our model **M**, we can ask about the likelihood of the parameter **$\Theta$<sub>M</sub>** such that the assumed model completely explains our data. # # In Bayesian statistical inference, we are interested in determining the quantity, *P* (**$\Theta$<sub>M</sub>** | **D<sub>RV</sub>**, **M**). It is the probability that the parameters are actually **$\Theta$<sub>M</sub>** under the assumed model given our data, **D<sub>RV</sub>**. The two conditional probabilities are related as: # # \begin{equation} \it{P}\, \mathrm{(\Theta_M\,|\,D_{RV}, M)}\; \it{P}\, \mathrm{(D_{RV}\,|\,M)} = \it{P}\, \mathrm{(\Theta_M, D_{RV}\,|\,M)} = \it{P}\, \mathrm{(D_{RV}\,|\,\Theta_M, M)}\;\, \it{P}\, \mathrm{(\Theta_M\,|\,M)} \mathrm{\tag{1}}\end{equation} # # # # where $\it{P}\, \mathrm{(\Theta_M, D_{RV}\,|\,M)}$ represents the joint probability of obtaining the parameter, **$\Theta$<sub>M</sub>**, such that the data, **D<sub>RV</sub>**, is observed. From Bayes' theorem, the two conditional probabilities can be rearranged as: # # \begin{equation} \it{P}\, \mathrm{(\Theta_M\,|\,D_{RV}, M)} = \frac {\it{P}\, \mathrm{(D_{RV}\,|\,\Theta_M, M)}\;\, \it{P}\, \mathrm{(\Theta_M\,|\,M)}}{\it{P}\, \mathrm{(D_{RV}\,|\,M)}}\mathrm{\tag{2}}\end{equation} # # # The MCMC analysis usually starts with selection of a set of parameter values, often referred to as **priors** - $\it{P}\, \mathrm{(\Theta_M\,|\,M)}$. As the name suggests, the values are chosen based on previous measurements, physical conditions ,and other known constraints. The denominator, $\it{P}\, \mathrm{(D_{RV}\,|\,M)}$, is termed as **evidence**. It describes how well our model explains our data after averaging over the complete range of the parameter set. The model is said to be good if it matches our data to a large extent. $\it{P}\, \mathrm{(\Theta_M\,|\,D_{RV}, M)}$ represents the **posterior**. This is a measure of our belief in the best parameter after combining our prior values with the current observations and normalizing by the evidence over the parameter space. # <img src="Image1.png" width="850" height="400"> # # The above process is summarized below. # # - With the set of input parameters as variables, write a function that specifies our model. # - Set up an ensemble of walkers defined by the parameters **$\Theta$<sub>M</sub>**. # - A grid containing the values of different parameters over their respective ranges is generated. # - Every walker will now begin exploring the parameter space. To do this, each walker takes a step to a new value of parameters and generates a model with that set of parameters. It then compares the model to the dataset, usually through minimizing the $\chi^2$ or maximizing the log-likelihood function. # \begin{equation} \mathrm{Likelihood} = -\frac{1}{2} \sum_{Data}^{}{\mathrm{ln}\;\{2\pi\;({y_{Error})}^{2}}\}-\frac{1}{2} \sum_{Data}^{}{\left(\frac{y_{Data}-y_{Model}}{y_{Error}}\right)^{2}}\mathrm{\tag{3}}\end{equation} # - The MCMC then determines the ratio of the likelihood generated by the model with the new set of parameters to data and compares it with the previous set of parameter. If the new location produces a better ratio, the walker moves there and repeats the process. If the new location is worse than the earlier, it retreats to its previous position and looks for a new direction. # - The walkers move around by exploring the parameter space and terminates its journey in the region of maximum likelihood. # # A posterior distribution is generated at the end of the process (also termed as the **production run**).If the MCMC runs a sufficient number of steps,it converges to the region of maximum likelihood. # # ## Fitting the Exoplanet's Radial Velocity # The RV data of 51 Pegasi can be downloaded from the Exoplanet archive. We are interested in the RV values with thier errors as a function of the Julian Date. For representation purpose, we shall phase-fold the time axis. # + # #!/usr/bin/env python3 import numpy as np import scipy as sp import pandas as pd import matplotlib.pyplot as plt import math import emcee import corner import pickle import tkinter as tk from tkinter import simpledialog from tkinter.simpledialog import askinteger import easygui from IPython.display import display, Math plt.rcParams['figure.figsize'] = [12,7] # + jupyter={"outputs_hidden": false} Data = pd.read_table('UID_0113357_RVC_005.dat',sep = '\s+',skiprows=22, header = None, index_col = None) print(Data) RV_Data = np.array(Data) HJD = RV_Data[:,[0]] Rad_Vel = RV_Data[:,[1]] RV_Error = RV_Data[:,[2]] plt.errorbar(HJD, Rad_Vel, RV_Error, color='black', fmt='o', capsize=5, capthick=1, ecolor='black') plt.xlabel('Heliocentric Julian Date (Time)') plt.ylabel('Radial Velocity') plt.grid() plt.show(block=False) len_HJD = len(HJD) Phase_Folded = np.empty((len_HJD, len_HJD)) fig = plt.figure() for i in range(0,len_HJD): t = HJD T0 = HJD[i] P = 4.230785 PF = ((t-T0)/P)-np.floor((t-T0)/P) Phase_Folded[:,[i]] = PF root =tk.Tk() canvas1 = tk.Canvas(root, width = 400, height = 200, relief = 'raised') canvas1.pack() label1 = tk.Label(root, text='Select the Reference Time (Fiducial)') label1.config(font=('helvetica', 14)) canvas1.create_window(200, 25, window=label1) label2 = tk.Label(root, text='Input the n\u1D57\u02B0 HJD to be taken as the reference \n\n(n\u2208Z\u207a; 1 \u2264 n \u2264 202):') label2.config(font=('helvetica', 10)) canvas1.create_window(200, 95, window=label2) mystring =tk.IntVar(root) def close_window(): root.destroy() e1 = tk.Entry(root,textvariable = mystring,width=25,fg="black",bd=3,selectbackground='gray').place(x=100, y=120) button1 = tk.Button(root, text='Submit', fg='White', bg= '#000000',height = 1, width = 10,command=close_window).place(x=150, y=170) root.mainloop() j = mystring.get() j = j-1 plt.errorbar(2*np.pi*Phase_Folded[:,[j]], Rad_Vel, RV_Error, color='black', fmt='o', capsize=5, capthick=1, ecolor='black') plt.xlabel('Phase Folded (Time)') plt.ylabel('Radial Velocity') plt.grid() plt.show(block=False) x_data = Phase_Folded[:,[j]] x_model = np.linspace(0, 1, 5000) # - # The radial velocity curve repeats over time and it appears to be a sinusoid. The RV method for detecting exoplanets relies on the fact that a star does not remain completely stationary when it is orbited by a planet. The star moves, ever so slightly, in a small circle or ellipse, responding to the gravitational pull of its smaller companion. When viewed from a distance, these slight movements affect the star's normal light spectrum, or color signature. The spectrum of a star that is moving towards the observer appears slightly shifted toward bluer (shorter) wavelengths. If the star is moving away, then its spectrum is shifted toward redder (longer) wavelengths. # # We define our model to be of the form # $$ # \mathrm{RV} = \mathrm{y_0} + \mathrm{A_0\;cos(2\,\pi\,t + \Phi_0)}\mathrm{\tag{4}} # $$ # where $\mathrm{y_0, A_0,}$ and $\mathrm{\Phi_0}$ are the parameters to be fitted. # ## Setting up the MCMC # The RV function is defined below: # # Model # def rvmodel_mcmc(Parameters,x=x_model): y0, A0, Phi0 = Parameters return y0 + (A0*np.cos((2*np.pi*x)+Phi0)) # We now need a log-likelihood function that estimates how good a fit the model is to the data for a given set of parameters, weighted by the RV error. The following function is used: # # \begin{equation} \mathrm{Likelihood} = -\frac{1}{2} \sum_{Data}^{}{\mathrm{ln}\;\{2\pi\;({y_{Error})}^{2}}\}-\frac{1}{2} \sum_{Data}^{}{\left(\frac{y_{Data}-y_{Model}}{y_{Error}}\right)^{2}}\end{equation} # # Likelihood Function # def lnlike(Parameters,x,y,yerror): return -0.5*(np.sum((np.log(2*np.pi*(yerror**2)))+(((y-rvmodel_mcmc(Parameters,x))/yerror)**2))) # The next function we need is one to check, before running the probability function on any set of parameters, that all variables are within their priors. The lnprior function specifies a bounds on the parameters. The output of this function is just an encoding similar to a true or false. # # # Priors # def lnprior(Parameters): y0, A0, Phi0 = Parameters if -50.0 < y0 < 50.0 and 0.0 < A0 < 125.0 and 0.0 < Phi0 < 2*np.pi: return 0.0 return -np.inf # The lnprob function combines the steps above by running the lnprior function, and if the function returned -np.inf, passing that through as a return, and if not, returning the lnlike for that model. # # # # Bayesian Posterior Probability # def lnprob(Parameters,x,y,yerror): lp = lnprior(Parameters) if not np.isfinite(lp): return -np.inf return lnlike(Parameters,x,y,yerror)+lnprior(Parameters) data = (x_data,Rad_Vel,RV_Error) nwalkers = 500 niter = 5000 initial = np.array([-2.0, 100.0, 3.0]) ndim = len(initial) p0 = [np.array(initial) + 1e-7 * np.random.randn(ndim) for k in range(nwalkers)] # We are now ready to run the MCMC. def main(p0,nwalkers,niter,ndim,lnprob,data): sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=data) print("Running burn-in...") p0, _, _ = sampler.run_mcmc(p0, 1000, progress=True) sampler.reset() print("Running production...") pos, prob, state = sampler.run_mcmc(p0, niter,progress=True) return sampler, pos, prob, state # The sampler here contains all the outputs of the MCMC, including the walker chains and the posteriors. # + jupyter={"outputs_hidden": false} sampler, pos, prob, state = main(p0,nwalkers,niter,ndim,lnprob,data) # + jupyter={"outputs_hidden": false} def plotter(sampler,x=x_data,Rad_Vel=Rad_Vel): #plt.ion() plt.errorbar(2*np.pi*x_data,Rad_Vel, RV_Error, color='black', fmt='o', capsize=5, capthick=1, ecolor='black') samples = sampler.flatchain for Parameters in samples[np.random.randint(len(samples), size=1000)]: plt.plot(2*np.pi*x_model, rvmodel_mcmc(Parameters,x_model), color='#800000',alpha=0.1) plt.xlabel('Phase Folded (Time)') plt.ylabel('Radial Velocity') plt.legend(["Random Parameter Samples from the Posterior Distribution"],fontsize=14) plt.grid() plt.show(block=False) # - plotter(sampler) # We can see that our perfectly fits our data. Also, the thousand samples drawn from the posteriors seem to overlap over each other quite well. # # + jupyter={"outputs_hidden": false} samples = sampler.flatchain samples[np.argmax(sampler.flatlnprobability)] samples = sampler.flatchain # + jupyter={"outputs_hidden": false} theta_max = samples[np.argmax(sampler.flatlnprobability)] best_fit_model_mcmc = rvmodel_mcmc(theta_max) plt.errorbar(2*np.pi*x_data,Rad_Vel, RV_Error, color='black', fmt='o', capsize=5, capthick=1, ecolor='black') plt.plot(2*np.pi*x_model,best_fit_model_mcmc,color='#FFFF66', label="Monte Carlo Markov Chain Fit") plt.xlabel('Phase Folded (Time)') plt.ylabel('Radial Velocity') plt.legend(fontsize=14) plt.grid() plt.show() # - # ### Posterior Spread # The corner.py module is used to visualize 1D and 2D spreads between the tested parameters and to obtain the uncertainties on the parameter estimations. # + jupyter={"outputs_hidden": false} def sample_walkers(nsamples,flattened_chain): models = [] draw = np.floor(np.random.uniform(0,len(flattened_chain),size=nsamples)).astype(int) Param = flattened_chain[draw] for l in Param: mod = rvmodel_mcmc(l) models.append(mod) spread = np.std(models,axis=0) med_model = np.median(models,axis=0) return med_model,spread med_model, spread = sample_walkers(1000,samples) # + jupyter={"outputs_hidden": false} plt.errorbar(2*np.pi*x_data,Rad_Vel, RV_Error, color='black', fmt='o', capsize=5, capthick=1, ecolor='black') plt.fill_between(2*np.pi*x_model,med_model-2*spread,med_model+2*spread,color='#FE891B',alpha=0.45,label=r'$2\sigma$ Posterior Spread') plt.fill_between(2*np.pi*x_model,med_model-spread,med_model+spread,color='#00FF7F',alpha=0.3,label=r'$1\sigma$ Posterior Spread') plt.plot(2*np.pi*x_model,best_fit_model_mcmc,color='#FFFF66', label="Monte Carlo Markov Chain Fit") plt.xlabel('Phase Folded (Time)') plt.ylabel('Radial Velocity') plt.legend(fontsize=14) plt.grid() plt.show() # + labels = ['$y₀$', '$A₀$', '$𝛟₀$'] label = ['y₀', 'A₀', '𝛟₀'] print('\033[1m' + 'Uncertainties based on the 16th, 50th, and 84th percentiles of the samples in the marginalized distributions' + '\033[0m') for m in range(ndim): mcmc = np.percentile(samples[:, m], [16, 50, 84]) q = np.diff(mcmc) txt1 = "\mathrm{{{3}}} = {0:.9f}_{{-{1:.3f}}}^{{{2:.3f}}}" txt1 = txt1.format(mcmc[1], q[0], q[1], label[m]) display(Math(txt1)) print('\033[1m' + 'Parameters based on the Highest Likelihood Model with data from the Posterior Distribution' + '\033[0m') for m in range(ndim): txt2 = "\mathrm{{{1}}} = {0:.9f}" txt2 = txt2.format(theta_max[m], label[m]) display(Math(txt2)) fig = corner.corner(samples,show_titles=True,labels=labels,smooth=True,plot_datapoints=True,quantiles=[0.16, 0.5, 0.84],levels=(1-np.exp(-0.5),1-np.exp(-0.5*4))) fig.show() # - # The most likely model doesn't always lie at the center of this spread - the spread is around the median model, but the one that absolutely maximizes the likelihood might lie at the edge or even outside this region. # # # # # # # # # # **Developed and designed by [<NAME>](https://github.com/Shubhonkar-Paramanick)**
MCMC_RadVel.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 # --- # ## Validation of EIS data # #### The Kramers-Kronig Relations # Electrochemical impedance spectroscopy (EIS) is built on linear systems theory which requires that the system satisfy conditions of causality, linearity, and stability. The Kramers-Kronig relations consist of a set of transformations that can be used to predict one component of the impedance from the other over the frequency limits from zero to infinity. For example, one might calculate the imaginary component of the impedance from the measured real component, # # $$ # Z^{\prime\prime}(\omega) = - \frac{2\omega}{\pi} \int_0^\infty \frac{Z^{\prime}(x) - Z^{\prime}(\omega)}{x^2 - \omega^2}dx # $$ # # where $Z^{\prime}(\omega)$ and $Z^{\prime\prime}(\omega)$ are the real and imaginary components of the impedance as a function of frequency, $\omega$. Similarly, the real part of the impedance spectrum can be calculated from the imaginary part by # # $$ # Z^{\prime}(\omega) = Z^{\prime}(\infty) + \frac{2}{\pi} \int_0^\infty{\frac{xZ^{\prime\prime}(x) - \omega Z^{\prime\prime}(\omega)}{x^2 - \omega^2}dx} # $$ # # The residual error between the predicted and measured impedance can then be used to determine consistency with the Kramers-Kronig relations. # # Practically, however, the 0 to $\infty$ frequency range required for integration can be difficult to measure experimentally, so several other methods have been developed to ensure Kramers-Kronig relations are met: # # - [Measurement models](#Measurement-models) # # - [The Lin-KK method](#The-Lin-KK-method) # #### Measurement models # + import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('../../../') from impedance.circuits import CustomCircuit # + # read data data = np.genfromtxt('../../../data/exampleData.csv', delimiter=',') f = data[:,0] Z = data[:,1] + 1j*data[:,2] mask = f < 1000 f = f[mask] Z = Z[mask] # + N = 10 circuit = 'R_0' initial_guess = [.015] for i in range(N): circuit += f'-p(R_{i % 9 + 1},C_{i % 9 + 1})' initial_guess.append(.03/N) initial_guess.append(10**(3 - 6*i/N)) meas_model = CustomCircuit(initial_guess=initial_guess, circuit=circuit) # + meas_model.fit(f, Z, method='lm') print(meas_model.get_verbose_string()) # + from impedance.plotting import plot_nyquist res_meas_real = (Z - meas_model.predict(f)).real/np.abs(Z) res_meas_imag = (Z - meas_model.predict(f)).imag/np.abs(Z) fig = plt.figure(figsize=(5,8)) gs = fig.add_gridspec(3, 1) ax1 = fig.add_subplot(gs[:2,:]) ax2 = fig.add_subplot(gs[2,:]) # plot original data plot_nyquist(ax1, f, Z, fmt='s') # plot measurement model plot_nyquist(ax1, f, meas_model.predict(f), fmt='-', scale=1e3, units='\Omega') ax1.legend(['Data', 'Measurement model'], loc=2, fontsize=12) # Plot residuals ax2.plot(f, res_meas_real, '-', label=r'$\Delta_{\mathrm{Real}}$') ax2.plot(f, res_meas_imag, '-', label=r'$\Delta_{\mathrm{Imag}}$') ax2.set_title('Measurement Model Error', fontsize=14) ax2.tick_params(axis='both', which='major', labelsize=12) ax2.set_ylabel('$\Delta$ $(\%)$', fontsize=14) ax2.set_xlabel('$f$ [Hz]', fontsize=14) ax2.set_xscale('log') ax2.set_ylim(-.1, .1) ax2.legend(loc=1, fontsize=14, ncol=2) vals = ax2.get_yticks() ax2.set_yticklabels(['{:.0%}'.format(x) for x in vals]) plt.tight_layout() plt.show() # - # #### The Lin-KK method # The lin-KK method from Schönleber et al. [1] is a quick test for checking the validity of EIS data. The validity of an impedance spectrum is analyzed by its reproducibility by a Kramers-Kronig (KK) compliant equivalent circuit. In particular, the model used in the lin-KK test is an ohmic resistor, $R_{Ohm}$, and $M$ RC elements. # # $$ # \hat Z = R_{Ohm} + \sum_{k=1}^{M} \frac{R_k}{1 + j \omega \tau_k} # $$ # # The $M$ time constants, $\tau_k$, are distributed logarithmically, # # $$ # \tau_1 = \frac{1}{\omega_{max}} ; \tau_M = \frac{1}{\omega_{min}} # ; \tau_k = 10^{\log{(\tau_{min}) + \frac{k-1}{M-1}\log{{( # \frac{\tau_{max}}{\tau_{min}}}})}} # $$ # # and are not fit during the test (only $R_{Ohm}$ and $R_{k}$ are free parameters). # # In order to prevent under- or over-fitting, Schönleber et al. propose using the ratio of positive resistor mass to negative resistor mass as a metric for finding the optimal number of RC elements. # # $$ # \mu = 1 - \frac{\sum_{R_k \ge 0} |R_k|}{\sum_{R_k < 0} |R_k|} # $$ # # The argument `c` defines the cutoff value for $\mu$. The algorithm starts at `M = 3` and iterates up to `max_M` until a $\mu < c$ is reached. The default of 0.85 is simply a heuristic value based off of the experience of Schönleber et al. # # If the argument `c` is `None`, then the automatic determination of RC elements is turned off and the solution is calculated for `max_M` RC elements. This manual mode should be used with caution as under- and over-fitting should be avoided. # # # [1] <NAME> al. A Method for Improving the Robustness of linear Kramers-Kronig Validity Tests. Electrochimica Acta 131, 20–27 (2014) [doi: 10.1016/j.electacta.2014.01.034](https://doi.org/10.1016/j.electacta.2014.01.034). # # + import matplotlib.pyplot as plt import numpy as np import sys sys.path.append('../../../') from impedance.validation import linKK # + # read data data = np.genfromtxt('../../../data/exampleData.csv', delimiter=',') f = data[:,0] Z = data[:,1] + 1j*data[:,2] mask = f < 1000 f = f[mask] Z = Z[mask] # + M, mu, Z_linKK, res_real, res_imag = linKK(f, Z, max_M=100) print('\nCompleted Lin-KK Fit\nM = {:d}\nmu = {:.2f}'.format(M, mu)) # + from impedance.plotting import plot_nyquist fig = plt.figure(figsize=(5,8)) gs = fig.add_gridspec(3, 1) ax1 = fig.add_subplot(gs[:2,:]) ax2 = fig.add_subplot(gs[2,:]) # plot original data plot_nyquist(ax1, f, Z, fmt='s') # plot measurement model plot_nyquist(ax1, f, Z_linKK, fmt='-', scale=1e3, units='\Omega') ax1.legend(['Data', 'Lin-KK model'], loc=2, fontsize=12) # Plot residuals ax2.plot(f, res_real, '-', label=r'$\Delta_{\mathrm{Real}}$') ax2.plot(f, res_imag, '-', label=r'$\Delta_{\mathrm{Imag}}$') ax2.set_title('Lin-KK Model Error', fontsize=14) ax2.tick_params(axis='both', which='major', labelsize=12) ax2.set_ylabel('$\Delta$ $(\%)$', fontsize=14) ax2.set_xlabel('$f$ [Hz]', fontsize=14) ax2.set_xscale('log') ax2.set_ylim(-.1, .1) ax2.legend(loc=1, fontsize=14, ncol=2) vals = ax2.get_yticks() ax2.set_yticklabels(['{:.0%}'.format(x) for x in vals]) plt.tight_layout() plt.show()
docs/source/examples/validation_example.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/GeneChuang0706/Deploying-Flask-To-Heroku/blob/master/Disco_Diffusion.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="TitleTop" # # Disco Diffusion v5.2 - Now with VR Mode # # In case of confusion, Disco is the name of this notebook edit. The diffusion model in use is Katherine Crowson's fine-tuned 512x512 model # # For issues, join the [Disco Diffusion Discord](https://discord.gg/msEZBy4HxA) or message us on twitter at [@somnai_dreams](https://twitter.com/somnai_dreams) or [@gandamu](https://twitter.com/gandamu_ml) # + [markdown] id="CreditsChTop" # ### Credits & Changelog ⬇️ # + [markdown] id="Credits" # #### Credits # # Original notebook by <NAME> (https://github.com/crowsonkb, https://twitter.com/RiversHaveWings). It uses either OpenAI's 256x256 unconditional ImageNet or Katherine Crowson's fine-tuned 512x512 diffusion model (https://github.com/openai/guided-diffusion), together with CLIP (https://github.com/openai/CLIP) to connect text prompts with images. # # Modified by <NAME> (https://github.com/russelldc, https://twitter.com/danielrussruss) to include (hopefully) optimal params for quick generations in 15-100 timesteps rather than 1000, as well as more robust augmentations. # # Further improvements from Dango233 and nsheppard helped improve the quality of diffusion in general, and especially so for shorter runs like this notebook aims to achieve. # # Vark added code to load in multiple Clip models at once, which all prompts are evaluated against, which may greatly improve accuracy. # # The latest zoom, pan, rotation, and keyframes features were taken from Chigozie Nri's VQGAN Zoom Notebook (https://github.com/chigozienri, https://twitter.com/chigozienri) # # Advanced DangoCutn Cutout method is also from Dango223. # # -- # # Disco: # # Somnai (https://twitter.com/Somnai_dreams) added Diffusion Animation techniques, QoL improvements and various implementations of tech and techniques, mostly listed in the changelog below. # # 3D animation implementation added by <NAME> (https://twitter.com/gandamu_ml) in collaboration with Somnai. Creation of disco.py and ongoing maintenance. # # Turbo feature by <NAME> (https://twitter.com/zippy731) # # Improvements to ability to run on local systems, Windows support, and dependency installation by HostsServer (https://twitter.com/HostsServer) # # VR Mode by <NAME> (https://twitter.com/nin_artificial) # + [markdown] id="LicenseTop" # #### License # + [markdown] id="License" # Licensed under the MIT License # # Copyright (c) 2021 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # -- # # MIT License # # Copyright (c) 2019 Intel ISL (Intel Intelligent Systems Lab) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # -- # # Licensed under the MIT License # # Copyright (c) 2021 <NAME> # # Copyright (c) 2022 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # + [markdown] id="ChangelogTop" # #### Changelog # + cellView="form" id="Changelog" #@title <- View Changelog skip_for_run_all = True #@param {type: 'boolean'} if skip_for_run_all == False: print( ''' v1 Update: Oct 29th 2021 - Somnai QoL improvements added by Somnai (@somnai_dreams), including user friendly UI, settings+prompt saving and improved google drive folder organization. v1.1 Update: Nov 13th 2021 - Somnai Now includes sizing options, intermediate saves and fixed image prompts and perlin inits. unexposed batch option since it doesn't work v2 Update: Nov 22nd 2021 - Somnai Initial addition of Katherine Crowson's Secondary Model Method (https://colab.research.google.com/drive/1mpkrhOjoyzPeSWy2r7T8EYRaU7amYOOi#scrollTo=X5gODNAMEUCR) Noticed settings were saving with the wrong name so corrected it. Let me know if you preferred the old scheme. v3 Update: Dec 24th 2021 - Somnai Implemented Dango's advanced cutout method Added SLIP models, thanks to NeuralDivergent Fixed issue with NaNs resulting in black images, with massive help and testing from @Softology Perlin now changes properly within batches (not sure where this perlin_regen code came from originally, but thank you) v4 Update: Jan 2022 - Somnai Implemented Diffusion Zooming Added Chigozie keyframing Made a bunch of edits to processes v4.1 Update: Jan 14th 2022 - Somnai Added video input mode Added license that somehow went missing Added improved prompt keyframing, fixed image_prompts and multiple prompts Improved UI Significant under the hood cleanup and improvement Refined defaults for each mode Added latent-diffusion SuperRes for sharpening Added resume run mode v4.9 Update: Feb 5th 2022 - gandamu / Adam Letts Added 3D Added brightness corrections to prevent animation from steadily going dark over time v4.91 Update: Feb 19th 2022 - gandamu / Adam Letts Cleaned up 3D implementation and made associated args accessible via Colab UI elements v4.92 Update: Feb 20th 2022 - gandamu / Adam Letts Separated transform code v5.01 Update: Mar 10th 2022 - gandamu / Adam Letts IPython magic commands replaced by Python code v5.1 Update: Mar 30th 2022 - zippy / <NAME> and gandamu / Adam Letts Integrated Turbo+Smooth features from Disco Diffusion Turbo -- just the implementation, without its defaults. Implemented resume of turbo animations in such a way that it's now possible to resume from different batch folders and batch numbers. 3D rotation parameter units are now degrees (rather than radians) Corrected name collision in sampling_mode (now diffusion_sampling_mode for plms/ddim, and sampling_mode for 3D transform sampling) Added video_init_seed_continuity option to make init video animations more continuous v5.1 Update: Apr 4th 2022 - MSFTserver aka HostsServer Removed pytorch3d from needing to be compiled with a lite version specifically made for Disco Diffusion Remove Super Resolution Remove SLIP Models Update for crossplatform support v5.2 Update: Apr 10th 2022 - nin_artificial / <NAME> VR Mode ''' ) # + [markdown] id="TutorialTop" # # Tutorial # + [markdown] id="DiffusionSet" # **Diffusion settings (Defaults are heavily outdated)** # --- # Disco Diffusion is complex, and continually evolving with new features. The most current documentation on on Disco Diffusion settings can be found in the unofficial guidebook: # # [Zippy's Disco Diffusion Cheatsheet](https://docs.google.com/document/d/1l8s7uS2dGqjztYSjPpzlmXLjl5PM3IGkRWI3IiCuK7g/edit) # # We also encourage users to join the [Disco Diffusion User Discord](https://discord.gg/XGZrFFCRfN) to learn from the active user community. # # This section below is outdated as of v2 # # Setting | Description | Default # --- | --- | --- # **Your vision:** # `text_prompts` | A description of what you'd like the machine to generate. Think of it like writing the caption below your image on a website. | N/A # `image_prompts` | Think of these images more as a description of their contents. | N/A # **Image quality:** # `clip_guidance_scale` | Controls how much the image should look like the prompt. | 1000 # `tv_scale` | Controls the smoothness of the final output. | 150 # `range_scale` | Controls how far out of range RGB values are allowed to be. | 150 # `sat_scale` | Controls how much saturation is allowed. From nshepperd's JAX notebook. | 0 # `cutn` | Controls how many crops to take from the image. | 16 # `cutn_batches` | Accumulate CLIP gradient from multiple batches of cuts. | 2 # **Init settings:** # `init_image` | URL or local path | None # `init_scale` | This enhances the effect of the init image, a good value is 1000 | 0 # `skip_steps` | Controls the starting point along the diffusion timesteps | 0 # `perlin_init` | Option to start with random perlin noise | False # `perlin_mode` | ('gray', 'color') | 'mixed' # **Advanced:** # `skip_augs` | Controls whether to skip torchvision augmentations | False # `randomize_class` | Controls whether the imagenet class is randomly changed each iteration | True # `clip_denoised` | Determines whether CLIP discriminates a noisy or denoised image | False # `clamp_grad` | Experimental: Using adaptive clip grad in the cond_fn | True # `seed` | Choose a random seed and print it at end of run for reproduction | random_seed # `fuzzy_prompt` | Controls whether to add multiple noisy prompts to the prompt losses | False # `rand_mag` | Controls the magnitude of the random noise | 0.1 # `eta` | DDIM hyperparameter | 0.5 # # .. # # **Model settings** # --- # # Setting | Description | Default # --- | --- | --- # **Diffusion:** # `timestep_respacing` | Modify this value to decrease the number of timesteps. | ddim100 # `diffusion_steps` || 1000 # **Diffusion:** # `clip_models` | Models of CLIP to load. Typically the more, the better but they all come at a hefty VRAM cost. | ViT-B/32, ViT-B/16, RN50x4 # + [markdown] id="SetupTop" # # 1. Set Up # + cellView="form" id="CheckGPU" #@title 1.1 Check GPU Status import subprocess simple_nvidia_smi_display = False#@param {type:"boolean"} if simple_nvidia_smi_display: # #!nvidia-smi nvidiasmi_output = subprocess.run(['nvidia-smi', '-L'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(nvidiasmi_output) else: # #!nvidia-smi -i 0 -e 0 nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(nvidiasmi_output) nvidiasmi_ecc_note = subprocess.run(['nvidia-smi', '-i', '0', '-e', '0'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(nvidiasmi_ecc_note) # + cellView="form" id="PrepFolders" #@title 1.2 Prepare Folders import subprocess, os, sys, ipykernel def gitclone(url): res = subprocess.run(['git', 'clone', url], stdout=subprocess.PIPE).stdout.decode('utf-8') print(res) def pipi(modulestr): res = subprocess.run(['pip', 'install', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') print(res) def pipie(modulestr): res = subprocess.run(['git', 'install', '-e', modulestr], stdout=subprocess.PIPE).stdout.decode('utf-8') print(res) def wget(url, outputdir): res = subprocess.run(['wget', url, '-P', f'{outputdir}'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(res) try: from google.colab import drive print("Google Colab detected. Using Google Drive.") is_colab = True #@markdown If you connect your Google Drive, you can save the final image of each run on your drive. google_drive = True #@param {type:"boolean"} #@markdown Click here if you'd like to save the diffusion model checkpoint file to (and/or load from) your Google Drive: save_models_to_google_drive = True #@param {type:"boolean"} except: is_colab = False google_drive = False save_models_to_google_drive = False print("Google Colab not detected.") if is_colab: if google_drive is True: drive.mount('/content/drive') root_path = '/content/drive/MyDrive/AI/Disco_Diffusion' else: root_path = '/content' else: root_path = os.getcwd() import os def createPath(filepath): os.makedirs(filepath, exist_ok=True) initDirPath = f'{root_path}/init_images' createPath(initDirPath) outDirPath = f'{root_path}/images_out' createPath(outDirPath) if is_colab: if google_drive and not save_models_to_google_drive or not google_drive: model_path = '/content/models' createPath(model_path) if google_drive and save_models_to_google_drive: model_path = f'{root_path}/models' createPath(model_path) else: model_path = f'{root_path}/models' createPath(model_path) # libraries = f'{root_path}/libraries' # createPath(libraries) # + cellView="form" id="InstallDeps" #@title ### 1.3 Install, import dependencies and set up runtime devices import pathlib, shutil, os, sys # There are some reports that with a T4 or V100 on Colab, downgrading to a previous version of PyTorch may be necessary. # .. but there are also reports that downgrading breaks them! If you're facing issues, you may want to try uncommenting and running this code. # nvidiasmi_output = subprocess.run(['nvidia-smi'], stdout=subprocess.PIPE).stdout.decode('utf-8') # cards_requiring_downgrade = ["Tesla T4", "V100"] # if is_colab: # if any(cardstr in nvidiasmi_output for cardstr in cards_requiring_downgrade): # print("Downgrading pytorch. This can take a couple minutes ...") # downgrade_pytorch_result = subprocess.run(['pip', 'install', 'torch==1.10.2', 'torchvision==0.11.3', '-q'], stdout=subprocess.PIPE).stdout.decode('utf-8') # print("pytorch downgraded.") #@markdown Check this if you want to use CPU useCPU = False #@param {type:"boolean"} if not is_colab: # If running locally, there's a good chance your env will need this in order to not crash upon np.matmul() or similar operations. os.environ['KMP_DUPLICATE_LIB_OK']='TRUE' PROJECT_DIR = os.path.abspath(os.getcwd()) USE_ADABINS = True if is_colab: if not google_drive: root_path = f'/content' model_path = '/content/models' else: root_path = os.getcwd() model_path = f'{root_path}/models' multipip_res = subprocess.run(['pip', 'install', 'lpips', 'datetime', 'timm', 'ftfy', 'einops', 'pytorch-lightning', 'omegaconf'], stdout=subprocess.PIPE).stdout.decode('utf-8') print(multipip_res) if is_colab: subprocess.run(['apt', 'install', 'imagemagick'], stdout=subprocess.PIPE).stdout.decode('utf-8') try: from CLIP import clip except: if not os.path.exists("CLIP"): gitclone("https://github.com/openai/CLIP") sys.path.append(f'{PROJECT_DIR}/CLIP') try: from guided_diffusion.script_util import create_model_and_diffusion except: if not os.path.exists("guided-diffusion"): gitclone("https://github.com/crowsonkb/guided-diffusion") sys.path.append(f'{PROJECT_DIR}/guided-diffusion') try: from resize_right import resize except: if not os.path.exists("ResizeRight"): gitclone("https://github.com/assafshocher/ResizeRight.git") sys.path.append(f'{PROJECT_DIR}/ResizeRight') try: import py3d_tools except: if not os.path.exists('pytorch3d-lite'): gitclone("https://github.com/MSFTserver/pytorch3d-lite.git") sys.path.append(f'{PROJECT_DIR}/pytorch3d-lite') try: from midas.dpt_depth import DPTDepthModel except: if not os.path.exists('MiDaS'): gitclone("https://github.com/isl-org/MiDaS.git") if not os.path.exists('MiDaS/midas_utils.py'): shutil.move('MiDaS/utils.py', 'MiDaS/midas_utils.py') if not os.path.exists(f'{model_path}/dpt_large-midas-2f21e586.pt'): wget("https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", model_path) sys.path.append(f'{PROJECT_DIR}/MiDaS') try: sys.path.append(PROJECT_DIR) import disco_xform_utils as dxf except: if not os.path.exists("disco-diffusion"): gitclone("https://github.com/alembics/disco-diffusion.git") if not os.path.exists('disco_xform_utils.py'): shutil.move('disco-diffusion/disco_xform_utils.py', 'disco_xform_utils.py') sys.path.append(PROJECT_DIR) import torch from dataclasses import dataclass from functools import partial import cv2 import pandas as pd import gc import io import math import timm from IPython import display import lpips from PIL import Image, ImageOps import requests from glob import glob import json from types import SimpleNamespace from torch import nn from torch.nn import functional as F import torchvision.transforms as T import torchvision.transforms.functional as TF from tqdm.notebook import tqdm from CLIP import clip from resize_right import resize from guided_diffusion.script_util import create_model_and_diffusion, model_and_diffusion_defaults from datetime import datetime import numpy as np import matplotlib.pyplot as plt import random from ipywidgets import Output import hashlib from functools import partial if is_colab: os.chdir('/content') from google.colab import files else: os.chdir(f'{PROJECT_DIR}') from IPython.display import Image as ipyimg from numpy import asarray from einops import rearrange, repeat import torch, torchvision import time from omegaconf import OmegaConf import warnings warnings.filterwarnings("ignore", category=UserWarning) # AdaBins stuff if USE_ADABINS: try: from infer import InferenceHelper except: if not os.path.exists("AdaBins"): gitclone("https://github.com/shariqfarooq123/AdaBins.git") if not os.path.exists(f'{PROJECT_DIR}/pretrained/AdaBins_nyu.pt'): createPath(f'{PROJECT_DIR}/pretrained') wget("https://cloudflare-ipfs.com/ipfs/Qmd2mMnDLWePKmgfS8m6ntAg4nhV5VkUyAydYBp8cWWeB7/AdaBins_nyu.pt", f'{PROJECT_DIR}/pretrained') sys.path.append(f'{PROJECT_DIR}/AdaBins') from infer import InferenceHelper MAX_ADABINS_AREA = 500000 import torch DEVICE = torch.device('cuda:0' if (torch.cuda.is_available() and not useCPU) else 'cpu') print('Using device:', DEVICE) device = DEVICE # At least one of the modules expects this name.. if not useCPU: if torch.cuda.get_device_capability(DEVICE) == (8,0): ## A100 fix thanks to Emad print('Disabling CUDNN for A100 gpu', file=sys.stderr) torch.backends.cudnn.enabled = False # + cellView="form" id="DefMidasFns" #@title ### 1.4 Define Midas functions from midas.dpt_depth import DPTDepthModel from midas.midas_net import MidasNet from midas.midas_net_custom import MidasNet_small from midas.transforms import Resize, NormalizeImage, PrepareForNet # Initialize MiDaS depth model. # It remains resident in VRAM and likely takes around 2GB VRAM. # You could instead initialize it for each frame (and free it after each frame) to save VRAM.. but initializing it is slow. default_models = { "midas_v21_small": f"{model_path}/midas_v21_small-70d6b9c8.pt", "midas_v21": f"{model_path}/midas_v21-f6b98070.pt", "dpt_large": f"{model_path}/dpt_large-midas-2f21e586.pt", "dpt_hybrid": f"{model_path}/dpt_hybrid-midas-501f0c75.pt", "dpt_hybrid_nyu": f"{model_path}/dpt_hybrid_nyu-2ce69ec7.pt",} def init_midas_depth_model(midas_model_type="dpt_large", optimize=True): midas_model = None net_w = None net_h = None resize_mode = None normalization = None print(f"Initializing MiDaS '{midas_model_type}' depth model...") # load network midas_model_path = default_models[midas_model_type] if midas_model_type == "dpt_large": # DPT-Large midas_model = DPTDepthModel( path=midas_model_path, backbone="vitl16_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode = "minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif midas_model_type == "dpt_hybrid": #DPT-Hybrid midas_model = DPTDepthModel( path=midas_model_path, backbone="vitb_rn50_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode="minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif midas_model_type == "dpt_hybrid_nyu": #DPT-Hybrid-NYU midas_model = DPTDepthModel( path=midas_model_path, backbone="vitb_rn50_384", non_negative=True, ) net_w, net_h = 384, 384 resize_mode="minimal" normalization = NormalizeImage(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]) elif midas_model_type == "midas_v21": midas_model = MidasNet(midas_model_path, non_negative=True) net_w, net_h = 384, 384 resize_mode="upper_bound" normalization = NormalizeImage( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) elif midas_model_type == "midas_v21_small": midas_model = MidasNet_small(midas_model_path, features=64, backbone="efficientnet_lite3", exportable=True, non_negative=True, blocks={'expand': True}) net_w, net_h = 256, 256 resize_mode="upper_bound" normalization = NormalizeImage( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) else: print(f"midas_model_type '{midas_model_type}' not implemented") assert False midas_transform = T.Compose( [ Resize( net_w, net_h, resize_target=None, keep_aspect_ratio=True, ensure_multiple_of=32, resize_method=resize_mode, image_interpolation_method=cv2.INTER_CUBIC, ), normalization, PrepareForNet(), ] ) midas_model.eval() if optimize==True: if DEVICE == torch.device("cuda"): midas_model = midas_model.to(memory_format=torch.channels_last) midas_model = midas_model.half() midas_model.to(DEVICE) print(f"MiDaS '{midas_model_type}' depth model initialized.") return midas_model, midas_transform, net_w, net_h, resize_mode, normalization # + cellView="form" id="DefFns" #@title 1.5 Define necessary functions # https://gist.github.com/adefossez/0646dbe9ed4005480a2407c62aac8869 import py3d_tools as p3dT import disco_xform_utils as dxf def interp(t): return 3 * t**2 - 2 * t ** 3 def perlin(width, height, scale=10, device=None): gx, gy = torch.randn(2, width + 1, height + 1, 1, 1, device=device) xs = torch.linspace(0, 1, scale + 1)[:-1, None].to(device) ys = torch.linspace(0, 1, scale + 1)[None, :-1].to(device) wx = 1 - interp(xs) wy = 1 - interp(ys) dots = 0 dots += wx * wy * (gx[:-1, :-1] * xs + gy[:-1, :-1] * ys) dots += (1 - wx) * wy * (-gx[1:, :-1] * (1 - xs) + gy[1:, :-1] * ys) dots += wx * (1 - wy) * (gx[:-1, 1:] * xs - gy[:-1, 1:] * (1 - ys)) dots += (1 - wx) * (1 - wy) * (-gx[1:, 1:] * (1 - xs) - gy[1:, 1:] * (1 - ys)) return dots.permute(0, 2, 1, 3).contiguous().view(width * scale, height * scale) def perlin_ms(octaves, width, height, grayscale, device=device): out_array = [0.5] if grayscale else [0.5, 0.5, 0.5] # out_array = [0.0] if grayscale else [0.0, 0.0, 0.0] for i in range(1 if grayscale else 3): scale = 2 ** len(octaves) oct_width = width oct_height = height for oct in octaves: p = perlin(oct_width, oct_height, scale, device) out_array[i] += p * oct scale //= 2 oct_width *= 2 oct_height *= 2 return torch.cat(out_array) def create_perlin_noise(octaves=[1, 1, 1, 1], width=2, height=2, grayscale=True): out = perlin_ms(octaves, width, height, grayscale) if grayscale: out = TF.resize(size=(side_y, side_x), img=out.unsqueeze(0)) out = TF.to_pil_image(out.clamp(0, 1)).convert('RGB') else: out = out.reshape(-1, 3, out.shape[0]//3, out.shape[1]) out = TF.resize(size=(side_y, side_x), img=out) out = TF.to_pil_image(out.clamp(0, 1).squeeze()) out = ImageOps.autocontrast(out) return out def regen_perlin(): if perlin_mode == 'color': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) elif perlin_mode == 'gray': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) else: init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) del init2 return init.expand(batch_size, -1, -1, -1) def fetch(url_or_path): if str(url_or_path).startswith('http://') or str(url_or_path).startswith('https://'): r = requests.get(url_or_path) r.raise_for_status() fd = io.BytesIO() fd.write(r.content) fd.seek(0) return fd return open(url_or_path, 'rb') def read_image_workaround(path): """OpenCV reads images as BGR, Pillow saves them as RGB. Work around this incompatibility to avoid colour inversions.""" im_tmp = cv2.imread(path) return cv2.cvtColor(im_tmp, cv2.COLOR_BGR2RGB) def parse_prompt(prompt): if prompt.startswith('http://') or prompt.startswith('https://'): vals = prompt.rsplit(':', 2) vals = [vals[0] + ':' + vals[1], *vals[2:]] else: vals = prompt.rsplit(':', 1) vals = vals + ['', '1'][len(vals):] return vals[0], float(vals[1]) def sinc(x): return torch.where(x != 0, torch.sin(math.pi * x) / (math.pi * x), x.new_ones([])) def lanczos(x, a): cond = torch.logical_and(-a < x, x < a) out = torch.where(cond, sinc(x) * sinc(x/a), x.new_zeros([])) return out / out.sum() def ramp(ratio, width): n = math.ceil(width / ratio + 1) out = torch.empty([n]) cur = 0 for i in range(out.shape[0]): out[i] = cur cur += ratio return torch.cat([-out[1:].flip([0]), out])[1:-1] def resample(input, size, align_corners=True): n, c, h, w = input.shape dh, dw = size input = input.reshape([n * c, 1, h, w]) if dh < h: kernel_h = lanczos(ramp(dh / h, 2), 2).to(input.device, input.dtype) pad_h = (kernel_h.shape[0] - 1) // 2 input = F.pad(input, (0, 0, pad_h, pad_h), 'reflect') input = F.conv2d(input, kernel_h[None, None, :, None]) if dw < w: kernel_w = lanczos(ramp(dw / w, 2), 2).to(input.device, input.dtype) pad_w = (kernel_w.shape[0] - 1) // 2 input = F.pad(input, (pad_w, pad_w, 0, 0), 'reflect') input = F.conv2d(input, kernel_w[None, None, None, :]) input = input.reshape([n, c, h, w]) return F.interpolate(input, size, mode='bicubic', align_corners=align_corners) class MakeCutouts(nn.Module): def __init__(self, cut_size, cutn, skip_augs=False): super().__init__() self.cut_size = cut_size self.cutn = cutn self.skip_augs = skip_augs self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=15, translate=(0.1, 0.1)), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomPerspective(distortion_scale=0.4, p=0.7), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.15), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) def forward(self, input): input = T.Pad(input.shape[2]//4, fill=0)(input) sideY, sideX = input.shape[2:4] max_size = min(sideX, sideY) cutouts = [] for ch in range(self.cutn): if ch > self.cutn - self.cutn//4: cutout = input.clone() else: size = int(max_size * torch.zeros(1,).normal_(mean=.8, std=.3).clip(float(self.cut_size/max_size), 1.)) offsetx = torch.randint(0, abs(sideX - size + 1), ()) offsety = torch.randint(0, abs(sideY - size + 1), ()) cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] if not self.skip_augs: cutout = self.augs(cutout) cutouts.append(resample(cutout, (self.cut_size, self.cut_size))) del cutout cutouts = torch.cat(cutouts, dim=0) return cutouts cutout_debug = False padargs = {} class MakeCutoutsDango(nn.Module): def __init__(self, cut_size, Overview=4, InnerCrop = 0, IC_Size_Pow=0.5, IC_Grey_P = 0.2 ): super().__init__() self.cut_size = cut_size self.Overview = Overview self.InnerCrop = InnerCrop self.IC_Size_Pow = IC_Size_Pow self.IC_Grey_P = IC_Grey_P if args.animation_mode == 'None': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.1), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) elif args.animation_mode == 'Video Input': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.5), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=15, translate=(0.1, 0.1)), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomPerspective(distortion_scale=0.4, p=0.7), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.15), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), # T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1), ]) elif args.animation_mode == '2D' or args.animation_mode == '3D': self.augs = T.Compose([ T.RandomHorizontalFlip(p=0.4), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomAffine(degrees=10, translate=(0.05, 0.05), interpolation = T.InterpolationMode.BILINEAR), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.RandomGrayscale(p=0.1), T.Lambda(lambda x: x + torch.randn_like(x) * 0.01), T.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.3), ]) def forward(self, input): cutouts = [] gray = T.Grayscale(3) sideY, sideX = input.shape[2:4] max_size = min(sideX, sideY) min_size = min(sideX, sideY, self.cut_size) l_size = max(sideX, sideY) output_shape = [1,3,self.cut_size,self.cut_size] output_shape_2 = [1,3,self.cut_size+2,self.cut_size+2] pad_input = F.pad(input,((sideY-max_size)//2,(sideY-max_size)//2,(sideX-max_size)//2,(sideX-max_size)//2), **padargs) cutout = resize(pad_input, out_shape=output_shape) if self.Overview>0: if self.Overview<=4: if self.Overview>=1: cutouts.append(cutout) if self.Overview>=2: cutouts.append(gray(cutout)) if self.Overview>=3: cutouts.append(TF.hflip(cutout)) if self.Overview==4: cutouts.append(gray(TF.hflip(cutout))) else: cutout = resize(pad_input, out_shape=output_shape) for _ in range(self.Overview): cutouts.append(cutout) if cutout_debug: if is_colab: TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("/content/cutout_overview0.jpg",quality=99) else: TF.to_pil_image(cutouts[0].clamp(0, 1).squeeze(0)).save("cutout_overview0.jpg",quality=99) if self.InnerCrop >0: for i in range(self.InnerCrop): size = int(torch.rand([])**self.IC_Size_Pow * (max_size - min_size) + min_size) offsetx = torch.randint(0, sideX - size + 1, ()) offsety = torch.randint(0, sideY - size + 1, ()) cutout = input[:, :, offsety:offsety + size, offsetx:offsetx + size] if i <= int(self.IC_Grey_P * self.InnerCrop): cutout = gray(cutout) cutout = resize(cutout, out_shape=output_shape) cutouts.append(cutout) if cutout_debug: if is_colab: TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("/content/cutout_InnerCrop.jpg",quality=99) else: TF.to_pil_image(cutouts[-1].clamp(0, 1).squeeze(0)).save("cutout_InnerCrop.jpg",quality=99) cutouts = torch.cat(cutouts) if skip_augs is not True: cutouts=self.augs(cutouts) return cutouts def spherical_dist_loss(x, y): x = F.normalize(x, dim=-1) y = F.normalize(y, dim=-1) return (x - y).norm(dim=-1).div(2).arcsin().pow(2).mul(2) def tv_loss(input): """L2 total variation loss, as in Mahendran et al.""" input = F.pad(input, (0, 1, 0, 1), 'replicate') x_diff = input[..., :-1, 1:] - input[..., :-1, :-1] y_diff = input[..., 1:, :-1] - input[..., :-1, :-1] return (x_diff**2 + y_diff**2).mean([1, 2, 3]) def range_loss(input): return (input - input.clamp(-1, 1)).pow(2).mean([1, 2, 3]) stop_on_next_loop = False # Make sure GPU memory doesn't get corrupted from cancelling the run mid-way through, allow a full frame to complete TRANSLATION_SCALE = 1.0/200.0 def do_3d_step(img_filepath, frame_num, midas_model, midas_transform): if args.key_frames: translation_x = args.translation_x_series[frame_num] translation_y = args.translation_y_series[frame_num] translation_z = args.translation_z_series[frame_num] rotation_3d_x = args.rotation_3d_x_series[frame_num] rotation_3d_y = args.rotation_3d_y_series[frame_num] rotation_3d_z = args.rotation_3d_z_series[frame_num] print( f'translation_x: {translation_x}', f'translation_y: {translation_y}', f'translation_z: {translation_z}', f'rotation_3d_x: {rotation_3d_x}', f'rotation_3d_y: {rotation_3d_y}', f'rotation_3d_z: {rotation_3d_z}', ) translate_xyz = [-translation_x*TRANSLATION_SCALE, translation_y*TRANSLATION_SCALE, -translation_z*TRANSLATION_SCALE] rotate_xyz_degrees = [rotation_3d_x, rotation_3d_y, rotation_3d_z] print('translation:',translate_xyz) print('rotation:',rotate_xyz_degrees) rotate_xyz = [math.radians(rotate_xyz_degrees[0]), math.radians(rotate_xyz_degrees[1]), math.radians(rotate_xyz_degrees[2])] rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) print("rot_mat: " + str(rot_mat)) next_step_pil = dxf.transform_image_3d(img_filepath, midas_model, midas_transform, DEVICE, rot_mat, translate_xyz, args.near_plane, args.far_plane, args.fov, padding_mode=args.padding_mode, sampling_mode=args.sampling_mode, midas_weight=args.midas_weight) return next_step_pil def do_run(): seed = args.seed print(range(args.start_frame, args.max_frames)) if (args.animation_mode == "3D") and (args.midas_weight > 0.0): midas_model, midas_transform, midas_net_w, midas_net_h, midas_resize_mode, midas_normalization = init_midas_depth_model(args.midas_depth_model) for frame_num in range(args.start_frame, args.max_frames): if stop_on_next_loop: break display.clear_output(wait=True) # Print Frame progress if animation mode is on if args.animation_mode != "None": batchBar = tqdm(range(args.max_frames), desc ="Frames") batchBar.n = frame_num batchBar.refresh() # Inits if not video frames if args.animation_mode != "Video Input": if args.init_image in ['','none', 'None', 'NONE']: init_image = None else: init_image = args.init_image init_scale = args.init_scale skip_steps = args.skip_steps if args.animation_mode == "2D": if args.key_frames: angle = args.angle_series[frame_num] zoom = args.zoom_series[frame_num] translation_x = args.translation_x_series[frame_num] translation_y = args.translation_y_series[frame_num] print( f'angle: {angle}', f'zoom: {zoom}', f'translation_x: {translation_x}', f'translation_y: {translation_y}', ) if frame_num > 0: seed += 1 if resume_run and frame_num == start_frame: img_0 = cv2.imread(batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png") else: img_0 = cv2.imread('prevFrame.png') center = (1*img_0.shape[1]//2, 1*img_0.shape[0]//2) trans_mat = np.float32( [[1, 0, translation_x], [0, 1, translation_y]] ) rot_mat = cv2.getRotationMatrix2D( center, angle, zoom ) trans_mat = np.vstack([trans_mat, [0,0,1]]) rot_mat = np.vstack([rot_mat, [0,0,1]]) transformation_matrix = np.matmul(rot_mat, trans_mat) img_0 = cv2.warpPerspective( img_0, transformation_matrix, (img_0.shape[1], img_0.shape[0]), borderMode=cv2.BORDER_WRAP ) cv2.imwrite('prevFrameScaled.png', img_0) init_image = 'prevFrameScaled.png' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps if args.animation_mode == "3D": if frame_num > 0: seed += 1 if resume_run and frame_num == start_frame: img_filepath = batchFolder+f"/{batch_name}({batchNum})_{start_frame-1:04}.png" if turbo_mode and frame_num > turbo_preroll: shutil.copyfile(img_filepath, 'oldFrameScaled.png') else: img_filepath = '/content/prevFrame.png' if is_colab else 'prevFrame.png' next_step_pil = do_3d_step(img_filepath, frame_num, midas_model, midas_transform) next_step_pil.save('prevFrameScaled.png') ### Turbo mode - skip some diffusions, use 3d morph for clarity and to save time if turbo_mode: if frame_num == turbo_preroll: #start tracking oldframe next_step_pil.save('oldFrameScaled.png')#stash for later blending elif frame_num > turbo_preroll: #set up 2 warped image sequences, old & new, to blend toward new diff image old_frame = do_3d_step('oldFrameScaled.png', frame_num, midas_model, midas_transform) old_frame.save('oldFrameScaled.png') if frame_num % int(turbo_steps) != 0: print('turbo skip this frame: skipping clip diffusion steps') filename = f'{args.batch_name}({args.batchNum})_{frame_num:04}.png' blend_factor = ((frame_num % int(turbo_steps))+1)/int(turbo_steps) print('turbo skip this frame: skipping clip diffusion steps and saving blended frame') newWarpedImg = cv2.imread('prevFrameScaled.png')#this is already updated.. oldWarpedImg = cv2.imread('oldFrameScaled.png') blendedImage = cv2.addWeighted(newWarpedImg, blend_factor, oldWarpedImg,1-blend_factor, 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) next_step_pil.save(f'{img_filepath}') # save it also as prev_frame to feed next iteration if vr_mode: generate_eye_views(TRANSLATION_SCALE,batchFolder,filename,frame_num,midas_model, midas_transform) continue else: #if not a skip frame, will run diffusion and need to blend. oldWarpedImg = cv2.imread('prevFrameScaled.png') cv2.imwrite(f'oldFrameScaled.png',oldWarpedImg)#swap in for blending later print('clip/diff this frame - generate clip diff image') init_image = 'prevFrameScaled.png' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps if args.animation_mode == "Video Input": if not video_init_seed_continuity: seed += 1 init_image = f'{videoFramesFolder}/{frame_num+1:04}.jpg' init_scale = args.frames_scale skip_steps = args.calc_frames_skip_steps loss_values = [] if seed is not None: np.random.seed(seed) random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True target_embeds, weights = [], [] if args.prompts_series is not None and frame_num >= len(args.prompts_series): frame_prompt = args.prompts_series[-1] elif args.prompts_series is not None: frame_prompt = args.prompts_series[frame_num] else: frame_prompt = [] print(args.image_prompts_series) if args.image_prompts_series is not None and frame_num >= len(args.image_prompts_series): image_prompt = args.image_prompts_series[-1] elif args.image_prompts_series is not None: image_prompt = args.image_prompts_series[frame_num] else: image_prompt = [] print(f'Frame {frame_num} Prompt: {frame_prompt}') model_stats = [] for clip_model in clip_models: cutn = 16 model_stat = {"clip_model":None,"target_embeds":[],"make_cutouts":None,"weights":[]} model_stat["clip_model"] = clip_model for prompt in frame_prompt: txt, weight = parse_prompt(prompt) txt = clip_model.encode_text(clip.tokenize(prompt).to(device)).float() if args.fuzzy_prompt: for i in range(25): model_stat["target_embeds"].append((txt + torch.randn(txt.shape).cuda() * args.rand_mag).clamp(0,1)) model_stat["weights"].append(weight) else: model_stat["target_embeds"].append(txt) model_stat["weights"].append(weight) if image_prompt: model_stat["make_cutouts"] = MakeCutouts(clip_model.visual.input_resolution, cutn, skip_augs=skip_augs) for prompt in image_prompt: path, weight = parse_prompt(prompt) img = Image.open(fetch(path)).convert('RGB') img = TF.resize(img, min(side_x, side_y, *img.size), T.InterpolationMode.LANCZOS) batch = model_stat["make_cutouts"](TF.to_tensor(img).to(device).unsqueeze(0).mul(2).sub(1)) embed = clip_model.encode_image(normalize(batch)).float() if fuzzy_prompt: for i in range(25): model_stat["target_embeds"].append((embed + torch.randn(embed.shape).cuda() * rand_mag).clamp(0,1)) weights.extend([weight / cutn] * cutn) else: model_stat["target_embeds"].append(embed) model_stat["weights"].extend([weight / cutn] * cutn) model_stat["target_embeds"] = torch.cat(model_stat["target_embeds"]) model_stat["weights"] = torch.tensor(model_stat["weights"], device=device) if model_stat["weights"].sum().abs() < 1e-3: raise RuntimeError('The weights must not sum to 0.') model_stat["weights"] /= model_stat["weights"].sum().abs() model_stats.append(model_stat) init = None if init_image is not None: init = Image.open(fetch(init_image)).convert('RGB') init = init.resize((args.side_x, args.side_y), Image.LANCZOS) init = TF.to_tensor(init).to(device).unsqueeze(0).mul(2).sub(1) if args.perlin_init: if args.perlin_mode == 'color': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, False) elif args.perlin_mode == 'gray': init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, True) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) else: init = create_perlin_noise([1.5**-i*0.5 for i in range(12)], 1, 1, False) init2 = create_perlin_noise([1.5**-i*0.5 for i in range(8)], 4, 4, True) # init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device) init = TF.to_tensor(init).add(TF.to_tensor(init2)).div(2).to(device).unsqueeze(0).mul(2).sub(1) del init2 cur_t = None def cond_fn(x, t, y=None): with torch.enable_grad(): x_is_NaN = False x = x.detach().requires_grad_() n = x.shape[0] if use_secondary_model is True: alpha = torch.tensor(diffusion.sqrt_alphas_cumprod[cur_t], device=device, dtype=torch.float32) sigma = torch.tensor(diffusion.sqrt_one_minus_alphas_cumprod[cur_t], device=device, dtype=torch.float32) cosine_t = alpha_sigma_to_t(alpha, sigma) out = secondary_model(x, cosine_t[None].repeat([n])).pred fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] x_in = out * fac + x * (1 - fac) x_in_grad = torch.zeros_like(x_in) else: my_t = torch.ones([n], device=device, dtype=torch.long) * cur_t out = diffusion.p_mean_variance(model, x, my_t, clip_denoised=False, model_kwargs={'y': y}) fac = diffusion.sqrt_one_minus_alphas_cumprod[cur_t] x_in = out['pred_xstart'] * fac + x * (1 - fac) x_in_grad = torch.zeros_like(x_in) for model_stat in model_stats: for i in range(args.cutn_batches): t_int = int(t.item())+1 #errors on last step without +1, need to find source #when using SLIP Base model the dimensions need to be hard coded to avoid AttributeError: 'VisionTransformer' object has no attribute 'input_resolution' try: input_resolution=model_stat["clip_model"].visual.input_resolution except: input_resolution=224 cuts = MakeCutoutsDango(input_resolution, Overview= args.cut_overview[1000-t_int], InnerCrop = args.cut_innercut[1000-t_int], IC_Size_Pow=args.cut_ic_pow, IC_Grey_P = args.cut_icgray_p[1000-t_int] ) clip_in = normalize(cuts(x_in.add(1).div(2))) image_embeds = model_stat["clip_model"].encode_image(clip_in).float() dists = spherical_dist_loss(image_embeds.unsqueeze(1), model_stat["target_embeds"].unsqueeze(0)) dists = dists.view([args.cut_overview[1000-t_int]+args.cut_innercut[1000-t_int], n, -1]) losses = dists.mul(model_stat["weights"]).sum(2).mean(0) loss_values.append(losses.sum().item()) # log loss, probably shouldn't do per cutn_batch x_in_grad += torch.autograd.grad(losses.sum() * clip_guidance_scale, x_in)[0] / cutn_batches tv_losses = tv_loss(x_in) if use_secondary_model is True: range_losses = range_loss(out) else: range_losses = range_loss(out['pred_xstart']) sat_losses = torch.abs(x_in - x_in.clamp(min=-1,max=1)).mean() loss = tv_losses.sum() * tv_scale + range_losses.sum() * range_scale + sat_losses.sum() * sat_scale if init is not None and init_scale: init_losses = lpips_model(x_in, init) loss = loss + init_losses.sum() * init_scale x_in_grad += torch.autograd.grad(loss, x_in)[0] if torch.isnan(x_in_grad).any()==False: grad = -torch.autograd.grad(x_in, x, x_in_grad)[0] else: # print("NaN'd") x_is_NaN = True grad = torch.zeros_like(x) if args.clamp_grad and x_is_NaN == False: magnitude = grad.square().mean().sqrt() return grad * magnitude.clamp(max=args.clamp_max) / magnitude #min=-0.02, min=-clamp_max, return grad if args.diffusion_sampling_mode == 'ddim': sample_fn = diffusion.ddim_sample_loop_progressive else: sample_fn = diffusion.plms_sample_loop_progressive image_display = Output() for i in range(args.n_batches): if args.animation_mode == 'None': display.clear_output(wait=True) batchBar = tqdm(range(args.n_batches), desc ="Batches") batchBar.n = i batchBar.refresh() print('') display.display(image_display) gc.collect() torch.cuda.empty_cache() cur_t = diffusion.num_timesteps - skip_steps - 1 total_steps = cur_t if perlin_init: init = regen_perlin() if args.diffusion_sampling_mode == 'ddim': samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), clip_denoised=clip_denoised, model_kwargs={}, cond_fn=cond_fn, progress=True, skip_timesteps=skip_steps, init_image=init, randomize_class=randomize_class, eta=eta, ) else: samples = sample_fn( model, (batch_size, 3, args.side_y, args.side_x), clip_denoised=clip_denoised, model_kwargs={}, cond_fn=cond_fn, progress=True, skip_timesteps=skip_steps, init_image=init, randomize_class=randomize_class, order=2, ) # with run_display: # display.clear_output(wait=True) for j, sample in enumerate(samples): cur_t -= 1 intermediateStep = False if args.steps_per_checkpoint is not None: if j % steps_per_checkpoint == 0 and j > 0: intermediateStep = True elif j in args.intermediate_saves: intermediateStep = True with image_display: if j % args.display_rate == 0 or cur_t == -1 or intermediateStep == True: for k, image in enumerate(sample['pred_xstart']): # tqdm.write(f'Batch {i}, step {j}, output {k}:') current_time = datetime.now().strftime('%y%m%d-%H%M%S_%f') percent = math.ceil(j/total_steps*100) if args.n_batches > 0: #if intermediates are saved to the subfolder, don't append a step or percentage to the name if cur_t == -1 and args.intermediates_in_subfolder is True: save_num = f'{frame_num:04}' if animation_mode != "None" else i filename = f'{args.batch_name}({args.batchNum})_{save_num}.png' else: #If we're working with percentages, append it if args.steps_per_checkpoint is not None: filename = f'{args.batch_name}({args.batchNum})_{i:04}-{percent:02}%.png' # Or else, iIf we're working with specific steps, append those else: filename = f'{args.batch_name}({args.batchNum})_{i:04}-{j:03}.png' image = TF.to_pil_image(image.add(1).div(2).clamp(0, 1)) if j % args.display_rate == 0 or cur_t == -1: image.save('progress.png') display.clear_output(wait=True) display.display(display.Image('progress.png')) if args.steps_per_checkpoint is not None: if j % args.steps_per_checkpoint == 0 and j > 0: if args.intermediates_in_subfolder is True: image.save(f'{partialFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') else: if j in args.intermediate_saves: if args.intermediates_in_subfolder is True: image.save(f'{partialFolder}/{filename}') else: image.save(f'{batchFolder}/{filename}') if cur_t == -1: if frame_num == 0: save_settings() if args.animation_mode != "None": image.save('prevFrame.png') image.save(f'{batchFolder}/{filename}') if args.animation_mode == "3D": # If turbo, save a blended image if turbo_mode and frame_num > 0: # Mix new image with prevFrameScaled blend_factor = (1)/int(turbo_steps) newFrame = cv2.imread('prevFrame.png') # This is already updated.. prev_frame_warped = cv2.imread('prevFrameScaled.png') blendedImage = cv2.addWeighted(newFrame, blend_factor, prev_frame_warped, (1-blend_factor), 0.0) cv2.imwrite(f'{batchFolder}/{filename}',blendedImage) else: image.save(f'{batchFolder}/{filename}') if vr_mode: generate_eye_views(TRANSLATION_SCALE, batchFolder, filename, frame_num, midas_model, midas_transform) # if frame_num != args.max_frames-1: # display.clear_output() plt.plot(np.array(loss_values), 'r') def generate_eye_views(trans_scale,batchFolder,filename,frame_num,midas_model, midas_transform): for i in range(2): theta = vr_eye_angle * (math.pi/180) ray_origin = math.cos(theta) * vr_ipd / 2 * (-1.0 if i==0 else 1.0) ray_rotation = (theta if i==0 else -theta) translate_xyz = [-(ray_origin)*trans_scale, 0,0] rotate_xyz = [0, (ray_rotation), 0] rot_mat = p3dT.euler_angles_to_matrix(torch.tensor(rotate_xyz, device=device), "XYZ").unsqueeze(0) transformed_image = dxf.transform_image_3d(f'{batchFolder}/{filename}', midas_model, midas_transform, DEVICE, rot_mat, translate_xyz, args.near_plane, args.far_plane, args.fov, padding_mode=args.padding_mode, sampling_mode=args.sampling_mode, midas_weight=args.midas_weight,spherical=True) eye_file_path = batchFolder+f"/frame_{frame_num:04}" + ('_l' if i==0 else '_r')+'.png' transformed_image.save(eye_file_path) def save_settings(): setting_list = { 'text_prompts': text_prompts, 'image_prompts': image_prompts, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, 'range_scale': range_scale, 'sat_scale': sat_scale, # 'cutn': cutn, 'cutn_batches': cutn_batches, 'max_frames': max_frames, 'interp_spline': interp_spline, # 'rotation_per_frame': rotation_per_frame, 'init_image': init_image, 'init_scale': init_scale, 'skip_steps': skip_steps, # 'zoom_per_frame': zoom_per_frame, 'frames_scale': frames_scale, 'frames_skip_steps': frames_skip_steps, 'perlin_init': perlin_init, 'perlin_mode': perlin_mode, 'skip_augs': skip_augs, 'randomize_class': randomize_class, 'clip_denoised': clip_denoised, 'clamp_grad': clamp_grad, 'clamp_max': clamp_max, 'seed': seed, 'fuzzy_prompt': fuzzy_prompt, 'rand_mag': rand_mag, 'eta': eta, 'width': width_height[0], 'height': width_height[1], 'diffusion_model': diffusion_model, 'use_secondary_model': use_secondary_model, 'steps': steps, 'diffusion_steps': diffusion_steps, 'diffusion_sampling_mode': diffusion_sampling_mode, 'ViTB32': ViTB32, 'ViTB16': ViTB16, 'ViTL14': ViTL14, 'RN101': RN101, 'RN50': RN50, 'RN50x4': RN50x4, 'RN50x16': RN50x16, 'RN50x64': RN50x64, 'cut_overview': str(cut_overview), 'cut_innercut': str(cut_innercut), 'cut_ic_pow': cut_ic_pow, 'cut_icgray_p': str(cut_icgray_p), 'key_frames': key_frames, 'max_frames': max_frames, 'angle': angle, 'zoom': zoom, 'translation_x': translation_x, 'translation_y': translation_y, 'translation_z': translation_z, 'rotation_3d_x': rotation_3d_x, 'rotation_3d_y': rotation_3d_y, 'rotation_3d_z': rotation_3d_z, 'midas_depth_model': midas_depth_model, 'midas_weight': midas_weight, 'near_plane': near_plane, 'far_plane': far_plane, 'fov': fov, 'padding_mode': padding_mode, 'sampling_mode': sampling_mode, 'video_init_path':video_init_path, 'extract_nth_frame':extract_nth_frame, 'video_init_seed_continuity': video_init_seed_continuity, 'turbo_mode':turbo_mode, 'turbo_steps':turbo_steps, 'turbo_preroll':turbo_preroll, } # print('Settings:', setting_list) with open(f"{batchFolder}/{batch_name}({batchNum})_settings.txt", "w+") as f: #save settings json.dump(setting_list, f, ensure_ascii=False, indent=4) # + cellView="form" id="DefSecModel" #@title 1.6 Define the secondary diffusion model def append_dims(x, n): return x[(Ellipsis, *(None,) * (n - x.ndim))] def expand_to_planes(x, shape): return append_dims(x, len(shape)).repeat([1, 1, *shape[2:]]) def alpha_sigma_to_t(alpha, sigma): return torch.atan2(sigma, alpha) * 2 / math.pi def t_to_alpha_sigma(t): return torch.cos(t * math.pi / 2), torch.sin(t * math.pi / 2) @dataclass class DiffusionOutput: v: torch.Tensor pred: torch.Tensor eps: torch.Tensor class ConvBlock(nn.Sequential): def __init__(self, c_in, c_out): super().__init__( nn.Conv2d(c_in, c_out, 3, padding=1), nn.ReLU(inplace=True), ) class SkipBlock(nn.Module): def __init__(self, main, skip=None): super().__init__() self.main = nn.Sequential(*main) self.skip = skip if skip else nn.Identity() def forward(self, input): return torch.cat([self.main(input), self.skip(input)], dim=1) class FourierFeatures(nn.Module): def __init__(self, in_features, out_features, std=1.): super().__init__() assert out_features % 2 == 0 self.weight = nn.Parameter(torch.randn([out_features // 2, in_features]) * std) def forward(self, input): f = 2 * math.pi * input @ self.weight.T return torch.cat([f.cos(), f.sin()], dim=-1) class SecondaryDiffusionImageNet(nn.Module): def __init__(self): super().__init__() c = 64 # The base channel count self.timestep_embed = FourierFeatures(1, 16) self.net = nn.Sequential( ConvBlock(3 + 16, c), ConvBlock(c, c), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c, c * 2), ConvBlock(c * 2, c * 2), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c * 2, c * 4), ConvBlock(c * 4, c * 4), SkipBlock([ nn.AvgPool2d(2), ConvBlock(c * 4, c * 8), ConvBlock(c * 8, c * 4), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 8, c * 4), ConvBlock(c * 4, c * 2), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 4, c * 2), ConvBlock(c * 2, c), nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False), ]), ConvBlock(c * 2, c), nn.Conv2d(c, 3, 3, padding=1), ) def forward(self, input, t): timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) v = self.net(torch.cat([input, timestep_embed], dim=1)) alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) pred = input * alphas - v * sigmas eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) class SecondaryDiffusionImageNet2(nn.Module): def __init__(self): super().__init__() c = 64 # The base channel count cs = [c, c * 2, c * 2, c * 4, c * 4, c * 8] self.timestep_embed = FourierFeatures(1, 16) self.down = nn.AvgPool2d(2) self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) self.net = nn.Sequential( ConvBlock(3 + 16, cs[0]), ConvBlock(cs[0], cs[0]), SkipBlock([ self.down, ConvBlock(cs[0], cs[1]), ConvBlock(cs[1], cs[1]), SkipBlock([ self.down, ConvBlock(cs[1], cs[2]), ConvBlock(cs[2], cs[2]), SkipBlock([ self.down, ConvBlock(cs[2], cs[3]), ConvBlock(cs[3], cs[3]), SkipBlock([ self.down, ConvBlock(cs[3], cs[4]), ConvBlock(cs[4], cs[4]), SkipBlock([ self.down, ConvBlock(cs[4], cs[5]), ConvBlock(cs[5], cs[5]), ConvBlock(cs[5], cs[5]), ConvBlock(cs[5], cs[4]), self.up, ]), ConvBlock(cs[4] * 2, cs[4]), ConvBlock(cs[4], cs[3]), self.up, ]), ConvBlock(cs[3] * 2, cs[3]), ConvBlock(cs[3], cs[2]), self.up, ]), ConvBlock(cs[2] * 2, cs[2]), ConvBlock(cs[2], cs[1]), self.up, ]), ConvBlock(cs[1] * 2, cs[1]), ConvBlock(cs[1], cs[0]), self.up, ]), ConvBlock(cs[0] * 2, cs[0]), nn.Conv2d(cs[0], 3, 3, padding=1), ) def forward(self, input, t): timestep_embed = expand_to_planes(self.timestep_embed(t[:, None]), input.shape) v = self.net(torch.cat([input, timestep_embed], dim=1)) alphas, sigmas = map(partial(append_dims, n=v.ndim), t_to_alpha_sigma(t)) pred = input * alphas - v * sigmas eps = input * sigmas + v * alphas return DiffusionOutput(v, pred, eps) # + [markdown] id="DiffClipSetTop" # # 2. Diffusion and CLIP model settings # + id="ModelSettings" #@markdown ####**Models Settings:** diffusion_model = "512x512_diffusion_uncond_finetune_008100" #@param ["256x256_diffusion_uncond", "512x512_diffusion_uncond_finetune_008100"] use_secondary_model = True #@param {type: 'boolean'} diffusion_sampling_mode = 'ddim' #@param ['plms','ddim'] use_checkpoint = True #@param {type: 'boolean'} ViTB32 = True #@param{type:"boolean"} ViTB16 = True #@param{type:"boolean"} ViTL14 = False #@param{type:"boolean"} RN101 = False #@param{type:"boolean"} RN50 = True #@param{type:"boolean"} RN50x4 = False #@param{type:"boolean"} RN50x16 = False #@param{type:"boolean"} RN50x64 = False #@param{type:"boolean"} #@markdown If you're having issues with model downloads, check this to compare SHA's: check_model_SHA = False #@param{type:"boolean"} def download_models(diffusion_model,use_secondary_model,fallback=False): model_256_downloaded = False model_512_downloaded = False model_secondary_downloaded = False model_256_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' model_512_SHA = '9c111ab89e214862b76e1fa6a1b3f1d329b1a88281885943d2cdbe357ad57648' model_secondary_SHA = '983e3de6f95c88c81b2ca7ebb2c217933be1973b1ff058776b970f901584613a' model_256_link = 'https://openaipublic.blob.core.windows.net/diffusion/jul-2021/256x256_diffusion_uncond.pt' model_512_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/512x512_diffusion_uncond_finetune_008100.pt' model_secondary_link = 'https://v-diffusion.s3.us-west-2.amazonaws.com/secondary_model_imagenet_2.pth' model_256_link_fb = 'https://www.dropbox.com/s/9tqnqo930mpnpcn/256x256_diffusion_uncond.pt' model_512_link_fb = 'https://huggingface.co/lowlevelware/512x512_diffusion_unconditional_ImageNet/resolve/main/512x512_diffusion_uncond_finetune_008100.pt' model_secondary_link_fb = 'https://the-eye.eu/public/AI/models/v-diffusion/secondary_model_imagenet_2.pth' model_256_path = f'{model_path}/256x256_diffusion_uncond.pt' model_512_path = f'{model_path}/512x512_diffusion_uncond_finetune_008100.pt' model_secondary_path = f'{model_path}/secondary_model_imagenet_2.pth' if fallback: model_256_link = model_256_link_fb model_512_link = model_512_link_fb model_secondary_link = model_secondary_link_fb # Download the diffusion model if diffusion_model == '256x256_diffusion_uncond': if os.path.exists(model_256_path) and check_model_SHA: print('Checking 256 Diffusion File') with open(model_256_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_256_SHA: print('256 Model SHA matches') model_256_downloaded = True else: print("256 Model SHA doesn't match, redownloading...") wget(model_256_link, model_path) if os.path.exists(model_256_path): model_256_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,use_secondary_model,True) elif os.path.exists(model_256_path) and not check_model_SHA or model_256_downloaded == True: print('256 Model already downloaded, check check_model_SHA if the file is corrupt') else: wget(model_256_link, model_path) if os.path.exists(model_256_path): model_256_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,True) elif diffusion_model == '512x512_diffusion_uncond_finetune_008100': if os.path.exists(model_512_path) and check_model_SHA: print('Checking 512 Diffusion File') with open(model_512_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_512_SHA: print('512 Model SHA matches') if os.path.exists(model_512_path): model_512_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,use_secondary_model,True) else: print("512 Model SHA doesn't match, redownloading...") wget(model_512_link, model_path) if os.path.exists(model_512_path): model_512_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,use_secondary_model,True) elif os.path.exists(model_512_path) and not check_model_SHA or model_512_downloaded: print('512 Model already downloaded, check check_model_SHA if the file is corrupt') else: wget(model_512_link, model_path) model_512_downloaded = True # Download the secondary diffusion model v2 if use_secondary_model: if os.path.exists(model_secondary_path) and check_model_SHA: print('Checking Secondary Diffusion File') with open(model_secondary_path,"rb") as f: bytes = f.read() hash = hashlib.sha256(bytes).hexdigest(); if hash == model_secondary_SHA: print('Secondary Model SHA matches') model_secondary_downloaded = True else: print("Secondary Model SHA doesn't match, redownloading...") wget(model_secondary_link, model_path) if os.path.exists(model_secondary_path): model_secondary_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,use_secondary_model,True) elif os.path.exists(model_secondary_path) and not check_model_SHA or model_secondary_downloaded: print('Secondary Model already downloaded, check check_model_SHA if the file is corrupt') else: wget(model_secondary_link, model_path) if os.path.exists(model_secondary_path): model_secondary_downloaded = True else: print('First URL Failed using FallBack') download_models(diffusion_model,use_secondary_model,True) download_models(diffusion_model,use_secondary_model) model_config = model_and_diffusion_defaults() if diffusion_model == '512x512_diffusion_uncond_finetune_008100': model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. 'rescale_timesteps': True, 'timestep_respacing': 250, #No need to edit this, it is taken care of later. 'image_size': 512, 'learn_sigma': True, 'noise_schedule': 'linear', 'num_channels': 256, 'num_head_channels': 64, 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, 'use_fp16': not useCPU, 'use_scale_shift_norm': True, }) elif diffusion_model == '256x256_diffusion_uncond': model_config.update({ 'attention_resolutions': '32, 16, 8', 'class_cond': False, 'diffusion_steps': 1000, #No need to edit this, it is taken care of later. 'rescale_timesteps': True, 'timestep_respacing': 250, #No need to edit this, it is taken care of later. 'image_size': 256, 'learn_sigma': True, 'noise_schedule': 'linear', 'num_channels': 256, 'num_head_channels': 64, 'num_res_blocks': 2, 'resblock_updown': True, 'use_checkpoint': use_checkpoint, 'use_fp16': not useCPU, 'use_scale_shift_norm': True, }) model_default = model_config['image_size'] if use_secondary_model: secondary_model = SecondaryDiffusionImageNet2() secondary_model.load_state_dict(torch.load(f'{model_path}/secondary_model_imagenet_2.pth', map_location='cpu')) secondary_model.eval().requires_grad_(False).to(device) clip_models = [] if ViTB32 is True: clip_models.append(clip.load('ViT-B/32', jit=False)[0].eval().requires_grad_(False).to(device)) if ViTB16 is True: clip_models.append(clip.load('ViT-B/16', jit=False)[0].eval().requires_grad_(False).to(device) ) if ViTL14 is True: clip_models.append(clip.load('ViT-L/14', jit=False)[0].eval().requires_grad_(False).to(device) ) if RN50 is True: clip_models.append(clip.load('RN50', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x4 is True: clip_models.append(clip.load('RN50x4', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x16 is True: clip_models.append(clip.load('RN50x16', jit=False)[0].eval().requires_grad_(False).to(device)) if RN50x64 is True: clip_models.append(clip.load('RN50x64', jit=False)[0].eval().requires_grad_(False).to(device)) if RN101 is True: clip_models.append(clip.load('RN101', jit=False)[0].eval().requires_grad_(False).to(device)) normalize = T.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711]) lpips_model = lpips.LPIPS(net='vgg').to(device) # + [markdown] id="SettingsTop" # # 3. Settings # + id="BasicSettings" #@markdown ####**Basic Settings:** batch_name = 'TimeToDisco' #@param{type: 'string'} steps = 250 #@param [25,50,100,150,250,500,1000]{type: 'raw', allow-input: true} width_height = [1280, 768]#@param{type: 'raw'} clip_guidance_scale = 5000 #@param{type: 'number'} tv_scale = 0#@param{type: 'number'} range_scale = 150#@param{type: 'number'} sat_scale = 0#@param{type: 'number'} cutn_batches = 4 #@param{type: 'number'} skip_augs = False#@param{type: 'boolean'} #@markdown --- #@markdown ####**Init Settings:** init_image = None #@param{type: 'string'} init_scale = 1000 #@param{type: 'integer'} skip_steps = 10 #@param{type: 'integer'} #@markdown *Make sure you set skip_steps to ~50% of your steps if you want to use an init image.* #Get corrected sizes side_x = (width_height[0]//64)*64; side_y = (width_height[1]//64)*64; if side_x != width_height[0] or side_y != width_height[1]: print(f'Changing output size to {side_x}x{side_y}. Dimensions must by multiples of 64.') #Update Model Settings timestep_respacing = f'ddim{steps}' diffusion_steps = (1000//steps)*steps if steps < 1000 else steps model_config.update({ 'timestep_respacing': timestep_respacing, 'diffusion_steps': diffusion_steps, }) #Make folder for batch batchFolder = f'{outDirPath}/{batch_name}' createPath(batchFolder) # + [markdown] id="AnimSetTop" # ### Animation Settings # + id="AnimSettings" #@markdown ####**Animation Mode:** animation_mode = 'None' #@param ['None', '2D', '3D', 'Video Input'] {type:'string'} #@markdown *For animation, you probably want to turn `cutn_batches` to 1 to make it quicker.* #@markdown --- #@markdown ####**Video Input Settings:** if is_colab: video_init_path = "/content/training.mp4" #@param {type: 'string'} else: video_init_path = "training.mp4" #@param {type: 'string'} extract_nth_frame = 2 #@param {type: 'number'} video_init_seed_continuity = True #@param {type: 'boolean'} if animation_mode == "Video Input": if is_colab: videoFramesFolder = f'/content/videoFrames' else: videoFramesFolder = f'videoFrames' createPath(videoFramesFolder) print(f"Exporting Video Frames (1 every {extract_nth_frame})...") try: for f in pathlib.Path(f'{videoFramesFolder}').glob('*.jpg'): f.unlink() except: print('') vf = f'select=not(mod(n\,{extract_nth_frame}))' subprocess.run(['ffmpeg', '-i', f'{video_init_path}', '-vf', f'{vf}', '-vsync', 'vfr', '-q:v', '2', '-loglevel', 'error', '-stats', f'{videoFramesFolder}/%04d.jpg'], stdout=subprocess.PIPE).stdout.decode('utf-8') # #!ffmpeg -i {video_init_path} -vf {vf} -vsync vfr -q:v 2 -loglevel error -stats {videoFramesFolder}/%04d.jpg #@markdown --- #@markdown ####**2D Animation Settings:** #@markdown `zoom` is a multiplier of dimensions, 1 is no zoom. #@markdown All rotations are provided in degrees. key_frames = True #@param {type:"boolean"} max_frames = 10000#@param {type:"number"} if animation_mode == "Video Input": max_frames = len(glob(f'{videoFramesFolder}/*.jpg')) interp_spline = 'Linear' #Do not change, currently will not look good. param ['Linear','Quadratic','Cubic']{type:"string"} angle = "0:(0)"#@param {type:"string"} zoom = "0: (1), 10: (1.05)"#@param {type:"string"} translation_x = "0: (0)"#@param {type:"string"} translation_y = "0: (0)"#@param {type:"string"} translation_z = "0: (10.0)"#@param {type:"string"} rotation_3d_x = "0: (0)"#@param {type:"string"} rotation_3d_y = "0: (0)"#@param {type:"string"} rotation_3d_z = "0: (0)"#@param {type:"string"} midas_depth_model = "dpt_large"#@param {type:"string"} midas_weight = 0.3#@param {type:"number"} near_plane = 200#@param {type:"number"} far_plane = 10000#@param {type:"number"} fov = 40#@param {type:"number"} padding_mode = 'border'#@param {type:"string"} sampling_mode = 'bicubic'#@param {type:"string"} #======= TURBO MODE #@markdown --- #@markdown ####**Turbo Mode (3D anim only):** #@markdown (Starts after frame 10,) skips diffusion steps and just uses depth map to warp images for skipped frames. #@markdown Speeds up rendering by 2x-4x, and may improve image coherence between frames. frame_blend_mode smooths abrupt texture changes across 2 frames. #@markdown For different settings tuned for Turbo Mode, refer to the original Disco-Turbo Github: https://github.com/zippy731/disco-diffusion-turbo turbo_mode = False #@param {type:"boolean"} turbo_steps = "3" #@param ["2","3","4","5","6"] {type:"string"} turbo_preroll = 10 # frames #insist turbo be used only w 3d anim. if turbo_mode and animation_mode != '3D': print('=====') print('Turbo mode only available with 3D animations. Disabling Turbo.') print('=====') turbo_mode = False #@markdown --- #@markdown ####**Coherency Settings:** #@markdown `frame_scale` tries to guide the new frame to looking like the old one. A good default is 1500. frames_scale = 1500 #@param{type: 'integer'} #@markdown `frame_skip_steps` will blur the previous frame - higher values will flicker less but struggle to add enough new detail to zoom into. frames_skip_steps = '60%' #@param ['40%', '50%', '60%', '70%', '80%'] {type: 'string'} #======= VR MODE #@markdown --- #@markdown ####**VR Mode (3D anim only):** #@markdown Enables stereo rendering of left/right eye views (supporting Turbo) which use a different (fish-eye) camera projection matrix. #@markdown Note the images you're prompting will work better if they have some inherent wide-angle aspect #@markdown The generated images will need to be combined into left/right videos. These can then be stitched into the VR180 format. #@markdown Google made the VR180 Creator tool but subsequently stopped supporting it. It's available for download in a few places including https://www.patrickgrunwald.de/vr180-creator-download #@markdown The tool is not only good for stitching (videos and photos) but also for adding the correct metadata into existing videos, which is needed for services like YouTube to identify the format correctly. #@markdown Watching YouTube VR videos isn't necessarily the easiest depending on your headset. For instance Oculus have a dedicated media studio and store which makes the files easier to access on a Quest https://creator.oculus.com/manage/mediastudio/ #@markdown #@markdown The command to get ffmpeg to concat your frames for each eye is in the form: `ffmpeg -framerate 15 -i frame_%4d_l.png l.mp4` (repeat for r) vr_mode = False #@param {type:"boolean"} #@markdown `vr_eye_angle` is the y-axis rotation of the eyes towards the center vr_eye_angle = 0.5 #@param{type:"number"} #@markdown interpupillary distance (between the eyes) vr_ipd = 5.0 #@param{type:"number"} #insist VR be used only w 3d anim. if vr_mode and animation_mode != '3D': print('=====') print('VR mode only available with 3D animations. Disabling VR.') print('=====') vr_mode = False def parse_key_frames(string, prompt_parser=None): """Given a string representing frame numbers paired with parameter values at that frame, return a dictionary with the frame numbers as keys and the parameter values as the values. Parameters ---------- string: string Frame numbers paired with parameter values at that frame number, in the format 'framenumber1: (parametervalues1), framenumber2: (parametervalues2), ...' prompt_parser: function or None, optional If provided, prompt_parser will be applied to each string of parameter values. Returns ------- dict Frame numbers as keys, parameter values at that frame number as values Raises ------ RuntimeError If the input string does not match the expected format. Examples -------- >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)") {10: 'Apple: 1| Orange: 0', 20: 'Apple: 0| Orange: 1| Peach: 1'} >>> parse_key_frames("10:(Apple: 1| Orange: 0), 20: (Apple: 0| Orange: 1| Peach: 1)", prompt_parser=lambda x: x.lower())) {10: 'apple: 1| orange: 0', 20: 'apple: 0| orange: 1| peach: 1'} """ import re pattern = r'((?P<frame>[0-9]+):[\s]*[\(](?P<param>[\S\s]*?)[\)])' frames = dict() for match_object in re.finditer(pattern, string): frame = int(match_object.groupdict()['frame']) param = match_object.groupdict()['param'] if prompt_parser: frames[frame] = prompt_parser(param) else: frames[frame] = param if frames == {} and len(string) != 0: raise RuntimeError('Key Frame string not correctly formatted') return frames def get_inbetweens(key_frames, integer=False): """Given a dict with frame numbers as keys and a parameter value as values, return a pandas Series containing the value of the parameter at every frame from 0 to max_frames. Any values not provided in the input dict are calculated by linear interpolation between the values of the previous and next provided frames. If there is no previous provided frame, then the value is equal to the value of the next provided frame, or if there is no next provided frame, then the value is equal to the value of the previous provided frame. If no frames are provided, all frame values are NaN. Parameters ---------- key_frames: dict A dict with integer frame numbers as keys and numerical values of a particular parameter as values. integer: Bool, optional If True, the values of the output series are converted to integers. Otherwise, the values are floats. Returns ------- pd.Series A Series with length max_frames representing the parameter values for each frame. Examples -------- >>> max_frames = 5 >>> get_inbetweens({1: 5, 3: 6}) 0 5.0 1 5.0 2 5.5 3 6.0 4 6.0 dtype: float64 >>> get_inbetweens({1: 5, 3: 6}, integer=True) 0 5 1 5 2 5 3 6 4 6 dtype: int64 """ key_frame_series = pd.Series([np.nan for a in range(max_frames)]) for i, value in key_frames.items(): key_frame_series[i] = value key_frame_series = key_frame_series.astype(float) interp_method = interp_spline if interp_method == 'Cubic' and len(key_frames.items()) <=3: interp_method = 'Quadratic' if interp_method == 'Quadratic' and len(key_frames.items()) <= 2: interp_method = 'Linear' key_frame_series[0] = key_frame_series[key_frame_series.first_valid_index()] key_frame_series[max_frames-1] = key_frame_series[key_frame_series.last_valid_index()] # key_frame_series = key_frame_series.interpolate(method=intrp_method,order=1, limit_direction='both') key_frame_series = key_frame_series.interpolate(method=interp_method.lower(),limit_direction='both') if integer: return key_frame_series.astype(int) return key_frame_series def split_prompts(prompts): prompt_series = pd.Series([np.nan for a in range(max_frames)]) for i, prompt in prompts.items(): prompt_series[i] = prompt # prompt_series = prompt_series.astype(str) prompt_series = prompt_series.ffill().bfill() return prompt_series if key_frames: try: angle_series = get_inbetweens(parse_key_frames(angle)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `angle` correctly for key frames.\n" "Attempting to interpret `angle` as " f'"0: ({angle})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) angle = f"0: ({angle})" angle_series = get_inbetweens(parse_key_frames(angle)) try: zoom_series = get_inbetweens(parse_key_frames(zoom)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `zoom` correctly for key frames.\n" "Attempting to interpret `zoom` as " f'"0: ({zoom})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) zoom = f"0: ({zoom})" zoom_series = get_inbetweens(parse_key_frames(zoom)) try: translation_x_series = get_inbetweens(parse_key_frames(translation_x)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `translation_x` correctly for key frames.\n" "Attempting to interpret `translation_x` as " f'"0: ({translation_x})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) translation_x = f"0: ({translation_x})" translation_x_series = get_inbetweens(parse_key_frames(translation_x)) try: translation_y_series = get_inbetweens(parse_key_frames(translation_y)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `translation_y` correctly for key frames.\n" "Attempting to interpret `translation_y` as " f'"0: ({translation_y})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) translation_y = f"0: ({translation_y})" translation_y_series = get_inbetweens(parse_key_frames(translation_y)) try: translation_z_series = get_inbetweens(parse_key_frames(translation_z)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `translation_z` correctly for key frames.\n" "Attempting to interpret `translation_z` as " f'"0: ({translation_z})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) translation_z = f"0: ({translation_z})" translation_z_series = get_inbetweens(parse_key_frames(translation_z)) try: rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `rotation_3d_x` correctly for key frames.\n" "Attempting to interpret `rotation_3d_x` as " f'"0: ({rotation_3d_x})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) rotation_3d_x = f"0: ({rotation_3d_x})" rotation_3d_x_series = get_inbetweens(parse_key_frames(rotation_3d_x)) try: rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `rotation_3d_y` correctly for key frames.\n" "Attempting to interpret `rotation_3d_y` as " f'"0: ({rotation_3d_y})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) rotation_3d_y = f"0: ({rotation_3d_y})" rotation_3d_y_series = get_inbetweens(parse_key_frames(rotation_3d_y)) try: rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z)) except RuntimeError as e: print( "WARNING: You have selected to use key frames, but you have not " "formatted `rotation_3d_z` correctly for key frames.\n" "Attempting to interpret `rotation_3d_z` as " f'"0: ({rotation_3d_z})"\n' "Please read the instructions to find out how to use key frames " "correctly.\n" ) rotation_3d_z = f"0: ({rotation_3d_z})" rotation_3d_z_series = get_inbetweens(parse_key_frames(rotation_3d_z)) else: angle = float(angle) zoom = float(zoom) translation_x = float(translation_x) translation_y = float(translation_y) translation_z = float(translation_z) rotation_3d_x = float(rotation_3d_x) rotation_3d_y = float(rotation_3d_y) rotation_3d_z = float(rotation_3d_z) # + [markdown] id="ExtraSetTop" # ### Extra Settings # Partial Saves, Advanced Settings, Cutn Scheduling # + id="ExtraSettings" #@markdown ####**Saving:** intermediate_saves = 0#@param{type: 'raw'} intermediates_in_subfolder = True #@param{type: 'boolean'} #@markdown Intermediate steps will save a copy at your specified intervals. You can either format it as a single integer or a list of specific steps #@markdown A value of `2` will save a copy at 33% and 66%. 0 will save none. #@markdown A value of `[5, 9, 34, 45]` will save at steps 5, 9, 34, and 45. (Make sure to include the brackets) if type(intermediate_saves) is not list: if intermediate_saves: steps_per_checkpoint = math.floor((steps - skip_steps - 1) // (intermediate_saves+1)) steps_per_checkpoint = steps_per_checkpoint if steps_per_checkpoint > 0 else 1 print(f'Will save every {steps_per_checkpoint} steps') else: steps_per_checkpoint = steps+10 else: steps_per_checkpoint = None if intermediate_saves and intermediates_in_subfolder is True: partialFolder = f'{batchFolder}/partials' createPath(partialFolder) #@markdown --- #@markdown ####**Advanced Settings:** #@markdown *There are a few extra advanced settings available if you double click this cell.* #@markdown *Perlin init will replace your init, so uncheck if using one.* perlin_init = False #@param{type: 'boolean'} perlin_mode = 'mixed' #@param ['mixed', 'color', 'gray'] set_seed = 'random_seed' #@param{type: 'string'} eta = 0.8#@param{type: 'number'} clamp_grad = True #@param{type: 'boolean'} clamp_max = 0.05 #@param{type: 'number'} ### EXTRA ADVANCED SETTINGS: randomize_class = True clip_denoised = False fuzzy_prompt = False rand_mag = 0.05 #@markdown --- #@markdown ####**Cutn Scheduling:** #@markdown Format: `[40]*400+[20]*600` = 40 cuts for the first 400 /1000 steps, then 20 for the last 600/1000 #@markdown cut_overview and cut_innercut are cumulative for total cutn on any given step. Overview cuts see the entire image and are good for early structure, innercuts are your standard cutn. cut_overview = "[12]*400+[4]*600" #@param {type: 'string'} cut_innercut ="[4]*400+[12]*600"#@param {type: 'string'} cut_ic_pow = 1#@param {type: 'number'} cut_icgray_p = "[0.2]*400+[0]*600"#@param {type: 'string'} # + [markdown] id="PromptsTop" # ### Prompts # `animation_mode: None` will only use the first set. `animation_mode: 2D / Video` will run through them per the set frames and hold on the last one. # + id="Prompts" text_prompts = { 0: ["A beautiful painting of a singular lighthouse, shining its light across a tumultuous sea of blood by <NAME> and <NAME>, Trending on artstation.", "yellow color scheme"], 100: ["This set of prompts start at frame 100","This prompt has weight five:5"], } image_prompts = { # 0:['ImagePromptsWorkButArentVeryGood.png:2',], } # + [markdown] id="DiffuseTop" # # 4. Diffuse! # + id="DoTheRun" #@title Do the Run! #@markdown `n_batches` ignored with animation modes. display_rate = 50 #@param{type: 'number'} n_batches = 50 #@param{type: 'number'} #Update Model Settings timestep_respacing = f'ddim{steps}' diffusion_steps = (1000//steps)*steps if steps < 1000 else steps model_config.update({ 'timestep_respacing': timestep_respacing, 'diffusion_steps': diffusion_steps, }) batch_size = 1 def move_files(start_num, end_num, old_folder, new_folder): for i in range(start_num, end_num): old_file = old_folder + f'/{batch_name}({batchNum})_{i:04}.png' new_file = new_folder + f'/{batch_name}({batchNum})_{i:04}.png' os.rename(old_file, new_file) #@markdown --- resume_run = False #@param{type: 'boolean'} run_to_resume = 'latest' #@param{type: 'string'} resume_from_frame = 'latest' #@param{type: 'string'} retain_overwritten_frames = False #@param{type: 'boolean'} if retain_overwritten_frames: retainFolder = f'{batchFolder}/retained' createPath(retainFolder) skip_step_ratio = int(frames_skip_steps.rstrip("%")) / 100 calc_frames_skip_steps = math.floor(steps * skip_step_ratio) if steps <= calc_frames_skip_steps: sys.exit("ERROR: You can't skip more steps than your total steps") if resume_run: if run_to_resume == 'latest': try: batchNum except: batchNum = len(glob(f"{batchFolder}/{batch_name}(*)_settings.txt"))-1 else: batchNum = int(run_to_resume) if resume_from_frame == 'latest': start_frame = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) else: start_frame = int(resume_from_frame)+1 if animation_mode != '3D' and turbo_mode == True and start_frame > turbo_preroll and start_frame % int(turbo_steps) != 0: start_frame = start_frame - (start_frame % int(turbo_steps)) if retain_overwritten_frames is True: existing_frames = len(glob(batchFolder+f"/{batch_name}({batchNum})_*.png")) frames_to_save = existing_frames - start_frame print(f'Moving {frames_to_save} frames to the Retained folder') move_files(start_frame, existing_frames, batchFolder, retainFolder) else: start_frame = 0 batchNum = len(glob(batchFolder+"/*.txt")) while os.path.isfile(f"{batchFolder}/{batch_name}({batchNum})_settings.txt") or os.path.isfile(f"{batchFolder}/{batch_name}-{batchNum}_settings.txt"): batchNum += 1 print(f'Starting Run: {batch_name}({batchNum}) at frame {start_frame}') if set_seed == 'random_seed': random.seed() seed = random.randint(0, 2**32) # print(f'Using seed: {seed}') else: seed = int(set_seed) args = { 'batchNum': batchNum, 'prompts_series':split_prompts(text_prompts) if text_prompts else None, 'image_prompts_series':split_prompts(image_prompts) if image_prompts else None, 'seed': seed, 'display_rate':display_rate, 'n_batches':n_batches if animation_mode == 'None' else 1, 'batch_size':batch_size, 'batch_name': batch_name, 'steps': steps, 'diffusion_sampling_mode': diffusion_sampling_mode, 'width_height': width_height, 'clip_guidance_scale': clip_guidance_scale, 'tv_scale': tv_scale, 'range_scale': range_scale, 'sat_scale': sat_scale, 'cutn_batches': cutn_batches, 'init_image': init_image, 'init_scale': init_scale, 'skip_steps': skip_steps, 'side_x': side_x, 'side_y': side_y, 'timestep_respacing': timestep_respacing, 'diffusion_steps': diffusion_steps, 'animation_mode': animation_mode, 'video_init_path': video_init_path, 'extract_nth_frame': extract_nth_frame, 'video_init_seed_continuity': video_init_seed_continuity, 'key_frames': key_frames, 'max_frames': max_frames if animation_mode != "None" else 1, 'interp_spline': interp_spline, 'start_frame': start_frame, 'angle': angle, 'zoom': zoom, 'translation_x': translation_x, 'translation_y': translation_y, 'translation_z': translation_z, 'rotation_3d_x': rotation_3d_x, 'rotation_3d_y': rotation_3d_y, 'rotation_3d_z': rotation_3d_z, 'midas_depth_model': midas_depth_model, 'midas_weight': midas_weight, 'near_plane': near_plane, 'far_plane': far_plane, 'fov': fov, 'padding_mode': padding_mode, 'sampling_mode': sampling_mode, 'angle_series':angle_series, 'zoom_series':zoom_series, 'translation_x_series':translation_x_series, 'translation_y_series':translation_y_series, 'translation_z_series':translation_z_series, 'rotation_3d_x_series':rotation_3d_x_series, 'rotation_3d_y_series':rotation_3d_y_series, 'rotation_3d_z_series':rotation_3d_z_series, 'frames_scale': frames_scale, 'calc_frames_skip_steps': calc_frames_skip_steps, 'skip_step_ratio': skip_step_ratio, 'calc_frames_skip_steps': calc_frames_skip_steps, 'text_prompts': text_prompts, 'image_prompts': image_prompts, 'cut_overview': eval(cut_overview), 'cut_innercut': eval(cut_innercut), 'cut_ic_pow': cut_ic_pow, 'cut_icgray_p': eval(cut_icgray_p), 'intermediate_saves': intermediate_saves, 'intermediates_in_subfolder': intermediates_in_subfolder, 'steps_per_checkpoint': steps_per_checkpoint, 'perlin_init': perlin_init, 'perlin_mode': perlin_mode, 'set_seed': set_seed, 'eta': eta, 'clamp_grad': clamp_grad, 'clamp_max': clamp_max, 'skip_augs': skip_augs, 'randomize_class': randomize_class, 'clip_denoised': clip_denoised, 'fuzzy_prompt': fuzzy_prompt, 'rand_mag': rand_mag, } args = SimpleNamespace(**args) print('Prepping model...') model, diffusion = create_model_and_diffusion(**model_config) model.load_state_dict(torch.load(f'{model_path}/{diffusion_model}.pt', map_location='cpu')) model.requires_grad_(False).eval().to(device) for name, param in model.named_parameters(): if 'qkv' in name or 'norm' in name or 'proj' in name: param.requires_grad_() if model_config['use_fp16']: model.convert_to_fp16() gc.collect() torch.cuda.empty_cache() try: do_run() except KeyboardInterrupt: pass finally: print('Seed used:', seed) gc.collect() torch.cuda.empty_cache() # + [markdown] id="CreateVidTop" # # 5. Create the video # + id="CreateVid" # @title ### **Create video** #@markdown Video file will save in the same folder as your images. skip_video_for_run_all = True #@param {type: 'boolean'} if skip_video_for_run_all == True: print('Skipping video creation, uncheck skip_video_for_run_all if you want to run it') else: # import subprocess in case this cell is run without the above cells import subprocess from base64 import b64encode latest_run = batchNum folder = batch_name #@param run = latest_run #@param final_frame = 'final_frame' init_frame = 1#@param {type:"number"} This is the frame where the video will start last_frame = final_frame#@param {type:"number"} You can change i to the number of the last frame you want to generate. It will raise an error if that number of frames does not exist. fps = 12#@param {type:"number"} # view_video_in_cell = True #@param {type: 'boolean'} frames = [] # tqdm.write('Generating video...') if last_frame == 'final_frame': last_frame = len(glob(batchFolder+f"/{folder}({run})_*.png")) print(f'Total frames: {last_frame}') image_path = f"{outDirPath}/{folder}/{folder}({run})_%04d.png" filepath = f"{outDirPath}/{folder}/{folder}({run}).mp4" cmd = [ 'ffmpeg', '-y', '-vcodec', 'png', '-r', str(fps), '-start_number', str(init_frame), '-i', image_path, '-frames:v', str(last_frame+1), '-c:v', 'libx264', '-vf', f'fps={fps}', '-pix_fmt', 'yuv420p', '-crf', '17', '-preset', 'veryslow', filepath ] process = subprocess.Popen(cmd, cwd=f'{batchFolder}', stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() if process.returncode != 0: print(stderr) raise RuntimeError(stderr) else: print("The video is ready and saved to the images folder") # if view_video_in_cell: # mp4 = open(filepath,'rb').read() # data_url = "data:video/mp4;base64," + b64encode(mp4).decode() # display.HTML(f'<video width=400 controls><source src="{data_url}" type="video/mp4"></video>')
Disco_Diffusion.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('/Users/navneethbabra/Documents/Capital-One-SFPD/sfpd-dispatch/sfpd_dispatch_data_subset.csv') df.head() dt = df[['call_type','received_timestamp','dispatch_timestamp','zipcode_of_incident']] dt.head() dt.to_csv('time.csv') df = pd.read_csv('/Users/navneethbabra/Documents/Capital-One-SFPD/time.csv') df.sort_values(['received_timestamp'], ascending = [False]).head() # + from datetime import datetime,timedelta dispatch_times = pd.read_csv('/Users/navneethbabra/Documents/Capital-One-SFPD/time.csv') def createTimeDelta(x): x = str(x) time = datetime.strptime(x,'%H:%M:%S') return timedelta(hours=time.hour,minutes=time.minute,seconds=time.second); # - dispatch_times['dispatch_timestamp'] = dispatch_times['dispatch_timestamp'].apply(createTimeDelta); #creates timedelta objects from timestamp dispatch_times['received_timestamp'] = dispatch_times['received_timestamp'].apply(createTimeDelta); #creates timedelta objects from timestamp dispatch_times['dispatch_time'] = dispatch_times['dispatch_timestamp'] - dispatch_times['received_timestamp'] #substracts timestamps dispatch_times.head() dispatch_times.to_csv('dispatch_times.csv') # + #get tiime sum for all types of incidents Sum1 = timedelta(hours = 0,minutes = 0, seconds=0) Sum2 = timedelta(hours = 0,minutes = 0, seconds=0) Sum3 = timedelta(hours = 0,minutes = 0, seconds=0) Sum4 = timedelta(hours = 0,minutes = 0, seconds=0) Sum5 = timedelta(hours = 0,minutes = 0, seconds=0) Sum6 = timedelta(hours = 0,minutes = 0, seconds=0) Sum7 = timedelta(hours = 0,minutes = 0, seconds=0) Sum8 = timedelta(hours = 0,minutes = 0, seconds=0) Sum9 = timedelta(hours = 0,minutes = 0, seconds=0) Sum10 = timedelta(hours = 0,minutes = 0, seconds=0) Sum11 = timedelta(hours = 0,minutes = 0, seconds=0) Sum12 = timedelta(hours = 0,minutes = 0, seconds=0) Sum13 = timedelta(hours = 0,minutes = 0, seconds=0) Sum14 = timedelta(hours = 0,minutes = 0, seconds=0) Sum15 = timedelta(hours = 0,minutes = 0, seconds=0) Sum16 = timedelta(hours = 0,minutes = 0, seconds=0) Sum17 = timedelta(hours = 0,minutes = 0, seconds=0) Sum18 = timedelta(hours = 0,minutes = 0, seconds=0) Sum19 = timedelta(hours = 0,minutes = 0, seconds=0) Sum20 = timedelta(hours = 0,minutes = 0, seconds=0) Sum21 = timedelta(hours = 0,minutes = 0, seconds=0) Sum22 = timedelta(hours = 0,minutes = 0, seconds=0) Sum23 = timedelta(hours = 0,minutes = 0, seconds=0) Sum24 = timedelta(hours = 0,minutes = 0, seconds=0) Sum25 = timedelta(hours = 0,minutes = 0, seconds=0) Sum26 = timedelta(hours = 0,minutes = 0, seconds=0) Sum27 = timedelta(hours = 0,minutes = 0, seconds=0) for index,row in dispatch_times.iterrows(): if row['zipcode_of_incident'] == 94102: Sum1+=row['dispatch_time'] if row['zipcode_of_incident'] == 94103: Sum2+=row['dispatch_time'] if row['zipcode_of_incident'] == 94107: Sum3+=row['dispatch_time'] if row['zipcode_of_incident'] == 94108: Sum4+=row['dispatch_time'] if row['zipcode_of_incident'] == 94109: Sum5+=row['dispatch_time'] if row['zipcode_of_incident'] == 94110: Sum6+=row['dispatch_time'] if row['zipcode_of_incident'] == 94112: Sum7+=row['dispatch_time'] if row['zipcode_of_incident'] == 94114: Sum8+=row['dispatch_time'] if row['zipcode_of_incident'] == 94115: Sum9+=row['dispatch_time'] if row['zipcode_of_incident'] == 94116: Sum10+=row['dispatch_time'] if row['zipcode_of_incident'] == 94117: Sum11+=row['dispatch_time'] if row['zipcode_of_incident'] == 94118: Sum12+=row['dispatch_time'] if row['zipcode_of_incident'] == 94121: Sum13+=row['dispatch_time'] if row['zipcode_of_incident'] == 94122: Sum14+=row['dispatch_time'] if row['zipcode_of_incident'] == 94123: Sum15+=row['dispatch_time'] if row['zipcode_of_incident'] == 94124: Sum16+=row['dispatch_time'] if row['zipcode_of_incident'] == 94127: Sum17+=row['dispatch_time'] if row['zipcode_of_incident'] == 94131: Sum18+=row['dispatch_time'] if row['zipcode_of_incident'] == 94132: Sum19+=row['dispatch_time'] if row['zipcode_of_incident'] == 94133: Sum20+=row['dispatch_time'] if row['zipcode_of_incident'] == 94134: Sum21+=row['dispatch_time'] if row['zipcode_of_incident'] == 94130: Sum22+=row['dispatch_time'] if row['zipcode_of_incident'] == 94129: Sum23+=row['dispatch_time'] if (row['zipcode_of_incident'] == 94104): Sum24+=row['dispatch_time'] if (row['zipcode_of_incident'] == 94105): Sum25+=row['dispatch_time'] if (row['zipcode_of_incident'] == 94111): Sum26+=row['dispatch_time'] if row['zipcode_of_incident'] == 94158: Sum27+=row['dispatch_time'] # - sumdata = {'call_type':['Medical Incident','Alarms','Structure Fire','Traffic Collision','Other','Gas Leak (Natural and LP Gases','Outside Fire','Electrical Hazard','Vehicle Fire','Citizen Assist / Service Call','Fuel Spill','Smoke Investigation (Outside)','Elevator / Escalator Rescue','Odor (Strange / Unknown)','Water Rescue','Train / Rail Incident','HazMat'], 'time_sum':[medicalIncidentSum, AlarmsSum, StructureFiresSum, TrafficCollisionSum, OtherSum, GasSum, OutsideSum, ElectricalSum, VehicleSum, CitizenSum, FuelSum, SmokeSum, ElevatorSum, OdorSum, WaterSum, TrainSum, HazMatSum]} sumData = pd.DataFrame(sumdata, columns = ['call_type', 'time_sum']) sumData callType = df[['call_type']] callType.head() callType.call_type.value_counts() sumdatazip = {'zipcode_of_incident':[94102,94103,94107,94108,94109,94110,94112,94114,94115,94116,94117,94118,94121,94122,94123,94124,94127,94131,94132,94133,94134,94130,94129,94104,94105,94111,94158], 'zip_sum':[Sum1, Sum2, Sum3, Sum4, Sum5, Sum6, Sum7, Sum8, Sum9, Sum10, Sum11, Sum12, Sum13, Sum14, Sum15, Sum16, Sum17,Sum18,Sum19,Sum20,Sum21,Sum22,Sum23,Sum24,Sum25,Sum26,Sum27]} sumDatazip = pd.DataFrame(sumdatazip, columns = ['zipcode_of_incident', 'zip_sum']) sumDatazip zipcode = df[['zipcode_of_incident']] zipcode.zipcode_of_incident.value_counts() pred = df[['received_timestamp','call_type','unit_type','latitude','longitude','row_id']] pred.head() pred.insert(6,'distance','') pred.head() # + from datetime import datetime pred.view(['received_timestamp'],'int64') # -
jupyter-notebooks/timedate:pred.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 # # Bikeshare Ridership # # Notebook to predict the number of riders per day for a bike share network based on the season of year and the given weather. # # ### Notebook Setup # + import os import sys sys.path.append("/Users/benjamin/Repos/ddl/yellowbrick") import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set_context('notebook') sns.set_style('whitegrid') # - # ## Data Loading data = pd.read_csv('bikeshare.csv') data.head() data.riders.mean() # + from sklearn.model_selection import train_test_split as tts features = [ 'season', 'year', 'month', 'hour', 'holiday', 'weekday', 'workingday', 'weather', 'temp', 'feelslike', 'humidity', 'windspeed', ] target = 'registered' # can be one of 'casual', 'registered', 'riders' X = data[features] y = data[target] X_train, X_test, y_train, y_test = tts(X, y, test_size=0.2) # - # ## Do Some Regression from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import r2_score # + # OLS from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f}".format(r2,me)) # - # L2 and L1 Regularization alphas = np.logspace(-10, 0, 200) # + from sklearn.linear_model import RidgeCV model = RidgeCV(alphas=alphas) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.alpha_)) # + from sklearn.linear_model import LassoCV model = LassoCV(alphas=alphas) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.alpha_)) # + from sklearn.linear_model import ElasticNetCV model = ElasticNetCV(alphas=alphas) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f}".format(r2,me)) # - sns.boxplot(y=target, data=data) # + from sklearn.preprocessing import PolynomialFeatures from sklearn.pipeline import Pipeline model = Pipeline([ ('poly', PolynomialFeatures(2)), ('lasso', LassoCV(alphas=alphas)), ]) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.named_steps['lasso'].alpha_)) # + model = Pipeline([ ('poly', PolynomialFeatures(2)), ('ridge', RidgeCV(alphas=alphas)), ]) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.named_steps['ridge'].alpha_)) # + model = Pipeline([ ('poly', PolynomialFeatures(3)), ('ridge', RidgeCV(alphas=alphas)), ]) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.named_steps['ridge'].alpha_)) # + model = Pipeline([ ('poly', PolynomialFeatures(4)), ('ridge', RidgeCV(alphas=alphas)), ]) model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f} alpha={:0.3f}".format(r2,me, model.named_steps['ridge'].alpha_)) # + from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f}".format(r2,me)) # - # ## Save the Forests! # + import pickle with open('forest-riders.pkl', 'wb') as f: pickle.dump(model, f) # - with open('forest-riders.pkl', 'rb') as f: model = pickle.load(f) model.predict(X_test) # + from sklearn.ensemble import AdaBoostRegressor model = AdaBoostRegressor() model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f}".format(r2,me)) # + from sklearn.linear_model import BayesianRidge model = BayesianRidge() model.fit(X_train, y_train) yhat = model.predict(X_test) r2 = r2_score(y_test, yhat) me = mse(y_test, yhat) print("r2={:0.3f} MSE={:0.3f}".format(r2,me)) # + from sklearn.neighbors import KNeighborsRegressor model = KNeighborsRegressor(5) model.fit(X_train, y_train) model.score(X_test, y_test)
examples/bbengfort/bikeshare/bikeshare.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 random import numpy as np import matplotlib.pyplot as plt from matplotlib import style # %matplotlib inline style.use('seaborn-white') fig = plt.figure() # - def create_plots(): xs = [] ys = [] for i in range(10): x = i y = random.randrange(10) xs.append(x) ys.append(y) return xs, ys # + ax1 = fig.add_subplot(2, 1, 1) ax1.text(0.5, 0.5, str((2, 3, 1)), fontsize=18, ha='center') # + ax2 = fig.add_subplot(2, 1, 2) x,y = create_plots() ax1.plot(x,y) x,y = create_plots() ax2.plot(x,y) # plt.show() # + fig = plt.figure() ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], xticklabels=[], ylim=(-1.2, 1.2)) ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4], ylim=(-1.2, 1.2)) x = np.linspace(0, 10) ax1.plot(np.sin(x)) ax2.plot(np.cos(x)); # - for i in range(1, 7): plt.subplot(2, 3, i) #plt.text(0.5, 0.5, str((2, 3, i)), # fontsize=18, ha='center') plt.plot(x, y) fig = plt.figure() #fig.subplots_adjust(hspace=0.4, wspace=0.4) for i in range(1, 7): ax = fig.add_subplot(2, 3, i) ax.text(0.5, 0.5, str((2, 3, i)), fontsize=18, ha='center')
matplotlib_experiments.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 # --- # ## Install googlesearch # - **Windows** and **Mac** users can install using **anaconda power shell** type:`conda install -c conda-forge googlesearch`, wait for the installer to complete. # - **Linux** users can install using **pip** type: `sudo -H /opt/jupyterhub/bin/python3 -m pip install google`, wait for the installer to complete; if your python kernel is in a different location, then change the install path (the part between -H and -m). If you have a Linux anaconda install, use conda first, if that fails then try pip. # # Once installed, then you can import the package in the cell below, then run it to test the install: import googlesearch # if you get an error message from the cell above, it usually means you did not install the package, read the error to debug the install. # # If successful then here is the rest of the script query = "python for data science" top_level_domain = 'co.in' language = 'en' howmany_hits = 100 # This is used to specify the number of results we desire per search block. search_start = 0 # Begin URL list at this non-404 result search_end = 15 # End URL list at this non-404 result how_long_between_http_requests = 2 # Wait time (in seconds) between consecutive HTTP requests. # If the wait time is too small Google will assume the process is a DoS attack and block your IP address. # # syntax: # search(query, tld=top_level_domain, lang=language, num=howmany_hits, start=search_start, stop=search_end, pause=how_long_between_http_requests) # produces an iterable (list) of valid URLs containing the search string # # + # Add code to prompt user for a search string, and place that string into `query` # Add code to prompt user for how many results to return, put that value into `search_end` limit the value to less than 20 # - for i in googlesearch.search(query, tld=top_level_domain, lang=language, num=howmany_hits, start=search_start, stop=search_end, pause=how_long_between_http_requests): print(i)
4-Databases/google_search.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 # --- # # Assignment 10 # # *Due date: 22.06.2022* # # This week's assignment has to be returned **in the form a jupyter notebook**. # # Don't forget the [instructions](../assignments)! # ## 01 - Maps with cartopy # For this assignment, you'll need to install [cartopy](https://scitools.org.uk/cartopy/docs/latest/index.html) first. # # Your task is to make a map as close as possible to [this one](https://github.com/fmaussion/intro_to_programming/blob/master/book/week_10/station_map.png). It displays the location and elevation of all ZAMG weather stations in Austria. Some pointers to get you on track: # - the location and elevation of all stations is read from the `ZEHNMIN Stations-Metadaten.csv` file that you can download [here](https://github.com/fmaussion/intro_to_programming/raw/master/book/project/ZEHNMIN%20Stations-Metadaten.csv). `pandas` can read it without any problems. # - the map is done with matplotlib and cartopy. I build my map based on elements from the following tutorials from the [official documentation](https://scitools.org.uk/cartopy/docs/latest/gallery/index.html): # - [map tile aquisition](https://scitools.org.uk/cartopy/docs/latest/gallery/scalar_data/eyja_volcano.html#sphx-glr-gallery-scalar-data-eyja-volcano-py) for the map background # - [features](https://scitools.org.uk/cartopy/docs/latest/gallery/lines_and_polygons/features.html#sphx-glr-gallery-lines-and-polygons-features-py) for the country borders # - [grid lines and tick labels](https://scitools.org.uk/cartopy/docs/latest/gallery/scalar_data/eyja_volcano.html#sphx-glr-gallery-scalar-data-eyja-volcano-py) for the lat lon grid # - matplotlib's `ax.scatterplot` as in the [Iceland example](https://scitools.org.uk/cartopy/docs/latest/gallery/scalar_data/eyja_volcano.html#sphx-glr-gallery-scalar-data-eyja-volcano-py) for the station markers and `ax.legend` for the legend. # # It is fine for me if you don't manage to do the exact same map mine needed . You can be creative as well! Any step towards completion is a good step. To help you further, here are all the imports I used for this task: # + import pandas as pd import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.io.img_tiles as cimgt # + # your code here # -
book/week_10/02-Assignment.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 # --- # #### Categorical Variables # # One of the main ways for working with categorical variables is using 0, 1 encodings. In this technique, you create a new column for every level of the categorical variable. The **advantages** of this approach include: # # 1. The ability to have differing influences of each level on the response. # 2. You do not impose a rank of the categories. # 3. The ability to interpret the results more easily than other encodings. # # The **disadvantages** of this approach are that you introduce a large number of effects into your model. If you have a large number of categorical variables or categorical variables with a large number of levels, but not a large sample size, you might not be able to estimate the impact of each of these variables on your response variable. There are some rules of thumb that suggest 10 data points for each variable you add to your model. That is 10 rows for each column. This is a reasonable lower bound, but the larger your sample (assuming it is representative), the better. # # Let's try out adding dummy variables for the categorical variables into the model. We will compare to see the improvement over the original model only using quantitative variables. # # Run the cell below to get started. # + import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error import test1 as t import seaborn as sns # %matplotlib inline df = pd.read_csv('./survey_results_public.csv') #Only use quant variables and drop any rows with missing values num_vars = df[['Salary', 'CareerSatisfaction', 'HoursPerWeek', 'JobSatisfaction', 'StackOverflowSatisfaction']] #Drop the rows with missing salaries drop_sal_df = num_vars.dropna(subset=['Salary'], axis=0) # Mean function fill_mean = lambda col: col.fillna(col.mean()) # Fill the mean fill_df = drop_sal_df.apply(fill_mean, axis=0) #Split into explanatory and response variables X = fill_df[['CareerSatisfaction', 'HoursPerWeek', 'JobSatisfaction', 'StackOverflowSatisfaction']] y = fill_df['Salary'] #Split into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .30, random_state=42) lm_model = LinearRegression(normalize=True) # Instantiate lm_model.fit(X_train, y_train) #Fit #Predict and score the model y_test_preds = lm_model.predict(X_test) "The r-squared score for the model using only quantitative variables was {} on {} values.".format(r2_score(y_test, y_test_preds), len(y_test)) # - # #### Question 1 # # **1.** Use the **df** dataframe. Identify the columns that are categorical in nature. How many of the columns are considered categorical? Use the reference [here](http://pbpython.com/categorical-encoding.html) if you get stuck. # + cat_df = df.select_dtypes(include=['object']) # Subset to a dataframe only holding the categorical columns # Print how many categorical columns are in the dataframe - should be 147 cat_df.shape[1] # - # Test your dataframe matches the solution t.cat_df_check(cat_df) # #### Question 2 # # **2.** Use **cat_df** and the cells below to fill in the dictionary below the correct value for each statement. np.sum(np.sum(cat_df.isnull())/cat_df.shape[0] == 0)# Cell for your work here np.sum(np.sum(cat_df.isnull())/cat_df.shape[0] > .5) np.sum(np.sum(cat_df.isnull())/cat_df.shape[0] > .75) # + # Provide the key as an `integer` that answers the question cat_df_dict = {'the number of columns with no missing values': 6, 'the number of columns with more than half of the column missing': 50, 'the number of columns with more than 75% of the column missing': 13 } # Check your dictionary results t.cat_df_dict_check(cat_df_dict) # - # #### Question 3 # # **3.** For each of the categorical variables, we now need to create dummy columns. However, as we saw above, there are a lot of missing values in the current set of categorical columns. So, you might be wondering, what happens when you dummy a column that has missing values. # # The documentation for creating dummy variables in pandas is available [here](http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.get_dummies.html), but we can also just put this to practice to see what happens. # # First, run the cell below to create a dataset that you will use before moving to the full stackoverflow data. # # After you have created **dummy_var_df**, use the additional cells to fill in the **sol_3_dict** with the correct variables that match each key. # + dummy_var_df = pd.DataFrame({'col1': ['a', 'a', 'b', 'b', 'a', np.nan, 'b', np.nan], 'col2': [1, np.nan, 3, np.nan, 5, 6, 7, 8] }) dummy_var_df # - pd.get_dummies(dummy_var_df['col1'])# Use this cell to write whatever code you need. # + a = 1 b = 2 c = 3 d = 'col1' e = 'col2' f = 'the rows with NaNs are dropped by default' g = 'the NaNs are always encoded as 0' sol_3_dict = {'Which column should you create a dummy variable for?': d, 'When you use the default settings for creating dummy variables, how many are created?': b, 'What happens with the nan values?': g } # Check your dictionary against the solution t.sol_3_dict_check(sol_3_dict) # - # #### Question 4 # # **4.** Notice, you can also use **get_dummies** to encode **NaN** values as their own dummy coded column using the **dummy_na** argument. Often these NaN values are also informative, but you are not capturing them by leaving them as 0 in every column of your model. # # Create a new encoding for **col1** of **dummy_var_df** that provides dummy columns not only for each level, but also for the missing values below. Store the 3 resulting dummy columns in **dummy_cols_df** and check your solution against ours. # + dummy_cols_df = pd.get_dummies(dummy_var_df['col1'], dummy_na=True) #Create the three dummy columns for dummy_var_df # Look at your result dummy_cols_df # - # Check against the solution t.dummy_cols_df_check(dummy_cols_df) # #### Question 5 # # **5.** We could use either of the above to begin creating an X matrix that would (potentially) allow us to predict better than just the numeric columns we have been using thus far. # # First, complete the **create_dummy_df**. Follow the instructions in the document string to assist as necessary. # + #Pull a list of the column names of the categorical variables cat_cols_lst = cat_df.columns def create_dummy_df(df, cat_cols, dummy_na): ''' INPUT: df - pandas dataframe with categorical variables you want to dummy cat_cols - list of strings that are associated with names of the categorical columns dummy_na - Bool holding whether you want to dummy NA vals of categorical columns or not OUTPUT: df - a new dataframe that has the following characteristics: 1. contains all columns that were not specified as categorical 2. removes all the original columns in cat_cols 3. dummy columns for each of the categorical columns in cat_cols 4. if dummy_na is True - it also contains dummy columns for the NaN values 5. Use a prefix of the column name with an underscore (_) for separating ''' df = pd.get_dummies(df,columns=cat_cols,prefix = cat_cols,dummy_na=dummy_na) return df # + #Dropping where the salary has missing values df = df.dropna(subset=['Salary'], axis=0) #Pull a list of the column names of the categorical variables cat_df = df.select_dtypes(include=['object']) cat_cols_lst = cat_df.columns df_new = create_dummy_df(df, cat_cols_lst, dummy_na=False) #Use your newly created function # Show a header of df_new to check print(df_new.shape) # - #check your dataframe against the solution dataframe. t.create_dummy_df_check(df_new) # #### Question 6 # # **6.** Use the document string below to complete the function. Then test your function against the solution. # + def clean_fit_linear_mod(df, response_col, cat_cols, dummy_na, test_size=.3, rand_state=42): ''' INPUT: df - a dataframe holding all the variables of interest response_col - a string holding the name of the column cat_cols - list of strings that are associated with names of the categorical columns dummy_na - Bool holding whether you want to dummy NA vals of categorical columns or not test_size - a float between [0,1] about what proportion of data should be in the test dataset rand_state - an int that is provided as the random state for splitting the data into training and test OUTPUT: test_score - float - r2 score on the test data train_score - float - r2 score on the test data lm_model - model object from sklearn X_train, X_test, y_train, y_test - output from sklearn train test split used for optimal model Your function should: 1. Drop the rows with missing response values 2. Drop columns with NaN for all the values 3. Use create_dummy_df to dummy categorical columns 4. Fill the mean of the column for any missing values 5. Split your data into an X matrix and a response vector y 6. Create training and test sets of data 7. Instantiate a LinearRegression model with normalized data 8. Fit your model to the training data 9. Predict the response for the training data and the test data 10. Obtain an rsquared value for both the training and test data ''' #Drop the rows with missing response values df = df.dropna(subset=[response_col], axis=0) #Drop columns with all NaN values df = df.dropna(how='all', axis=1) #Dummy categorical variables df = create_dummy_df(df, cat_cols, dummy_na) # Mean function fill_mean = lambda col: col.fillna(col.mean()) # Fill the mean df = df.apply(fill_mean, axis=0) #Split into explanatory and response variables X = df.drop(response_col, axis=1) y = df[response_col] #Split into train and test X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=rand_state) lm_model = LinearRegression(normalize=True) # Instantiate lm_model.fit(X_train, y_train) #Fit #Predict using your model y_test_preds = lm_model.predict(X_test) y_train_preds = lm_model.predict(X_train) #Score using your model test_score = r2_score(y_test, y_test_preds) train_score = r2_score(y_train, y_train_preds) return test_score, train_score, lm_model, X_train, X_test, y_train, y_test #Test your function with the above dataset test_score, train_score, lm_model, X_train, X_test, y_train, y_test = clean_fit_linear_mod(df_new, 'Salary', cat_cols_lst, dummy_na=False) # - #Print training and testing score print("The rsquared on the training data was {}. The rsquared on the test data was {}.".format(train_score, test_score)) # Notice how much higher the rsquared value is on the training data than it is on the test data - why do you think that is? # ### This is likely due to `overfitting`!!!
lessons/CRISP_DM/Categorical Variables - Solution.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 import scipy.stats as st import statsmodels.formula.api as smf import statsmodels.api as sm import pingouin as pg # %matplotlib inline data = pd.read_csv('Wii.dat',sep="\t") data.head(10) data['athlete'].unique() data['stretch'].unique() data['wii'].unique() data.groupby(['athlete','stretch','wii'])['injury'].describe() unique_list = [1,2,3,4,5,6,7,8] unique_list data['interaction']=0 for i in range(8): for j in range(15): data.at[15*i+j,'interaction'] = unique_list[i] pg.homoscedasticity(data, dv='injury',group='interaction') contrast_ath = np.array([[1,-1]]) contrast_ath =contrast_ath.reshape(2,1) contrast_ath contrast_str = np.array([[1,-1]]) contrast_str =contrast_str.reshape(2,1) contrast_str contrast_wii = np.array([[1,-1]]) contrast_wii =contrast_wii.reshape(2,1) contrast_wii m01 = smf.ols('injury~C(athlete,contrast_ath)*C(stretch,contrast_str)*C(wii,contrast_wii)',data=data).fit() m01.summary() sm.stats.anova_lm(m01,typ=3) # # **Making barplots and interaction plot** _ = sns.barplot(x='athlete',y='injury',data=data) _ = sns.barplot(x='stretch',y='injury',data=data) _ = sns.barplot(x='wii',y='injury',data=data) from statsmodels.graphics.factorplots import interaction_plot # athlete-stretch , non-significant fig = interaction_plot(data.stretch, data.athlete, data.injury, colors=['red','blue'], markers=['D','^'], ms=10) # athlete-wii, significant fig = interaction_plot(data.wii, data.athlete, data.injury, colors=['red','blue'], markers=['D','^'], ms=10) # stretch-wii , significant fig = interaction_plot(data.wii, data.stretch, data.injury, colors=['red','blue'], markers=['D','^'], ms=10) data_play = data[data['wii']=='Playing Wii'] data_watch = data[data['wii']=='Watching Wii'] data_play.reset_index(inplace=True, drop=True) # seeing the below 2 graph for stretch*wii*athlete interaction and its clear that the this interaction is present from the graph fig = interaction_plot(data_play.stretch, data_play.athlete, data_play.injury, colors=['red','blue'], markers=['D','^'], ms=10) data_watch.reset_index(inplace=True, drop=True) fig = interaction_plot(data_watch.stretch, data_watch.athlete, data_watch.injury, colors=['red','blue'], markers=['D','^'], ms=10) from IPython.display import Image Image('triple_interaction.png') m02 = smf.ols('injury~C(athlete)*C(stretch)*C(wii)',data=data).fit() m02.summary() prediction = pd.DataFrame(m02.fittedvalues) prediction.columns = ['predicted'] prediction.tail() prediction['standarized_prediction'] = (prediction['predicted']-prediction['predicted'].mean())/prediction['predicted'].std() import statsmodels.stats.outliers_influence as sms summary_frame = sms.OLSInfluence(m01).summary_frame() summary_frame = pd.merge(summary_frame, prediction, how = 'inner', left_index = True, right_index = True) _ = sns.scatterplot(y = 'standard_resid', x='standarized_prediction', data = summary_frame) _ = plt.axhline(y=0) _ = pg.qqplot(summary_frame['standard_resid'], confidence=False) # # **<NAME>** data_1 = data[data['interaction']==1] data_2 = data[data['interaction']==2] data_3 = data[data['interaction']==3] data_4 = data[data['interaction']==4] data_5 = data[data['interaction']==5] data_6 = data[data['interaction']==6] data_7 = data[data['interaction']==7] data_8 = data[data['interaction']==8] st.kruskal(data_1['injury'], data_2['injury'], data_3['injury'],data_4['injury'],data_5['injury'],data_6['injury'],data_7['injury'],data_8['injury']) sm.stats.anova_lm(m01,typ=3,robust="hc3")
Python/statistics_with_Python/12_GLM3_FactorialAnova/Smart_Alex/Task5_wii.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="T98Q6eQQjGNJ" # # + [markdown] id="NB-prMD9t-DZ" # # **Image Captioning - DL Assignment2** # # ## Assignment Details # # # # 1. **Group:90**<br> # 2. **Members** # * <NAME> - 2019AD04096 # * <NAME> - 2019AD04061 # * <NAME> - 2019AD04100 # + [markdown] id="9_2RX0BIj3jf" # **Import Libraries/Dataset** # + id="hWunmxED_bqI" import pandas as pd import numpy as np import re import os.path import tensorflow as tf from tensorflow.keras.preprocessing.image import load_img import matplotlib.pyplot as plt import glob from PIL import Image import string import time pd.set_option('display.max_colwidth', None) # + [markdown] id="BYatCzmUj71-" # ### Checking GPU availability # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="GIunmYEvuOwQ" outputId="3e5dc75b-9187-4678-a82b-b57fcdb86f69" print("Version: ", tf.__version__) print("Eager mode: ", tf.executing_eagerly()) print("GPU is", "available" if tf.config.list_physical_devices("GPU") else "NOT AVAILABLE") print("GPU device name:", tf.test.gpu_device_name()) # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="SSpFp1PLIRd6" outputId="ea16311f-279c-482d-f51c-14b1b2c307eb" from google.colab import drive drive.mount('/content/drive') # + [markdown] id="wvbXUR8qvHE9" # ### **Data Visualization and augmentation:** # + [markdown] id="34vO_DGgkGh1" # ##### **Read the pickle file** # + id="physical-aspect" pkl_df = pd.read_pickle("/content/set_4.pkl") # + id="banner-violation" pkl_list=[] for d in pkl_df: pkl_list.append(re.split('#|\t',d,maxsplit=2)) # + id="interested-people" mdf = pd.DataFrame(pkl_list,columns =['ImageName', 'id','Caption']) # + id="mbZEdIHVDUqR" mdf = mdf.groupby(['ImageName']).sum() mdf.drop(columns=['id'],inplace=True) mdf.reset_index(inplace=True) # + colab={"base_uri": "https://localhost:8080/", "height": 252} id="18g5pje4NJnT" outputId="89a8b08b-367e-49b8-9477-4ce4a9a42da1" mdf.head() # + [markdown] id="I_FRZJE_kkQ2" # ### **Image dataset** # + colab={"base_uri": "https://localhost:8080/", "height": 35} id="pyeY0IVaMU_F" outputId="741d7111-e864-4ed7-df1c-014ddcdc3812" import os os.getcwd() # + [markdown] id="lNWi0XZC1cvG" # **Convert the data into the correct format which could be used for ML model.** # + id="shaped-tract" colab={"base_uri": "https://localhost:8080/", "height": 0} outputId="540ff02b-2df0-43b3-e823-da1977acf415" from tqdm import tqdm image_dict = {} for filename in tqdm(glob.glob('*.jpg')): img=load_img(filename,target_size=(224,224)) image_dict[filename]=img # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="K6PcfqbKM48t" outputId="0aa05ff7-0385-4580-dc28-f3a186600b9c" len(image_dict) # + id="fundamental-future" dic={} for i in mdf.ImageName: for j in image_dict: if i in j: dic[i]=image_dict[j] # + id="NlELG3acxJTC" df_test = pd.DataFrame.from_dict(dic,orient='index',columns=['Image']) df_test.reset_index(inplace=True) df_test.rename(columns={'index':'ImageName'},inplace=True) # + id="OPhBJ-a-AJ4Q" main_df = pd.merge(mdf,df_test,on=['ImageName']) # + colab={"base_uri": "https://localhost:8080/", "height": 285} id="6Bu5pSK4B50w" outputId="f6a79266-a86b-4434-a1a7-5e63c40cec00" main_df.head() # + colab={"base_uri": "https://localhost:8080/"} id="HcgGyokMBvJ3" outputId="8d776f5c-9938-416b-dab7-29e8a255a85e" main_df.info() # + [markdown] id="lgI-8lB1oM3c" # ### **Plot at least two samples and their captions (use matplotlib/seaborn/any other library)** # + colab={"base_uri": "https://localhost:8080/", "height": 1277} id="rfFik3-L0iq4" outputId="9969ac61-bd2a-42fc-af4c-f64f17049334" for i in range(len(main_df.head())): print("Caption: "+ str(main_df['Caption'][i].split(".")[:-1])) plt.imshow(main_df['Image'][i]) plt.axis(False) plt.show() # + [markdown] id="vPubkP93vd2E" # ### **Bring the train and test data in the required format** # + id="lNS-hBNQUlTB" image = main_df['Image'] for i in range(len(image)): image[i]=np.asarray(image[i]) # + id="hGRzVL7WiAYn" from sklearn.model_selection import train_test_split # keeping 50% size, as colab session crashes if we increase the train size train, test = train_test_split(main_df, test_size=0.5) # + id="ZJ-hE7BLWYoo" caption_dict={} for i in range(len(train)): caption_dict[train.ImageName.values[i]]=["START "+sent.strip()+" END" for sent in train.Caption.values[i].lower().split(".")][:-1] # + colab={"base_uri": "https://localhost:8080/"} id="ZXU33ppAak6G" outputId="905ccdd2-a43a-44ab-e3a7-eb1b5c7af7ba" caption_dict.get('1000268201_693b08cb0e.jpg') # + id="k7H3zRi3ak4D" count_words = {} count=1 for k,vv in caption_dict.items(): for v in vv: for word in v.split(): if word not in count_words: count_words[word] = count count +=1 # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="v8VWJI3GUmhG" outputId="5b84ad8d-75ff-4d04-a9d7-adff780979dc" len(count_words) # + id="8x24musvchSn" for k,vv in caption_dict.items(): for v in vv: encode=[] for word in v.split(): encode.append(count_words[word]) caption_dict[k][vv.index(v)]=encode # + colab={"base_uri": "https://localhost:8080/"} id="Agy_sGoUchMd" outputId="8d9f2650-f3f9-4481-9446-838814fdda00" caption_dict.get('1000268201_693b08cb0e.jpg') # + [markdown] id="kn5ks2JOu8Qr" # **Model Building** # + [markdown] id="oII7OMnnvvNT" # ##### **Use Pretrained Resnet-50 model trained on ImageNet dataset** # + id="6CVpN3vG5RzQ" colab={"base_uri": "https://localhost:8080/", "height": 0} outputId="fe16ee32-1a29-4599-dded-8ffcab3bec3f" from tensorflow.keras.applications import ResNet50 resnet_model = ResNet50() # + id="V3lOjpn79q6S" from tensorflow.keras.models import Model # + id="roeFPk70OKEc" image_model = Model(inputs=resnet_model.input, outputs=resnet_model.layers[-2].output) # + [markdown] id="s7N5JJo8x-Wg" # ### **Bring the train in the required format.** # + id="KchJW-naQlYk" image_feat = {} for im in range(len(train)): img = train['Image'].values[im].reshape(1,224,224,3) pred = image_model.predict(img).reshape(2048,) image_feat[train.ImageName.values[im]] = pred # + id="fkeUvUEDBGdP" from tensorflow.keras.utils import to_categorical from tensorflow.keras.preprocessing.sequence import pad_sequences # + id="kE6faLY4kK_t" MAX_LEN = 0 for k, vv in caption_dict.items(): for v in vv: if len(v) > MAX_LEN: MAX_LEN = len(v) # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="39a3dXJachKC" outputId="0d61b56d-994b-47dc-eac2-1e6119192a49" MAX_LEN # + id="KYhrqE5AmGyI" VOCAB_SIZE = len(count_words) def generator(photo, caption): n_samples = 0 X = [] y_in = [] y_out = [] for k, vv in caption.items(): for v in vv: for i in range(1, len(v)): try: X.append(photo[k]) in_seq= [v[:i]] out_seq = v[i] in_seq = pad_sequences(in_seq, maxlen=MAX_LEN, padding='post', truncating='post')[0] out_seq = to_categorical([out_seq], num_classes=VOCAB_SIZE+1)[0] y_in.append(in_seq) y_out.append(out_seq) except: pass return X, y_in, y_out # + id="UVnm1ep8mGvW" X, y_in, y_out = generator(image_feat, caption_dict) # + id="h1BC3mZCo2dv" X = np.asarray(X) y_in = np.asarray(y_in) y_out = np.asarray(y_out) # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="WLdaGuosX-pB" outputId="eaba79cc-b81c-492f-d309-9dba9fcc663a" X.shape,y_in.shape,y_out.shape # + id="5Y4-VDBDmUWq" from tensorflow.keras.models import Model, Sequential from tensorflow.keras import layers from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import Embedding from tensorflow.keras.layers import Dropout from tensorflow.keras.layers import RepeatVector from tensorflow.keras.layers import TimeDistributed from tensorflow.keras.layers import Concatenate # + [markdown] id="oafVd2ztk8pj" # ### **Four(4) layered RNN - We are using LSTM as it is an RNN architecture** # + [markdown] id="l8vcR9WpzaZe" # **Add one layer of dropout at the appropriate position and give reasons.** # + [markdown] id="TaJJiyjMlWbw" # Adding **L2 regularization** to all the **RNN** layers and one layer of 20% dropout - adding before last layer of **LSTM** abecause they are the one with the greater number of parameters and thus they're likely to excessively co-adapting themselves causing overfitting. However, since it's a stochastic regularization technique, we can really place it everywhere. # + [markdown] id="Pt3tpV1azhT8" # **Choose the appropriate activation function for all the layers.** # + [markdown] id="XqIn_AK2l1vg" # Adding **softmax** as appropriate activation function - **Adam** optimizer as it converges really faster and adding **categorical crossentropy** as loss function with **accuracy** as performance metric # + [markdown] id="WL6afWsu6Fz-" # ### **Give reasons for the choice of learning rate and its value:** Adding learning rate as 0.0001 as it was hypertuned and gave better results # # + [markdown] id="5NqZtR1SnEUr" # **Model Compilation** # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="RsZhZeXqmUOg" outputId="e81b837c-0b50-460c-c06b-aad0330d33dc" embedding_size = 128 max_len = MAX_LEN vocab_size = len(count_words) + 1 image_model1 = Sequential() image_model1.add(Dense(embedding_size, input_shape=(2048,), activation='relu')) image_model1.add(Dropout(0.2)) image_model1.add(RepeatVector(max_len)) language_model = Sequential() language_model.add(Embedding(input_dim=vocab_size, output_dim=embedding_size, input_length=max_len)) language_model.add(LSTM(128, kernel_regularizer=tf.keras.regularizers.l2(l2=0.0001), return_sequences=True)) language_model.add(Dropout(0.2)) language_model.add(TimeDistributed(Dense(embedding_size))) conca = Concatenate()([image_model1.output, language_model.output])2 #Add L2 regularization to all the RNN layers. x = LSTM(128, kernel_regularizer=tf.keras.regularizers.l2(l2=0.0001), return_sequences=True)(conca) x = LSTM(128, kernel_regularizer=tf.keras.regularizers.l2(l2=0.0001), return_sequences=False)(x) out = Dense(vocab_size,activation='softmax')(x) model = Model(inputs=[image_model1.input, language_model.input], outputs = out) #Compiling the model with above parameters model.compile(optimizer=tf.keras.optimizers.Adam(1e-3), loss=tf.losses.categorical_crossentropy, metrics=['accuracy']) #Print the model summary model.summary() # + colab={"base_uri": "https://localhost:8080/", "height": 735} id="y6jO2qwtw8Hj" outputId="2bd51033-ab05-43f2-9931-42655859ff2a" from tensorflow.keras.utils import plot_model plot_model(model,show_shapes=True,dpi=72) # + [markdown] id="hb4k_Z_Rtpe8" # **Model Training** # + [markdown] id="dyCpWNienMtf" # **Print the train and validation loss for each epoch. Use the appropriate batch size** # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="Vlu8Aj2zEju7" outputId="4c74e2fa-74d8-429d-db8e-998867f56496" start = time.time() history = model.fit([X, y_in], y_out, batch_size=720, epochs=35, validation_split=0.1, use_multiprocessing=True) end = time.time() # + [markdown] id="LqkzMAysnc1Z" # **total time** taken for training: ~15 mins # + colab={"base_uri": "https://localhost:8080/", "height": 0} id="kwZayxeBul4X" outputId="1816e268-09e9-4132-ffac-1fb49cc83dc1" # Print the total time taken for training print("Total time taken for training: ", (end - start)/60, "mins") # + [markdown] id="5qh_7sUjy6w1" # **Plot the loss and accuracy history graphs for both train and validation set** # + colab={"base_uri": "https://localhost:8080/", "height": 499} id="PaBX7Bwpu-6B" outputId="d1d620da-847a-4fa2-c3c4-3fc0994cbb43" acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(len(history.epoch)) plt.figure(figsize=(8, 8)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.show() # + id="NSBDWSJEZvlG" inv_dict = {v:k for k, v in count_words.items()} # + id="suRK5DgTZvc-" def getImage(x): test_img = np.reshape(x, (1,224,224,3)) return test_img # + [markdown] id="-jHI0ngXtfCN" # **Model Evaluation: Take a random image from google and generate caption for that image** # + id="d_YuyUi8jjbA" testImg = load_img('/content/test_image3.jpg',target_size=(224,224,3)) # + colab={"base_uri": "https://localhost:8080/", "height": 300} id="OdW8Ex8xj3VA" outputId="84a79677-cb03-429d-a460-9a37c517c35a" test_pred = image_model.predict(getImage(testImg)).reshape(1,2048) text_inp = ['START'] count = 0 caption = '' while count < 25: count += 1 encoded = [] for i in text_inp: encoded.append(count_words[i]) encoded = [encoded] encoded = pad_sequences(encoded, padding='post', truncating='post', maxlen=MAX_LEN) prediction = np.argmax(model.predict([test_pred, encoded])) sampled_word = inv_dict[prediction] caption = caption + ' ' + sampled_word if sampled_word == 'END': break text_inp.append(sampled_word) plt.figure() plt.imshow(testImg) plt.xlabel(caption.replace("END","").strip())
Group90_DL_Assignment_2.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="Ndo4ERqnwQOU" # ##### Copyright 2020 The TensorFlow Authors. # + cellView="form" id="MTKwbguKwT4R" #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # + [markdown] id="xfNT-mlFwxVM" # # Введение в автоэнкодеры # + [markdown] id="0TD5ZrvEMbhZ" # <table class="tfo-notebook-buttons" align="left"> # <td> # <a target="_blank" href="https://www.tensorflow.org/tutorials/generative/autoencoder"> # <img src="https://www.tensorflow.org/images/tf_logo_32px.png" /> # Смотрите на TensorFlow.org</a> # </td> # <td> # <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ru/tutorials/generative/autoencoder.ipynb"> # <img src="https://www.tensorflow.org/images/colab_logo_32px.png" /> # Запустите в Google Colab</a> # </td> # <td> # <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ru/tutorials/generative/autoencoder.ipynb"> # <img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> # Изучайте код на GitHub</a> # </td> # <td> # <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ru/tutorials/generative/autoencoder.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Скачайте ноутбук</a> # </td> # </table> # + [markdown] id="8a2322303a3f" # Note: Вся информация в этом разделе переведена с помощью русскоговорящего Tensorflow сообщества на общественных началах. Поскольку этот перевод не является официальным, мы не гарантируем что он на 100% аккуратен и соответствует [официальной документации на английском языке](https://www.tensorflow.org/?hl=en). Если у вас есть предложение как исправить этот перевод, мы будем очень рады увидеть pull request в [tensorflow/docs](https://github.com/tensorflow/docs) репозиторий GitHub. Если вы хотите помочь сделать документацию по Tensorflow лучше (сделать сам перевод или проверить перевод подготовленный кем-то другим), напишите нам на [<EMAIL> list](https://groups.google.com/a/tensorflow.org/forum/#!forum/docs-ru). # + [markdown] id="ITZuApL56Mny" # В этом руководстве представлены три примера автоэнкодеров: основной, шумоподавление изображения и обнаружение аномалий. # # Автоэнкодер - это особый тип нейронной сети, которая обучается копировать свои входные данные в выходные данные. Например, учитывая изображение рукописной цифры, автокодер сначала кодирует изображение в скрытое представление меньшей размерности, а затем декодирует скрытое представление обратно в изображение. Автоэнкодер учится сжимать данные, сводя к минимуму ошибку восстановления. # # Чтобы узнать больше об автоэнкодерах, прочитайте главу 14 из [Deep Learning](https://www.deeplearningbook.org/) Яна Гудфеллоу, <NAME> и <NAME>. # + [markdown] id="e1_Y75QXJS6h" # ## Имопорт TensorFlow и библиотек # + id="YfIk2es3hJEd" import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split from tensorflow.keras import layers, losses from tensorflow.keras.datasets import fashion_mnist from tensorflow.keras.models import Model # + [markdown] id="iYn4MdZnKCey" # ## Загрузка датасета # Для начала вы обучите базовый автоэнкодер, используя набор данных Fashion MNIST. Каждое изображение в этом наборе данных имеет размер 28x28 пикселей. # + id="YZm503-I_tji" (x_train, _), (x_test, _) = fashion_mnist.load_data() x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. print (x_train.shape) print (x_test.shape) # + [markdown] id="VEdCXSwCoKok" # ## Первый пример: базовый автоэнкодер # ![Основные результаты автоэнкодера](images/intro_autoencoder_result.png) # # Определите автоэнкодер с двумя полносвязными слоями: `кодировщик`, который сжимает изображения в 64-мерный скрытый вектор, и `декодировщик`, который восстанавливает исходное изображение из скрытого пространства. # # Чтобы определить вашу модель, используйте [Keras Model Subclassing API](https://www.tensorflow.org/guide/keras/custom_layers_and_models). # # + id="0MUxidpyChjX" latent_dim = 64 class Autoencoder(Model): def __init__(self, encoding_dim): super(Autoencoder, self).__init__() self.latent_dim = latent_dim self.encoder = tf.keras.Sequential([ layers.Flatten(), layers.Dense(latent_dim, activation='relu'), ]) self.decoder = tf.keras.Sequential([ layers.Dense(784, activation='sigmoid'), layers.Reshape((28, 28)) ]) def call(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded autoencoder = Autoencoder(latent_dim) # + id="9I1JlqEIDCI4" autoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError()) # + [markdown] id="7oJSeMTroABs" # Обучите модель, используя `x_train` как в качестве входных признаков, так и в качестве входных маркеров. `Энкодер` научится сжимать набор данных из 784 измерений в скрытое пространство, а `декодер` научится восстанавливать исходные изображения. # + id="h1RI9OfHDBsK" autoencoder.fit(x_train, x_train, epochs=10, shuffle=True, validation_data=(x_test, x_test)) # + [markdown] id="wAM1QBhtoC-n" # Теперь, когда модель обучена, давайте протестируем ее путем кодирования и декодирования изображений из тестового набора. # + id="Pbr5WCj7FQUi" encoded_imgs = autoencoder.encoder(x_test).numpy() decoded_imgs = autoencoder.decoder(encoded_imgs).numpy() # + id="s4LlDOS6FUA1" n = 10 plt.figure(figsize=(20, 4)) for i in range(n): # display original ax = plt.subplot(2, n, i + 1) plt.imshow(x_test[i]) plt.title("original") 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(decoded_imgs[i]) plt.title("reconstructed") plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.show() # + [markdown] id="r4gv6G8PoRQE" # ## Второй пример: уменьшение шума на изображении # # ![Результаты шумоподавления изображения](images/image_denoise_fmnist_results.png) # # Автоэнкодер также можно обучить удалению шума с изображений. В следующем разделе вы создадите зашумленную версию набора данных Fashion MNIST, применив случайный шум к каждому изображению. Затем вы обучите автоэнкодер, используя зашумленное изображение в качестве входных данных и исходное изображение в качестве цели. # # Давайте повторно импортируем набор данных, чтобы убрать изменения, сделанные ранее. # + id="gDYHJA2PCQ3m" (x_train, _), (x_test, _) = fashion_mnist.load_data() # + id="uJZ-TcaqDBr5" x_train = x_train.astype('float32') / 255. x_test = x_test.astype('float32') / 255. x_train = x_train[..., tf.newaxis] x_test = x_test[..., tf.newaxis] print(x_train.shape) # + [markdown] id="aPZl_6P65_8R" # Добавление случайного шума к изображениям # + id="axSMyxC354fc" noise_factor = 0.2 x_train_noisy = x_train + noise_factor * tf.random.normal(shape=x_train.shape) x_test_noisy = x_test + noise_factor * tf.random.normal(shape=x_test.shape) x_train_noisy = tf.clip_by_value(x_train_noisy, clip_value_min=0., clip_value_max=1.) x_test_noisy = tf.clip_by_value(x_test_noisy, clip_value_min=0., clip_value_max=1.) # + [markdown] id="wRxHe4XXltNd" # Посмотрите зашумленные изображения. # + id="thKUmbVVCQpt" n = 10 plt.figure(figsize=(20, 2)) for i in range(n): ax = plt.subplot(1, n, i + 1) plt.title("original + noise") plt.imshow(tf.squeeze(x_test_noisy[i])) plt.gray() plt.show() # + [markdown] id="Sy9SY8jGl5aP" # ### Определениее сверточного автоенкодера # + [markdown] id="vT_BhZngWMwp" # В этом примере вы обучите сверточный автоэнкодер, используя слои [Conv2D](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) в `encoder` и [Conv2DTranspose](https : //www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2DTranspose) в `decoder`. # + id="R5KjoIlYCQko" class Denoise(Model): def __init__(self): super(Denoise, self).__init__() self.encoder = tf.keras.Sequential([ layers.Input(shape=(28, 28, 1)), layers.Conv2D(16, (3,3), activation='relu', padding='same', strides=2), layers.Conv2D(8, (3,3), activation='relu', padding='same', strides=2)]) self.decoder = tf.keras.Sequential([ layers.Conv2DTranspose(8, kernel_size=3, strides=2, activation='relu', padding='same'), layers.Conv2DTranspose(16, kernel_size=3, strides=2, activation='relu', padding='same'), layers.Conv2D(1, kernel_size=(3,3), activation='sigmoid', padding='same')]) def call(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded autoencoder = Denoise() # + id="QYKbiDFYCQfj" autoencoder.compile(optimizer='adam', loss=losses.MeanSquaredError()) # + id="IssFr1BNCQX3" autoencoder.fit(x_train_noisy, x_train, epochs=10, shuffle=True, validation_data=(x_test_noisy, x_test)) # + [markdown] id="G85xUVBGTAKp" # Давайте взглянем на краткое описание енкодера. Обратите внимание, как изображения уменьшаются с 28x28 до 7x7. # + id="oEpxlX6sTEQz" autoencoder.encoder.summary() # + [markdown] id="DDZBfMx1UtXx" # Декодер увеличивает разрешение изображения с 7x7 до 28x28. # + id="pbeQtYMaUpro" autoencoder.decoder.summary() # + [markdown] id="A7-VAuEy_N6M" # Просмотрим зашумленные изображения и изображений с шумоподавлением, созданные автокодером. # + id="t5IyPi1fCQQz" encoded_imgs = autoencoder.encoder(x_test).numpy() decoded_imgs = autoencoder.decoder(encoded_imgs).numpy() # + id="sfxr9NdBCP_x" n = 10 plt.figure(figsize=(20, 4)) for i in range(n): # display original + noise ax = plt.subplot(2, n, i + 1) plt.title("original + noise") plt.imshow(tf.squeeze(x_test_noisy[i])) plt.gray() ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) # display reconstruction bx = plt.subplot(2, n, i + n + 1) plt.title("reconstructed") plt.imshow(tf.squeeze(decoded_imgs[i])) plt.gray() bx.get_xaxis().set_visible(False) bx.get_yaxis().set_visible(False) plt.show() # + [markdown] id="ErGrTnWHoUYl" # ## Третий пример: обнаружение аномалии # # ## Обзор # # # В этом примере вы обучите автоэнкодер обнаруживать аномалии в [наборе данных ECG5000](http://www.timeseriesclassification.com/description.php?Dataset=ECG5000). Этот набор данных содержит 5000 [электрокардиограмм](https://en.wikipedia.org/wiki/Electrocardiography), каждая из которых содержит 140 точек данных. Вы будете использовать упрощенную версию датасета, где каждый пример помечен как `0`(соответствует ненормальному ритму) или `1`(соответствует нормальному ритму). Вам нужно идентифицировать аномальные ритмы. # # Примечание. Это размеченный набор данных, поэтому вы можете назвать его `обучение с учителем`. Цель этого примера - проиллюстрировать концепции обнаружения аномалий, которые вы можете применить к большим наборам данных, где у вас нет размеченных меток(например, если у вас было несколько тысяч нормальных ритмов и только небольшое количество аномальных ритмов). # # Как вы обнаружите аномалии с помощью автокодировщика? Напомним, что автоэнкодер обучен минимизировать ошибку восстановления. Вы обучите автоэнкодер только нормальным ритмам, а затем воспользуетесь им для восстановления всех данных. Наша гипотеза состоит в том, что аномальные ритмы будут иметь более высокую ошибку восстановления. Таким образом вы классифицируете ритм как аномалию, если ошибка восстановления превышает фиксированный порог. # + [markdown] id="i5estNaur_Mh" # ### Загрузка ECG датасета # + [markdown] id="y35nsXLPsDNX" # Набор данных, который вы будете использовать, основан на одном из [timeseriesclassification.com](http://www.timeseriesclassification.com/description.php?Dataset=ECG5000). # # + id="KmKRDJWgsFYa" # Загружаем датасет dataframe = pd.read_csv('http://storage.googleapis.com/download.tensorflow.org/data/ecg.csv', header=None) raw_data = dataframe.values dataframe.head() # + id="UmuCPVYKsKKx" # Последний элемент строки содержит метку labels = raw_data[:, -1] # Остальные данные это данные электрокардиограмм data = raw_data[:, 0:-1] train_data, test_data, train_labels, test_labels = train_test_split( data, labels, test_size=0.2, random_state=21 ) # + [markdown] id="byK2vP7hsMbz" # Нормализуем данные до `[0,1]`. # + id="tgMZVWRKsPx6" min_val = tf.reduce_min(train_data) max_val = tf.reduce_max(train_data) train_data = (train_data - min_val) / (max_val - min_val) test_data = (test_data - min_val) / (max_val - min_val) train_data = tf.cast(train_data, tf.float32) test_data = tf.cast(test_data, tf.float32) # + [markdown] id="BdSYr2IPsTiz" # Вы будете обучать автоэнкодер, используя только нормальные ритмы, которые в этом наборе данных обозначены как `1`. Отделите нормальные ритмы от ненормальных. # + id="VvK4NRe8sVhE" train_labels = train_labels.astype(bool) test_labels = test_labels.astype(bool) normal_train_data = train_data[train_labels] normal_test_data = test_data[test_labels] anomalous_train_data = train_data[~train_labels] anomalous_test_data = test_data[~test_labels] # + [markdown] id="wVcTBDo-CqFS" # Отрисуйте нормальные ритмы ECG. # + id="ZTlMIrpmseYe" plt.grid() plt.plot(np.arange(140), normal_train_data[0]) plt.title("A Normal ECG") plt.show() # + [markdown] id="QpI9by2ZA0NN" # Отрисуйте ненормальные ритмы ECG. # + id="zrpXREF2siBr" plt.grid() plt.plot(np.arange(140), anomalous_train_data[0]) plt.title("An Anomalous ECG") plt.show() # + [markdown] id="0DS6QKZJslZz" # ### Создание модели # + id="bf6owZQDsp9y" class AnomalyDetector(Model): def __init__(self): super(AnomalyDetector, self).__init__() self.encoder = tf.keras.Sequential([ layers.Dense(32, activation="relu"), layers.Dense(16, activation="relu"), layers.Dense(8, activation="relu")]) self.decoder = tf.keras.Sequential([ layers.Dense(16, activation="relu"), layers.Dense(32, activation="relu"), layers.Dense(140, activation="sigmoid")]) def call(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return decoded autoencoder = AnomalyDetector() # + id="gwRpBBbg463S" autoencoder.compile(optimizer='adam', loss='mae') # + [markdown] id="zuTy60STBEy4" # Обратите внимание, что автокодировщик обучается с использованием только нормальных ЭКГ, но оценивается с использованием полного набора данных. # + id="V6NFSs-jsty2" history = autoencoder.fit(normal_train_data, normal_train_data, epochs=20, batch_size=512, validation_data=(test_data, test_data), shuffle=True) # + id="OEexphFwwTQS" plt.plot(history.history["loss"], label="Training Loss") plt.plot(history.history["val_loss"], label="Validation Loss") plt.legend() # + [markdown] id="ceI5lKv1BT-A" # Вы быстро классифицируете ЭКГ как аномальную, если ошибка реконструкции больше одного стандартного отклонения от нормальных обучающих примеров. Сначала давайте построим нормальную ЭКГ из датасета, ее реконструкцию после кодирования и декодирования и ошибку реконструкции. # + id="hmsk4DuktxJ2" encoded_imgs = autoencoder.encoder(normal_test_data).numpy() decoded_imgs = autoencoder.decoder(encoded_imgs).numpy() plt.plot(normal_test_data[0],'b') plt.plot(decoded_imgs[0],'r') plt.fill_between(np.arange(140), decoded_imgs[0], normal_test_data[0], color='lightcoral' ) plt.legend(labels=["Input", "Reconstruction", "Error"]) plt.show() # + [markdown] id="ocA_q9ufB_aF" # Создайте аналогичный график, на этот раз для аномального примера. # + id="vNFTuPhLwTBn" encoded_imgs = autoencoder.encoder(anomalous_test_data).numpy() decoded_imgs = autoencoder.decoder(encoded_imgs).numpy() plt.plot(anomalous_test_data[0],'b') plt.plot(decoded_imgs[0],'r') plt.fill_between(np.arange(140), decoded_imgs[0], anomalous_test_data[0], color='lightcoral' ) plt.legend(labels=["Input", "Reconstruction", "Error"]) plt.show() # + [markdown] id="ocimg3MBswdS" # ### Определение аномалий # + [markdown] id="Xnh8wmkDsypN" # Вы можете обнаружить аномалии, вычисляя, превышают ли потери при реконструкции фиксированный порог. В этом руководстве вы рассчитаете среднюю среднюю ошибку для нормальных примеров из обучающего набора, а затем классифицируете будущие примеры как аномальные, если ошибка реконструкции превышает одно стандартное отклонение от обучающего набора. # + [markdown] id="TeuT8uTA5Y_w" # Постройте график ошибки реконструкции на нормальных ЭКГ из обучающей выборки # + id="gwLuxrb-s0ss" reconstructions = autoencoder.predict(normal_train_data) train_loss = tf.keras.losses.mae(reconstructions, normal_train_data) plt.hist(train_loss, bins=50) plt.xlabel("Train loss") plt.ylabel("No of examples") plt.show() # + [markdown] id="mh-3ChEF5hog" # Выберите пороговое значение, которое на одно стандартное отклонение выше среднего. # + id="82hkl0Chs3P_" threshold = np.mean(train_loss) + np.std(train_loss) print("Threshold: ", threshold) # + [markdown] id="uEGlA1Be50Nj" # Примечание. Существуют и другие стратегии, которые вы можете использовать для выбора порогового значения для определения аномалий. Правильный подход будет зависеть от вашего набора данных. Вы можете узнать больше по ссылкам в конце этого руководства. # + [markdown] id="zpLSDAeb51D_" # Если вы исследуете ошибку реконструкции для аномальных примеров, вы заметите, что большинство из них имеют бОльшую ошибку реконструкции, чем пороговое значение. Изменяя порог, вы можете настроить [precision](https://developers.google.com/machine-learning/glossary#precision) и [recall] (https://developers.google.com/machine-learning/glossary#recall) вашего классификатора. # + id="sKVwjQK955Wy" reconstructions = autoencoder.predict(anomalous_test_data) test_loss = tf.keras.losses.mae(reconstructions, anomalous_test_data) plt.hist(test_loss, bins=50) plt.xlabel("Test loss") plt.ylabel("No of examples") plt.show() # + [markdown] id="PFVk_XGE6AX2" # Классифицируйте ЭКГ как аномалию, если ошибка восстановления превышает пороговое значение. # + id="mkgJZfhh6CHr" def predict(model, data, threshold): reconstructions = model(data) loss = tf.keras.losses.mae(reconstructions, data) return tf.math.less(loss, threshold) def print_stats(predictions, labels): print("Accuracy = {}".format(accuracy_score(labels, preds))) print("Precision = {}".format(precision_score(labels, preds))) print("Recall = {}".format(recall_score(labels, preds))) # + id="sOcfXfXq6FBd" preds = predict(autoencoder, test_data, threshold) print_stats(preds, test_labels) # + [markdown] id="HrJRef8Ln945" # ## Следующие шаги # # Чтобы узнать больше об обнаружении аномалий с помощью автоэнкодеров, ознакомьтесь с этим прекрасным [интерактивным примером](https://anomagram.fastforwardlabs.com/#/), созданным <NAME> с помощью TensorFlow.js. # Для практического использования вы можете узнать, как [Airbus обнаруживает аномалии в данных телеметрии МКС](https://blog.tensorflow.org/2020/04/how-airbus-detects-anomalies-iss-telemetry-data- tfx.html) с помощью TensorFlow. # Чтобы узнать больше об основах, прочтите это [сообщение в блоге](https://blog.keras.io/building-autoencoders-in-keras.html) <NAME>. # Для получения дополнительной информации ознакомьтесь с главой 14 из [Deep Learning](https://www.deeplearningbook.org/) <NAME>, <NAME> и <NAME>.
site/ru/tutorials/generative/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 # --- # + id="JSjG64ra4aFu" # from google.colab import drive # drive.mount('/content/drive') # + id="3uDWznlVHuI6" # path = "/content/drive/MyDrive/Research/cods_comad_plots/sdc_task/mnist/" # + id="jIzYDQ-xN0Qj" m = 100 desired_num = 10000 # + id="V8-7SARDZErK" import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from matplotlib import pyplot as plt import copy # Ignore warnings import warnings warnings.filterwarnings("ignore") torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False # + id="acRFqJNrZErV" transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5), (0.5))]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) # + id="gh5DXuAV1tp5" colab={"base_uri": "https://localhost:8080/"} outputId="5e8ca20f-7c79-48b7-8f5e-864b029c04c5" classes = ('zero','one','two','three','four','five','six','seven','eight','nine') foreground_classes = {'zero','one'} fg_used = '01' fg1, fg2 = 0,1 all_classes = {'zero','one','two','three','four','five','six','seven','eight','nine'} background_classes = all_classes - foreground_classes background_classes # + id="Xbr_H78mp_Of" trainloader = torch.utils.data.DataLoader(trainset, batch_size=10, shuffle = False) testloader = torch.utils.data.DataLoader(testset, batch_size=10, shuffle = False) # + id="V_JUhwCeZErk" dataiter = iter(trainloader) background_data=[] background_label=[] foreground_data=[] foreground_label=[] batch_size=10 for i in range(6000): images, labels = dataiter.next() for j in range(batch_size): if(classes[labels[j]] in background_classes): img = images[j].tolist() background_data.append(img) background_label.append(labels[j]) else: img = images[j].tolist() foreground_data.append(img) foreground_label.append(labels[j]) foreground_data = torch.tensor(foreground_data) foreground_label = torch.tensor(foreground_label) background_data = torch.tensor(background_data) background_label = torch.tensor(background_label) # + id="iyyWx5g58erM" def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img#.numpy() plt.imshow(np.reshape(npimg, (28,28))) plt.show() # + colab={"base_uri": "https://localhost:8080/"} id="U5w9S6xb6EFl" outputId="d5135715-3573-4f4e-f7ed-a0248fbc4196" foreground_data.shape, foreground_label.shape, background_data.shape, background_label.shape # + id="IRd6EpWM6Abq" val, idx = torch.max(background_data, dim=0, keepdims= True,) # torch.abs(val) # + id="Sly62nHh6VJy" mean_bg = torch.mean(background_data, dim=0, keepdims= True) std_bg, _ = torch.max(background_data, dim=0, keepdims= True) # + colab={"base_uri": "https://localhost:8080/"} id="K89Qj57m6axj" outputId="016e099f-ff97-431d-a17b-dc8368070beb" mean_bg.shape, std_bg.shape # + id="wGVjRbqZ6lzV" foreground_data = (foreground_data - mean_bg) / std_bg background_data = (background_data - mean_bg) / torch.abs(std_bg) # + colab={"base_uri": "https://localhost:8080/"} id="yxZVq5OW6o3L" outputId="615c1cf1-a914-4391-da98-e2906f6c0277" foreground_data.shape, foreground_label.shape, background_data.shape, background_label.shape # + colab={"base_uri": "https://localhost:8080/"} id="pTrGcqI7GsBA" outputId="b3d6c020-3bdf-4a31-c212-ddbb954c5f48" torch.sum(torch.isnan(foreground_data)), torch.sum(torch.isnan(background_data)) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="fIqpbILY-BiG" outputId="9fdaa465-4faa-4233-f20d-fb4ad52b1ae7" imshow(foreground_data[0]) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="tRvTvlVo98xz" outputId="66ceb12d-301f-44b9-a4f0-0979997c0b69" imshow(background_data[0]) # + [markdown] id="ccO3wCVRNrxe" # ## generating CIN train and test data # + colab={"base_uri": "https://localhost:8080/"} id="30usvva6N0Nq" outputId="c4df2b6c-10cd-4893-fb8d-cb13172d8484" np.random.seed(0) bg_idx = np.random.randint(0,47335,m-1) fg_idx = np.random.randint(0,12665) bg_idx, fg_idx # + id="Q3ryiEQ5N0GY" # for i in background_data[bg_idx]: # imshow(i) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="ZtUC0dNdN0Dz" outputId="87a4ba7b-4471-4f40-b33d-46a3559971b3" imshow(torch.sum(background_data[bg_idx], axis = 0)) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="UY1IevjcN0BL" outputId="b6f6592f-9567-45a3-e03e-82069c070b41" imshow(foreground_data[fg_idx]) # + colab={"base_uri": "https://localhost:8080/"} id="e6niBULUNz-k" outputId="fffcf0e8-dabf-4335-b055-062dbdfb5f97" tr_data = ( torch.sum(background_data[bg_idx], axis = 0) + foreground_data[fg_idx] )/m tr_data.shape # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="SSLaezrFNz7r" outputId="3cc573f4-7e79-4953-a157-6721975d05d6" imshow(tr_data) # + colab={"base_uri": "https://localhost:8080/"} id="aNZSuYqiOC6d" outputId="92bd688e-db2b-4311-da5a-d342f1406772" foreground_label[fg_idx] # + id="vD1bssSmOC3k" train_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images train_label=[] # label of mosaic image = foreground class present in that mosaic for i in range(desired_num): np.random.seed(i) bg_idx = np.random.randint(0,47335,m-1) fg_idx = np.random.randint(0,12665) tr_data = ( torch.sum(background_data[bg_idx], axis = 0) + foreground_data[fg_idx] ) / m label = (foreground_label[fg_idx].item()) train_images.append(tr_data) train_label.append(label) # + colab={"base_uri": "https://localhost:8080/"} id="CkoRVhHSOC09" outputId="806b6fc1-8e3a-4c93-ab0c-bca1f14dcaf7" train_images = torch.stack(train_images) train_images.shape, len(train_label) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="KrJqFMoEOCyK" outputId="73a9f546-8b9f-471d-f7ae-33ef810e7881" imshow(train_images[0]) # + id="cv6LZJMoOeb8" test_images =[] # list of mosaic images, each mosaic image is saved as list of 9 images test_label=[] # label of mosaic image = foreground class present in that mosaic for i in range(10000): np.random.seed(i) fg_idx = np.random.randint(0,12665) tr_data = ( foreground_data[fg_idx] ) / m label = (foreground_label[fg_idx].item()) test_images.append(tr_data) test_label.append(label) # + colab={"base_uri": "https://localhost:8080/"} id="ZBuH3ayNOeZU" outputId="b052d8cf-8f9b-4296-f864-370fb35f1927" test_images = torch.stack(test_images) test_images.shape, len(test_label) # + colab={"base_uri": "https://localhost:8080/", "height": 265} id="wv_aBpW8OeWs" outputId="b68613de-9bc4-4f5a-c9bd-1bb3cdb2d7cb" imshow(test_images[0]) # + colab={"base_uri": "https://localhost:8080/"} id="7mvKwVWNOeTi" outputId="52a96b4f-a506-45da-f088-eb2c51840d8b" torch.sum(torch.isnan(train_images)), torch.sum(torch.isnan(test_images)) # + colab={"base_uri": "https://localhost:8080/"} id="919oQptjOosG" outputId="ab4e4d8e-c059-46ba-92b7-85e1c295d01f" np.unique(train_label), np.unique(test_label) # + [markdown] id="dl3dzlPPOsDT" # ## creating dataloader # + id="hX35HdXoOoot" class CIN_Dataset(Dataset): """CIN_Dataset dataset.""" def __init__(self, list_of_images, labels): """ Args: csv_file (string): Path to the csv file with annotations. root_dir (string): Directory with all the images. transform (callable, optional): Optional transform to be applied on a sample. """ self.image = list_of_images self.label = labels def __len__(self): return len(self.label) def __getitem__(self, idx): return self.image[idx] , self.label[idx] # + id="Y44ojnvZOolr" batch = 250 train_data = CIN_Dataset(train_images, train_label) train_loader = DataLoader( train_data, batch_size= batch , shuffle=True) test_data = CIN_Dataset( test_images , test_label) test_loader = DataLoader( test_data, batch_size= batch , shuffle=False) # + colab={"base_uri": "https://localhost:8080/"} id="dLJ5YSOOO6s6" outputId="81f6ac39-fd66-46e0-be66-83c72482879b" train_loader.dataset.image.shape, test_loader.dataset.image.shape # + [markdown] id="z0oF6s0dO7zy" # ## model # + id="KoP6hoBqNJxX" class Classification(nn.Module): def __init__(self): super(Classification, self).__init__() self.fc1 = nn.Linear(28*28, 50) self.fc2 = nn.Linear(50, 2) torch.nn.init.xavier_normal_(self.fc1.weight) torch.nn.init.zeros_(self.fc1.bias) torch.nn.init.xavier_normal_(self.fc2.weight) torch.nn.init.zeros_(self.fc2.bias) def forward(self, x): x = x.view(-1, 28*28) x = F.relu(self.fc1(x)) x = self.fc2(x) return x # + [markdown] id="KwP2xvB7PBFK" # ## training # + id="uPYplUGazU9I" torch.manual_seed(12) classify = Classification().double() classify = classify.to("cuda") # + id="n5g3geNJ5zEu" import torch.optim as optim criterion = nn.CrossEntropyLoss() optimizer_classify = optim.Adam(classify.parameters(), lr=0.001 ) #, momentum=0.9) # + id="725MVVfLS3et" colab={"base_uri": "https://localhost:8080/"} outputId="fbc1f069-a2a5-4d3a-c85d-23d74d63bd59" correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in train_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( desired_num , 100 * correct / total)) print("total correct", correct) print("total train set images", total) # + colab={"base_uri": "https://localhost:8080/"} id="iYTaJG0GPLA7" outputId="ee493b91-017b-44b4-ff33-0c73a4128c83" correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in test_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d test images: %f %%' % ( 10000 , 100 * correct / total)) print("total correct", correct) print("total train set images", total) # + colab={"base_uri": "https://localhost:8080/"} id="LCWyTEIKPNlK" outputId="001f951e-b5aa-44e7-c47d-2a6940987413" nos_epochs = 200 tr_loss = [] for epoch in range(nos_epochs): # loop over the dataset multiple times epoch_loss = [] cnt=0 iteration = desired_num // batch running_loss = 0 #training data set for i, data in enumerate(train_loader): inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") inputs = inputs.double() # zero the parameter gradients optimizer_classify.zero_grad() outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) # print(outputs) # print(outputs.shape,labels.shape , torch.argmax(outputs, dim=1)) loss = criterion(outputs, labels) loss.backward() optimizer_classify.step() running_loss += loss.item() mini = 1 if cnt % mini == mini-1: # print every 40 mini-batches # print('[%d, %5d] loss: %.3f' %(epoch + 1, cnt + 1, running_loss / mini)) epoch_loss.append(running_loss/mini) running_loss = 0.0 cnt=cnt+1 tr_loss.append(np.mean(epoch_loss)) if(np.mean(epoch_loss) <= 0.001): break; else: print('[Epoch : %d] loss: %.3f' %(epoch + 1, np.mean(epoch_loss) )) print('Finished Training') # + colab={"base_uri": "https://localhost:8080/", "height": 284} id="nfzc13qsPST6" outputId="908fecf8-3f28-49b5-b848-1b742d431246" plt.plot(tr_loss) # + colab={"base_uri": "https://localhost:8080/"} id="uORwiHXMPU7P" outputId="2b3b56e0-61ea-4871-eade-52a0ea41d02d" correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in train_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( desired_num , 100 * correct / total)) print("total correct", correct) print("total train set images", total) # + colab={"base_uri": "https://localhost:8080/"} id="YqPjpP3EPWQK" outputId="0f22782e-58b0-4dca-a6bd-81a2a406c7fe" correct = 0 total = 0 count = 0 flag = 1 with torch.no_grad(): for data in test_loader: inputs, labels = data inputs = inputs.double() inputs, labels = inputs.to("cuda"),labels.to("cuda") outputs = classify(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the %d train images: %f %%' % ( 10000 , 100 * correct / total)) print("total correct", correct) print("total test set images", total) # + id="c6wGSifzPXzx"
AAAI/Learnability/CIN/MLP/MNIST/MNIST_CIN_10000_MLP_m_100.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=[] # # Destroy AWS Resources # - # %load_ext lab_black # %load_ext autoreload # %autoreload 2 # + import os from glob import glob from time import sleep import boto3 from dotenv import find_dotenv, load_dotenv # + # %aimport src.s3.buckets import src.s3.buckets as s3b # %aimport src.cw.cloudwatch_logs import src.cw.cloudwatch_logs as cwlogs # %aimport src.iam.iam_roles import src.iam.iam_roles as iamr # %aimport src.firehose.kinesis_firehose import src.firehose.kinesis_firehose as knsfire # %aimport src.ec2.ec2_instances_sec_groups import src.ec2.ec2_instances_sec_groups as ec2h # %aimport src.keypairs.ssh_keypairs import src.keypairs.ssh_keypairs as ssh_keys # %aimport src.ansible.playbook_utils import src.ansible.playbook_utils as pbu # - load_dotenv(find_dotenv()) aws_region = os.getenv("AWS_REGION") # ## About # In this notebook, the following AWS resources will be destroyed # - EC2 instance # - S3 bucket # - CloudWatch Logging group (automatically deletes CloudWatch Logging stream) # - IAM role # - Kinesis Firehose Delivery Stream # # ### Pre-Requisites # 1. As mentioned in `README.md`, the following environment variables should be set with the user's AWS credendials ([1](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_environment.html), [2](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_profiles.html)) # - `AWS_ACCESS_KEY_ID` # - `AWS_SECRET_KEY` # - `AWS_REGION` # # These credentials must be associated to a user group whose users have been granted programmatic access to AWS resources. In order to configure this for an IAM user group, see the documentation [here](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html#id_users_create_console). # # ### Notes # 1. All resources must exist in the same AWS region (specified by the environment variable `AWS_REGION`). # ## User Inputs # + tags=["parameters"] # S3 s3_bucket_name = "" # IAM Role iam_role_name = "kinesis-firehose-role" iam_policy_name = "mypolicy" # Kinesis Firehose Stream firehose_stream_name = "twitter_delivery_stream" # CloudWatch Logging cw_logs_group_name = f"kinesisfirehose_{firehose_stream_name}" # EC2 Security Groups sg_group_tags = [{"Key": "Name", "Value": "allow-inbound-ssh"}] # SSH Key Pairs key_fname = "aws_ec2_key" keypair_name = "ec2-key-pair" # EC2 Instances ec2_instance_tags_list = [{"Key": "Name", "Value": "my-ec2-instance"}] ansible_inventory_host_vars_fpath = "inventories/production/host_vars/ec2host" # - # ## Reset Host Target EC2 Attributes in Ansible Inventory # Reset the target IP address # %%time pbu.replace_inventory_host_ip(ansible_inventory_host_vars_fpath, "...") # Reset the target Python version # %%time pbu.replace_inventory_python_version(ansible_inventory_host_vars_fpath, "2.7") # ## Stop EC2 Instance # %%time ec2_instance_filter = dict(Filters=[{"Name": "tag:Name", "Values": ["my-ec2-instance"]}]) # Filter instances group by tag filtered_instances_list = ec2h.list_ec2_instances_by_filter(aws_region, ec2_instance_filter) # Slice filtered instances by index, to get first matching instance_id first_filtered_instance_id = filtered_instances_list[0]["id"] stop_instance_response = ec2h.stop_instance(first_filtered_instance_id, aws_region) stop_instance_response # ## Terminate EC2 Instance # %%time ec2_instance_filter = dict(Filters=[{"Name": "tag:Name", "Values": ["my-ec2-instance"]}]) # Filter instances group by tag filtered_instances_list = ec2h.list_ec2_instances_by_filter(aws_region, ec2_instance_filter) # Slice filtered instances by index, to get first matching instance_id first_filtered_instance_id = filtered_instances_list[0]["id"] terminated_instance_response = ec2h.terminate_instance(first_filtered_instance_id, aws_region) terminated_instance_response # %%time ec2_instance_filter = dict( Filters=[{"Name": "tag:Name", "Values": ["my-ec2-instance"]}] ) ec2h.check_ec2_instance_termination(ec2_instance_filter, aws_region) # ## Delete Local SSH Key Pair # %%time key_deletion_response = ssh_keys.delete_key_pair(keypair_name, aws_region) key_deletion_response # %%time key_filter = dict(Filters=[{"Name": "tag:Name", "Values": ["my-ssh-key-pair"]}]) ssh_keys.check_deletion_key_pair(key_filter, aws_region) # ## Delete EC2 Security Groups sleep(45) # %%time sg_filter = dict(Filters=[{"Name": "tag:Name", "Values": ["allow-inbound-ssh"]}]) sg_id_list = ec2h.get_security_group_ids(aws_region, sg_filter) ec2h.delete_sg(sg_id_list[0], aws_region) # %%time sg_filter = dict(Filters=[{"Name": "tag:Name", "Values": ["allow-inbound-ssh"]}]) ec2h.check_ec2_security_group_deletion(sg_filter, aws_region) # ## Delete the Kinesis Firehose Delivery Stream # + tags=[] # %%time firehose_deletion_response = knsfire.delete_kinesis_firehose_stream( firehose_stream_name, aws_region ) knsfire.check_kinesis_firehose_stream_seletion(firehose_stream_name, aws_region) # - # ## IAM # ### Delete IAM Firehose-S3 Policy # Get Attached IAM Policies # + tags=[] # %%time iam_firehose_s3_policy_list = iamr.get_iam_policies(aws_region, attached=True) iam_policy_dict = [ iam_firehose_s3_policy for iam_firehose_s3_policy in iam_firehose_s3_policy_list if iam_firehose_s3_policy["PolicyName"] == iam_policy_name ][0] iam_policy_dict # - # Delete IAM Firehose-S3 Policy # + tags=[] # %%time policy_detachment_response, policy_deletion_response = iamr.delete_iam_policy( iam_policy_dict["Arn"], iam_role_name, aws_region ) print(policy_detachment_response) print(policy_deletion_response) # - # ### Delete IAM Role # %%time iam_role_deletion_response = iamr.delete_iam_role(iam_role_name, aws_region) iamr.check_iam_role_deletion(iam_role_name, aws_region) # ## Delete CloudWatch Log Group and Stream # + tags=[] # %%time cwlogs.delete_cw_log_group_stream(cw_logs_group_name, firehose_stream_name, aws_region) cwlogs.check_cw_log_group_deletion(cw_logs_group_name, aws_region) cwlogs.check_cw_log_stream_deletion(cw_logs_group_name, firehose_stream_name, aws_region) # - # ## (Optional) Delete the S3 Bucket # %%time if s3_bucket_name: s3_bucket_deletion_response = s3b.delete_s3_bucket(s3_bucket_name, aws_region) s3b.check_s3_bucket_deletion(s3_bucket_name, aws_region)
6_delete_aws_resources.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 # --- # # JIT Engine: Matrix + Broadcasted Vector # # This example will go over how to compile MLIR code intended to add a matrix to a vector using broadcasting. # # In other words, we want to write a function equivalent to this NumPy code. # + import numpy as np matrix = np.full([4,3], 100, dtype=np.float32) vector = np.arange(4, dtype=np.float32) matrix + np.expand_dims(vector, 1) # - # Let’s first import some necessary modules and generate an instance of our JIT engine. # + import mlir_graphblas engine = mlir_graphblas.MlirJitEngine() # - # Here's the MLIR code we'll use. mlir_text = """ #trait_matplusvec = { indexing_maps = [ affine_map<(i,j) -> (i,j)>, affine_map<(i,j) -> (i)>, affine_map<(i,j) -> (i,j)> ], iterator_types = ["parallel", "parallel"] } func @mat_plus_vec(%arga: tensor<10x?xf32>, %argb: tensor<10xf32>) -> tensor<10x?xf32> { %c1 = arith.constant 1 : index %arga_dim1 = tensor.dim %arga, %c1 : tensor<10x?xf32> %output_memref = memref.alloca(%arga_dim1) : memref<10x?xf32> %output_tensor = memref.tensor_load %output_memref : memref<10x?xf32> %answer = linalg.generic #trait_matplusvec ins(%arga, %argb : tensor<10x?xf32>, tensor<10xf32>) outs(%output_tensor: tensor<10x?xf32>) { ^bb(%a: f32, %b: f32, %x: f32): %sum = arith.addf %a, %b : f32 linalg.yield %sum : f32 } -> tensor<10x?xf32> return %answer : tensor<10x?xf32> } """ # Note that the input matrix has an arbitrary number of columns. # # These are the passes we'll use to optimize and compile our MLIR code. passes = [ "--graphblas-structuralize", "--graphblas-optimize", "--graphblas-lower", "--sparsification", "--sparse-tensor-conversion", "--linalg-bufferize", "--func-bufferize", "--tensor-constant-bufferize", "--tensor-bufferize", "--finalizing-bufferize", "--convert-linalg-to-loops", "--convert-scf-to-std", "--convert-memref-to-llvm", "--convert-math-to-llvm", "--convert-openmp-to-llvm", "--convert-arith-to-llvm", "--convert-math-to-llvm", "--convert-std-to-llvm", "--reconcile-unrealized-casts" ] # Let's compile our MLIR code using our JIT engine. engine.add(mlir_text, passes) mat_plus_vec = engine.mat_plus_vec # Let's see how well our function works. # + # generate inputs m = np.arange(40, dtype=np.float32).reshape([10,4]) v = np.arange(10, dtype=np.float32) / 10 # generate output result = mat_plus_vec(m, v) # - result # Let's verify that our result is correct. np.all(result == m + np.expand_dims(v, 1))
docs/tools/engine/matrix_plus_broadcasted_vector.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 urllib import json import datetime # grab the base data DANE_URL = "https://opendata.arcgis.com/datasets/b913e9591eae4912b33dc5b4e88646c5_10.geojson?where=GEO%20%3D%20'County'%20AND%20NAME%20%3D%20'Dane'" response = urllib.request.urlopen(DANE_URL) dane_data = json.loads(response.read()) data_elems = dane_data['features'] # I guess WI DHS stoppped serving data in date order and does not use an ISO date format def parse_date(dstring): date_part = dstring.split()[0] year,month,day = date_part.split('/') return datetime.date(int(year), int(month), int(day)) # first sort the data elements by date de_date_tups = [(el,parse_date(el['properties']['DATE']).toordinal()) for el in data_elems] de_date_tups = sorted(de_date_tups, key=lambda tup: tup[1]) # pull the elements back out in order data_elems = [el[0] for el in de_date_tups] # and pull out important values new_neg = [el['properties']['NEG_NEW'] for el in data_elems] new_pos = [el['properties']['POS_NEW'] for el in data_elems] # + # now strip off missing data points from the front def first_non_none(vals): for i in range(len(vals)): if vals[i] is not None: return i return len(vals) # just in case one or the other has more missing samples neg_start = first_non_none(new_neg) pos_start = first_non_none(new_pos) start = max(neg_start, pos_start) # and reduce new_neg = new_neg[start:] new_pos = new_pos[start:] new_tot = [new_neg[i] + new_pos[i] for i in range(len(new_neg))] new_pos_perc = [float(new_pos[i]) / new_tot[i] for i in range(len(new_tot))] # - # now get some sliding window sums for averaging def sliding_window_sum(vals, window_size): # check for degenerate case if len(vals) < window_size: return [sum(vals)] # otherwise track each ret_sums = list() # get initial sum curr_sum = sum(vals[:window_size]) ret_sums.append(curr_sum) # and iterate to the end i = window_size while i < len(vals): # take off the one before the window curr_sum -= vals[i - window_size] # and add the new val into the window curr_sum += vals[i] ret_sums.append(curr_sum) i += 1 return ret_sums # get a 7-day sliding average of positive percentages new_tot_7win = sliding_window_sum(new_tot, 7) new_pos_7win = sliding_window_sum(new_pos, 7) new_pos_perc_7win = [float(new_pos_7win[i]) / new_tot_7win[i] for i in range(len(new_tot_7win))] # grab last 8 weeks of real percentages and average pos_perc_8wk = new_pos_perc[-56:] pos_perc_8wk_7win = new_pos_perc_7win[-56:] import matplotlib.pyplot as plt # and plot plt.plot(pos_perc_8wk) plt.plot(pos_perc_8wk_7win) plt.xticks([0, 7, 14, 21, 28, 35, 42, 49, 56]) plt.yticks([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.10, 0.11, 0.12, 0.13, 0.14, 0.15]) plt.ylim([-0.001, 0.151]) plt.grid() plt.show() pos_perc_8wk
dane_county_pos_rate.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 cartoframes APIKEY = "<KEY>" cc = cartoframes.CartoContext(base_url='https://lokiintelligent.carto.com/', api_key=APIKEY) from cartoframes import Credentials, CartoContext creds = Credentials(username='lokiintelligent', key='shirl3yt3mpl3') creds.save() df = cc.read('arenas_nba') df.address1 df[df.team=='Toronto Raptors'] # + import geopandas as gdp import cartoframes import pandas as pd APIKEY = "<KEY>" cc = cartoframes.CartoContext(base_url='https://lokiintelligent.carto.com/', api_key=APIKEY) from shapely.geometry import Point address_df = pd.read_csv(r'C:\Data\us\ak\city_of_juneau.csv') geometry = [Point(xy) for xy in zip(address_df.LON, address_df.LAT)] address_df = address_df.drop(['LON', 'LAT'], axis=1) crs = {'init': 'epsg:4326'} geo_df = gdp.GeoDataFrame(address_df, crs=crs, geometry=geometry) cc.write(geo_df, 'juneau_addresses')
Chapter14/Scripts/Chapter14.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 2 venv # language: python # name: python2 # --- from imctools.scripts import ometiff2analysis from imctools.scripts import cropobjects from imctools.scripts import croprandomsection from imctools.scripts import resizeimage from imctools.scripts import generatedistancetospheres from imctools.scripts import imc2tiff from imctools.scripts import ome2micat from imctools.scripts import probablity2uncertainty import os import re # %load_ext rpy2.ipython # # # This script must be adapted to use # Currently it will convert txt in subfolders of the folder base_folder into OME.tiffs # and then create tiff stacks for analysis and ilastik based on the pannel_csv # run it like this # this will create crops for ilastik # load the ilatik_random folder in ilastik and do the classifictation # check the uncertainties # # The script can also convert mcd files directly or ZIP folders containing MCD or TXT files - please ask Vito how to adapt # + # the folders with the txt/mcd files for the analysis folders = ['/home/hartlandj/Data/METABRIC/METABRIC_txt/'] # output for OME tiffs out_tiff_folder = '/home/jwindh/Data/VitoExample/ometiff' # filename part that all the imc txt files should have, can be set to '' if none common_file_part = '.txt' # a csv indicating which columns should be used for ilastik (0, 1) in ilastik column pannel_csv = '/home/jwindh/Data/VitoExample/configfiles/20170626_pannel_METABRICl.csv' metal_col = 'Metal Tag' ilastik_col = 'ilastik' # Explicitly indicates which metals should be used for the full stack full_col = 'full' # specify the folder to put the analysis in analysis_folder = '/home/jwindh/Data/VitoExample/analysis' # specify the subfolders cp_folder = '/home/jwindh/Data/VitoExample/cpout' uncertainty_folder = analysis_folder micat_folder = '/home/jwindh/Data/VitoExample/micat' sm_csv = '/home/vitoz/Data/spillover/2017007_second_ss_steph/20170707_ss_stef2__spillmat.csv' sm_outname = os.path.join(analysis_folder,'sm_full') # parameters for resizing the images for ilastik suffix_full = '_full' suffix_ilastik = '_ilastik' suffix_ilastik_scale = '_ilastik_s2' suffix_cropmask = 'cropmask' suffic_segmentation = 'sphereseg' suffix_mask = '_mask.tiff' suffix_probablities = '_probabilities' failed_images = list() re_idfromname = re.compile('_l(?P<Label>[0-9]+)_') # - # Specify which steps to run do_convert_txt = False do_stacks = True do_ilastik = True do_micat = True # Generate all the folders if necessary for fol in [out_tiff_folder, analysis_folder, cp_folder, micat_folder,uncertainty_folder]: if not os.path.exists(fol): os.makedirs(fol) # Convert txt to ome if do_convert_txt: for fol in folders: for fn in os.listdir(fol): if len([f for f in os.listdir(out_tiff_folder) if (fn.rstrip('.txt').rstrip('.mcd') in f)]) == 0: if common_file_part in fn: # and 'tuningtape' not in fn: print(fn) txtname = os.path.join(fol, fn) try: imc2tiff.save_imc_to_tiff(txtname,tifftype='ome', outpath=out_tiff_folder) except: failed_images.append(txtname) print(txtname) # Generate the analysis stacks # + if do_stacks: for img in os.listdir(out_tiff_folder): if not img.endswith('.ome.tiff'): pass basename = img.rstrip('.ome.tiff') ometiff2analysis.ometiff_2_analysis(os.path.join(out_tiff_folder, img), analysis_folder, basename+suffix_full, pannelcsv=pannel_csv, metalcolumn=metal_col, usedcolumn=full_col) # - # Generate the ilastik stacks if do_ilastik: for img in os.listdir(out_tiff_folder): if not img.endswith('.ome.tiff'): pass basename = img.rstrip('.ome.tiff') ometiff2analysis.ometiff_2_analysis(os.path.join(out_tiff_folder, img), analysis_folder, basename + suffix_ilastik, pannelcsv=pannel_csv, metalcolumn=metal_col, usedcolumn=ilastik_col, addsum=True) # -> Before the next step run the cellprofiler 'prepare_ilastik' pipeline to generate a stacks for ilastik that are scaled and have hot pixels removed # # From there run the pixel classification in Ilastik either via X2GO on our server or even better on an image processing virutal machine from the ZMB. # # For classification use 3 pixeltypes: # - Nuclei # - Cytoplasm/Membrane # - Background # # Usually it is best to label very sparsely to avoid creating a to large but redundant training data set. After initially painting few pixels, check the uncertainty frequently and only paint pixels with high uncertainty. # # Once this looks nice for all the cropped sections, batch process the whole images using the code bellow. # ## Run the ilastik classification as a batch fn_ilastikproject = '/home/jwindh/Data/VitoExample/pipeline/MyProject.ilp' bin_ilastik = "/mnt/bbvolume/labcode/ilastik-1.2.0-Linux/run_ilastik.sh" fn_ilastik_input =os.path.join(analysis_folder,"*"+suffix_ilastik_scale+'.tiff') glob_probabilities = os.path.join(analysis_folder,"{nickname}"+suffix_probablities+'.tiff') # + magic_args="-s \"$bin_ilastik\" \"$fn_ilastikproject\" \"$glob_probabilities\" \"$fn_ilastik_input\" " language="bash" # echo $1 # echo $2 # echo $3 # echo $4 # LAZYFLOW_TOTAL_RAM_MB=40000 \ # LAZYFLOW_THREADS=16\ # $1 \ # --headless --project=$2 \ # --output_format=tiff \ # --output_filename_format=$3 \ # --export_dtype uint16 --pipeline_result_drange="(0.0, 1.0)" \ # --export_drange="(0,65535)" $4 # - # ## Generate the spillovermatrix for cellprofiler compensation # + magic_args="-i pannel_csv -i metal_col -i full_col -i sm_csv -i sm_outname" language="R" # metal_col = make.names(metal_col) # full_col = make.names(full_col) # # pannel_dat = read.csv(pannel_csv) # analysis_channels = pannel_dat[pannel_dat[,full_col] ==T,metal_col] # # analysis_channels = paste(analysis_channels, 'Di', sep = '') # # sm = as.matrix(read.csv(sm_csv, row.names=1)) # # sm_table = CATALYST::adaptSpillmat(sm, analysis_channels) # # write.table(sm_table, paste0(sm_outname,'.csv')) # tiff::writeTIFF(sm_table, paste0(sm_outname,'.tiff'), bits.per.sample = 32, reduce = T) # - # ## convert probabilities to uncertainties for fn in os.listdir(analysis_folder): if fn.endswith(suffix_probablities+'.tiff'): probablity2uncertainty.probability2uncertainty(os.path.join(analysis_folder,fn), uncertainty_folder) # ## Generate the micat folder if do_micat: if not(os.path.exists(micat_folder)): os.makedirs(micat_folder) ome2micat.omefolder2micatfolder(out_tiff_folder, micat_folder, fol_masks=cp_folder,mask_suffix=suffix_mask, dtype='uint16')
examples/old_example_preprocessing_pipeline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.2 64-bit # language: python # name: python3 # --- # # Transformarea Isentropă # !pip install ipympl # %matplotlib ipympl import ipywidgets as widgets import matplotlib.pyplot as plt import numpy as np # informatia este luată de aici: # https://kapernikov.com/ipywidgets-with-matplotlib/ class Sines(widgets.HBox): def __init__(self): super().__init__() output = widgets.Output() self.x = np.linspace(0, 2*np.pi, 100) initial_color='FF00DD' with output: self.fig, self.ax = plt.subplots(constrained_layout=True, figsize=(6,4)) self.line, = self.ax.plot(self.x, np.sin(self.x),'k-') self.fig.canvas.toolbar_position='bottom' self.ax.grid(True) int_slider = widgets.IntSlider(1, 0, 10, 1,description='frequency') #color_picker = widgets.ColorPicker(value=initial_color, description='pick a color') text_xlabel = widgets.Text(value='', description='xlabel', continuous_update=False) text_ylabel = widgets.Text(value='', description='ylabel', continuous_update=False) controls = widgets.VBox([int_slider, # color_picker, text_xlabel, text_ylabel]) int_slider.observe(self.update, 'value') #color_picker.observe(self.line_color, 'value') text_xlabel.observe(self.update_xlabel, 'value') text_ylabel.observe(self.update_ylabel, 'value') text_xlabel.value = 'x' text_ylabel.value = 'y' self.children=[controls, output] def update(self, change): """Draw line in plot""" self.line.set_ydata(np.sin(change.new * self.x)) self.fig.canvas.draw() def line_color(self, change): self.line.set_color(change.new) def update_xlabel(self, change): self.ax.set_xlabel(change.new) def update_ylabel(self, change): self.ax.set_ylabel(change.new) Sines()
Notebooks/trans-isentropa.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 # --- # # Creating a simple ODE model # In this series of notebooks, we will run through the steps involved in creating a new model within pybamm. Before using pybamm we recommend following the [Getting Started](../Getting%20Started) guides. # # In this notebook we create and solve the following simple ODE model: # # \begin{align*} # \frac{\textrm{d} x}{\textrm{d} t} &= 4x - 2y, \quad x(0) = 1, \\ # \frac{\textrm{d} y}{\textrm{d} t} &= 3x - y, \quad y(0) = 2. # \end{align*} # # We begin by importing the pybamm library into this notebook, along with numpy and matplotlib, which we use for plotting: # # %pip install pybamm -q # install PyBaMM if it is not installed import pybamm import numpy as np import matplotlib.pyplot as plt # ## Setting up the model # We first initialise the model using the `BaseModel` class. This sets up the required structure for our model. model = pybamm.BaseModel() # Next, we define the variables in the model using the `Variable` class. In more complicated models we can give the variables more informative string names, but here we simply name the variables "x" and "y" x = pybamm.Variable("x") y = pybamm.Variable("y") # We can now use the symbols we have created for our variables to write out our governing equations. Note that the governing equations must be provied in the explicit form `d/dt = rhs` since pybamm only stores the right hand side (rhs) and assumes that the left hand side is the time derivative. dxdt = 4 * x - 2 * y dydt = 3 * x - y # The governing equations must then be added to the dictionary `model.rhs`. The dictionary stores key and item pairs, where the key is the variable which is governed by the equation stored in the corresponding item. Note that the keys are the symbols that represent the variables and are not the variable names (e.g. the key is `x`, not the string "x"). model.rhs = {x: dxdt, y: dydt} # The initial conditions are also stored in a dictionary, `model.initial_conditions`, which again uses the variable as the key model.initial_conditions = {x: pybamm.Scalar(1), y: pybamm.Scalar(2)} # Finally, we can add any variables of interest to our model. Note that these can be things other than the variables that are solved for. For example, we may want to store the variable defined by $z=x+4y$ as a model output. Variables are added to the model using the `model.variables` dictionary as follows: model.variables = {"x": x, "y": y, "z": x + 4 * y} # Note that the keys of this dictionary are strings (i.e. the names of the variables). The string names can be different from the variable symbol, and should in general be something informative. The model is now completely defined and is ready to be discretised and solved! # ## Using the model # We first discretise the model using the `pybamm.Discretisation` class. Calling the method `process_model` turns the model variables into a `pybamm.StateVector` object that can be passed to a solver. Since the model is a system of ODEs we do not need to provide a mesh or worry about any spatial dependence, so we can use the default discretisation. Details on how to provide a mesh will be covered in the following notebook. disc = pybamm.Discretisation() # use the default discretisation disc.process_model(model); # Now that the model has been discretised it is ready to be solved. Here we choose the ODE solver `pybamm.ScipySolver` and solve, returning the solution at 20 time points in the interval $t \in [0, 1]$ solver = pybamm.ScipySolver() t = np.linspace(0, 1, 20) solution = solver.solve(model, t) # After solving, we can extract the variables from the solution. These are automatically post-processed so that the solutions can be called at any time $t$ using interpolation. The times at which the model was solved at are stored in `solution.t` and the statevectors at those times are stored in `solution.y` t_sol, y_sol = solution.t, solution.y # get solution times and states x = solution["x"] # extract and process x from the solution y = solution["y"] # extract and process y from the solution # We then plot the numerical solution against the exact solution. # + t_fine = np.linspace(0, t[-1], 1000) fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 4)) ax1.plot(t_fine, 2 * np.exp(t_fine) - np.exp(2 * t_fine), t_sol, x(t_sol), "o") ax1.set_xlabel("t") ax1.legend(["2*exp(t) - exp(2*t)", "x"], loc="best") ax2.plot(t_fine, 3 * np.exp(t_fine) - np.exp(2 * t_fine), t_sol, y(t_sol), "o") ax2.set_xlabel("t") ax2.legend(["3*exp(t) - exp(2*t)", "y"], loc="best") plt.tight_layout() plt.show() # - # In the [next notebook](./2-a-pde-model.ipynb) we show how to create, discretise and solve a PDE model in pybamm. # ## References # # The relevant papers for this notebook are: pybamm.print_citations()
examples/notebooks/Creating Models/1-an-ode-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 # --- # <img src="https://github.com/jupytercon/2020-exactlyallan/raw/master/images/RAPIDS-header-graphic.png"> # <p style="background-color:red;color:white;font:2em"> <b> Note: It is advised to close the previous notebook kernels and clear GPU Memory in order to avoid GPU Resource Out of Memory errors </b></p> # # Data Inspection and Validation # ***Loading data, vetting its quality, and understanding its shape*** # ## Overview # This intro notebook will use cuDF and hvplot (with bokeh charts) to load a public bike share dataset and get a general sense of what it contains, then run some cursory visualization to validate that the data is free of issues. # # ### cuDF and hvplot # - [cuDF](https://docs.rapids.ai/api/cudf/stable/), the core of RAPIDS, is a Python GPU DataFrame library (built on the Apache Arrow columnar memory format) for loading, joining, aggregating, filtering, and otherwise manipulating data in a pandas-like API. # - [hvplot](https://hvplot.holoviz.org/) is a high-level plotting API for the PyData ecosystem built on [HoloViews](http://holoviews.org/). # ## Imports # Let's first make sure the necessary imports are present to load. import cudf import hvplot.cudf import cupy import pandas as pd # ## Data Size and GPU Speedups # This tutorial's dataset size is about `2.1GB` unzipped and contains about `9 million rows`. While this will do for a tutorial, its still too small to get a sense of the speed up possible with GPU acceleration. We've created a larger `300 million row` [2010 Census Visualization](https://github.com/rapidsai/plotly-dash-rapids-census-demo) application available through the RAPIDS [GitHub page](https://github.com/rapidsai) as another demo. # ## Loading Data into cuDF # We need to download and extract the sample data we will use for this tutorial. This notebook uses the Kaggle [Chicago Divvy Bicycle Sharing Data](https://www.kaggle.com/yingwurenjian/chicago-divvy-bicycle-sharing-data) dataset. Once the `data.csv` file is downloaded and unzipped, point the paths below at the location *(Make sure to set DATA_DIR to the path you saved that data file to)*: # # + from pathlib import Path DATA_DIR = Path("../data") # - # Download and Extract the dataset # ! wget -N -P {DATA_DIR} https://rapidsai-data.s3.us-east-2.amazonaws.com/viz-data/data.tar.xz # ! tar -xf {DATA_DIR}/data.tar.xz -C {DATA_DIR} FILENAME = Path("data.csv") # We now read the .csv file into the GPU cuDF Dataframe (which behaves similar to a Pandas dataframe). df = cudf.read_csv(DATA_DIR / FILENAME) # ## Mapping out the Data Shape # CuDF supports all the standard Pandas operations for a quick look at the data e.g. to see the total number of rows... len(df) # Or to inspect the column headers and first few rows... df.head() # Or to see the full list of columns... df.columns # Or see how many trips were made by subscribers. df.groupby("usertype").size() # ## Improving Data Utility # Now that we have a basic idea of how big our dataset is and what it contains, we want to start making the data more meaningful. This task can vary from removing unnecessary columns, mapping values to be more human readable, or formatting them to be understood by our tools. # # Having looked at the `df.head()` above, the first thing we might want is to re-load the data, parsing the start-stop time columns as more usable datetimes types: df = cudf.read_csv(DATA_DIR / FILENAME, parse_dates=('starttime', 'stoptime')) # One thing we will want to do is to look at trips by day of week. Now that we have real datetime columns, we can use `dt.weekday` to add a `weekday` column to our `cudf` Dataframe: df["weekday"] = df['starttime'].dt.weekday # ## Inspecting Data Quality and Distribution # Another important step is getting a sense of the quality of the dataset. As these datasets are often larger than is feasible to look through row by row, mapping out the distribution of values early on helps find issuse that can derail an analysis later. # # Some examples are gaps in data, unexpected or empty value types, infeasible values, or incorrect projections. # ## Gender and Subsriber Columns # We could do this in a numerical way, such as getting the totals from the 'gender' data column as a table: mf_counts = df.groupby("gender").size().rename("count").reset_index() mf_counts # While technically functional as a table, taking values and visualizating them as bars help to intuitively show the scale of the difference faster (hvplot's API makes this very simple): mf_counts.hvplot.bar("gender","count").opts(title="Total trips by gender") # ### A Note on Preattentive Attributes # This subconcious ability to quickly recognize patterns is due to our brain's natural ability to find [preattentive attributes](http://daydreamingnumbers.com/blog/preattentive-attributes-example/), such as height, orientation, or color. Imagine 100 values in a table and 100 in a bar chart and how quickly you would be albe to find the smallest and largest values in either. # ### Try It out # Now try using [hvplot's user guide](https://hvplot.holoviz.org/user_guide/Plotting.html) and our examples to create a hvplot that shows the distribution of `Subscriber` types: # + # code here # - # The above data columns maybe show some potentially useful disparities, but without supplimental data, it would be hard to have a follow up question. # # ## Trip Starts # Instead, another question we might want to ask is how many trip starts are there per day of the week? We can group the `cudf` Dataframe and call `hvplot.bar` directly the result: day_counts = df.groupby("weekday").size().rename("count").reset_index() day_counts.hvplot.bar("weekday", "count").opts(title="Trip starts, per Week Day", yformatter="%0.0f") # With 0-4 being a weekday, and 5-6 being a weekend, there is a clear drop off of ridership on the weekends. Lets note that! # # ## Trips by Duration # Another quick look we can generate is to see the overall distribution of trip durations, this time using `hvplot.hist`: # We selected an arbitrary 50 for bin size, try and see patterns with other sizes df.hvplot.hist(y="tripduration").opts( title="Trips Duration Histrogram", yformatter="%0.0f" ) # Clearly, most trips are less than 15 minuites long. # # `hvplot` also makes it simple to interrogate different dimensions. For example, we can add `groupby="month"` to our call to `hvplot.hist`, and automatically get a slider to see a histogram specific to each month: df.hvplot.hist(y="tripduration", bins=50, groupby="month").opts( title="Trips Duration Histrogram by Month", yformatter="%0.0f", width=400 ) # By scrubbing between the months we can start to see a pattern of slightly longer trip durations emerge during the summer months. # # # ## Trips vs Temperatures # Lets follow up on this by using `hvplot` to generate a KDE distributions using our `cudf` Dataframes for 9 million trips: df.hvplot.kde(y="temperature").opts(title="Distribution of trip temperatures") # Clearly most trips occur around a temperature sweet spot of around 65-80 degrees. # # # The `hvplot.heatmap` method can group in two dimensions and colormap according to aggregations on those groups. Here we see *average* trip duration by year and month: df.hvplot.heatmap(x='month', y='year', C='tripduration', reduce_function=cudf.DataFrame.mean , colorbar=True, cmap="Viridis") # So what we saw hinted at with the trip duration slider is much more clearly shown in this literal heatmap *(ba-dom-tss)*. # # # ## Trip Geography # Temperature and months aside, we might also want to bin the data geographically to check for anomalies. The `hvplot.hexbin` can show the counts for trip starts overlaid on a tile map: df.hvplot.hexbin(x='longitude_start', y='latitude_start', geo=True, tiles="OSM").opts(width=600, height=600) # Interestingly there seems to be a strong concentration of trips in a core area that radiate outwards. Lets take note of that. # # The location of the data compared to a current system map also seems to show that everything is where it should be, without any extraneous data points or off map projections: # # <img src="https://raw.githubusercontent.com/jupytercon/2020-exactlyallan/master/images/DivvyBikesStation_ map.png" /> # ## Data Cleanup # Based on our inspection, this dataset is uncommonly well formatted and of high quality. But a little cleanup and formatting aids will make some things simpler in future notebooks. # # One thing that is missing is a list of just station id's and their coordinates. Let's generate that and save it for later. First, let's group by all the unique "from" and "to" station id values, and take a representative from each group: from_ids = df.groupby("from_station_id") to_ids = df.groupby("to_station_id") # It's possible (but unlikely) that a particular station is only a sink or source for trips. For good measure, let's make sure the group keys are identical: all(from_ids.size().index.values == to_ids.size().index.values) # Each group has items for a single station, which all have the same lat/lon. So let's make a new DataFrame by taking a representative from each group, then rename some columns: stations = from_ids.nth(1).to_pandas() stations.index.name = "station_id" stations.rename(columns={"latitude_start": "lat", "longitude_start": "lon"}, inplace=True) stations = stations.reset_index().filter(["station_id", "lat", "lon"]) stations # Finally write the results to "stations.csv" in our data directory: stations.to_csv(DATA_DIR / "stations.csv", index=False) # ## Summary of the Data # Overall this is an interesting and useful dataset. Our preliminary vetting found no issues with quality and already started to hint at areas to investigate: # # - Weekday vs Weekend trip counts # - Bike trips vs weather correlation # - Core vs Outward trip concentrations # # We will follow up with these findings in our next notebook.
notebooks/01 Data Inspection and 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 # --- # replace __ with string if True: result = 'true value' else: result = 'false value' #self.assertEqual(__, result) assert __ == result # replace __ with string result = 'default value' if True: result = 'true value' assert __ == result # replace __ with string if False: result = 'first value' elif True: result = 'true value' else: result = 'default value' assert __ == result # replace __ with an int i = 1 result = 1 while i <= 10: result = result * i i += 1 assert __ == result # replace __ with an int i = 1 result = 1 while True: if i > 10: break result = result * i i += 1 assert __ == result # replace __ with a list of ints i = 0 result = [] while i < 10: i += 1 if (i % 2) == 0: continue result.append(i) assert __ == result # replace __ with a list of strings phrase = ["fish", "and", "chips"] result = [] for item in phrase: result.append(item.upper()) assert __ == result # + # replace __ with regex (in raw string format) import re round_table = [ ("Lancelot", "Blue"), ("Galahad", "I don't know!"), ("Robin", "Blue! I mean Green!"), ("Arthur", "Is that an African Swallow or European Swallow?") ] result = [] for knight, answer in round_table: result.append("Contestant: '" + knight + "' Answer: '" + answer + "'") text = __ assert re.match(text, result[2]) != None #i.e. is a match assert re.match(text, result[0]) == None #i.e. is not a match assert re.match(text, result[1]) == None assert re.match(text, result[3]) == None
control_koans.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 # --- # <h1 style="font-size:35px; # color:black; # ">Lab 3 Accuracy of Quantum Phase Estimation</h1> # Prerequisite # - [Ch.3.5 Quantum Fourier Transform](https://qiskit.org/textbook/ch-algorithms/quantum-fourier-transform.html) # - [Ch.3.6 Quantum Phase Estimation](https://qiskit.org/textbook/ch-algorithms/quantum-phase-estimation.html) # # Other relevant materials # - [QCQI] <NAME> and <NAME>. 2011. Quantum Computation and Quantum Information from qiskit import * import numpy as np from qiskit.visualization import plot_histogram import qiskit.tools.jupyter from qiskit.tools.monitor import job_monitor from qiskit.ignis.mitigation.measurement import * import matplotlib.pyplot as plt # <h2 style="font-size:24px;">Part 1: Performance of Quantum Phase Estimation</h2> # # <br> # <div style="background: #E8E7EB; border-radius: 5px; # -moz-border-radius: 5px;"> # <p style="background: #800080; # border-radius: 5px 5px 0px 0px; # padding: 10px 0px 10px 10px; # font-size:18px; # color:white; # "><b>Goal</b></p> # <p style=" padding: 0px 0px 10px 10px; # font-size:16px;">Investigate the relationship between the number of qubits required for the desired accuracy of the phase estimation with high probability.</p> # </div> # # # The accuracy of the estimated value through Quantum Phase Estimation (QPE) and its probability of success depend on the number of qubits employed in QPE circuits. Therefore, one might want to know the necessary number of qubits to achieve the targeted level of QPE performance, especially when the phase that needs to be determined cannot be decomposed in a finite bit binary expansion. # In Part 1 of this lab, we examine the number of qubits required to accomplish the desired accuracy and the probability of success in determining the phase through QPE. # <h3 style="font-size: 20px">1. Find the probability of obtaining the estimation for a phase value accurate to $2^{-2}$ successfully with four counting qubits.</h3> # <h4 style="font-size: 17px">&#128211;Step A. Set up the QPE circuit with four counting qubits and save the circuit to the variable 'qc4'. Execute 'qc4' on a qasm simulator. Plot the histogram of the result.</h4> # Check the QPE chapter in Qiskit textbook ( go to `3. Example: Getting More Precision` section [here](https://qiskit.org/textbook/ch-algorithms/quantum-phase-estimation.html#3.-Example:-Getting-More-Precision-) ) for the circuit. def qft(n): """Creates an n-qubit QFT circuit""" circuit = QuantumCircuit(n) def swap_registers(circuit, n): for qubit in range(n//2): circuit.swap(qubit, n-qubit-1) return circuit def qft_rotations(circuit, n): """Performs qft on the first n qubits in circuit (without swaps)""" if n == 0: return circuit n -= 1 circuit.h(n) for qubit in range(n): circuit.cp(np.pi/2**(n-qubit), qubit, n) qft_rotations(circuit, n) qft_rotations(circuit, n) swap_registers(circuit, n) return circuit # + ## Start your code to create the circuit, qc4 qc4.draw() # - ## Run this cell to simulate 'qc4' and to plot the histogram of the result sim = Aer.get_backend('qasm_simulator') shots = 20000 count_qc4 = execute(qc4, sim, shots=shots).result().get_counts() plot_histogram(count_qc4, figsize=(9,5)) # Having performed `Step A` successfully, you will have obtained a distribution similar to the one shown below with the highest probability at `0101` which corresponds to the estimated $\phi$ value, `0.3125`. # ![](image/L3_qc4_hist.png) # Since the number of counting qubits used for the circuit is four, the best estimated value should be accurate to $\delta = 2^{-4} = 0.0625$. However, there are multiple possible outcomes as $\theta = 1/3$ cannot be expressed in a finite number of bits, the estimation by QPE here is not always bounded by this accuracy. # Running the following cell shows the same histogram but with all possible estimated $\phi$ values on the x-axis. phi_est = np.array([round(int(key, 2)/2**t,3) for key in list(count_qc4.keys())]) key_new = list(map(str, phi_est)) count_new = dict(zip(key_new, count_qc4.values())) plot_histogram(count_new, figsize=(9,5)) # **Suppose the outcome of the final measurement is $m$, and let $b$ the best estimation which is `0.3125` for this case.** # <h4 style="font-size: 17px">&#128211;Step B. Find $e$, the maximum difference in integer from the best estimation <code>0101</code> so that all the outcomes, 'm's, would approximate $\phi$ to an accuracy $2^{-2}$ when $|m - b| \leq \frac{e}{2^{t}}$. </h4> # In this case, the values of $t$ and $b$ are $4$ and $0.3125$, respectively. # For example, under $e = 1$, the considered outcomes are `0100`, `0101`, `0110` which correspond to the values of $m$: $0.25,~0.312,~0.375$, respectively, and all of them approximate the value $\frac{1}{3}$ to an accuracy $2^{-2}$. # + ## Your code goes here # - # <h4 style="font-size: 17px">&#128211;Step C. Compute the probability of obtaining an approximation correct to an accuracy $2^{-2}$. Verify that the computed probability value is larger or equal to $1- \frac{1}{2(2^{(t-n)}-2)}$ where $t$ is the number of counting bits and the $2^{-n}$ is the desired accuracy. </h4> # Now it is easy to evaluate the probability of the success from the histogram since all the outcomes that approximate $\phi$ to the accuracy $2^{-2}$ can be found based on the maximum difference $e$ from the best estimate. # + ## Your code goes here # - # <h3 style="font-size: 20px">2. Compute the probability of success for the accuracy $2^{-2}$ when the number of counting qubits, $t$, varies from four to nine. Compare your result with the equation $t=n+log(2+\frac{1}{2\epsilon})$ when $2^{-n}$ is the desired accuracy and $\epsilon$ is 1 - probability of success.</h3> # The following plot shows the relationship between the number of counting qubit, t, and the minimum probability of success to approximate the phase to an accuracy $2^{-2}$. Check the Ch. 5.2.1 Performance and requirements in `[QCQI]`. # + y = lambda t, n: 1-1/(2*(2**(t-n)-2)) t_q = np.linspace(3.5, 9.5, 100 ) p_min = y(t_q, 2) plt.figure(figsize=(7, 5)) plt.plot(t_q, p_min, label='$p_{min}$') plt.xlabel('t: number of counting qubits') plt.ylabel('probability of success for the accuracy $2^{-2}$') plt.legend(loc='lower right') plt.title('Probability of success for different number of counting qubits') plt.show() # - # <h4 style="font-size: 17px">&#128211;Step A. Construct QPE circuit to estimate $\phi$ when $\phi = 1/3$ with for the different number of counting qubits, $t$, when $t = [4, 5, 6, 7, 8, 9]$. Store all the circuits in a list variable 'circ' to simulate all the circuits at once as we did in Lab2. </h4> # + ## Your Code to create the list variable 'circ' goes here # + # Run this cell to simulate `circ` and plot the histograms of the results results = execute(circ, sim, shots=shots).result() n_circ = len(circ) counts = [results.get_counts(idx) for idx in range(n_circ)] fig, ax = plt.subplots(n_circ,1,figsize=(25,40)) for idx in range(n_circ): plot_histogram(counts[idx], ax=ax[idx]) plt.tight_layout() # - # <h4 style="font-size: 17px">&#128211;Step B. Determine $e$, the maximum difference in integer from the best estimation for the different number of counting qubits, $t = [4, 5, 6, 7, 8, 9]$. Verify the relationship $e=2^{t-n}-1$ where $n=2$ since the desired accuracy is $2^{-2}$ in this case. </h4> # + ## Your Code goes here # - # If you successfully calculated $e$ values for all the counting qubits, $t=[4,5,6,7,8,9]$, you will be able to generate the following graph that verifies the relationship $e = 2^{t-2} -1$ with the $e$ values that you computed. # ![](image/L3_e_max.png) # <h4 style="font-size: 17px">&#128211;Step C. Evaluate the probability of success estimating $\phi$ to an accuracy $2^{-2}$ for all the values of $t$, the number of counting qubits. Save the probabilities to the list variable, 'prob_success'. </h4> # + ## Your code to create the list variable, 'prob_success', goes here # - # <h4 style="font-size: 17px">&#128211;Step D. Overlay the results of Step C on the graph that shows the relationship between the number of counting qubits, $t$, and the minimum probability of success to approximate the phase to an accuracy $2^{-2}$. Understand the result. </h4> # + ## Your code goes here # - # ![](image/L3_prob_t.png) # Your plot should be similar to the above one. # The line plot in the left panel shows the minimum success probability to estimate $\phi$ within the accuracy $2^{-2}$ as the number of counting qubits varies. The overlaid orange dots are the same values, but from the simulation, which confirms the relationship the line plot represents as the lower bound. The right panel displays the same result but zoomed by adjusting the y-axis range. # The following graph exhibits the relationships with different accuracy levels. The relationship, $t=n+log(2+\frac{1}{2\epsilon})$, indicates the number of counting qubits $t$ to estimate $\phi$ to an accuracy $2^{-2}$ with probability of success at least $1-\epsilon$, as we validated above. # + t = np.linspace(5.1, 10, 100) prob_success_n = [y(t, n) for n in [2, 3, 4]] prob_n2, prob_n3, prob_n4 = prob_success_n[0], prob_success_n[1], prob_success_n[2] plt.figure(figsize=(7, 5)) plt.plot(t, prob_n2, t, prob_n3, t, prob_n4, t, [1]*len(t),'--' ) plt.axis([5, 10, 0.7, 1.05]) plt.xlabel('t: number of counting qubits') plt.ylabel('probability of success for the accuracy $2^{-n}$') plt.legend(['n = 2', 'n = 3', 'n = 4'], loc='lower right') plt.grid(True) # - # <h2 style="font-size:24px;">Part 2: QPE on Noisy Quantum System</h2> # # <br> # <div style="background: #E8E7EB; border-radius: 5px; # -moz-border-radius: 5px;"> # <p style="background: #800080; # border-radius: 5px 5px 0px 0px; # padding: 10px 0px 10px 10px; # font-size:18px; # color:white; # "><b>Goal</b></p> # <p style=" padding: 0px 0px 10px 10px; # font-size:16px;">Run the QPE circuit on a real quantum system to understand the result and limitations when using noisy quantum systems</p> # </div> # # # The accuracy analysis that we performed in Part 1 would not be correct when the QPE circuit is executed on present day noisy quantum systems. In part 2, we will obtain QPE results by running the circuit on a backend from IBM Quantum Experience to examine how noise affects the outcome and learn techniques to reduce its impact. # <h4 style="font-size: 17px">&#128211;Step A. Load your account and select the backend from your provider. </h4> # + ## Your code goes here. # - # <h4 style="font-size: 17px">&#128211;Step B. Generate multiple ( as many as you want ) transpiled circuits of <code>qc4</code> that you set up in Part 1 at the beginning. Choose one with the minimum circuit depth, and the other with the maximum circuit depth.</h4> # Transpile the circuit with the parameter `optimization_level = 3` to reduce the error in the result. As we learned in Lab 1, Qiskit by default uses a stochastic swap mapper to place the needed SWAP gates, which varies the transpiled circuit results even under the same runtime settings. Therefore, to achieve shorter depth transpiled circuit for smaller error in the outcome, transpile `qc4` multiple times and choose one with the minimum circuit depth. Select the maximum circuit depth one as well for comparison purposes. # + ## Your code goes here # - # <h4 style="font-size: 17px">&#128211;Step C. Execute both circuits on the backend that you picked. Plot the histogram for the results and compare them with the simulation result in Part 1.</h4> # + ## Your code goes here # - # The following shows the sample result. # ![](image/L3_QPEresults.png) # <h4 style="font-size: 17px">Step D. Measurement Error Mitigation </h4> # In the previous step, we utilized our knowledge about Qiskit transpiler to get the best result. Here, we try to mitigate the errors in the result further through the measurement mitigation technique that we learned in Lab 2. # <p>&#128211;Construct the circuits to profile the measurement errors of all basis states using the function 'complete_meas_cal'. Obtain the measurement filter object, 'meas_filter', which will be applied to the noisy results to mitigate readout (measurement) error. # + ## Your Code goes here # - # <p>&#128211;Plot the histogram of the results before and after the measurement error mitigation to exhibit the improvement. # + ## Your Code goes here # - # The following plot shows the sample result. # ![](image/L3_QPEresults_final.png) # The figure below displays a simulation result with the sample final results from both the best and worst SWAP mapping cases after applying the measurement error mitigation. In Lab 2, as the major source of the error was from the measurement, after the error mitigation procedure, the outcomes were significantly improved. For QPE case, however, the measurement error doesn't seem to be the foremost cause for the noise in the result; CNOT gate errors dominate the noise profile. In this case, choosing the transpiled circuit with the least depth was the crucial procedure to reduce the errors in the result. # ![](image/L3_QPE_final.png)
content/ch-labs/Lab03_AccuracyQPE.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 folium m = folium.Map(location=[45.5236, -122.6750]) m # + m = folium.Map(location=[45.372, -121.6972], zoom_start=12, tiles="Stamen Terrain") tooltip = "Click me!" folium.Marker( [45.3288, -121.6625], popup="<i>Mt. Hood Meadows</i>", tooltip=tooltip ).add_to(m) folium.Marker( [45.3311, -121.7113], popup="<b>Timberline Lodge</b>", tooltip=tooltip ).add_to(m) m # -
docs/notebooks/folium_intro.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. # Notebook authors: <NAME> (<EMAIL>) # and <NAME> (<EMAIL>) # This notebook reproduces figures for chapter 17 from the book # "Probabilistic Machine Learning: An Introduction" # by <NAME> (MIT Press, 2021). # Book pdf is available from http://probml.ai # - # <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/pml-book/blob/main/pml1/figure_notebooks/chapter17_kernel_methods_figures.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ## Figure 17.1:<a name='17.1'></a> <a name='ARDkernel'></a> # # Function samples from a GP with an ARD kernel. (a) $\ell _1=\ell _2=1$. Both dimensions contribute to the response. (b) $\ell _1=1$, $\ell _2=5$. The second dimension is essentially ignored. Adapted from Figure 5.1 of <a href='#Rasmussen06'>[RW06]</a> . # Figure(s) generated by [gprDemoArd.py](https://github.com/probml/pyprobml/blob/master/scripts/gprDemoArd.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gprDemoArd.py # ## Figure 17.2:<a name='17.2'></a> <a name='maternKernel'></a> # # Functions sampled from a GP with a Matern kernel. (a) $\nu =5/2$. (b) $\nu =1/2$. # Figure(s) generated by [gpKernelPlot.py](https://github.com/probml/pyprobml/blob/master/scripts/gpKernelPlot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gpKernelPlot.py # ## Figure 17.3:<a name='17.3'></a> <a name='GPsamplesPeriodic'></a> # # Functions sampled from a GP using various stationary periodic kernels. # Figure(s) generated by [gpKernelPlot.py](https://github.com/probml/pyprobml/blob/master/scripts/gpKernelPlot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gpKernelPlot.py # ## Figure 17.4:<a name='17.4'></a> <a name='duvenaud-2-2'></a> # # Examples of 1d structures obtained by multiplying elementary kernels. Top row shows $\mathcal K (x,x'=1)$. Bottom row shows some functions sampled from $GP(f|0,\mathcal K )$. From Figure 2.2 of <a href='#duvenaud-thesis-2014'>[Duv14]</a> . Used with kind permission of <NAME> #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.4.png" width="256"/> # ## Figure 17.5:<a name='17.5'></a> <a name='duvenaud-2-4'></a> # # Examples of 1d structures obtained by adding elementary kernels. Here $\mathrm SE ^ (\mathrm short ) $ and $\mathrm SE ^ (\mathrm long ) $ are two SE kernels with different length scales. From Figure 2.4 of <a href='#duvenaud-thesis-2014'>[Duv14]</a> . Used with kind permission of <NAME> #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.5.png" width="256"/> # ## Figure 17.6:<a name='17.6'></a> <a name='GPGM'></a> # # A Gaussian process for 2 training points, $ \bm x _1$ and $ \bm x _2$, and 1 testing point, $ \bm x _ * $, represented as a graphical model representing $p( \bm y , \bm f _ X |\mathbf X ) = \mathcal N ( \bm f _ X |m(\mathbf X ), \mathcal K (\mathbf X )) \DOTSB \prod@ \slimits@ _i p(y_i|f_i)$. The hidden nodes $f_i=f( \bm x _i)$ represent the value of the function at each of the data points. These hidden nodes are fully interconnected by undirected edges, forming a Gaussian graphical model; the edge strengths represent the covariance terms $\Sigma _ ij =\mathcal K ( \bm x _i, \bm x _j)$. If the test point $ \bm x _ * $ is similar to the training points $ \bm x _1$ and $ \bm x _2$, then the value of the hidden function $f_ * $ will be similar to $f_1$ and $f_2$, and hence the predicted output $y_*$ will be similar to the training values $y_1$ and $y_2$ #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.6.png" width="256"/> # ## Figure 17.7:<a name='17.7'></a> <a name='gpr'></a> # # (a) some functions sampled from a GP prior with squared exponential kernel. (b-d) : some samples from a GP posterior, after conditioning on 1,2, and 4 noise-free observations. The shaded area represents $\mathbb E \left[ f( \bm x ) \right ] \pm 2 \mathrm std \left[ f( \bm x ) \right ]$. Adapted from Figure 2.2 of <a href='#Rasmussen06'>[RW06]</a> . # Figure(s) generated by [gprDemoNoiseFree.py](https://github.com/probml/pyprobml/blob/master/scripts/gprDemoNoiseFree.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gprDemoNoiseFree.py # ## Figure 17.8:<a name='17.8'></a> <a name='gprParams'></a> # # Some 1d GPs with SE kernels but different hyper-parameters fit to 20 noisy observations. The hyper-parameters $(\ell ,\sigma _f,\sigma _y)$ are as follows: (a) (1,1,0.1) (b) (3.0, 1.16, 0.89). Adapted from Figure 2.5 of <a href='#Rasmussen06'>[RW06]</a> . # Figure(s) generated by [gprDemoChangeHparams.py](https://github.com/probml/pyprobml/blob/master/scripts/gprDemoChangeHparams.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gprDemoChangeHparams.py # ## Figure 17.9:<a name='17.9'></a> <a name='gprLocalMin'></a> # # Illustration of local minima in the marginal likelihood surface. (a) We plot the log marginal likelihood vs kernel length scale $\ell $ and observation noise $\sigma _y$, for fixed signal level $\sigma _f=1$, using the 7 data points shown in panels b and c. (b) The function corresponding to the lower left local minimum, $(\ell ,\sigma _y) \approx (1,0.2)$. This is quite ``wiggly'' and has low noise. (c) The function corresponding to the top right local minimum, $(\ell ,\sigma _y) \approx (10,0.8)$. This is quite smooth and has high noise. The data was generated using $(\ell ,\sigma _f,\sigma _y)=(1,1,0.1)$. Adapted from Figure 5.5 of <a href='#Rasmussen06'>[RW06]</a> . # Figure(s) generated by [gpr_demo_marglik.py](https://github.com/probml/pyprobml/blob/master/scripts/gpr_demo_marglik.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gpr_demo_marglik.py # ## Figure 17.10:<a name='17.10'></a> <a name='gpClassifyIris2'></a> # # GP classifier for a binary classification problem on Iris flowers (Setosa vs Versicolor) using a single input feature (sepal length). The fat vertical line is the credible interval for the decision boundary. (a) SE kernel. (b) SE plus linear kernel. Adapted from Figures 7.11--7.12 of <a href='#Martin2018'>[Mar18]</a> . # Figure(s) generated by [gp_classify_iris_1d_pymc3.py](https://github.com/probml/pyprobml/blob/master/scripts/gp_classify_iris_1d_pymc3.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gp_classify_iris_1d_pymc3.py # ## Figure 17.11:<a name='17.11'></a> <a name='gpClassifySpaceFlu'></a> # # (a) Fictitious ``space flu'' binary classification problem. (b) Fit from a GP with SE kernel. Adapted from Figures 7.13--7.14 of <a href='#Martin2018'>[Mar18]</a> . # Figure(s) generated by [gp_classify_spaceflu_1d_pymc3.py](https://github.com/probml/pyprobml/blob/master/scripts/gp_classify_spaceflu_1d_pymc3.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n gp_classify_spaceflu_1d_pymc3.py # ## Figure 17.12:<a name='17.12'></a> <a name='largeMargin'></a> # # Illustration of the large margin principle. Left: a separating hyper-plane with large margin. Right: a separating hyper-plane with small margin #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.12.png" width="256"/> # ## Figure 17.13:<a name='17.13'></a> <a name='margin'></a> # # (a) Illustration of the geometry of a linear decision boundary in 2d. A point $ \bm x $ is classified as belonging in decision region $\mathcal R _1$ if $f( \bm x )>0$, otherwise it belongs in decision region $\mathcal R _0$; $ \bm w $ is a vector which is perpendicular to the decision boundary. The term $w_0$ controls the distance of the decision boundary from the origin. $ \bm x _ \perp $ is the orthogonal projection of $ \bm x $ onto the boundary. The signed distance of $ \bm x $ from the boundary is given by $f( \bm x )/|| \bm w ||$. Adapted from Figure 4.1 of <a href='#BishopBook'>[Bis06]</a> . (b) Points with circles around them are support vectors, and have dual variables $\alpha _n >0$. In the soft margin case, we associate a slack variable $\xi _n$ with each example. If $0 < \xi _n < 1$, the point is inside the margin, but on the correct side of the decision boundary. If $\xi _n>1$, the point is on the wrong side of the boundary. Adapted from Figure 7.3 of <a href='#BishopBook'>[Bis06]</a> #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.13_A.png" width="256"/> # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.13_B.png" width="256"/> # ## Figure 17.14:<a name='17.14'></a> <a name='SVMfeatureScaling'></a> # # Illustration of the benefits of scaling the input features before computing a max margin classifier. Adapted from Figure 5.2 of <a href='#Geron2019'>[Aur19]</a> . # Figure(s) generated by [svm_classifier_feature_scaling.py](https://github.com/probml/pyprobml/blob/master/scripts/svm_classifier_feature_scaling.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n svm_classifier_feature_scaling.py # ## Figure 17.15:<a name='17.15'></a> <a name='tipping-logodds'></a> # # Log-odds vs $x$ for 3 different methods. Adapted from Figure 10 of <a href='#Tipping01'>[Tip01]</a> . Used with kind permission of Mike Tipping #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.15.png" width="256"/> # ## Figure 17.16:<a name='17.16'></a> <a name='multiclassDiscrim'></a> # # (a) The one-versus-rest approach. The green region is predicted to be both class 1 and class 2. (b) The one-versus-one approach. The label of the green region is ambiguous. Adapted from Figure 4.2 of <a href='#BishopBook'>[Bis06]</a> #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.16_A.png" width="256"/> # <img src="https://raw.githubusercontent.com/probml/pml-book/main/pml1/figures/images/Figure_17.16_B.png" width="256"/> # ## Figure 17.17:<a name='17.17'></a> <a name='rbfMoons'></a> # # SVM classifier with RBF kernel with precision $\gamma $ and regularizer $C$ applied to two moons data. Adapted from Figure 5.9 of <a href='#Geron2019'>[Aur19]</a> . # Figure(s) generated by [svm_classifier_2d.py](https://github.com/probml/pyprobml/blob/master/scripts/svm_classifier_2d.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n svm_classifier_2d.py # ## Figure 17.18:<a name='17.18'></a> <a name='SVMvsCgamma'></a> # # (a) A cross validation estimate of the 0-1 error for an SVM classifier with RBF kernel with different precisions $\gamma =1/(2\sigma ^2)$ and different regularizer $\lambda =1/C$, applied to a synthetic data set drawn from a mixture of 2 Gaussians. (b) A slice through this surface for $\gamma =5$ The red dotted line is the Bayes optimal error, computed using Bayes rule applied to the model used to generate the data. Adapted from Figure 12.6 of <a href='#HastieBook'>[HTF09]</a> . # Figure(s) generated by [svmCgammaDemo.py](https://github.com/probml/pyprobml/blob/master/scripts/svmCgammaDemo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n svmCgammaDemo.py # ## Figure 17.19:<a name='17.19'></a> <a name='etube'></a> # # (a) Illustration of $\ell _2$, Huber and $\epsilon $-insensitive loss functions, where $\epsilon =1.5$. # Figure(s) generated by [huberLossPlot.py](https://github.com/probml/pyprobml/blob/master/scripts/huberLossPlot.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n huberLossPlot.py # ## Figure 17.20:<a name='17.20'></a> <a name='SVR'></a> # # Illustration of support vector regression. Adapted from Figure 5.11 of <a href='#Geron2019'>[Aur19]</a> . # Figure(s) generated by [svm_regression_1d.py](https://github.com/probml/pyprobml/blob/master/scripts/svm_regression_1d.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n svm_regression_1d.py # ## Figure 17.21:<a name='17.21'></a> <a name='kernelClassif'></a> # # Example of non-linear binary classification using an RBF kernel with bandwidth $\sigma =0.3$. (a) L2VM. (b) L1VM. (c) RVM. (d) SVM. Black circles denote the support vectors. # Figure(s) generated by [kernelBinaryClassifDemo.py](https://github.com/probml/pyprobml/blob/master/scripts/kernelBinaryClassifDemo.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n kernelBinaryClassifDemo.py # ## Figure 17.22:<a name='17.22'></a> <a name='kernelRegrDemoData'></a> # # Model fits for kernel based regression on the noisy sinc function using an RBF kernel with bandwidth $\sigma =0.3$. (a) L2VM with $\lambda =0.5$. (b) L1VM with $\lambda =0.5$. (c) RVM. (d) SVM regression with $C=1/\lambda $. chosen by cross validation. Red circles denote the retained training exemplars. # Figure(s) generated by [rvm_regression_1d.py](https://github.com/probml/pyprobml/blob/master/scripts/rvm_regression_1d.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n rvm_regression_1d.py # ## Figure 17.23:<a name='17.23'></a> <a name='kernelRegrDemoStem'></a> # # Estimated coefficients for the models in \cref fig:kernelRegrDemoData . # Figure(s) generated by [rvm_regression_1d.py](https://github.com/probml/pyprobml/blob/master/scripts/rvm_regression_1d.py) #@title Click me to run setup { display-mode: "form" } try: if PYPROBML_SETUP_ALREADY_RUN: print('skipping setup') except: PYPROBML_SETUP_ALREADY_RUN = True print('running setup...') # !git clone --depth 1 https://github.com/probml/pyprobml /pyprobml &> /dev/null # %cd -q /pyprobml/scripts # %reload_ext autoreload # %autoreload 2 # !pip install superimport deimport -qqq import superimport def try_deimport(): try: from deimport.deimport import deimport deimport(superimport) except Exception as e: print(e) print('finished!') try_deimport() # %run -n rvm_regression_1d.py # ## References: # <a name='Geron2019'>[Aur19]</a> <NAME> "Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques for BuildingIntelligent Systems (2nd edition)". (2019). # # <a name='BishopBook'>[Bis06]</a> <NAME> "Pattern recognition and machine learning". (2006). # # <a name='duvenaud-thesis-2014'>[Duv14]</a> <NAME> "Automatic Model Construction with Gaussian Processes". (2014). # # <a name='HastieBook'>[HTF09]</a> <NAME>, <NAME> and <NAME>. "The Elements of Statistical Learning". (2009). # # <a name='Martin2018'>[Mar18]</a> <NAME> "Bayesian analysis with Python". (2018). # # <a name='Rasmussen06'>[RW06]</a> <NAME> and <NAME>. "Gaussian Processes for Machine Learning". (2006). # # <a name='Tipping01'>[Tip01]</a> <NAME> "Sparse Bayesian learning and the relevance vector machine". In: jmlr (2001). # #
pml1/figure_notebooks/chapter17_kernel_methods_figures.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: fmri # language: python # name: fmri # --- # # Encoding combined model results # + language="bash" # # . ~/.bashrc # module load fsl # # cd /u/project/monti/Analysis/Analogy/analysis/group/encoding # # mkdir vis # fslmaths ab-mainrel-kfold-elasticnet-lambda1/n1000-ab_BARTnorm_cv-relation_tfce_corrp_tstat1.nii.gz \ # -thr .95 -bin vis/ab-BARTnorm_1 # # fslmaths ab-mainrel-kfold-elasticnet-lambda1/n1000-ab_BART_cv-relation_tfce_corrp_tstat1.nii.gz \ # -thr .95 vis/ab-BART_thr95 # # fslmaths cd-mapping/n1000-CDMatch_rstpostprob79_tfce_corrp_tstat1.nii.gz \ # -thr .95 -bin -mul 2 vis/cd-BART_2 # # fslmaths vis/ab-BARTnorm_1 -add vis/cd-BART_2 vis/encoding-result # + language="bash" # # . ~/.bashrc # module load fsl # # cd /u/project/monti/Analysis/Analogy/analysis/group/encoding # # mkdir vis # # fslmaths ab-mainrel-kfold-elasticnet-lambda1/n5000-ab_BART_cv-relation_tfce_p_tstat1.nii.gz \ # -thr .95 vis/ab-BART_uncorrp_thr95 # # fslmaths ab-mainrel-kfold-elasticnet-lambda1/n5000-ab_BART_cv-relation_tfce_corrp_tstat1.nii.gz \ # -mas vis/ab-BART_uncorrp_thr95 vis/ab-BART_corrp_masked_uncorrp # # # + language="bash" # # . ~/.bashrc # module load fsl # # cd /u/project/monti/Analysis/Analogy/analysis/group/multivariate/rsa/pearson # # mkdir vis # fslmaths n1000-AB_BART79_tfce_corrp_tstat1 -thr .95 -bin sig_mask # fslmaths n1000-AB_BART79-accuracy_tfce_corrp_tstat1 \ # -mul sig_mask \ # -thr .95 -bin -mul 2 vis/bart-acc_2 # # fslmaths n1000-AB_BART79-baseline_tfce_corrp_tstat1 \ # -mul sig_mask \ # -thr .95 -bin vis/bart-base # # fslmaths vis/bart-base -add vis/bart-acc_2 vis/bart-vs-other_2 # # rm sig_mask # # fslmaths n1000-AB_BART79_vox_fdrp_tstat1 -thr .95 -bin sig_mask # fslmaths n1000-AB_BART79-accuracy_vox_fdrp_tstat1 \ # -mul sig_mask \ # -thr .95 -bin -mul 2 vis/bart-acc_2 # # fslmaths n1000-AB_BART79-baseline_tfce_corrp_tstat1 \ # -mul sig_mask \ # -thr .95 -bin vis/bart-base # # rm sig_mask # # fslmaths vis/bart-base -add vis/bart-acc_2 vis/bart-vs-other_2 # - # # Model correlations # + import json import sys import os os.chdir("..") from datetime import datetime # import pandas as pd import numpy as np from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import LeaveOneGroupOut from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from analysis.fmri.analogy_utils import analysisSettings, contrastSettings, projectSettings, \ PATHS, order, \ pu, pa, pv, rsa, \ compile_models, save_rois, load_rois, load_betas from analysis.fmri.analogy_rsa import get_model_rdms paths = PATHS # %matplotlib inline import matplotlib.pyplot as plt # model_figure # plotmodels_old(models, save=False) modelnames = ["mainrel", "w2vdiff", "concatword", "rstpostprob79", "bart79thresh", "accuracy"] raw_vis_models_df = pu.load_labels(os.path.join(paths["code"], "labels", "raw_models.csv")) vis_model_rdms = get_model_rdms(raw_vis_models_df, modelnames) # .sort_values("MainCond", "ABTag") f = plt.figure(figsize=(20,10)) axarr = f.subplots(1, len(vis_model_rdms.name.unique())) rdms = vis_model_rdms[vis_model_rdms.type == "avg"] for j, m in enumerate(vis_model_rdms.name.unique()): pv.plot_rdm(rdms[rdms.name==m].iloc[:, 2:].dropna(axis=1), ax=axarr[j], cb=False, cmap="plasma") # axarr[j].set_title(m) axarr[j].set_axis_off() # Relationship between the models model_rdms = vis_model_rdms modelnames = ["", "Baseline", "Word2vec-diff", "Word2vec-concat", "BART", "BART-thresh", "Accuracy"] f = plt.figure(figsize=(11, 11)) ax = f.gca() # f, axarr = plt.subplots(1,3, figsize=(11, 8.5)) im = ax.matshow( model_rdms[model_rdms.type == "avg"].dropna(axis=1).iloc[:, 2:].T.corr(method="spearman"), vmin=-1, vmax=1, cmap="bwr") f.colorbar(im, fraction=0.046, pad=0.04) # ax.set_xticks(range(len(modelnames))) # ax.set_yticks(range(len(modelnames))) ax.set_yticklabels(modelnames, fontsize=20) ax.set_xticklabels(modelnames, rotation=45, fontsize=20) # -
notebooks/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.8.5 64-bit (conda) # name: python385jvsc74a57bd0b3ba2566441a7c06988d0923437866b63cedc61552a5af99d1f4fb67d367b25f # --- # + # default_exp Regular_Expresssions # - # # Regular Expresssions in Python # # > Note: The interesting stuff #hide from nbdev.showdoc import * # First line of all python programs should be a shebang line # # # A phone number in the US is 3 digits a - 3 more digies a dash and then 4 digists like: # # 415-555-0000 # # whereas we know this is not a phone number: # # 4,155,550,0000 # # # Regex are like the advanced search feature in Word # # ![](.\images\Word_Regular_Expressions_like_search.png) # + #export def isPhoneNumber(text): if len(text) != 12: return False # not phone number size for i in range(0,3): if not text[i].isdecimal(): return False # no are code if text[3] != '-': return False # missing dash for i in range(4,7): if not text[i].isdecimal(): return False # no second position 3 digits if text[7] != '-': return False # missing dash for i in range(8,12): if not text[i].isdecimal(): return False # no third position 4 digits return True print(isPhoneNumber('415-555-1234')) # - # Non-Regex isPhoneNumber True # # ![](.\images\Non-Regex_isPhoneNumber_True.png) print(isPhoneNumber('Hello')) # I had done a typo in the message missing 1 digit at the end of each numver and got false # # ![](.\images\no_valid_US_number_in_the_message.png) # message = 'Call me at 415-555-1012 tomorrow, or ar 015-555-9999 at the office' foundNumber = False for i in range (len(message)): chunk = message[i:i+12] if isPhoneNumber(chunk): print('Phone number found: '+ chunk) foundNumber = True if not foundNumber: print('Could not find a valid US number in the message.') # + import re message = 'Call me at 415-555-1012 tomorrow, or ar 015-555-9999 at the office' phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #RegEx will return a 'match object' which is why we are calling it 'mo' mo = phoneNumRegex.search(message) print(mo.group()) print(mo) # - import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') #RegEx will return a 'match object' which is why we are calling it 'mo' mo = phoneNumRegex.findall('Call me at 415-555-1012 tomorrow, or ar 015-555-9999 at the office') print(mo) import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') print(phoneNumRegex.findall('Call me at 415-555-1012 tomorrow, or ar 015-555-9999 at the office')) # # # RegEx Overview summary # # ![](.\images\RegEx_Overview.png) # # Or just use "findall" instead of "search" to get all the match groups as a list right away import re phoneNumberRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') phoneNumberRegex.search('My number is 415-555-4242') mo = phoneNumberRegex.search('My number is 415-555-4242') print(mo.group()) phoneNumberRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') mo = phoneNumberRegex.search('My number is 415-555-4242') print(mo) mo.group(1) mo.group(2) phoneNumberRegex = re.compile(r'\((\d\d\d)\) (\d\d\d-\d\d\d\d)') mo = phoneNumberRegex.search('My number is (415) 555-4242') print(mo) mo.group(2) mo.group(1) batRegex = re.compile(r'Bat(man|mobile|copter|\'bat\')') mo = batRegex.search('Batmobile lost a wheel') mo.group() # When Regex object found nothing it will error out saying it only has a 'None' value. That's expected and needs to be handled in the code before calling the .group() method to display the results # # ![](.\images\RegEx_catching_None_return_value.png) # # mo = batRegex.search('Batmotorcycle lost a wheel') mo == None batRegex = re.compile(r'Bat(man|mobile|copter|\'bat\')') mo = batRegex.search('Batmobile lost a wheel') mo.group(1) # # # ![](./images/RegEx_Groups.png) import re batRegex = re.compile(r'Batman|Batwomen') # '?' means group can appear 0 or one time batRegexShorter = re.compile(r'Bat(wo)?man') mo = batRegex.search('The Adventures of Batman') mo2 = batRegexShorter.search('The Adventures of Batman') print(mo.group()) print(mo2.group()) mo2 = batRegexShorter.search('The Adventures of Batwoman') print(mo2.group()) mo2 = batRegexShorter.search('The Adventures of Batwowowowoman') mo2 == None phoneRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') mo = phoneRegex.search('My phone number is 415-555-1234') mo.group() mo = phoneRegex.search('My phone number is 555-1234') mo == None phoneLocalRegex = re.compile(r'(\d\d\d-)?\d\d\d-\d\d\d\d') mo = phoneLocalRegex.search('My phone number is 415-555-1234') mo.group() mo2 = phoneLocalRegex.search('My phone number is 555-1234') mo2.group() batRegex = re.compile(r'Bat(wo)*man') batRegex.search('The Adventures of Batman') batRegex.search('The Adventures of Batwoman') batRegex.search('The Adventures of Batwowowowowoman') batRegex = re.compile(r'Bat(wo)+man') mo = batRegex.search('The Adventures of Batman') mo == None batRegex.search('The Adventures of Batwoman') batRegex.search('The Adventures of Batwowowowoman') regex = re.compile(r'\+\*\?') regex.search('Litteral reserved characters search like +*? without spaces in between!') # ![](./images/RegEx_greedy_non_greedy.png) import re phoneRegex = re.compile(r'\d\d\d\-\d\d\d-\d\d\d\d') phoneRegex # + message = ''' <NAME> Campus Address <EMAIL> Permanent Address 256 Fitzpatrick Hall 1060 W. Addison St. Notre Dame, IN 46556 Chicago, IL 60613 574-631-6039 773-404-2827 OBJECTIVE To obtain a summer internship in Mechanical Engineering. EDUCATION University of Notre Dame Bachelor of Science in Mechanical Engineering GPA: 3.1/4.0, to be awarded May 2006 Dean's List: Spring 2004 Study Abroad Program London, England COURSEWORK Engineering Graphics (Pro-E) Thermodynamics Mechanical Design Computing & Programming Control Systems I, II Heat Transfer COMPUTER Languages: FORTRAN, MATLAB, C++ SKILLS Systems: MS-DOS, UNIX, Macintosh, Windows: 9x, XP, 2000, & NT Software: ProEngineer Wildfire, AutoCAD, MS Word, MS Excel EXPERIENCE Alivaf Technology Corporation, San Antonio, TX, June-September 2004 Engineering Intern: Design widgets using Pro-Engineer to meet design specifications. Selected and tested appropriate materials to optimized strength- to-weight ratio. Tested widgets using IBRAKEM testing apparatus. University of Notre Dame, Notre Dame, IN, Fall 2004 Undergraduate Research Assistant: Conducted preliminary research on fuel cells. Assisted in setting up apparatus for rheology experiments using polymers and fiber composites. Took permeability measurements of deformed fabrics. MEMBERSHIPS American Society of Mechanical Engineers (ASME), member, 2004 <NAME>, Treasurer, 2005 Organized fundraisers grossing $3,000 National Society of Black Engineers, member, 2004 Association for Computing Machinery, member, 2003 ACTIVITIES Racquetball, jogging, church volunteer, math tutor REFERENCES Available upon request SAMPLE RESUME ''' phoneRegex.findall(message) # - phoneRegex.search(message) # findall does not return a match object, insteads it returns a list of strings... ...unless you have defined groups in the regex then it returns a list of tuples # # ![](./images/RegEx_findall_does_not_return_match_object_it_returns_a_list_of_strings.png) import re phoneRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') phoneRegex.findall(message) import re # defining a groug containing sub-groups phoneRegex = re.compile(r'((\d\d\d)-(\d\d\d-\d\d\d\d))') phoneRegex.findall(message) # # looking at character classes like \d, but we can create our own # # digitRegex = re.compile(r'\d') digitRegexEquivalent = re.compile(r'0|1|2|3|4|5|6|7|8|9') # ![](.\images\RegEx_Common_character_classes.png) # + lyrics = """12 drummers drumming, 11 pipers piping, 10 lords a leaping, 9 ladies dancing, 8 maids a milking, 7 swans a swimming, 6 geese a laying, 5 golden rings, 4 calling birds, 3 french hens, 2 turtle doves, 1 partridge in a pear tree""" [from|https://github.com/bronsonavila/automate-boring-stuff-python-notes ] # - xmasRegex = re.compile(r'\d+\s\w+') xmasRegex.findall(lyrics) vowelRegex = re.compile(r'[aeiouAEIOU]') # equivalent to (a|e|i|o|u) vowelRegex.findall('Robocop eats baby food!') doubleVowelRegex = re.compile(r'[aeiouAEIOU]{2}') # equivalent to (a|e|i|o|u) doubleVowelRegex .findall('Robocop eats baby food!') consonantsRegex = re.compile(r'[^aeiouAEIOU]') # equivalent to not (a|e|i|o|u) consonantsRegex.findall('Robocop eats baby food!') # it will also capture the spaces and ponctuation... # ![](./images/RegEx_classes_and_findall.png) import re beginsWithHelloRegEx = re.compile(r'^Hello') beginsWithHelloRegEx.search('Hello there!') beginsWithHelloRegEx.search('He said Hello.') == None endsWithWorldRegEx = re.compile(r'World!$') endsWithWorldRegEx.search('We are the champion of the World!') endsWithWorldRegEx.search('Where in the World! is that Word!') == None allDigitsRegex = re.compile(r'^\d+$') allDigitsRegex.search('01235676976344') # but with the "x" in the middle and the match is not true anymore allDigitsRegex.search('01235676976x344') == None # "." means any characters except a new line atRegex = re.compile(r'.at') atRegex.findall('The cat in the hat sat on a flat mat.') atRegex = re.compile(r'.{1,2}at') atRegex.findall('The cat in the hat sat on a flat mat.') tellMeYourName = 'First Name: Thierry Last Name: Cailleau' nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)') nameRegex.search(tellMeYourName) nameRegex.findall(tellMeYourName) # ".*" uses greedy mode # If you want to just find the first hit you want to use ".*?" # server = '<To serve humans> for dinner.>' nonGreedyRegex = re.compile(r'<(.*?)>') nonGreedyRegex.findall(server) GreedyRegex = re.compile(r'<(.*)>') GreedyRegex.findall(server) primeDirectives = 'Serve the public trust.\nProtect the innocent.\nUphold the law.' dotStartRegex = re.compile(r'.*') dotStartRegex.findall(primeDirectives) dotStartRegex.search(primeDirectives) dotStartDotAllRegex = re.compile(r'.*', re.DOTALL) dotStartDotAllRegex.search(primeDirectives) dotStartDotAllRegex.findall(primeDirectives) vowelRegex = re.compile(r'[aeiou]') vowelRegex.findall('Al, why does your programming book talks about Robocop so much?') # It only retruns the lower-case vowels # vowelRegex = re.compile(r'[aeiou]', re.IGNORECASE) vowelRegex.findall('Al, why does your programming book talks about Robocop so much?') vowelRegex = re.compile(r'[aeiou]', re.I) vowelRegex.findall('Al, why does your programming book talks about Robocop so much?') # ![](./images/RegEx_Dot_Star.png) # to replace with regular expressions by using "sub()" for substitution import re namesRegex = re.compile(r'Agent \w+') namesRegex.findall('Agent Alice gave the secret document to Agent Bob.') namesRegex.sub('REDACTED', 'Agent Alice gave the secret document to Agent Bob.') partialNamesRegex = re.compile(r'Agent (\w)\w*') partialNamesRegex.findall('Agent Alice gave the secret document to Agent Bob.') partialNamesRegex.sub(r'Agent \1*****', 'Agent Alice gave the secret document to Agent Bob.') # "\1" whatever matches group 1 # # phoneLocalRegex = re.compile(r'(\d\d\d)(-)?\d\d\d-\d\d\d\d') # (415) 555-1234 415-555-1234 phoneLocalRegex.search('My phone number is 415-555-1234') # The verbose format helps to avoid newline and whitesapces to help document the regex phoneLocalRegex = re.compile(r''' (\d\d\d) # this is the area code (-)? # first dash \d\d\d # first 3 digits - # second dash \d\d\d\d # last 4 digitis ''', re.VERBOSE) # (415) 555-1234 415-555-1234 # This way it is easier to make the regex more complicated but still easy to read phoneLocalRegex = re.compile(r''' (\d\d\d)| # this is the area code \((\d\d\d)\) # or with parenthesis (-)? # first dash \d\d\d # first 3 digits - # second dash \d\d\d\d # last 4 digits \sx\d(2,4) # this accounts for a possible extension ''', re.VERBOSE) # (415) 555-1234 415-555-1234 # This way it is easier to make the regex more complicated but still easy to read phoneLocalRegex = re.compile(r''' (\d\d\d)| # this is the area code \((\d\d\d)\) # or with parenthesis (-)? # first dash \d\d\d # first 3 digits - # second dash \d\d\d\d # last 4 digits \sx\d(2,4) # this accounts for a possible extension ''', re.VERBOSE | re.DOTALL | re.IGNORECASE) # "|" only place where "bitwise" OR operator is used in python # ![](./images/RegEx_sub_for_substitute.png) # Note: got to 10_1_Python_Phone_and_email_scrapper.ipynb
10_Python_Regular_Expresssions.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 matplotlib.pyplot as plt from matplotlib import pylab import numpy as np import pandas as pd import matplotlib.ticker as ticker from osgeo import gdal import salem from salem import * import fiona, rasterio import geopandas as gpd from rasterio.plot import show from rasterio.features import rasterize from rasterstats import zonal_stats from sklearn.metrics import mean_squared_error as MSE import pwlf import math from scipy import stats from scipy.stats import chisquare from scipy.optimize import curve_fit from scipy.interpolate import interp1d import statsmodels.api as stm import statsmodels.formula.api as smf from hydroeval import * import xarray as xr import pickle def cm2inch(*tupl):### plots in cm ##frontiers 180 mm for full width, 85 mm half width (1 column) figures inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tupl) import warnings warnings.filterwarnings("ignore") years = [2016, 2017, 2018] fl_path = '/home/pelto/Desktop/ice_flux/' + 'Conrad' + '/' ZS_df_2016 = pd.read_csv(fl_path+'ZS_2016.csv') ZS_df_2017 = pd.read_csv(fl_path+'ZS_2017.csv') ZS_df_2018 = pd.read_csv(fl_path+'ZS_2018.csv') sVSTAKE=1.10; sVOFFice=1.1; sVCoreg=2.0; sVRAND=1.5 sVsys=np.sqrt((sVOFFice**2)+(sVCoreg)**2) sVZ=np.sqrt((sVsys**2)+((sVRAND)**2)) sVZ # + font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} mfc='none'; mew=1.1; elw=0.9 plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1.'; pylab.rcParams['ytick.major.pad']='1.' fig1, ax1 = plt.subplots(1,3, sharex=True, sharey=True, figsize=(cm2inch(18, 5))) #obs. and flux gate SMB boxplot/errorbar plot fig2, ax2 = plt.subplots(1,3, sharex=True, sharey=True, figsize=(cm2inch(18, 5))) ##mass conservation plot count = 0 for yr in range(len(years)): # season balance = 'Ba' # Bw or Ba (winter or annual) # rho_snow = 445. # 470 kg m-3 geodetic or 457 glaciological, or...take given years obs. value year = years[yr] # any of: 2016, 2017, 2018 I = np.abs(year - 2016) # for selecting raster inputs gl = 1 # number to select glacier Glacier = ['Kokanee', 'Conrad', 'Illecillewaet',] glacier = ['kokanee', 'conrad', 'illecillewaet',] # d = 20. #20. #distance (m) between flux gate points Dint = 0.85 #depth integrated velocity ratio, 1.0= all sliding sVSTAKE=1.10; sVOFFice=1.8; sVCoreg=3.0; sVRAND=2.0 sVsys=np.sqrt((sVSTAKE**2)+(sVOFFice**2)) sVZ=np.sqrt((sVsys**2)+(sVRAND**2)) sHopt = 0.078 #10.2 ## ME:10.2 m, MAE:0.223 (percent ratio) 0.16 is 2x the ME of Conrad, Illec, Kokanee cb = 6 ##center bin use this to assure flux in is from bins cb+1 and cb+2 top =10 ## top bin fl_path = '/home/pelto/Desktop/ice_flux/' + Glacier[gl] + '/' gpr_path = '/home/pelto/GIS/GPR/ComparisonData/' path = '/home/pelto/Desktop/lidar_cbt_analysis/' + glacier[gl] + '/' VDIR = 'individual' # 'average' or 'individual' ITS_LIVE = False firn = False fit='PW' # PW or 'LIN' if VDIR == 'individual': vf_list = ['conrad_2016_vy_25m_pos.tif','conrad_2017_vy_25m_pos.tif','conrad_2018_vy_25m_pos_17mos.tif'] vdir = '/home/pelto/Desktop/velocity_mapping/' +Glacier[gl] + '_DEMs/spm2/3m/' ITS = fl_path + 'ITS_Live/' + str(year) + '_conrad_ITS_LIVE.tif' if year == 2017: print(year) VX = vdir+ vf_list[I][:-14] + 'vx_25m.tif' VY = vdir+ vf_list[I] if year == 2018: print(year) VX = vdir+ vf_list[I][:-20] + 'vx_25m.tif' VY = vdir+ vf_list[I] elif year == 2016: VX = vdir+ vf_list[I][:-14] + 'vx_25m.tif' VY = vdir+ vf_list[I] else: vdir = '/home/pelto/Desktop/velocity_mapping/Conrad_DEMs/spm2/3m/' #bedem5_spm2/' VX = vdir+ 'conrad_all_3mdems+planet_25m_vx.tif' #'conrad_fast_vy.tif' VY = vdir+ 'conrad_all_3mdems+planet_25m_vy.tif' #'conrad_all_dem3m_vy_new_blur3_5m.tif' ITS = fl_path + 'ITS_Live/' + 'mosaic_conrad_ITS_LIVE.tif' # topo_list = ['140911_conrad_update_dem1_clip.tif', '20160912_conrad_dem1_clip_slave.tif', '20170917_conrad_dem1_clip_slave.tif'] topo = path + '20160912_conrad_dem1_clip_slave.tif' #path + topo_list[I] farinotti = gpr_path + 'RGI60-02.02171_thickness.tif' dhW_list = ['conrad_2016_winter_dh_dt14s.tif', 'conrad_2017_winter_dh_dt16s.tif', 'conrad_2018_winter_dh_dt.tif'] dhA_list = ['conrad_2015_2016_dh_dt_filled_1416+50cm.tif', 'conrad_2017_2016_dh_dt_17s14m.tif' ,'conrad_2018_2017_dh_dt.tif'] #'conrad_2016_2017_dh_dt+50cm.tif' if balance == 'Bw': dh_r = path+ dhW_list[I] #winter height change TIFF else: dh_r = path+ dhA_list[I] #Annual height change TIFF SLOPE = '/home/pelto/GIS/DEM/Slope/ConradSlope160912_20m.tif' pts_file = fl_path + 'gis/conrad_bins_11_pts_25m_wgs84.shp' #'conrad_points_17gates_C_20m_wgs84_b.shp' # 'conrad_points_gates_20m_wgs84.shp' ##must be WGS84 gates = fl_path+'conrad_flux_gates_new11.shp' #'conrad_flux_gates_17_C.shp' #conrad_flux_gates_17_C conrad_flux_gates shpf = path + Glacier[gl] + '/conrad_all_glaciers_2014.shp' #GLIMS_BC/glims_all/all_glaciers_2016.shp' bins=fl_path+'gis/conrad_bins_11_2016.shp' #'_bins_2017_C'+'.shp' #_bins_2017_C _bins obs = pd.read_csv(fl_path+ 'Conrad_bdot.csv') rho = pd.read_csv(fl_path + 'RHO.csv') ## MUST MATCH NUMBER OF BINS conrad_rho_new11.csv # open GeoTIFFs as arrays vy = salem.open_xr_dataset(VY);vy = vy.to_array(name='vy') vx = salem.open_xr_dataset(VX);vx = vx.to_array(name='vx') msk = salem.open_xr_dataset('/home/pelto/Desktop/lidar_cbt_analysis/conrad/conrad_total_msk.tif') msk_conrad = salem.open_xr_dataset('/home/pelto/Desktop/lidar_cbt_analysis/conrad/conrad_2014_extent_5m.tif') gpr = salem.open_xr_dataset(fl_path + 'gpr_25_100m_5m.tif') #'gpr_outlines_all_25_25m_re5m.tif' farin = salem.open_xr_dataset(farinotti) H_opt = salem.open_xr_dataset(fl_path+'Conrad_opt_thick_final.tif') #'opt_thick_251sw.tif') gates = salem.read_shapefile(gates) gpr_reproj = vy.salem.transform(gpr);gpr = gpr_reproj.to_array(name='gpr') slope=salem.open_xr_dataset(SLOPE);slope_reproj = vy.salem.transform(slope) slope = slope_reproj.to_array(name='slope') msk_reproj = vy.salem.transform(msk) #note succeeding trying to use gdalwarp to go from 2955 --> 32611 msk = msk_reproj.to_array(name='msk') msk_conrad_reproj = vy.salem.transform(msk_conrad);msk_conrad = msk_conrad_reproj.to_array(name='msk_conrad') ITS = salem.open_xr_dataset(ITS); ITS_reproj = vy.salem.transform(ITS);ITS = ITS_reproj.to_array(name='ITS') # farin = farin.to_array(name='vx') H_opt_reproj = vy.salem.transform(H_opt);H_opt = H_opt_reproj.to_array(name='H_opt') farin_reproj= vy.salem.transform(farin);farin = farin_reproj.to_array(name='farin') srtm_corr = fl_path + 'conrad_SRTM_diff_30m.tif' srtm_corr = salem.open_xr_dataset(srtm_corr) srtm_corr = vy.salem.transform(srtm_corr) srtm_corr = srtm_corr.to_array(name='srtm_corr') srtm_corr.data[srtm_corr.data>10.0] = 0.0 ##remove positive anomalous values srtm_corr.data[srtm_corr.data<-50.0] = 0.0 ##remove negative anomalous values farin_corr = farin + srtm_corr; farin_corr= farin_corr.rename('farin_corr') gpr.data[gpr.data<0.5] = np.nan; # no data on file set to zero, slope.data[slope.data<0.0]=np.nan vy.data[vy.data<0.01]=np.nan vz = vy; vz.data = np.sqrt(vx.data**2 + vz.data**2 ) vz.data[msk_conrad.data!=1.0] = np.nan;ITS.data[msk_conrad.data!=1.0] = np.nan; vz=xr.DataArray(vz.data, coords=vz.coords, name='vz') # np.savetxt(), vz[0].data, delimiter=',') with open(fl_path+str(year)+'_vz.pkl', 'wb') as f: pickle.dump(vz[0].data, f) with open(fl_path+str(year)+'_ITS.pkl', 'wb') as f: pickle.dump(ITS[0].data, f) # vx.data[msk.data==0] = np.nan;vy.data[msk.data==0] = np.nan;VZ[msk_conrad.data<0.0] = np.nan VZ_off_ice = vz.copy(); VZ_off_ice.data[msk.data==1.0] = np.nan DIFF = vz - ITS print("VZ -ITS:", np.nanmean(DIFF)); print("VZ DIFF ratio:", np.nanmean(DIFF)/np.nanmean(vz)) dh = salem.open_xr_dataset(dh_r); dh_reproj = vy.salem.transform(dh); dh = dh_reproj.to_array(name='dh')#dh.data[dh.data<1] = np.nan dem = salem.open_xr_dataset(topo);dem_reproj = vy.salem.transform(dem); dem = dem_reproj.to_array(name='dem') dem.data[dem.data<1] = np.nan fig, ax = plt.subplots(1,1, sharex=True, sharey=True, figsize=(cm2inch(18, 8.25))) grid = vy.salem.grid ##full view sm = Map(grid, countries=False) sm.set_lonlat_contours(interval=0) sm.set_scale_bar() sm.set_data(vz) #, label='m') sm.set_vmax(val=50.) # Change the lon-lat countour setting sm.set_lonlat_contours(add_ytick_labels=True, interval=0.05, linewidths=0.75, linestyles='--', colors='0.25') off_ice_V = np.nanmean(VZ_off_ice) print(off_ice_V) print(np.nanstd(VZ_off_ice)) print('Mean Vel. vz', round(np.nanmean(vz),2), round(np.nanstd(vz),2)) print('Mean Vel. ITS', round(np.nanmean(ITS),2), round(np.nanstd(ITS),2)) gdf = salem.read_shapefile(shpf) sm.set_shapefile(gdf, linewidth=1) sm.set_shapefile(gates, linewidth=1.5, color='r') sm.visualize() # fig.savefig(fl_path+ 'products/'+ glacier[gl] + str(year) +'_thickness_gates_diff.png', dpi=300) # fig.show() ## Functions for calculating zonal statistics over each flux gate bin # https://community.esri.com/groups/python-snippets/blog/2019/05/07/calculating-zonal-statistics-with-python-rasterstats # For loading shapefiles into geopandas dataframe def enum_items(source): print("\n") for ele in enumerate(source): print(ele) def list_columns(df): field_list = list(df) enum_items(field_list) return field_list def loadshp_as_gpd(shp): data_shp = gpd.read_file(shp) return data_shp # For loading feature classes into geopandas dataframe def loadfc_as_gpd(fgdb): layers = fiona.listlayers(fgdb) enum_items(layers) index = int(input("Which index to load? ")) fcgpd = gpd.read_file(fgdb,layer=layers[index]) return fcgpd # For re-projecting input vector layer to raster projection def reproject(fcgpd, raster): proj = raster.crs.to_proj4() print("Original vector layer projection: ", fcgpd.crs) reproj = fcgpd.to_crs(proj) print("New vector layer projection (PROJ4): ", reproj.crs) # fig, ax = plt.subplots(figsize=(15, 15)) # rplt.show(raster, ax=ax) # reproj.plot(ax=ax, facecolor='none', edgecolor='red') # fig.show() return reproj def dissolve_gpd(df): field_list = list_columns(df) index = 1 #int(input("Dissolve by which field (index)? ")) dgpd = df.dissolve(by=field_list[index]) return dgpd # For selecting which raster statistics to calculate def stats_select(): stats_list = stats_list = ['min', 'max', 'mean', 'count', 'sum', 'std', 'median', 'majority', 'minority', 'unique', 'range'] enum_items(stats_list) # indices = input("Enter raster statistics selections separated by space: ") indices='2 3 5 6' stats = list(indices.split()) out_stats = list() for i in stats: out_stats.append(stats_list[int(i)]) return out_stats def get_zonal_stats(vector, raster, stats): # Run zonal statistics, store result in geopandas dataframe result = zonal_stats(vector, raster, stats=stats, geojson_out=True) geostats = gpd.GeoDataFrame.from_features(result) return geostats ## make an ice velocity quiver plot # fig, ax = plt.subplots(1,1,figsize=(10,10)) df = salem.read_shapefile(pts_file) df_file = loadshp_as_gpd(pts_file) # df_file.crs coords = np.array([p.xy for p in df.geometry]).squeeze() df['lon'] = coords[:, 0]; df['lat'] = coords[:, 1] # ax.scatter(df.lon, df.lat, s=10, c='r' )#c='depth',cmap='viridis', s=10, ax=ax); xx, yy = salem.transform_proj(salem.wgs84, grid.proj, df['lon'].values, df['lat'].values) df['x'] = xx; df['y'] = yy # shp_plt = reproject(df, VX) X, Y = np.meshgrid(vx.coords['x'],vx.coords['y']) U = vx.data[0]; V = vy.data[0] vns = ['vx','vy','vz', 'ITS', 'gpr','H_opt','dem','farin_corr','dh','slope'] M = xr.merge([vx,vy,vz,ITS,gpr,H_opt,dem,farin_corr,dh,slope]) for vn in vns: df[vn] = M[vn][0].interp(x=('z', df.x), y=('z', df.y)) df_agg = df[['ID', 'len', 'distance', 'angle', 'geometry', 'lon', 'lat']].copy() ii, jj = grid.transform(df['lon'], df['lat'], crs=salem.wgs84, nearest=True) df_agg['i'] = ii; df_agg['j'] = jj # # We trick by creating an index of similar i's and j's df_agg['ij'] = ['{:04d}_{:04d}'.format(i, j) for i, j in zip(ii, jj)] df_agg = df_agg.groupby('ij').mean() # Select for vn in vns: df_agg[vn] = M[vn][0].isel(x=('z', df_agg.i), y=('z', df_agg.j)) df_test = df_agg.copy() #add in missing IPR data D = df_agg[['ID', 'len', 'distance', 'angle', 'lon', 'lat', 'vx', 'vy', 'vz','ITS', 'gpr', 'slope','H_opt', 'dem', 'farin_corr']].copy() D['vzdir'] = np.arcsin(D.vx/D.vz) *180/math.pi #degrees from north if VDIR == 'individual': # fill any missing vel. direction for i in range(len((D))): if np.isnan(D.vzdir[i])==True: G=D.ID[i];V=np.nanmedian(D.vzdir[D.ID==G]) D.vzdir[i]=V ## fill in velocity nans at edges (sometimes 1-2 nan pts at edge due to mask res.) for i in range(D.ID.nunique()): d=D[(D.ID==i)&(D.distance<230)] dist=d.distance[np.isnan(d.vz)].values; x=d.distance[np.logical_not(np.isnan(d.vz))].values;y=d.vz.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 1); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.vz[(D.ID==i)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==i)&(D.distance>(D.len - 100))] dist=d.distance[np.isnan(d.vz)].values; x=d.distance[np.logical_not(np.isnan(d.vz))].values;y=d.vz.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 1); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.vz[(D.ID==i)&(D.distance==dist[f])]=fill[f] ### fill ice thickness gaps #last and first points in each line are zero depth (except gate 7 end, gates 6, 8, 9 start) D.distance[(D.ID==0)&(D.distance==511.4)]=522.8 D.gpr[D.distance==0.0]=0.0;D.gpr[(D.distance==D.len)]=0.0; D.gpr[(D.ID==8)&(D.distance==0.0)]=np.nan;D.gpr[(D.ID==9)&(D.distance==0.0)]=np.nan; D.gpr[(D.ID==7)&(D.distance==D.len)]=np.nan;D.gpr[(D.ID==6)&(D.distance==0.0)]=np.nan;D.gpr[(D.ID==6)&(D.distance==D.len)]=np.nan D.H_opt[(D.gpr==0.0)&(D.distance==0.0)]=0.0;D.H_opt[(D.gpr==0.0)&(D.distance==D.len)]=0.0; D.farin_corr[(D.gpr==0.0)&(D.distance==0.0)]=0.0;D.farin_corr[(D.gpr==0.0)&(D.distance==D.len)]=0.0; ## start with gates where left bound is not bedrock d=D[(D.ID==8)&(D.distance<200)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 2); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==8)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==8)&(D.distance>350)&(D.distance<700)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 2); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==8)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==8)&(D.distance>700)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 2); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==8)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==9)&(D.distance>800)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 4); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist)#;plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==9)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==0)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 6); poly = np.poly1d(coefficients);new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==0)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==1)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 5); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist)#;plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==1)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==2)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 6); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist)#;plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==2)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==3)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 8); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==3)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==4)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 6); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==4)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==5)&(D.distance<1400)];dist=d.distance[np.isnan(d.gpr)].values; x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 3); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==5)&(D.distance==dist[f])]=fill[f] d=D[(D.ID==7)];dist=d.distance[np.isnan(d.gpr)].values;#&(D.distance<500) x=d.distance[np.logical_not(np.isnan(d.gpr))].values;y=d.gpr.values; y=y[np.logical_not(np.isnan(y))] coefficients = np.polyfit(x, y, 7); poly = np.poly1d(coefficients); new_x = np.linspace(x[0], x[-1]); new_y = poly(new_x);fill=poly(dist);#plt.scatter(dist,fill,color='r');plt.plot(x, y, "o", new_x, new_y) for f in range(len(dist)): D.gpr[(D.ID==7)&(D.distance==dist[f])]=fill[f] D_all=D.copy() if ITS_LIVE == True: D['vfg'] = D.ITS else: #multiply velocity vector by cosine of angle between vector and flux gate (line or line segment) D['vfg'] = np.abs(D.vz * np.cos((D.vzdir-(D.angle-90.))*(math.pi/180.))) #velocity normal to gate per slice # D.to_csv(fl_path+ glacier[gl]+ 'D_test.csv') for i in range(len((D))): #D.ID.nunique()): if np.isnan(D.vfg[i])==True: G=D.ID[i] V=np.nanmean(D.vfg[D.ID==G]) D.vfg[i]=V with open(fl_path + str(year)+'_Dvfg.pkl', 'wb') as f: pickle.dump(D.vfg.values, f) ##### correct ice thickness for thinning ############## DH=[] D1=D.copy(); D1.reset_index(inplace=True,drop=True);DH=[] for i in range(len(D1)): fl_id=D1.loc[i].ID if year == 2016: del_h = 0.0 elif year == 2017: del_h=new16.loc[fl_id].dh_mean elif year == 2018: del_h=new17.loc[fl_id].dh_mean DH.append(del_h) D['DH']=DH #used to correct ice thickness for surface height change due to mass loss D.H_opt = D.H_opt + D.DH D.H_opt[D.H_opt<0.] = 0.0 D.gpr = D.gpr + D.DH D.gpr[D.gpr<0.] = 0.0 D.farin_corr = D.farin_corr + D.DH D.farin_corr[D.farin_corr<0.] = 0.0 ##### end correct ice thickness for thinning ############## D.sort_values(by=['distance','ID'],ascending=[True,True], inplace=True) for n in range(D.ID.nunique()): for c in range(len(D.ID[D.ID==n])): #.count()-1)#range(D.ID[D.ID==n].count()-1): idx=D[(D.ID==n)&(D.distance==D[D.ID==n].distance[c])].index if c==0: ## first point in line L= D.distance[D.ID==n][c+1] - D.distance[D.ID==n][c] G= L * D.H_opt[D.ID==n][c+1]*0.5;J= L * D.farin_corr[D.ID==n][c+1]*0.5 #area of triangle elif c==1: #second point from start L= (D.distance[D.ID==n][c+1] - D.distance[D.ID==n][c])/2 G= L * D.H_opt[D.ID==n][c]; J= L * D.farin_corr[D.ID==n][c] elif c==len(D.ID[D.ID==n])-2: #second to last point L= (D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1])/2 G= L * D.H_opt[D.ID==n]; J= L * D.farin_corr[D.ID==n] elif c==len(D.ID[D.ID==n])-1: #last point in line L= (D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1]) G= L * D.H_opt[D.ID==n][c-1]*0.5; J= L * D.farin_corr[D.ID==n][c-1]*0.5 #area of triangle else: L=(((D.distance[D.ID==n][c+1]-D.distance[D.ID==n][c])/2) + ((D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1])/2)) G=L* D.H_opt[D.ID==n][c] ; J=L* D.farin_corr[D.ID==n][c] D.loc[idx,'A_Hopt']= G;D.loc[idx,'A_farin']= J; D.loc[idx,'Len_mod']= L D_all=D.copy() D['Qopt'] = D.A_Hopt * (D.vfg) * Dint;D['Qfarin'] = D.A_farin * (D.vfg) * Dint ### Uncertainties D['sQout'] = np.sqrt((sVZ * D.A_Hopt)**2 + ((D.vfg*Dint) * D.Len_mod * (sHopt*D.H_opt))**2) D['sQout_low'] = np.sqrt((sVZ * D.A_Hopt)**2 + ((D.vfg*0.80) * D.Len_mod * (sHopt*D.H_opt))**2) D['sQout_high'] = np.sqrt((sVZ * D.A_Hopt)**2 + ((D.vfg*1.00) * D.Len_mod * (sHopt*D.H_opt))**2) D['sQoutF'] = np.sqrt((sVZ * D.A_farin)**2 + ((D.vfg*Dint) * D.Len_mod * (sHopt*D.farin_corr))**2) Q_out= [0.,] #flux out per gate cr_area = [0.,] # cross-section area per gate vzdir = [0.,]; sQout= [0.,];sQout_low= [0.,];sQout_high= [0.,];vfg_all=[];gate_elev=[];v_gate_mean=[0.,]; GPR=[0.,];HF=[0.,];Hopt=[0.,];gate_width=[0.,];Len_mod=[0.,]; DV= D.copy(); DV = DV.dropna(subset=['vfg']) for n in range(D.ID.nunique()): vfg_all.append(DV.vfg[DV.ID==n]);gate_elev.append(D.dem[D.ID==n].mean()) ####### calculate flux per bin by summing slices ####### for n in range(D.ID.nunique()+1): Q_out.append(D.Qopt[D.ID==n].sum()) ;cr_area.append(D.A_Hopt[D.ID==n].sum()) vzdir.append(D.vzdir[D.ID==n].mean()) sQout.append(D.sQout[D.ID==n].sum());sQout_low.append(D.sQout_low[D.ID==n].sum()); sQout_high.append(D.sQout_high[D.ID==n].sum()) v_gate_mean.append(D.vfg[D.ID==n].mean());Hopt.append(D.H_opt[D.ID==n].mean()) gate_width.append(D.len[D.ID==n].max()); Len_mod.append(D.Len_mod[D.ID==n].sum()) GPR.append(D.gpr[D.ID==n].mean()) Q_in = [Q_out[1:]]; sQin = [sQout[1:]+ [0.0]] ##1.0 instead of zero to prevent uncertainty nan sQin_low = [sQout_low[1:]+ [0.0]];sQin_high = [sQout_high[1:]+ [0.0]] Q_in = np.squeeze(Q_in);sQin = np.squeeze(sQin);sQin_low = np.squeeze(sQin_low);sQin_high = np.squeeze(sQin_high) Q_outF= [0.,] #flux out per gate cr_areaF = [0.,]; sQoutF = [0.,] for n in range(D.ID.nunique()+1): Q_outF.append(D.Qfarin[D.ID==n].sum()) ;cr_areaF.append(D.A_farin[D.ID==n].sum()) sQoutF.append(D.sQoutF[D.ID==n].sum()); HF.append(D.farin_corr[D.ID==n].mean()) Q_inF = [Q_outF[1:]] #flux in per bin Q_inF = np.squeeze(Q_inF);sQinF = [sQoutF[1:]+ [0.0]]; sQinF = np.squeeze(sQinF) FG = pd.DataFrame(list(zip(Q_out, Q_in, cr_area, sQout, sQout_low, sQout_high, sQin, sQin_low, sQin_high, Q_outF, Q_inF, sQoutF, sQinF, cr_areaF, vzdir, v_gate_mean, gate_width,GPR,Hopt, HF,Len_mod)), columns=['Q_out', 'Q_in', 'cr_area', 'sQout', 'sQout_low', 'sQout_high', 'sQin', 'sQin_low', 'sQin_high','Q_outF', 'Q_inF', 'sQoutF', 'sQinF', 'cr_areaF', 'vzdir', 'v_gate_mean','gate_width','gpr','Hopt','HF','Len_mod']) FG.loc[cb, 'Q_in'] = FG.Q_out[cb+1]+ FG.Q_out[cb+2] ## Q_in for cb (center bin) FG.loc[cb, 'Q_inF'] = FG.Q_outF[cb+1]+ FG.Q_outF[cb+2] ## Q_in for cb (center bin) FG.loc[(cb+1), 'Q_in'] = 0.0 ## set Q_in to zero (one to prevent uncertainty nan) for top of west wing FG.loc[(cb+1), 'Q_inF'] = 0.0 ## set Q_in to zero (one to prevent uncertainty nan) for top of west wing FG['vel_fg'] = FG.Q_out / FG.cr_area #net velocity per gate FG['vel_fgF'] = FG.Q_outF / FG.cr_area FG['bin']=np.arange(0,len(range(D.ID.nunique()+1)),1) # FG['sQnet_opt'] = np.sqrt(FG.sQopt**2 + FG.sQin**2) FG['spQout'] = FG.sQout / FG.Q_out * 100. #%err on flux FG['spQin'] = FG.sQin / FG.Q_in * 100. #%err on flux FG['spQoutF'] = FG.sQoutF / FG.Q_outF * 100. #%err on flux FG['spQinF'] = FG.sQinF / FG.Q_inF * 100. #%err on flux ### import data per bin: height change, elevation, surface area, obs.SMB etc. FG_df = FG.copy(); dem_r = topo;vel_r = VY; shp = loadshp_as_gpd(bins) rasters = [dh_r, dem_r]; names = ['dh','dem'] #, vel_r,SLOPE ,'vy','slope' for i in range(len(rasters)): raster = rasters[i]; rst = rasterio.open(raster); shp = reproject(shp, rst) #shp is in correct projection, trying anyway for calculation name = names[i] stat = stats_select() #'['min', 'max', 'mean', 'count', 'sum', 'std', 'median', 'majority', 'minority', 'unique', 'range'] ZS = (get_zonal_stats(shp, raster, stat)) ZS.drop(['geometry'], axis=1, inplace=True) ZS.rename(columns={"mean": name+"_mean", "median":name+"_med", "std": name+"_std", "count":name+"_count"}, inplace=True) ZS.sort_values(by=['bin'],ascending=True, inplace=True) ZS.set_index('bin', inplace=True) FG_df = pd.concat([FG_df, ZS], axis=1) rho.sort_values(by='bin',ascending=True, inplace=True) # sort by bin rho.set_index('bin', inplace=True) # set bin as index for sorting FG_df = pd.concat([FG_df, rho], axis=1) WR= np.array(FG_df.dem_count[1:]) WR= np.append(WR,[0]) # calculate area of flux in (area of bin above a given bin) FG_df['Q_net'] = FG_df.Q_in - FG_df.Q_out #net flux per gate FG_df['Q_netA']= FG_df.Q_net / FG_df.dem_count FG_df['Q_netF'] = FG_df.Q_inF - FG_df.Q_outF #net flux per gate FG_df['Q_netAF']= FG_df.Q_netF / FG_df.dem_count FG_df['area_Qin']= WR FG_df.loc[cb, 'area_Qin'] = FG_df.dem_count[cb+1]+ FG_df.dem_count[cb+2] FG_df['sQoptA'] = FG_df.sQout / FG_df.dem_count FG_df['sQoptA_low'] = FG_df.sQout_low / FG_df.dem_count;FG_df['sQoptA_high'] = FG_df.sQout_high / FG_df.dem_count FG_df['sQ_inA'] = FG_df.sQin / (FG_df.area_Qin+0.001) FG_df['sQ_inA_low'] = FG_df.sQin_low / (FG_df.area_Qin+0.001);FG_df['sQ_inA_high'] = FG_df.sQin_high / (FG_df.area_Qin+0.001) FG_df['sQnetA_opt'] = np.sqrt(FG_df.sQoptA**2 + FG_df.sQ_inA**2) FG_df['sQnetA_opt_low'] = np.sqrt(FG_df.sQoptA_low**2 + FG_df.sQ_inA_low**2);FG_df['sQnetA_opt_high'] = np.sqrt(FG_df.sQoptA_high**2 + FG_df.sQ_inA_high**2) FG_df['sQoutFA'] = FG_df.sQoutF / FG_df.dem_count FG_df['sQ_inFA'] = FG_df.sQinF / (FG_df.area_Qin+0.001) FG_df['sQnetFA'] = np.sqrt(FG_df.sQoutFA**2 + FG_df.sQ_inFA**2) ##calculate height change due to mass balance for highest bins considering firn compaction if firn == False: FG_df.Vfirn = 0.00 if year==2017: FG_df.loc[top, 'dh_mean'] = -0.78 # correct top bin dh for void, took median of highest avail. data if year==2018: FG_df.loc[top-1, 'dh_mean'] = 0.55 FG_df.loc[top, 'dh_mean'] = 0.62 FG_df['b_fg_h'] = FG_df.dh_mean - FG_df.Q_netA + FG_df.Vfirn FG_df['b_fg_hF'] = FG_df.dh_mean - FG_df.Q_netAF + FG_df.Vfirn FG_df.column_depth = FG_df.column_depth * FG_df.firn_area ## adjust firn column height for firn area FG_df['RHO'] = ((FG_df.column_density * FG_df.column_depth) + (910. * (FG_df.Hopt-FG_df.column_depth)))/ FG_df.Hopt FG_df['RHO_F'] = ((FG_df.column_density * FG_df.column_depth) + (910. * (FG_df.HF-FG_df.column_depth)))/ FG_df.HF FG_df.loc[0, 'RHO'] = 910.;FG_df.loc[0, 'RHO_F'] = 910. if balance == 'Bw': FG_df['b_fg_we'] = FG_df.rho_snow/1000 * FG_df.b_fg_h FG_df['b_fg_weF'] = FG_df.rho_snow/1000 * FG_df.b_fg_hF else: FG_df['b_fg_we'] = FG_df['RHO']/1000. * FG_df.b_fg_h #FG_df['rho_%s'%year]/1000. * FG_df.b_fg_h FG_df['b_fg_weF'] = FG_df['RHO_F']/1000. * FG_df.b_fg_hF ### Uncertainties #sDHdt = 0.21 #0.04 #m Bias dh from Pelto et al. 2019 if I==0: sDHdt = 0.21 #NMAD from Pelto et al. 2019 if I==1: sDHdt = 0.31 elif I==2: sDHdt = 0.59 sVfirn = 0.10; sRHO = 0.10 #0.05 # percent uncertainty in density FG_df['sDH_opt'] = np.sqrt(sDHdt**2 + (FG_df.sQnetA_opt)**2 + (FG_df.Vfirn*sVfirn)**2) FG_df['sBwe_opt'] = np.sqrt((FG_df.sDH_opt * (FG_df['RHO']/1000.))**2+ (FG_df.b_fg_h * (FG_df['RHO']/1000.*sRHO))**2) FG_df['sDH_F'] = np.sqrt(sDHdt**2 + (FG_df.sQnetFA)**2 + (FG_df.Vfirn*sVfirn)**2) FG_df['sBwe_F'] = np.sqrt((FG_df.sDH_F * (FG_df['RHO_F']/1000.))**2+ (FG_df.b_fg_hF * (FG_df['RHO_F']/1000.*sRHO))**2) D['Agpr']=np.NaN;D.gpr[D.len==0.]=np.nan; #D.gpr[D.ID==6]=np.nan; D.gpr[(D.ID==6)]=0.0 ## &(D.distance==0.0)temp. add false point to avoid instability D = D.dropna(subset=['gpr']); D.sort_values(by=['distance','ID'],ascending=[True,True], inplace=True) for n in range(D.ID.nunique()): for c in range(len(D.ID[D.ID==n])): #.count()-1)#range(D.ID[D.ID==n].count()-1): idx=D[(D.ID==n)&(D.distance==D[D.ID==n].distance[c])].index if c==0: ## first point in line L= D.distance[D.ID==n][c+1] - D.distance[D.ID==n][c] G= L * D.gpr[D.ID==n][c+1]*0.5;J= L * D.farin_corr[D.ID==n][c+1]*0.5 #area of triangle elif c==1: #second point from start L= (D.distance[D.ID==n][c+1] - D.distance[D.ID==n][c])/2 G= L * D.gpr[D.ID==n][c]; J= L * D.farin_corr[D.ID==n][c] elif c==len(D.ID[D.ID==n])-2: #second to last point L= (D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1])/2 G= L * D.gpr[D.ID==n]; J= L * D.farin_corr[D.ID==n] elif c==len(D.ID[D.ID==n])-1: #last point in line L= (D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1]) G= L * D.gpr[D.ID==n][c-1]*0.5; J= L * D.farin_corr[D.ID==n][c-1]*0.5 #area of triangle else: L=(((D.distance[D.ID==n][c+1]-D.distance[D.ID==n][c])/2) + ((D.distance[D.ID==n][c] - D.distance[D.ID==n][c-1])/2)) G=L* D.gpr[D.ID==n][c] ; J=L* D.farin_corr[D.ID==n][c] D.loc[idx,'Agpr']= G; D.loc[idx,'Len_gpr']= L #calculate flux out using GPR thicknesses sGPR = 0.10 #0.0516 #gpr error % D['sInterp_gpr'] = np.nan for n in range(len(D.Len_gpr)): if D.Len_gpr[n] > 50.: D.sInterp_gpr[n] = D.gpr[n] * 0.10 else: D.sInterp_gpr[n] = 0.0 sH_gpr = np.sqrt(D.sInterp_gpr**2+ (D.gpr*sGPR)**2) D['Qo_gpr'] = D.Agpr * (D.vfg) * Dint#* 0.9 D['sQo_gpr'] = np.sqrt((sVZ * (D.gpr) * D.Len_gpr)**2 + ((D.vfg*Dint) * D.Len_gpr * (sH_gpr))**2) Qo_gpr = [0.,] #flux out per gate cr_area_gpr = [0.,] # cross-section area per gate vzdir_gpr = [0.,]; sQo_gpr= [0.,]; Len_gpr=[0.,] for n in range(D.ID.nunique()): #for n in D.ID.unique(): the ID's are out of order here Qo_gpr.append(D.Qo_gpr[D.ID==n].sum()) ; cr_area_gpr.append(D.Agpr[D.ID==n].sum()) vzdir_gpr.append(D.vzdir[D.ID==n].mean()); sQo_gpr.append(D.sQo_gpr[D.ID==n].sum()) Len_gpr.append(D.Len_gpr[D.ID==n].sum()); Qin_gpr = [Qo_gpr[1:]+ [0.0]] #flux in per bin, add zero to end for top bin Qin_gpr = np.squeeze(Qin_gpr); sQin_gpr = [sQo_gpr[1:]+ [0.0]]; sQin_gpr = np.squeeze(sQin_gpr) FG_gpr = pd.DataFrame(list(zip(Qo_gpr, Qin_gpr, cr_area_gpr, sQo_gpr,sQin_gpr,Len_gpr)), columns=['Qo_gpr', 'Qin_gpr', 'cr_area_gpr', 'sQo_gpr','sQin_gpr','Len_gpr']) FG_gpr['bin'] = np.arange(0,len(range(D.ID.nunique()+1)),1)#[0,1,2,3] FG_gpr.loc[cb+1, 'Qo_gpr'] = FG_df.Q_out[cb+1] #flux out for top of west wing, which has no radar measurements FG_gpr.loc[cb, 'Qin_gpr'] = FG_gpr.Qo_gpr[cb+1]+ FG_gpr.Qo_gpr[cb+2] #flux in for center bin FG_gpr.loc[(cb+1), 'Qin_gpr'] = 0.0 ## set Q_in to zero for top of west wing FG_gpr['spQo_gpr'] = FG_gpr.sQo_gpr / FG_gpr.Qo_gpr * 100. #%err on flux FG_gpr['spQin_gpr'] = FG_gpr.sQin_gpr / FG_gpr.Qin_gpr * 100. #%err on flux FG_all = FG_df.merge(FG_gpr, how='left') #on='bin') FG_all['Q_net_gpr'] = FG_all.Qin_gpr - FG_all.Qo_gpr FG_all['Q_netA_gpr']= FG_all.Q_net_gpr / FG_all.dem_count FG_all.loc[cb+1, 'Q_netA_gpr'] = np.nan # no flux est for bin without IPR measurements FG_all['b_fg_h_gpr'] = FG_all.dh_mean - FG_all.Q_netA_gpr+ FG_all.Vfirn #dh1516_mean FG_all.loc[cb+1, 'b_fg_h_gpr'] = np.nan # SMB for top of west wing, which has no radar measurements FG_all['sQoutA_gpr'] = FG_all.sQo_gpr / FG_all.dem_count FG_all['sQ_inA_gpr'] = FG_all.sQin_gpr / (FG_all.area_Qin+0.001) FG_all['sQnetA_gpr'] = np.sqrt(FG_all.sQoutA_gpr**2 + FG_all.sQ_inA_gpr**2) FG_all['RHO_g'] = ((FG_all.column_density * FG_all.column_depth) + (910. * (FG_all.gpr-FG_all.column_depth)))/ FG_all.gpr; FG_all.loc[0, 'RHO_g'] = 910. if balance == 'Bw': FG_all['b_fg_we_gpr'] = FG_df.rho_snow/1000. * FG_all.b_fg_h_gpr else: FG_all['b_fg_we_gpr'] = FG_all['RHO_g']/1000. * FG_all.b_fg_h_gpr #FG_all.loc[len(FG_gpr)-1,'b_fg_we_gpr'] = np.nan #no radar data available for flux calculation for top bin FG_all['sDH_gpr'] = np.sqrt(sDHdt**2 + (FG_all.sQnetA_gpr)**2 + (FG_all.Vfirn*sVfirn)**2) FG_all['sBwe_gpr'] = np.sqrt((FG_all.sDH_gpr * (FG_all['RHO_g']/1000.))**2+ (FG_all.b_fg_h_gpr * (FG_all['RHO_g']/1000.*sRHO))**2) n = 0; a = 0.7; s= 10 #markersize obs=obs[(obs.Year==year)]; obs.reset_index(inplace=True) obs = obs.dropna(subset=['Ba']) y_ax_obs=obs[(obs.Year==year)].Ba; x_ax_obs=obs[(obs.Year==year)].Elev new = FG_all.copy();#new.drop([7],inplace=True);new.reset_index(inplace=True) yerr = [0.0, new.sBwe_gpr, new.sBwe_opt, new.sBwe_F] #new.sBwe_gpr new['xerr'] = new.dem_std * 1.5 #2 std dev -- 95% of data xerr = new.xerr x_ax_fg_gpr=new.dem_med;y_ax_fg_gpr=new.b_fg_we_gpr x_ax_fg_opt=new.dem_med;y_ax_fg_opt=new.b_fg_we;x_ax_fg_F=new.dem_med ;y_ax_fg_F=new.b_fg_weF x = [x_ax_obs, x_ax_fg_gpr, x_ax_fg_opt, x_ax_fg_F] y = [y_ax_obs, y_ax_fg_gpr, y_ax_fg_opt, y_ax_fg_F] letter=['A','B','C'] color = ['k', '#51c2d5','#663f3f','#ec4646'] #'teal', '#74c476', '#238b45'] # label = ['Obs.', 'Fg IPR', 'Fg OGGM','Farinotti'] label=['Observed', 'FG IPR', 'FG OGGM', 'FG Farinotti'] sym = ['o', '^', 's', 'd'] # Call function to create error bars shift = [-50,0,50] ax1[count].scatter(x[0],y[0],color=color[0], label=label[0], alpha=a+.2, s=s,facecolor='', zorder=3) for i in range(3): ax1[count].errorbar((x[i+1]+shift[i]), y[i+1], xerr=None, yerr=yerr[i+1], fmt=sym[i+1], ecolor=color[i+1], zorder=2, label=label[i+1], alpha=0.8, mfc=mfc, mew=mew, c=color[i+1], ms=4, elinewidth=0.7) #elinewidth=0.7 ## plot data and regression lines ytxt = [0.2, 0.15, 0.1, 0.05] txt= ['Observed', 'FG IPR ', 'FG OGGM ', 'FG Farinotti'] if balance == 'Ba': ax1[count].axhline(linewidth=1, color='k', ls='--', alpha=a+.2, zorder=0) ax2[count].axhline(linewidth=1, color='k', ls='--', alpha=a+.2, zorder=0) ############ obs data box plot ################ obs_data=obs[(obs.Year==year)]; obs_data.reset_index(inplace=True) if year == 2017: obs_data[balance]= obs_data[balance]-0.32 ## GPS survey correction between LiDAR 9-17-2017 and field 9-8-2017 bin_size = 100.; z_range = np.arange(1950., 3250., bin_size) i = 0; Z_F = []; Zor_F= []; OB_F=[] for z in z_range: W=0;bin_size = 100.; COU=1 while W==0: OBS = [];Z = [];Zor = []; for n in range(len(obs_data[balance])): if ((z - bin_size/2.) <= obs_data.Elev[n]) and (obs_data.Elev[n] <= (z + bin_size/2.)): O = obs_data[balance][n] Z.append(z);Zor.append(obs_data.Elev[n]);OBS.append(O) if len(OBS)<2: bin_size=bin_size*(1+(.2*COU)) COU=COU+1 else: OB_F.append(np.array(OBS)); Z_F.append(np.array(Z)); Zor_F.append(np.array(Zor)) W=1 i += 1 ##################Difference########################################################### GPR = [];OPT = [];FAR = [] for z in z_range: W=0; COU=1;bin_size = 100. while W==0: GG=[];PP=[];FF=[] ####collect balance values for each elevation bin for n in range(len(new.dem_mean)): #for n in new.bin: # if ((z - bin_size/2.) <= new.dem_mean[n]) and (new.dem_mean[n] <= (z + bin_size/2.)): G = new.b_fg_we_gpr[n] P = new.b_fg_we[n] F = new.b_fg_weF[n] GG.append(G);FF.append(F);PP.append(P) GG=np.array(GG) GG = GG[np.logical_not(np.isnan(GG))] if len(GG)<1: bin_size=bin_size*(1+(0.1*COU)) COU=COU+1 else: GPR.append(GG);OPT.append(np.array(PP));FAR.append(np.array(FF)) W=1 if count == 0: gpr_bdiff=[];opt_bdiff=[];farin_bdiff=[];z_range_all=[];obs_all=obs_data;obs_bin_all=[];gpr_all=[]; opt_all=[];farin_all=[];elev_all=[];elev_gpr_all=[];gpr_bin_all=[];opt_bin_all=[];farin_bin_all=[]; NSE=[];PBias=[];RSR=[];RSQ=[];SE=[];SL=[];ME=[];MAE=[];MSE_ABL=[];MSE_ACC=[];MSE_ALL=[];RLM_SL=[]; RLM_SE=[];SL_L=[];SE_L=[];RSQ_L=[];gpr_bd_fg=[];opt_bd_fg=[];farin_bd_fg=[];obs_fg_all=[];ELA_pw=[];ELA_lin=[] ###### bfinned observations for each flux bin ############## OB_FG=[];OB_FG_h=[] for i in range(len(new.dem_mean)): f = new.dem_mean[i] W=0;bin_size = new.dem_std[i]*2; COU=1 while W==0: OBSFG = []; OBSFGh=[] for n in range(len(obs_data[balance])): if ((f - bin_size) <= obs_data.Elev[n]) and (obs_data.Elev[n] <= (f + bin_size)): O = obs_data[balance][n] Oh= obs_data['Ba_h'][n] OBSFG.append(O);OBSFGh.append(Oh) if len(OBSFG)<3:#and bin_size<175: bin_size=bin_size*(1+(.2*COU)) COU=COU+1 else: OB_FG.append(np.array(OBSFG));OB_FG_h.append(np.array(OBSFGh)); W=1 ##### boxplot of observations ###### meanlineprops = dict(linestyle='--', linewidth=1., color='0.5'); medianprops = dict(linestyle='-', linewidth=1, color='k') boxprops = dict(linewidth=0.5); BOX=ax1[count].boxplot(OB_FG,meanprops=meanlineprops,medianprops=medianprops,showmeans=True, meanline=True,sym='', positions=new.dem_med,widths=75,boxprops=boxprops,whiskerprops=boxprops) OBF=[];GPRq=[];OPTq=[];FARq=[];OB_FGmean=[];OB_FG_hmean=[] ###calculate mean of balance values within each elevation bin for i in range(len(OB_F)): OBF.append(np.round(OB_F[i].mean(),3));GPRq.append(np.round(GPR[i].mean(),3)) OPTq.append(np.round(OPT[i].mean(),3));FARq.append(np.round(FAR[i].mean(),3)) for i in range(len(OB_FG)): ##OBS means for each FG bin OB_FGmean.append(np.round(OB_FG[i].mean(),3));OB_FG_hmean.append(np.round(OB_FG_h[i].mean(),3)) FG_all['OB_FG']=OB_FGmean FG_all.dropna(subset=['b_fg_we_gpr'], inplace=True) ## remove data for bins where GPR is nan obs_fg_all.extend(OB_FGmean);obs_bin_all.extend(OBF);gpr_bin_all.extend(GPRq);opt_bin_all.extend(OPTq);farin_bin_all.extend(FARq);z_range_all.extend(z_range) ##all binned data elev_gpr_all.extend(FG_all.dem_mean);gpr_all.extend(FG_all.b_fg_we_gpr);opt_all.extend(new.b_fg_we); farin_all.extend(new.b_fg_weF);elev_all.extend(new.dem_mean) ## all point and gate data gpr_bdiff.extend((np.array(OBF) - np.array(GPRq))); opt_bdiff.extend((np.array(OBF) - np.array(OPTq))); farin_bdiff.extend((np.array(OBF) - np.array(FARq))) gpr_bd_fg.extend((np.array(OB_FGmean) - np.array(new.b_fg_we_gpr)))#; gpr_bd_fg.extend([np.nan,np.nan]) opt_bd_fg.extend((np.array(OB_FGmean) - np.array(new.b_fg_we))); farin_bd_fg.extend((np.array(OB_FGmean) - np.array(new.b_fg_weF))) ############## piecewise function ######################################## # y_bin=[OBF,GPRq[:-2],OPTq,FARq]; x_bin=[z_range,z_range[:-2],z_range,z_range] y_bin=[OB_FGmean,FG_all.b_fg_we_gpr, new.b_fg_we,new.b_fg_weF]; x_bin=[new.dem_med,FG_all.dem_med,new.dem_med,new.dem_med] bp = [2525,2575,2500] # break point (~ELA) ELA = [2530,2600,2645]; s_ELA = [135,110,90] def piecewise_linear(x, x0, y0, k1, k2): x0=bp[I] return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) for i in range(4): x0=bp[I];Y=np.array(y_bin[i]); X=np.array(x_bin[i]) p , e = curve_fit(piecewise_linear, X, Y ) xd = np.arange(1950., 3200., 10.); yd = piecewise_linear(xd, *p) ## get the slope model = pwlf.PiecewiseLinFit(xd, yd) breaks = model.fit_guess([x0]); #breakpoints = [2150.,x0,2900.] sl=model.slopes; se=model.standard_errors(); rsq=model.r_squared() SL.append(sl);RSQ.append(rsq) #x_hat = np.linspace(2150, 2900, 10); y_hat = model.predict(x_hat) ela = (0.0 - model.intercepts[0]) / sl[0]; ELA_pw.append(ela) if fit == 'PW': ax1[count].plot(xd, piecewise_linear(xd, *p), color=color[i], lw=1., alpha=0.9)#0.9 # X=np.array(y_bin[i]); Y=np.array(x_bin[i]) ######## calc SE ###### model1 = pwlf.PiecewiseLinFit(X, Y) breakpoints1 = [1950,x0,3300] model1.fit_with_breaks(breakpoints1);se=model1.standard_errors();SE.append(se); ####################### x1=np.array(x_bin[i]); y1=np.array(y_bin[i]) # mean square error of the lines for Line in range(2): Pred=[];Act=[] if Line ==0: INDEX= np.where(x1<x0)[0] for ix in INDEX: Pred.append( p[2]*x1[ix]+(p[1]-p[2]*x0)) Act.append(y1[ix]) MSE_ABL.append(MSE(Act,Pred)) if Line==1: INDEX= np.where(x1>=x0)[0] for ix in INDEX: Pred.append( p[3]*x1[ix]+(p[1]-p[3]*x0)) Act.append(y1[ix]) MSE_ACC.append(MSE(Act,Pred)) ########## Linear fit ################## for i in range(4): Y=np.array(y_bin[i]);X=np.array(x_bin[i]) model = pwlf.PiecewiseLinFit(X, Y) breakpoints = [1950.,3300.] model.fit_with_breaks(breakpoints) x_hat = np.linspace(1950, 3120, 10); y_hat = model.predict(x_hat) if fit == 'LIN': ax1[count].plot(x_hat, y_hat, lw=1.1, alpha=a, color=color[i], zorder=1)#label=label[i]) sll=model.slopes; sel=model.standard_errors(); rsql=model.r_squared() SL_L.append(sll);SE_L.append(sel);RSQ_L.append(rsql) x1=np.array(x_bin[i]); y1=np.array(y_bin[i]) p , e = curve_fit(piecewise_linear, x1, y1 ) xd = np.arange(1950., 3150., 10.) ela = (0.0 - model.intercepts[0]) / sll[0]; ELA_lin.append(ela) ########################### end piecewise ################################ ## add ELA to plot ax1[count].errorbar(ELA[I],0., xerr=s_ELA[I], yerr=None, fmt='o', c='limegreen', mec='b', mfc='limegreen',mew=mew, elinewidth=elw+0.4, label='ELA Satellite', alpha=0.85, zorder=4) ax1[count].set(xlim=(1845,3270), ylim=(-7.5,4.2)) ax1[2].legend(loc='best', bbox_to_anchor=(0.48, 0.55), labelspacing=0.2, handletextpad=0.1) ax1[count].xaxis.set_major_locator(ticker.MultipleLocator(200)) ax1[count].text(0.92, 0.03, letter[count], transform=ax1[count].transAxes) ax1[count].text(0.03, 0.92, year, transform=ax1[count].transAxes) ax2[count].text(0.03, 0.92, year, transform=ax2[count].transAxes) ax1[count].set_xticklabels(['',2000, '', 2400, '', 2800, '', 3200]) ################### mass conservation plot #################################### BM= []; BMh=[] for i in range(len(OB_FG)): B = OB_FG[i].mean();Bh = np.mean(OB_FG_h[i]) # choose median or mean BM.append(B);BMh.append(Bh) new['SMB'] = OB_FGmean; new['BH']= BMh # or OB_FG_hmean new['BMC'] = new.BH + new.Q_netA - new.Vfirn new['BMC_gpr'] = new.BH + new.Q_netA_gpr - new.Vfirn new['BMCF'] = new.BH + new.Q_netAF - new.Vfirn ###################### https://pypi.org/project/hydroeval/ ############################## ############### STATS using elev binned data EST=[np.array(GPRq[:-2]),np.array(OPTq),np.array(FARq)] ## must be arrays not lists OBFa=np.array(OBF);OBFGma=np.array(OB_FGmean) ME.append(0.0);MAE.append(0.0),RSR.append(0.0);PBias.append(0.0);NSE.append(0.0) for e in range(3): FLB=np.array(y_bin[e+1]) if e==0: PBias.extend(evaluator(pbias, FLB, np.array(FG_all.OB_FG))) #def pbias(simulations, evaluation): ME.append((np.array(FG_all.OB_FG)-FLB).mean());MAE.append(np.abs(np.array(FG_all.OB_FG)-FLB).mean()) else: PBias.extend(evaluator(pbias, FLB, OBFGma)) # RMSE=evaluator(rmse, EST[e], OBFa); RSR.extend((RMSE/(np.std(OBFa)))) ME.append((OBFGma-FLB).mean()); MAE.append(np.abs(OBFGma-FLB).mean()) MC = [new.BMC_gpr,new.BMC, new.BMCF] # MC= [new.b_fg_h_gpr, new.b_fg_h, new.b_fg_hF] Yvv = [new.Q_netA_gpr, new.Q_netA, new.Q_netAF] Yvv_lbl=[r'$V^{\uparrow}_{IPR}$',r'$V^{\uparrow}_{OGGM}$',r'$V^{\uparrow}_{Farin}$'] yerr_dh= [new.sBwe_gpr/(new['RHO_g']/1000) , new.sBwe_opt/(new['RHO']/1000), new.sBwe_F/(new['RHO_F']/1000)] if I == 0: overlap=[];overlap_gpr=[];overlapF=[] MC_LIST=[overlap_gpr,overlap,overlapF] for i in range(3): if i == 0: ax2[count].errorbar(new.dem_med+shift[i]+5,MC[i], xerr=None, yerr=yerr_dh[i], fmt=sym[i+1], c=color[i+1], mfc=mfc,mew=mew, elinewidth=elw,mec=color[i+1], label=txt[i+1], alpha=0.8, zorder=3) else: ax2[count].errorbar(new.dem_med+shift[i],MC[i], xerr=None, yerr=yerr_dh[i], fmt=sym[i+1], c=color[i+1], mec=color[i+1], mfc=mfc,mew=mew, elinewidth=elw, label=txt[i+1], alpha=0.8, zorder=3) ####count the number of SMB obs. +/- 1-error which fall within the uncertainty bounds of the LiDAR height change OL = MC_LIST[i] ## select which list to append to for r in range(len(MC[i])): M_min = MC[i][r] - yerr_dh[i][r]; M_max = MC[i][r]+ yerr_dh[i][r] L_min = new.dh_mean[r] - sDHdt*2; L_max = new.dh_mean[r] + sDHdt*2 if (i==0) and r>5 and r<8: ## gpr bins without data OL.append(np.nan) elif M_min > L_min and M_min < L_max: OL.append(1);# W=0 elif M_max < L_max and M_max > L_min: OL.append(1); #W=0 elif M_max > L_max and M_min < L_min: OL.append(1); #W=0 elif M_max < L_max and M_min > L_min: OL.append(1); #W=0 else: OL.append(0) Ybd = [BM, new.b_fg_we_gpr, new.b_fg_we, new.b_fg_weF] ax2[count].errorbar(new.dem_med,new.dh_mean, xerr=50, yerr=sDHdt*2, fmt='o', c='k', label='LiDAR',alpha=0.8, zorder=2, mfc='none', elinewidth=elw) ax2[count].text(0.92, 0.92, letter[count], transform=ax2[count].transAxes) ax2[count].set(xlim=(1845,3250), ylim=(-7.,3.5)) ax2[count].set_xticklabels(['',2000, '', 2400, '', 2800, '', 3200]) # ax1[count].set(ylim=(-9.,3.5)) #xlim=(1850,3300) ax2[2].legend(loc='lower center', ncol=2,columnspacing=0.5,handletextpad=0.5) ax1[count].tick_params(which='major', length=3); ax2[count].tick_params(which='major', length=3) count+=1 bin_df = pd.DataFrame(list(zip(z_range, OB_F, GPR, OPT, FAR)), columns=['Elev', 'OBS', 'GPR', 'OGGM', 'FARIN']) bin_df.to_csv(fl_path+'bin_df_' + str(year) +'.csv') if year==2016: new16=new.copy();new16.to_pickle(fl_path+'conrad_new16.pkl') elif year==2017: new17=new.copy();new17.to_pickle(fl_path+'conrad_new17.pkl') else: new.to_pickle(fl_path+'conrad_new18.pkl') if year == 2016: VEL_LIST = [D.vfg.mean()] else: VEL_LIST.append(D.vfg.mean()) fig1.subplots_adjust(bottom=0.09, top=0.98, hspace=0.1, left=0.06, right=0.99, wspace=0.05)#left=0.07, right=0.9,wspace=0.05, fig2.subplots_adjust(bottom=0.09, top=0.98, hspace=0.1, left=0.06, right=0.99, wspace=0.05) # fig2.text(0.008, 0.6, 'Height change (m ice $a^{-1}$)', rotation=90); fig1.text(0.008, 0.6, 'Mass balance (m w.e.)', rotation=90) # fig1.text(0.45, 0.01, 'Elevation (m a.s.l.)');fig2.text(0.45, 0.01, 'Elevation (m a.s.l.)') if ITS_LIVE == True: vtype='_ITSLIVE' else: vtype='_indV25m' if firn==True: FIRN= "_FIRN" else: FIRN ="_NOFIRN" fig1.savefig(fl_path+'products/'+glacier[gl]+'_bdot_'+ fit +'_11bins_25m_OBFG_dcalc_' +str(Dint)+'_'+balance + FIRN+ vtype + '.pdf', dpi=300) #_NOfirn fig2.savefig(fl_path+'products/'+glacier[gl]+'_mass_con_' + fit + '_11bins_' + str(Dint)+'_'+balance + FIRN + vtype + '.pdf', dpi=300) SE=np.array(SE);SL=np.array(SL);SE_L=np.array(SE_L);SL_L=np.array(SL_L); # - print('ipr',np.sum(MC_LIST[0])/ len(MC_LIST[0]), np.nansum(MC_LIST[0]), len(MC_LIST[0]), 'nan:',len(np.array(MC_LIST[0])[np.isnan(np.array(MC_LIST[0]))])) print('OGGM',round(np.sum(MC_LIST[1])/ len(MC_LIST[1]),3), np.sum(MC_LIST[1]), len(MC_LIST[1])) print('Farin',round(np.sum(MC_LIST[2])/ len(MC_LIST[2]),3), np.sum(MC_LIST[2]), len(MC_LIST[2])) print('all',round(np.nansum(MC_LIST)/ (len(MC_LIST[0])+len(MC_LIST[1])+len(MC_LIST[2])-6),3), np.nansum(MC_LIST), (len(MC_LIST[0])+len(MC_LIST[1])+len(MC_LIST[2]))-6) pd.set_option('display.max_columns', None) new # + ### Conrad ANOVA # stats.f_oneway(obs_fg_all,gpr_all),stats.f_oneway(obs_fg_all,opt_all) ,stats.f_oneway(obs_fg_all,farin_all) # + ### save residuals residuals= [z_range_all,gpr_bdiff,farin_bdiff,opt_bdiff,obs_bin_all] r = pd.DataFrame(list(zip(z_range_all,elev_all,gpr_bdiff,farin_bdiff,opt_bdiff,gpr_bd_fg,opt_bd_fg,farin_bd_fg,obs_bin_all,obs_fg_all)), columns=['z_range_all','elev_all','gpr_bdiff','farin_bdiff','opt_bdiff','gpr_bd_fg','opt_bd_fg','farin_bd_fg', 'obs_bin_all','obs_fg_all']) # r['zrel'] = r.elev_all-np.nanmin(dem.data[msk_conrad.data==1.0]) ## use minimum elevation # r.zrel= r.zrel / np.nanmax(dem.data[msk_conrad.data==1.0]) ## ## use minimum elevation r['zrel'] = r.elev_all-r.z_range_all.min() r.zrel= r.zrel / r.zrel.max() r['gpr_fr']=r.gpr_bdiff/np.abs(r.obs_bin_all);r['far_fr']=r.farin_bdiff/np.abs(r.obs_bin_all); r['opt_fr']=r.opt_bdiff/np.abs(r.obs_bin_all); ## for FG bins r['opt_bd_fr']=r.opt_bd_fg/np.abs(r.obs_fg_all) r['farin_bd_fr']=r.farin_bd_fg/np.abs(r.obs_fg_all);r['gpr_bd_fr']=r.gpr_bd_fg/np.abs(r.obs_fg_all); # pd.set_option('display.max_columns', None) # r fig_path= '/home/pelto/Desktop/ice_flux/figures/' with open(fig_path + glacier[gl]+'_residuals.pkl', 'wb') as f: #_NOfirn pickle.dump(r, f) # - # ## Stake Velocities stakes=pd.read_csv(fl_path + 'stake_vel_VV_ALL.csv') k_stakes=pd.read_csv('/home/pelto/Desktop/ice_flux/Kokanee/stakes_vel.csv') # + ###### plot stake versus flux gate velocties fig3, ax3 = plt.subplots(1,1, sharex=True, sharey=True, figsize=(cm2inch(6, 6))) Yvv = [new.Q_netA_gpr, new.Q_netA, new.Q_netAF] Yvv_lbl=[r'$V^{\uparrow}_{IPR}$',r'$V^{\uparrow}_{OGGM}$',r'$V^{\uparrow}_{Farin}$'] ax3.scatter(stakes.Elev_Old+25.,stakes.velocity,color='#1c9099',label='Stakes', alpha=0.6, s=6,facecolor='', zorder=3) # AX=ax3.twinx() # for i in range(3): # ax3.scatter(new.dem_mean, Yvv[i], edgecolor='k', marker=sym[i+1], alpha=0.6, label=Yvv_lbl[i], s=35, # color=color[i+1], zorder=2, linewidth=0.25) meanlineprops = dict(linestyle='--', lw=0.5, color='r');medianprops = dict(linestyle='-', lw=0.5,color='k') boxprops = dict(linewidth=0.25); BOXVEL=ax3.boxplot(vfg_all,meanprops=meanlineprops,medianprops=medianprops,boxprops=boxprops,whiskerprops=boxprops, showmeans=True, meanline=True, sym='', positions=gate_elev,widths=30, zorder=1) # ax3.set_xticks([2000, 2200, 2400, 2600, 2800, ]) #, 2650]) ax3.xaxis.set_major_locator(ticker.MultipleLocator(200)) # ax3.set_xticklabels([2100, 2200, 2300, 2400, 2500, 2600]) ax3.set_xticklabels(['',2000, '', 2400, '', 2800, '',3200, '']) ax3.set(xlim=(1850, 3150)) # ax3.legend(loc='upper right', labelspacing=0.35) fig3.text(0.005, 0.7, 'Ice velocity (m $a^{-1}$)',rotation=90) # fig3.text(0.005, 0.65, r'$V^{\uparrow}$' + '(m ice $a^{-1}$)',rotation=90) #transform=ax3.transAxes) # fig3.text(0.94, 0.7, 'Ice velocity (m $a^{-1}$)',rotation=90) fig3.subplots_adjust(bottom=0.11, top=0.98, hspace=0.1, left=0.15, right=0.98, wspace=0.05) fig3.savefig(fl_path + 'products/' + glacier[gl] + '_Velocities_only.pdf', dpi=300) # - # ## 3-Panel plot emergence velocity I_stakes_mean = [2.97,1.89,0.76,np.nan,-0.83,-1.57];I_stakes_mean_elev =[2206.26, 2325.64, 2395.14, 2479.68, 2547.14, 2585.20] k_stakes_mean=[1.37,1.01,0.56];k_stakes_mean_elev=[2289.58, 2422.68,2519.7] C_stakes_mean=[0.98,2.20,2.13,1.49,1.48,1.01,-1.11];C_stakes_mean_elev=[1998.67, 2079.7 , 2127.6 , 2215.65, 2334.59, 2426.14, 2554.7] # + ##only emergence velocity import pickle font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 9} plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1.';pylab.rcParams['ytick.major.pad']='1.' fig_path= '/home/pelto/Desktop/ice_flux/figures/' ;pylab.rcParams['ytick.major.size']='3' Glacier = ['Conrad', 'Illecillewaet','Kokanee', 'Nordic','Zillmer'] glacier = ['conrad', 'illecillewaet','kokanee', 'nordic', 'zillmer'] ########### plot for all three glaciers fig3, ax3 = plt.subplots(1,5, sharey=True, figsize=(cm2inch(18, 5))) ##mass conservation plot color = ['k', '#51c2d5','#663f3f','#ec4646'] letter=['A','B','C','D','E'] for g in range(len(glacier)): # VV=pd.read_csv(fig_path+ glacier[g]+ '_new_2018.csv') fpath=fl_path[:-7]+Glacier[g]+'/' with open(fpath + glacier[g] +'_new18.pkl', 'rb') as f: VV = pickle.load(f) # with open(fig_path + glacier[g] +'_vfg_all.pkl', 'rb') as f: # vfg_all = pickle.load(f) # with open(fig_path +glacier[g] +'_gate_elev.pkl', 'rb') as f: # gates_elev = pickle.load(f) for i in range(3): Yvv = [VV.Q_netA_gpr, VV.Q_netA, VV.Q_netAF] Yvv_lbl=[r'$V_{z,IPR}$',r'$V_{z,OGGM}$',r'$V_{z,Farin}$'] print(np.mean([VV.Q_netA_gpr[0], VV.Q_netA[0], VV.Q_netAF[0]])) ax3[g].scatter(VV.dem_mean, Yvv[i], edgecolor=color[i+1], marker=sym[i+1], alpha=0.9, label=Yvv_lbl[i], s=40, color=color[i+1], zorder=1+i, linewidth=0.25,facecolor='',lw=mew+.1) # ax3[0].set_ylim(-12,8) ax3[1].yaxis.set_major_locator(ticker.MultipleLocator(1));#set_xticks([2100, 2200, 2300, 2400, 2500, 2600]) if g == 0: ax3[0].xaxis.set_major_locator(ticker.MultipleLocator(200)); ax3[0].set_xticklabels(['',2000, '', 2400, '', 2800, '']); ax3[0].set(xlim=(1850, 3120))#, ylim=(-3.2,3.2)) elif g==1: ax3[1].set_xticks([2100, 2200, 2300, 2400, 2500, 2600]) #, 2650]) ax3[1].set_xticklabels(["", 2200, "", 2400, "", 2600]) ax3[1].set(xlim=(2160, 2625))#AX.set_yticklabels([""]) elif g==2: ax3[g].xaxis.set_major_locator(ticker.MultipleLocator(200)); ax3[2].set_xticklabels(['', '2400', '', 2600, '', '']) ax3[g].set_xticks([2300, 2400, 2500, 2600, 2700, 2800]) ;ax3[g].set(xlim=(2250, 2760)) elif g==3: ax3[g].xaxis.set_major_locator(ticker.MultipleLocator(200)); ax3[3].set_xticklabels(['',2200, 2400, 2600, 2800]) ;ax3[g].set(xlim=(2150, 2850)) elif g==4: ax3[g].xaxis.set_major_locator(ticker.MultipleLocator(200));ax3[g].set(xlim=(2000, 2700)) # ax3[2].set_xticklabels([2300, '', 2500, '', 2700, '']) ax3[g].set_xticklabels(['','',2200, 2400, 2600, 2800]) ax3[g].set_zorder(1) ax3[g].patch.set_visible(False) ax3[g].text(0.90, 0.03, letter[g], transform=ax3[g].transAxes) ax3[g].text(0.97, 0.92, Glacier[g], transform=ax3[g].transAxes, ha='right') # if g==0: # ax3[g].text(0.75, 0.95, Glacier[g], transform=ax3[g].transAxes) # elif g==1: # ax3[g].text(0.6, 0.95, Glacier[g], transform=ax3[g].transAxes) # else: # ax3[g].text(0.7, 0.95, Glacier[g], transform=ax3[g].transAxes) ax3[g].axhline(linewidth=1, color='k', ls='--', alpha=0.25, zorder=0) # ELA 2013--2018 ELA=[2591,2549,2605,2588,2466]; ELA_std=[58,51,61,37,42] ax3[g].errorbar(ELA[g],0.,xerr=ELA_std[g],color='k', alpha=.9, fmt='o',ms=4, zorder=7,lw=mew+.1,label='ELA') ###individual stakes # ax3[0].scatter(stakes.Elev_Old,stakes.VV_tan,color='r',label='StakesTAN', alpha=0.9, # s=8,facecolor='', zorder=6) # ax3[1].scatter(I_stakes.Elev,I_stakes.VV_d,color='k',label='', alpha=0.4, # s=8,facecolor='', zorder=6) # ax3[2].scatter(k_stakes.Elev,k_stakes.VV,color='k',label='', alpha=0.4, # s=8,facecolor='', zorder=6) # ax3[0].scatter(stakes.Elev_Old+25.,stakes.VV,color='r',label='Stakes', alpha=0.9, # s=8,facecolor='', zorder=6) # ax3[0].scatter(stakes.Elev_Old+25.,stakes.VV_diff,color='k',label='', alpha=0.4, # s=8,facecolor='', zorder=6) ## grouped stakes ax3[1].scatter(I_stakes_mean_elev,I_stakes_mean,color='k',label='Stakes', alpha=.9, s=40,facecolor='', zorder=6,lw=mew+.1) ax3[2].scatter(k_stakes_mean_elev,k_stakes_mean,color='k',label='Stakes', alpha=.9, s=40,facecolor='', zorder=6,lw=mew+.1) ax3[0].scatter(C_stakes_mean_elev,C_stakes_mean,color='k',label='Stakes', alpha=.9, s=40,facecolor='', zorder=6,lw=mew+.1) ax3[1].legend(loc='lower left', labelspacing=0.18, ncol=1,columnspacing=0.05,handletextpad=0.05, borderpad=0.07,borderaxespad=0.15) #, bbox_to_anchor=(0.99, 0.94)) # ax3[0].set_ylabel(r'$V_{z}$' + ' (m ice $a^{-1}$)') fig3.text(0.005, 0.4, r'$V_{z}$' + ' (m ice $a^{-1}$)',rotation=90) #transform=ax3[g].transAxes) # fig3.text(0.975, 0.67, 'Ice velocity (m $a^{-1}$)',rotation=90) ax3[2].set_xlabel('Elevation (m a.s.l.)')#;ax3[0].set_ylabel(r'$V_{z}$' + ' (m ice $a^{-1}$)') fig3.subplots_adjust(bottom=0.185, top=0.99, hspace=0.05, left=0.065, right=0.99, wspace=0.09) fig3.savefig(fig_path + 'Emergence_velocities_5.pdf', dpi=300) # - # # Conrad Statistics ELA ELA_sat=[];sELA_sat=[] for i in range(len(ELA)): ELA_sat= ELA_sat+ ([ELA[i]] * 4) sELA_sat= sELA_sat+ ([s_ELA[i]] * 4) ELA_sat,sELA_sat # + # MSE_ABL,MSE_ACC, 'MSE_ABL','MSE_ACC',RSR, NSE, method=[] for i in range(4): method.extend(label) len(method) STATS=pd.DataFrame(list(zip(method,SL_L[:,0], SE_L[:,1],SL[:,0], SE[:,1],SL[:,1], SE[:,2], ELA_pw ,ELA_sat,sELA_sat,ME,MAE)),#PBias columns=['method','ALL','ALLse','ABL', 'ABLse', 'ACC', 'ACCse', 'ELA', 'ELA_sat' ,'sELA_sat','ME','MAE']) #'PBias' STATS.ALL=STATS.ALL*1000;STATS.ALLse=STATS.ALLse*1000;STATS.ABL=STATS.ABL*1000;STATS.ABLse=STATS.ABLse*1000; STATS.ACC=STATS.ACC*1000;STATS.ACCse=STATS.ACCse*1000 STATS # STATS.ACC[STATS.method=='Observed'].min()/STATS.ACC[STATS.method=='Observed'].max() # STATS.ACC.mean()/STATS.ABLse.mean() # STATS=pd.read_pickle(FLP+Glacier[1]+ '/' + glacier[1]+ '_NOfirn_PW_stats.pkl') # STATS M= ['Observed','FG IPR','FG OGGM','FG Farinotti'] for m in M: L= STATS[STATS.method==m].values MEAN= np.nanmean(L[:,1:],axis=0) MEAN= np.insert(MEAN,0,m) STATS= STATS.append(dict(zip(STATS.columns, MEAN)),ignore_index=True) STATS=STATS.round(2);STATS.ABLse=STATS.ABLse.round(1);STATS.ACCse=STATS.ACCse.round(1);STATS.ALLse=STATS.ALLse.round(1) STATS.ELA=STATS.ELA.round(0);STATS.ELA=pd.to_numeric(STATS.ELA, downcast='integer') #.round(0)#STATS.PBias=STATS.PBias.round(1) STATS.ELA_sat=STATS.ELA_sat.round(0);STATS.ELA_sat=pd.to_numeric(STATS.ELA_sat, downcast='integer') STATS.sELA_sat=STATS.sELA_sat.round(0);STATS.sELA_sat=pd.to_numeric(STATS.sELA_sat, downcast='integer') if firn == True: STATS.to_pickle(fl_path+glacier[gl]+'_stats_firn_LIN_stats.pkl') else: STATS.to_pickle(fl_path+glacier[gl]+'_stats_NOfirn_LIN_stats.pkl') # STATS.to_pickle(fl_path+'conrad_stats_ITS_LIVE_NOfirn.pkl') # STATS.to_pickle(fl_path+glacier[gl]+'_stats_mosaic_NOfirn.pkl') STATS # - S1=STATS.copy() AB=[];AC=[];AL=[];EL=[]; for i in range(len(S1)): AL.append(str(S1.ALL[i])+' $\pm$ '+str(S1.ALLse[i])) AB.append(str(S1.ABL[i])+' $\pm$ '+str(S1.ABLse[i])) AC.append((str(S1.ACC[i])+' $\pm$ '+str(S1.ACCse[i]))) EL.append((str(S1.ELA_sat[i])+' $\pm$ '+str(S1.sELA_sat[i]))) S1.ABL=AB;S1.ACC=AC;S1.ALL=AL;S1.ELA_sat=EL S1.drop(columns=['ABLse','ACCse','ALLse','sELA_sat'], inplace=True) S1 print(S1.to_latex(index=False)) # ## Calculate statistics for all five glaciers # + Glacier = ['Conrad', 'Illecillewaet','Kokanee', 'Nordic','Zillmer'] glacier = ['conrad', 'illecillewaet','kokanee', 'nordic', 'zillmer'] FLP='/home/pelto/Desktop/ice_flux/' if firn ==False: K_stats=pd.read_pickle(FLP+ Glacier[2]+ '/' + glacier[2]+ '_stats_NOfirn_LIN_stats.pkl') #NO_firn C_stats=pd.read_pickle(FLP+Glacier[0]+ '/' + glacier[0]+ '_stats_NOfirn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') I_stats=pd.read_pickle(FLP+Glacier[1]+ '/' + glacier[1]+ '_stats_NOfirn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl') #'_LIN_firn_stats.pkl') N_stats=pd.read_pickle(FLP+ Glacier[3]+ '/' + glacier[3]+ '_stats_NOfirn_LIN_stats.pkl') #NO_firn Z_stats=pd.read_pickle(FLP+Glacier[4]+ '/' + glacier[4]+ '_stats_NOfirn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') else: K_stats=pd.read_pickle(FLP+ Glacier[2]+ '/' + glacier[2]+ '_stats_firn_LIN_stats.pkl') #NO_firn C_stats=pd.read_pickle(FLP+Glacier[0]+ '/' + glacier[0]+ '_stats_firn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') I_stats=pd.read_pickle(FLP+Glacier[1]+ '/' + glacier[1]+ '_stats_firn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl') #'_LIN_firn_stats.pkl') N_stats=pd.read_pickle(FLP+ Glacier[3]+ '/' + glacier[3]+ '_stats_firn_LIN_stats.pkl') #NO_firn Z_stats=pd.read_pickle(FLP+Glacier[4]+ '/' + glacier[4]+ '_stats_firn_LIN_stats.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') ## ITS LIVE stats # C_stats=pd.read_pickle(FLP+Glacier[0]+ '/' + glacier[0]+ '_stats_ITS_LIVE_NOfirn.pkl')# # I_stats=pd.read_pickle(FLP+Glacier[1]+ '/' + glacier[1]+ '_stats_ITS_LIVE_NOfirn.pkl') # N_stats=pd.read_pickle(FLP+ Glacier[3]+ '/' + glacier[3]+ '_stats_ITS_LIVE_NOfirn.pkl') #NO_firn # Z_stats=pd.read_pickle(FLP+Glacier[4]+ '/' + glacier[4]+ '_stats_ITS_LIVE_NOfirn.pkl')# ## Mosaic stats # K_stats=pd.read_pickle(FLP+ Glacier[2]+ '/' + glacier[2]+ '_stats_mosaic_NOfirn.pkl') #NO_firn # C_stats=pd.read_pickle(FLP+Glacier[0]+ '/' + glacier[0]+ '_stats_mosaic_NOfirn.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') # I_stats=pd.read_pickle(FLP+Glacier[1]+ '/' + glacier[1]+ '_stats_mosaic_NOfirn.pkl')#'_stats_ITS_LIVE_NOfirn.pkl') #'_LIN_firn_stats.pkl') # N_stats=pd.read_pickle(FLP+ Glacier[3]+ '/' + glacier[3]+ '_stats_mosaic_NOfirn.pkl') #NO_firn # Z_stats=pd.read_pickle(FLP+Glacier[4]+ '/' + glacier[4]+ '_stats_mosaic_NOfirn.pkl')#'_stats_ITS_LIVE_NOfirn.pkl')#'_firn_LIN_stats.pkl') # + ########## ALL STATS ##################### tail = True I_stats['Glacier']=Glacier[1];C_stats['Glacier']=Glacier[0];K_stats['Glacier']=Glacier[2]; Z_stats['Glacier']=Glacier[3];Z_stats['Glacier']=Glacier[4]; ### all av. stats if tail ==True: for i in range(len(frames)): frames[i] = frames[i].tail(4) else: frames=[C_stats,I_stats,K_stats,N_stats,Z_stats] ### all stats ALL_stats=pd.concat(frames, join='inner') # inner keeps order ALL_stats.ME[ALL_stats.method=='Observed']=np.nan;#ALL_stats.PBias[ALL_stats.method=='Observed']=np.nan ALL_stats.MAE[ALL_stats.method=='Observed']=np.nan; print(len(ALL_stats)) ALL_stats.reset_index(inplace=True);ALL_stats.drop(columns=['index'], inplace=True) # ALL =ALL_stats.copy() # ALL_stats.drop(columns=['method'], inplace=True) M= ['Observed','FG IPR','FG OGGM','FG Farinotti'] for m in M: L= ALL_stats[ALL_stats.method==m].values if m == 'Observed': MEAN= np.nanmean(L[:,1:-2],axis=0) # MEAN= np.nanmean(L[:,1:],axis=0)np.nanmean(L[:,:-4],axis=0) MEAN=np.append(MEAN,[np.nan,np.nan],axis=0) #MEAN=MEAN.tolist() #MEAN=np.array(MEAN.extend([1,1,1])) else: MEAN= np.nanmean(L[:,1:],axis=0) #L[:,:-1] MEANI= np.insert(MEAN,0,m) ALL_stats= ALL_stats.append(dict(zip(ALL_stats.columns, MEANI)),ignore_index=True) if tail == True: a=[];pdiff=[] for i in range(len(frames)+1): o=ALL_stats.ALL[i*4] for n in range(4): b=ALL_stats.ALL[(i*4)+n] d = ((o-b)/b)*100 pdiff.append(d.round(1)) ALL_stats['ALL_pdiff']=pdiff; ALL_stats.ALL_pdiff[ALL_stats.method=='Observed']=np.nan; ALL_stats=ALL_stats.round(2) # np.nanmean(ALL_stats.ALL_pdiff),np.nanstd(ALL_stats.ALL_pdiff) # np.nanmean(ALL_stats.tail(4).ALL_pdiff),np.nanstd(ALL_stats.tail(4).ALL_pdiff) # print(np.nanmean(pd.to_numeric(ALL_stats.PBias[ALL_stats.method!='Observed'].values)),np.nanstd(pd.to_numeric(ALL_stats.PBias[ALL_stats.method!='Observed'].values))) # print(np.nanmean(pd.to_numeric(ALL_stats.ME[ALL_stats.method!='Observed'].values)),np.nanstd(pd.to_numeric(ALL_stats.ME[ALL_stats.method!='Observed'].values))) # print(np.nanmean(pd.to_numeric(ALL_stats.MAE[ALL_stats.method!='Observed'].values)),np.nanstd(pd.to_numeric(ALL_stats.MAE[ALL_stats.method!='Observed'].values))) ALL_stats # - S1=ALL_stats.copy() AB=[];AC=[];AL=[] for i in range(len(S1)): AL.append(str(S1.ALL[i])+' $\pm$ '+str(S1.ALLse[i])) AB.append(str(S1.ABL[i])+' $\pm$ '+str(S1.ABLse[i])) AC.append((str(S1.ACC[i])+' $\pm$ '+str(S1.ACCse[i]))) S1.ABL=AB;S1.ACC=AC;S1.ALL=AL S1.drop(columns=['ABLse','ACCse','ALLse'], inplace=True) S1 print(S1.to_latex(index=False)) # ALL_statsF.to_pickle('/home/pelto/Desktop/ice_flux/figures/ALL_stats_firn_LIN_stats.pkl') ALL_stats.to_pickle('/home/pelto/Desktop/ice_flux/figures/ALL_stats_NOfirn_LIN_stats.pkl') # ## Plot all years' SMB data for all glaciers on one panel each # + ######### ALL YEARS ALL GLACIERS LIN #### Glacier = ['Conrad', 'Illecillewaet','Kokanee',] with open('/home/pelto/Desktop/ice_flux/' + Glacier[1] +'/ALL_list.pkl', 'rb') as f: illec_all = pickle.load(f) with open('/home/pelto/Desktop/ice_flux/' + Glacier[2] +'/ALL_list.pkl', 'rb') as f: kok_all = pickle.load(f) font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) SEa=[];SLa=[] obs = pd.read_csv(fl_path+ 'Conrad_bdot.csv') obs.dropna(subset=['Ba'],inplace=True) # obs=obs[obs.Year==2016 and obs.Year==2017 and obs.Year==2018] ############## linear function ######################################## fig3, ax3 = plt.subplots(1,3, sharex=False, sharey=True, figsize=(cm2inch(18, 8.5)))# figsize=(8,8))#(3.5,3.5)) # y_bin=[obs_all,gpr_ALL,opt_all,farin_all]; x_bin=[z_range_all,zr_gpr,z_range_all,z_range_all] label=['Observed', 'FG IPR', 'FG OGGM', 'FG Farinotti'] for r in range(3): for i in range(4): if r==0: y_bin=[obs.Ba[(obs.Year>2015) & (obs.Year < 2019)],gpr_all,opt_all,farin_all]; x_bin=[obs.Elev[(obs.Year>2015) & (obs.Year < 2019)],elev_gpr_all,elev_all,elev_all]; x0=2525; breakpoints = [1850.,3300.];xd = np.arange(1950., 3150., 10.);x_hat = np.linspace(1900, 3180, 10) elif r==1: x_bin=[illec_all[i+4],illec_all[i+4],illec_all[i+4],illec_all[i+4]]; y_bin=[illec_all[i],illec_all[i],illec_all[i],illec_all[i]]; x0=2500; xd = np.linspace(2040, 2660, 10) breakpoints = [2040.,2680.];x_hat = np.arange(2040.,2660.,10.) else: x_bin=[kok_all[i+4],kok_all[i+4],kok_all[i+4],kok_all[i+4]]; y_bin=[kok_all[i],kok_all[i],kok_all[i],kok_all[i]];xd = np.arange(2280., 2800., 10.) x0=2560; breakpoints = [2200.,2900.]; x_hat= np.arange(2280., 2800., 10.) def piecewise_linear(x, x0, y0, k1, k2): return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) Y=np.array(y_bin[i]);X=np.array(x_bin[i]) model = pwlf.PiecewiseLinFit(X, Y) model.fit_with_breaks(breakpoints) y_hat = model.predict(x_hat) ax3[r].plot(x_hat, y_hat, lw=1., alpha=1, color=color[i],zorder=1) SLa.append(model.slopes); SEa.append(model.standard_errors()) x1=np.array(x_bin[i]); y1=np.array(y_bin[i]) p , e = curve_fit(piecewise_linear, x1, y1 ) # mean square error of the lines MSE_results=[] for Line in range(2): Pred=[];Act=[] if Line ==0: INDEX= np.where(x1<x0)[0] for ix in INDEX: Pred.append( p[2]*x1[ix]+(p[1]-p[2]*x0)) Act.append(y1[ix]) MSE_results.append(MSE(Act,Pred)) if Line==1: INDEX= np.where(x1>=x0)[0] for ix in INDEX: Pred.append( p[3]*x1[ix]+(p[1]-p[3]*x0)) Act.append(y1[ix]) MSE_results.append(MSE(Act,Pred)) ax3[r].scatter(x_bin[i], y_bin[i], color=color[i], s=10, marker=sym[i], facecolors='none', lw=0.5, label=label[i], zorder=2,alpha=0.7) ax3[0].xaxis.set_major_locator(ticker.MultipleLocator(400));ax3[1].xaxis.set_major_locator(ticker.MultipleLocator(200));ax3[2].xaxis.set_major_locator(ticker.MultipleLocator(200)) ax3[r].text(0.92, 0.03, letter[r], transform=ax3[r].transAxes) ax3[2].legend(loc='lower right', bbox_to_anchor=(0.98, 0.34), labelspacing=0.2, handletextpad=0.1) ax3[r].axhline(linewidth=1, color='k', ls='--', alpha=0.25, zorder=0) ax3[r].text(0.05, 0.95, Glacier[r], transform=ax3[r].transAxes) ax3[0].set(ylim=(-7.5,3.5),ylabel='Mass balance (m w.e.)') ax3[1].set(xlabel='Elevation (m a.s.l.)') fig3.subplots_adjust(bottom=0.15, top=0.98, hspace=0.1, left=0.06, right=0.985, wspace=0.05) fig3.savefig(fl_path + 'products/' + 'All_glaciers_all_years_combined_LIN.pdf', dpi=300) # + ######## ALL YEARS CONRAD ONLY #### font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) obs = pd.read_csv(fl_path+ 'Conrad_bdot.csv') obs.dropna(subset=['Ba'],inplace=True) # obs=obs[obs.Year==2016 and obs.Year==2017 and obs.Year==2018] ############## piecewise function ######################################## fig3, ax3 = plt.subplots(1, sharex=True, sharey=True, figsize=(cm2inch(8.5, 8.5)))# figsize=(8,8))#(3.5,3.5)) # y_bin=[obs_all,gpr_ALL,opt_all,farin_all]; x_bin=[z_range_all,zr_gpr,z_range_all,z_range_all] def piecewise_linear(x, x0, y0, k1, k2): x0=2525. return np.piecewise(x, [x < x0], [lambda x:k1*x + y0-k1*x0, lambda x:k2*x + y0-k2*x0]) label=['Observed', 'FG IPR', 'FG OGGM', 'FG Farinotti'];SEa=[];SLa=[] y_bin=[obs.Ba,gpr_all,opt_all,farin_all]; x_bin=[obs.Elev,elev_gpr_all,elev_all,elev_all] for i in range(4): ##pwlf Y=np.array(y_bin[i]) X=np.array(x_bin[i]) model = pwlf.PiecewiseLinFit(X, Y) breakpoints = [1850.,x0,3300.] model.fit_with_breaks(breakpoints) x_hat = np.linspace(1900, 3270, 10) y_hat = model.predict(x_hat) plt.plot(x_hat, y_hat, lw=1., alpha=1, color=color[i],zorder=1) SLa.append(model.slopes) SEa.append(model.standard_errors()) x1=np.array(x_bin[i]); y1=np.array(y_bin[i]) p , e = curve_fit(piecewise_linear, x1, y1 ) xd = np.arange(1950., 3150., 10.) # ax3.plot(xd, piecewise_linear(xd, *p), color=color[i], label=label[i], lw=1.0) # mean square error of the lines x0=2525. # MSE_results=[] for Line in range(2): Pred=[];Act=[] if Line ==0: INDEX= np.where(x1<x0)[0] for ix in INDEX: Pred.append( p[2]*x1[ix]+(p[1]-p[2]*x0)) Act.append(y1[ix]) # MSE_results.append(MSE(Act,Pred)) if Line==1: INDEX= np.where(x1>=x0)[0] for ix in INDEX: Pred.append( p[3]*x1[ix]+(p[1]-p[3]*x0)) Act.append(y1[ix]) # MSE_results.append(MSE(Act,Pred)) ax3.scatter(x_bin[i], y_bin[i], color=color[i], s=10, marker=sym[i], facecolors='none', lw=0.5, label=label[i], zorder=2,alpha=0.7) # meanlineprops = dict(linestyle='--', linewidth=1., color=color[i]) # medianprops = dict(linestyle='-', linewidth=1, color=color[i]) # if i == 1: # BOX2=ax3.boxplot(y_bin[i],meanprops=meanlineprops,medianprops=medianprops,showmeans=True, meanline=True,sym='', # positions=[1950, 2050, 2150, 2250, 2350, 2450, 2550, 2650, 2750, 2850, 2950, 3050],widths=75) # else: # BOX2=ax3.boxplot(y_bin[i],meanprops=meanlineprops,medianprops=medianprops,showmeans=True, meanline=True,sym='', # positions=[1950, 2050, 2150, 2250, 2350, 2450, 2550, 2650, 2750, 2850, 2950, 3050,3150,3250],widths=75) # ax3.text(0.2, ytxt[i], txt[i]+ ' L1: '+ str(np.round(p[2]*1000,2)) +' L2: ' + # str(np.round(p[3]*1000,2)) + ' AABR: ' + str(np.round(p[2]/p[3],2)), # transform=ax3.transAxes) # ax3.text(0.55, ytxt[i], txt[i] + ' L1: '+ str(round(SL[0]*1000,2))+u" \u00B1 "+ str(round(SE[1]*1000*1.96,2)) +' L2: ' + # str(round(SL[1]*1000,2))+u" \u00B1 "+ str(round(SE[2]*1000*1.96,2)) ,transform=ax3.transAxes) #+ ' AABR: ' + str(np.round(p[2]/p[3],2)), ax3.legend(loc='best') ax3.axhline(linewidth=1, color='k', ls='--', alpha=0.25, zorder=0) ax3.set(ylim=(-8.,3.1),xlim=(1870,3300),ylabel='Mass balance (m w.e.)',xlabel='Elevation (m a.s.l.)') # print(MSE_results) fig3.savefig(fl_path + 'products/' + glacier[gl]+'_' + balance +'_all_years_combined.pdf', dpi=300) # - # ## Plot flux gates as cross-sections (just Conrad) # + ##########just conrad font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1.' pylab.rcParams['ytick.major.pad']='1.' j,k = 0,0 n=0 # K['area_opt'] = K.thick_opt * 10 a=0.8 letter=['A','B','C','D','E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'] div = 1000 # to make y axis km instead of m use 1000, else 1 obs_H = D.copy() obs_H = obs_H.dropna(subset=['gpr']) #, inplace=True) fig, ax = plt.subplots(2,6, figsize=(7.08,2.53)) for i in range(D.ID.nunique()): K=D[D.ID==i].sort_values(by=['distance']) O=obs_H[obs_H.ID==i].sort_values(by=['distance']) # plot glacier surface ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div), color='#43a2ca', alpha=a, label='Ice surf.') #plot gpr thickness gates gpr=(O[O.ID==i].dem/div)-(O[O.ID==i].gpr)/div gpr_mask=np.isfinite(gpr) ax[j,k].plot(O[O.ID==i].distance, gpr, marker='o' , ms=1.5, ls='--', color='k', alpha=a, label='Obs. bed') # ax[j,k].set_ylim(((K.elev[K.ID_opt==i])-(K[K.ID_opt==i].thick_opt)+5).max(), -5) ##plot optimized thickness gates ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div)-(K[K.ID==i].H_opt/div), ls='--', c='r', alpha=a, label='Model bed') #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div)-(K[K.ID==i].farin_corr/div), ls='--', c='salmon', alpha=a, label='Farinotti bed') #marker='o') # ax[1,4].axis('off') if i == 0 or i==11: ax[j,k].text(0.9, 0.08, letter[i], transform=ax[j,k].transAxes, fontweight='bold', verticalalignment='center', horizontalalignment='center') else: ax[j,k].text(0.1, 0.08, letter[i], transform=ax[j,k].transAxes, fontweight='bold', verticalalignment='center', horizontalalignment='center') if i == 6 : ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(200/div)) else: ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(100/div)) ax[j,k].tick_params(which='major', length=2) # ax[j,k].text(0.05, 0.05, letter[i], transform=ax[j,k].transAxes, fontweight='bold', fontsize=10, verticalalignment='center', horizontalalignment='center',) # ax[0,0].set_ylim((1.9, 2.01)) # ax[0,1].set_ylim((1.95, 2.11)) # ax[0,4].set_ylim((2.09, 2.31)) ax[0,5].set_xlim((-100, 2250)) ax[1,5].set_xlim((-100, 1100)) n += 1 k += 1 if n == 5: j += 1 k = 0 if n== 11: j += 1 k = 0 # ax[1,2].legend(loc='best')#, bbox_to_anchor=(0.45, -0.65),) # fig.text(0.01, 0.6, 'Altitude (km a.s.l.)', rotation=90) # fig.text(0.5, 0.01, 'Distance (m)') fig.subplots_adjust(bottom=0.115, top=0.98, left=0.055, right=0.99, wspace=0.25, hspace=0.18) plt.savefig(fl_path + 'products/' + glacier[gl]+'_trial.pdf', dpi=300) plt.show() # for i in range(4): # area=K[K.ID_opt==i].area_opt # area_total = area.sum() # print(area_total) # - # ## Plot flux gates as cross-sections (All 5 glaciers) # + ## ALL glaciers ## Conrad 10 gates, 11 bins, Illec. 5 gates 6 bins, Kokanee 5 gates 6 bins Glacier = ['Kokanee', 'Conrad', 'Illecillewaet', 'Nordic','Zillmer'] glacier = ['kokanee', 'conrad', 'illecillewaet', 'nordic', 'zillmer'] import pickle with open('/home/pelto/Desktop/ice_flux/Illecillewaet/' + glacier[2] +'_df_agg.pkl', 'rb') as f: df_agg_Illec = pickle.load(f) with open('/home/pelto/Desktop/ice_flux/Kokanee/' + glacier[0] +'_df_agg.pkl', 'rb') as f: df_agg_Kok = pickle.load(f) with open('/home/pelto/Desktop/ice_flux/Nordic/2016_D.pkl', 'rb') as f: df_agg_nord = pickle.load(f) with open('/home/pelto/Desktop/ice_flux/Zillmer/zillmer_2016_D.pkl', 'rb') as f: df_agg_zill = pickle.load(f) font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1.' pylab.rcParams['ytick.major.pad']='1.' j,k = 0,0; n=0; l=1.25 # K['area_opt'] = K.thick_opt * 10 a=0.8 letter=['A','B','C','D','E', 'F', 'G', 'H', 'I', 'J', 'K','L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'X', 'Y', 'Z','AA','AB','AC','AD',' '] gate=['C0','C1','C2','C3','C4','C5','C6','C7','C8','C9','I0','I1','I2','I3','I4','K0', 'K1', 'K2', 'K3', 'K4','N0', 'N1', 'N2', 'N3', 'N4','Z0', 'Z1', 'Z2', 'Z3',' ',] div = 1000 # to make y axis km instead of m use 1000, else 1 #Conrad data obs_H = D.copy(); obs_H.gpr[obs_H.len==0.0]=np.nan;obs_H = obs_H.dropna(subset=['gpr']) #, inplace=True) fig, ax = plt.subplots(6,5, figsize=(cm2inch(18, 15))) for i in range(D.ID.nunique()+8+5+6+6): ###conrad gates if n<10: K=D_all[D_all.ID==i].sort_values(by=['distance']) O=obs_H[obs_H.ID==i].sort_values(by=['distance']) # plot glacier surface ax[j,k].tick_params(which='major', length=1.75) ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div), color='#43a2ca', alpha=a, label='Ice surf.', lw=l) #plot gpr thickness gates if n!=6: gpr=(O[O.ID==i].dem/div)-(O[O.ID==i].gpr)/div gpr_mask=np.isfinite(gpr) ax[j,k].plot(O[O.ID==i].distance, gpr, marker='o' , ms=1.0, ls='--', color='k', alpha=a, label='Obs. bed', lw=l) ##plot optimized thickness gates ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div)-(K[K.ID==i].H_opt/div), ls='-.', c='r', alpha=a, label='Model bed', lw=l) #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K[K.ID==i].distance, (K[K.ID==i].dem/div)-(K[K.ID==i].farin_corr/div), ls='--', c='salmon', alpha=a, label='Farinotti bed', lw=l) #marker='o') ax[j,k].text(0.04, 0.09, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') if i == 10: ax[j,k].text(0.9, 0.9, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='center') else: ax[j,k].text(0.9, 0.09, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='center') if i <5 or i==6: ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(100/div)) else: ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(200/div)) # ax[j,k].text(0.04, 0.04, letter[i], transform=ax[j,k].transAxes, fontweight='bold', fontsize=10, verticalalignment='center', horizontalalignment='center',) ax[0,0].set_ylim((1.965, 2.1)); ax[1,2].set_ylim((2.6, 2.95)); ax[1,3].set_ylim((2.63, 3.02)) ax[2,4].set_ylim((2.25, 2.6)); ax[0,3].set_ylim((2.1, 2.31)) # ax[0,5].set_xlim((-100, 1450)); ax[1,5].set_xlim((-50, 1300)) ; n += 1; k += 1 if n == 5: j += 1; k = 0 if n== 10: j += 1; k = 0 ###Illec. gates elif n > 9 and n < 16: # if n==12: # k += 1 K=df_agg_Illec[df_agg_Illec.id==i-10].sort_values(by=['distance']) obs_H = df_agg_Illec.copy();obs_H = obs_H.dropna(subset=['gpr']) O=obs_H[obs_H.id==i-10].sort_values(by=['distance']) # plot glacier surface ax[j,k].tick_params(which='major', length=1.75) ax[j,k].plot(K.distance, (K.dem/div), color='#43a2ca', alpha=a, label='Ice surface', lw=l,) #plot gpr thickness gates gpr=(O.dem/div)-(O.gpr/div) gpr_mask=np.isfinite(gpr) ax[j,k].plot(O.distance, gpr, marker='o' , ms=1.0, ls='--', color='k', alpha=a, label='Observed bed', lw=l) # ax[j,k].set_ylim(((df_agg.elev[df_agg.id_opt==i])-(df_agg[df_agg.id_opt==i].thick_opt)+5).max(), -5) ##plot optimized thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.H_opt/div), ls='-.', c='r', alpha=a, label='OGGM bed', lw=l) #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.farin_corr/div), ls='--', c='salmon', alpha=a, label='Farinotti et al. (2019) bed', lw=l) #marker='o') # ax[2,4].set_ylim(2.1, 2.22) if i <= 10: ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(100/div)) else: ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(200/div)) #ax[j,k].set_facecolor('0.92') ## make grey background for Illec. ax[j,k].text(0.04, 0.09, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') if i == 12 or i==13: ax[j,k].text(0.9, 0.9, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='center') else: ax[j,k].text(0.9, 0.09, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='center') n += 1; k += 1 if n == 15: j += 1; k = 0 ## kokanee gates elif n > 14 and n < 21: K=df_agg_Kok[df_agg_Kok.id==i-15].sort_values(by=['distance']) obs_H = df_agg_Kok.copy();obs_H = obs_H.dropna(subset=['gpr']) O=obs_H[obs_H.id==i-15].sort_values(by=['distance']) # plot glacier surface ax[j,k].tick_params(which='major', length=1.75) ax[j,k].plot(K.distance, (K.dem/div), color='#43a2ca', alpha=a, label='Ice surface',lw=l) #plot gpr thickness gates gpr=(O.dem/div)-(O.gpr/div) gpr_mask=np.isfinite(gpr) ax[j,k].plot(O.distance, gpr, marker='o', ms=1.0, ls='--', color='k', alpha=a, label='Obs. bed', lw=l) ##plot optimized thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.H_opt/div), ls='-.', c='r', alpha=a, label='OGGM bed',lw=l) #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.farin_corr/div), ls='--', c='salmon', alpha=a, label='FAR19 bed', lw=l) #marker='o') ax[j,k].yaxis.set_major_locator(ticker.MultipleLocator(100/div)) ## ax[3,0].set_ylim(2275/div, 2400/div);ax[3,2].set_ylim(2410/div, 2680/div);ax[3,4].set_ylim((2.59, 2.76)) # ax[3,3].set_xlim(1000, 1500);ax[3].set_ylim(2510/div, 2710/div) ax[4].set_ylim(2590/div, 2750/div) ax[j,k].text(0.9, 0.9, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') if i == 19: ax[j,k].text(0.04, 0.9, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left',) else: ax[j,k].text(0.04, 0.09, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') n += 1; k += 1 if n == 20: j += 1; k = 0 #nordic gates elif n > 20 and n < 27: K=df_agg_nord[df_agg_nord.id==i-21].sort_values(by=['distance']) obs_H = df_agg_nord.copy();obs_H = obs_H.dropna(subset=['gpr']) O=obs_H[obs_H.id==i-21].sort_values(by=['distance']) # plot glacier surface ax[j,k].tick_params(which='major', length=1.75) ax[j,k].plot(K.distance, (K.dem/div), color='#43a2ca', alpha=a, label='Ice surface',lw=l) #plot gpr thickness gates gpr=(O.dem/div)-(O.gpr/div) gpr_mask=np.isfinite(gpr) ax[j,k].plot(O.distance, gpr, marker='o', ms=1.0, ls='--', color='k', alpha=a, label='Obs. bed', lw=l) ##plot optimized thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.H_opt/div), ls='-.', c='r', alpha=a, label='OGGM bed',lw=l) #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.farin_corr/div), ls='--', c='salmon', alpha=a, label='FAR19 bed', lw=l) #marker='o') if n == 27: ax[j,k].text(0.9, 0.09, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') else: ax[j,k].text(0.9, 0.9, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') ax[j,k].text(0.04, 0.09, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') ax[4,1].yaxis.set_major_locator(ticker.MultipleLocator(200/div));ax[4,3].yaxis.set_major_locator(ticker.MultipleLocator(100/div)) ax[4,3].set_ylim((2.095, 2.22)); n += 1; k += 1 if n == 30: j += 1; k = 0 elif n > 29 and n < 36: K=df_agg_zill[df_agg_zill.id==i-30].sort_values(by=['distance']) obs_H = df_agg_zill.copy();obs_H = obs_H.dropna(subset=['gpr']) O=obs_H[obs_H.id==i-30].sort_values(by=['distance']) # plot glacier surface ax[j,k].tick_params(which='major', length=1.75) ax[j,k].plot(K.distance, (K.dem/div), color='#43a2ca', alpha=a, label='Ice surface',lw=l) #plot gpr thickness gates gpr=(O.dem/div)-(O.gpr/div) gpr_mask=np.isfinite(gpr) ax[j,k].plot(O.distance, gpr, marker='o', ms=1.0, ls='--', color='k', alpha=a, label='Obs. bed', lw=l) ##plot optimized thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.H_opt/div), ls='-.', c='r', alpha=a, label='OGGM bed',lw=l) #marker='o') ##plot Farinotti thickness gates ax[j,k].plot(K.distance, (K.dem/div)-(K.farin_corr/div), ls='--', c='salmon', alpha=a, label='FAR19 bed', lw=l) #marker='o') ax[j,k].text(0.95, 0.09, letter[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='right') ax[j,k].text(0.04, 0.09, gate[i], transform=ax[j,k].transAxes, verticalalignment='center', horizontalalignment='left') ax[5,0].set_ylim((1.97, 2.27));ax[5,1].set_ylim((2.03, 2.47)) n += 1; k += 1 ax[4,4].legend(bbox_to_anchor=(1.07, 0.99));ax[4,4].axis('off'); # plt.axhspan(0.75, i+.2, facecolor='0.2', alpha=0.5) fig.text(0.003, 0.6, 'Altitude (km a.s.l.)', rotation=90) fig.text(0.46, 0.009, 'Distance (m)') fig.subplots_adjust(bottom=0.054, top=0.98, left=0.055, right=0.99, wspace=0.26, hspace=0.19) plt.savefig(fl_path + 'products/' +'All_gates_all_glaciers_5_NEW.pdf', dpi=300) # - # # Ice velocity, flux gates quiver plot # + year=2017 vf_list = ['conrad_2016_vy_25m_pos.tif','conrad_2017_vy_25m_pos.tif','conrad_2018_vy_25m_pos_17mos.tif'] vdir = '/home/pelto/Desktop/velocity_mapping/Conrad_DEMs/spm2/3m/' ITS = fl_path + 'ITS_Live/' + str(year) + '_conrad_ITS_LIVE.tif' I = np.abs(year - 2016) ### for 2016/7 if I == 2: VX = vdir+ vf_list[I][:-20] + 'vx_25m.tif' VY = vdir+ vf_list[I] VM = vdir+ vf_list[I][:-20] + 'vm_25m.tif' else: VX = vdir+ vf_list[I][:-14] + 'vx_25m.tif' VY = vdir+ vf_list[I] VM = vdir+ vf_list[I][:-14] + 'vm_25m.tif' vy = salem.open_xr_dataset(VY);vy = vy.to_array(name='vy') vx = salem.open_xr_dataset(VX);vx = vx.to_array(name='vx') vz = vy vz.data = np.sqrt(vx.data**2 + vz.data**2 ) vz.data[vz.data<0.01]=np.nan; #vz.data[vz.data>50.0]=np.nan vz.data[msk_conrad.data!=1.0] = np.nan; font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1' pylab.rcParams['ytick.major.pad']='1' fig, ax = plt.subplots(1, figsize=cm2inch(8.5,10.)) topo_big = '/home/pelto/Desktop/lidar_cbt_analysis/conrad/dem_mosaic_conrad.tif' grid1 = mercator_grid(center_ll=(-116.92, 50.802), extent=(4700, 7400)) ##zoomed out view # 487892.000 5509738.000 491232.000 5512358.000 # grid1 = vx.salem.grid ##full view sm1 = Map(grid1, countries=False) sm1.set_lonlat_contours(interval=0) sm1.set_scale_bar(location=(0.13, 0.06),add_bbox=True,bbox_dy=1.5,linewidth=1.0) VZA=xr.DataArray(data=vz, coords=vz.coords, dims=vz.dims, name='VZA', attrs=vz.attrs) #,indexes=vx.indexes fastpath=False) # VZA.data=VZA.data*(msk+1.0) sm1.set_data(vz) sm1.set_cmap("Spectral_r") sm1.set_vmax(val=60.) shape = salem.read_shapefile('/home/pelto/Desktop/lidar_cbt_analysis/conrad/Conrad/conrad_16_extent.shp') # Change the lon-lat countour setting sm1.set_lonlat_contours(add_ytick_labels=True, interval=0.05, linewidths=0.75, linestyles='--', colors='0.25') sm1.set_topography(topo_big, relief_factor=0.8) sm1.set_shapefile(shape, lw=1.2, color='k') sm1.set_shapefile(gates, color='w', lw=1.1) obs_shp = '/home/pelto/Desktop/ice_flux/Flux_pts.csv' obs_pts = pd.read_csv(obs_shp) #salem.read_shapefile(obs_shp) x, y = sm1.grid.transform(obs_pts.lon.values, obs_pts.lat.values) ax.scatter(x, y, color='k', s=8, facecolor='w',zorder=3) sm1.append_colorbar(ax=ax, pad=0.1, label='Ice velocity (m yr$^{-1}$)')#, cbar_title='Ice Velocity (m yr$^-1$)') sm1.plot(ax=ax) u = D.vx.values;v = D.vy.values X, Y = np.meshgrid(D.lon,D.lat) # transform their coordinates to the map reference system and plot the arrows xx, yy = sm1.grid.transform(D.lon, D.lat, crs=salem.wgs84)#sm1.grid.proj # xx, yy = np.meshgrid(xx,yy) # qu = ax.quiver(xx, yy, u, v) ###### start:stop:step n=1 Q = ax.quiver(xx[::n], yy[::n], u[::n], v[::n], scale=600.) #, pivot='mid') qk = ax.quiverkey(Q, 0.07, 0.10, 50, r'$40 \frac{m}{a}$', labelpos='N', coordinates='figure', labelsep=0.025, zorder=1) fig.subplots_adjust(bottom=0.05, top=0.99, left=0.14, right=0.88) #, wspace=0.22, hspace=0.15 plt.savefig(fl_path+ 'products/conrad_vel_gates_quiver_'+str(year) +'_1.pdf', dpi=300) # - # # Firn coverage figure # + year=2017 vf_list = ['conrad_2016_vy_25m_pos.tif','conrad_2017_vy_25m_pos.tif','conrad_2018_vy_25m_pos_17mos.tif'] vdir = '/home/pelto/Desktop/velocity_mapping/Conrad_DEMs/spm2/3m/' ITS = fl_path + 'ITS_Live/' + str(year) + '_conrad_ITS_LIVE.tif' I = np.abs(year - 2016) ### for 2016/7 if I == 2: VX = vdir+ vf_list[I][:-20] + 'vx_25m.tif' VY = vdir+ vf_list[I] VM = vdir+ vf_list[I][:-20] + 'vm_25m.tif' else: VX = vdir+ vf_list[I][:-14] + 'vx_25m.tif' VY = vdir+ vf_list[I] VM = vdir+ vf_list[I][:-14] + 'vm_25m.tif' vy = salem.open_xr_dataset(VY);vy = vy.to_array(name='vy') vx = salem.open_xr_dataset(VX);vx = vx.to_array(name='vx') vz = vy vz.data = np.sqrt(vx.data**2 + vz.data**2 ) vz.data[vz.data<0.01]=np.nan; #vz.data[vz.data>50.0]=np.nan vz.data[msk_conrad.data!=1.0] = np.nan; firn = '/home/pelto/Desktop/ice_flux/Conrad/AAR_conrad_2012_2018.tif' firn =salem.open_xr_dataset(firn); firn_reproj = vx.salem.transform(firn);firn = firn_reproj.to_array(name='firn') firn.data[msk_conrad.data!=1.0] = np.nan; font = {'family' : 'Helvetica', 'weight' : 'normal', 'size' : 8} plt.rc('font', **font) pylab.rcParams['xtick.major.pad']='1';pylab.rcParams['ytick.major.pad']='1' fig, ax = plt.subplots(1, figsize=cm2inch(8.5,10.)) topo_big = '/home/pelto/Desktop/lidar_cbt_analysis/conrad/dem_mosaic_conrad.tif' grid1 = mercator_grid(center_ll=(-116.92, 50.802), extent=(4700, 7400)) ##zoomed out view # 487892.000 5509738.000 491232.000 5512358.000 # grid1 = vx.salem.grid ##full view sm1 = Map(grid1, countries=False) sm1.set_lonlat_contours(interval=0) sm1.set_scale_bar(location=(0.13, 0.06),add_bbox=True,bbox_dy=1.5,linewidth=1.0) # VZA.data=VZA.data*(msk+1.0) sm1.set_data(firn) sm1.set_cmap("Blues") # sm1.set_vmax(val=60.) shape = salem.read_shapefile('/home/pelto/Desktop/lidar_cbt_analysis/conrad/Conrad/conrad_16_extent.shp') # Change the lon-lat countour setting sm1.set_lonlat_contours(add_ytick_labels=True, interval=0.05, linewidths=0.75, linestyles='--', colors='0.25') sm1.set_topography(topo_big, relief_factor=0.8) sm1.set_shapefile(shape, lw=1.2, color='k') sm1.set_shapefile(gates, color='w', lw=1.1) obs_shp = '/home/pelto/Desktop/ice_flux/Flux_pts.csv' obs_pts = pd.read_csv(obs_shp) #salem.read_shapefile(obs_shp) x, y = sm1.grid.transform(obs_pts.lon.values, obs_pts.lat.values) ax.scatter(x, y, color='k', s=8, facecolor='w',zorder=3) sm1.append_colorbar(ax=ax, pad=0.1, label='Firn cover (years)')#, cbar_title='Ice Velocity (m yr$^-1$)') sm1.plot(ax=ax) fig.subplots_adjust(bottom=0.05, top=0.99, left=0.14, right=0.88) #, wspace=0.22, hspace=0.15 plt.savefig(fl_path+ 'products/conrad_firn_map.pdf', dpi=300) # -
flux_gate-Conrad.ipynb
# Transformers installation # ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # # ! pip install git+https://github.com/huggingface/transformers.git # # Fine-tune a pretrained model # There are significant benefits to using a pretrained model. It reduces computation costs, your carbon footprint, and allows you to use state-of-the-art models without having to train one from scratch. 🤗 Transformers provides access to thousands of pretrained models for a wide range of tasks. When you use a pretrained model, you train it on a dataset specific to your task. This is known as fine-tuning, an incredibly powerful training technique. In this tutorial, you will fine-tune a pretrained model with a deep learning framework of your choice: # # * Fine-tune a pretrained model with 🤗 Transformers [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer). # * Fine-tune a pretrained model in TensorFlow with Keras. # * Fine-tune a pretrained model in native PyTorch. # # <a id='data-processing'></a> # ## Prepare a dataset # + cellView="form" hide_input=true #@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/_BZearw7f0w?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>') # - # Before you can fine-tune a pretrained model, download a dataset and prepare it for training. The previous tutorial showed you how to process data for training, and now you get an opportunity to put those skills to the test! # # Begin by loading the [Yelp Reviews](https://huggingface.co/datasets/yelp_review_full) dataset: # + from datasets import load_dataset dataset = load_dataset("yelp_review_full") dataset[100] # - # As you now know, you need a tokenizer to process the text and include a padding and truncation strategy to handle any variable sequence lengths. To process your dataset in one step, use 🤗 Datasets [`map`](https://huggingface.co/docs/datasets/process.html#map) method to apply a preprocessing function over the entire dataset: # + from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") def tokenize_function(examples): return tokenizer(examples["text"], padding="max_length", truncation=True) tokenized_datasets = dataset.map(tokenize_function, batched=True) # - # If you like, you can create a smaller subset of the full dataset to fine-tune on to reduce the time it takes: small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) # <a id='trainer'></a> # ## Fine-tune with `Trainer` # + cellView="form" hide_input=true #@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/nvBXf7s7vTI?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>') # - # 🤗 Transformers provides a [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) class optimized for training 🤗 Transformers models, making it easier to start training without manually writing your own training loop. The [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) API supports a wide range of training options and features such as logging, gradient accumulation, and mixed precision. # # Start by loading your model and specify the number of expected labels. From the Yelp Review [dataset card](https://huggingface.co/datasets/yelp_review_full#data-fields), you know there are five labels: # + from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5) # - # <Tip> # # You will see a warning about some of the pretrained weights not being used and some weights being randomly # initialized. Don't worry, this is completely normal! The pretrained head of the BERT model is discarded, and replaced with a randomly initialized classification head. You will fine-tune this new model head on your sequence classification task, transferring the knowledge of the pretrained model to it. # # </Tip> # ### Training hyperparameters # Next, create a [TrainingArguments](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.TrainingArguments) class which contains all the hyperparameters you can tune as well as flags for activating different training options. For this tutorial you can start with the default training [hyperparameters](https://huggingface.co/docs/transformers/main_classes/trainer#transformers.TrainingArguments), but feel free to experiment with these to find your optimal settings. # # Specify where to save the checkpoints from your training: # + from transformers import TrainingArguments training_args = TrainingArguments(output_dir="test_trainer") # - # ### Metrics # [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) does not automatically evaluate model performance during training. You will need to pass [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) a function to compute and report metrics. The 🤗 Datasets library provides a simple [`accuracy`](https://huggingface.co/metrics/accuracy) function you can load with the `load_metric` (see this [tutorial](https://huggingface.co/docs/datasets/metrics.html) for more information) function: # + import numpy as np from datasets import load_metric metric = load_metric("accuracy") # - # Call `compute` on `metric` to calculate the accuracy of your predictions. Before passing your predictions to `compute`, you need to convert the predictions to logits (remember all 🤗 Transformers models return logits): def compute_metrics(eval_pred): logits, labels = eval_pred predictions = np.argmax(logits, axis=-1) return metric.compute(predictions=predictions, references=labels) # If you'd like to monitor your evaluation metrics during fine-tuning, specify the `evaluation_strategy` parameter in your training arguments to report the evaluation metric at the end of each epoch: # + from transformers import TrainingArguments training_args = TrainingArguments(output_dir="test_trainer", evaluation_strategy="epoch") # - # ### Trainer # Create a [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) object with your model, training arguments, training and test datasets, and evaluation function: trainer = Trainer( model=model, args=training_args, train_dataset=small_train_dataset, eval_dataset=small_eval_dataset, compute_metrics=compute_metrics, ) # Then fine-tune your model by calling [train()](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer.train): trainer.train() # <a id='keras'></a> # ## Fine-tune with Keras # + cellView="form" hide_input=true #@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/rnTGBy2ax1c?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>') # - # 🤗 Transformers models also supports training in TensorFlow with the Keras API. You only need to make a few changes before you can fine-tune. # ### Convert dataset to TensorFlow format # The [DefaultDataCollator](https://huggingface.co/docs/transformers/master/en/main_classes/data_collator#transformers.DefaultDataCollator) assembles tensors into a batch for the model to train on. Make sure you specify `return_tensors` to return TensorFlow tensors: # + from transformers import DefaultDataCollator data_collator = DefaultDataCollator(return_tensors="tf") # - # <Tip> # # [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) uses [DataCollatorWithPadding](https://huggingface.co/docs/transformers/master/en/main_classes/data_collator#transformers.DataCollatorWithPadding) by default so you don't need to explicitly specify a data collator. # # </Tip> # # Next, convert the tokenized datasets to TensorFlow datasets with the [`to_tf_dataset`](https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.to_tf_dataset) method. Specify your inputs in `columns`, and your label in `label_cols`: # + tf_train_dataset = small_train_dataset.to_tf_dataset( columns=["attention_mask", "input_ids", "token_type_ids"], label_cols=["labels"], shuffle=True, collate_fn=data_collator, batch_size=8, ) tf_validation_dataset = small_eval_dataset.to_tf_dataset( columns=["attention_mask", "input_ids", "token_type_ids"], label_cols=["labels"], shuffle=False, collate_fn=data_collator, batch_size=8, ) # - # ### Compile and fit # Load a TensorFlow model with the expected number of labels: # + import tensorflow as tf from transformers import TFAutoModelForSequenceClassification model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5) # - # Then compile and fine-tune your model with [`fit`](https://keras.io/api/models/model_training_apis/) as you would with any other Keras model: # + model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=tf.metrics.SparseCategoricalAccuracy(), ) model.fit(tf_train_dataset, validation_data=tf_validation_dataset, epochs=3) # - # <a id='pytorch_native'></a> # ## Fine-tune in native PyTorch # + cellView="form" hide_input=true #@title from IPython.display import HTML HTML('<iframe width="560" height="315" src="https://www.youtube.com/embed/Dh9CL8fyG80?rel=0&amp;controls=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>') # - # [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer) takes care of the training loop and allows you to fine-tune a model in a single line of code. For users who prefer to write their own training loop, you can also fine-tune a 🤗 Transformers model in native PyTorch. # # At this point, you may need to restart your notebook or execute the following code to free some memory: del model del pytorch_model del trainer torch.cuda.empty_cache() # Next, manually postprocess `tokenized_dataset` to prepare it for training. # # 1. Remove the `text` column because the model does not accept raw text as an input: # # ```py # >>> tokenized_datasets = tokenized_datasets.remove_columns(["text"]) # ``` # # 2. Rename the `label` column to `labels` because the model expects the argument to be named `labels`: # # ```py # >>> tokenized_datasets = tokenized_datasets.rename_column("label", "labels") # ``` # # 3. Set the format of the dataset to return PyTorch tensors instead of lists: # # ```py # >>> tokenized_datasets.set_format("torch") # ``` # # Then create a smaller subset of the dataset as previously shown to speed up the fine-tuning: small_train_dataset = tokenized_datasets["train"].shuffle(seed=42).select(range(1000)) small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42).select(range(1000)) # ### DataLoader # Create a `DataLoader` for your training and test datasets so you can iterate over batches of data: # + from torch.utils.data import DataLoader train_dataloader = DataLoader(small_train_dataset, shuffle=True, batch_size=8) eval_dataloader = DataLoader(small_eval_dataset, batch_size=8) # - # Load your model with the number of expected labels: # + from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=5) # - # ### Optimizer and learning rate scheduler # Create an optimizer and learning rate scheduler to fine-tune the model. Let's use the [`AdamW`](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) optimizer from PyTorch: # + from torch.optim import AdamW optimizer = AdamW(model.parameters(), lr=5e-5) # - # Create the default learning rate scheduler from [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer): # + from transformers import get_scheduler num_epochs = 3 num_training_steps = num_epochs * len(train_dataloader) lr_scheduler = get_scheduler( name="linear", optimizer=optimizer, num_warmup_steps=0, num_training_steps=num_training_steps ) # - # Lastly, specify `device` to use a GPU if you have access to one. Otherwise, training on a CPU may take several hours instead of a couple of minutes. # + import torch device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu") model.to(device) # - # <Tip> # # Get free access to a cloud GPU if you don't have one with a hosted notebook like [Colaboratory](https://colab.research.google.com/) or [SageMaker StudioLab](https://studiolab.sagemaker.aws/). # # </Tip> # # Great, now you are ready to train! 🥳 # ### Training loop # To keep track of your training progress, use the [tqdm](https://tqdm.github.io/) library to add a progress bar over the number of training steps: # + from tqdm.auto import tqdm progress_bar = tqdm(range(num_training_steps)) model.train() for epoch in range(num_epochs): for batch in train_dataloader: batch = {k: v.to(device) for k, v in batch.items()} outputs = model(**batch) loss = outputs.loss loss.backward() optimizer.step() lr_scheduler.step() optimizer.zero_grad() progress_bar.update(1) # - # ### Metrics # Just like how you need to add an evaluation function to [Trainer](https://huggingface.co/docs/transformers/master/en/main_classes/trainer#transformers.Trainer), you need to do the same when you write your own training loop. But instead of calculating and reporting the metric at the end of each epoch, this time you will accumulate all the batches with [`add_batch`](https://huggingface.co/docs/datasets/package_reference/main_classes.html?highlight=add_batch#datasets.Metric.add_batch) and calculate the metric at the very end. # + metric = load_metric("accuracy") model.eval() for batch in eval_dataloader: batch = {k: v.to(device) for k, v in batch.items()} with torch.no_grad(): outputs = model(**batch) logits = outputs.logits predictions = torch.argmax(logits, dim=-1) metric.add_batch(predictions=predictions, references=batch["labels"]) metric.compute() # - # <a id='additional-resources'></a> # ## Additional resources # For more fine-tuning examples, refer to: # # - [🤗 Transformers Examples](https://github.com/huggingface/transformers/tree/master/examples) includes scripts # to train common NLP tasks in PyTorch and TensorFlow. # # - [🤗 Transformers Notebooks](https://huggingface.co/docs/transformers/master/en/notebooks) contains various notebooks on how to fine-tune a model for specific tasks in PyTorch and TensorFlow.
transformers_doc/training.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 # --- # How many mergers are excluded due to merger overlap? # # # There are 628 / 1584 mergers finally left. # + import utils.sampling as smp import matplotlib.pyplot as plt import tree import pickle import tree.halomodule as hmo import numpy as np from analysis.misc import load_cat import scipy.stats import tree.ctutils as ctu from analysis.evol_lambda import MainPrg import draw import load import analysis.evol_lambda as evl import analysis.Major_Minor_accretion as mma import analysis.misc as amsc import tree.ctutils as ctu import utils.match as mtc # Read a single galaxy evolution catalog. from analysis.MajorMinorAccretion_module import * from analysis.all_plot_modules import * verbose=True # In[4]: base = './' cdir = ['catalog/', 'HM/', 'catalog_GM/', "easy_final/"][3] clusters = ['01605', '07206', \ '35663', '24954', '49096', \ '05427', '05420', '29172', \ '29176', '10002', '36415', \ '06098', '39990', '36413', \ '17891', '04466'] # parameters used for lambda_arr clipping. #ind_upper = 20 #ind_lower = 20 #sig_upper = 2.0 #sig_lower = 2.0 # 62: z = 1.666 nout_fi = 187 minimum_good_snap = 87 wdir = '/home/hoseung/Work/data/' mpgs = pickle.load(open(wdir + "all_prgs/main_prgs_5_10_0.5_0.5_0.5_37_0.01_before_filter.pickle", "rb")) mc_M = 0 mc_m = 0 for gg in mpgs: if hasattr(gg, "merger"): if gg.merger is not None: mc_M += sum((gg.merger.nout_ini >= 37) * (gg.merger.mr < 4)) mc_m += sum((gg.merger.nout_ini >= 37) * (gg.merger.mr >= 4)) print(" # Major / minor mergers originally", mc_M, mc_m)
scripts/scripts_ipynb/revision_N_overlap_mergers.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="view-in-github" # <a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D3_ModelFitting/student/W1D3_Tutorial4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] colab_type="text" # # Neuromatch Academy: Week 1, Day 3, Tutorial 4 # # Model Fitting: Multiple linear regression and polynomial regression # # **Content creators**: <NAME>, <NAME>, <NAME> with help from <NAME>, <NAME> # # **Content reviewers**: <NAME>, <NAME>, <NAME>, <NAME> # + [markdown] colab_type="text" # --- # #Tutorial Objectives # # This is Tutorial 4 of a series on fitting models to data. We start with simple linear regression, using least squares optimization (Tutorial 1) and Maximum Likelihood Estimation (Tutorial 2). We will use bootstrapping to build confidence intervals around the inferred linear model parameters (Tutorial 3). We'll finish our exploration of regression models by generalizing to multiple linear regression and polynomial regression (Tutorial 4). We end by learning how to choose between these various models. We discuss the bias-variance trade-off (Tutorial 5) and Cross Validation for model selection (Tutorial 6). # # In this tutorial, we will generalize the regression model to incorporate multiple features. # - Learn how to structure inputs for regression using the 'Design Matrix' # - Generalize the MSE for multiple features using the ordinary least squares estimator # - Visualize data and model fit in multiple dimensions # - Fit polynomial regression models of different complexity # - Plot and evaluate the polynomial regression fits # # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 517} colab_type="code" outputId="734d53cd-8d17-4ed6-f84c-3ce333d47491" #@title Video 1: Multiple Linear Regression and Polynomial Regression from IPython.display import YouTubeVideo video = YouTubeVideo(id="d4nfTki6Ejc", width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video # + [markdown] colab_type="text" # --- # # Setup # + cellView="both" colab={} colab_type="code" import numpy as np import matplotlib.pyplot as plt # + cellView="form" colab={} colab_type="code" #@title Figure Settings # %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") # + cellView="form" colab={} colab_type="code" #@title Helper Functions def plot_fitted_polynomials(x, y, theta_hat): """ Plot polynomials of different orders Args: x (ndarray): input vector of shape (n_samples) y (ndarray): vector of measurements of shape (n_samples) theta_hat (dict): polynomial regression weights for different orders """ x_grid = np.linspace(x.min() - .5, x.max() + .5) plt.figure() for order in range(0, max_order + 1): X_design = make_design_matrix(x_grid, order) plt.plot(x_grid, X_design @ theta_hat[order]); plt.ylabel('y') plt.xlabel('x') plt.plot(x, y, 'C0.'); plt.legend([f'order {o}' for o in range(max_order + 1)], loc=1) plt.title('polynomial fits') plt.show() # + [markdown] colab_type="text" # --- # # Section 1: Multiple Linear Regression # # + [markdown] colab_type="text" # Now that we have considered the univariate case and how to produce confidence intervals for our estimator, we turn to the general linear regression case, where we can have more than one regressor, or feature, in our input. # # Recall that our original univariate linear model was given as # # \begin{align} # y = \theta x + \epsilon # \end{align} # # where $\theta$ is the slope and $\epsilon$ some noise. We can easily extend this to the multivariate scenario by adding another parameter for each additional feature # # \begin{align} # y = \theta_0 + \theta_1 x_1 + \theta_1 x_2 + ... +\theta_d x_d + \epsilon # \end{align} # # where $\theta_0$ is the intercept and $d$ is the number of features (it is also the dimensionality of our input). # # We can condense this succinctly using vector notation for a single data point # # \begin{align} # y_i = \boldsymbol{\theta}^{\top}\mathbf{x}_i + \epsilon # \end{align} # # and fully in matrix form # # \begin{align} # \mathbf{y} = \mathbf{X}\boldsymbol{\theta} + \mathbf{\epsilon} # \end{align} # # where $\mathbf{y}$ is a vector of measurements, $\mathbf{X}$ is a matrix containing the feature values (columns) for each input sample (rows), and $\boldsymbol{\theta}$ is our parameter vector. # # This matrix $\mathbf{X}$ is often referred to as the "[design matrix](https://en.wikipedia.org/wiki/Design_matrix)". # + [markdown] colab_type="text" # For this tutorial we will focus on the two-dimensional case ($d=2$), which allows us to easily visualize our results. As an example, think of a situation where a scientist records the spiking response of a retinal ganglion cell to patterns of light signals that vary in contrast and in orientation. Then contrast and orientation values can be used as features / regressors to predict the cells response. # # In this case our model can be writen as: # # \begin{align} # y = \theta_0 + \theta_1 x_1 + \theta_2 x_2 + \epsilon # \end{align} # # or in matrix form where # # \begin{align} # \mathbf{X} = # \begin{bmatrix} # 1 & x_{1,1} & x_{1,2} \\ # 1 & x_{2,1} & x_{2,2} \\ # \vdots & \vdots & \vdots \\ # 1 & x_{n,1} & x_{n,2} # \end{bmatrix}, # \boldsymbol{\theta} = # \begin{bmatrix} # \theta_0 \\ # \theta_1 \\ # \theta_2 \\ # \end{bmatrix} # \end{align} # # For our actual exploration dataset we shall set $\boldsymbol{\theta}=[0, -2, -3]$ and draw $N=40$ noisy samples from $x \in [-2,2)$. Note that setting the value of $\theta_0 = 0$ effectively ignores the offset term. # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="code" outputId="4c8c9f8a-3a63-4517-ca62-62225b8955ff" #@title #@markdown Execute this cell to simulate some data # Set random seed for reproducibility np.random.seed(1234) # Set parameters theta = [0, -2, -3] n_samples = 40 # Draw x and calculate y n_regressors = len(theta) x0 = np.ones((n_samples, 1)) x1 = np.random.uniform(-2, 2, (n_samples, 1)) x2 = np.random.uniform(-2, 2, (n_samples, 1)) X = np.hstack((x0, x1, x2)) noise = np.random.randn(n_samples) y = X @ theta + noise ax = plt.subplot(projection='3d') ax.plot(X[:,1], X[:,2], y, '.') ax.set( xlabel='$x_1$', ylabel='$x_2$', zlabel='y' ) plt.tight_layout() # + [markdown] colab_type="text" # Now that we have our dataset, we want to find an optimal vector of paramters $\boldsymbol{\hat\theta}$. Recall our analytic solution to minimizing MSE for a single regressor: # # \begin{align} # \hat\theta = \frac{\sum_{i=1}^N x_i y_i}{\sum_{i=1}^N x_i^2}. # \end{align} # # The same holds true for the multiple regressor case, only now expressed in matrix form # # \begin{align} # \boldsymbol{\hat\theta} = (\mathbf{X}^\top\mathbf{X})^{-1}\mathbf{X}^\top\mathbf{y}. # \end{align} # # This is called the [ordinary least squares](https://en.wikipedia.org/wiki/Ordinary_least_squares) (OLS) estimator. # + [markdown] colab_type="text" # ### Exercise 1: Ordinary Least Squares Estimator # # In this exercise you will implement the OLS approach to estimating $\boldsymbol{\hat\theta}$ from the design matrix $\mathbf{X}$ and measurement vector $\mathbf{y}$. You can use the `@` symbol for matrix multiplication, `.T` for transpose, and `np.linalg.inv` for matrix inversion. # # + colab={} colab_type="code" def ordinary_least_squares(X, y): """Ordinary least squares estimator for linear regression. Args: x (ndarray): design matrix of shape (n_samples, n_regressors) y (ndarray): vector of measurements of shape (n_samples) Returns: ndarray: estimated parameter values of shape (n_regressors) """ ###################################################################### ## TODO for students: solve for the optimal parameter vector using OLS # Fill out function and remove raise NotImplementedError("Student exercise: solve for theta_hat vector using OLS") ###################################################################### # Compute theta_hat using OLS theta_hat = ... return theta_hat # Uncomment below to test your function # theta_hat = ordinary_least_squares(X, y) # print(theta_hat) # + [markdown] cellView="both" colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="text" outputId="615e4006-d167-487b-964e-4ee6df25b2f2" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial4_Solution_2b5abc38.py) # # # + [markdown] colab_type="text" # After filling in this function, you should see that $\hat{\theta}$ = [ 0.13861386, -2.09395731, -3.16370742] # + [markdown] colab_type="text" # Now that we have our $\mathbf{\hat\theta}$, we can obtain $\mathbf{\hat y}$ and thus our mean squared error. # + colab={"base_uri": "https://localhost:8080/", "height": 34} colab_type="code" outputId="d69d05e8-7263-4e68-ea38-aadc773ac052" # Compute predicted data theta_hat = ordinary_least_squares(X, y) y_hat = X @ theta_hat # Compute MSE print(f"MSE = {np.mean((y - y_hat)**2):.2f}") # + [markdown] colab_type="text" # Finally, the following code will plot a geometric visualization of the data points (blue) and fitted plane. You can see that the residuals (green bars) are orthogonal to the plane. # # Extra: how would you check that the residuals are orthogonal to the fitted plane? (this is sometimes called the orthogonality principle, see [least squares notes](https://www.cns.nyu.edu/~eero/NOTES/leastSquares.pdf)) # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="code" outputId="1781187f-c89d-488a-f333-63583152d733" #@title #@markdown Execute this cell to visualize data and predicted plane theta_hat = ordinary_least_squares(X, y) xx, yy = np.mgrid[-2:2:50j, -2:2:50j] y_hat_grid = np.array([xx.flatten(), yy.flatten()]).T @ theta_hat[1:] y_hat_grid = y_hat_grid.reshape((50, 50)) ax = plt.subplot(projection='3d') ax.plot(X[:, 1], X[:, 2], y, '.') ax.plot_surface(xx, yy, y_hat_grid, linewidth=0, alpha=0.5, color='C1', cmap=plt.get_cmap('coolwarm')) for i in range(len(X)): ax.plot((X[i, 1], X[i, 1]), (X[i, 2], X[i, 2]), (y[i], y_hat[i]), 'g-', alpha=.5) ax.set( xlabel='$x_1$', ylabel='$x_2$', zlabel='y' ) plt.tight_layout() # + [markdown] colab_type="text" # --- # # Section 2: Polynomial Regression # + [markdown] colab_type="text" # So far today, you learned how to predict outputs from inputs by fitting a linear regression model. We can now model all sort of relationships, including in neuroscience! # # One potential problem with this approach is the simplicity of the model. Linear regression, as the name implies, can only capture a linear relationship between the inputs and outputs. Put another way, the predicted outputs are only a weighted sum of the inputs. What if there are more complicated computations happening? Luckily, many more complex models exist (and you will encounter many more over the next 3 weeks). One model that is still very simple to fit and understand, but captures more complex relationships, is **polynomial regression**, an extension of linear regression. # # Since polynomial regression is an extension of linear regression, everything you learned so far will come in handy now! The goal is the same: we want to predict the dependent variable $y_{n}$ given the input values $x_{n}$. The key change is the type of relationship between inputs and outputs that the model can capture. # # Linear regression models predict the outputs as a weighted sum of the inputs: # # $$y_{n}= \theta_0 + \theta x_{n} + \epsilon_{n}$$ # # With polynomial regression, we model the outputs as a polynomial equation based on the inputs. For example, we can model the outputs as: # # $$y_{n}= \theta_0 + \theta_1 x_{n} + \theta_2 x_{n}^2 + \theta_3 x_{n}^3 + \epsilon_{n}$$ # # We can change how complex a polynomial is fit by changing the order of the polynomial. The order of a polynomial refers to the highest power in the polynomial. The equation above is a third order polynomial because the highest value x is raised to is 3. We could add another term ($+ \theta_4 x_{n}^4$) to model an order 4 polynomial and so on. # # # + [markdown] colab_type="text" # First, we will simulate some data to practice fitting polynomial regression models. We will generate random inputs $x$ and then compute y according to $y = x^2 - x - 2 $, with some extra noise both in the input and the output to make the model fitting exercise closer to a real life situation. # + cellView="form" colab={"base_uri": "https://localhost:8080/", "height": 431} colab_type="code" outputId="d6179fe7-a3cd-4691-8e9a-0747b591f86b" #@title #@markdown Execute this cell to simulate some data # setting a fixed seed to our random number generator ensures we will always # get the same psuedorandom number sequence np.random.seed(121) n_samples = 30 x = np.random.uniform(-2, 2.5, n_samples) # inputs uniformly sampled from [-2, 2.5) y = x**2 - x - 2 # computing the outputs output_noise = 1/8 * np.random.randn(n_samples) y += output_noise # adding some output noise input_noise = 1/2 * np.random.randn(n_samples) x += input_noise # adding some input noise fig, ax = plt.subplots() ax.scatter(x, y) # produces a scatter plot ax.set(xlabel='x', ylabel='y'); # + [markdown] colab_type="text" # ## Section 2.1: Design matrix for polynomial regression # # Now we have the basic idea of polynomial regression and some noisy data, let's begin! The key difference between fitting a linear regression model and a polynomial regression model lies in how we structure the input variables. # # For linear regression, we used $X = x$ as the input data. To add a constant bias (a y-intercept in a 2-D plot), we use $X = \big[ \boldsymbol 1, x \big]$, where $\boldsymbol 1$ is a column of ones. When fitting, we learn a weight for each column of this matrix. So we learn a weight that multiples with column 1 - in this case that column is all ones so we gain the bias parameter ($+ \theta_0$). We also learn a weight for every column, or every feature of x, as we learned in Section 1. # # This matrix $X$ that we use for our inputs is known as a **design matrix**. We want to create our design matrix so we learn weights for $x^2, x^3,$ etc. Thus, we want to build our design matrix $X$ for polynomial regression of order $k$ as: # # $$X = \big[ \boldsymbol 1 , x^1, x^2 , \ldots , x^k \big],$$ # # where $\boldsymbol{1}$ is the vector the same length as $x$ consisting of of all ones, and $x^p$ is the vector or matrix $x$ with all elements raised to the power $p$. Note that $\boldsymbol{1} = x^0$ and $x^1 = x$ # + [markdown] colab_type="text" # ### Exercise 2: Structure design matrix # # Create a function (`make_design_matrix`) that structures the design matrix given the input data and the order of the polynomial you wish to fit. We will print part of this design matrix for our data and order 5. # + colab={} colab_type="code" def make_design_matrix(x, order): """Create the design matrix of inputs for use in polynomial regression Args: x (ndarray): input vector of shape (n_samples) order (scalar): polynomial regression order Returns: ndarray: design matrix for polynomial regression of shape (samples, order+1) """ ######################################################################## ## TODO for students: create the design matrix ## # Fill out function and remove raise NotImplementedError("Student exercise: create the design matrix") ######################################################################## # Broadcast to shape (n x 1) so dimensions work if x.ndim == 1: x = x[:, None] #if x has more than one feature, we don't want multiple columns of ones so we assign # x^0 here design_matrix = np.ones((x.shape[0], 1)) # Loop through rest of degrees and stack columns (hint: np.hstack) for degree in range(1, order + 1): design_matrix = ... return design_matrix # Uncomment to test your function order = 5 # X_design = make_design_matrix(x, order) # print(X_design[0:2, 0:2]) # + [markdown] cellView="both" colab={"base_uri": "https://localhost:8080/", "height": 52} colab_type="text" outputId="26d7cc21-1ca2-4050-9817-67d3f3ce3895" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial4_Solution_f8576b48.py) # # # + [markdown] colab_type="text" # You should see that the printed section of this design matrix is `[[ 1. -1.51194917] # [ 1. -0.35259945]]` # + [markdown] colab_type="text" # ## Section 2.2: Fitting polynomial regression models # + [markdown] colab_type="text" # Now that we have the inputs structured correctly in our design matrix, fitting a polynomial regression is the same as fitting a linear regression model! All of the polynomial structure we need to learn is contained in how the inputs are structured in the design matrix. We can use the same least squares solution we computed in previous exercises. # + [markdown] colab_type="text" # ### Exercise 3: Fitting polynomial regression models with different orders # + [markdown] colab_type="text" # Here, we will fit polynomial regression models to find the regression coefficients ($\theta_0, \theta_1, \theta_2,$ ...) by solving the least squares problem. Create a function `solve_poly_reg` that loops over different order polynomials (up to `max_order`), fits that model, and saves out the weights for each. You may invoke the `ordinary_least_squares` function. # # We will then qualitatively inspect the quality of our fits for each order by plotting the fitted polynomials on top of the data. In order to see smooth curves, we evaluate the fitted polynomials on a grid of $x$ values (ranging between the largest and smallest of the inputs present in the dataset). # + colab={} colab_type="code" def solve_poly_reg(x, y, max_order): """Fit a polynomial regression model for each order 0 through max_order. Args: x (ndarray): input vector of shape (n_samples) y (ndarray): vector of measurements of shape (n_samples) max_order (scalar): max order for polynomial fits Returns: dict: fitted weights for each polynomial model (dict key is order) """ # Create a dictionary with polynomial order as keys, # and np array of theta_hat (weights) as the values theta_hats = {} # Loop over polynomial orders from 0 through max_order for order in range(max_order + 1): ################################################################################## ## TODO for students: Create design matrix and fit polynomial model for this order # Fill out function and remove raise NotImplementedError("Student exercise: fit a polynomial model") ################################################################################## # Create design matrix X_design = ... # Fit polynomial model this_theta = ... theta_hats[order] = this_theta return theta_hats # Uncomment to test your function max_order = 5 # theta_hats = solve_poly_reg(x, y, max_order) # plot_fitted_polynomials(x, y, theta_hats) # + [markdown] cellView="both" colab={"base_uri": "https://localhost:8080/", "height": 433} colab_type="text" outputId="87845605-a4f8-4648-8812-c12597d6c270" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial4_Solution_9b1eebd9.py) # # *Example output:* # # <img alt='Solution hint' align='left' width=560 height=416 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D3_ModelFitting/static/W1D3_Tutorial4_Solution_9b1eebd9_0.png> # # # + [markdown] colab_type="text" # ## Section 2.4: Evaluating fit quality # # As with linear regression, we can compute mean squared error (MSE) to get a sense of how well the model fits the data. # # We compute MSE as: # # $$ MSE = \frac 1 N ||y - \hat y||^2 = \sum_{i=1}^N (y_i - \hat y_i)^2 $$ # # where the predicted values for each model are given by $ \hat y = X \hat \theta$. # # *Which model (i.e. which polynomial order) do you think will have the best MSE?* # + [markdown] colab_type="text" # ### Exercise 4: Compute MSE and compare models # # We will compare the MSE for different polynomial orders with a bar plot. # + colab={"base_uri": "https://localhost:8080/", "height": 483} colab_type="code" outputId="ccd168b3-9f71-4e55-919d-c19ed9173e3f" mse_list = [] order_list = list(range(max_order + 1)) for order in order_list: X_design = make_design_matrix(x, order) ############################################################################ # TODO for students: Compute MSE (fill in ... sections) ############################################################################# # Get prediction for the polynomial regression model of this order y_hat = ... # Compute the residuals residuals = ... # Compute the MSE mse = ... mse_list.append(mse) fig, ax = plt.subplots() # Uncomment once above exercise is complete # ax.bar(order_list, mse_list) ax.set(title='Comparing Polynomial Fits', xlabel='Polynomial order', ylabel='MSE') # + [markdown] cellView="both" colab={"base_uri": "https://localhost:8080/", "height": 430} colab_type="text" outputId="3095d670-d022-4220-f726-7adccff2e250" # [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D3_ModelFitting/solutions/W1D3_Tutorial4_Solution_ccea5dd7.py) # # *Example output:* # # <img alt='Solution hint' align='left' width=558 height=414 src=https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/tutorials/W1D3_ModelFitting/static/W1D3_Tutorial4_Solution_ccea5dd7_0.png> # # # + [markdown] colab_type="text" # --- # # Summary # # * Linear regression generalizes naturally to multiple dimensions # * Linear algebra affords us the mathematical tools to reason and solve such problems beyond the two dimensional case # # * To change from a linear regression model to a polynomial regression model, we only have to change how the input data is structured # # * We can choose the complexity of the model by changing the order of the polynomial model fit # # * Higher order polynomial models tend to have lower MSE on the data they're fit with # # **Note**: In practice, multidimensional least squares problems can be solved very efficiently (thanks to numerical routines such as LAPACK). # # # + [markdown] colab_type="text" # **Suggested readings** # # [Introduction to Applied Linear Algebra – Vectors, Matrices, and Least Squares](http://vmls-book.stanford.edu/) # <NAME> and <NAME>
tutorials/W1D3_ModelFitting/student/W1D3_Tutorial4.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 Dataquest Project # =================== # # ## Learning how to use a Jupyter Notebook # # *The content below was a meta-exercise from the 'Python Fundamentals' course on how to work with Jupyter Notebooks.* # ### Loading Data # # The cell below illustrates how to load data from a csv file into python: # # 1. Point the open() function to the path of your file, which returns a file object # 2. Import the reader() function from the 'csv' library # 3. Feed the file object into the reader() function, which returns a reader object that iterates through lines of the csv # 4. Feed the reader object into a list, which makes a list of lists, each corresponding to a row in the csv file # 5. Slice into the first 4 rows of the data to preview its contents opened_file = open('AppleStore.csv') from csv import reader read_file = reader(opened_file) data = list(read_file) data[:3] # ### About the data # # The data above was obtained from the public Kaggle dataset [Mobile App Store](https://www.kaggle.com/ramamet4/app-store-apple-data-set-10k-apps/), which is a snapshot from 2017 of the details 7000+ apps on the iOS App Store. See the data dictionary below: # # |Column Name |Description | # |------------------|-----------------------------------------------| # |'id' |App ID | # |'track_name' |App Name | # |'size_bytes' |Size (in Bytes) | # |'currency' |Currency Type | # |'price' |Price amount | # |'rating_count_tot'|User Rating counts (for all version) | # |'rating_count_ver'|User Rating counts (for current version) | # |'user_rating' |Average User Rating value (for all version) | # |'user_rating_ver' |Average User Rating value (for current version)| # |'ver' |Latest version code | # |'cont_rating' |Content Rating | # |'prime_genre' |Primary Genre | # |'sup_devices.num' |Number of supporting devices | # |'ipadSc_urls.num' |Number of screenshots showed for display | # |'lang.num' |Number of supported languages | # |'vpp_lic' |Vpp Device Based Licensing Enabled |
dataquest_projects/first.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 # --- # # Step 1: Check available variables # # In this notebook, we are going to check which variables are available in our collaboration. As we cannot see the data, we need to get some basic information about the available data in another way. Preferably, every node should have FAIR data descriptions, if not available, this will be the first step to identify local variable names. # # Access to this collaboration, and its connected nodes has been arranged by the central server. Based on the given username and password (and server URL) we can connect to our collaboration. # # **Task: fill in the correct connection details in the cell below, and execute the first two cells** # + vantage_broker_url = "" vantage_broker_username = "" vantage_broker_password = "" vantage_broker_encryption = None vantage_broker_port = 5000 vantage_broker_api_path = "/api" # - # ! pip install vantage6-client # Setup client connection from vantage6.client import Client client = Client(vantage_broker_url, vantage_broker_port, vantage_broker_api_path) client.authenticate(vantage_broker_username, vantage_broker_password) client.setup_encryption(vantage_broker_encryption) # We are now connected to the Vantage central server, and have access to several collaborations. # # **Task: execute the cell below, to which collaboration(s) do we have access? And which nodes are available in this collaboration?** # + import json collaboration_list = client.collaboration.list() collaboration_index = 0 organization_ids_ = [ ] for organization in collaboration_list[collaboration_index]['organizations']: organization_ids_.append(organization['id']) print(json.dumps(client.node.list(), indent=2)) # - # Now we know the collaboration, we can post a request to the central server. In this request, we will ask to retrieve the variables available at every node. This is done by requesting to execute the Docker image with name `jaspersnel/v6-colnames-py`. # # **Task: execute the cell below. To which collaboration is this result being sent to? Given the result of the previous cell, which nodes will be targeted to execute this variable retrieval?** # + input_ = { "master": "true", "method":"master", "args": [ ], "kwargs": {} } task = client.post_task( name="RetrieveVariables", image="ghcr.io/maastrichtu-biss/v6-colnames-py", collaboration_id=collaboration_list[collaboration_index]['id'],#Get the first collaboration associated with user input_= input_, organization_ids=[organization_ids_[0]] ) print(json.dumps(task, indent=2)) # - # The request has been sent to the given collaboration. Now we can fetch for the results. As we do not know when the nodes are finished, we implemented a waiting loop procedure. This is implemented below at line 5. # # **Task: execute the cell below. Which column names are available, and on how many nodes?** import time import json resultObjRef = task.get("results")[0] resultObj = client.result.get(resultObjRef['id']) attempts = 1 while((resultObj["finished_at"] == None) and attempts < 10): print("waiting...") time.sleep(5) resultObj = client.result.get(resultObjRef['id']) attempts += 1 colnamesLists = resultObj['result'] colnamesLists
1_check_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 # --- # # Efficient Net の確認を行う # %cd ../../SupervisedSimSiam/ # %pwd from torchsummary import summary import torch import torch.nn.functional as F # + # %load_ext autoreload # %autoreload 2 from modules.models.efficient_net import SqueezeExcitation # - seblock = SqueezeExcitation(10, 5) summary(seblock, (10, 255, 255)) # # Effnet_b0の確認 from modules.models.efficient_net import efficientnet_b0 model = efficientnet_b0(input_ch=3, num_classes=5) summary(model, (3, 250, 250)) model = efficientnet_b0(input_ch=3, num_classes=0) summary(model, (3, 250, 250)) # # torch関数の確認 labels = torch.randint(high=10, size=(1,20)) print(labels) mask = torch.eq(labels, labels.T).float() print(mask) print(torch.unbind(labels, dim=1)) torch.cat(torch.unbind(labels, dim=1), dim=0) print(mask.repeat(5, 5).size()) print(mask.size()) print(torch.arange(5)) print(torch.arange(5).view(-1, 1)) torch.scatter( torch.ones(10,10), 1, torch.arange(5).view(-1, 1), 0 ) print(mask) mask.sum(1) labels.contiguous().view(-1, 1) p = torch.rand(size=(5, 10)) p.size() # + #p = torch.cat(torch.unbind(p, dim=1), dim=0) #p.size() # - print(p.size()) print(torch.matmul(p, p.T).size())
notebook/effnet_test.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 1.5.3 # language: julia # name: julia-1.5 # --- # + ## GoNuts Model 3 ## Decision Making and Optimization - assignment prof.Liuzzi # - using JuMP, GLPK; m = Model(with_optimizer(GLPK.Optimizer)); ## definition of the variables @variable(m, xGE >= 0, Int); @variable(m, xKE >= 0, Int); @variable(m, xGT >= 0, Int); @variable(m, xKT >= 0, Int); @variable(m, xGN >= 0, Int); @variable(m, xKN >= 0, Int); @variable(m, yE, Bin); @variable(m, yT, Bin); @variable(m, yN, Bin); ## definition of objective functions @objective(m, Min, 21xGE + 22.5xKE + 22.5xGT + 24.5xKT + 23xGN + 25.5xKN + 1500yE + 2000yT + 3000yN) ## definition of constraints @constraint(m, constraintC1, xGE + xKE <= 425); @constraint(m, constraintC2, xGT + xKT <= 400); @constraint(m, constraintC3, xGN + xKN <= 750); @constraint(m, constraintD1, xGE + xGT + xGN >= 550); @constraint(m, constraintD2, xKE + xKT + xKN >= 450); @constraint(m, constraintLmax1, xGE + xKE - 425yE <= 0); @constraint(m, constraintLmax2, xGT + xKT - 400yT <= 0); @constraint(m, constraintLmax3, xGN + xKN - 750yN <= 0); @constraint(m, constraintLmin1, xGE + xKE - 100yE >= 0); @constraint(m, constraintLmin2, xGT + xKT - 250yT >= 0); @constraint(m, constraintLmin3, xGN + xKN - 600yN >= 0); ## visualize problems in Jupyter m ## launch optimizatio optimize!(m); termination_status(m) ## print optimal solutions println("Optimal Solutions:"); println("xGE = ", value(xGE)); println("xKE = ", value(xKE)); println("xGT = ", value(xGT)); println("xKT = ", value(xKT)); println("xGN = ", value(xGN)); println("xKN = ", value(xKN)); println("yE = ", value(yE)); println("yT = ", value(yT)); println("yN = ", value(yN)); ## print total optimized cost println("** Optimal objective function value = ", objective_value(m))
.ipynb_checkpoints/optimization_go_nuts_model3-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 # --- import pandas as pd from sqlalchemy import create_engine BT_all = pd.read_csv('/users/jdlara/Documents/Box Sync/EPIC-Biomass/Biomass data/BillionTonUpdateForestResources/KDF_Frst_LOGT.dat', encoding='UTF-8', delimiter = ',', dtype = {'fcode':str}) BT_all = BT_all.fillna(0) FIPS_all = pd.read_csv('/users/jdlara/Documents/Box Sync/EPIC-Biomass/Biomass data/BillionTonUpdateForestResources/fips_codes2.csv', encoding='UTF-8', dtype = {'State FIPS Code':str,'County FIPS Code':str}) FIPS_all['fcode'] = FIPS_all[['State FIPS Code', 'County FIPS Code']].apply(lambda x: ''.join(x), axis=1) FIPS_all = FIPS_all.loc[FIPS_all['Entity Description'] == 'County'] FIPS_all = FIPS_all.set_index('fcode') df_join = BT_all.join(FIPS_all, on = 'fcode') engine = create_engine('postgresql+pg8000://jdlara:<EMAIL>@<EMAIL>:5432/apl_cec?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory', isolation_level="AUTOCOMMIT") df_join.to_sql('KDF_Frst_LOGT', engine, schema='Billion_TON', if_exists = 'replace') engine_source = create_engine('postgresql+pg8000://jdlara:<EMAIL>0@<EMAIL>:5432/switch_gis?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') engine_dest = create_engine('postgresql+pg8000://jdlara:<EMAIL>:5432/APL_CEC?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') df_r = pd.read_sql_query('select * from ventyx_may_2012.maj_road_polyline',engine_source) df_subs = pd.read_sql_query('select * from ventyx_may_2012.e_buses_wecc_point',engine_source) df_subs = df_subs.set_index('gid') df_counties = df_counties.set_index('gid') df_counties.to_sql('Counties', engine, schema='General_GIS_DATA', if_exists = 'replace') #df_subs.to_sql('WECC_Substations', engine, schema='General_GIS_DATA', if_exists = 'replace') engine_source = create_engine('postgresql+pg8000://jdlara:<EMAIL>:5432/switch_gis?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory') df_roads = pd.read_sql_query('select * from ventyx_may_2012.maj_road_polyline',engine_source) df_roads = df_roads.set_index('gid') df_roads.to_sql('maj_road_polyline', engine, schema='General_GIS_DATA', if_exists = 'replace') BT_all = pd.read_csv('/Users/jdlara/Documents/Box Sync/EPIC-Biomass/Data sept 25/LEMMA_parallel_CRMORT.csv', encoding='UTF-8', delimiter = ',') engine = create_engine('postgresql+pg8000://jdlara:<EMAIL>:5432/apl_cec?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory', isolation_level="AUTOCOMMIT") BT_all.to_sql('lemma_crmort', engine, schema='lemma', if_exists = 'replace',chunksize=10000) BT_all.head(5)
sandbox/Clean BT_file.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 # --- # header files import numpy as np import torch import torch.nn as nn import torchvision from google.colab import drive drive.mount('/content/drive') np.random.seed(1234) torch.manual_seed(1234) torch.cuda.manual_seed(1234) # define transforms train_transforms = torchvision.transforms.Compose([torchvision.transforms.RandomRotation(30), torchvision.transforms.Resize((224, 224)), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) # datasets train_data = torchvision.datasets.ImageFolder("/content/drive/My Drive/train_images/", transform=train_transforms) val_data = torchvision.datasets.ImageFolder("/content/drive/My Drive/val_images/", transform=train_transforms) print(len(train_data)) print(len(val_data)) # load the data train_loader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True, num_workers=16, pin_memory=True) val_loader = torch.utils.data.DataLoader(val_data, batch_size=32, shuffle=True, num_workers=16, pin_memory=True) # + class Convolution(torch.nn.Sequential): # init method def __init__(self, in_channels, out_channels, kernel_size, strides, padding, dilation=1): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.strides = strides self.padding = padding self.dilation = dilation self.add_module("conv", torch.nn.Conv2d(self.in_channels, self.out_channels, kernel_size=self.kernel_size, stride=self.strides, padding=self.padding, dilation=self.dilation)) self.add_module("norm", torch.nn.BatchNorm2d(self.out_channels)) self.add_module("act", torch.nn.ReLU(inplace=True)) # define VGG19 network class VGG19(nn.Module): # init method def __init__(self, num_classes = 2): super(VGG19, self).__init__() self.features = nn.Sequential( # first cnn block Convolution(3, 64, 3, 1, 1), Convolution(64, 64, 3, 1, 1), nn.MaxPool2d(kernel_size=2, stride=2), # second cnn block Convolution(64, 128, 3, 1, 1), Convolution(128, 128, 3, 1, 1), nn.MaxPool2d(kernel_size=2, stride=2), # third cnn block Convolution(128, 256, 3, 1, 1), Convolution(256, 256, 3, 1, 1), Convolution(256, 256, 3, 1, 1), Convolution(256, 256, 3, 1, 1), nn.MaxPool2d(kernel_size=2, stride=2), # fourth cnn block Convolution(256, 512, 3, 1, 1), Convolution(512, 512, 3, 1, 1), Convolution(512, 512, 3, 1, 1), Convolution(512, 512, 3, 1, 1), # fifth cnn block Convolution(512, 512, 3, 1, 2, 2), Convolution(512, 512, 3, 1, 2, 2), Convolution(512, 512, 3, 1, 2, 2), Convolution(512, 512, 3, 1, 2, 2), ) self.avgpool = nn.AdaptiveAvgPool2d(7) self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(inplace = True), nn.Dropout(0.5), nn.Linear(4096, 4096), nn.ReLU(inplace = True), nn.Dropout(0.5), nn.Linear(4096, num_classes), ) # forward step def forward(self, x): x = self.features(x) x = self.avgpool(x) x = x.view(x.shape[0], -1) x = self.classifier(x) return x # - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = VGG19() model.to(device) # loss criterion = torch.nn.CrossEntropyLoss() # define optimizer optimizer = torch.optim.SGD(model.parameters(), lr=0.005, momentum=0.9, weight_decay=5e-4) # + train_losses = [] train_acc = [] val_losses = [] val_acc = [] best_metric = -1 best_metric_epoch = -1 # train and validate for epoch in range(0, 100): # train model.train() training_loss = 0.0 total = 0 correct = 0 for i, (input, target) in enumerate(train_loader): input = input.to(device) target = target.to(device) optimizer.zero_grad() output = model(input) loss = criterion(output, target) loss.backward() optimizer.step() training_loss = training_loss + loss.item() _, predicted = output.max(1) total += target.size(0) correct += predicted.eq(target).sum().item() training_loss = training_loss / float(len(train_loader)) training_accuracy = str(100.0 * (float(correct) / float(total))) train_losses.append(training_loss) train_acc.append(training_accuracy) # validate model.eval() valid_loss = 0.0 total = 0 correct = 0 for i, (input, target) in enumerate(val_loader): with torch.no_grad(): input = input.to(device) target = target.to(device) output = model(input) loss = criterion(output, target) _, predicted = output.max(1) total += target.size(0) correct += predicted.eq(target).sum().item() valid_loss = valid_loss + loss.item() valid_loss = valid_loss / float(len(val_loader)) valid_accuracy = str(100.0 * (float(correct) / float(total))) val_losses.append(valid_loss) val_acc.append(valid_accuracy) # store best model if(float(valid_accuracy) > best_metric and epoch >= 10): best_metric = float(valid_accuracy) best_metric_epoch = epoch torch.save(model.state_dict(), "best_model.pth") print() print("Epoch" + str(epoch) + ":") print("Training Accuracy: " + str(training_accuracy) + " Validation Accuracy: " + str(valid_accuracy)) print("Training Loss: " + str(training_loss) + " Validation Loss: " + str(valid_loss)) print() # + import matplotlib.pyplot as plt e = [] for index in range(0, 30): e.append(index) plt.plot(e, train_losses) plt.show() # - plt.plot(e, val_losses) plt.show()
notebooks/dilated_vgg19.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 # --- # # Now You Code 3: Area and Circumfrence # # In this assignment you are tasks with writing a program which inputs the radius of a circle, and outputs the circumfrence and area of that circle. Feel free to lookup the formulas online. # # We will use the **Write - Refactor - Test - Rewrite** approach to complete the final solution which uses functions. # # **NOTE** `import math` then use `math.PI` to get the value of Pi https://en.wikipedia.org/wiki/Pi # ## Step 1: Write # # Here's the algorihm of this program. Write the solution in Python. # # ``` # input radius as a float # calculate circle area # calcuate circle circumfrence # print radus, area, circumfrence # ``` # # Example run: # # ``` # Enter Radius: 1 # A circle with radius 1.000000 has area 3.141593 and circumfrence 6.283185 # ``` # import math ## TODO: Write the solution here Step 1 # ## Step 2: Refactor # # Next we need to refactor the `area` and `circumfrence` logic into functions. # # - `CircleArea()` has one input a `radius` and returns the `area` as output. # - `CircleCircumfrence()` has one input a `radius` and returns the `circumfrence` as output. # # + ## Step 2: Refactor into two functions def CircleArea... and def CircleCircumfrence # - # ## Step 3: Test # # Time to test. Write two tests, once for each function # ``` # WHEN radius=1 We EXPECT CircleArea(radius) to return 3.141593 # WHEN radius=1 We EXPECT CircleCircumfrence(radius) to return 6.283185 # ``` # # Make sure you call the function to get the actual, just like in the coding lab. # # NOTE: If its accurate to 4 decimal places, that's sufficient. The test values might be different because of how the "%f" format code works. # Step 3: Write tests. # ## Step 4: rewrite the program to use the function # # Finally re-write the original program, but call the functions. # ## Step 4: Write program here from the algorithm above # ## Step 6: Questions # # 1. Provide 3 advantages for programming a user function in your code like `CircleArea` or `CircleCircumfrence` # 2. If we want to guarantee our `CircleCircumfrence` function is 100% accurate, what is the minimum number of test cases must we provide in step 3? # # ## Reminder of Evaluation Criteria # # 1. What the problem attempted (analysis, code, and answered questions) ? # 2. What the problem analysis thought out? (does the program match the plan?) # 3. Does the code execute without syntax error? # 4. Does the code solve the intended problem? # 5. Is the code well written? (easy to understand, modular, and self-documenting, handles errors) #
content/lessons/06/Now-You-Code/NYC3-Area-Circumfrence.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 # --- # + # Load packages import tensorflow as tf from tensorflow import keras import numpy as np import pandas as pd import os import pickle import time import scipy as scp import scipy.stats as scps from scipy.optimize import differential_evolution from scipy.optimize import minimize from datetime import datetime import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression # Load my own functions import dnnregressor_train_eval_keras as dnnk import make_data_wfpt as mdw from kde_training_utilities import kde_load_data import ddm_data_simulation as ddm_sim import boundary_functions as bf # + # Handle some cuda business os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"]="2" from tensorflow.python.client import device_lib print(device_lib.list_local_devices()) # + # Load Model model_path = '/media/data_cifs/afengler/data/kde/full_ddm/keras_models/dnnregressor_ornstein_uhlenbeck_06_28_19_00_43_25/model_0' ckpt_path = '/media/data_cifs/afengler/data/kde/full_ddm/keras_models/dnnregressor_ornstein_uhlenbeck_06_28_19_00_43_25/ckpt_0_60' model = keras.models.load_model(model_path) model.load_weights(ckpt_path) # - model.summary() # + # Initializations ----- n_runs = 100 n_samples = 2500 feature_file_path = '/media/data_cifs/afengler/data/kde/ornstein_uhlenbeck/train_test_data/test_features.pickle' mle_out_path = '/media/data_cifs/afengler/data/kde/ornstein_uhlenbeck/mle_runs' # NOTE PARAMETERS: WEIBULL: [v, a, w, node, shape, scale] param_bounds = [(-2, 2), (0.5, 2), (0.3, 0.7), (-1.0, 1.0)] # my_optim_columns = ['v_sim', 'a_sim', 'w_sim', 'node_sim', 'theta_sim', # 'v_mle', 'a_mle', 'w_mle', 'node_mle', 'theta_mle', 'n_samples'] # Get parameter names in correct ordering: dat = pickle.load(open(feature_file_path, 'rb')) parameter_names = list(dat.keys())[:-2] # :-1 to get rid of 'rt' and 'choice' here # Make columns for optimizer result table p_sim = [] p_mle = [] for parameter_name in parameter_names: p_sim.append(parameter_name + '_sim') p_mle.append(parameter_name + '_mle') my_optim_columns = p_sim + p_mle + ['n_samples'] # Initialize the data frame in which to store optimizer results optim_results = pd.DataFrame(np.zeros((n_runs, len(my_optim_columns))), columns = my_optim_columns) optim_results.iloc[:, 2 * len(parameter_names)] = n_samples # define boundary boundary = bf.constant boundary_multiplicative = True # Define the likelihood function def log_p(params = [0, 1, 0.9], model = [], data = [], parameter_names = []): # Make feature array feature_array = np.zeros((data[0].shape[0], len(parameter_names) + 2)) # Store parameters cnt = 0 for i in range(0, len(parameter_names), 1): feature_array[:, i] = params[i] cnt += 1 # Store rts and choices feature_array[:, cnt] = data[0].ravel() # rts feature_array[:, cnt + 1] = data[1].ravel() # choices # Get model predictions prediction = model.predict(feature_array) # Some post-processing of predictions prediction[prediction < 1e-29] = 1e-29 return(- np.sum(np.log(prediction))) def make_params(param_bounds = []): params = np.zeros(len(param_bounds)) for i in range(len(params)): params[i] = np.random.uniform(low = param_bounds[i][0], high = param_bounds[i][1]) return params # --------------------- # - my_optim_columns # + # Main loop ----------- TD: Parallelize for i in range(0, n_runs, 1): # Get start time start_time = time.time() tmp_params = make_params(param_bounds = param_bounds) # Store in output file optim_results.iloc[i, :len(parameter_names)] = tmp_params # Print some info on run print('Parameters for run ' + str(i) + ': ') print(tmp_params) # Define boundary params # Linear Collapse # boundary_params = {'node': tmp_params[3], # 'theta': tmp_params[4]} # Constant boundary_params = {} # Run model simulations ddm_dat_tmp = ddm_sim.ddm_flexbound_simulate(v = tmp_params[0], a = tmp_params[1], w = tmp_params[2], s = 1, delta_t = 0.001, max_t = 20, n_samples = n_samples, boundary_fun = boundary, # function of t (and potentially other parameters) that takes in (t, *args) boundary_multiplicative = boundary_multiplicative, # CAREFUL: CHECK IF BOUND boundary_params = boundary_params) # Print some info on run print('Mean rt for current run: ') print(np.mean(ddm_dat_tmp[0])) # Run optimizer out = differential_evolution(log_p, bounds = param_bounds, args = (model, ddm_dat_tmp, parameter_names), popsize = 30, disp = True) # Print some info print('Solution vector of current run: ') print(out.x) print('The run took: ') elapsed_time = time.time() - start_time print(time.strftime("%H:%M:%S", time.gmtime(elapsed_time))) # Store result in output file optim_results.iloc[i, len(parameter_names):(2*len(parameter_names))] = out.x # ----------------------- # Save optimization results to file optim_results.to_csv(mle_out_path + '/mle_results_1.csv') # - # Read in results optim_results = pd.read_csv(mle_out_path + '/mle_results.csv') plt.scatter(optim_results['v_sim'], optim_results['v_mle'], c = optim_results['theta_mle']) # Regression for v reg = LinearRegression().fit(np.expand_dims(optim_results['v_mle'], 1), np.expand_dims(optim_results['v_sim'], 1)) reg.score(np.expand_dims(optim_results['v_mle'], 1), np.expand_dims(optim_results['v_sim'], 1)) plt.scatter(optim_results['a_sim'], optim_results['a_mle'], c = optim_results['theta_mle']) # Regression for a reg = LinearRegression().fit(np.expand_dims(optim_results['a_mle'], 1), np.expand_dims(optim_results['a_sim'], 1)) reg.score(np.expand_dims(optim_results['a_mle'], 1), np.expand_dims(optim_results['a_sim'], 1)) plt.scatter(optim_results['w_sim'], optim_results['w_mle']) # Regression for w reg = LinearRegression().fit(np.expand_dims(optim_results['w_mle'], 1), np.expand_dims(optim_results['w_sim'], 1)) reg.score(np.expand_dims(optim_results['w_mle'], 1), np.expand_dims(optim_results['w_sim'], 1)) plt.scatter(optim_results['theta_sim'], optim_results['theta_mle']) # Regression for c1 reg = LinearRegression().fit(np.expand_dims(optim_results['theta_mle'], 1), np.expand_dims(optim_results['theta_sim'], 1)) reg.score(np.expand_dims(optim_results['theta_mle'], 1), np.expand_dims(optim_results['theta_sim'], 1)) plt.scatter(optim_results['c2_sim'], optim_results['c2_mle'], c = optim_results['a_mle']) # Regression for w reg = LinearRegression().fit(np.expand_dims(optim_results['c2_mle'], 1), np.expand_dims(optim_results['c2_sim'], 1)) reg.score(np.expand_dims(optim_results['c2_mle'], 1), np.expand_dims(optim_results['c2_sim'], 1))
deprecated/.ipynb_checkpoints/keras_mle_ddm-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 # --- # Now it's time for you to demonstrate your new skills with a project of your own! # # In this exercise, you will work with a dataset of your choosing. Once you've selected a dataset, you'll design and create your own plot to tell interesting stories behind the data! # # ## Setup # # Run the next cell to import and configure the Python libraries that you need to complete the exercise. import pandas as pd pd.plotting.register_matplotlib_converters() import matplotlib.pyplot as plt # %matplotlib inline import seaborn as sns print("Setup Complete") # The questions below will give you feedback on your work. Run the following cell to set up the feedback system. # Set up code checking from learntools.core import binder binder.bind(globals()) from learntools.data_viz_to_coder.ex7 import * print("Setup Complete") # ## Step 1: Attach a dataset to the notebook # # Begin by selecting a CSV dataset from [Kaggle Datasets](https://www.kaggle.com/datasets). If you're unsure how to do this, please revisit the instructions in the previous tutorial. # # Once you have selected a dataset, click on the **[+ Add data]** option in the top right corner. This will generate a pop-up window that you can use to search for your chosen dataset. # # ![ex6_search_dataset](https://i.imgur.com/cIIWPUS.png) # # Once you have found the dataset, click on the **[Add]** button to attach it to the notebook. You can check that it was successful by looking at the **Data** dropdown menu to the right of the notebook -- look for an **input** folder containing a subfolder that matches the name of the dataset. # # <center> # <img src="https://i.imgur.com/nMYc1Nu.png" width=30%><br/> # </center> # # You can click on the carat to the left of the name of the dataset to double-check that it contains a CSV file. For instance, the image below shows that the example dataset contains two CSV files: (1) **dc-wikia-data.csv**, and (2) **marvel-wikia-data.csv**. # # <center> # <img src="https://i.imgur.com/B4sJkVA.png" width=30%><br/> # </center> # # Once you've uploaded a dataset with a CSV file, run the code cell below **without changes** to receive credit for your work! # Check for a dataset with a CSV file step_1.check() # ## Step 2: Specify the filepath # # Now that the dataset is attached to the notebook, you can find its filepath. To do this, begin by clicking on the CSV file you'd like to use. This will open the CSV file in a tab below the notebook. You can find the filepath towards the top of this new tab. # # ![ex6_filepath](https://i.imgur.com/fgXQV47.png) # # After you find the filepath corresponding to your dataset, fill it in as the value for `my_filepath` in the code cell below, and run the code cell to check that you've provided a valid filepath. For instance, in the case of this example dataset, we would set # ``` # my_filepath = "../input/fivethirtyeight-comic-characters-dataset/dc-wikia-data.csv" # ``` # Note that **you must enclose the filepath in quotation marks**; otherwise, the code will return an error. # # Once you've entered the filepath, you can close the tab below the notebook by clicking on the **[X]** at the top of the tab. # + # Fill in the line below: Specify the path of the CSV file to read my_filepath = ____ # Check for a valid filepath to a CSV file in a dataset step_2.check() # - # #%%RM_IF(PROD)%% my_filepath = "../input/abcdefg1234.csv" step_2.assert_check_failed() # #%%RM_IF(PROD)%% my_filepath = "../input/candy.csv" step_2.assert_check_passed() # ## Step 3: Load the data # # Use the next code cell to load your data file into `my_data`. Use the filepath that you specified in the previous step. # + # Fill in the line below: Read the file into a variable my_data my_data = ____ # Check that a dataset has been uploaded into my_data step_3.check() # - # #%%RM_IF(PROD)%% my_data = pd.read_csv(my_filepath, index_col="id") step_3.assert_check_passed() # **_After the code cell above is marked correct_**, run the code cell below without changes to view the first five rows of the data. # Print the first five rows of the data my_data.head() # ## Step 4: Visualize the data # # Use the next code cell to create a figure that tells a story behind your dataset. You can use any chart type (_line chart, bar chart, heatmap, etc_) of your choosing! # + # Create a plot ____ # Your code here # Check that a figure appears below step_4.check() # - # #%%RM_IF(PROD)%% sns.regplot(x=my_data['sugarpercent'], y=my_data['winpercent']) step_4.assert_check_passed() # ## Keep going # # Learn how to use your skills after completing the micro-course to create data visualizations in a **[final tutorial](#$NEXT_NOTEBOOK_URL$)**.
notebooks/data_viz_to_coder/raw/ex7.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 Bio import SeqIO # load dna sequence into a list nucleotide = SeqIO.parse('sequences.fasta','fasta') nucleotide_data = [] for sequence in nucleotide: nucleotide_data.append(str(sequence.seq)) # find max length of the sequence max_len = 0 for data in nucleotide_data: if len(data) > max_len: max_len = len(data) print(max_len) # extend the string to same length (max_len) for i in range(0, len(nucleotide_data)): nucleotide_data[i] = nucleotide_data[i].ljust(max_len, 'N') # split string to string for i in range(0, len(nucleotide_data)): nucleotide_data[i] = [char for char in nucleotide_data[i]] # + #import for ML import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from keras.models import Sequential, Model from keras.layers import Activation, Dense, Input from keras import optimizers from keras import backend as K # + #encoding data with numbers nucleic_acid_encoding = { 'A': 0, 'G': 1, 'C': 2, 'T': 3, 'Y': 4, 'M': 5, 'S': 6, 'K': 7, 'R': 8, 'W': 9, 'N': 10 } encoded_nucleotide = [] for i in range(0, len(nucleotide_data)): encoded_nucleotide.append([]) for j in range(0, max_len): encoded_nucleotide[i].append(nucleic_acid_encoding[nucleotide_data[i][j]]) encoded_nucleotide = np.array(encoded_nucleotide) # + # building autoencoder encoding_dim1 = 128 encoding_dim2 = 16 encoding_dim3 = 3 decoding_dim3 = 16 decoding_dim2 = 128 input_data = Input(shape=encoded_nucleotide.shape[1]) encoded1 = Dense(encoding_dim1, activation='relu')(input_data) encoded2 = Dense(encoding_dim2, activation='relu')(encoded1) encoded3 = Dense(encoding_dim3, activation='relu', name='encode_layer')(encoded2) decoded3 = Dense(decoding_dim3, activation='relu')(encoded3) decoded2 = Dense(decoding_dim2, activation='relu')(decoded3) decoded1 = Dense(encoded_nucleotide.shape[1], activation='relu')(decoded2) autoencoder = Model(input_data, decoded1) autoencoder.compile(optimizer='adam', loss=tf.keras.losses.MeanSquaredLogarithmicError()) hist_auto = autoencoder.fit(encoded_nucleotide, encoded_nucleotide, epochs=500, batch_size=32, shuffle=True, validation_split=0.2) # + # plot training history plt.figure() plt.plot(hist_auto.history['loss']) plt.plot(hist_auto.history['val_loss']) plt.title('Autoencoder model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'val'], loc='upper right') plt.show() # - autoencoder.summary() # autoencoder architecture # + # build another model that outputs 3 dimensional data encoded_layer = Model(inputs=autoencoder.input, outputs=autoencoder.get_layer('encode_layer').output) # + # crearte new dataset with 3 dimensional data encoded_data = [] for sequence in encoded_nucleotide: encoded_data.append(encoded_layer.predict(np.array([sequence,]))[0]) # + # import for clustering from sklearn.cluster import KMeans from mpl_toolkits.mplot3d import Axes3D # + # determine the optimal number of clusters using elbow method inertia = [] K = range(1,6) for k in K: km = KMeans(init='k-means++', n_clusters=k, n_init=10) km.fit(encoded_data) inertia.append(km.inertia_) plt.plot(K, inertia, 'bx-') plt.xlabel('Number of Clusters K') plt.ylabel('Inertia') plt.title('Elbow Method For Optimal K') plt.show() # + # create a dataset for visualizing clusters kmeans = KMeans(init='k-means++', n_clusters=3, n_init=10) kmeans.fit(encoded_data) P = kmeans.predict(encoded_data) # + # plot 3D graph of clusters # %matplotlib encoded_fig = plt.figure() ax = Axes3D(encoded_fig) p = ax.scatter([row[0] for row in encoded_data], [row[1] for row in encoded_data], [row[2] for row in encoded_data], c=P, marker="o", picker=True, cmap="rainbow") plt.colorbar(p, shrink=0.5) for angle in range(0, 360): ax.view_init(30, angle) plt.draw() plt.pause(.001) # -
.ipynb_checkpoints/Clustering-SARS-COV-2-checkpoint.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: alpha # language: python # name: alpha # --- # + # %load_ext line_profiler # %load_ext autoreload import numpy as np import tensorflow as tf import tensorflow_addons as tfa from matplotlib import pyplot as plt # %matplotlib inline # %config InlineBackend.figure_format = 'retina' from tqdm import auto as tqdm from functools import lru_cache import pickle import os # - # Prepare data # + def normalize(a, axis=None): return a / np.linalg.norm(a, axis=axis, keepdims=True) @lru_cache() def make_mnist_data(P=5000, d=20, P_test=None): # Load data from https://www.openml.org/d/554 from sklearn.datasets import fetch_openml X_raw, y_raw = fetch_openml('mnist_784', version=1, return_X_y=True) if P_test is None: P_test = P X = X_raw[:P+P_test] y = (2*(y_raw.astype(int) % 2) - 1)[:P+P_test].reshape(-1) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=P_test, random_state=42) from sklearn.decomposition import PCA pca = PCA(n_components = d) pca = pca.fit(X_train) X_train = pca.transform(X_train) X_test = pca.transform(X_test) # project to hyper-sphere of radius sqrt(d) X_train = np.sqrt(d) * normalize(X_train, axis=1) X_test = np.sqrt(d) * normalize(X_test, axis=1) return X_train, X_test, y_train, y_test # - X_train, X_test, y_train, y_test = make_mnist_data() # + # pickle.dump((X_train, X_test, y_train, y_test), open('mnist.pkl', 'wb')) # - # Prepare network def make_CK_model(N, loss='squared_hinge', optimizer='adam'): model = tf.keras.Sequential([ tf.keras.layers.InputLayer(d, name='inputs'), tf.keras.layers.Dense(N, use_bias=False, activation='tanh', name='intermediate'), tf.keras.layers.Dense(1, use_bias=False, name='outputs') ]) def accuracy(y_true, y_pred): return tf.reduce_mean(tf.cast(y_true*y_pred > 0, float)) model.compile(loss=loss, optimizer=optimizer, metrics=[accuracy]) return model class SaveCallback(tf.keras.callbacks.Callback): """ Allows for logarithmically spaced model saving and checkpointing """ def __init__(self, filepath, save_every=1, logarithmic=False): self.filepath = filepath self.save_every = save_every self.logarithmic = logarithmic self.last_checkpoint_epoch = 0 self.epoch = 0 def set_model(self, model): self.model = model def on_train_begin(self, logs=None): self._save_model('MODEL', weights_only=False) def on_epoch_end(self, epoch, logs=None): self.epoch = epoch if self.logarithmic: save_this_epoch = (epoch >= self.last_checkpoint_epoch * 10**self.save_every) else: save_this_epoch = (epoch >= self.last_checkpoint_epoch + self.save_every) if save_this_epoch: self.last_checkpoint_epoch = epoch self._save_model(f'checkpoint_{epoch}.ckpt', weights_only=True) def on_train_end(self, logs=None): self._save_model(f'checkpoint_{self.epoch}.ckpt', weights_only=True) def _save_model(self, filename, weights_only=True): filepath = os.path.join(self.filepath, filename) if weights_only: self.model.save_weights(filepath, overwrite=True) else: self.model.save(filepath, overwrite=True) # Train! # + P = 5000 d = 20 X_train, X_test, y_train, y_test = make_mnist_data(P=P, d=d) N = int(1.1*P) model_directory = f'checkpoints/P_{P}-d_{d}-N_{N}_mnist' mirrored_strategy = tf.distribute.MirroredStrategy() with mirrored_strategy.scope(): model = make_CK_model(N) # + batch_size = min(1024, P//2) n_steps = int(1e6) n_saves = 100 batches_per_epoch = P//batch_size epochs = n_steps//batches_per_epoch tqdm_callback = tfa.callbacks.TQDMProgressBar(show_epoch_progress=False) save_callback = SaveCallback(model_directory, logarithmic=True, save_every=np.log10(epochs)/(n_saves)) result = model.fit(X_train, y_train, epochs = epochs, batch_size=batch_size, verbose=0, callbacks=[tqdm_callback, save_callback]) pickle.dump(result, open(os.path.join(model_directory, 'result.pkl'), 'wb'))
code/progressive_training/L=1/ck_progressive_training.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 # --- # ### 词云/TF-IDF 关键词提取/主题模型和文本分析/文本类型预测 ## Copyright private in 2018 # Modify Date: # 2018 - 9 - 18 # Purpose : 词云/TF-IDF 关键词提取/主题模型和文本分析/文本类型预测 # # ---------- import sys sys.version # + #from gensim.models import word2vec #help(word2vec) # - #coding:utf-8 __author__ = 'naturelanguageprocessing' import warnings import numpy warnings.filterwarnings("ignore") import jieba import codecs # codecs 提供的open 方法来指定打开的文件的语言编码,他会在读取的时候 import numpy as np import matplotlib.pyplot as plt import pandas as pd import matplotlib # #%matplotlib inline #嵌入中显示图片显示 matplotlib.rcParams['figure.figsize'] = (10.0,5.0) # figure size 大小 from wordcloud import WordCloud # 词云 # ### 数据来着中国新闻网上的,短讯新闻 # + #df = pd.read_csv('./data/entertainment_news.csv',names = ['url','contenttitle','content','label'],encoding = 'utf-8') #df = pd.read_csv(r'C:\Users\H155809\out.csv',encoding = 'utf-8') #df = pd.read_csv('C:\\Users\\H155809\\out.csv',encoding = 'utf-8') df = pd.read_csv("./data/military_news.csv",encoding = 'utf-8') df = df.dropna() # drop掉可能为空的行数 content = df.content.values.tolist() #取出数据中的content列,通过values tolist 转成Python列表 #segment initial segment = [] #new list - 存储所有分完词的list for line in content: try: segs = jieba.lcut(line) # lcut:listcut - segs is list for seg in segs: if len(seg)>1 and seg!='\r\n': #新闻的文本>1非空 同时不等于换行 等赋值给segment segment.append(seg) except: #异常的话 print line print(line) continue # - cuted = jieba.lcut(content[0]) print segment[0],segment[1],segment[2],segment[3],segment[4],segment[5],segment[6] segment[0],segment[1],segment[2],segment[3],segment[4],segment[5],segment[6] print content[0] print content[1] df.head() # # (一) 生成词云 # ### 2.Remove Stopwords # + import pandas as pd words_df = pd.DataFrame({'segment':segment}) # 读取stopwords 表 stopwords = pd.read_csv("./data/stopwords_NLP.txt", index_col = False, quoting = 3,sep = "\t", names = ['stopword'], encoding = 'utf-8') # stopwards.head() # 3.词频统计 words_df = words_df[~words_df.segment.isin(stopwords.stopword)] #分完词后的segment 词中,不再停用词当中的词取出来保留。 #print words_df # 按照sgement 来分组并通过聚合agg 来统计出的频次 words_stat = words_df.groupby(by = ['segment'])['segment'].agg({"计数":numpy.size}) # numpy.shape # reset_index来拉平,并且是计数 这一列按照降序排序 ascending = False words_stat = words_stat.reset_index().sort_values(by = ["计数"],ascending = False) words_stat.head() # 从高到低显示 # - # ### 4.画词云 # + #help(WordCloud) # + #type(words_stat) #words_stat.index # + #words_stat.head(100).values # + # 指定字体 - simhei.ttf, background is "white" , max font size is 80 "font_path 用于指定载入特定的字体文件..." wordcloud = WordCloud(font_path = "./data/simhei.ttf",max_words = 200,background_color = "white",width = 400,height =200, max_font_size = 80) # 取出一部分高频出现的词语做可视化 - Dict # x[0] : word - 是segment的内容 # x[1] : frequency of word - Values 是 "计数" word_frequency = {x[0]:x[1] for x in words_stat.head(1000).values} # 取出前1000个词的values的数组构建一个字典 wordcloud = wordcloud.fit_words(word_frequency) # show the image plt.imshow(wordcloud) plt.show() # - wordcloud.fit_words({x[0]:x[1] for x in words_stat.head(1000).values } ) help(wordcloud) # ### 5.自定义背景图做词云的背景 - 白底 # + # import lib functions from scipy.misc import imread matplotlib.rcParams['figure.figsize'] = (9.0, 6.0) # Fig size from wordcloud import WordCloud,ImageColorGenerator # Color Generator # 读入图片作为模板 bimg = imread('./image/entertainment.png') # wordcloud 初始化: background, font and max font size ; mask 以上述图片作为模板; font_path = 'data/simhei.ttf 微软雅黑字体 wordcloud = WordCloud(background_color = 'white', mask = bimg, font_path = 'data/simhei.ttf', max_font_size = 200 ) word_frequency = {x[0]:x[1] for x in words_stat.head(1000).values} # 取出前1000个词的values 的数组 wordcloud = wordcloud.fit_words(word_frequency) bimgColors = ImageColorGenerator(bimg) # 通过导入的图片来生成颜色 plt.axis("off") plt.imshow(wordcloud.recolor(color_func = bimgColors)) # 用现有的图片比重新生成word cloud 更快 plt.show() # - # # (二) 中文自然语言处理文本分析 # ### 1.关键词提取 - based on TF - IDF:基于词频的 # + ### based on TF-IDF ## function : jieba.analyse.extract_tags(sentence, topK = 20, withWeight = False, allowPOS= ()) ## sentence is tested text ## TopK 返回几个权重最大的几个关键词, default value = 20 ## withWeight 决定是否返回关键词的权重, default value = False ## allowPOS 包含指定的词性; 名词或形容词, default value = NULL 即不筛选 # + import jieba.analyse as analyse import pandas as pd df = pd.read_csv('./data/technology_news.csv',encoding = 'utf-8') df = df.dropna() # drop掉可能为空的行数 lines = df.content.values.tolist() #取出数据中的content列,通过values tolist 转成Python列表 # 利用join 函数将所有的文本拼接在一起 content = "".join(lines) # -- # 按照空格打印出前30出现频率最高的词 # 按照TF - IDF 计算值抽取出高频的词 - extract_tags() print "在技术类新闻中出现最高频率的前30个词分别是:" # %time print " ".join(analyse.extract_tags(content,topK = 30, withWeight = False, allowPOS = () )) # - help(analyse) # ### 2.基于TextRank提取关键词 # #%time print "".join(jieba.analyse.textrank(content,topK = 20, withWeight = False, allowPOS = ('ns','n','vn','v')) )# 默认是过滤词性的 # %time print " ".join(analyse.textrank(content,topK =30,withWeight = False,allowPOS = ('ns'))) ## ## 1. 将待抽取关键词的文本进行分类 ## 2. 以固定窗口大小(default value = 5 ), 词与词之间的共同出现的关系构建图 ## 3. 计算图中节点的pagerank ## 4. 算法计算比TF-IDF 速度慢, import jieba.analyse as analyse import pandas as pd df = pd.read_csv("./data/sports_news.csv", encoding = 'utf-8') df = df.dropna() lines = df.content.values.tolist() content = " ".join(lines) # print - allowPOS 返回词性。默认是过滤词性 v: 动词, n:名词 print "通过Textrank提取主题关键词:" # %time print " ".join(analyse.textrank(content,topK = 20, withWeight = False, allowPOS = ('v','n') )) # ### 3.LDA 主题模型 - 无监督学习 # + ### 无监督学习 - 抽取一定数量的主题,每个主题的权重从到大到小显示出来 ### 找到一堆文本中的主题,发现用户都在关心什么话题 # - from gensim import corpora, models, similarities import gensim # ### 3.1载入停用词 # load stopwards stopwords = pd.read_csv("./data/stopwords_NLP.txt", index_col = False, quoting = 3,sep = "\t", names = ['stopword'], encoding = 'utf-8') stopwords = stopwords['stopword'].values len(stopwords) # ### 转化成合适的数据格式 # + # 转化成合适的数据格式 # 将文本内容处理成固定的格式,一个包含句子的List,每个list中的元素是分词后的词list; # [[第,一,条,新闻,在这里], [第二条新闻在这里], [这是在做什么,]] # import jieba.analyse as analyse import pandas as pd df = pd.read_csv('./data/technology_news.csv',encoding = 'utf-8') df = df.dropna() # drop掉可能为空的行数 lines = df.content.values.tolist() #取出数据中的content列,通过values tolist 转成Python列表 sentences = [] for line in lines: try: segs = jieba.lcut(line) # jieba分词 - linecut segs = filter(lambda x:len(x)>1, segs) # 分词后词的数量比1小的是空,filter 掉不需要。 segs = filter(lambda x:x not in stopwords, segs) # 分词完的词在stopwords中,同样不需要 sentences.append(segs) except Exception,e: print line continue # - ## check for word in sentences[4]: print word # ### 3.2 Bag of Words Model - 词袋模型 #bag of words - 词袋模型 dictonary = corpora.Dictionary(sentences) # 把 sentences 中的词建成字典(word ->index 映射) # 通过过词袋模型 将文本转化成数字, 学习下来新的词 - corpus = [dictonary.doc2bow(sentence) for sentence in sentences] # ### 3.3 LDA 建模 # + # # topK = 20个主题 and corpus 表示设定好的格式数据 lda = gensim.models.ldamodel.LdaModel(corpus = corpus, id2word = dictonary, num_topics = 20 ) # Topk = 10 and 3nd 分类 # 打印出第3种分类,及该分类中的前10个高频词及权重(权重由大到小显示) print lda.print_topic(3,topn = 10) # + #help(lda.get_document_topics) # - # 打印出主题,主题数目设定为20 ,每个主题里面的数量是8 - 可作为关键主题和信息的提取 for topic in lda.print_topics(num_topics = 20, num_words = 8): print topic[1] # # (三) 用机器学习的方法处理中文文本 # ### 1. 准备数据 # + ## 准备数据 import jieba import pandas as pd # df_technology df_technology = pd.read_csv("./data/technology_news.csv", encoding = 'utf-8') df_technology = df_technology.dropna() # 取消可能为空的行数 # df_car df_car = pd.read_csv("./data/car_news.csv", encoding = 'utf-8') df_car = df_car.dropna() # df_entertainment df_entertainment = pd.read_csv("./data/entertainment_news.csv", encoding = 'utf-8') df_entertainment = df_entertainment.dropna() # df_sprots = pd.read_csv("./data/sports_news.csv", encoding = 'utf-8') df_sprots = df_sprots.dropna() # df_military = pd.read_csv("./data/military_news.csv", encoding = 'utf-8') df_military = df_military.dropna() # + # 每个种类提取一定数量的文本样本记录 technology = df_technology.content.values.tolist()[100:2100] car = df_car.content.values.tolist()[100:2100] entertainment = df_entertainment.content.values.tolist()[100:2100] sprots = df_sprots.content.values.tolist()[100:2100] military = df_military.content.values.tolist()[100:2100] # - # print 1 records ramdomly print "娱乐数据个别样本:\n",entertainment[11] print "运动数据个边样本:\n",sprots[1] print "军事题材的个别样本:\n",military[11] # ### 2 分词与中文文本分类 # load stopwards stopwords = pd.read_csv("./data/stopwords_NLP.txt", index_col = False,names =['stopword'],encoding = 'utf-8',quoting = 3,sep = "\t") # reading stopwords = stopwords['stopword'].values # load values # ### 2.1 ML数据集的预处理:去掉空格并打上标签 # + # Remove stopwords in fucntion def preprocess_text(content_lines,sentences,category): for line in content_lines: try: segs = jieba.lcut(line) segs = filter(lambda x:len(x)>1, segs) # 空格 清掉 segs = filter(lambda x:x not in stopwords, segs) # 把 sentences 里面的词通过空格链接起来,并打上category 的标签 sentences.append( (" ".join(segs), category) ) except Exception, e: print line continue # generated date sentences =[] # 将全部的数据传进来做数据的预处理,并为各个种类带上标签: ‘technology’ and 'car' and so on preprocess_text(technology,sentences,'technology') preprocess_text(car,sentences,'car') preprocess_text(sprots,sentences,'sprots') preprocess_text(military,sentences,'military') preprocess_text(entertainment,sentences,'entertainment') # - # ### 3. 将数据分成测试数据集合和训练数据集之前,先提前打乱数据集合 # + # 将数据分成测试数据集合和训练数据集之前,先提前打乱数据集合 import random random.shuffle(sentences) # 乱序 # print for sentence in sentences[:2]: # sentences 是由内容和标签组成一个样本,由多个样本组成的list print sentence[0],sentence[1] # - for content in sentences[0:3]: print "文本内容是:",content[0],"=>对应的标签是:<<",content[1],">>" for content in sentences[0]: print "content >>>",content[0] # ### 4.Split Data into Train and Test Data Serts # + # Split Data into Train and Test Data Serts from sklearn.model_selection import train_test_split # 拉链函数zip来把数据的文本内容赋值给x, 标签 ‘technology’ and 'car' and so on 赋值给我label: y x,y = zip(*sentences) # x 是全部的文本,y是全部的标签 x_train,x_test,y_train,y_test = train_test_split(x,y,random_state = 200) # output len(x_train) # - len(x_test) # ### 5.通过词袋模型对文本进行特征提取,找到每个词对应的下标,并以下标作为向量 # + from sklearn.feature_extraction.text import CountVectorizer # 向量化计数器 # 在上述通过空格衔接起来的词中取出4000个词,通过CountVectorizer 来找到每个词对应的词向量。该向量统计也会考虑每个词出现的频次 vec = CountVectorizer(analyzer = 'word', # 按照空格链接起来的词 max_features = 4000) # 取出最高频的4000 个词,并以4000词的对应下标值组成一个向量 # 用训练集做fit vec.fit(x_train) # 将字符串的np数组x(词语或者一句话)转化成向量 def get_features(x): vec.transform(x) # - temp = ["我 是 中国 人"] import numpy as np vec.transform(np.array(temp)) # 词向量映射成1*4000的词向量 # ### 6. import classifiter to fit data # ### 6.1 导入朴素贝叶斯分类器来训练数据 # import多项式的朴素贝叶斯模型作为分类器来训练模型 from sklearn.naive_bayes import MultinomialNB classifier = MultinomialNB() # 将训练文本转化成向量的x_train 丢进来,及标签y_train 作为训练 classifier.fit(vec.transform(x_train),y_train) # 训练文本转化成向量的x_train 丢进 ### 计算准确率 on test data sets classifier.score(vec.transform(x_test),y_test) ## length of x_test data sets len(x_test) # ### 7. 在特征方面引入N-gram 模型做分词处理,N =1,2 : ngram_range = (1,3),并加大词表数量 # #### N = 2 把“我是”“中国” 等加进来作为特征,N =3 把“我是中”,“国人是” # #### N =2,3 的数据不会太密集,所以不容易出现过拟合 # + from sklearn.feature_extraction.text import CountVectorizer # 向量化计数器 vec = CountVectorizer(analyzer = 'word', # 按照空格链接起来的词 ngram_range = (1,3), # N-gram 模型 N = 1,2 max_features = 20000) # 加大词表数量 # 用训练集做fit vec.fit(x_train) # 将字符串的np数组x(词语)转化成向量 def get_features(x): x.transform(x) # - #训练过程 classifier = MultinomialNB() # 将训练文本转化成向量的x_train 丢进来,及标签y_train 作为训练 classifier.fit(vec.transform(x_train),y_train) ### 计算准确率 on test data sets classifier.score(vec.transform(x_test),y_test) # + from sklearn.model_selection import StratifiedKFold X1 = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) y1 = np.array([0, 0, 1, 1]) skf = StratifiedKFold(n_splits=2) skf.get_n_splits(X1, y1) print ">>skf is :",skf for train_index,test_index in skf.split(X1,y1): X1_train,X1_test = X1[train_index], X1[test_index] y1_train,y1_test = y1[train_index],y1[test_index] print "X_train", X1_train print "X_test", X1_test print "y_train", y1_train print "y_test", y1_test # - # ### 8.随机乱序后,数据集变得更随机 - 这样很好 # ### 通过交叉验证集合fit Model - crossvalidation ,kfold = 5 时最后保证每一折的数据都是均衡 # # + #help(StratifiedKFold) # + # 当前数据为4个种类,这里KFold 成4个部分,三个部分做trian data sets, 1个部分做test data sets # 通过 KFold 来分类数据- 每1折的数据尽量数据均衡 from sklearn.model_selection import StratifiedKFold from sklearn.metrics import accuracy_score, precision_score import numpy as np # K 层的交叉验证 def stratifiedkfold_cv(x,y,clf_class,shuffle= True,n_folds = 5,**kwargs): stratifiedk_fold = StratifiedKFold(n_splits = n_folds, shuffle = shuffle) # 按照y 标签来类K 折 y_pred = y[:] for train_index,test_index in stratifiedk_fold.split(x,y): X_train, X_test = x[train_index],x[test_index] # K-1折做数据训练,1折做测试数据集 y_train = y[train_index] clf = clf_class(**kwargs) clf.fit(X_train,y_train) y_pred[test_index] = clf.predict(X_test) return y_pred # - vec_x = vec.transform(x) # + #help(precision_score) # - NB = MultinomialNB y_true = y y_pred = stratifiedkfold_cv(vec.transform(x),np.array(y),NB) print "%","%f" %((precision_score(y_true,y_pred,labels = None, average = 'macro'))*100) print "通过在K=5折的交叉验证,可以看到在5个类别上的结果平均准确率是上面的结果:" # # (四) 整理文本分类Class import re from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB class TextClassifier(): def __init__(self,classifier = MultinomialNB()) : # 默认是朴素贝叶斯模型 self.classifier = classifier self.vectorizer = CountVectorizer(analyzer = 'word', ngram_range = (1,3), max_features = 2000) def features(self,X): return self.vectorizer.transform(X) # 每一句通过查字典化成向量 def fit(self,X,y): self.vectorizer.fit(X) # 先在训练集上转成文本 self.classifier.fit(self.features(X), y) # 再将训练集文本转成向量 def predict(self,x): return self.classifier.predict(self.features([x])) def score(self,X,y): # 打分 return self.classifier.score(self.features(X),y) # + ## class的调用 classifier = TextClassifier() classifier.fit(x_train,y_train) # prediction & score print(classifier.predict('融资 是 创业 很难 做到 的 事情')) print(classifier.score(x_test,y_test)) # - # # (五) SVM Text Classifier # from sklearn.svm import SVC svm = SVC(kernel = 'linear') svm.fit(vec.transform(x_train), y_train) svm.score(vec.transform(x_test), y_test) # RBF Kernal - 高斯核 -速度比较慢 from sklearn.svm import SVC svm = SVC() # 默认RBF Kernal svm.fit(vec.transform(x_train), y_train) svm.score(vec.transform(x_test), y_test) # 换一个特征提取模型 import re from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.svm import SVC class TextClassifier(): def __init__(self,classifier = SVC(kernel = 'linear')) : # 默认是线性SVM self.classifier = classifier self.vectorizer = TfidfVectorizer(analyzer = 'word', ngram_range = (1,3), max_features = 2000) def features(self,X): return self.vectorizer.transform(X) # 将文本转化成向量 def fit(self,X,y): self.vectorizer.fit(X) self.classifier.fit(self.features(X), y) def predict(self,x): return self.classifier.predict(self.features([x])) def score(self,X,y): return self.classifier.score(self.features(X),y) # + ## class的调用 classifier = TextClassifier() classifier.fit(x_train,y_train) # prediction & score print(classifier.predict('拿到 年终奖 高高兴兴 回家 过年 发现 微信 群里 红包 满天飞')) print(classifier.score(x_test,y_test)) # -
2-Nature-Language-Process-Text-Analysis-Classification.ipynb
# --- # jupyter: # jupytext: # formats: ipynb,py:light # 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 seaborn as sns from os import makedirs from os.path import join, exists from nilearn.plotting import plot_connectome, plot_roi, find_parcellation_cut_coords import bct import datetime from nilearn.mass_univariate import permuted_ols from scipy.stats import pearsonr, spearmanr from sklearn.impute import KNNImputer sns.set(context='poster', style='ticks') # + crayons_l = sns.crayon_palette(['Vivid Tangerine', 'Cornflower']) crayons_d = sns.crayon_palette(['Brick Red', 'Midnight Blue']) grays = sns.light_palette('#999999', n_colors=3, reverse=True) f_2 = sns.crayon_palette(['Red Orange', 'Vivid Tangerine']) m_2 = sns.crayon_palette(['Cornflower', 'Cerulean']) # - def jili_sidak_mc(data, alpha): import math import numpy as np mc_corrmat = data.corr() mc_corrmat.fillna(0, inplace=True) eigvals, eigvecs = np.linalg.eig(mc_corrmat) M_eff = 0 for eigval in eigvals: if abs(eigval) >= 0: if abs(eigval) >= 1: M_eff += 1 else: M_eff += abs(eigval) - math.floor(abs(eigval)) else: M_eff += 0 print('Number of effective comparisons: {0}'.format(M_eff)) # and now applying M_eff to the Sidak procedure sidak_p = 1 - (1 - alpha)**(1/M_eff) if sidak_p < 0.00001: print('Critical value of {:.3f}'.format( alpha), 'becomes {:2e} after corrections'.format(sidak_p)) else: print('Critical value of {:.3f}'.format( alpha), 'becomes {:.6f} after corrections'.format(sidak_p)) return sidak_p, M_eff # + subjects = ['101', '102', '103', '104', '106', '107', '108', '110', '212', '213', '214', '215', '216', '217', '218', '219', '320', '321', '322', '323', '324', '325', '327', '328', '329', '330', '331', '332', '333', '334', '335', '336', '337', '338', '339', '340', '341', '342', '343', '344', '345', '346', '347', '348', '349', '350', '451', '452', '453', '455', '456', '457', '458', '459', '460', '462', '463', '464', '465', '467', '468', '469', '470', '502', '503', '571', '572', '573', '574', '575', '577', '578', '579', '580', '581', '582', '584', '585', '586', '587', '588', '589', '590', '591', '592', '593', '594', '595', '596', '597', '598', '604', '605', '606', '607', '608', '609', '610', '611', '612', '613', '614', '615', '616', '617', '618', '619', '620', '621', '622', '623', '624', '625', '626', '627', '628', '629', '630', '631', '633', '634'] #subjects = ['101', '102'] sink_dir = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/data/output' fig_dir = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/figures/' shen = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/shen2015_2mm_268_parcellation.nii.gz' craddock = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/craddock2012_tcorr05_2level_270_2mm.nii.gz' masks = ['shen2015', 'craddock2012'] tasks = {'retr': [{'conditions': ['Physics', 'General']}, {'runs': [0, 1]}], 'fci': [{'conditions': ['Physics', 'NonPhysics']}, {'runs': [0, 1, 2]}]} sessions = [0, 1] sesh = ['pre', 'post'] conds = ['high-level', 'lower-level'] iqs = ['VCI', 'WMI', 'PRI', 'PSI', 'FSIQ'] index = pd.MultiIndex.from_product([subjects, sessions, tasks, conds, masks], names=['subject', 'session', 'task', 'condition', 'mask']) # - data_dir = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/data' b_df = pd.read_csv( join(data_dir, 'rescored', 'physics_learning-nonbrain_OLS-imputed.csv'), index_col=0, header=0) b_df['SexXClass'] = b_df['F'] * b_df['Mod'] for iq in iqs: b_df['{0}2XSex'.format(iq)] = b_df['F'] * b_df['{0}2'.format(iq)] b_df['{0}2XClass'.format(iq)] = b_df['Mod'] * b_df['{0}2'.format(iq)] b_df['{0}2XClassXSex'.format(iq)] = b_df['F'] * b_df['Mod'] * b_df['{0}2'.format(iq)] b_df['delta{0}XSex'.format(iq)] = b_df['F'] * b_df['delta{0}'.format(iq)] b_df['delta{0}XClass'.format(iq)] = b_df['Mod'] * b_df['delta{0}'.format(iq)] b_df['delta{0}XClassXSex'.format(iq)] = b_df['F'] * b_df['Mod'] * b_df['delta{0}'.format(iq)] head_size = pd.read_csv(join( data_dir, 'head-size_2019-05-29 15:19:53.287525.csv'), index_col=0, header=0) head_size['normalized head size'] = (head_size['average_head_size']-np.mean( head_size['average_head_size']))/np.std(head_size['average_head_size']) # + fd = pd.read_csv(join( data_dir, 'avg-fd-per-condition-per-run_2019-05-29.csv'), index_col=0, header=0) fd['normalized fd'] = ( fd['average fd']-np.mean(fd['average fd']))/np.std(fd['average fd']) retr_fd = fd[fd['task'] == 'retr'] fci_fd = fd[fd['task'] == 'fci'] df_pivot = retr_fd[retr_fd['condition'] == 'high-level'].reset_index() retr_phys_fd = df_pivot.pivot( index='subject', columns='session', values='average fd') retr_phys_fd.rename( {'pre': 'pre phys retr fd', 'post': 'post phys retr fd'}, axis=1, inplace=True) df_pivot = retr_fd[retr_fd['condition'] == 'lower-level'].reset_index() retr_genr_fd = df_pivot.pivot( index='subject', columns='session', values='average fd') retr_genr_fd.rename( {'pre': 'pre gen retr fd', 'post': 'post gen retr fd'}, axis=1, inplace=True) df_pivot = fci_fd[fci_fd['condition'] == 'high-level'].reset_index() fci_phys_fd = df_pivot.pivot( index='subject', columns='session', values='average fd') fci_phys_fd.rename( {'pre': 'pre phys fci fd', 'post': 'post phys fci fd'}, axis=1, inplace=True) df_pivot = fci_fd[fci_fd['condition'] == 'lower-level'].reset_index() fci_ctrl_fd = df_pivot.pivot( index='subject', columns='session', values='average fd') fci_ctrl_fd.rename( {'pre': 'pre ctrl fci fd', 'post': 'post ctrl fci fd'}, axis=1, inplace=True) # - # rest_fd = pd.read_csv( # join(data_dir, 'avg-fd-per-run-rest_2019-05-31.csv'), index_col=0, header=0) # rest_fd['normalized fd'] = ( # rest_fd['average fd']-np.mean(rest_fd['average fd']))/np.std(rest_fd['average fd']) # # df_pivot = rest_fd.reset_index() # rest_fd = df_pivot.pivot( # index='subject', columns='session', values='normalized fd') # rest_fd.rename({'pre': 'pre rest fd', 'post': 'post rest fd'}, # axis=1, inplace=True) big_df = pd.concat([b_df, retr_phys_fd, retr_genr_fd, fci_phys_fd, fci_ctrl_fd], axis=1) # ## First, we'll test connectivity during the physics knowledge task # We'll run the permuted OLS regressions with few permutations for a first pass look at how brain connectivity explains variance in different subscores of the WAIS. Significant regressions at this step will be re-run later with more permutations, for more accurate <i>p</i>- and <i>t</i>-values. This is a more efficient use of computational resources than running all possible regressions with many permutations right off the bat. # + # read in every person's connectivity matrix (yikes) # one task & condition at a time, I think. otherwise it becomes a memory issue post_retr_conn = pd.DataFrame(columns=np.arange(0, 268**2)) for subject in subjects: try: corrmat = np.genfromtxt(join(sink_dir, 'corrmats', '{0}-session-1_retr-Physics_shen2015-corrmat.csv'.format(subject)), delimiter=' ') post_retr_conn.at[subject] = np.ravel(corrmat, order='F') except Exception as e: print(subject, e) # - brain_impute = KNNImputer(n_neighbors=5, weights='distance') imp_conns = brain_impute.fit_transform(post_retr_conn) imp_conn_df = pd.DataFrame(data=imp_conns, columns=post_retr_conn.columns, index=post_retr_conn.index) for column in imp_conn_df.columns: num = np.nonzero(imp_conn_df[column].values)[0].shape if num[0] <= 5: imp_conn_df.drop(column, axis=1, inplace=True) # + big_df.index = big_df.index.astype(int) imp_conn_df.index = post_retr_conn.index.astype(int) imp_conn_df = imp_conn_df.astype('float') all_data = pd.concat([big_df, imp_conn_df], axis=1) all_data.dropna(how='any', axis=0, inplace=True) conns = list(set(imp_conn_df.columns)) # + sig = {} n_perm = 10000 retr_iqs = ['VCI2', 'WMI2', 'FSIQ2', 'deltaWMI'] for iq in retr_iqs: p, t, _ = permuted_ols(all_data['{0}'.format(iq)].values, all_data[conns].values, all_data[['{0}XSex'.format(iq), '{0}XClass'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys retr fd']].values, n_perm=n_perm) sig['post (IQ): {0}'.format(iq)] = np.max(p[0]) # if np.max(p) > 1: # nodaleff_sig['{0}2 {1} p'.format(iq, key)] = p.T # nodaleff_sig['{0}2 {1} t'.format(iq, key)] = t.T p, t, _ = permuted_ols(all_data['{0}XSex'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XClass'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys retr fd']].values, n_perm=n_perm) sig['post (IQXSex): {0}'.format(iq)] = np.max(p[0]) p, t, _ = permuted_ols(all_data['{0}XClass'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XSex'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys retr fd']].values, n_perm=n_perm) sig['post (IQXClass): {0}'.format(iq)] = np.max(p[0]) p, t, _ = permuted_ols(all_data['{0}XClassXSex'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XSex'.format(iq), '{0}XClass'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys retr fd']].values, n_perm=n_perm) sig['post (IQXSexXClass): {0}'.format(iq)] = np.max(p[0]) # - sig # ### For all significant OLS regressions, max p-value goes in a dataframe sessions = ['post', 'delta'] variables = ['IQ', 'IQXSex', 'IQXClass', 'IQXClassXSex'] index = pd.MultiIndex.from_product([sessions, iqs]) significant = pd.DataFrame(index=index) for key in sig.keys(): if sig[key] >= 1.5: #print(key, sig[key]) sig_keys = key.split(' ') sesh = sig_keys[0] iq = sig_keys[-1] variable = sig_keys[1].strip('():') significant.at[(sesh, iq), variable] = sig[key] significant.to_csv( join(sink_dir, 'whole_brain-retr-permuted_ols-most_sig_pval.csv')) sig_keys = significant.dropna(how='all').index print(sig_keys) keys = [] for i in np.arange(0, len(sig_keys)): if sig_keys[i][0] == 'post': keys.append(str(sig_keys[i][1] + '2')) if sig_keys[i][0] == 'delta': keys.append(str(sig_keys[i][0] + sig_keys[i][1])) shen_nii = '/Users/kbottenh/Dropbox/Projects/physics-retrieval/shen2015_2mm_268_parcellation.nii.gz' coordinates = find_parcellation_cut_coords(labels_img=shen_nii) datetime.datetime.now().strftime("%H:%M:%S") post_retr_conn = None # ## And now we do it all over again for FCI # + # read in every person's connectivity matrix (yikes) # one task & condition at a time, I think. otherwise it becomes a memory issue post_fci_conn = pd.DataFrame(columns=np.arange(0, 268**2)) for subject in subjects: try: corrmat = np.genfromtxt(join(sink_dir, 'corrmats', '{0}-session-1_fci-Physics_shen2015-corrmat.csv'.format(subject)), delimiter=' ') post_fci_conn.at[subject] = np.ravel(corrmat, order='F') except Exception as e: print(subject, e) # - brain_impute = KNNImputer(n_neighbors=5, weights='distance') imp_conns = brain_impute.fit_transform(post_fci_conn) imp_conn_df = pd.DataFrame(data=imp_conns, columns=post_fci_conn.columns, index=post_fci_conn.index) for column in imp_conn_df.columns: num = np.nonzero(imp_conn_df[column].values)[0].shape if num[0] <= 5: imp_conn_df.drop(column, axis=1, inplace=True) # + big_df.index = big_df.index.astype(int) imp_conn_df.index = post_fci_conn.index.astype(int) imp_conn_df = imp_conn_df.astype('float') all_data = pd.concat([big_df, imp_conn_df], axis=1) all_data.dropna(how='any', axis=0, inplace=True) conns = list(set(imp_conn_df.columns)) # + sig = {} n_perm = 10000 fci_iqs = ['VCI2', 'deltaPRI', 'deltaFSIQ'] for iq in fci_iqs: p, t, _ = permuted_ols(all_data['{0}'.format(iq)].values, all_data[conns].values, all_data[['{0}XSex'.format(iq), '{0}XClass'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys fci fd']].values, n_perm=n_perm, verbose=2, n_jobs=2) sig['post (IQ): {0}'.format(iq)] = np.max(p[0]) # if np.max(p) > 1: # nodaleff_sig['{0}2 {1} p'.format(iq, key)] = p.T # nodaleff_sig['{0}2 {1} t'.format(iq, key)] = t.T p, t, _ = permuted_ols(all_data['{0}XSex'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XClass'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys fci fd']].values, n_perm=n_perm, verbose=2) sig['post (IQXSex): {0}'.format(iq)] = np.max(p[0]) p, t, _ = permuted_ols(all_data['{0}XClass'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XSex'.format(iq), '{0}XClassXSex'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys fci fd']].values, n_perm=n_perm, verbose=2) sig['post (IQXClass): {0}'.format(iq)] = np.max(p[0]) p, t, _ = permuted_ols(all_data['{0}XClassXSex'.format(iq)].values, all_data[conns].values, all_data[['{0}'.format(iq), '{0}XSex'.format(iq), '{0}XClass'.format(iq), 'F', 'StrtLvl', 'SexXClass', 'Age', 'Mod', 'post phys fci fd']].values, n_perm=n_perm, verbose=2) sig['post (IQXSexXClass): {0}'.format(iq)] = np.max(p[0]) # - sig sessions = ['post', 'delta'] variables = ['IQ', 'IQXSex', 'IQXClass', 'IQXClassXSex'] index = pd.MultiIndex.from_product([sessions, iqs]) significant = pd.DataFrame(index=index) for key in sig.keys(): if sig[key] >= 1.5: #print(key, sig[key]) sig_keys = key.split(' ') sesh = sig_keys[0] iq = sig_keys[-1] variable = sig_keys[1].strip('():') significant.at[(sesh, iq), variable] = sig[key] significant.to_csv( join(sink_dir, 'whole_brain-fci-permuted_ols-most_sig_pval.csv')) sig_keys = significant.dropna(how='all').index print(sig_keys) keys = [] for i in np.arange(0, len(sig_keys)): if sig_keys[i][0] == 'post': keys.append(str(sig_keys[i][1] + '2')) if sig_keys[i][0] == 'delta': keys.append(str(sig_keys[i][0] + sig_keys[0][1]))
examples/statistics/poststats_network_conn-outdated.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:larval_gonad] # language: python # name: conda-env-larval_gonad-py # --- # # Figures for BSC # Brian requested the following for the BSC: # # * heatmaps and clusters of scRNA. # * X, Y 4th chromosome expression patterns. # + import os import sys import re from pathlib import Path from itertools import zip_longest from yaml import load from IPython.display import display, HTML, Markdown import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.lines import Line2D import seaborn as sns # Project level imports from larval_gonad.notebook import Nb # - # Setup notebook nbconfig = Nb.setup_notebook(seurat_dir='../output/scrnaseq-wf/scrnaseq_combine_force') clusters = ( nbconfig.seurat.get_clusters('res.0.6') .map(nbconfig.short_cluster_annot) .pipe(lambda x: x[x != 'UNK']) .astype('category') .cat.as_ordered() .cat.reorder_categories(nbconfig.short_cluster_order) .to_frame() .assign(colors=lambda df: df.cluster.map(dict(zip(nbconfig.short_cluster_order, nbconfig.colors['clusters'])))) .rename_axis('cell_id') ) tsne = ( nbconfig.seurat.get_tsne() .rename_axis('cell_id') .merge(clusters, on='cell_id') ) def make_list(list_like): return np.array( list( zip_longest(list_like[:4], list_like[4:8], [list_like[-1]]) ) ).flatten().tolist() # + fig, ax = plt.subplots(figsize=(8, 8)) ax.scatter(tsne.tSNE_1, tsne.tSNE_2, s=20, c=tsne.colors) # clean up axis ax.set_aspect('equal') sns.despine(fig=fig, left=True, bottom=True) plt.setp(ax, yticks=[], xticks=[]); # legend legend_elements = [ #Patch(facecolor=color, edgecolor='k', label=f'{lclus} ({sclus})') Line2D([0], [0], marker='o', color=(1, 1, 1, 0), markeredgecolor=color, markerfacecolor=color, markersize=10, label=f'{lclus} ({sclus})') for sclus, lclus, color in zip(make_list(nbconfig.short_cluster_order), make_list(nbconfig.cluster_order[:9]), make_list(nbconfig.colors['clusters'][:9])) if sclus is not None ] ax.legend(handles=legend_elements, loc='lower center', ncol=4, bbox_to_anchor=[0.5, 1], facecolor=None) for clus, row in tsne.groupby('cluster').agg({'tSNE_1': np.mean, 'tSNE_2': np.mean}).iterrows(): plt.text(row.tSNE_1, row.tSNE_2, clus, backgroundcolor=(1, 1, 1, .9), ha='center', va='center') plt.tight_layout() plt.savefig('../output/notebook/2019-02-11_tsne.png') # - zscores = ( pd.read_parquet('../output/scrnaseq-wf/tpm_zscore_w_rep.parquet') .loc[:, nbconfig.sel_cluster_order_w_rep] ) with open('../paper_submission/config.yaml') as fh: lit_genes = load(fh.read())['lit_genes'] lit_fbgn = list(map(lambda x: nbconfig.symbol2fbgn[x], lit_genes)) lit_zscores = zscores.reindex(lit_fbgn).rename(index=nbconfig.fbgn2symbol) lit_zscores long_to_short = dict(zip(nbconfig.sel_cluster_order, nbconfig.short_cluster_order)) def process_text(txt): match = re.match(f'(?P<type>.*?)-(?P<rep>rep\d)', txt) if match['rep'] == 'rep2': return long_to_short[match['type']] return '' # + fig, ax = plt.subplots(figsize=(8, 8)) sns.heatmap(lit_zscores, cmap='viridis', yticklabels=True, xticklabels=True, vmin=-3, vmax=3, cbar_kws=dict(label='Normalized Expression\n(z-score)'), ax=ax) # fix up x-axis labels = [ process_text(l.get_text()) for l in ax.get_xticklabels() ] ax.set_xticklabels(labels, rotation=0, fontdict=dict(size=18), ha='center', va='bottom'); ax.set_xlabel('') ax.xaxis.tick_top() # fix up y-axis labels = [ l.get_text() for l in ax.get_yticklabels() ] ax.set_yticklabels(labels, rotation=0, fontdict=dict(style='italic', size=18), va='center'); ax.set_ylabel('') # Add cluster lines loc = 3 for i in range(8): ax.axvline(loc, color='w', ls=':', lw=2) loc += 3 # Add cluster lines ax.axhline(2, color='w', ls=':', lw=2) ax.axhline(4, color='w', ls=':', lw=2) ax.axhline(7, color='w', ls=':', lw=2) ax.axhline(9, color='w', ls=':', lw=2) ax.axhline(10, color='w', ls=':', lw=2) # increase cbar axis cbar = ax.collections[0].colorbar label = cbar.ax.get_ylabel() cbar.ax.set_ylabel(label, fontdict=dict(fontsize=18)) cbar.ax.tick_params(labelsize=14) # save figure plt.savefig('../output/notebook/2019-02-11_lit_genes.png') # - from sklearn.cluster import KMeans tpm = pd.read_parquet('../output/scrnaseq-wf/tpm_w_rep.parquet').loc[:, nbconfig.sel_cluster_order_w_rep] X = tpm.values kmeans = KMeans(n_clusters=9) gene_clusters = kmeans.fit_predict(X) zscores_kmeans = zscores.iloc[np.argsort(gene_clusters), :] fig, ax = plt.subplots(figsize=(8, 8)) sns.heatmap(zscores_kmeans, cmap='viridis', yticklabels=False, xticklabels=True, vmin=-3, vmax=3, cbar_kws=dict(label='Normalized Expression\n(z-score)'), ax=ax) # + # fix up x-axis labels = [ process_text(l.get_text()) for l in ax.get_xticklabels() ] ax.set_xticklabels(labels, rotation=0, fontdict=dict(size=18), ha='center', va='bottom'); ax.set_xlabel('') ax.xaxis.tick_top() # fix up y-axis labels = [ l.get_text() for l in ax.get_yticklabels() ] ax.set_yticklabels(labels, rotation=0, fontdict=dict(style='italic', size=18), va='center'); ax.set_ylabel('') # Add cluster lines loc = 3 for i in range(8): ax.axvline(loc, color='w', ls=':', lw=2) loc += 3 # Add cluster lines ax.axhline(2, color='w', ls=':', lw=2) ax.axhline(4, color='w', ls=':', lw=2) ax.axhline(7, color='w', ls=':', lw=2) ax.axhline(9, color='w', ls=':', lw=2) ax.axhline(10, color='w', ls=':', lw=2) # increase cbar axis cbar = ax.collections[0].colorbar label = cbar.ax.get_ylabel() cbar.ax.set_ylabel(label, fontdict=dict(fontsize=18)) cbar.ax.tick_params(labelsize=14) # save figure plt.savefig('../output/notebook/2019-02-11_all_genes.png') # -
notebook/2019-02-11_BSC_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 # --- # + # 20 Apr 2018 # # plot the PV snapshots from pydra_misc import read_qq import matplotlib.pyplot as plt import numpy as np from casl import parameters # + kt = 101 data_dir = "/network/group/aopp/oceans/DPM004_MAK_GEOMET/hydra_data/hydra/ca/channel/qg2l/casl/jet/code_testing/nx128ny64hb0.50kd20.0bdpi0.8w0.50r001/" # data_dir = "/home/julian/data/hydra_data/jet/nx128ny64hb0.50kd20.0bdpi0.8w0.50r001/" t_now, qq = read_qq(data_dir, parameters.nx, parameters.ny, kt) x_vec = np.linspace(0, parameters.ellx, parameters.nx) y_vec = np.linspace(0, parameters.elly, parameters.ny + 1) # swap axis to have the indexing consistent with the Fortran code main_invert (y, x, layers) qq = np.swapaxes(qq, 0, 1) fig = plt.figure(figsize=(10, 7)) ax1 = plt.subplot(2, 1, 1) plt.contourf(x_vec, y_vec, qq[:, :, 0], 31, cmap = "RdBu_r") plt.title(r"qq1, t = %g" % t_now) ax2 = plt.subplot(2, 1, 2) plt.contourf(x_vec, y_vec, qq[:, :, 1], 31, cmap = "RdBu_r") plt.title(r"qq2, t = %g" % t_now) # -
wrapper/plot_qq_snapshot.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/sebastianoscarlopez/learning-deep-learning/blob/master/digits_recognition.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="7HP-Dh_6ZckV" colab_type="text" # # Description # # Digits recognition it is called the Hello World of Neural Network. # # Made using Python, numpy applied to MNIST dataset. # # It example is based on http://neuralnetworksanddeeplearning.com/chap1.html # + [markdown] colab_type="text" id="wf2jrkItPrkd" # # Preparation # + [markdown] id="OjWQpXIVQAHM" colab_type="text" # ## Base libraries # + id="V6rkxiBZA_Tf" colab_type="code" colab={} # %tensorflow_version 2.x # + id="UBBnR-Fop9OL" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="ac7019cf-ef8d-406d-aaea-1e47e0a9f3ee" import numpy as np import matplotlib.pyplot as plt import pickle import os from google.colab import drive drive.mount('/content/gdrive', force_remount=True) # + [markdown] id="E3-sDpO9PtIS" colab_type="text" # ## Load data # + [markdown] id="YC_M5N7_QNN1" colab_type="text" # **mnist_loader** # # A library to load the MNIST image $28*28$ with digits # + [markdown] id="Oc7UHuIB0EX-" colab_type="text" # data stored on training_data (60%) test_data (10%), array image rearrange in vector of 784 # + id="hiQm4nv81nr-" colab_type="code" colab={} from keras.datasets import mnist # + [markdown] id="30VBYRYPZhAc" colab_type="text" # unit vector with a 1.0 in the jth position and zeroes elsewhere. # # Output layer are 10 neurons representing numbers from 0 to 9 # + id="yIA70eakY4oB" colab_type="code" colab={} def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.""" e = np.zeros((10, 1)) e[j] = 1.0 return e # + id="sWfkDgb7A0fp" colab_type="code" colab={} (x_train, y_train), (x_test, y_test) = mnist.load_data() training_inputs = [ np.reshape(x, (784, 1)) for x in x_train ] training_results = [ vectorized_result(y) for y in y_train ] training_data = list(zip(training_inputs, training_results))#list(map(lambda x, y: [x, y], training_inputs, training_results)) test_inputs = [ np.reshape(x, (784, 1)) for x in x_test ] test_data = list(zip(test_inputs, y_test)) #list(map(lambda x, y: [x, y], test_inputs, y_test)) # + [markdown] id="5rl7Ib6hrPWy" colab_type="text" # # Network design # + [markdown] id="kZIlym0zrtBr" colab_type="text" # Class wich made the network. The **sizes** parameter in its constructors is an array with the number of neurons on each layer # + id="5lSOB8zQrThg" colab_type="code" colab={} class Network(object): def __init__(self, sizes): self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y, 1) for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] # + [markdown] id="7blpLN3yy5nr" colab_type="text" # Trainning using Stochastic Gradient Descent. # # training_data" is a list of tuples "(x, y)" representing the training inputs and the desired outputs. # # epochs total of trainning. # # mini_batch_size indicated the group of data to be trainning together # # eta is the learning rate # + id="eGyngxxJyEfY" colab_type="code" colab={} class Network(Network): def SGD(self, training_data, epochs, mini_batch_size, eta, progress_callback = None): n = len(training_data) for j in range(epochs): np.random.shuffle(training_data) progress_callback(j, False) mini_batches = [ training_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if progress_callback: progress_callback(j, True) # + [markdown] id="RLdL8ptkvE8b" colab_type="text" # Given the input $x$ returns the output vector # + id="bXUIKWDWvHIo" colab_type="code" colab={} class Network(Network): def feedforward(self, x): for b, w in zip(self.biases, self.weights): x = self.sigmoid(np.dot(w, x)+b) return x # + [markdown] id="5QBcS9JbaFHB" colab_type="text" # Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch # + id="tYqkuUl0Z6fl" colab_type="code" colab={} class Network(Network): def update_mini_batch(self, mini_batch, eta): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] # + [markdown] id="L_utRp-Vk5Fo" colab_type="text" # Return a tuple $\nabla a, \nabla b$ representing the gradient for the cost function $C_x$ # + id="h9sqqoMfbXfU" colab_type="code" colab={} class Network(Network): def backprop(self, x, y): nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = self.sigmoid(z) activations.append(activation) # backward pass delta = self.cost_derivative(activations[-1], y) * \ self.sigmoid_prime(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # Note that the variable l in the loop below is used a little # differently to the notation in Chapter 2 of the book. Here, # l = 1 means the last layer of neurons, l = 2 is the # second-last layer, and so on. It's a renumbering of the # scheme in the book, used here to take advantage of the fact # that Python can use negative indices in lists. for l in range(2, self.num_layers): z = zs[-l] sp = self.sigmoid_prime(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) # + [markdown] id="6aFCD3wUmm3m" colab_type="text" # Return the number of test inputs for which the neural network outputs the correct result. # # The output will to be the neuron in the final layer that has the highest activation. # + id="EIrLzk5Qm_o7" colab_type="code" colab={} class Network(Network): def evaluate(self, test_data): test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data] return sum(int(x == y) for (x, y) in test_results) # + [markdown] id="IL7f07tHnpPr" colab_type="text" # Return the vector of partial derivatives $\partial C_x \partial a$ for the output activations # + id="Bn6JLdDinrsQ" colab_type="code" colab={} class Network(Network): def cost_derivative(self, output_activations, y): return (output_activations-y) # + [markdown] id="RyP-PRcCshgu" colab_type="text" # Sigmoid neuron $\sigma(\zeta) = \frac{1}{1 + e^{-\zeta}}$ where $-\zeta = w.x + b$ # + id="h-sm7xB8sCyS" colab_type="code" colab={} class Network(Network): def sigmoid(self, z): return 1.0/(1.0+np.exp(-z)) # + [markdown] id="Y9DswPMXoryg" colab_type="text" # $f'(\sigma)$ # + id="EMGBhiecok9A" colab_type="code" colab={} class Network(Network): def sigmoid_prime(self, z): return self.sigmoid(z)*(1-self.sigmoid(z)) # + [markdown] id="e2yjgo3Ap6_d" colab_type="text" # # Network creation # + [markdown] id="b4tylZ4Urqjv" colab_type="text" # Network with 3 layers # input layer: $784 = 28 * 28$ # # Hidden layer: only one with 30 neurons # # Output layer: 10 neurons representing 0-9 # + id="CLxkisa-p6Gc" colab_type="code" colab={} net = Network([784, 30, 10]) # + [markdown] id="wxmhH3gsppJC" colab_type="text" # # Training # + id="wnWEKRoN5SQ7" colab_type="code" colab={} path_folder = '/content/gdrive/My Drive/Colab' model_name = 'digits_recognition.model' path_model = f'{path_folder}/{model_name}' # + id="l7UKiPVeDduO" colab_type="code" colab={} def save_model(): model_stream = open(path,"wb") current_model = [net.weights, net.biases] pickle.dump(current_model, model_stream) model_stream.close() # + id="q_saeoquR0FF" colab_type="code" colab={} def load_model(): print(path_model) model_stream = open(path_model,"rb") current_model = pickle.load(model_stream) model_stream.close() net.weights = current_model[0] net.biases = current_model[1] net.num_layers = len(net.weights) + 1 # + [markdown] id="x6q1DaxZn5XP" colab_type="text" # The network will be evaluated against the test data after each epoch. This is useful for tracking progress, but slows things down substantially. # It will save the model # + id="ScW01T-dmqFf" colab_type="code" colab={} def progress_callback(epoch, is_complete): save_model() if epoch == 0 and not is_complete: print(".Start {0} / {1}".format(net.evaluate(test_data), len(test_data))) if is_complete: print("Epoch {0}: {1} / {2}".format(epoch, net.evaluate(test_data), len(test_data))) # + [markdown] id="JaiJOBmnqsis" colab_type="text" # Load previous model saved # + id="26Dg0htKqn6V" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 34} outputId="7e079596-5e3b-4a2c-85f6-263cfa8f5c93" if os.path.exists(path_model): load_model() # + id="ubezplagpxNE" colab_type="code" outputId="9f6f38e7-5bb7-40b8-c0e4-f3eee54e8b41" colab={"base_uri": "https://localhost:8080/", "height": 392} net.SGD(training_data, 200, 100, 0.1, progress_callback) # + [markdown] id="k2lAcUShGx-P" colab_type="text" # A custom 5 digit for validate model # + id="W95pwAEDNLqu" colab_type="code" colab={} print(test_data[0][0].shape) # + id="eukAImeA6rOP" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 316} outputId="d56cf81f-8383-49b2-dbd6-c11ce33856cb" def validationData(): image_name = '5_2.bmp' path_image = f'{path_folder}/{image_name}' image_stream = open(path_image,"rb") ba = bytearray(image_stream.read()) pixels = np.flip(np.array(ba[len(ba)-784:]).reshape((28, 28)), 0) plt.imshow(pixels, cmap='gray') x = pixels.reshape((784,1)) result = net.sigmoid(np.dot(net.weights[0], x) + net.biases[0]) result = net.sigmoid(np.dot(net.weights[1], result) + net.biases[1]) result = np.argmax(result) print(result) plt.show() validationData() # + id="mZyYZDGP1BZQ" colab_type="code" colab={} def draw(input, label, output): image = np.reshape(input, (28, 28)) image = np.array(image, dtype='float') pixels = image.reshape((28, 28)) plt.imshow(pixels, cmap='gray') plt.show() print("{0} - {1}".format(label, output)) draw(test_data[0][0], test_data[0][1], self.evaluate(test_data))
digits_recognition.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 # --- # # Prototype hybrid embedding : data-parallel frequent categories and model- parallel infrequent categories import numpy as np # + class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' import matplotlib from matplotlib import pyplot as plt plt.rcParams['figure.figsize'] = [10, 6] font = {'family' : 'normal', 'weight' : 'normal', 'size' : 16} matplotlib.rc('font', **font) # + # utility functions from copy import deepcopy def flatten_data(data): # concatenate all iterations samples_data = np.concatenate([deepcopy(data[i][1]) for i in range(len(data))], axis=1) # data dimensions embedding_sizes = data[0][0] num_tables = samples_data.shape[0] num_samples = samples_data.shape[1] # flatten and make categories unique samples = np.zeros(num_tables * num_samples, dtype=np.int32) category_index_offset = 0 for j in range(num_tables): for i in range(num_samples): samples[i * num_tables + j] = (category_index_offset + samples_data[j, i]) category_index_offset += embedding_sizes[j] return samples # - # # Calibration - communication measurements # + node_list = [2, 4, 8, 16] # per gpu: D_ar = np.array([0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] )* 1024*1024 T_ar = np.array([ 31.940742, 36.368742, 46.126742, 77.696742, 103.154742, 124.293742, 191.450742, 331.715742, 611.883742, 1199.531742, 2225.175742, 4391.540742, 8586.129742]) # + # 4 nodes # The results of measuring the latencies for varying amount of data # per node? D_a2a_data = [] T_a2a_data = [] # 2 nodes: T_a2a_data.append( np.array( [69.71, 69.98, 67.27, 68.65, 67.98, 68.32, 66.96, 68.03, 67.47, 68.88, 69.02, 69.39, 71.76, 75.59, 84.35, 115.3, 166.4 ,261, 450.7], dtype=np.float64)) D_a2a_data.append( np.array( [64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216], dtype=np.float64)) # 4 nodes: D_a2a_data.append(np.array( [128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216 ], dtype=np.float64)) # T_a2a = np.array([116, 101, 101, 112, 101, 99, 103, 100, 102, 101, 270, 109, 107, 117, 159, 230, 369, 690]) T_a2a_data.append(np.array( [116, 101, 101, 112, 101, 99, 103, 100, 102, 101, 105, 109, 107, 117, 159, 230, 369, 690], dtype=np.float64)) # 8 nodes: # D_a2a_data.append(np.array( # [64, 128, 256, 512, 1024, 2048, 4096, 8192, # 16384, 32768, 65536, 131072, 262144, 524288, # 1048576, 2097152, 4194304, 8388608, 16777216], dtype=np.float64)) # T_a2a_data.append(np.array( # [0.14, 0.13, 212.2, 230.9, 201.9, 207.5, 190.4, # 193, 194.8, 187.7, 198.4, 392.8, 190.4, 190, # 212.5, 245.2, 376.4, 487.2, 858.1], dtype=np.float64)) D_a2a_data.append(np.array( [256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216], dtype=np.float64)) T_a2a_data.append(np.array( [212.2, 230.9, 201.9, 207.5, 190.4, 193, 194.8, 187.7, 198.4, 195, 190.4, 190, 212.5, 245.2, 376.4, 487.2, 858.1], dtype=np.float64)) # 16 nodes: # D_a2a_data.append(np.array( # [64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, # 32768, 65536, 131072, 262144, 524288, 1048576, # 2097152, 4194304, 8388608, 16777216], dtype=np.float64 # )) # T_a2a_data.append(np.array( # [0.12, 0.12, 0.13, 445.7, 496.8, 387.9, 397.3, 400.4, # 403.8, 391.3, 408.6, 402.8, 390.1, 406.1, 408.2, 432.2, # 481.4, 1136.2, 1210.3], dtype=np.float64 # )) D_a2a_data.append(np.array( [512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216], dtype=np.float64 )) T_a2a_data.append(np.array( [445.7, 496.8, 387.9, 397.3, 400.4, 403.8, 391.3, 408.6, 402.8, 390.1, 406.1, 408.2, 432.2, 481.4, 1136.2, 1210.3], dtype=np.float64 )) import matplotlib.pyplot as plt B_IB = 200e9 B_AR = 130e9 for i, num_nodes in enumerate(node_list): D_a2a = D_a2a_data[i] T_a2a = T_a2a_data[i] T_sol_a2a = 8 * D_a2a * (num_nodes-1) / num_nodes / B_IB * 1e6 T_sol_ar = D_ar / B_AR * 1e6 mark_a2a = T_sol_a2a > 10 mask_ar = T_sol_ar > 10 plt.title(f'calibration data {num_nodes} nodes') plt.plot(D_a2a, T_a2a, 'b.-', label='all-to-all latencies ($\mu s$)') plt.plot(D_a2a[mark_a2a], T_sol_a2a[mark_a2a], 'b--', label='all-to-all SOL') plt.plot(D_ar, T_ar, 'k.-', label='all reduce latencies ($\mu s$)') plt.plot(D_ar[mask_ar], T_sol_ar[mask_ar], 'k--', label='all-reduce SOL') plt.xscale('log') plt.yscale('log') plt.legend() plt.show() # - # # Data Reader # + import numpy as np label_dim = 1 dense_dim = 13 slot_num = 26 label_dtype = [(f"label_{i}", 'f4') for i in range(label_dim)] dense_dtype = [(f"dense_{i}", 'f4') for i in range(dense_dim)] sparse_dtype = [(f"sparse_{i}", 'i4') for i in range(slot_num)] dataset_dtype = np.dtype(label_dtype + dense_dtype + sparse_dtype) # dataset_fname = "/raid/datasets/criteo/mlperf/40m.limit_preshuffled/train_data.bin" # Set dataset path here dataset_fname = "/datasets/creito/train_data.bin" # dlcluster # + def memmap_dataset(fname): fp = np.memmap(fname, dtype=dataset_dtype, mode='r') num_samples = fp.size print(f"mmap file done samples: {num_samples}") return (fp, num_samples) nmap = memmap_dataset(dataset_fname) # - def read_a_batch(nmap, batch_id, batch_size): (fp, num_samples) = nmap max_range = min((batch_id + 1)*batch_size, num_samples) batch = np.array(fp[batch_id*batch_size : max_range]).tolist() sparse_batch = [s[label_dim + dense_dim : ] for s in batch] return np.array([*sparse_batch]) example_data = read_a_batch(nmap, 0, 65536) # Read 15 batches and format as old reader # Note: temporary to avoid touching too much of the existing code embed_sizes = np.array([39884407, 39043, 17289, 7420, 20263, 3, 7120, 1543, 63, 38532952, 2953546, 403346, 10, 2208, 11938, 155, 4, 976, 14, 39979772, 25641295, 39664985, 585935, 12972, 108, 36]) data = [] for i in range(15): data.append((embed_sizes, read_a_batch(nmap, i, 65536).T)) # # Initialize frequent categories # + from copy import deepcopy import numpy as np def interpolate_T(D, T, bytes_in): # Calibration data of communication times may be noisy data: # fit a straight line locally using a Guassion kernel and # evaluate the line at D=bytes_in # if zeros bytes, no communication will be performed and return t = 0 epsilon = 0.5 if bytes_in < epsilon or bytes_in < D[0] / 2: return 0. d_max = D[-1] # width of fit on logarithmic scale width_log = 2. num_points = D.size sigma = (bytes_in * width_log - bytes_in / width_log) / 2. kernel = np.exp(-(D-bytes_in)**2/(2*sigma*sigma)) # Solve # kernel * ( a D + b ) = kernel * T # for a and b using linear regression. M = np.zeros((num_points, 2), dtype=np.float64) M[:,0] = kernel * D M[:,1] = kernel # linear regression using Moore-Penrose inverse beta = np.dot(np.dot(np.linalg.inv(np.dot(M.T, M)), M.T), kernel * T) a = beta[0] b = beta[1] # evaluate interpolation and return interpolation t_comm_interpolated = a*bytes_in + b return t_comm_interpolated # - for i, num_nodes in enumerate(node_list): print(f"interpolation of calibration data for {num_nodes} nodes") D_a2a = D_a2a_data[i] T_a2a = T_a2a_data[i] N = 300 data_a2a = np.linspace(D_a2a[0], D_a2a[-1], N) t_a2a_int = np.zeros(N) for i, d in enumerate(data_a2a): t_a2a_int[i] = interpolate_T(D_a2a, T_a2a, d) data_ar = np.linspace(D_ar[0], D_ar[-1], N) t_ar_int = np.zeros(N) for i, d in enumerate(data_ar): t_ar_int[i] = interpolate_T(D_ar, T_ar, d) plt.subplot(121) plt.plot(D_a2a, T_a2a, 'k.-', label='calibration all-to-all') plt.plot(data_a2a, t_a2a_int, label='interpolation all-to-all') plt.plot(D_ar, T_ar, 'b.-', label='calibration all-reduce') plt.plot(data_ar, t_ar_int, 'r', label='interpolation all reduce') plt.title('calibration data') plt.xscale('log') plt.yscale('log') plt.xlabel('number of bytes per gpu') plt.ylabel('communication time ($\mu s$)') plt.legend() # plt.show() plt.subplot(122) # plt.plot(D_a2a, T_a2a, 'k.-', label='calibration all-to-all') plt.plot(data_a2a, t_a2a_int, label='interpolation all-to-all') # plt.plot(D_ar, T_ar, 'b.-', label='calibration all-reduce') plt.plot(data_ar, t_ar_int, 'r', label='interpolation all reduce') plt.title('interpolation of data') plt.xscale('log') plt.yscale('log') plt.xlabel('number of bytes per gpu') plt.legend() plt.tight_layout() plt.show() def initialize_frequent_categories(data, num_nodes, embedding_parameters, calibration_data): num_batches = len(data) batch_size = data[0][1].shape[1] embedding_sizes = data[0][0] num_tables = embedding_sizes.size #print('initializing frequent categories..') # get samples and category counts #print('flattening data..') samples = flatten_data(data) categories, counts = np.unique(samples, return_counts=True) #print('performing stats..') # sort counts and categories from most frequent to least frequent index_count_sort = np.argsort(counts) categories_sort = deepcopy(categories[index_count_sort])[::-1] counts_sort = deepcopy(counts[index_count_sort])[::-1] num_samples = num_tables * num_batches * batch_size ## plot stats: # plt.plot(np.cumsum(counts_sort) / num_samples*100, label='frequent categories') # plt.legend() # plt.show() # embedding parameters embedding_vec_size = embedding_parameters.embedding_vec_size data_element_size = embedding_parameters.data_element_size # calibration data D_a2a = calibration_data.D_a2a # unit : data in bytes per gpu total the all-to-all message size (# ranks x size) T_a2a = calibration_data.T_a2a # unit : time in microseconds D_ar = calibration_data.D_ar # unit : data in bytes per gpu T_ar = calibration_data.T_ar # unit : time in microseconds # some theoretical maxima B_a2a_max = 190e9 B_ar_max = 230e9 n_max = 0.1 * B_a2a_max / B_ar_max * num_nodes / (num_nodes-1) # node occupancy of the categories n_c = counts_sort / (num_batches * num_nodes) num_frequent_max = (np.argmax(n_c < n_max) + 1) #print('calculating communication times..') # calculate the communication times for all possible number of # frequent categories up to num_frequent_max communication_time = np.zeros(num_frequent_max) comm_time_ar = np.zeros(num_frequent_max) comm_time_a2a = np.zeros(num_frequent_max) for num_frequent_categories in range(num_frequent_max): # calculate all-to-all bytes bytes_a2a = (num_samples - np.sum(counts_sort[:num_frequent_categories]) ) * embedding_vec_size * data_element_size bytes_a2a_gpu = bytes_a2a / (num_batches * num_nodes) / 8 # calculate all-reduce bytes bytes_ar = num_frequent_categories * embedding_vec_size * data_element_size t_ar = interpolate_T(D_ar, T_ar, bytes_ar) t_a2a = 2*interpolate_T(D_a2a, T_a2a, bytes_a2a_gpu) # record data comm_time_ar[num_frequent_categories] = t_ar comm_time_a2a[num_frequent_categories] = t_a2a communication_time[num_frequent_categories] = t_ar + t_a2a num_frequent = int(np.argmin(communication_time) + 1) return num_frequent, categories_sort, counts_sort, communication_time, comm_time_ar, comm_time_a2a # + # test code class EmbeddingParameters: def __init__(self, embedding_vec_size=128, data_element_size=2): self.embedding_vec_size = embedding_vec_size self.data_element_size = data_element_size class CalibrationData: def __init__(self, D_ar, T_ar, D_a2a, T_a2a): self.D_ar = D_ar self.T_ar = T_ar self.D_a2a = D_a2a self.T_a2a = T_a2a import matplotlib plt.rcParams['figure.figsize'] = [14, 8] font = {'family' : 'normal', 'weight' : 'normal', 'size' : 16} matplotlib.rc('font', **font) # - for i, num_nodes in enumerate(node_list): D_a2a = D_a2a_data[i] T_a2a = T_a2a_data[i] print() print() print(f'{color.BOLD}{color.GREEN}Hybrid embedding communication optimization on {num_nodes} nodes{color.END}') N = 300 data_a2a = np.linspace(D_a2a[0], D_a2a[-1], N) t_a2a_int = np.zeros(N) for i, d in enumerate(data_a2a): t_a2a_int[i] = interpolate_T(D_a2a, T_a2a, d) data_ar = np.linspace(D_ar[0], D_ar[-1], N) t_ar_int = np.zeros(N) for i, d in enumerate(data_ar): t_ar_int[i] = interpolate_T(D_ar, T_ar, d) plt.subplot(121) plt.plot(D_a2a, T_a2a, 'k.-', label='calibration all-to-all') plt.plot(data_a2a, t_a2a_int, label='interpolation all-to-all') plt.plot(D_ar, T_ar, 'b.-', label='calibration all-reduce') plt.plot(data_ar, t_ar_int, 'r', label='interpolation all reduce') plt.title('calibration data') plt.xscale('log') plt.yscale('log') plt.xlabel('number of bytes per gpu') plt.ylabel('communication time ($\mu s$)') plt.legend() # plt.show() embedding_vec_size = 128 data_element_size = 2 num_frequent_categories, frequent_categories, counts_frequent_categories, communication_time, comm_time_ar, comm_time_a2a \ = initialize_frequent_categories( data, num_nodes, EmbeddingParameters(embedding_vec_size=embedding_vec_size, data_element_size=data_element_size), CalibrationData(D_ar, T_ar, D_a2a, T_a2a)) num_frequent = num_frequent_categories num_frequent_max = communication_time.size t_min = communication_time[num_frequent-1] plt.subplot(122) plt.title('intitialization frequent categories - communication time') plt.text(num_frequent-1, t_min+100, f'comm time = {t_min:4.0f} microseconds') plt.plot(range(num_frequent_max), communication_time, 'k-', label=f'communication time, num_frequent = {num_frequent:3,d}') plt.plot(range(num_frequent_max), comm_time_ar, 'r--', label=f'communication time all-reduce') plt.plot(range(num_frequent_max), comm_time_a2a, 'b--', label=f'communication time all-to-all') plt.plot(range(num_frequent_max), t_min*np.ones(num_frequent_max), 'k--') plt.xlabel('number of frequent categories') plt.ylabel('communication time ($\mu s$)') plt.legend() plt.tight_layout() plt.show() counts = counts_frequent_categories num_batches = len(data) batch_size = data[0][1].shape[1] num_tables = data[0][1].shape[0] num_samples = batch_size * num_batches * num_tables percentage_samples_ar = np.sum(counts[:num_frequent_categories]) / num_samples * 100 print(f'speedup hybrid model vs model-parallel : {color.BOLD}{communication_time[0] / communication_time[num_frequent_categories-1]:4.2f} X{color.END}') print() print(f'number of frequent categories = {color.BOLD}{color.BLUE}{num_frequent_categories:3,d}{color.END}') print(f'total communication time = {color.BOLD}{color.BLUE}{communication_time[num_frequent_categories-1]:4.0f} microseconds {color.END}(vs {communication_time[0]:4.0f} microseconds)') print() print(f'samples covered by all-reduce{color.BOLD} (data-parallel){color.END} = {percentage_samples_ar:2.1f} %') print(f'samples covered by all-to-all{color.BOLD} (model-parallel){color.END} = {100-percentage_samples_ar:2.1f} %') print() bytes_ar = num_frequent_categories * embedding_vec_size * data_element_size print(f'bytes per gpu into all-reduce : {int(bytes_ar):8,d} bytes per gpu') bytes_a2a = (num_samples - np.sum(counts[:num_frequent_categories]) ) * embedding_vec_size * data_element_size bytes_a2a_gpu = bytes_a2a / (num_batches * num_nodes) / 8 print(f'bytes per gpu into all-to-all : {int(bytes_a2a):8,d} bytes per gpu, equivalent rank size = {int(bytes_ar/(num_nodes*8)):6,d} bytes') print(f'') print() t_ar = interpolate_T(D_ar, T_ar, bytes_ar) latency_ar = (t_ar*1e-6 - bytes_ar / 130e9)*1e6 print(f'all-reduce communication time : {t_ar:3.1f} microseconds,\x1b[31m latency = {latency_ar:3.1f} microseconds\x1b[0m (assuming 130 GB/s algo bandwidth)') t_a2a = interpolate_T(D_a2a, T_a2a, bytes_a2a_gpu) latency_a2a = (t_a2a*1e-6 - bytes_a2a_gpu*(num_nodes-1)/num_nodes / 24e9)*1e6 print(f'all-to-all communication time : {t_a2a:3.1f} microseconds,\x1b[31m latency = {latency_a2a:3.1f} microseconds\x1b[0m (assuming 24 GB/s NIC-IB bandwidth)') print() print(f'latency all-reduce + 2 x latency all-to-all = {color.BOLD}\x1b[31m {latency_ar + 2*latency_a2a:3.1f} microseconds latency total\x1b[0m on {num_nodes}{color.END} nodes') # # Initialize data-structures # + # configure nodes and gpus class Gpu: def __init__(self): self.frequent_categories = None self.category_frequent_index = None self.frequent_embedding_vectors = None self.frequent_partial_gradients = None self.category_location = None self.node = None def init_embedding_cache(self, num_frequent, embedding_vec_size): self.num_frequent = num_frequent self.frequent_embedding_vectors = np.zeros(num_frequent*embedding_vec_size, dtype=np.float32) self.frequent_partial_gradients = np.zeros(num_frequent*embedding_vec_size, dtype=np.float32) class Node: def __init__(self, num_gpus): self.gpus = [Gpu() for i in range(num_gpus)] for i in range(num_gpus): self.gpus[i].gpu_id = i self.gpus[i].node = self # reference to this node class Network: def __init__(self, nodes): self.nodes = nodes def all_reduce(self): pass def all_to_all(self): pass # + # setup nodes, gpus and network: i_node = 1 # 4 nodes num_nodes = node_list[i_node] nodes = [Node(8) for i in range(num_nodes)] gpus = [gpu for node in nodes for gpu in node.gpus] num_gpus = len(gpus) for i in range(num_nodes): nodes[i].node_id = i network = Network(nodes) for node in nodes: print(f"Node {node.node_id} with gpu's {[gpu.gpu_id for gpu in node.gpus]}, reporting for duty!") for gpu in gpus: print(f"Gpu {gpu.gpu_id} on node {gpu.node.node_id}, reporting for duty!") print(f"network with nodes {[node.node_id for node in network.nodes]} reporting for duty!") # + print(f'{color.BOLD}{color.GREEN}Hybrid embedding communication optimization on {num_nodes} nodes{color.END}') print() print(f'Setting up data structures for run on {num_nodes} nodes') D_a2a = D_a2a_data[i_node] T_a2a = T_a2a_data[i_node] print(f'Initializing frequent categories..') embedding_vec_size = 128 data_element_size = 2 num_frequent_categories, frequent_categories, counts_frequent_categories, communication_time, comm_time_ar, comm_time_a2a \ = initialize_frequent_categories( data, num_nodes, EmbeddingParameters(embedding_vec_size=embedding_vec_size, data_element_size=data_element_size), CalibrationData(D_ar, T_ar, D_a2a, T_a2a)) # - num_frequent = num_frequent_categories t_min = communication_time[num_frequent-1] print(f"Number of frequent categories = {color.BOLD}{num_frequent:5,d}{color.END}, embedding communication time {color.BOLD}{t_min:4.0f}{color.END} microseconds") # ## category_frequent_index # + embedding_sizes = data[0][0] num_tables = embedding_sizes.size num_categories = np.sum(embedding_sizes) print(f'Total number of categories : {num_categories:8,d}, category_frequent_index array size : {num_categories*4/(1024*1024):4.2f} MB') category_frequent_index = num_categories * np.ones(num_categories, dtype=np.int32) frequent_categories = frequent_categories[:num_frequent] # initializing category_frequent_index : category_frequent_index[frequent_categories] = np.array(range(num_frequent), dtype=np.int32) # this array is identical on all gpu's : for gpu in gpus: gpu.category_frequent_index = category_frequent_index n_display = 20 print(f'{color.BOLD}{color.RED}category |-> frequent category cache index{color.END}') for category in range(n_display): frequent_category_cache_index = category_frequent_index[category] if frequent_category_cache_index < num_categories: print(f'category {color.BOLD}{category:3d}{color.END} |-> cache index {color.BOLD}{color.BLUE}{frequent_category_cache_index:6,d}{color.END}') else: print(f'category {color.BOLD}{category:3d}{color.END} |-> cache index {color.BOLD}{color.RED}END{color.END}') # - category_frequent_index.shape np.sum(category_frequent_index < num_categories) # initialize frequent_embedding_vectors # initialize frequent_partial_gradients for gpu in gpus: gpu.init_embedding_cache(num_frequent, embedding_vec_size) # + # %%time # takes a lot of time, there are many infrequent categories! (15 minutes) # category_location num_infrequent = num_categories - num_frequent category_location = num_categories * np.ones((num_categories,2), dtype=np.int32) #locations_infrequent = [ [int(np.floor(i/8)),i%8] for i in range(num_infrequent) ] infrequent_index = np.zeros(num_categories) infrequent_index[category_frequent_index == num_categories] = range(num_infrequent) for c in range(num_categories): if category_frequent_index[c] == num_categories: index = infrequent_index[c] category_location[c,:] = [index % num_gpus, index // num_gpus] # - for gpu in gpus: gpu.category_location = category_location n_display = 20 print(f'{color.BOLD}{color.RED}category |-> category location {color.END}') for category in range(n_display): location = category_location[category,:] if location[0] < num_categories: print(f'category {color.BOLD}{category:3d}{color.END} |-> category location {color.BOLD}{color.GREEN}{location}{color.END}') else: print(f'category {color.BOLD}{category:3d}{color.END} |-> category location {color.BOLD}{color.RED}END{color.END}') # + # multi-node: node_id, gpu_id # single-node: gpu_id, category_model_index # linear location index: # # multi-node: node_id * 8 + gpu_id # single-node: gpu_id * max_model_size + category_model_index # sample 3 in network 5: category 7 stored in model (gpu) 8 # + # HybridEmbedding: # # frequent_categories_ # category_frequent_index_ # category_location_ # # frequent_embedding_; # infrequent_embeddin_; # Forward: sample |-> batch embedding vectors in mlp (concatenation) # # data-parallel (all-reduce), model-parallel (all-to-all) # # # sample : 26 fields categorical feature => category # embedding vector category 0, embedding vector category 1, embedding vector category 2, ... # EmbeddingFrequent ( data-parallel, all-reduce ) # # frequent_embedding_vectors # frequent_partial_gradients # # stores the frequent embedding # update: reduces locally the frequent gradients into the frequent_partial_gradients array # frequent sample indices: update_sgd(sample_indices_frequent, samples_frequent_index, gradients_samples) # # all-reduce : frequent_partial_gradients # update the frequent_embedding_vectors # # EmbeddingInfrequent => # # store the infrequent categories # # infrequent_embedding_vectors # # # # local batch, global batch # # all-to-all forward # send buffer: # (I) entire batch |-> mark samples' categories that is placed here # create list of indices for entire batch, of samples' embedding vector to send # create offset per destination # receive buffer: # (II) local mlp - batch |-> sort by source ( doesn't need to be sort ) # # all-to-all backward # send buffer: (II) # receive buffer: (I) # # update infrequent embedding vectors # (I) |-> categories |-> where stored? samples_infrequent_index # update_sgd(sample_indices_infrequent, samples_infrequent_index, infrequent_embedding_vectors) # - # # Index calculations # ## Embedding # + from bisect import bisect_left def get_node_gpu(node_id, gpu_id): # not efficient, but that's not the point here! :P node = None gpu = None for node_ in nodes: if node_.node_id == node_id: node = node_ break for gpu_ in node.gpus: if gpu_.gpu_id == gpu_id: gpu = gpu_ break return node, gpu def get_network_id(node_id, gpu_id): for i in range(len(gpus)): if gpus[i].node.node_id == node_id and gpus[i].gpu_id == gpu_id: return i raise KeyError(f"Not found: node {node_id}, GPU {gpu_id}") def cub_DeviceSelect(gpu, samples, network_id): location = gpu.category_location[samples,:] samples_mask = (location[:,0] == network_id) samples_filter = np.r_[:samples.size][samples_mask] return samples_filter # model indices: forward-send, backward-receive def calculate_model_indices(samples, node_id, gpu_id): _, gpu = get_node_gpu(node_id, gpu_id) network_id = get_network_id(node_id, gpu_id) section_size = samples.size // num_gpus sample_model_indices = cub_DeviceSelect(gpu, samples, network_id) network_offset_model_indices = np.zeros(num_gpus, dtype=np.int32) for i in range(num_gpus): network_offset_model_indices[i] = bisect_left(sample_model_indices, i * section_size) return sample_model_indices, network_offset_model_indices # network indices: forward-receive, backward-send def calculate_network_indices(samples, node_id, gpu_id): _, gpu = get_node_gpu(node_id, gpu_id) section_size = samples.size // num_gpus network_id = get_network_id(node_id, gpu_id) start_idx = network_id * section_size end_idx = min((network_id + 1) * section_size, samples.size) sub_batch = samples[start_idx:end_idx] location = gpu.category_location[sub_batch,:] samples_mask = location[:,0] < num_categories infrequent_indices = deepcopy(np.r_[:sub_batch.size][samples_mask]) network_indices = deepcopy(location[:, 0][samples_mask]) sorted_indices = np.array(sorted(zip(network_indices, infrequent_indices), key=lambda x: x[0])) sample_network_offsets = np.zeros(num_gpus, dtype=np.int32) if len(network_indices): sample_network_indices = sorted_indices[:,1] for i in range(num_gpus): sample_network_offsets[i] = bisect_left(sorted_indices[:,0], i) else: sample_network_indices = np.zeros(0) return sample_network_indices, sample_network_offsets # - iteration = 0 batch = flatten_data([data[0]]) # + model_indices = {} model_indices_offsets = {} for node_ in nodes: for gpu_ in node_.gpus: node_id = node_.node_id gpu_id = gpu_.gpu_id idx, off = calculate_model_indices(batch, node_id, gpu_id) model_indices[(node_id, gpu_id)] = idx model_indices_offsets[(node_id, gpu_id)] = off # print(model_indices) # print(model_indices_offsets) network_indices = {} network_indices_offsets = {} for node_ in nodes: for gpu_ in node_.gpus: node_id = node_.node_id gpu_id = gpu_.gpu_id idx, off = calculate_network_indices(batch, node_id, gpu_id) network_indices[(node_id, gpu_id)] = idx network_indices_offsets[(node_id, gpu_id)] = off # print(network_indices) # print(network_indices_offsets) # - # frequent sample indices def calculate_frequent_sample_indices(samples, node_id, gpu_id): _, gpu = get_node_gpu(node_id, gpu_id) section_size = samples.size // num_gpus network_id = get_network_id(node_id, gpu_id) start_idx = network_id * section_size end_idx = min((network_id + 1) * section_size, samples.size) sub_batch = samples[start_idx:end_idx] freq_indices = gpu.category_frequent_index[sub_batch] samples_mask = freq_indices < num_categories frequent_sample_indices = deepcopy(np.r_[:sub_batch.size][samples_mask]) return frequent_sample_indices # + frequent_sample_indices = {} for node_ in nodes: for gpu_ in node_.gpus: node_id = node_.node_id gpu_id = gpu_.gpu_id frequent_sample_indices[(node_id, gpu_id)] = \ calculate_frequent_sample_indices(batch, node_id, gpu_id) # print(frequent_sample_indices) # - # This computation takes quite a long time # TODO: numpify more for better performance def calculate_model_cache_indices(samples, node_id, gpu_id): _, gpu = get_node_gpu(node_id, gpu_id) section_size = samples.size // num_gpus model_id = get_network_id(node_id, gpu_id) num_frequent_per_model = num_frequent // num_gpus # Compute the mask network_frequent_mask = np.zeros(num_gpus * num_frequent_per_model, dtype=bool) for i in range(num_gpus): freq_index = gpu.category_frequent_index[ samples[i * section_size:(i+1)*section_size]] for idx in freq_index: if idx < num_frequent and idx // num_frequent_per_model == model_id: network_frequent_mask[i * num_frequent_per_model + idx % num_frequent_per_model] = True # Select categories according to the mask model_cache_indices = np.r_[:num_gpus * num_frequent_per_model][network_frequent_mask] # Compute offsets model_cache_indices_offsets = np.zeros(num_gpus + 1, dtype=np.int32) for i in range(num_gpus): model_cache_indices_offsets[i] = bisect_left(model_cache_indices, i * num_frequent_per_model) model_cache_indices_offsets[num_gpus] = model_cache_indices.size # Convert to buffer indices model_cache_indices = (model_cache_indices % num_frequent_per_model + model_id * num_frequent_per_model) return model_cache_indices, model_cache_indices_offsets # + model_cache_indices = {} model_cache_indices_offsets = {} for node_ in nodes: for gpu_ in node_.gpus: node_id = node_.node_id gpu_id = gpu_.gpu_id idx, off = calculate_model_cache_indices(batch, node_id, gpu_id) model_cache_indices[(node_id, gpu_id)] = idx model_cache_indices_offsets[(node_id, gpu_id)] = off # print(model_cache_indices) # print(model_cache_indices_offsets) # - def calculate_network_cache_indices(samples, node_id, gpu_id): _, gpu = get_node_gpu(node_id, gpu_id) model_id = get_network_id(node_id, gpu_id) network_mask = np.zeros(num_frequent, dtype=bool) section_size = samples.size // num_gpus sample_mlp_batch = samples[model_id * section_size:min(samples.size,(model_id + 1)*section_size)] freq_index = gpu.category_frequent_index[sample_mlp_batch] for index in freq_index: if index < num_frequent: network_mask[index] = True network_cache_indices = np.r_[:num_frequent][network_mask] # Compute offsets num_frequent_per_model = num_frequent // num_gpus network_cache_indices_offsets = np.zeros(num_gpus + 1, dtype=np.int32) for i in range(num_gpus): network_cache_indices_offsets[i] = bisect_left(network_cache_indices, i * num_frequent_per_model) network_cache_indices_offsets[num_gpus] = network_cache_indices.size return network_cache_indices, network_cache_indices_offsets, network_mask network_cache_indices = {} network_cache_indices_offsets = {} network_cache_masks = {} for node_ in nodes: for gpu_ in node_.gpus: node_id = node_.node_id gpu_id = gpu_.gpu_id idx, off, mask = calculate_network_cache_indices(batch, node_id, gpu_id) network_cache_indices[(node_id, gpu_id)] = idx network_cache_indices_offsets[(node_id, gpu_id)] = off network_cache_masks[(node_id, gpu_id)] = mask # + # embedding model forward: node_id = 0 gpu_id = 1 network_id = get_network_id(node_id, gpu_id) samples = flatten_data([data[0]]) # location_samples = category_location[samples,:] # sample_lin_location_index = np.zeros(samples.size, dtype=np.int32) # for i, category in enumerate(samples): # if category_location[category,0] < num_categories: # lin_location_index = category_location[category,0]*8 + category_location[category,1] # sample_lin_location_index[i] = lin_location_index # else: # sample_lin_location_index[i] = num_categories # model_lin_index = node_id * 8 + gpu_id # samples_mask = (sample_lin_location_index == model_lin_index) samples_mask = category_location[samples,0] == network_id samples_mask np.sum(samples_mask) # - data[0][1] # # Forward send # + # calculate # - # # Forward receive # # Backward reduce # # Backward send # # # Backward receive nn = 16 55*1024*26*128*2/(nn*nn*64)/4.4 # # Read 15 batches of 64k samples # + import os import numpy as np def read_variable(lines, indx): line_i = lines[indx] line_split = line_i.split() variable_name = line_split[0] num_data = int(line_split[1]) if num_data == 1: offset = 0 if len(line_split) == 3: data = np.int64(line_split[2]) offset = 0 else: offset = 1 data = np.int64(lines[indx+1]) return variable_name, data, indx + 1 + offset else: values = np.zeros(num_data, dtype=np.int64) for i in range(num_data): values[i] = np.int64(lines[indx+1+i]) return variable_name, values, indx + 1 + num_data def read_dlrm_data(folder_name): data = {} file_names = os.listdir(folder_name) for file_name in file_names: print(file_name) split_list = file_name.split("_") iteration = int(split_list[2]) gpu_id = int(split_list[4].split(".")[0]) # parse file fobj = open(os.path.join(folder_name, file_name), "r") lines = fobj.readlines() indx = 0 _, num_samples, indx = read_variable(lines, indx) _, slot_num, indx = read_variable(lines, indx) _, size_embedding, indx = read_variable(lines, indx) size_embeddings = size_embedding.astype(np.int64) _, categories_raw, indx = read_variable(lines, indx) categories = np.zeros( (slot_num, num_samples), dtype=np.int64 ) if slot_num > 1: for i in range(categories_raw.size): offset = 0 if slot_num > 1: offset = np.sum(size_embeddings[:i%slot_num]) #print(f"i mod 2 : {i%2}, i/2 : {np.int(np.floor(i / 2))}") categories[(i%slot_num), int(np.floor(i / 2))] = categories_raw[i] - offset else: categories = categories_raw.reshape((1, categories_raw.size)) data[(iteration, gpu_id)] = (num_samples, size_embeddings, categories) return data # - data_folder = os.path.join("/mnt/c/Users/dabel/Documents/mlperf/data/") data = read_dlrm_data(data_folder) # + iterations = {} # concatenate embeddings per iteration for iteration, gpu in data: if not iteration in iterations: iterations[iteration] = [gpu] else: iterations[iteration].append(gpu) iteration_numbers = [num for num in iterations] iteration_numbers = np.sort(iteration_numbers) #print(len(iteration_numbers), iteration_numbers) samples_iteration = [] for iteration in iteration_numbers: i_table = 0 embedding_sizes = [] data_iteration = np.zeros( (26, 65536), dtype=np.int64 ) for gpu in range(16): size_embeddings_gpu = data[(iteration, gpu)][1] num_tables_gpu = size_embeddings_gpu.size for i_table_gpu in range(num_tables_gpu): data_iteration[i_table,:] = data[(iteration, gpu)][2][i_table_gpu,:] if num_tables_gpu > 1: embedding_sizes.append(size_embeddings_gpu[i_table_gpu]) else: embedding_sizes.append(size_embeddings_gpu) i_table += 1 samples_iteration.append( (np.array(embedding_sizes), data_iteration) ) # - len(samples_iteration) samples_iteration[0][1].shape from copy import deepcopy samples = np.concatenate([deepcopy(samples_iteration[i][1]) for i in range(len(samples_iteration))], axis=1) samples samples.shape data = samples_iteration
Supermicro/benchmarks/dlrm/implementations/hugectr_J_2/notebooks/prototype_hybrid_embedding.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 # --- # # Tuning the Best CNN Models # # # In this notebook, I will select the top three best models and tune their hyperparameters to get the best fit. # # | Model | Accuracy | # | ---- | ---- | # | LogisticRegression | 0.792 | # | KNeighborsClassifier | 0.750 | # | SVC | 0.715 | # | LinearSVC | 0.741 | # | SGDClassifier | 0.359 | # | DecisionTreeClassifier | 0.803| # | RandomForestClassifier | 0.853 | # | BaggingClassifier | 0.822 | # | GradientBoostingClassifier | 0.786 | # | AdaBoostClassifier | 0.785 | # # DecisionTree, RandomForest, and Bagging have the best accuracy so these are the ones I will tune. # + import pandas as pd import nltk import numpy as np import seaborn as sns import matplotlib.pyplot as plt import re from nltk.stem import WordNetLemmatizer from nltk import word_tokenize from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV from sklearn import tree from sklearn import ensemble from sklearn.pipeline import Pipeline from sklearn.metrics import confusion_matrix, classification_report, mean_squared_error from math import sqrt # - cnn_df = pd.read_excel('../data/interim/cnn_ready_to_code.xlsx').drop(columns=['Unnamed: 0', 'Unnamed: 0.1']).fillna(0) cnn_df.head() y = np.array(cnn_df['isad']) X = cnn_df.drop(columns=['identifier', 'contributor', 'subjects', 'start_time', 'stop_time', 'runtime', 'isad']).dropna() X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=18) stop_words = stopwords.words('english') stop_words.extend(['from', 'subject', 're', 'edu', 'use', 'not', 'would', 'say', 'could', '_', 'be', 'know', 'good', 'go', 'get', 'do', 'done', 'try', 'many', 'some', 'nice', 'thank', 'think', 'see', 'rather', 'easy', 'easily', 'lot', 'lack', 'make', 'want', 'seem', 'run', 'need', 'even', 'right', 'line', 'even', 'also', 'may', 'take', 'come', 'hi', 'ha', 'le', 'u', 'wa', 'thi', 'to', 'one']) def clean_sent(sentences): for sent in sentences: sent = str(sent) sent = re.sub('\s+', ' ', sent) # remove newline chars sent = re.sub("\'", "", sent) # remove single quotes sent = re.sub("([\d,\,\./!#$%&\'\":;>\?@\[\]`)(\+])+", "", sent) # remove digits and remove punctuation sent = re.sub("([-])+", " ", sent) yield(sent) corpus_train = list(clean_sent(X_train.sentence.values.tolist())) corpus_test = list(clean_sent(X_test.sentence.values.tolist())) corpus_train[:5] # + #lemmatize before vectorizing class LemmaTokenizer: def __init__(self): self.wnl = WordNetLemmatizer() def __call__(self, doc): return [self.wnl.lemmatize(t) for t in word_tokenize(doc)] vect = TfidfVectorizer(tokenizer=LemmaTokenizer(), strip_accents='unicode', stop_words='english', min_df=2, max_df=0.3, ngram_range=(1,2)) # - X_train_bow = vect.fit_transform(corpus_train) X_test_bow = vect.transform(corpus_test) X_train_bow_df = pd.DataFrame(X_train_bow.toarray()) X_train_joined = X_train.reset_index().join(X_train_bow_df).drop(columns=['index']) X_test_bow_df = pd.DataFrame(X_test_bow.toarray()) X_test_joined = X_test.reset_index().join(X_test_bow_df).drop(columns=['index']) X_train_joined = X_train_joined.drop(columns=['sentence']) X_test_joined = X_test_joined.drop(columns=['sentence']) def plot_confusion_matrix(model, X, y): pred = model.predict(X) c=confusion_matrix(y, pred) sns.heatmap(c,cmap='BrBG',annot=True) print(c) plt.show() # + params = {'criterion' : ['gini', 'entropy'], 'splitter' : ['best', 'random'], 'max_depth' : [10, 50, 75, 100, 200], 'min_samples_split': [2, 5, 10]} dtc = tree.DecisionTreeClassifier(random_state=18) cv = GridSearchCV(dtc, params) cv.fit(X_train_joined, y_train) # Compute and print metrics print("Accuracy: {}".format(cv.score(X_test_joined, y_test))) print("Tuned Model Parameters: {}".format(cv.best_params_)) # - plot_confusion_matrix(cv, X_test_joined, y_test) rfc = ensemble.RandomForestClassifier(criterion='entropy', random_state=18) params = {'n_estimators': [10, 100, 500, 1000], 'max_depth' : [10, 50, 100, 200], 'max_features' : ['sqrt', 'log2', None], 'min_samples_split': [2, 5, 10]} cv = RandomizedSearchCV(rfc, params) #cv = GridSearchCV(rfc, params) cv.fit(X_train_joined, y_train) # Compute and print metrics print("Accuracy: {}".format(cv.score(X_test_joined, y_test))) print("Tuned Model Parameters: {}".format(cv.best_params_)) plot_confusion_matrix(cv, X_test_joined, y_test) # + rfc = ensemble.RandomForestClassifier(criterion='entropy', n_estimators=100, min_samples_split=2, max_features='sqrt', random_state=18) params = {'max_depth' : [150, 200, 300, 500]} #cv = RandomizedSearchCV(rfc, params) cv = GridSearchCV(rfc, params) cv.fit(X_train_joined, y_train) # Compute and print metrics print("Accuracy: {}".format(cv.score(X_test_joined, y_test))) print("Tuned Model Parameters: {}".format(cv.best_params_)) # - # That got worse, so let's say these parameters are the best: # # Tuned Model Parameters: {'n_estimators': 100, 'min_samples_split': 2, 'max_features': 'sqrt', 'max_depth': 200} # + bgc = ensemble.BaggingClassifier(random_state=18) params = {'n_estimators': [10, 100, 500, 1000], 'max_features' : [0.25, 0.5, 0.75, 1.0]} cv = RandomizedSearchCV(bgc, params) cv.fit(X_train_joined, y_train) # Compute and print metrics print("Accuracy: {}".format(cv.score(X_test_joined, y_test))) print("Tuned Model Parameters: {}".format(cv.best_params_)) # -
notebooks/Tuning CNN Models.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 # --- # # Simple Neural Network Project # ## We will analyze malicious sites and do simple machine learning # # ## I will demonstrate the neural network description and how to best process the model. # # ## I divided the project part by part, you can find out what part we did by looking at the title # import pandas as pd import numpy as np # ## Basic Data Analysis df = pd.read_excel("maliciousornot.xlsx") # most people using like this of course u can define data like DataFrame or as df # let see the data first 5 df.head() # let see last five df.tail() df.info(); # We have float and int values we can use all of them this data is cool df.describe() ## So Type data mean value means there is %38 percent malicious site in data df.corr()["Type"].sort_values() ## Let see the correlation # + import matplotlib.pyplot as plt plt.style.use("seaborn-whitegrid") import seaborn as sns # - ## Let see the correlation with visualization tool list1 = ["Type", "SOURCE_K", "NUMBER_SPECIAL_CHARACTERS", "SOURCE_APP_BYTES", "SOURCE_I","URL_LENGTH"] plt.figure(figsize=(15,7)) sns.heatmap(df[list1].corr(), annot = True, fmt = ".2f") plt.show() # + plt.figure(figsize=(15,9)) df.corr()["Type"].sort_values().plot(kind="bar") # + ## Let's see how many of each sns.countplot(x="Type", data = df) # - # Missing Value import missingno as msno msno.bar(df) ## Our data %100 percent is full no missing value a = list(df.columns.unique()) ## This part can show us every correlation by each, as you can see its very complicated plt.figure(figsize=(15,10)) sns.heatmap(df[a].corr(), annot = True, fmt = ".2f") plt.show() df.isnull().sum().sum() # No missing Value # # Machine Learning Part # + # Lets define our x and y value for machine learning # We will prepare a model according to its type and train it y = df["Type"].values x = df.drop("Type",axis = 1).values # - 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=42) # we will allocate thirty percent for the test value from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaler.fit(x_train) x_train = scaler.transform(x_train) x_test = scaler.transform(x_test) import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Dropout from tensorflow.keras.callbacks import EarlyStopping x_train.shape # ## Neural Network Part # # + model = Sequential() # we will use relu for activation its better then others and the first will have 30 neurons # Optimizer will be adam its also better then other model.add(Dense(units=30,activation = "relu")) model.add(Dense(units=15,activation = "relu")) model.add(Dense(units=15,activation = "relu")) model.add(Dense(units=1,activation = "sigmoid")) model.compile(loss="binary_crossentropy",optimizer = "adam") # - model.fit(x=x_train, y=y_train, epochs=700,validation_data=(x_test,y_test),verbose=1) # 700 epochs enough i think # There is no need to redefine the validation_data, we can also give it in the model # Verbose 1 its okay it will show us the loss value one by one # let's see the list model.history.history modelLoss = pd.DataFrame(model.history.history) # + modelLoss.plot(); # we expect these two very bad values ​​to be very close to each other, but they are # this means our neurons are not making accurate predictions # - # ### EarlyStopping Tool # + # We will use our early stop tool # will stop automatically after they start to be far from each other # it doesn't need to be epoch 700 # Lets define neural network again model = Sequential() model.add(Dense(units=30,activation = "relu")) model.add(Dense(units=15,activation = "relu")) model.add(Dense(units=15,activation = "relu")) model.add(Dense(units=1,activation = "sigmoid")) model.compile(loss="binary_crossentropy",optimizer = "adam") # - earlyStopping = EarlyStopping(monitor="val_loss",mode="min",verbose=1,patience=25) # using this we will provide what I said above model.fit(x=x_train, y=y_train, epochs = 700, validation_data = (x_test,y_test), verbose = 1, callbacks=[earlyStopping]) # using callbacks we can define earlystopping parameter # Let's observe the model again and make sure it works. modelLoss = pd.DataFrame(model.history.history) # + modelLoss.plot(); # looks fine but not very accurate still some error # - # ## DropOut Tool # + # we define this parameter under each neural network # This is doing the extraction of sixty percent of the incoming data, in fact over fifty percent can corrupt the data a little # But don't worry, our data is pretty solid model = Sequential() model.add(Dense(units=30,activation = "relu")) model.add(Dropout(0.6)) model.add(Dense(units=15,activation = "relu")) model.add(Dropout(0.6)) model.add(Dense(units=15,activation = "relu")) model.add(Dropout(0.6)) model.add(Dense(units=1,activation = "sigmoid")) model.compile(loss="binary_crossentropy",optimizer = "adam") # - model.fit(x=x_train, y=y_train, epochs = 700, validation_data = (x_test,y_test), verbose = 1, callbacks=[earlyStopping]) lossDf = pd.DataFrame(model.history.history) # + lossDf.plot(); # slightly better than before #zigzags are visible as data has been removed # - # now we can read our test values ​​to our neurons # In this way, we can calculate mathematically how many percent accuracy our model has. ouprrr = model.predict_classes(x_test) ouprrr from sklearn.metrics import classification_report, confusion_matrix # + print(classification_report(y_test,ouprrr)) # this great model has an accuracy of near precision 97% # - print(confusion_matrix(y_test,ouprrr)) df2 = pd.DataFrame(ouprrr) df2["y_test"] = df2 df2.head() df2.drop(df2.columns[[0]], axis = 1, inplace = True) df2.head() df3 = pd.DataFrame(x_test) rel = pd.concat([df3,df2],axis = 0) rel.head()
neuralnet.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 # --- # ## Summary # # --- # ## Imports # + import random from pathlib import Path import matplotlib as mpl import matplotlib.patches as patches import matplotlib.pyplot as plt import networkx as nx import numpy as np from IPython.display import SVG, set_matplotlib_formats # - set_matplotlib_formats("svg") NOTEBOOK_DIR = Path("xx_graphic_abstract") NOTEBOOK_DIR.mkdir(exist_ok=True) SVG("../docs/images/static/introduction/csps-protein-design.svg") labels = [ "A", "P", "G", "N", "A", "Q", "E", "V", "D", "S", "H", "Y", "L", "K", "E", "V", "E", "I", "R", "A", "W", "F", "S", "N", "T" ] print(len(labels)) G = nx.Graph() G.add_nodes_from(range(25)) assert G.number_of_nodes() == 25 edges_sequential = np.c_[ list(range(G.number_of_nodes() - 1)), list(range(1, G.number_of_nodes())) ].tolist() edges_contacts = [ [22, 0], [0, 21], [21, 2], [2, 20], [19, 7], [8, 18], [10, 18], [16, 14], [11, 16], [16, 20], [16, 23], [21, 17], ] G.add_edges_from(edges_sequential) G.add_edges_from(edges_contacts) angles = [ -20, -5, -20, -25, -30, 60, 60, 60, 80, 100, 100, 100, 160, 160, -150, -90, -45, -70, -90, -160, 160, 110, 110, 140, ] labels = {i: l for i, l in enumerate(labels)} assert len(angles) == G.number_of_nodes() - 1 # + starting_pos = [0, 2] length = 1 positions = [starting_pos] for angle in angles: dx = np.cos(np.deg2rad(angle)) * length dy = np.sin(np.deg2rad(angle)) * length new_pos = [positions[-1][0] + dx, positions[-1][1] + dy] positions.append(new_pos) # - color_given = "#3d89ffff" color_pred = "#1cff56ff" # + fg, ax = plt.subplots(figsize=(6, 6)) ax.axis("off") nx.draw_networkx_nodes( G, pos=positions, node_size=800, with_labels=True, node_color="white", edgecolors="k", linewidths=1.5, ax=ax, ) nx.draw_networkx_edges(G, pos=positions, edgelist=edges_sequential, width=2) nx.draw_networkx_edges( G.to_directed(), pos=positions, edgelist=edges_contacts, arrowstyle="<|-|>", edge_color="#3d89ffff", width=2, style="dashed", linestyle="", arrowsize=15, node_size=1000, min_source_margin=16, connectionstyle="arc3,rad=0.1", ) fg.subplots_adjust(0.005, 0.005, 0.995, 0.995) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-empty.svg"), transparent=True) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-empty.pdf")) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-empty.png"), dpi=300) # + fg, ax = plt.subplots(figsize=(6, 6)) ax.axis("off") nx.draw_networkx_nodes( G, pos=positions, node_size=800, with_labels=True, # node_color="#3d89ffff", node_color=color_pred, edgecolors="k", linewidths=1.5, ax=ax, ) nx.draw_networkx_edges(G, pos=positions, edgelist=edges_sequential, width=2) nx.draw_networkx_edges( G.to_directed(), pos=positions, edgelist=edges_contacts, # edgelist=edges_contacts + [[e[1], e[0]] for e in edges_contacts], arrowstyle="<|-|>", edge_color="#3d89ffff", width=2, style="dashed", linestyle="", arrowsize=15, node_size=1000, min_source_margin=16, connectionstyle="arc3,rad=0.1", ) nx.draw_networkx_labels(G, pos=positions, labels=labels, font_size=18, verticalalignment="center") fg.subplots_adjust(0.005, 0.005, 0.995, 0.995) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-filled.svg"), transparent=True) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-filled.pdf")) fg.savefig(NOTEBOOK_DIR.joinpath("protein-csp-filled.png"), dpi=300) # - SVG("../docs/images/static/introduction/csps-protein-design.svg") # + def draw_networkx_nodes_ellipses( G, pos, nodelist=None, node_height=1, node_width=2, node_angle=0, node_color="r", node_shape="o", alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, linewidths=None, label=None, **kwargs ): """Draw the nodes of the graph G. This draws only the nodes of the graph G. Parameters ---------- G : graph A networkx graph pos : dictionary A dictionary with nodes as keys and positions as values. Positions should be sequences of length 2. ax : Matplotlib Axes object, optional Draw the graph in the specified Matplotlib axes. nodelist : list, optional Draw only specified nodes (default G.nodes()) node_height : scalar or array Height of ellipse nodes (default=300). If an array is specified it must be the same length as nodelist. node_width : scalar or array Width of ellipse nodes (default=300). If an array is specified it must be the same length as nodelist. node_width : scalar or array Angle of major axis of ellipse nodes (default=300). If an array is specified it must be the same length as nodelist. node_color : color string, or array of floats Node color. Can be a single color format string (default='r'), or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details. node_shape : string The shape of the node. Specification is as matplotlib.scatter marker, one of 'so^>v<dph8' (default='o'). alpha : float The node transparency (default=1.0) cmap : Matplotlib colormap Colormap for mapping intensities of nodes (default=None) vmin,vmax : floats Minimum and maximum for node colormap scaling (default=None) linewidths : [None | scalar | sequence] Line width of symbol border (default =1.0) label : [None| string] Label for legend Returns ------- matplotlib.collections.EllipseCollection `EllipseCollection` of the nodes. """ import collections try: import numpy import matplotlib.pyplot as plt import matplotlib as mpl except ImportError: raise ImportError("Matplotlib required for draw()") except RuntimeError: print("Matplotlib unable to open display") raise if ax is None: ax = plt.gca() if nodelist is None: nodelist = list(G) if not nodelist or len(nodelist) == 0: # empty nodelist, no drawing return None try: xy = numpy.asarray([pos[v] for v in nodelist]) except KeyError as e: raise nx.NetworkXError("Node %s has no position." % e) except ValueError: raise nx.NetworkXError("Bad value in node positions.") if isinstance(alpha, collections.Iterable): node_color = apply_alpha(node_color, alpha, nodelist, cmap, vmin, vmax) alpha = None if cmap is not None: cm = mpl.cm.get_cmap(cmap) norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax) else: cm = None norm = None node_collection = mpl.collections.EllipseCollection( widths=node_width, heights=node_height, angles=-45, offsets=np.array(xy), cmap=cm, norm=norm, transOffset=ax.transData, linewidths=linewidths, **kwargs, ) # node_collection.set_color(node_color) node_collection.set_label(label) node_collection.set_zorder(1) ax.add_collection(node_collection) return node_collection # - angle = np.pi / 6 angle cmap = plt.get_cmap('tab20b<') # + def standardize(a): a = a - a.min() a = a / (a.max() - a.min()) return a def add_padding(a, padding): range_ = a.max() - a.min() a = padding + a / range_ * (range_ - padding * 2) return a def adjust_y_corrd(x, y, angle): return y + x / np.cos(angle) * np.sin(angle) def adjust_pos(pos, scalex, padding): x = np.array([v[0] for v in pos.values()]) y = np.array([v[1] for v in pos.values()]) # Put x and y in the 0 to 1 range x = standardize(x) y = standardize(y) # x = add_padding(x, padding[0]) y = add_padding(y, padding[1]) # x *= scalex # y = adjust_y_corrd(x, y, angle) # pos = {k: np.array([x[i], y[i]]) for i, k in enumerate(pos)} return pos def add_hex_edges(x, y, eps): x_new = [x[0], x[1], x[1] + eps, x[2] - eps, x[2], x[3], x[3] - eps, x[0] + eps] y_new = [y[0] + eps, y[1] - eps, y[1], y[2], y[2] - eps, y[3] + eps, y[3], y[0]] return np.array(x_new), np.array(y_new) cmap = plt.cm.get_cmap("tab20c") scalex = 0.5 node_size = 125 eps = 0.02 x = np.array([0.0, 0.0, 1.0, 1.0]) * scalex y = np.array([0.0, 1.0, 1.0, 0.0]) x, y = add_hex_edges(x, y, eps=eps) y = adjust_y_corrd(x, y, angle) pos = np.array(positions) pos = pos - pos.min() node_size = node_size / (pos.max() - pos.min()) pos = pos / (pos.max() - pos.min()) pos = {i: pos[i] for i in range(len(pos))} pos = adjust_pos(pos, x.max(), padding=(0.1, 0.07)) fg, ax = plt.subplots(figsize=(3, 6)) ax.add_patch( patches.Polygon( xy=list(zip(x, y)), fill=True, alpha=0.5, linewidth=1, facecolor=cmap(15), # facecolor="lightgrey", edgecolor="k", joinstyle="round", zorder=0, ) ) draw_networkx_nodes_ellipses( G, pos, cmap=cmap, node_width=node_size * np.cos(angle), node_height=node_size, facecolors="white", edgecolors="black", linewidths=1.5, ax=ax, ) # edges = nx.draw_networkx_edges( # G.to_directed(), # pos=pos, # edgelist=list(G.edges()), # arrowstyle="<->", # width=1, # style="--", # linestyle="--", # arrowsize=10, # node_size=200, # min_source_margin=7, # ax=ax, # ) # nx.draw_networkx_edges(G, pos=pos, edgelist=edges_sequential, width=2) nx.draw_networkx_edges( G.to_directed(), pos=pos, edgelist=edges_sequential, # edgelist=edges_contacts + [[e[1], e[0]] for e in edges_contacts], arrowstyle="<->", # edge_color="k", edge_color=cmap(12), width=1.5, arrowsize=12, node_size=0, min_source_margin=0, connectionstyle="arc3,rad=0.1", alpha=0.9, zorder=999, ) nx.draw_networkx_edges( G.to_directed(), pos=pos, edgelist=edges_contacts, # edgelist=edges_contacts + [[e[1], e[0]] for e in edges_contacts], arrowstyle="<->", # edge_color="k", edge_color=cmap(12), width=1.5, arrowsize=9, node_size=400, min_source_margin=11, connectionstyle="arc3,rad=0.1", alpha=0.7, zorder=999, ) # offset = 0.55 # x += offset # pos = {k: np.array([v[0] + offset, v[1]]) for k, v in pos.items()} # for loc in pos.values(): # ax.arrow(loc[0] - 0.05, loc[1], 0.01, 0, width=0.005, alpha=0.5, zorder=3, fill=False) # # center_y = adjust_y_corrd(center_x, 0, angle) # # ax.arrow(0.3, center_y, 0.2, 0, width=0.02, alpha=0.5, zorder=3, fill=False) # ax.add_patch( # patches.Polygon( # xy=list(zip(x, y)), fill=True, alpha=0.5, linewidth=1, facecolor=cmap(3), edgecolor="k", # ) # ) # draw_networkx_nodes_ellipses( # G, # pos, # cmap=cmap, # node_color=cmap(0), # node_width=node_size * np.cos(angle), # node_height=node_size, # ax=ax, # ) # # edges = nx.draw_networkx_edges( # # G.to_directed(), # # pos=pos, # # edgelist=list(G.edges()), # # arrowstyle="<->", # # width=1, # # style="--", # # linestyle="--", # # arrowsize=10, # # node_size=200, # # min_source_margin=7, # # ax=ax, # # ) # nx.draw_networkx_edges(G, pos=positions, edgelist=edges_sequential, width=2) # out = nx.draw_networkx_edges( # G.to_directed(), # pos=positions, # edgelist=edges_contacts, # # edgelist=edges_contacts + [[e[1], e[0]] for e in edges_contacts], # arrowstyle="<|-|>", # edge_color="#3d89ffff", # width=2, # style="dashed", # linestyle="", # arrowsize=15, # node_size=1000, # min_source_margin=16, # connectionstyle="arc3,rad=0.1", # ) ax.set_xlim(-0.005, 0.505) ax.set_ylim(y.min(), y.max()) ax.axis("off") fg.subplots_adjust(0.005, 0.005, 0.995, 0.995) fg.savefig(NOTEBOOK_DIR.joinpath("graph-conv-layer.svg"), transparent=True) fg.savefig(NOTEBOOK_DIR.joinpath("graph-conv-layer.pdf")) fg.savefig(NOTEBOOK_DIR.joinpath("graph-conv-layer.png"), dpi=300) # - cmap(0) pos = np.array(positions) pos = pos - pos.min() pos = pos / (pos.max() - pos.min()) p
notebooks/xx_graphic_abstract.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 # --- # + import csv # Manage data # CSV files generated from Lecun's files using # https://pjreddie.com/projects/mnist-in-csv/ # # Training data trn_labels = [] trn_images = [] with open("mnist_train.csv", "r") as train: reader = csv.reader(train) for row in reader: trn_labels.append(int(row[0])) tmp = map(float,row[1:]) tmp[:] = [x / 255.0 for x in tmp] trn_images.append(tmp) print "Number of training imgs: ", len(trn_labels) # Test data test_labels = [] test_images = [] with open("mnist_test.csv", "r") as test: reader = csv.reader(test) for row in reader: test_labels.append(int(row[0])) tmp = map(float,row[1:]) tmp[:] = [x / 255.0 for x in tmp] test_images.append(tmp) print "Number of test imgs: ", len(test_labels)
nn/fnn/mnist_csv_loader.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 # --- # + import json import numpy as np import pandas as pd import pymongo import scipy from bson import ObjectId, json_util from pandas.io.json import json_normalize from pymongo import MongoClient as Connection from scipy import sparse, spatial from scipy.spatial.distance import cdist, pdist, squareform from sklearn.metrics.pairwise import cosine_similarity # scientific notation disabled form smaller numbers pd.options.display.float_format = '{:.5f}'.format # alles resultate anzeigen und nicht nur das letzte from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" # + # display multiple outputs in one row import pandas as pd import numpy as np from IPython.display import display, HTML CSS = """ .output { flex-direction: row; } """ HTML('<style>{}</style>'.format(CSS)) # + connection = Connection() db = connection.recipe_db input_data = db.recipes_without_reviews data = json.loads(json_util.dumps(input_data.find())) # - data2 = pd.DataFrame(json_normalize(data)) # + ing = pd.DataFrame(json_normalize(data, record_path='ingredients', meta='id', record_prefix='ingredients_', errors='ignore')) nutritions = pd.DataFrame(json_normalize(data, record_path='nutritions', meta=['id', 'prep_time', 'rating', 'rating_count', 'ready_in_time', 'review_count'])) # + # ------ erstellung und data cleansing - Ingredients # schmeiss alle zutaten raus, die weniger als 5 mal verwendet werden # setze multiinde auf 'id' und 'ingredients_id' ingredients = ing.set_index(['id', 'ingredients_id']) # filtere alle Zutaten samt ihrer rezepte id, die weniger gleich 5 mal vorkommen ingredients_eqles_5_ing = ingredients.groupby( 'ingredients_id').filter(lambda x: len(x) <= 5) # droppe alle rezepte, die eine Zutate besitzen, die weniger gleich 5 Mal vorkommen ingredients_filt = ingredients.drop(ingredients_eqles_5_ing.index.get_level_values('id').values, level=0) # drop alls rows with ingredients_id == 0 ingredients_eqal_zero = ingredients_filt[ingredients_filt.index.get_level_values('ingredients_id') == 0] ingredients_filt = ingredients_filt.drop(ingredients_eqal_zero.index.get_level_values('id').values, level=0) # + # ------ Erstellung und cleansing des Nutrition Dataframes # erstelle neue liste auf basis der bereits gefilterten rezepte aus ingredients_filt id_overlap_mask = nutritions['id'].isin(ingredients_filt.index.get_level_values('id').values) # erstelle datenframe auf basis der overlapliste nutritions_filt = nutritions.loc[id_overlap_mask] nutrition_db = nutritions_filt.pivot_table( index=['id'], columns=['name'], values=['amount'], ).reset_index() nutrition_db.set_index('id', inplace=True) # remove multiindex 'amount' nutrition_db.columns = nutrition_db.columns.droplevel(0) # entferne alle NA nutrition_db = nutrition_db.dropna() # gleiche nochmals die ids der beiden dataframe nutrition und ingredients ab, da der nutrition dataframe noch NA Werte hatt id_overlap_mask = ingredients_filt.index.get_level_values('id').isin(nutrition_db.index) ingredients_db = ingredients_filt[id_overlap_mask] # abgleich ob anzahl der indizes von nutrition und zutaten dataframe gleich sind # + ingredients_db.reset_index(inplace=True) recipe_db = pd.get_dummies(ingredients_db['ingredients_id']).groupby( ingredients_db['id']).apply(max) # + new_ingredients = ingredients_db.copy() #new_ingredients = new_ingredients.groupby("id")["ingredients_grams"].sum().reset_index() gramms_ingredients = new_ingredients.groupby("id")["ingredients_grams"].sum().reset_index().copy() Q1 = gramms_ingredients.quantile(0.25) Q3 = gramms_ingredients.quantile(0.75) IQR = Q3 - Q1 #Filter out all recipes which are outlier by their weight (gramms) df = gramms_ingredients[((gramms_ingredients >= (Q1 - 1.5 * IQR))& (gramms_ingredients <= (Q3 + 1.5 * IQR))).all(axis=1)].copy() #filter out recipes by weight which are not in the range 500 - 2373.59 gramms df_start_at_fivehundret = df[df['ingredients_grams'].between(500, 2373.58225, inclusive=True)].copy() df_start_at_fivehundret.set_index('id', inplace=True) id_overlap_mask = nutritions['id'].isin(df_start_at_fivehundret.index.get_level_values('id').values) # erstelle datenframe auf basis der overlapliste nutritions_filt_gramm = nutritions.loc[id_overlap_mask] nutrition_db2 = nutritions_filt_gramm.pivot_table( index=['id'], columns=['name'], values=['amount'], ).reset_index() #create new nutrition db based on the above filtering nutrition_db2.set_index('id', inplace=True) nutrition_db2.columns = nutrition_db2.columns.droplevel(0) # + import matplotlib.pyplot as plt from pylab import * # %matplotlib inline from matplotlib import rcParams rcParams['font.family'] = 'Inconsolata' # figure related code fig = plt.figure() fig.suptitle('Rezeptgewicht Bereinigung', fontsize=14, fontweight='medium') plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom=True, # ticks along the bottom edge are off top=False, # ticks along the top edge are off labelbottom=True) # labels along the bottom edge are off ax = fig.add_subplot(111) ax.boxplot(gramms_ingredients['ingredients_grams'], positions=[1], whiskerprops = dict(linestyle='--', linewidth=2), sym="+", patch_artist=True, boxprops=dict(facecolor='slategrey'), #capprops=dict(color=c), #flierprops=dict(color=c, markeredgecolor=c) #medianprops=dict(color=c), ) ax.boxplot(df_start_at_fivehundret['ingredients_grams'], positions=[2], whiskerprops = dict(linestyle='--', linewidth=2), sym="+", patch_artist=True, boxprops=dict(facecolor='slategrey'), #capprops=dict(color=c), #flierprops=dict(color=c, markeredgecolor=c) #medianprops=dict(color=c), ) a=ax.get_xticks().tolist() a[0]='Mit Ausreißern \n n = 4062' a[1]='Ohne Ausreißer \n n = 3771' ax.set_xticklabels(a) ax.yaxis.grid() #ax.set_title('n') #ax.set_xlabel('recipe_grams') ax.set_ylabel('Rezeptgewicht in Gramm') plt.xticks([1,2]) plt.flier_props = dict(marker="+", markersize=17) plt.show()
code/plot/plot_gewicht_ausreisser.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 # --- # # 添加自定义字段:hostname # + import logging from socket import gethostname logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(hostname)s - %(message)s') class NewLogger(logging.Logger): def makeRecord(self, *args, **kwargs): rv = super(NewLogger, self).makeRecord(*args, **kwargs) rv.__dict__['hostname'] = gethostname() # print(rv.__dict__) return rv logging.setLoggerClass(NewLogger) logger = logging.getLogger(__name__) logger.info('Hello World!')
开发常用/日志-logging:自定义format字段.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://colab.research.google.com/github/https-deeplearning-ai/tensorflow-1-public/blob/master/C3/W3/ungraded_labs/C3_W3_Lab_6_sarcasm_with_1D_convolutional.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # + [markdown] id="YEdilk144fzb" # # Ungraded Lab: Training a Sarcasm Detection Model using a Convolution Layer # # You will be doing the same steps here as the previous lab but will be using a convolution layer instead. As usual, try tweaking the parameters and observe how it affects the results. # # + [markdown] id="pmokcpHc5u1R" # ## Download the Dataset # + id="dxezdGoV29Yz" # Download the dataset # !gdown --id 1xRU3xY5-tkiPGvlz5xBJ18_pHWSRzI4v # + id="BTcGA2Po2_nN" import json # Load the JSON file with open("./sarcasm.json", 'r') as f: datastore = json.load(f) # Initialize the lists sentences = [] labels = [] # Collect sentences and labels into the lists for item in datastore: sentences.append(item['headline']) labels.append(item['is_sarcastic']) # + [markdown] id="F2zXSds45s2P" # ## Split the Dataset # + id="baDwTn9S3ENB" training_size = 20000 # Split the sentences training_sentences = sentences[0:training_size] testing_sentences = sentences[training_size:] # Split the labels training_labels = labels[0:training_size] testing_labels = labels[training_size:] # + [markdown] id="NdpLY-or5pTP" # ## Data preprocessing # + id="RHjZR4oi3LOq" import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences vocab_size = 10000 max_length = 120 trunc_type='post' padding_type='post' oov_tok = "<OOV>" # Initialize the Tokenizer class tokenizer = Tokenizer(num_words=vocab_size, oov_token=oov_tok) # Generate the word index dictionary tokenizer.fit_on_texts(training_sentences) word_index = tokenizer.word_index # Generate and pad the training sequences training_sequences = tokenizer.texts_to_sequences(training_sentences) training_padded = pad_sequences(training_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type) # Generate and pad the testing sequences testing_sequences = tokenizer.texts_to_sequences(testing_sentences) testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding=padding_type, truncating=trunc_type) # Convert the labels lists into numpy arrays training_labels = np.array(training_labels) testing_labels = np.array(testing_labels) # + [markdown] id="HQBjPv_A5m1x" # ## Build and Compile the Model # + id="jGwXGIXvFhXW" import tensorflow as tf # Parameters embedding_dim = 16 filters = 128 kernel_size = 5 dense_dim = 6 # Model Definition with Conv1D model_conv = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.Conv1D(filters, kernel_size, activation='relu'), tf.keras.layers.GlobalMaxPooling1D(), tf.keras.layers.Dense(dense_dim, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) # Set the training parameters model_conv.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy']) # Print the model summary model_conv.summary() # + [markdown] id="PcXC5QG45kM7" # ## Train the Model # + id="oB6C55FO3z3q" NUM_EPOCHS = 10 # Train the model history_conv = model_conv.fit(training_padded, training_labels, epochs=NUM_EPOCHS, validation_data=(testing_padded, testing_labels)) # + id="g9DC6dmLF8DC" import matplotlib.pyplot as plt # Plot Utility def plot_graphs(history, string): plt.plot(history.history[string]) plt.plot(history.history['val_'+string]) plt.xlabel("Epochs") plt.ylabel(string) plt.legend([string, 'val_'+string]) plt.show() # Plot the accuracy and loss history plot_graphs(history_conv, 'accuracy') plot_graphs(history_conv, 'loss') # + pycharm={"name": "#%%\n"}
C3/W3/ungraded_labs/C3_W3_Lab_6_sarcasm_with_1D_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 # language: python # name: python3 # --- import time import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.utils import shuffle from sklearn.metrics import confusion_matrix, classification_report, accuracy_score, roc_curve, roc_auc_score, auc from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC from sklearn.feature_selection import chi2, SelectKBest from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score from sklearn.preprocessing import LabelEncoder, MinMaxScaler # # Data Pre-processing dataset = pd.read_csv("/home/med/Documents/url_class/iscxurl2016/All.csv") dataset.head() dataset['URL_Type_obf_Type'].value_counts().plot(kind = 'barh') print(dataset.iloc[0]) lb = 'URL_Type_obf_Type' print(dataset[lb].value_counts()) # Data cleansing (drop all rows containing NaN value) dataset = dataset.dropna(axis=1) dataset = dataset.replace(np.Infinity, np.nan).dropna(axis=0) dataset.head() dataset['URL_Type_obf_Type'].value_counts().plot(kind = 'barh') dataset.shape #Normalize features and split labels column scaler = MinMaxScaler() features = pd.DataFrame(scaler.fit_transform(dataset.loc[:, dataset.columns != lb]), columns=dataset.columns[:-1] ) labels = dataset[lb] print(features.head()) print(labels.value_counts()) # ## Chi-score of features chi_score = chi2(features, labels) p_values = pd.Series(chi_score[1],index = features.columns) p_values.sort_values(ascending = False , inplace = True) #p_values.plot.bar() print('Values in order of descending 64-values (higher=more significant)') print(p_values.index[:64]) # ## Dataset with 64th first rank features in chi-score dataset_64 = dataset.copy() dataset_64 = dataset_64[p_values.index[:64].insert(65, lb)] dataset_64.head() # ## Creating features and labes features_64 = dataset_64.loc[:, dataset_64.columns != lb].to_numpy() print(features_64[0]) # ## Encoding labels coding_labels = { "benign" : 0, "Defacement" : 1, "malware" : 2, "phishing" : 3, "spam" : 4 } labels_64 = dataset_64[lb].map(coding_labels).to_numpy() print(labels_64) # ## Defining tets and visualisation plot Functions def compareModels(accuracies, results, classifiers): comp = plt.figure(figsize=(10, 8)) comp.suptitle('Comparison of models') x = comp.add_subplot(111) plt.boxplot(results) x.set_xticklabels(classifiers) plt.show() def testModel(model, X_test, y_test): # make predictions on validation dataset predictions = model.predict(X_test) print("Accuracy = {:.2f}".format(accuracy_score(y_test, predictions)*100)) print('Confusion Matrix:') cm = confusion_matrix(y_test, predictions) sn.heatmap(cm, annot=True, fmt='g', cmap='Blues', xticklabels=['Benign','Defacement','Malware','Phishing','Spam'], yticklabels=['Benign','Defacement','Malware','Phishing','Spam']) print('Classification Report:') print(classification_report(y_test, predictions)) def aucPlot(model, X_test, y_test, classifier): lr_probs = model.predict_proba(X_test) # keep probabilities for the positive outcome only lr_probs = lr_probs.reshape(lr_probs.shape[0], 5) print(lr_probs[0]) #lr_probs = np.transpose([pred[:, 1] for pred in lr_probs]) # calculate scores lr_auc = roc_auc_score(y_test, lr_probs, multi_class="ovr") # summarize scores print(classifier, ' : ROC AUC=%.2f %%' % (lr_auc*100)) # Compute ROC curve and ROC area for each class fpr = dict() tpr = dict() roc_auc = dict() labels = ['Benign', 'Defacement', 'Malware', 'Phishing', 'Spam'] colors = ['blue', 'magenta', 'red', 'cyan', 'orange'] n_classes = 5 for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test, lr_probs[:, i], pos_label=i) roc_auc[i] = auc(fpr[i], tpr[i]) # Plot of a ROC curve for a specific class plt.figure(figsize=(15, 15)) for i in range(n_classes): plt.plot(fpr[i], tpr[i], color=colors[i], label=labels[i]+' ROC curve (area = %0.2f)' % roc_auc[i]) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([-0.01, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Multi Class Classification') plt.legend(loc="lower right") plt.show() # ## Shuffeling and splitting data into train set and test set X_train, X_test, y_train, y_test = train_test_split(features_64, labels_64, test_size=0.2, random_state=36) # # Building and training models models = [] models.append(('LogisticRegression', LogisticRegression(solver='liblinear', multi_class='auto'))) models.append(('KNN', KNeighborsClassifier())) models.append(('DecisionTreeClassifier', DecisionTreeClassifier())) models.append(('SVM', SVC(gamma='auto'))) models.append(('RandomForestClassifier', RandomForestClassifier(n_estimators=10))) models.append(('NaiveBayes', GaussianNB())) # # Evaluate each model in turn using 10-fold cross-validation # + results = [] classifiers = [] accuracies = [] for classifier, model in models: kfold = StratifiedKFold(n_splits=10) start_time = time.time() cv_results = cross_val_score(model, X_train, y_train, cv=kfold, scoring='accuracy') end_time = time.time() - start_time if end_time > 60: end_time = "%.2f (m)" % (end_time/60) else: end_time = "%.2f (s)" % (end_time) accuracies.append((cv_results.mean(), classifier)) results.append(cv_results) classifiers.append(classifier) details = "%s: \t %f \t (%f)" % (classifier, cv_results.mean(), cv_results.std()) print("{} \t | time : {}".format(details, end_time)) # - accuracies.sort(reverse=True) for a, c in accuracies: print("{} \t {:.2f} %".format(c, a*100)) compareModels(accuracies, results, classifiers) # # Training, testing and visualising best three models rf = RandomForestClassifier(n_estimators=10) rf.fit(X_train, y_train) testModel(rf, X_test, y_test) aucPlot(rf, X_test, y_test, 'RandomForestClassifier') cart = DecisionTreeClassifier() cart.fit(X_train, y_train) testModel(cart, X_test, y_test) aucPlot(cart, X_test, y_test, 'DecisionTreeClassifier') knn = KNeighborsClassifier() knn.fit(X_train, y_train) testModel(knn, X_test, y_test) aucPlot(knn, X_test, y_test, 'KNeighborsClassifier')
MachineLearningModels_multiclass.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 # --- # ## <span style="color:#8735fb; font-size:24pt"> Multi Node Multi-GPU performance sweeps on Kubernetes </span> # # Before going ahead with the rest of the notebook, please follow the steps provided in the [Detailed Setup Guide](./Detailed_setup_guide.md) to setup Azure Kubernetes Services (AKS). # + import certifi import cudf import cuml import cupy as cp import numpy as np import os import pandas as pd import random import seaborn as sns import time import yaml from functools import partial from math import cos, sin, asin, sqrt, pi from tqdm import tqdm from typing import Optional import dask import dask.array as da import dask_cudf from dask_kubernetes import KubeCluster, make_pod_from_dict from dask.distributed import Client, WorkerPlugin, wait, progress class SimpleTimer: def __init__(self): self.start = None self.end = None self.elapsed = None def __enter__(self): self.start = time.perf_counter_ns() return self def __exit__(self, exc_type, exc_val, exc_tb): self.end = time.perf_counter_ns() self.elapsed = self.end - self.start def create_pod_from_yaml(yaml_file): with open(yaml_file, 'r') as reader: d = yaml.safe_load(reader) d = dask.config.expand_environment_variables(d) return make_pod_from_dict(d) def build_worker_and_scheduler_pods(sched_spec, worker_spec): assert os.path.isfile(sched_spec) assert os.path.isfile(worker_spec) sched_pod = create_pod_from_yaml(sched_spec) worker_pod = create_pod_from_yaml(worker_spec) return sched_pod, worker_pod # + dask.config.set({"logging.kubernetes": "info", "logging.distributed": "info", "kubernetes.scheduler-service-type": "LoadBalancer", "kubernetes.idle-timeout": None, "kubernetes.scheduler-service-wait-timeout": 3600, "kubernetes.deploy-mode": "remote", "kubernetes.logging": "info", "distributed.logging": "info", "distributed.scheduler.idle-timeout": None, "distributed.scheduler.locks.lease-timeout": None, "distributed.comm.timeouts.connect": 3600, "distributed.comm.tls.ca-file": certifi.where()}) sched_spec_path = "./podspecs/azure/scheduler-specs.yml" worker_spec_path = "./podspecs/azure/cuda-worker-specs.yml" # - sched_pod, worker_pod = build_worker_and_scheduler_pods(sched_spec=sched_spec_path, worker_spec=worker_spec_path) # + cluster = KubeCluster(pod_template=worker_pod, scheduler_pod_template=sched_pod) client = Client(cluster) scheduler_address = cluster.scheduler_address # - # This will probably take around 3 to 4 minutes. Hang tight! client # ### Helper function to scale the workers def scale_workers(client, n_workers, timeout=300): client.cluster.scale(n_workers) m = len(client.has_what().keys()) start = end = time.perf_counter_ns() while ((m != n_workers) and (((end - start) / 1e9) < timeout) ): time.sleep(5) m = len(client.has_what().keys()) end = time.perf_counter_ns() if (((end - start) / 1e9) >= timeout): raise RuntimeError(f"Failed to rescale cluster in {timeout} sec." "Try increasing timeout for very large containers, and verify available compute resources.") # ### Scale the workers scale_workers(client, 8, timeout=360) # ### Helper functions # + def construct_worker_pool(client, n_workers, auto_scale=False, timeout=300): workers = [w for w in client.has_what().keys()] if (len(workers) < n_workers): if (auto_scale): scale_workers(client=client, n_workers=n_workers, timeout=timeout) workers = [w for w in client.has_what().keys()] else: print("Attempt to construct worker pool larger than available worker set, and auto_scale is False." " Returning entire pool.") else: workers = random.sample(population=workers, k=n_workers) return workers def estimate_df_rows(client, files, storage_opts={}, testpct=0.01): workers = client.has_what().keys() est_size = 0 for file in files: if (file.endswith('.csv')): df = dask_cudf.read_csv(file, npartitions=len(workers), storage_options=storage_opts) elif (file.endswith('.parquet')): df = dask_cudf.read_parquet(file, npartitions=len(workers), storage_options=storage_opts) # Select only the index column from our subsample est_size += (df.sample(frac=testpct).iloc[:,0].shape[0] / testpct).compute() del df return est_size def pretty_print(scheduler_dict): print(f"All workers for scheduler id: {scheduler_dict['id']}, address: {scheduler_dict['address']}") for worker in scheduler_dict['workers']: print(f"Worker: {worker} , gpu_machines: {scheduler_dict['workers'][worker]['gpu']}") # - # ### Taxi Data Setup # + def clean(df_part, remap, must_haves): """ This function performs the various clean up tasks for the data and returns the cleaned dataframe. """ tmp = {col:col.strip().lower() for col in list(df_part.columns)} df_part = df_part.rename(columns=tmp) # rename using the supplied mapping df_part = df_part.rename(columns=remap) # iterate through columns in this df partition for col in df_part.columns: # drop anything not in our expected list if col not in must_haves: df_part = df_part.drop(col, axis=1) continue # fixes datetime error found by <NAME> and fixed by <NAME> if df_part[col].dtype == 'object' and col in ['pickup_datetime', 'dropoff_datetime']: df_part[col] = df_part[col].astype('datetime64[ms]') continue # if column was read as a string, recast as float if df_part[col].dtype == 'object': df_part[col] = df_part[col].astype('float32') else: # downcast from 64bit to 32bit types # Tesla T4 are faster on 32bit ops if 'int' in str(df_part[col].dtype): df_part[col] = df_part[col].astype('int32') if 'float' in str(df_part[col].dtype): df_part[col] = df_part[col].astype('float32') df_part[col] = df_part[col].fillna(-1) return df_part def coalesce_taxi_data(fraction, random_state): base_path = 'gs://anaconda-public-data/nyc-taxi/csv' # list of column names that need to be re-mapped remap = {} remap['tpep_pickup_datetime'] = 'pickup_datetime' remap['tpep_dropoff_datetime'] = 'dropoff_datetime' remap['ratecodeid'] = 'rate_code' #create a list of columns & dtypes the df must have must_haves = { 'pickup_datetime': 'datetime64[ms]', 'dropoff_datetime': 'datetime64[ms]', 'passenger_count': 'int32', 'trip_distance': 'float32', 'pickup_longitude': 'float32', 'pickup_latitude': 'float32', 'rate_code': 'int32', 'dropoff_longitude': 'float32', 'dropoff_latitude': 'float32', 'fare_amount': 'float32' } # apply a list of filter conditions to throw out records with missing or outlier values query_frags = [ 'fare_amount > 0 and fare_amount < 500', 'passenger_count > 0 and passenger_count < 6', 'pickup_longitude > -75 and pickup_longitude < -73', 'dropoff_longitude > -75 and dropoff_longitude < -73', 'pickup_latitude > 40 and pickup_latitude < 42', 'dropoff_latitude > 40 and dropoff_latitude < 42' ] valid_months_2016 = [str(x).rjust(2, '0') for x in range(1, 7)] valid_files_2016 = [f'{base_path}/2016/yellow_tripdata_2016-{month}.csv' for month in valid_months_2016] df_2014_fractional = dask_cudf.read_csv(f'{base_path}/2014/yellow_*.csv', chunksize=25e6).sample( frac=fraction, random_state=random_state) df_2014_fractional = clean(df_2014_fractional, remap, must_haves) df_2015_fractional = dask_cudf.read_csv(f'{base_path}/2015/yellow_*.csv', chunksize=25e6).sample( frac=fraction, random_state=random_state) df_2015_fractional = clean(df_2015_fractional, remap, must_haves) df_2016_fractional = dask_cudf.read_csv(valid_files_2016, chunksize=25e6).sample( frac=fraction, random_state=random_state) df_2016_fractional = clean(df_2016_fractional, remap, must_haves) df_taxi = dask.dataframe.multi.concat([df_2014_fractional, df_2015_fractional, df_2016_fractional]) df_taxi = df_taxi.query(' and '.join(query_frags)) return df_taxi # + def taxi_csv_data_loader(client, response_dtype=np.float32, fraction=1.0, random_state=0): response_id = 'fare_amount' workers = client.has_what().keys() km_fields = ['passenger_count', 'trip_distance', 'pickup_longitude', 'pickup_latitude', 'rate_code', 'dropoff_longitude', 'dropoff_latitude', 'fare_amount'] taxi_df = coalesce_taxi_data(fraction=fraction, random_state=random_state) taxi_df = taxi_df[km_fields] with dask.annotate(workers=set(workers)): taxi_df = client.persist(collections=taxi_df) X = taxi_df[taxi_df.columns.difference([response_id])].astype(np.float32) y = taxi_df[response_id].astype(response_dtype) wait(taxi_df) return taxi_df, X, y def taxi_parquet_data_loader(client, response_dtype=np.float32, fraction=1.0, random_state=0): # list of column names that need to be re-mapped remap = {} remap['tpep_pickup_datetime'] = 'pickup_datetime' remap['tpep_dropoff_datetime'] = 'dropoff_datetime' remap['ratecodeid'] = 'rate_code' #create a list of columns & dtypes the df must have must_haves = { 'pickup_datetime': 'datetime64[ms]', 'dropoff_datetime': 'datetime64[ms]', 'passenger_count': 'int32', 'trip_distance': 'float32', 'pickup_longitude': 'float32', 'pickup_latitude': 'float32', 'rate_code': 'int32', 'dropoff_longitude': 'float32', 'dropoff_latitude': 'float32', 'fare_amount': 'float32' } # apply a list of filter conditions to throw out records with missing or outlier values query_frags = [ 'fare_amount > 0 and fare_amount < 500', 'passenger_count > 0 and passenger_count < 6', 'pickup_longitude > -75 and pickup_longitude < -73', 'dropoff_longitude > -75 and dropoff_longitude < -73', 'pickup_latitude > 40 and pickup_latitude < 42', 'dropoff_latitude > 40 and dropoff_latitude < 42' ] workers = client.has_what().keys() taxi_parquet_path = "gs://anaconda-public-data/nyc-taxi/nyc.parquet" response_id = 'fare_amount' fields = ['passenger_count', 'trip_distance', 'pickup_longitude', 'pickup_latitude', 'rate_code', 'dropoff_longitude', 'dropoff_latitude', 'fare_amount'] taxi_df = dask_cudf.read_parquet(taxi_parquet_path, npartitions=len(workers), chunksize=25e6).sample( frac=fraction, random_state=random_state) taxi_df = clean(taxi_df, remap, must_haves) taxi_df = taxi_df.query(' and '.join(query_frags)) taxi_df = taxi_df[fields] with dask.annotate(workers=set(workers)): taxi_df = client.persist(collections=taxi_df) wait(taxi_df) X = taxi_df[taxi_df.columns.difference([response_id])].astype(np.float32) y = taxi_df[response_id].astype(response_dtype) return taxi_df, X, y # - # ### Performance Validation Code # + def record_elapsed_timings_to_df(df, timings, record_template, type, columns, write_to=None): records = [dict(record_template, **{"sample_index": i, "elapsed": elapsed, "type": type}) for i, elapsed in enumerate(timings)] df = df.append(other=records, ignore_index=True) if (write_to): df.to_csv(write_to, columns=columns) return df def collect_load_time_samples(load_func, count, return_final_sample=True, verbose=False): timings = [] for m in tqdm(range(count)): with SimpleTimer() as timer: df, X, y = load_func() timings.append(timer.elapsed) if (return_final_sample): return df, X, y, timings return None, None, None, timings def collect_func_time_samples(func, count, verbose=False): timings = [] for k in tqdm(range(count)): with SimpleTimer() as timer: func() timings.append(timer.elapsed) return timings def sweep_fit_func(model, func_id, require_compute, X, y, xy_fit, count): _fit_func_attr = getattr(model, func_id) if (require_compute): if (xy_fit): fit_func = partial(lambda X, y: _fit_func_attr(X, y).compute(), X, y) else: fit_func = partial(lambda X: _fit_func_attr(X).compute(), X) else: if (xy_fit): fit_func = partial(_fit_func_attr, X, y) else: fit_func = partial(_fit_func_attr, X) return collect_func_time_samples(func=fit_func, count=count) def sweep_predict_func(model, func_id, require_compute, X, count): _predict_func_attr = getattr(model, func_id) predict_func = partial(lambda X: _predict_func_attr(X).compute(), X) return collect_func_time_samples(func=predict_func, count=count) def performance_sweep(client, model, data_loader, hardware_type, worker_counts=[1], samples=1, load_samples=1, max_data_frac=1.0, predict_frac=0.05, scaling_type='weak', xy_fit=True, fit_requires_compute=False, update_workers_in_kwargs=True, response_dtype=np.float32, out_path='./perf_sweep.csv', append_to_existing=False, model_name=None, fit_func_id="fit", predict_func_id="predict", scaling_denom=None, model_args={}, model_kwargs={}): """ Primary performance sweep entrypoint. Parameters ------------ client: DASK client associated with the cluster we're interesting in collecting performance data for. model: Model object on which to gather performance data. This will be created and destroyed, once for each element of 'worker_counts' data_loader: arbitrary data loading function that will be called to load the appropriate testing data. Function that is responsible for loading and returning the data to be used for a given performance run. Function signature must accept (client, fraction, and random_state). Client should be used to distribute data, and loaders should utilize fraction and random_state with dask's dataframe.sample method to allow for control of how much data is loaded. When called, its return value should be of the form: df, X, y, where df is the full dask_cudf dataframe, X is a dask_cudf dataframe which contains all explanatory variables that will be passed to the 'fit' function, and y is a dask_cudf series or dataframe that contains response variables which should be passed to fit/predict as fit(X, y) hardware_type: indicates the core hardware the current sweep is running on. ex. 'T4', 'V100', 'A100' worker_counts: List indicating the number of workers that should be swept. Ex [1, 2, 4] worker counts must fit within the cluster associated with 'client', if the current DASK worker count is different from what is requested on a given sweep, attempt to automatically scale the worker count. NOTE: this does not mean we will scale the available cluster nodes, just the number of deployed worker pods. samples: number of fit/predict samples to record per worker count load_samples: number of times to sample data loads. This effectively times how long 'data_loader' runs. max_data_frac: maximum fraction of data to return. Strong scaling: each run will utilize max_data_frac data. Weak scaling: each run will utilize (current worker count) / (max worker count) * max_data_frac data. predict_frac: fraction of training data used to test inference scaling_type: values can be 'weak' or 'strong' indicating the type of scaling sweep to perform. xy_fit: indicates whether or not the model's 'fit' function is of the form (X, y), when xy_fit is False, we assume that fit is of the form (X), as is the case with various unsupervised methods ex. KNN. fit_requires_compute: False generally, set this to True if the model's 'fit' function requires a corresponding '.compute()' call to execute the required work. update_workers_in_kwargs: Some algorithms accept a 'workers' list, much like DASK, and will require their kwargs to have workers populated. Setting this flag handles this automatically. response_dtype: defaults to np.float32, some algorithms require another dtype, such as int32 out_path: path where performance data csv should be saved append_to_existing: When true, append results to an existing csv, otherwise overwrite. model_name: Override what we output as the model name fit_func_id: Defaults to 'fit', only set this if the model has a non-standard naming. predict_func_id: Defaults to 'predict', only set this if the model has a on-standard predict naming. scaling_denom: (weak scaling) defaults to max(workers) if unset. Specifies the maximum worker count that weak scaling should scale against. For example, when using 1 worker in a weak scaling sweep, the worker will attempt to process a fraction of the total data equal to 1/scaling_denom model_args: args that will be passed to the model's constructor model_kwargs: keyword args that will be passed to the model's constructor Returns -------- """ cols = ['n_workers', 'sample_index', 'elapsed', 'type', 'algorithm', 'scaling_type', 'data_fraction', 'hardware'] perf_df = cudf.DataFrame(columns=cols) if (append_to_existing): try: perf_df = cudf.read_csv(out_path) except: pass model_name = model_name if model_name else str(model) scaling_denom = scaling_denom if (scaling_denom is not None) else max(worker_counts) max_data_frac = min(1.0, max_data_frac) start_msg = f"Starting {scaling_type}-scaling performance sweep for:\n" start_msg += f" model : {model_name}\n" start_msg += f" data loader: {data_loader}.\n" start_msg += f"Configuration\n" start_msg += "==========================\n" start_msg += f"{'Worker counts':<25} : {worker_counts}\n" start_msg += f"{'Fit/Predict samples':<25} : {samples}\n" start_msg += f"{'Data load samples':<25} : {load_samples}\n" start_msg += f"- {'Max data fraction':<23} : {max_data_frac}\n" start_msg += f"{'Model fit':<25} : {'X ~ y' if xy_fit else 'X'}\n" start_msg += f"- {'Response DType':<23} : {response_dtype}\n" start_msg += f"{'Writing results to':<25} : {out_path}\n" start_msg += f"- {'Method':<23} : {'overwrite' if not append_to_existing else 'append'}\n" print(start_msg, flush=True) for n in worker_counts: fraction = (n / scaling_denom) * max_data_frac if scaling_type == 'weak' else max_data_frac record_template = {"n_workers": n, "type": "predict", "algorithm": model_name, "scaling_type": scaling_type, "data_fraction": fraction, "hardware": hardware_type} scale_workers(client, n) print(f"Sampling <{load_samples}> load times with {n} workers.", flush=True) load_func = partial(data_loader, client=client, response_dtype=response_dtype, fraction=fraction, random_state=0) df, X, y, load_timings = collect_load_time_samples(load_func=load_func, count=load_samples) perf_df = record_elapsed_timings_to_df(df=perf_df, timings=load_timings, type='load', record_template=record_template, columns=cols, write_to=out_path) print(f"Finished loading <{load_samples}>, samples, to <{n}> workers with a mean time of {np.mean(load_timings)/1e9:0.4f} sec.", flush=True) print(f"Sweeping {model_name} '{fit_func_id}' with <{n}> workers. Sampling <{samples}> times.", flush=True) if (update_workers_in_kwargs and 'workers' in model_kwargs): model_kwargs['workers'] = workers = client.has_what().keys() print(model_args, model_kwargs) m = model(*model_args, **model_kwargs) if (fit_func_id): fit_timings = sweep_fit_func(model=m, func_id=fit_func_id, require_compute=fit_requires_compute, X=X, y=y, xy_fit=xy_fit, count=samples) perf_df = record_elapsed_timings_to_df(df=perf_df, timings=fit_timings, type='fit', record_template=record_template, columns=cols, write_to=out_path) print(f"Finished gathering <{samples}>, 'fit' samples using <{n}> workers, with a mean time of {np.mean(fit_timings)/1e9:0.4f} sec.", flush=True) else: print(f"Skipping fit sweep, fit_func_id is None") if (predict_func_id): print(f"Sweeping {model_name} '{predict_func_id}' with <{n}> workers. Sampling <{samples}> times.", flush=True) predict_timings = sweep_predict_func(model=m, func_id=predict_func_id, require_compute=True, X=X, count=samples) perf_df = record_elapsed_timings_to_df(df=perf_df, timings=predict_timings, type='predict', record_template=record_template, columns=cols, write_to=out_path) print(f"Finished gathering <{samples}>, 'predict' samples using <{n}> workers, with a mean time of {np.mean(predict_timings)/1e9:0.4f} sec.", flush=True) else: print(f"Skipping inference sweep. predict_func_id is None") # - # ### Visualization and Analysis # + def simple_ci(df, fields, groupby): gbdf = df[fields].groupby(groupby).agg(['mean', 'std', 'count']) ci = (1.96 + gbdf['elapsed']['std'] / np.sqrt(gbdf['elapsed']['count'])) ci_df = ci.reset_index() ci_df['ci.low'] = gbdf['elapsed'].reset_index()['mean'] - ci_df[0] ci_df['ci.high'] = gbdf['elapsed'].reset_index()['mean'] + ci_df[0] return ci_df def visualize_csv_data(csv_path): df = cudf.read_csv(csv_path) fields = ['elapsed', 'elapsed_sec', 'type', 'n_workers', 'hardware', 'scaling_type'] groupby = ['n_workers', 'type', 'hardware', 'scaling_type'] df['elapsed_sec'] = df['elapsed']/1e9 ci_df = simple_ci(df, fields, groupby=groupby) # Rescale to seconds ci_df[['ci.low', 'ci.high']] = ci_df[['ci.low', 'ci.high']]/1e9 # Print confidence intervals print(ci_df[['hardware', 'n_workers', 'type', 'ci.low', 'ci.high']][ci_df['type'] != 'load']) sns.set_theme(style="whitegrid") sns.set(rc={'figure.figsize':(20, 10)}, font_scale=2) # Boxplots for elapsed time at each worker count. plot_df = df[fields][df[fields].type != 'load'].to_pandas() ax = sns.catplot(data=plot_df, x="n_workers", y="elapsed_sec", col="type", row="scaling_type", hue="hardware", kind="box", height=8, order=None) # - # ### Taxi Data Configuration (Medium Sized Dataset) # We can use the parquet data from the Anaconda public repo here (hosted in google file system). THis will illustrate how much faster it is to read parquet, and gives us around 150 million rows of data to work with. # + # Uncomment to test with Taxi Dataset preload_data = False append_to_existing = True samples = 5 load_samples = 1 worker_counts = [8] scaling_denom = 8 hardware_type = "V100" max_data_frac = 0.75 scale_type = 'weak' # weak | strong out_prefix = 'taxi_medium' if (not preload_data): data_loader = taxi_parquet_data_loader else: data = taxi_parquet_data_loader(client, fraction=max_data_frac) data_loader = lambda client, response_dtype, fraction, random_state: data if (not hardware_type): raise RuntimeError("Please specify the hardware type for this run! ex. (T4, V100, A100)") sweep_kwargs = { 'append_to_existing': append_to_existing, 'samples': samples, 'load_samples': load_samples, 'worker_counts': worker_counts, 'scaling_denom': scaling_denom, 'hardware_type': hardware_type, 'data_loader': data_loader, 'max_data_frac': max_data_frac, 'scaling_type': scale_type } # - # #### It is worth noting that in this notebook we will be using much larger datasets compared to our other [notebook with XGBoost](./MNMG_XGBoost.ipynb) which uses a smaller dataset. The order of rows here is > 150 million. Now, with Azureml Opendatasets, we have to first download the data to the client machine and then distribute it over the workers. This would be slow and communication-wise inefficient for very large datasets. Hence we use the parquets and the csvs publicly hosted by Anaconda in google file system (GCFCS). With the latter endpoints, the workers can directly read the csv/parquet files without having to transfer them over the network from the client machine. You can choose any other public/private endpoints that directly allow reading from parquet or csv files. taxi_parquet_path = ["gs://anaconda-public-data/nyc-taxi/nyc.parquet/*.parquet"] estimated_rows = estimate_df_rows(client, files=taxi_parquet_path, testpct=0.0001) print(estimated_rows) # ### Taxi Data Configuration (Large Dataset) # The largest dataset we'll work with, contains up to 450 million rows of taxi data, stored as CSV files. # + # # Uncomment to sweep with the large Taxi Dataset # preload_data = True # append_to_existing = True # samples = 5 # load_samples = 1 # worker_counts = [8] # scaling_denom = 8 # hardware_type = "V100" # data_loader = taxi_csv_data_loader # max_data_frac = .5 # scale_type = 'weak' # out_prefix = 'taxi_large' # if (not preload_data): # data_loader = taxi_csv_data_loader # else: # data = taxi_csv_data_loader(client, fraction=max_data_frac) # data_loader = lambda client, response_dtype, fraction, random_state: data # if (not hardware_type): # raise RuntimeError("Please specify the hardware type for this run! ex. (T4, V100, A100)") # sweep_kwargs = { # 'append_to_existing': append_to_existing, # 'samples': samples, # 'load_samples': load_samples, # 'worker_counts': worker_counts, # 'scaling_denom': scaling_denom, # 'hardware_type': hardware_type, # 'data_loader': data_loader, # 'max_data_frac': max_data_frac, # 'scaling_type': scale_type # } # - # ### ETL Exploration CSV vs Parquet # + remap = {} remap['tpep_pickup_datetime'] = 'pickup_datetime' remap['tpep_dropoff_datetime'] = 'dropoff_datetime' remap['ratecodeid'] = 'rate_code' #create a list of columns & dtypes the df must have must_haves = { 'pickup_datetime': 'datetime64[ms]', 'dropoff_datetime': 'datetime64[ms]', 'passenger_count': 'int32', 'trip_distance': 'float32', 'pickup_longitude': 'float32', 'pickup_latitude': 'float32', 'rate_code': 'int32', 'dropoff_longitude': 'float32', 'dropoff_latitude': 'float32', 'fare_amount': 'float32' } # apply a list of filter conditions to throw out records with missing or outlier values query_frags = [ 'fare_amount > 0 and fare_amount < 500', 'passenger_count > 0 and passenger_count < 6', 'pickup_longitude > -75 and pickup_longitude < -73', 'dropoff_longitude > -75 and dropoff_longitude < -73', 'pickup_latitude > 40 and pickup_latitude < 42', 'dropoff_latitude > 40 and dropoff_latitude < 42' ] workers = client.has_what().keys() # + base_path = 'gcs://anaconda-public-data/nyc-taxi/csv' with SimpleTimer() as timer_csv: df_csv_2014 = dask_cudf.read_csv(f'{base_path}/2014/yellow_*.csv', chunksize=25e6) df_csv_2014 = clean(df_csv_2014, remap, must_haves) df_csv_2014 = df_csv_2014.query(' and '.join(query_frags)) with dask.annotate(workers=set(workers)): df_csv_2014 = client.persist(collections=df_csv_2014) wait(df_csv_2014) print(df_csv_2014.columns) rows_csv = df_csv_2014.iloc[:,0].shape[0].compute() print(f"CSV load took {timer_csv.elapsed/1e9} sec. For {rows_csv} rows of data => {rows_csv/(timer_csv.elapsed/1e9)} rows/sec") # - client.cancel(df_csv_2014) # + with SimpleTimer() as timer_parquet: df_parquet = dask_cudf.read_parquet(f'gs://anaconda-public-data/nyc-taxi/nyc.parquet/*', chunksize=25e6) df_parquet = clean(df_parquet, remap, must_haves) df_parquet = df_parquet.query(' and '.join(query_frags)) with dask.annotate(workers=set(workers)): df_parquet = client.persist(collections=df_parquet) wait(df_parquet) print(df_parquet.columns) rows_parquet = df_parquet.iloc[:,0].shape[0].compute() print(f"Parquet load took {timer_parquet.elapsed/1e9} sec. For {rows_parquet} rows of data => {rows_parquet/(timer_parquet.elapsed/1e9)} rows/sec") # - client.cancel(df_parquet) # Speedup with 8 V100 nodes should be approximately 2.5-5x speedup = (rows_parquet/(timer_parquet.elapsed/1e9))/(rows_csv/(timer_csv.elapsed/1e9)) print(speedup) # ## <span style="color:#8735fb; font-size:24pt"> cuML Algorithms Performance Sweeps </span> # ### RandomForestRegressor # + from cuml.dask.ensemble import RandomForestRegressor rf_kwargs = { "workers": client.has_what().keys(), "n_estimators": 10, "max_depth": 12 } rf_csv_path = f"./{out_prefix}_random_forest_regression.csv" performance_sweep(client=client, model=RandomForestRegressor, **sweep_kwargs, out_path=rf_csv_path, response_dtype=np.int32, model_kwargs=rf_kwargs) # - rf_csv_path = f"./{out_prefix}_random_forest_regression.csv" visualize_csv_data(rf_csv_path) # ### KMeans # + from cuml.dask.cluster import KMeans kmeans_kwargs = { "client": client, "n_clusters": 12, "max_iter": 371, "tol": 1e-5, "oversampling_factor": 3, "max_samples_per_batch": 32768/2, "verbose": False, "init": 'random' } kmeans_csv_path = f'./{out_prefix}_kmeans.csv' performance_sweep(client=client, model=KMeans, **sweep_kwargs, out_path=kmeans_csv_path, xy_fit=False, model_kwargs=kmeans_kwargs) # - visualize_csv_data(kmeans_csv_path) # ### Nearest Neighbors # + from cuml.dask.neighbors import NearestNeighbors nn_kwargs = {} nn_csv_path = f'./{out_prefix}_nn.csv' performance_sweep(client=client, model=NearestNeighbors, **sweep_kwargs, out_path=nn_csv_path, xy_fit=False, predict_func_id='get_neighbors', model_kwargs=nn_kwargs) # - nn_csv_path = f'./{out_prefix}_nn.csv' visualize_csv_data(nn_csv_path) # ### TruncatedSVD # + from cuml.dask.decomposition import TruncatedSVD tsvd_kwargs = { "client": client, "n_components": 5 } tsvd_csv_path = f'./{out_prefix}_tsvd.csv' performance_sweep(client=client, model=TruncatedSVD, **sweep_kwargs, out_path=tsvd_csv_path, xy_fit=False, fit_requires_compute=True, fit_func_id="fit_transform", predict_func_id=None, model_kwargs=tsvd_kwargs) # - visualize_csv_data(tsvd_csv_path) # ### Lasso Regression # + from cuml.dask.linear_model import Lasso as LassoRegression lasso_kwargs = { "client": client } lasso_csv_path = f'./{out_prefix}_lasso_regression.csv' performance_sweep(client=client, model=LassoRegression, **sweep_kwargs, out_path=lasso_csv_path, model_kwargs=lasso_kwargs) # - visualize_csv_data(lasso_csv_path) # ### ElasticNet Regression # + from cuml.dask.linear_model import ElasticNet as ElasticNetRegression elastic_kwargs = { "client": client, } enr_csv_path = f'./{out_prefix}_elastic_regression.csv' performance_sweep(client=client, model=ElasticNetRegression, **sweep_kwargs, out_path=enr_csv_path, model_kwargs=elastic_kwargs) # - visualize_csv_data(enr_csv_path) # ### Model Parallel Multi-GPU Linear Regression # + from cuml.dask.solvers import CD # This uses model parallel Coordinate Descent cd_kwargs = { } cd_csv_path = f'./{out_prefix}_mutli_gpu_linear_regression.csv' performance_sweep(client=client, model=CD, **sweep_kwargs, out_path=cd_csv_path, model_kwargs=cd_kwargs) # - visualize_csv_data(cd_csv_path) # ### XGBoost # + import xgboost as xgb xg_args = [client] xg_kwargs = { 'params': { 'tree_method': 'gpu_hist', }, 'num_boost_round': 100 } xgb_csv_path = f'./{out_prefix}_xgb.csv' class XGBProxy(): """ Create a simple API wrapper around XGBoost so that it supports the fit/predict workflow. Parameters ------------- data_loader: data loader object intended to be used by the performance sweep. """ def __init__(self, data_loader): self.args = [] self.kwargs = {} self.data_loader = data_loader self.trained_model = None def loader(self, client, response_dtype, fraction, random_state): """ Wrap the data loader method so that it creates a DMatrix from the returned data. """ df, X, y = self.data_loader(client, response_dtype, fraction, random_state) dmatrix = xgb.dask.DaskDMatrix(client, X, y) return dmatrix, dmatrix, dmatrix def __call__(self, *args, **kwargs): """ Acts as a pseudo init function which initializes our model args. """ self.args = args self.kwargs = kwargs return self def fit(self, X): """ Wrap dask.train, and store the model on our proxy object. """ if (self.trained_model): del self.trained_model self.trained_model = xgb.dask.train(*self.args, dtrain=X, evals=[(X, 'train')], **self.kwargs) return self def predict(self, X): assert(self.trained_model) return xgb.dask.predict(*self.args, self.trained_model, X) xgb_proxy = XGBProxy(data_loader) performance_sweep(client=client, model=xgb_proxy, data_loader=xgb_proxy.loader, hardware_type=hardware_type, worker_counts=worker_counts, samples=samples, load_samples=load_samples, max_data_frac=max_data_frac, scaling_type=scale_type, out_path=xgb_csv_path, append_to_existing=append_to_existing, update_workers_in_kwargs=False, xy_fit=False, scaling_denom = scaling_denom, model_args=xg_args, model_kwargs=xg_kwargs) # - visualize_csv_data(xgb_csv_path) # ## Clean Up client.close() cluster.close()
azure/kubernetes/Dask_cuML_Exploration_Full.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 def extract_subtask_AB(fileName,subTask): df = pd.read_csv(fileName,sep='\t').set_index('id') df['GEN_probs']=df.filter(like='-GEN', axis=1).sum(axis=1) df['NGEN_probs']=df.filter(like='NGEN', axis=1).sum(axis=1) df['OAG_probs']=df.filter(like='OAG', axis=1).sum(axis=1) df['CAG_probs']=df.filter(like='CAG', axis=1).sum(axis=1) df['NAG_probs']=df.filter(like='NAG', axis=1).sum(axis=1) df['Sub-task B_preds']=df[['GEN_probs','NGEN_probs']].idxmax(axis=1).apply(lambda x: pd.Series(str(x).split('_'))[0]) df['Sub-task A_preds']=df[['OAG_probs','CAG_probs','NAG_probs']].idxmax(axis=1).apply(lambda x: pd.Series(str(x).split('_'))[0]) return df extract_subtask_AB('dev.tsv','C') # + import pandas as pd def extract_subtask_AB(fileName,subTask): df = pd.read_csv(fileName,sep='\t').set_index('id') column_names=df.filter(like='probs', axis=1).columns.tolist() listA=list(set([ x.split('-')[0] for x in column_names])) listB=list(set([ x[x.find('-')+1:x.find('_')] for x in column_names])) for label in listA: filter_str=r'^{}-'.format(label) print(filter_str) df[label+'_probs']=df.filter(regex=filter_str, axis=1).sum(axis=1) for label in listB: filter_str="-{}".format(label) print(filter_str) df[label+'_probs']=df.filter(regex=filter_str, axis=1).sum(axis=1) prob_listA=[x+'_probs' for x in listA ] prob_listB=[x+'_probs' for x in listB ] df['Sub-task B_preds']=df[prob_listB].idxmax(axis=1).apply( lambda x: pd.Series(str(x).split('_'))[0]) df['Sub-task A_preds']=df[prob_listA].idxmax(axis=1).apply( lambda x: pd.Series(str(x).split('_'))[0]) return df extract_subtask_AB('../ENG/Sub-task C/output/bert-base-cased/dev.tsv','C') # -
notebooks/extractAB_fromC.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 rxitect.models.vanilla.generator import VanillaGenerator from rxitect.structs.vocabulary import SelfiesVocabulary from rdkit.Chem import Draw from rdkit import Chem from typing import List import torch import selfies as sf # - voc = SelfiesVocabulary(vocabulary_file_path="../data/processed/selfies_voc.txt") gen = VanillaGenerator(voc=voc) gen.load_state_dict(torch.load("../models/27022022_epoch=49.pkg")) gen.eval() samples = gen.sample(10) def draw_sampled_selfies(sampled_selfies: torch.Tensor) -> List[str]: """ Helper function that takes generated encoded SELFIES tensors, decodes them to SMILES and draws them on screen. """ dec_sampled = [voc.decode(x) for x in sampled_selfies] smiles = [sf.decoder(x) for x in dec_sampled] Draw.MolsToGridImage([Chem.MolFromSmiles(smi) for smi in smiles]) return smiles smiles =draw_sampled_selfies(samples) Draw.MolsToGridImage([Chem.MolFromSmiles(smi) for smi in smiles])
notebooks/eval_RL_trained_boi.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 # --- # # Linux/Ubuntu # # ## 1 What is Linux # # ### 1.1 History of Linux # # **Unix** was initially designed and implemented at AT&T Bell Labs 1969 by <NAME>, <NAME>, <NAME>, and # <NAME> # # * First released in 1971 and was written in assembly language # # * Re-written in C by <NAME> in 1973 for better portability (with exceptions to the kernel and I/O) # # **Linux Kernel**: [Linus Torvalds(林纳斯·托瓦兹)](https://baike.baidu.com/item/林纳斯·本纳第克特·托瓦兹/1034429?fromtitle=Linus%20Torvalds&fromid=9336769&fr=aladdin), a student at University of Helsinki began working on his own operating system, which became the "Linux Kernel", 1991 # # * Linus released his **kernel** for `free download` and helped further developmen # # * Linux as the kernel only, applications on top of the kernel were still missing # # **Linux System**: Linux kernel + `software` # # * `GNU/Linux(Linux)`: Linux kernel + software from the GNU project released under the `GNU Public License (GPL)`:Free to use, # # * The GNU Project by <NAME> started in 1983 Creating a “complete Unix-compatible software system” with entirely free software # # It appears in many different architectures, from mainframes to **server** to **desktop** to **mobile** and on a staggeringly **wide** variety of hardware. # ### 1.2 Linux is for everyone # # # #### 1.2.1 <b style="color:blue">Linux is everywhere</b> # # * **Linux** powers 100% of the world’s **supercomputers**, # # * most of the **servers** powering the Internet, the majority of financial trades worldwide # # * over billion **Android** and Embeed devices. # # # #### 1.2.2 <b style="color:blue">Linux is important for engineer and scientiste</b> # # **Linux is the preferred platform for scientific computing** # # Linux is also open source, which allows users to peer into its inner workings. # # Download stats across **all packages** on PyPI: # # * https://pypistats.org/packages/__all__ # # The download proportion of **Linux >90%** # # ![pypi-os](./img/linux/pypi-os.jpg) # # Let us to get the PyPI downloads by operating system of packages with `pypistats` # # ``` # >sudo -H python3 -m pip install pypistats # ``` # ``` # >pypistats system package-name # ``` # # **The PyPI downloads by operating system** # # **SciPy packages**: # !pypistats system matplotlib # **CoolProp packages**: # !pypistats system coolprop # For engineer and scientist # # * The **maximum** proportion of the operating system is **Linux.** # # * The **proportion** of using Linux operating system was **higher than** Windows and others. # # **Linux is important for engineer and scientist!** # # ### 1.3 Linux System Architecture # # The Linux system basically works on 4 layers. See the below diagram, shows the layers of of the Linux system architecture. # # ![Architecture-of-Linux](./img/linux/Architecture-of-Linux.png) # # # * **Hardware** − Hardware consists of all physical devices attached to the System. For example: Hard disk drive, RAM, Motherboard, CPU etc. # # * **Kernel** − Kernel is the core component for any (Linux) operating system which directly interacts with the hardware. # # * **Shell** − Shell is the interface which takes input from Users and sends instructions to the Kernel, Also takes the output from Kernel and send the result back to output shell. # # * **Applications** − These are the utility programs which runs on Shell. This can be any application like Your web browser, media player, text editor etc # # # ## 2 Linux Distributions # # * **Essential components**: Linux kernel + GNU system utilities + installation scripts + management utilities etc. # # * Many software vendors release their own packages, known as `distributions` # # * Debian, [Ubuntu](https://www.ubuntu.com/), Linux Mint,[Ubuntukylin](http://www.ubuntukylin.com/) # # * Red Hat,[Fedora](https://getfedora.org/en/), CentOS, Scientific Linux # # * **Mobile** OS: [Android](https://en.wikipedia.org/wiki/Android_(operating_system))(Google),[Tizen](https://www.tizen.org/)(The Linux Foundation) # # **[DistroWatch](https://distrowatch.com/)** # # DistroWatch is a website dedicated to talking about, reviewing and keeping up to date with open source operating systems. # # This site particularly focuses on `Linux distributions` and flavours of BSD, though other open source operating systems are sometimes discussed. # # ## 3 Desktop Environment # # Linux distributions offer a variety of **`desktop environment`**: # # **GNOME,KDE,MATE,Xfce** # # * MATE and Xfce are the more **lightweigh** desktop environments. # # ![Linux-desktop](./img/linux/Linux-desktop.jpg) # # # # ## 5 Ubuntu # # [Ubuntu](https://www.ubuntu.com/) is a free and open-source operating system and [Linux](https://en.wikipedia.org/wiki/Linux) distribution based on [Debian](https://www.debian.org/). # # <NAME>(马克·沙特尔沃思) led a team of developers to establish Ubuntu. # # Ubuntu is offered in three official editions: # # * <b style="color:blue">Ubuntu Desktop</b> for personal computers, # # * <b style="color:blue">Ubuntu Server</b> for servers and the cloud # # * <b style="color:blue">Ubuntu Core</b> for Internet of things devices and robots. # # # The first official Ubuntu release — Version 4.10, codenamed the ‘Warty Warthog(长疣的疣猪)’ — was launched in October 2004 # # * **New releases** of Ubuntu occur every **6** months. # # * The **long-term support (LTS)** releases occur every **2** # # * The most recent LTS is `20.04 LTS` ,supported for ten years. # # >Ubuntu is named after the Southern African philosophy of ubuntu (literally, 'human-ness'), which Canonical suggests can be loosely translated as <b style="color:blue">humanity to others(善待他人)</b> or <b style="color:blue">I am what I am because of who we all are(我存在,因为我们存在)</b> # > # >The African philosophy of “ubuntu” — a concept in which your sense of self is shaped by your relationships with other people. It’s a way of living that begins with the premise that “I am” only because “we are.” # > # # [优麒麟(Ubuntu Kylin)](http://www.ubuntukylin.com/) # # 由中国 CCN(由CSIP、Canonical、NUDT三方联合组建)开源创新联合实验室与天津麒麟信息技术有限公司主导开发的全球开源项目,其宗旨是通过研发用户友好的桌面环境以及特定需求的应用软件,为全球 Linux 桌面用户带来非凡的全新体验! # 优麒麟操作系统是 Ubuntu 官方衍生版,得到来自 Debian、Ubuntu、Mate、LUPA 等国际社区及众多国内外社区爱好者的广泛参与和热情支持 # # [银河麒麟](http://www.kylinos.cn/) # # 银河麒麟操作系统及相关衍生产品已成功应用于国防、政务、电力、金融、能源、教育等行业,基于银河麒麟操作系统和飞腾CPU的自主可控产品及方案已经成为我国自主安全可控信息系统的核心技术应用。 # # **Ubuntu on Windows** # # * [Install Windows Subsystem for Linux (WSL) on Windows 10(Chinese)](https://docs.microsoft.com/zh-cn/windows/wsl/install-win10) # # # ## 6 Using Terminal # # Programmers use **"Terminal"** to issue commands, instead of the graphical user interface # # To launch a Terminal in Debian/Ubuntu: # # * Press `Ctrl+Alt+T` # # * `Right-click` inside a folder/desktop, then,click `open a terminal` # # A Terminal displays a command prompt ending with a `"$"` sign, in the form of: # # `"Username@ComputerName:CurrentDirectory$"` # # You can enter commands after the command prompt. For example, enter "`ls`" to list the contents of the current working directory, e.g., # # ```bash # <prompt>$ls # ``` # !ls # ## 7 Linux File System # # Linux supports numerous file systems, but common choices for the system disk on a block device include the **`ext*`** family (ext2, ext3 and ext4), XFS, JFS, and btrfs. # # **Ext4**(fourth extended filesystem ) is the default file system on most Linux distributions # # >In computing, **a file system** controls how data is stored and retrieved. # # >Without a file system, data placed in a storage medium would be one large body of data with no way to tell where one piece of data stops and the next begins. By separating the data into pieces and giving each piece a name, the data is easily isolated and identified. # # >Taking its name from the way paper-based data management system is named, # > * **file**: each group of data # > * **file system**: the structure and logic rules used to manage the groups of data and their names # # # ### 7.1 Files # # A simple description of the UNIX system, also applicable to Linux, is this: # # * **"On a UNIX system, everything is a file; if something is not a file, it is a process."** # # **Sorts of files** # # Most files are just files, called **regular files**(普通文件): # # * they contain normal data,executable files or programs, input for or output from a program and so on. # # While it is reasonably safe to suppose that **everything you encounter on a Linux system is a file**, there are some exceptions. # # * **Directories** files that are lists of other files. # # * **Special** files: the mechanism used for input and output. Most special files are in `/dev` # # * **Links** : a system to make a file or directory visible in multiple parts of the system's file tree. # # * **(Domain) sockets**: a special file type, similar to TCP/IP sockets, providing inter-process networking protected by the file system's access control. # # * **Named pipes:** act more or less like sockets and form a way for processes to communicate with each other, without using network socket semantics. # # # ### 7.2 File Directory Structure # # * All`files` are arranged in `directories`. # # * These `directores` are organized into the `file system` # # ![Linux File System](./img/linux/linux-file-system.jpg) # # ![dir](./img/linux/linux-dir.jpg) # # **Important Directories** # # * <b style="color:blue">/</b>: the **root** directory # # * <b style="color:blue">/boot</b>: contains `bootable kernel and bootloader`(可引导内核和引导加载程序) # # * <b style="color:blue">/home</b>: contains home directories of **all users**.(所有用户的主目录) # # * This is the directory where you are at when you login to a Linux/UNIX system. # # * <b style="color:blue">/lib,/lib64</b>: contains **libraries** that are essential for system operation, available for use by all users. # # * <b style="color:blue">/bin</b>: contains files that are essential for system operation, available for use by all users. # # * <b style="color:blue">/mnt</b>: A convenient point to `temporarily mount devices`, such as CD-ROMs and flash memory sticks. # # * <b style="color:blue">/etc</b>: contains various system **configurations** # # * <b style="color:blue">/dev</b>: contains various **devices** such as hard disk, CD-ROM drive etc(**In Linux, everything is a file**) # # # # # ![dev](./img/linux/linux-dev.jpg) # # #### 7.2.1 Linux: HOME Directory # # The **/home/** contains home directories of all users. # # This is the directory where you are at when you **login** to a Linux/UNIX system. # # * For regular users, it is typically called <b style="color:blue">/home/username</b> for Ubuntu # * The home directory for superuser 'root' is `/root`. # * System users do not have home directory. # # Consider, a regular user account **"user1"**. # # * He can store his personal files and directories in the directory <b style="color:blue">/home/user1</b>. # # * He can't save files outside his user directory and does not have access to directories of other users. # * For instance, he cannot access directory <b style="color:blue">/home/user2</b> of another user account"user2". # # When **user1** login the Linux operating system, the <b style="color:blue">/home/user1</b> is the default **working directory**. # # ```bash # $pwd # ``` # * `pwd` stands for `Print Working Directory` and is shell built-in command. It prints the complete path of the working directory with the path starting from root **(/)**. # # ![](./img/linux/linux-wd.jpg) # ### 7.3 File Path # # File Path(Definition): position/address in the `directory tree` # # **Absolute path** # # `Uniquely` defined and does **NOT depend on the current path** # # An absolute path begins from the **root** directory. That is, it starts with a `"/"` followed by all the sub-directories, separated with `"/"` leading to the file, e.g., `"/usr/lib/jvm/jdk1.7.0_07/bin/".` # # **Relative path** # # A relative path is relative to the so-called **current working directory**. A relative path does NOT begin with "/" or "~". # # For example, # # if the current working directory is `"/usr/lib/jvm/"`, then the relative pathname "`jdk1.7.0_07/bin/" `refers to `"/usr/lib/jvm/jdk1.7.0_07/bin/".` # # # **Change Directory `"cd"` Command** # # To change the current working directory, issue command `"cd <new-pathname>"`. # # You can specify new-pathname in two ways: `absolute` or `relative`. # # As explained earlier, an absolute path begins with a `"/" (root directory) or "~"` (home directory); # # whereas a relative path is relative to the `current working directory` and does NOT begin with "/" or "~". For example, # # ```bash # # cd / // Change directory (absolute) to the root # # cd /usr/local // Change directory (absolute) to "/usr/local" # # cd demo // Change directory (relative) to demo of the current directory # # cd demo/bin // Change directory (relative) to demo/bin of the current directory # ``` # **Root (/), Home (~), Parent (..), Current (.) Previous (-) Directory** # # * "/" to denote the root; # # * "~" to refer to your home directory; # # * ".." (double-dot) to refer to the parent directory; * # # * "." (single-dot) to refer to the current directory; # # * "-" (dash) to refer to the previous directory. # # For example, # # # ```bash # # cd ~ // Change directory to the home directory of the current user # # cd // same as above, default for "cd" is home directory # # cd ~/Documents // Change directory to the sub-directory "Documents" of the home directory of the current user # # cd .. // Change directory to the parent directory of the current working directory # # cd - // Change directory to the previous working directory (OLDPWD) # ``` # # For example,we open the terminal in root,then # # ![](./img/linux/linux-path-1.jpg) # # **List Directory `"ls"` Command** # # You can use command `ls` to list the contents of the current working directory, e.g., # # List contents of current working directory in short format # # # !ls # List in "long" format # !ls -l # ![](./img/linux/ls.jpg) # ### 7.4 Linux is Case Sensitive # # All names are **case sensitive** # # * Commands, variables, files etc. # # Example: `MyFile.txt, myfile.txt, MYFILE.TXT` are three different files in Linux # # # ### 7.5 Linux File Permission # # Designed as the multi **user** environment, the **access restriction** of files to other users on the system is embedded. # # ![](./img/UnixFileLongFormat.png) # # Three types of **file permission** # # * Read (r) # # * Write (w) # # * Execute (x) # # Three types of **user** # # * User (u) (owner) # # * Group (g) (group members) # # * World (o) (everyone else on the system) # # Each file in Linux has the following attributes: # # * `Owner permissions`: determine what actions the owner of the file can perform on a file # # * `Group permissions`: determine what actions a user, who is a member of the group that a file belongs to, can perform on a file # # * `Other(world) permissions`: indicate what action all other users can perform on a file # # # The `-l`option to **ls** displays the file type,using the **first column** indicates the type of a **file/dir/link** # # * `d`: for directory # # * `l`: for `symbolic link`(符号链接(软链接):将路径名链接到一个文件) # # * `-` for normal file # # > **A symbolic link** is a `file` that links to another file or directory using its path. you can think of a symbolic link as `a shortcut` to a file or directory (folder). symbolic links may be used in the command line, or in a script or another program. # # # ![UnixFileLongFormat.png](./img/linux/UnixFileLongFormat.png) # # ![linux-file-permissions.jpg](./img/linux/linux-file-permission.jpg) # # ### 7.6 Changing File Permission # # **chmod** is a *NIX command to change permissions on a file # # Usage: # ```bash # chmod <option> <permissions> <file or directory name> # ``` # **chmod in Symbolic Mode:** # # |Chmod| operator Description| # |:-------:|:--------:| # |+ |Adds the designated permission(s) to a file or directory| # |- |Removes the designated permission(s) from a file or directory| # |= |Sets the designated permission(s) and removes other permission(s| # # ```bash # $chmod u-x filename # ``` # ![](./img/linux/linux-hello.png) # ## 8 Applications and Utilities # # * **LibreOffice**: The default Ubuntu's productivity suite, which is a variant of OpenOffice (currently owned by Apache). It includes: # # * Writer: word processor, similar to Microsoft Word. # * Calc: spreadsheet, similar to Microsoft Excel. # * Impresss: Presentation program, similar to Microsoft Powerpoint. # * Math: Math formula editor. # * Draw: Graphics application for creating images. # * Base: Database application, similar to Microsoft Access. # # * **Dia**: Technical diagram drawing editor, similar to Microsoft Visio. # # * **gedit** Text Editor: The GNU gedit is the default text editor in Ubuntu. # # * **Screenshot**: Press `PrintScreen` key to capture the entire screen; `alt+PrintScreen` key to capture the current window. The images are captured in PNG. Alternatively, use the dash to search for `"Screenshot"`. You can set the area of screenshot. # # ## 9 APT for Managing Software # # Ubuntu adopts Debian's **Advanced Packaging Tool (APT)** for software package management of `".deb"` package. # # >Other Linux distros, such as Red Hat, uses RPM Package Manager. # # APT can properly handle the dependencies. It automatically finds and downloads all the dependencies of the packages to be installed. It can also resume installation after an interruption. # # The apt includes sub-commands such as `list, search, show, update, install, remove, upgrade, full-upgrade, edit-source`. # # ### 9.1 Software sources # # `APT` keeps a list of software sources on your computer in a file at `/etc/apt/sources.list`. # # Before installing software, you **should update your package list** with apt update: # # ``` # sudo apt update # ``` # # > **Superuser 'root' and Superuser-do 'sudo'** # > # > **Superuser root** # > # > In Linux, the default **superuser** is called `root`, which can do everything and anything, including destructive tasks. # > # > Doing regular tasks (such as program development) with root can be dangerous, as root could remove important system files and destroy your > system. Hence, it is strongly recommended to do regular work with a regular user instead of superuser. # > # > However, at times, you need the **superuser privilege to perform a task**, such as install a new software and writing to a system > directory. You can do it in two ways: **sudo (superuser-do)** # > # > **sudo <command>** # > # > An authorized user can run a command with `superuser privilege by prefixing it with 'sudo'` (superuser-do). # > # > * The list of users authorized to do 'sudo' is kept in /etc/sudoers (called sudo list). # > # > When you issue **sudo <command>**, the system will prompt for **password** Reply with the CURRENT login-user's password. # # ### 9.2 Installing a package with APT # # Installing a package with APT # # ``` # sudo apt install git # ``` # # ### 9.3 Uninstalling a package with APT # # * Remove # # You can uninstall a package with `apt remove`: # ``` # sudo apt remove git # ``` # # * Purge # # You can also choose to `completely remove the package and its associated configuration files` with `apt purge` # ``` # sudo apt purge git # ``` # # ### 9.4 Upgrading existing software # # If software updates are available, you can get the updates with # # ``` # sudo apt update # ``` # # install the updates with # # ``` # sudo apt upgrade # ``` # # which will upgrade all of your packages. # # To upgrade a `specific` package, without upgrading all the other out-of-date packages at the same time, you can use # ``` # sudo apt install somepackage # ``` # which may be useful if you're low on disk space or you have limited download bandwidth. # # ### 9.5 Searching for software # You can search the archives for a package with a given keyword with `apt search` # # ``` # apt search python3-pip # ``` # You can view more information about a package before installing it with `apt show` # # ``` # apt show python3-pip # ``` # # ### 9.6 Installing a package with dpkg # # * `dpkg:` The dpkg (Debian Package Manager) is the low level tool for installing, removing and providing information about '.deb' packages. # # ```bash # sudo dpkg -i vscode_filename.deb # ``` # # # Reference # # * [How to install and Get Started with Ubuntu Desktop 16.04LTS](http://www3.ntu.edu.sg/home/ehchua/programming/howto/Ubuntu_HowTo.html) # # * edX: Introduction to Linux https://www.edx.org/course/introduction-to-linux # # * Ubuntu https://www.ubuntu.com/ # # * Ubuntukylin https://www.ubuntukylin.com/ # #
notebook/Unit8-1-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 # --- # # Scikit-Learn # # * [Preprocess dataset](#preprocess_dataset) # * [Divide into train and test](#divide_train_test) # * [PCA](#PCA) # * [Clustering](#clustering) # * [Silhouette](#silhouette) # * [Classifier](#classifier) # * [Predict](#predict) # * [Evaluate](#evaluate) # + import numpy as np from sklearn import datasets import matplotlib.pyplot as plt ### Load Dataset iris = datasets.load_iris() X = iris.data y = iris.target print(X[:10]) print(y[:10]) # - # <a id='preprocess_dataset'></a> # ## Preprocess dataset # <a id='divide_train_test'></a> # ### Divide into train and test 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) print("From the datasets X and y") print(np.shape(X) ) print(np.shape(y) ) print("It has been split into train and test:") print("Size of train:") print(np.shape(x_train) ) print(np.shape(y_train) ) print("Size of test:") print(np.shape(x_test) ) print(np.shape(y_test) ) # <a id='PCA'></a> # ### PCA # Define a function to compute PCA and perform a scatterplot from sklearn.decomposition import PCA import matplotlib.pyplot as plt def plot_dataset(X,colors): pca = PCA(n_components=2) pca.fit(X) principalComponents = pca.fit_transform(X) plt.scatter(principalComponents[:, 0], principalComponents[:, 1],c=colors) plt.show() # <a id='clustering'></a> # ## Clustering # + from sklearn.cluster import DBSCAN db = DBSCAN(eps=0.3, min_samples=5).fit(x_train) #use db.labels_ as colors plot_dataset(x_train,db.labels_) # - from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=3, random_state=0).fit(x_train) plot_dataset(x_train,kmeans.labels_) # <a id='silhouette'></a> # ### Silhouette # + from sklearn import metrics silhouette_scores=[] for i in range(2,10): kmeans = KMeans(n_clusters=i, random_state=0).fit(x_train) labels = kmeans.labels_ silhouette=metrics.silhouette_score(x_train, labels, metric='euclidean') silhouette_scores.append(silhouette) plt.plot(silhouette_scores) plt.show() # - # <a id='classifier'></a> # ## Classifier ### Train KNN from sklearn import neighbors n_neighbors = 15 clf = neighbors.KNeighborsClassifier(n_neighbors) clf.fit(x_train, y_train) # <a id='predict'></a> # ### Predict # Make a prediction y_predicted = clf.predict( x_test ) print(y_predicted) # <a id='evaluate'></a> # ### Evaluate from sklearn.metrics import confusion_matrix confusion_matrix(y_test, y_predicted) from sklearn.metrics import precision_recall_fscore_support precision,recall,f_score,support = precision_recall_fscore_support(y_test, y_predicted, average='macro') print(precision) print(recall) print(f_score)
documents/scikit-learn.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 # --- # # THE SPARKS FOUNDATION # # Task-6 Prediction using Decision Tree Algorithm # # ### By <NAME> # + #importing all the required libraries import numpy as np import pandas as pd import sklearn.metrics as sm import seaborn as sns import matplotlib.pyplot as mt # %matplotlib inline from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.tree import plot_tree from sklearn.preprocessing import LabelEncoder from sklearn.metrics import confusion_matrix, classification_report # - #reading the data data=pd.read_csv('Iris.csv',index_col=0) data.head() data.info() # We can see there is no null values. data.describe() # # Input data visualization sns.pairplot(data, hue='Species') # We can observe that speciesv "Iris Setosa" makes a distinctive cluster in every parameter, while other two species overlap a bit each other. # # Finding the correlation matrix data.corr() # In next step, using heatmap to visulaize data sns.heatmap(data.corr()) # We observed that: # (i)Petal length is highly related to petal width # (ii)Sepal length is not related to sepal width # # Data preprocessing target=data['Species'] df=data.copy() df=df.drop('Species', axis=1) df.shape #defingi the attributes and labels X=data.iloc[:, [0,1,2,3]].values le=LabelEncoder() data['Species']=le.fit_transform(data['Species']) y=data['Species'].values data.shape # # Trainig the model # We will now split the data into test and train. X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42) print("Traingin split:",X_train.shape) print("Testin spllit:",X_test.shape) # Defining Decision Tree Algorithm dtree=DecisionTreeClassifier() dtree.fit(X_train,y_train) print("Decision Tree Classifier created!") # # Classification Report and Confusion Matrix y_pred=dtree.predict(X_test) print("Classification report:\n",classification_report(y_test,y_pred)) print("Accuracy:",sm.accuracy_score(y_test,y_pred)) # The accuracy is 1 or 100% since i took all the 4 features of the iris dataset. #confusion matrix cm=confusion_matrix(y_test,y_pred) cm # # Visualization of trained model #visualizing the graph mt.figure(figsize=(20,10)) tree=plot_tree(dtree,feature_names=df.columns,precision=2,rounded=True,filled=True,class_names=target.values) # The Descision Tree Classifier is created and is visaulized graphically. Also the prediction was calculated using decision tree algorithm and accuracy of the model was evaluated.
Decision_tree.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: ElastixEnv # language: python # name: elastixenv # --- # ## 1. Simple Elastix # ### Registration # First import is currently necessary to run ITKElastix on MacOs from itk import itkElastixRegistrationMethodPython import itk from itkwidgets import compare, checkerboard import numpy as np # **Image registration** finds the *spatial transformation that aligns images in the presence of noise*. # In image registration, we typically identify the two images as the fixed and moving image. Our goal is to find the spatial transformation that makes the moving image align with the fixed image. # # First, let's load our **fixed image** and the image we will align to our fixed image, the **moving image**. # Load images with itk floats (itk.F). Necessary for elastix fixed_image = itk.imread('data/CT_2D_head_fixed.mha', itk.F) moving_image = itk.imread('data/CT_2D_head_moving.mha', itk.F) # For now we will use a default parametermap of elastix, for more info about parametermaps, see [example2](ITK_Example02_CustomOrMultipleParameterMaps.ipynb#section_id2) parameter_object = itk.ParameterObject.New() default_rigid_parameter_map = parameter_object.GetDefaultParameterMap('rigid') parameter_object.AddParameterMap(default_rigid_parameter_map) # Registration can either be done in one line with the registration function... # Call registration function result_image, result_transform_parameters = itk.elastix_registration_method( fixed_image, moving_image, parameter_object=parameter_object, log_to_console=False) # .. or by initiating an elastix image filter object. The result of these to methods should only differ due to the stochastic nature of elastix. # # The object oriented method below can be used when more explicit function calls are preferred. # + # Load Elastix Image Filter Object elastix_object = itk.ElastixRegistrationMethod.New() elastix_object.SetFixedImage(fixed_image) elastix_object.SetMovingImage(moving_image) elastix_object.SetParameterObject(parameter_object) # Set additional options elastix_object.SetLogToConsole(False) # Update filter object (required) elastix_object.UpdateLargestPossibleRegion() # Results of Registration result_image = elastix_object.GetOutput() result_transform_parameters = elastix_object.GetTransformParameterObject() # - # Save image with itk itk.imwrite(result_image,'exampleoutput/result_image.mha') # The output of the elastix algorithm is the registered (transformed) version of the moving image. The parameters of this transformation can also be obtained after registation. # ### Visualization # The results of the image registration can be visualized with widgets from the itkwidget library such as the checkerboard and compare widgets. checkerboard(fixed_image, result_image) compare(fixed_image, result_image, link_cmap=True) # + # import napari # + # Cast result images to numpy arrays for Napari Viewer # fixed_image_np = np.asarray(fixed_image).astype(np.float32) # moving_image_np = np.asarray(moving_image).astype(np.float32) # result_image_np = np.asarray(result_image).astype(np.float32) # - # with napari.gui_qt(): # viewer = napari.Viewer() # viewer.add_image(fixed_image_np) # viewer.add_image(moving_image_np) # viewer.add_image(result_image_np)
examples/ITK_Example01_SimpleRegistration.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:GAT] # language: python # name: conda-env-GAT-py # --- # + import pandas as pd import torch # %matplotlib inline import time import numpy as np from torchvision import datasets from torchvision import transforms import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader # - DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # + # Note transforms.ToTensor() scales input images to 0-1 range train_dataset = datasets.MNIST(root='data', train=True, transform=transforms.ToTensor(), download=True) test_dataset = datasets.MNIST(root='data', train=False, transform=transforms.ToTensor()) train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=BATCH_SIZE, shuffle=False) # Checking the dataset for images, labels in train_loader: # (128, 1, 28, 28) = (batch_size, color, height, width) print('Image batch dimensions:', images.shape) # (128, 1) = (batch_size, 1) print('Image label dimensions:', labels.shape) break # + class NLP(torch.nn.Module): def __init__(self, n_features, n_hidden, n_classes): super().__init__() self.n_classes = n_classes self.model = nn.Sequential( nn.Flatten(), nn.Linear(n_features, n_hidden), nn.Sigmoid(), nn.Linear(n_hidden, n_classes), ) def forward(self, x): logits = self.model(x) probas = torch.softmax(logits, dim=1) return logits, probas # negative log-liklihood loss def nll_loss(x, y): y = torch.from_numpy(np.take(np.eye(10), y, axis=0)) return torch.sum(x * y) def get_accuracy(logits, y): pred = torch.argmax(logits, axis=1) corr_pred = torch.sum(pred == y) return corr_pred / len(y) def nll_loss_test(model, dataloader): curr_loss = 0 model.eval() # disable norms and dropout with torch.no_grad(): # disable backprop for i, (imgs, labels) in enumerate(dataloader): imgs.to(DEVICE) labels.to(DEVICE) logits, probas = model(imgs) curr_loss += nll_loss(probas, labels) return curr_loss / (i + 1) # + BATCH_SIZE = 256 EPOCHS = 500 model = NLP(n_features=28*28, n_hidden=64, n_classes=10).to(DEVICE) opt = torch.optim.SGD(model.parameters(), lr=.1) ## Training Phase for epoch in range(EPOCHS): model.train() cum_loss = 0 corr_pred = 0 for i, (imgs, labels) in enumerate(train_loader): imgs.to(DEVICE) labels.to(DEVICE) logits, probas = model(imgs) loss = nll_loss(probas, labels) cum_loss += loss corr_pred += get_accuracy(logits, labels) opt.zero_grad() loss.backward() opt.step() if not epoch % (EPOCHS // 100): print(f"Epoch: {epoch:03d} | Train. Loss: {cum_loss / (i + 1):.4f} | Train Acc: {corr_pred / len(train_loader) * 100:.2f}% \ | Test Loss: {nll_loss_test(model, test_loader):.4f}") # -
ch9/mlp-pytorch_softmax.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 numpy import pi import mbuild as mb from mbuild.lib.atoms import H from mbuild.lib.surfaces import Betacristobalite from mbuild.lib.recipes.polymer import Polymer from pmpc.mpc import MPC from mbuild.lib.moieties.peg import PegMonomer # - # %cd pmpc # + from numpy import pi import mbuild as mb from mbuild.lib.atoms import H from mbuild.lib.surfaces import Betacristobalite from brush import Brush class PMPCLayer(mb.lib.recipes.Monolayer): """Create a layer of grafted pMPC brushes on a beta-cristobalite surface.""" def __init__(self, pattern, tile_x=1, tile_y=1, chain_length=4, alpha=pi / 4): surface = Betacristobalite() brush = Brush(chain_length=chain_length, alpha=alpha) hydrogen = H() super(PMPCLayer, self).__init__(surface, brush, backfill=hydrogen, pattern=pattern, tile_x=tile_x, tile_y=tile_y) Brush(chain_length=4).visualize(backend='nglview',show_ports=True) # - monomer = MPC() monomer.visualize(backend='nglview') chain = mb.recipes.Polymer() monomer = MPC() chain.add_monomer(monomer, indices=[19, 22], separation = .15,replace=True) # chain.add_end_groups(CH3(), index=30, separation=.15) chain.build(n = 10) chain.visualize(backend='nglview') monomer = MPC() # print(list(enumerate(list(monomer.particles())))) # print(list(monomer.available_ports())[0]) # print(list(monomer.available_ports())[1]) monomer.visualize(show_ports=True, backend='nglview') # monomer.visualize(show_ports=True) chain = Polymer() chain.add_monomer(compound=monomer, separation=.15, indices=[1, 37]) # chain.add_end_groups(H()) chain.build(n=5, sequence='A')
pmpc_WIP.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 # --- # <h1>Auto Encoder</h1> # <h6><NAME></h6> # Date: 01 July 2019 # + #in autoencoding we first encode the image to compress the image and then decoding or expanding image #since compression is dataset dependent therefore we will not use it to #it is actually used to clrear the noise #it is unsupervised #we use it for noise removal # - import numpy as np import matplotlib.pyplot as plt # %matplotlib inline from keras.datasets import mnist (x_train, _ ), (x_test, _) = mnist.load_data() #we dont require y_train or y_test because unsupervised learning, model will learn itself x_train=x_train.astype('float32')/255 #Normalizing x_test=x_test.astype('float32')/255 #Normalizing x_train=x_train.reshape(-1,28,28,1) x_test=x_test.reshape(-1,28,28,1) print(x_test.shape,x_train.shape) # + #adding random noise 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.) # value less than 0 becomes 0 and greatefr than 1 becomes 1 x_test_noisy =np.clip(x_test_noisy,0.,1.) # value less than 0 becomes 0 and greatefr than 1 becomes 1 # - n=10 plt.figure(figsize=(20,2)) for i in range(1, n+1): ax= plt.subplot(1,n,i) plt.imshow(x_test_noisy[i].reshape(28,28)) plt.gray() plt.show() import keras from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D from keras.models import Model # + #Encoder input_img= Input(shape=(28,28,1)) x=Conv2D(32, (3,3), activation='relu', padding = 'same')(input_img) #here the dimension of the image remains same because we have used padding='same' x=MaxPooling2D((2,2), padding='same')(x) #here dimension becomes half x=Conv2D(32, (3,3), activation='relu', padding = 'same')(x) #here the dimension of the image remains same because we have used padding='same' encoded=MaxPooling2D((2,2), padding='same')(x) # 'same' gives us the matrix one greater dimension if the dimension is odd so that no data is lost # 'valid' removes one dimension therefore data is lost #decoder x=Conv2D(32, (3,3), activation='relu', padding = 'same')(encoded) x=UpSampling2D((2,2))(x) x=Conv2D(32, (3,3), activation='relu', padding = 'same')(x) x=UpSampling2D((2,2))(x) decoded= Conv2D(1, (3,3), activation='sigmoid', padding='same')(x) autoencoder = Model(input_img, decoded) autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy') # - autoencoder.summary() autoencoder.fit(x_train_noisy, x_train, epochs=10, batch_size=128, shuffle=True,validation_data=(x_test_noisy,x_test))
Deep Learning/Auto Encoder/Auto Encoders.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 # --- # # miRNA Pipeline # ## Be sure to install paramiko and scp with pip before using this notebook # ## 1. Configure AWS key pair, data location on S3 and the project information # This cell only contains information that you, the user, should input. # # #### String Fields # # **s3_input_files_address**: This is an s3 path to where your input fastq files are found. This shouldn't be the path to the actual fastq files, just to the directory containing all of them. All fastq files must be in the same s3 bucket. # # **s3_output_files_address**: This is an s3 path to where you would like the outputs from your project to be uploaded. This will only be the root directory, please see the README for information about exactly how outputs are structured # # **design_file**: This is a path to your design file for this project. Please see the README for the format specification for the design files. # # **your_cluster_name**: This is the name given to your cluster when it was created using cfncluster. # # **private_key**: The path to your private key needed to access your cluster. # # **project_name**: Name of your project. There should be no whitespace. # # **workflow**: The workflow you want to run for this project. For the miRNASeq pipeline the possible workflow is "bowtie2". # # **genome**: The name of the reference you want to use for your project. Currently only "human" is supported here. # # #### analysis_steps # This is a set of strings that contains the steps you would like to run. The order of the steps does not matter. # # posible bowtie2 steps: "fastqc", "trim", "cut_adapt", "align_and_count", "multiqc" # + import os import sys from util import PipelineManager from util import DesignFileLoader ## S3 input and output addresses. # Notice: DO NOT put a forward slash at the end of your addresses. s3_input_files_address = "s3://ucsd-ccbb-interns/Mengyi/mirna_test/20171107_Tom_miRNASeq/fastq" s3_output_files_address = "s3://ucsd-ccbb-interns/Mustafa/smallrna_test" ## Path to the design file design_file = "../../data/cirrus-ngs/mirna_test_design.txt" ## CFNCluster name your_cluster_name = "mustafa8" ## The private key pair for accessing cluster. private_key = "/home/mustafa/keys/interns_oregon_key.pem" ## Project information # Recommended: Specify year, month, date, user name and pipeline name (no empty spaces) project_name = "test_project" ## Workflow information: only "bowtie2" now workflow = "bowtie2" ## Genome information: currently available genomes: human, mouse genome = "mouse" ## "fastqc", "trim", "cut_adapt", "align_and_count", "merge_counts", "multiqc" analysis_steps = {"fastqc", "trim", "cut_adapt", "align_and_count","multiqc"} ## If delete cfncluster after job is done. delete_cfncluster = False print("Variables set.") # - # ## 2. Create CFNCluster # Following cell connects to your cluster. Run before step 3. sys.path.append("../../src/cirrus_ngs") from cfnCluster import CFNClusterManager, ConnectionManager ## Create a new cluster master_ip_address = CFNClusterManager.create_cfn_cluster(cluster_name=your_cluster_name) ssh_client = ConnectionManager.connect_master(hostname=master_ip_address, username="ec2-user", private_key_file=private_key) # ## 3. Run the pipeline # This cell actually executes your pipeline. Make sure that steps 1 and 2 have been completed before running. # + ## DO NOT edit below reference = "hairpin_{}".format(genome) print(reference) sample_list, group_list, pair_list = DesignFileLoader.load_design_file(design_file) PipelineManager.execute("SmallRNASeq", ssh_client, project_name, workflow, analysis_steps, s3_input_files_address, sample_list, group_list, s3_output_files_address, reference, "NA", pair_list) # - # ## 4. Check status of pipeline # This allows you to check the status of your pipeline. You can specify a step or set the step variable to "all". If you specify a step it should be one that is in your analysis_steps set. You can toggle how verbose the status checking is by setting the verbose flag (at the end of the second line) to False. step="all" PipelineManager.check_status(ssh_client, step, "SmallRNASeq", workflow, project_name, analysis_steps,verbose=True) # ## 5. Display MultiQC report # ### Note: Run the cells below after the multiqc step is done # Download the multiqc html file to local notebook_dir = os.getcwd().split("notebooks")[0] + "data/" # !aws s3 cp $s3_output_files_address/$project_name/$workflow/multiqc_report.html $notebook_dir # + from IPython.display import IFrame IFrame(os.path.relpath("{}multiqc_report.html".format(notebook_dir)), width="100%", height=1000) # -
notebooks/cirrus-ngs/miRNAPipeline.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.9.9 ('pangeo-forge-recipes') # language: python # name: python3 # --- # # Running your recipe on Pangeo Forge Cloud # # Welcome to the Pangeo Forge introduction tutorial! This is the 3rd part in a sequence, the flow of which is described {doc}`here </introduction_tutorial/index>`. # ## Outline Part 3 # # We are at an exciting point - transitioning to [Pangeo Forge Cloud](../pangeo_forge_cloud/index.md). In this part of the tutorial we are setting up our recipe, which we have thus far only run in a limited compute environment on a small section of data, to run at scale in the cloud. In order to do that we will need to: # # 1. Fork the `staged-recipes` repo # 2. Add the recipe files: a `.py` file and a `meta.yaml` file # 4. Make a PR to the `staged-recipes` repo # # ### A note for Sandbox users # If you have been using the [Pangeo Forge Sandbox](../pangeo_forge_recipes/installation.md#pangeo-forge-sandbox) for the first two parts that's great. In order to complete this part of the tutorial you will have to complete step 1 locally, and download the files you make in step 2 in order to make the PR in step 3. # ## Fork the `staged-recipes` repo # # [`pangeo-forge/staged-recipes`](https://github.com/pangeo-forge/staged-recipes) is a repository that exists as a staging ground for recipes. It is where recipes get reviewed before they are run. Once the recipe is run the code will be transitioned to its own repository for that recipe, called a [Feedstock](../pangeo_forge_cloud/core_concepts.md). # # You can fork a repo through the web browser or the Github CLI. Checkout the [Github docs](https://docs.github.com/en/get-started/quickstart/fork-a-repo) for steps how to do this. # ## Add the recipe files # # Within `staged-recipes`, recipes files should go in a new folder for your dataset in the `recipes` subdirectory. The name of the new folder will become the name of the feedstock repository, the repository where the recipe code will live after the data have been processed. # # In the example below we call the folder `oisst`, so the feedstoack will be called `oisst-feedstock`. The final file structure we are creating is this: # # ``` # staged-recipes/recipes/ # └──oisst/ #    ├──recipe.py #    └──meta.yaml # ``` # The name of the folder `oisst` would vary based on the name of the dataset. # ### Copy the recipe code into a single `.py` file # # Within the `oisst` folder create a file called `recipe.py` and copy the recipe creation code from the first two parts of this tutorial. We don't have to copy any of the code we used for local testing - the cloud automation will take care of testing and scaling the processing on the cloud infrastructure. We will call this file `recipe.py` the **recipe module**. For OISST it should look like: # + import pandas as pd from pangeo_forge_recipes.patterns import ConcatDim, FilePattern from pangeo_forge_recipes.recipes import XarrayZarrRecipe dates = pd.date_range('1981-09-01', '2022-02-01', freq='D') def make_url(time): yyyymm = time.strftime('%Y%m') yyyymmdd = time.strftime('%Y%m%d') return ( 'https://www.ncei.noaa.gov/data/sea-surface-temperature-optimum-interpolation/' f'v2.1/access/avhrr/{yyyymm}/oisst-avhrr-v02r01.{yyyymmdd}.nc' ) time_concat_dim = ConcatDim("time", dates, nitems_per_file=1) pattern = FilePattern(make_url, time_concat_dim) recipe = XarrayZarrRecipe(pattern, inputs_per_chunk=2) # - # Another step, complete! # ## Create a `meta.yaml` file # # The `meta.yaml` is a YAML file. YAML is a common language used for writing configuration files. `meta.yaml` contains two important things: # 1. metadata about the recipe # 2. the [Bakery](../pangeo_forge_cloud/core_concepts.md), designating the cloud infrastructure where the recipe will be run and stored. # # Here we will walk through each field of the `meta.yaml`. A template of `meta.yaml` is also available [here](https://github.com/pangeo-forge/sandbox/blob/main/recipe/meta.yaml). # # ### `title` and `description` # # These fields describe the dataset. They are not highly restricted. # # ```{code-block} yaml # :lineno-start: 1 # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # ``` # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :emphasize-lines: 1, 2 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # ``` # ### `pangeo_forge_version` # # This is the version of the `pangeo_forge_recipes` library that you used to create the recipe. It's important to track in case someone wants to run your recipe in the future. Conda users can find this information with `conda list`. # # ```{code-block} yaml # :lineno-start: 3 # pangeo_forge_version: "0.8.2" # ``` # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :lineno-start: 1 # :emphasize-lines: 3 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # pangeo_forge_version: "0.6.2" # ``` # ### `recipes` section # # The `recipes` section explains the recipes contained in the **recipe module** (`recipe.py`). This feels a bit repetitive in the case of OISST, but becomes relevant in the case where someone is defining multiple recipe classes in the same recipe module, for example with different chunk schemes. # # ```{code-block} yaml # :lineno-start: 4 # recipes: # - id: noaa-oisst-avhrr-only # object: "recipe:recipe" # ``` # The id `noaa-oisst-avhrr-only` is the name that we are giving our recipe class. It is a string that we as the maintainer chose. # The entry `recipe:recipe` describes where the recipe Python object is. We are telling it that our recipe object is in a file called `recipe`, inside of of a variable called `recipe`. Unless there is a specific reason to deviate, `recipe:recipe` is a good convention here. # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :lineno-start: 1 # :emphasize-lines: 4-6 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # pangeo_forge_version: "0.6.2" # recipes: # - id: noaa-oisst-avhrr-only # object: "recipe:recipe" # ``` # ### `provenance` section # # Provenance explains the origin of the dataset. The core information about provenance is the `provider` field, which is outlined as part of the STAC Metadata Specification. See the [STAC Provider docs](https://github.com/radiantearth/stac-spec/blob/master/collection-spec/collection-spec.md#provider-object) for more details. # # ```{code-block} yaml # :lineno-start: 7 # provenance: # providers: # - name: "NOAA NCEI" # description: "National Oceanographic & Atmospheric Administration National Centers for Environmental Information" # roles: # - producer # - licensor # url: https://www.ncdc.noaa.gov/oisst # license: "CC-BY-4.0" # ``` # One field to highlight is the `license` field, described in the STAC docs [here](https://github.com/radiantearth/stac-spec/blob/master/collection-spec/collection-spec.md#license). It is important to locate the licensing information of the dataset and provide it in the `meta.yaml`. # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :lineno-start: 1 # :emphasize-lines: 7-15 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # pangeo_forge_version: "0.6.2" # recipes: # - id: noaa-oisst-avhrr-only # object: "recipe:recipe" # provenance: # providers: # - name: "NOAA NCEI" # description: "National Oceanographic & Atmospheric Administration National Centers for Environmental Information" # roles: # - producer # - licensor # url: https://www.ncdc.noaa.gov/oisst # license: "CC-BY-4.0" # ``` # ### `maintainers` section # # This is information about you, the recipe creator! Multiple maintainers can be listed. The required fields are `name` and `github` username; `orcid` and `email` may also be included. # # ```{code-block} yaml # :lineno-start: 17 # maintainers: # - name: "<NAME>" # orcid: "9999-9999-9999-9999" # github: dvaughan0987 # ``` # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :lineno-start: 1 # :emphasize-lines: 16-19 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # pangeo_forge_version: "0.6.2" # recipes: # - id: noaa-oisst-avhrr-only # object: "recipe:recipe" # provenance: # providers: # - name: "NOAA NCEI" # description: "National Oceanographic & Atmospheric Administration National Centers for Environmental Information" # roles: # - producer # - licensor # url: https://www.ncdc.noaa.gov/oisst # license: "CC-BY-4.0" # maintainers: # - name: "<NAME>" # orcid: "9999-9999-9999-9999" # github: dvaughan0987 # ``` # ### `bakery` section # # **Bakeries** are where the work gets done on Pangeo Forge Cloud. A single bakery is a set of cloud infrastructure hosted by a particular institution or group. # # Selecting a `bakery` is how you choose where the recipe will be run and hosted. The [Pangeo Forge website](https://pangeo-forge.org/dashboard/bakeries) hosts a full list of available bakeries. # # ```{code-block} yaml # :lineno-start: 17 # bakery: # id: "pangeo-ldeo-nsf-earthcube" # ``` # ```{admonition} Full File Preview # :class: dropdown # ```{code-block} yaml # :lineno-start: 1 # :emphasize-lines: 20, 21 # # title: "NOAA Optimum Interpolated SST" # description: "1/4 degree daily gap filled sea surface temperature (SST)" # pangeo_forge_version: "0.6.2" # recipes: # - id: noaa-oisst-avhrr-only # object: "recipe:recipe" # provenance: # providers: # - name: "NOAA NCEI" # description: "National Oceanographic & Atmospheric Administration National Centers for Environmental Information" # roles: # - producer # - licensor # url: https://www.ncdc.noaa.gov/oisst # license: "CC-BY-4.0" # maintainers: # - name: "<NAME>" # orcid: "9999-9999-9999-9999" # github: dvaughan0987 # bakery: # id: "pangeo-ldeo-nsf-earthcube" # ``` # And that is the `meta.yaml`! Between the `meta.yaml` and `recipe.py` we have now put together all the files we need for cloud processing. # ## Make a PR to the `staged-recipes` repo # # At this point you should have created two files - `recipe.py` and `meta.yaml` and they should be in the new folder you created for your dataset in `staged-recipes/recipes`. # # It's time to submit the changes as a Pull Request. Creating the Pull Request on Github is what officially submits your recipe for review to run. If you have opened an issue for your dataset you can reference it in the Pull Request. Otherwise, provide a notes about the datasets and hit submit! # ## After the PR # # With the PR in, all the steps to stage the recipe are complete! At this point a [`@pangeo-forge-bot`](https://github.com/pangeo-forge-bot) will perform a series of automated checks on your PR, a full listing of which is provided in {doc}`../pangeo_forge_cloud/pr_checks_reference`. # # All information you need to contribute your recipe to Pangeo Forge Cloud will be provided in the PR discussion thread by either [`@pangeo-forge-bot`](https://github.com/pangeo-forge-bot) or a human maintainer of Pangeo Forge. # # Merging the PR will transform your submitted files into a new Pangeo Forge [Feedstock repository](../pangeo_forge_cloud/core_concepts.md) and initiate full builds for all recipes contained in your PR. A complete description of what to expect during and post PR merge is provided in {doc}`../pangeo_forge_cloud/recipe_contribution`. # ## End of the Introduction Tutorial # # Congratulations, you've completed the introduction tutorial! # # From here, we hope you are excited to try writing your own recipe. As you write, you may find additional documentation helpful, such as the {doc}`../pangeo_forge_recipes/recipe_user_guide/index` or the more advanced {doc}`../pangeo_forge_recipes/tutorials/index`. For recipes questions not covered there, you are invited to open Issues on the [`pangeo-forge/pangeo-forge-recipes`](https://github.com/pangeo-forge/pangeo-forge-recipes/issues) GitHub repository. # # Happy ARCO building! We look forward to your {doc}`../pangeo_forge_cloud/recipe_contribution`. #
docs/introduction_tutorial/intro_tutorial_part3.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.5 64-bit (''a2'': conda)' # name: python3 # --- # + import sys import itertools import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader import anfis from membership import BellMembFunc, make_bell_mfs from experimental import train_anfis, test_anfis dtype = torch.float # - from jang_examples import * show_plots = True model = jang_ex4_trained_model() test_data = jang_ex4_data('jang-example4-data.trn') test_anfis(model, test_data, show_plots) test_data = jang_ex4_data('jang-example4-data.chk') test_anfis(model, test_data, show_plots) show_plots = True model = ex1_model() train_data = make_sinc_xy() train_anfis(model, train_data, 500, show_plots) show_plots = True model = ex2_model() train_data = ex2_training_data() train_anfis(model, train_data, 200, show_plots) test_data = ex2_testing_data() test_anfis(model, test_data, show_plots)
example4T.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Python 3.10.2 64-bit # language: python # name: python3 # --- # # Clustering con Python import pandas as pd import matplotlib.pyplot as plt from sklearn.cluster import AgglomerativeClustering from scipy.cluster.hierarchy import dendrogram, linkage from sklearn.cluster import KMeans df = pd.read_csv("../datasets/wine/winequality-red.csv", sep = ";") df.head() df.shape plt.hist(df["quality"]) df.groupby("quality").mean() # ### Normalización de los datos df_norm = (df-df.min())/(df.max()-df.min()) df_norm.head() # ## Clustering jerárquico con Scikit-learn clus= AgglomerativeClustering(n_clusters=6, linkage="ward").fit(df_norm) md_h = pd.Series(clus.labels_) plt.hist(md_h) plt.title("Histograma de los clusters") plt.xlabel("Cluster") plt.ylabel("Número de vinos del cluster") Z = linkage(df_norm, "ward") plt.figure(figsize=(25,10)) plt.title("Dendrograma de los vinos") plt.xlabel("ID del vino") plt.ylabel("Distancia") dendrogram(Z, leaf_rotation=90., leaf_font_size=4.) plt.show() plt.figure(figsize=(25,10)) plt.title("Dendrograma de los vinos") plt.xlabel("ID del vino") plt.ylabel("Distancia") dendrogram(Z, leaf_rotation=90., leaf_font_size=4., truncate_mode="lastp", p=12, show_leaf_counts=True, show_contracted=True,) plt.axhline(y=4.5, c='k') plt.show() # ## K-Means model = KMeans(n_clusters=6) model.fit(df_norm) model.labels_ md_k = pd.Series(model.labels_) df_norm["clust_h"] = md_h df_norm["clust_k"] = md_k df_norm.head() plt.hist(md_k) model.cluster_centers_ model.inertia_ # ## Interpretación Final df_norm.groupby("clust_k").mean() # * Los vinos pertenecientes al mismo cluster deberían tener un precio similar # * La calidad del vino depende: fixed_acidity, citric_acid, alcohol, sugar
MaPeCode_Notebooks/18. Clustering completo.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.6.4 # language: julia # name: julia-0.6 # --- # # Rectifier - State Events using Modia using Modia.Electric using ModiaMath.plot # Modia has a contruct positive(c), which signals that a state event occurs when c becomes positive or negative and returns true when c>0. # # Using this constrct it is possible to model an ideal diode. The i versus u characteristics is described as a parametric curve with curve parameter s: (v(s), i(s)), since the characteristic is vertical for non-negative voltage. # # The Modia model of the ideal diaode is: using Modia.Synchronous.positive @model IdealDiode begin # Ideal diode @extends OnePort() @inherits v, i s = Float(start=0.0) # Auxiliary variable for actual position on the ideal diode characteristic #= s = 0: knee point s < 0: below knee point, diode conducting s > 0: above knee point, diode locking =# @equations begin v = if positive(s); 0 else s end i = if positive(s); s else 0 end end end; Rload=10; @model Rectifier begin R=Resistor(R=Rload) r=Resistor(R=0.1) C=Capacitor(C=1,start=0) D=IdealDiode() V=SineVoltage(V=5,freqHz=1.5, offset=0, startTime=0) @equations begin connect(V.p, D.p) connect(D.n, R.p) connect(R.n, r.p) connect(r.n, V.n) connect(C.n, R.n) connect(C.p, R.p) end end; result = simulate(Rectifier, 2); plot(result, ("C.v", "V.v"))
docs/Rectifier.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 pandas as pd # from statsmodels.tsa.arima.model import ARIMA import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM import keras # + # df = pd.read_csv(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard\datasetformapping.csv') # + # df.head() # + # df_predict = df[df['Country/Region'] == 'US'] # + # df_predict['daily_confirmed'] = df_predict['Confirmed'].diff() # + # df_predict['daily_confirmed'] = df_predict['daily_confirmed'].fillna(1) # + # df_predict.head() # + # df_predict = df_predict.sort_values('ObservationDate') # + # y = df_predict['daily_confirmed'].values # + # y # + # model = ARIMA(y[:-14], order=(1,0,0)) # + # y[:-14] # + # model_fit = model.fit() # + # model_fit.predict(1,15) # + # print(y[-14:]) # - df = pd.read_csv(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard\datasetformapping.csv',index_col = 'ObservationDate') df data_from_us = df[df['Country/Region'].isin(['US'])] data_from_us data = data_from_us.groupby('ObservationDate').sum()['Confirmed'] data df1 = np.array(data.sort_values()) df1[:10] # + data_from_us['Confirmed'].plot(figsize=(16,5)) plt.legend() plt.grid('On') plt.show() # - # Normalize Data # + scaler = StandardScaler() # sklearn StandardScaler # Standardize features by removing the mean and scaling to unit variance. # z = (x - u) / s # where u is the mean of the training samples or zero if with_mean=False, # and s is the standard deviation of the training samples or one if with_std=False. dataset = scaler.fit_transform(df1.reshape(-1,1)) dataset[0] # - # Train test split train_size = int(len(dataset)*0.7) test_size = len(dataset) - train_size train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:] print('train shape ', train.shape) print('test shape ', test.shape) def create_dataset(dataset, look_back=1): dataX, dataY = [], [] for i in range(len(dataset)-look_back - 1): a = dataset[i:(i+look_back), 0] dataX.append(a) dataY.append(dataset[i+look_back,0]) return np.array(dataX), np.array(dataY) # + # create train and test dataset look_back = 40 # train test split trainX, trainY = create_dataset(train,look_back) testX, testY = create_dataset(test, look_back) # + # reshape input to be [samples, time steps, features] trainX = np.reshape(trainX,(trainX.shape[0],trainX.shape[1],1)) testX = np.reshape(testX,(testX.shape[0],testX.shape[1],1)) # - batch_size = 1 # + model = Sequential() model.add(LSTM(128, batch_input_shape=(batch_size, look_back, 1), stateful=True)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='sgd') for i in range(60): model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) model.reset_states() # - trainPredict = model.predict(trainX,batch_size=batch_size) model.reset_states() testPredict = model.predict(testX,batch_size=batch_size) trainPredict = scaler.inverse_transform(trainPredict) trainY = scaler.inverse_transform([trainY]) testPredict = scaler.inverse_transform(testPredict) testY = scaler.inverse_transform([testY]) import math trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0])) print('train Score: %.2f RMSE' % (trainScore)) testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0])) print('Test Score: %.2f RMSE' % (testScore)) testPredict[-9:-1] realdata = data.sort_values() realdata[-9:-1] predicted_data = pd.DataFrame(testPredict, index=realdata.index[-108:]) predicted_data # + plt.figure(figsize=(14,5)) plt.plot(realdata, label='real data') plt.plot(predicted_data, label='predicted') plt.xticks([realdata.index[0], predicted_data.index[0], realdata.index[-1]]) plt.vlines(predicted_data.index[0], realdata.min(), realdata.max(), color='r', label='split') plt.legend() plt.xlabel('date') plt.show() # - testPredict.shape from datetime import datetime, timedelta def future_predict(model, last_look_back_days, future_days=50): future_predicts = np.array([]) dt = datetime.strptime(realdata.index[-1], '%Y-%m-%d') dates = np.array([]) for day in range(future_days): dataset = scaler.fit_transform(last_look_back_days.reshape(-1,1)) testX, testY = create_dataset(dataset, look_back=len(last_look_back_days)-2) testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1)) new_predict = model.predict(testX, batch_size=batch_size) new_predict = scaler.inverse_transform(new_predict) future_predicts = np.append(future_predicts, new_predict) dates = np.append(dates, [dt + timedelta(days=day)]) dates[day].strftime('%m/%d/%Y') model.reset_states() last_look_back_days = np.delete(last_look_back_days, 0) last_look_back_days = np.append(last_look_back_days, new_predict) predicts = pd.DataFrame(future_predicts, index=dates) predicts return predicts predicts = future_predict(model, predicted_data.values[-100:],future_days=200) predicts # + plt.figure(figsize=(14,5)) plt.plot(predicts, label='predicts') plt.legend() plt.xlabel('date') plt.show() # - model.save(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard') model = keras.models.load_model('.') predicted_data.to_csv(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard\predicted_data.csv') realdata.to_csv(r'C:\Users\mengh\plotly dash covid app\COVID-dashboard\realdata.csv')
covid-cases-prediction.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="XiprJxiXIfN9" #Importing libraries import numpy as np import pandas as pd import random import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # %matplotlib inline # + colab={} colab_type="code" id="QQWy8t4SIfOA" #Defining independent variable as angles from 60deg to 300deg converted to radians x = np.array([i*np.pi/180 for i in range(10,360,3)]) # + colab={} colab_type="code" id="CGRXp2TZIfOC" #Setting seed for reproducability np.random.seed(10) # + colab={} colab_type="code" id="NLYdFsSaIfOE" #Defining the target/dependent variable as sine of the independent variable y = np.sin(x) + np.random.normal(0,0.15,len(x)) # + colab={} colab_type="code" id="A9hruXjrIfOG" #Creating the dataframe using independent and dependent variable data = pd.DataFrame(np.column_stack([x,y]),columns=['x','y']) # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" executionInfo={"elapsed": 2870, "status": "ok", "timestamp": 1560000616843, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="0j1ucc3fIfOI" outputId="c4df36fd-c705-4f9d-e73b-09a70bee42b9" #Printing first 5 rows of the data data.head() # + colab={"base_uri": "https://localhost:8080/", "height": 503} colab_type="code" executionInfo={"elapsed": 3529, "status": "ok", "timestamp": 1560000617523, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="iXKirMENIfOO" outputId="56723192-ac14-41c9-d978-3232a8bc5c5c" #Plotting the dependent and independent variables plt.figure(figsize=(12,8)) plt.plot(data['x'],data['y'],'.') # + colab={"base_uri": "https://localhost:8080/", "height": 204} colab_type="code" executionInfo={"elapsed": 3494, "status": "ok", "timestamp": 1560000617525, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="c0KKNiYHIfOR" outputId="77397a05-f698-45f3-9969-73319abe35be" # polynomial regression with powers of x from 1 to 15 for i in range(2,16): #power of 1 is already there, hence starting with 2 colname = 'x_%d'%i #new var will be x_power data[colname] = data['x']**i data.head() # + [markdown] colab_type="text" id="n1nldRkUIsoU" # ### Creating test and train Set Randomly # + colab={} colab_type="code" id="AUQZSAHhIfOT" data['randNumCol'] = np.random.randint(1, 6, data.shape[0]) train=data[data['randNumCol']<=3] test=data[data['randNumCol']>3] train = train.drop('randNumCol', axis=1) test = test.drop('randNumCol', axis=1) # + [markdown] colab_type="text" id="1Z29VxBTIfOV" # ## Linear Regression # + colab={} colab_type="code" id="AlurQC8dIfOW" #Import Linear Regression model from scikit-learn. from sklearn.linear_model import LinearRegression # + colab={} colab_type="code" id="VUf2CVczIfOY" #Separating the independent and dependent variables X_train = train.drop('y', axis=1).values y_train = train['y'].values X_test = test.drop('y', axis=1).values y_test = test['y'].values # + colab={"base_uri": "https://localhost:8080/", "height": 320} colab_type="code" executionInfo={"elapsed": 4405, "status": "ok", "timestamp": 1560000618475, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="e87fTLw7IfOc" outputId="79e47a56-e717-4e5f-a169-6e39dd5644c2" #Linear regression with one features independent_variable_train = X_train[:,0:1] linreg = LinearRegression(normalize=True) linreg.fit(independent_variable_train,y_train) y_train_pred = linreg.predict(independent_variable_train) rss_train = sum((y_train_pred-y_train)**2) / X_train.shape[0] independent_variable_test = X_test[:,0:1] y_test_pred = linreg.predict(independent_variable_test) rss_test = sum((y_test_pred-y_test)**2)/ X_test.shape[0] print("Training Error", rss_train) print("Testing Error",rss_test) plt.plot(X_train[:,0:1],y_train_pred) plt.plot(X_train[:,0:1],y_train,'.') # + colab={"base_uri": "https://localhost:8080/", "height": 320} colab_type="code" executionInfo={"elapsed": 4372, "status": "ok", "timestamp": 1560000618476, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="ktx_Ep4LIfOf" outputId="8422f232-8f22-4890-892c-f1aeb269f5be" #Linear regression with three features independent_variable_train = X_train[:,0:3] linreg = LinearRegression(normalize=True) linreg.fit(independent_variable_train,y_train) y_train_pred = linreg.predict(independent_variable_train) rss_train = sum((y_train_pred-y_train)**2) / X_train.shape[0] independent_variable_test = X_test[:,0:3] y_test_pred = linreg.predict(independent_variable_test) rss_test = sum((y_test_pred-y_test)**2)/ X_test.shape[0] print("Training Error", rss_train) print("Testing Error",rss_test) plt.plot(X_train[:,0:1],y_train_pred) plt.plot(X_train[:,0:1],y_train,'.') # + colab={"base_uri": "https://localhost:8080/", "height": 320} colab_type="code" executionInfo={"elapsed": 4357, "status": "ok", "timestamp": 1560000618477, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="blee6wddIfOi" outputId="363df04b-46bd-4a2e-d27c-a9c3f84848ef" #Linear regression with Seven features independent_variable_train = X_train[:,0:9] linreg = LinearRegression(normalize=True) linreg.fit(independent_variable_train,y_train) y_train_pred = linreg.predict(independent_variable_train) rss_train = sum((y_train_pred-y_train)**2) / X_train.shape[0] independent_variable_test = X_test[:,0:9] y_test_pred = linreg.predict(independent_variable_test) rss_test = sum((y_test_pred-y_test)**2)/ X_test.shape[0] print("Training Error", rss_train) print("Testing Error",rss_test) plt.plot(X_train[:,0:1],y_train_pred) plt.plot(X_train[:,0:1],y_train,'.') # + colab={} colab_type="code" id="s3Cd83HrIfOk" # defining a function which will fit linear regression model, plot the results, and return the coefficients def linear_regression(train_x, train_y, test_x, test_y, features, models_to_plot): #Fit the model linreg = LinearRegression(normalize=True) linreg.fit(train_x,train_y) train_y_pred = linreg.predict(train_x) test_y_pred = linreg.predict(test_x) #Check if a plot is to be made for the entered features if features in models_to_plot: plt.subplot(models_to_plot[features]) plt.tight_layout() plt.plot(train_x[:,0:1],train_y_pred) plt.plot(train_x[:,0:1],train_y,'.') plt.title('Number of Predictors: %d'%features) #Return the result in pre-defined format rss_train = sum((train_y_pred-train_y)**2)/train_x.shape[0] ret = [rss_train] rss_test = sum((test_y_pred-test_y)**2)/test_x.shape[0] ret.extend([rss_test]) ret.extend([linreg.intercept_]) ret.extend(linreg.coef_) return ret # + colab={} colab_type="code" id="dTH2mkB3IfOm" #Initialize a dataframe to store the results: col = ['mrss_train','mrss_test','intercept'] + ['coef_Var_%d'%i for i in range(1,16)] ind = ['Number_of_variable_%d'%i for i in range(1,16)] coef_matrix_simple = pd.DataFrame(index=ind, columns=col) # + colab={} colab_type="code" id="wkc3Cg_sIfOr" #Define the number of features for which a plot is required: models_to_plot = {1:231,3:232,6:233,9:234,12:235,15:236} # + colab={"base_uri": "https://localhost:8080/", "height": 585} colab_type="code" executionInfo={"elapsed": 10100, "status": "ok", "timestamp": 1560000624263, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="latyKt6WIfOu" outputId="0e1394cc-d2de-40d5-b88b-332cd58b7e6d" #Iterate through all powers and store the results in a matrix form plt.figure(figsize=(12,8)) for i in range(1,16): train_x = X_train[:,0:i] train_y = y_train test_x = X_test[:,0:i] test_y = y_test coef_matrix_simple.iloc[i-1,0:i+3] = linear_regression(train_x,train_y, test_x, test_y, features=i, models_to_plot=models_to_plot) # + colab={"base_uri": "https://localhost:8080/", "height": 534} colab_type="code" executionInfo={"elapsed": 10066, "status": "ok", "timestamp": 1560000624265, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="4fQrthy0IfOy" outputId="f31c7e6c-92d0-458d-9cc5-931d066393f8" #Set the display format to be scientific for ease of analysis pd.options.display.float_format = '{:,.2g}'.format coef_matrix_simple # + colab={"base_uri": "https://localhost:8080/", "height": 301} colab_type="code" executionInfo={"elapsed": 10056, "status": "ok", "timestamp": 1560000624266, "user": {"displayName": "<NAME>", "photoUrl": "", "userId": "14774175216384036942"}, "user_tz": -330} id="WLcisBSWIfO3" outputId="26c4150f-659c-4533-9f4c-8cdd853ddeb9" coef_matrix_simple[['mrss_train','mrss_test']].plot() plt.xlabel('Features') plt.ylabel('MRSS') plt.legend(['train', 'test']) # -
Regression/ridge lasso 1/Ridge and Lasso Implementation.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 # --- # + # lets pip install a cool package! # #!pip install ipyvolume # then lets import import ipyvolume # #%matplotlib inline # + # make sure you unpack this dataset! import yt import numpy as np ds = yt.load('/Users/jillnaiman1/Downloads/enzo_tiny_cosmology/DD0027/DD0027') # - # what are the variables "native" to this dataset? ds.field_list # what are some of the things yt derives for us? ds.derived_field_list dd = ds.covering_grid(level=0,left_edge=[0,0,0], dims=ds.domain_dimensions) # lets plot the gas density in 3d density3d = dd[('gas','density')] density3d = density3d.to_ndarray() density3d, density3d.shape # sense these are low levels, lets take the log density3d = np.log10(density3d) density3d # finally, lets renormalize to the max & min ranges: density3d = (density3d - np.min(density3d))/(np.max(density3d)-np.min(density3d)) density3d # + #from IPython.display import IFrame #IFrame(src='http://localhost:8888/notebooks/prep_week13.ipynb',width=1000,height=500) ipyvolume.figure(width=800, height=500) # now lets plot! ipyvolume.quickvolshow(density3d, level=[0.1, 0.5, 0.75], opacity=0.03, level_width=0.1) # not: you might have to restart your browser after you pip install # note the 3 levels & opacities refer to the RGB levels # levels are telling you where each color will "hit" in your density # So, for example, if I want RED to hit at 1/2 of my density level # (recall we have renormalized our density box) # then I can set the "levels" of the first abar to 0.5 # Then I can set the opacity levels for the other colors way down & the RED one way up # + # there are also the "opacity" and "brightness" to play with # + # since we also have velocity vectors for the gas in this sim # lets plot them with arrows so we can see how they are moving! # first we'll grab the x/y/z positions #x = dd[('gas','x')].to_ndarray() #y = dd[('gas','y')].to_ndarray() #z = dd[('gas','z')].to_ndarray() # now we want lists so we'll grab data another way dd2 = ds.all_data() x = dd2[('gas','x')].to_ndarray() y = dd2[('gas','y')].to_ndarray() z = dd2[('gas','z')].to_ndarray() # lets normalize them all to the max #x = (x-x.min())/(x.max()-x.min()) #y = (y-y.min())/(y.max()-y.min()) #z = (z-z.min())/(z.max()-z.min()) # - # then lets grab vel x/y/z vx = dd2[('gas','velocity_x')].to_ndarray() vy = dd2[('gas','velocity_y')].to_ndarray() vz = dd2[('gas','velocity_z')].to_ndarray() # lets plot! ipyvolume.quickquiver(x,y,z, vx,vy,vz, size=5) # + # obviously, those are too many arrows! # lets only look at the dense gas: density2 = dd2[('gas','density')].to_ndarray() density2 = (density2-density2.min())/(density2.max()-density2.min()) # at > 0.005 -> you can see clumps of gas where stuff is falling in # at > 0.0005 you can see some streams of gas # > 0.00005 you see lots of stream structures # 0.000005 you see structure, but its hard to disentangle # I feel like 0.00002 or 0.00001 is a good bet mask = density2 > 0.00002 # + ipyvolume.quickquiver(x[mask],y[mask],z[mask], vx[mask],vy[mask],vz[mask], size=5) # we can also do some stylistic thigns like: ipyvolume.style.use("dark") # looks better ipyvolume.show() # -
_site/week13/prep_week13.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 # --- # # Testing Score-Only MCMC sampling # %pylab inline from nsec.samplers import ScoreHamiltonianMonteCarlo, ScoreMetropolisAdjustedLangevinAlgorithm from nsec.datasets.swiss_roll import get_swiss_roll import jax import jax.numpy as jnp import tensorflow_probability as tfp; tfp = tfp.experimental.substrates.jax # ## Instantiating test distribution # + # Create a swiss roll distribution dist = get_swiss_roll(.5, 2048) # Define the score function score = jax.grad(dist.log_prob) # - init_samples = dist.sample(10000, seed=jax.random.PRNGKey(0)) hist2d(init_samples[:,0], init_samples[:,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') # ## Validating Score-Hamiltonian Monte-Carlo # + # Initialize the HMC transition kernel. num_results = int(20e3) num_burnin_steps = int(1e3) # First running SHMC kernel_shmc = ScoreHamiltonianMonteCarlo( target_score_fn=jax.grad(dist.log_prob), num_leapfrog_steps=10, num_delta_logp_steps=16, step_size=0.1) samples_shmc, is_accepted_shmc = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_shmc, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # + # Then running true HMC kernel_hmc = ScoreHamiltonianMonteCarlo( target_score_fn=jax.grad(dist.log_prob), num_leapfrog_steps=10, num_delta_logp_steps=16, step_size=0.1) samples_hmc, is_accepted_hmc = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_hmc, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # - figure(figsize=(15,5)) subplot(131) hist2d(init_samples[:,0], init_samples[:,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Samples from true distribution') legend() subplot(132) hist2d(samples_shmc[is_accepted_shmc,0], samples_shmc[is_accepted_shmc,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Score-only HMC') legend() subplot(133) hist2d(samples_hmc[is_accepted_hmc,0], samples_hmc[is_accepted_hmc,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('True HMC') legend() # No difference in number of accepted steps print(len(where(is_accepted_hmc)[0]), len(where(is_accepted_shmc)[0])) # + # Reducing the number of points in the logp integration kernel_shmc = ScoreHamiltonianMonteCarlo( target_score_fn=jax.grad(dist.log_prob), num_leapfrog_steps=10, num_delta_logp_steps=2, step_size=0.1) samples_shmc, is_accepted_shmc = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_shmc, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # - figure(figsize=(15,5)) subplot(131) hist2d(init_samples[:,0], init_samples[:,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Samples from true distribution') legend() subplot(132) hist2d(samples_shmc[is_accepted_shmc,0], samples_shmc[is_accepted_shmc,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Score-only HMC (2 pts integration)') legend() subplot(133) hist2d(samples_hmc[is_accepted_hmc,0], samples_hmc[is_accepted_hmc,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('True HMC') legend() # Even with 2 integration points for delta logp, no obvious problem print(len(where(is_accepted_hmc)[0]), len(where(is_accepted_shmc)[0])) # ## Validating Score MALA # + # First running SMALA kernel_smala = ScoreMetropolisAdjustedLangevinAlgorithm( target_score_fn=jax.grad(dist.log_prob), num_delta_logp_steps=16, step_size=0.1) samples_smala, is_accepted_smala = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_smala, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # + kernel_mala = tfp.mcmc.MetropolisAdjustedLangevinAlgorithm( target_log_prob_fn=dist.log_prob, step_size=0.1) samples_mala, is_accepted_mala = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_mala, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # - figure(figsize=(15,5)) subplot(131) hist2d(init_samples[:,0], init_samples[:,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Samples from true distribution') legend() subplot(132) hist2d(samples_smala[is_accepted_smala,0], samples_smala[is_accepted_smala,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Score-only MALA (16 pts integration)') legend() subplot(133) hist2d(samples_mala[is_accepted_mala,0], samples_mala[is_accepted_mala,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('True MALA') legend() print(len(where(is_accepted_mala)[0]), len(where(is_accepted_smala)[0])) # + # Testing with fewer integration steps kernel_smala = ScoreMetropolisAdjustedLangevinAlgorithm( target_score_fn=jax.grad(dist.log_prob), num_delta_logp_steps=2, step_size=0.1) samples_smala, is_accepted_smala = tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=init_samples[1], kernel=kernel_smala, trace_fn=lambda _, pkr: pkr.is_accepted, seed=jax.random.PRNGKey(1)) # - figure(figsize=(15,5)) subplot(131) hist2d(init_samples[:,0], init_samples[:,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Samples from true distribution') legend() subplot(132) hist2d(samples_smala[is_accepted_smala,0], samples_smala[is_accepted_smala,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('Score-only MALA (2 pts integration)') legend() subplot(133) hist2d(samples_mala[is_accepted_mala,0], samples_mala[is_accepted_mala,1],64,range=[[-15,15],[-15,15]]); gca().set_aspect('equal') scatter(init_samples[1,0], init_samples[1,1], label='x0', color='C1') title('True MALA') legend() print(len(where(is_accepted_mala)[0]), len(where(is_accepted_smala)[0]))
notebooks/test_samplers.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: auto # language: python # name: auto # --- from pycaret.classification import * import pandas as pd # !pwd df = pd.read_csv('merged_patterns.csv').drop('Unnamed: 0', axis=1) df_copy = df.copy(deep=True) # df_copy = df_copy.filter(['f1', 'f2', 'f3', 'f4', 'f5', 'label']) exp_name = setup(data=df_copy, target='label', normalize=True, normalize_method='zscore') best_model = compare_models(fold=5) best_model lightgbm = create_model('lightgbm') tune_model(lightgbm, n_iter=200, choose_better=True)
price-pattern-pycaret.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 # --- # # Electron affinities # # + import numpy as np import pandas as pd from qa_tools.utils import * from qa_tools.data import prepare_dfs from qa_tools.prediction import * from qa_tools.analysis import * json_path = '../../json-data/dimer-pyscf.qa-data.posthf.json' df_qc, df_qats = prepare_dfs(json_path, get_CBS=False) # - # ## QA prediction errors # # There is some intrinsic error in modeling a target system (e.g., N atom) by changing the nuclear charge of a reference system's basis set (e.g., C<sup> &ndash;</sup> ). # + system_label = 'o.h' delta_charge = -1 target_initial_charge = 0 # Initial charge of the system. basis_set = 'cc-pV5Z' lambda_specific_atom = 0 change_signs = True # Multiple all predictions by negative one (e.g., for electron affinities) n_points = 2 poly_order = 4 # + use_ts = False remove_outliers = False ea_qc_prediction = energy_change_charge_qc_dimer( df_qc, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers ) ea_qats_predictions = energy_change_charge_qa_dimer( df_qc, df_qats, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, use_ts=use_ts, lambda_specific_atom=lambda_specific_atom, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers ) ea_qc_prediction = hartree_to_ev(ea_qc_prediction) ea_qats_predictions = {key:hartree_to_ev(value) for (key,value) in ea_qats_predictions.items()} ea_qats_errors = {key:value-ea_qc_prediction for (key,value) in ea_qats_predictions.items()} print(f'PySCF prediction of EA for {system_label}: {ea_qc_prediction:.3f} eV\n') print(f'QA prediction errors in eV:') print(pd.DataFrame(ea_qats_errors, index=[f'QA'])) # - # ## QATS-*n* prediction errors # # Now, we can look at approximating the QA prediction by using a Taylor series centered on $\Delta Z = 0$. # + use_ts = True remove_outliers = False ea_qc_prediction = energy_change_charge_qc_dimer( df_qc, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers ) ea_qats_predictions = energy_change_charge_qa_dimer( df_qc, df_qats, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, use_ts=use_ts, lambda_specific_atom=lambda_specific_atom, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers ) ea_qc_prediction = hartree_to_ev(ea_qc_prediction) ea_qats_predictions = {key:hartree_to_ev(value) for (key,value) in ea_qats_predictions.items()} ea_qats_errors = {key:value-ea_qc_prediction for (key,value) in ea_qats_predictions.items()} print(f'PySCF prediction of EA for {system_label}: {ea_qc_prediction:.3f} eV\n') print(f'QATS-n prediction errors in eV:') print(pd.DataFrame(ea_qats_errors, index=[f'QATS-{n}' for n in range(5)])) # - # ### Specifying lambda values # # We can also specify specific lambda values to include. For example, we could only look at lambda values of +-1. # + considered_lambdas = [-1] use_ts = True remove_outliers = False ea_qc_prediction = energy_change_charge_qc_dimer( df_qc, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers ) ea_qats_predictions = energy_change_charge_qa_dimer( df_qc, df_qats, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, use_ts=use_ts, lambda_specific_atom=lambda_specific_atom, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers, considered_lambdas=considered_lambdas ) ea_qc_prediction = hartree_to_ev(ea_qc_prediction) ea_qats_predictions = {key:hartree_to_ev(value) for (key,value) in ea_qats_predictions.items()} ea_qats_errors = {key:value-ea_qc_prediction for (key,value) in ea_qats_predictions.items()} print(f'PySCF prediction of EA for {system_label}: {ea_qc_prediction:.3f} eV\n') print(f'QATS-n prediction errors in eV:') print(pd.DataFrame(ea_qats_errors, index=[f'QATS-{n}' for n in range(5)])) # - # ## QATS-*n* errors with respect to QA # # Or you, can compute the difference between QATS-*n* (predictions with Taylor series) and QA. # + return_qats_vs_qa = True use_ts = True remove_outliers = False ea_qats_predictions = energy_change_charge_qa_dimer( df_qc, df_qats, system_label, delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, use_ts=use_ts, lambda_specific_atom=lambda_specific_atom, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers, return_qats_vs_qa=return_qats_vs_qa ) ea_qats_predictions = {key:hartree_to_ev(value) for (key,value) in ea_qats_predictions.items()} print(f'Differences between QATS-n and QA in eV:') print(pd.DataFrame(ea_qats_predictions, index=[f'QATS-{n}' for n in range(5)])) # - # ## Overall statistics # # We can also compute mean absolute errors (MAEs), root mean squared error (RMSE) and max error. # + all_systems = all_dimer_systems[0:-2] target_initial_charge = 0 considered_lambdas = None return_qats_vs_qa = False use_ts = True remove_outliers = False max_qats_order = 4 for i in range(len(all_systems)): sys_error = error_change_charge_qats_dimer( df_qc, df_qats, all_systems[i], delta_charge, target_initial_charge=target_initial_charge, change_signs=change_signs, basis_set=basis_set, use_ts=use_ts, lambda_specific_atom=lambda_specific_atom, n_points=n_points, poly_order=poly_order, remove_outliers=remove_outliers, return_qats_vs_qa=return_qats_vs_qa, considered_lambdas=considered_lambdas ) if i == 0: all_error = sys_error else: all_error = pd.concat( [all_error, sys_error], axis=1 ) if use_ts or return_qats_vs_qa == True: # MAE for n in range(0, max_qats_order+1): qatsn_errors = all_error.iloc[n].values qatsn_mae = np.mean(np.abs(qatsn_errors)) print(f'QATS-{n} MAE: {qatsn_mae:.3f} eV') # RMSE print() for n in range(0, max_qats_order+1): qatsn_errors = all_error.iloc[n].values qatsn_rmse = np.sqrt(np.mean((qatsn_errors)**2)) print(f'QATS-{n} RMSE: {qatsn_rmse:.3f} eV') # Max print() for n in range(0, max_qats_order+1): qatsn_errors = all_error.iloc[n].values qatsn_max = np.max(np.abs(qatsn_errors)) print(f'QATS-{n} max abs.: {qatsn_max:.3f} eV') else: # MAE qatsn_errors = all_error.iloc[0].values qatsn_mae = np.mean(np.abs(qatsn_errors)) print(f'QA MAE: {qatsn_mae:.3f} eV') # RMSE print() qatsn_rmse = np.sqrt(np.mean((qatsn_errors)**2)) print(f'QA RMSE: {qatsn_rmse:.3f} eV') # Max print() qatsn_max = np.max(np.abs(qatsn_errors)) print(f'QA max abs.: {qatsn_max:.3f} eV')
notebooks/dimers/electron_affinities_dimers.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 pd.set_option('precision', 1) # **Question 1** (25 points) # # There is simulated data of 25,000 human heights and weights of 18 years old children at this URL # `http://socr.ucla.edu/docs/resources/SOCR_Data/SOCR_Data_Dinov_020108_HeightsWeights.html` # # The original data has height in inches and weight in pounds. # # - Find the average height in cm, weight in kg, and BMI for each of the four categories defined below: # # ``` # BMI Category # 18 or less Underweight # 18 – 22 Normal # 22 – 25 Overweight # More than 25 Obese # ``` # # - Do this in a reproducible way - that is, **all** processing of the data must be done in **code** # - Use **method chaining** to generate the summary # # Your final table should look like this: # # | status | ht_in_cm | wt_in_kg | bmi | # |:------------|-----------:|-----------:|--------:| # | Underweight | 173.1 | 51.4 | 17.1 | # | Normal | 172.7 | 58.8 | 19.7 | # | Overweight | 170.6 | 65.9 | 22.6 | # | Obese | 166.1 | 70.0 | 25.4 | # # Notes # # - 1 inch = 2.54 cm # - 1 pound = 0.453592 kg # - BMI = weight in kg / (height in meters^2) url = 'https://rb.gy/u3dvsb' df = pd.read_html(url, header=0, index_col=0)[0] s = ( df. assign( ht_in_cm = 2.54*df['Height(Inches)'], wt_in_kg = 0.453592*df['Weight(Pounds)'], ). drop(['Height(Inches)','Weight(Pounds)'], axis=1). pipe(lambda x: x.assign(bmi = x.wt_in_kg/(x.ht_in_cm/100)**2)). pipe(lambda x: x.assign( status = pd.cut(x.bmi, [0,18,22,25,np.infty], labels=['Underweight', 'Normal', 'Overweight', 'Obese']))). groupby('status'). mean() ) s # **Question 2** (25 points) # # Using the `EtLT` data pipeline pattern. # # - Using `requests`, download all people from the Star Wars REST API at https://swapi.dev/api and store the information about each person in a MongoDB database # - Extract the data from MongoDB database # - Flatten the nested JSON structure into a `pandas` DataFrame # - Save to an SQLite3 database # - Use SQL to transform the data in the SQLite3 dataase <font color=red>This question is not clear and was not considred in grading</font> # + import requests sw_people = requests.get('https://swapi.dev/api/people').json()['results'] # - from pymongo import MongoClient client = MongoClient('mongodb:27017') client.drop_database('starwars') db = client.starwars people = db.people result = people.insert_many(sw_people) import pandas as pd df = pd.DataFrame(list(people.find())) # + # df = pd.DataFrame(sw_people) # - df.head() df.films df = ( df. explode('films'). explode('species'). explode('vehicles'). explode('starships') ) df.shape df.head() import sqlite3 conn = sqlite3.connect('data/people.db') df['_id'] = df['_id'].astype('string') df.to_sql('people', conn, index=False) cr = conn.cursor() cr.execute('SELECT * FROM people LIMIT 1') cr.fetchall() # **Question 3** (50 points) # # The data set in `dm.csv` contains 11 columns as described below. The first 10 columns are features (X), and the last is the target (y). The features have been transformed such that the mean = zero, and the sum of squares = 0. # # ``` # age age in years # sex # bmi body mass index # bp average blood pressure # s1 tc, T-Cells (a type of white blood cells) # s2 ldl, low-density lipoproteins # s3 hdl, high-density lipoproteins # s4 tch, thyroid stimulating hormone # s5 ltg, lamotrigine # s6 glu, blood sugar level # target measure of disease severity at 1 year # ``` # # - Split the data into X_train, X_test, y_train, y_test # - Plot the correlation matrix of X_train features as a heatmap using seaborn # - Perform a PCA on X_train # - Display a biplot of X_train projected on the first 2 principal components # - Write a function that returns the number of components needed to explain p% of the variance in X_train, and show the result for p=90 # - Create a dummy regression model AND a proper regression model with sklearn's RandomForestRegressor to predict the target from the 10 features # - Perform hyperparameter optimization on at least 2 parameters of the Random Forest model using GridSearch and create a tuned RandomForestRegressor model with the best parameters # - Plot the learning curve for the tuned Random Forest # - Evaluate the model performance on test data using R^2 and mean absolute error for both dummy and Random Forest models # - Plot feature importances for the Random Forest model using permutation importance and mean absolute Shapley values data = pd.read_csv('dm.csv') import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( data.iloc[:, :10], data.iloc[:, -1] ) sns.heatmap(X_train.corr()) plt.axis('equal'); from sklearn.decomposition import PCA pca = PCA() pc = pca.fit_transform(X_train) from yellowbrick.features import PCA as PCA_ pca_viz = PCA_(proj_features = True) pca_viz.fit_transform(X_train) pca_viz.show(); pca.explained_variance_ratio_.cumsum() def n_comp(pca, threshold): """Returns number of compoentns to exceed threshold explained variance.""" return (pca.explained_variance_ratio_.cumsum() > threshold).nonzero()[0][0] + 1 n_comp(pca, 0.9) from sklearn.dummy import DummyRegressor from sklearn.ensemble import RandomForestRegressor dummy = DummyRegressor() rf = RandomForestRegressor() rf.estimator_params params = { 'max_depth': [2,5,10, None], 'min_samples_leaf': [1,2,5,10], } from sklearn.model_selection import GridSearchCV gs = GridSearchCV(rf, params) gs.fit(X_train, y_train) tuned_rf = RandomForestRegressor(**gs.best_params_) from yellowbrick.model_selection import LearningCurve lc_viz = LearningCurve(tuned_rf) lc_viz.fit(X_train, y_train) lc_viz.show(); from sklearn.metrics import r2_score, mean_absolute_error dummy.fit(X_train, y_train) r2_score(y_test, dummy.predict(X_test)) mean_absolute_error(y_test, dummy.predict(X_test)) tuned_rf.fit(X_train, y_train) r2_score(y_test, tuned_rf.predict(X_test)) mean_absolute_error(y_test, tuned_rf.predict(X_test)) from sklearn.inspection import permutation_importance importances = permutation_importance(tuned_rf, X_train, y_train) importances['importances_mean'] idx = np.argsort(-importances['importances_mean']) sns.barplot(importances['importances_mean'][idx], X_train.columns[idx]); import shap explainer = shap.TreeExplainer(tuned_rf) sv = explainer.shap_values(X_train) shap.summary_plot(sv, plot_type='bar', feature_names=X_train.columns)
exams/Exam_Solutions.ipynb
// --- // jupyter: // jupytext: // text_representation: // extension: .cs // format_name: light // format_version: '1.5' // jupytext_version: 1.14.4 // kernelspec: // display_name: .NET (C#) // language: C# // name: .net-csharp // --- // # Reading Values out of a Excel File // // This code snippet lets you get the value of a cell (located by row and column name) from a .xlsx- File // ## Required NuGet Packages // [ClosedXML on NuGet.org](https://www.nuget.org/packages/ClosedXML) // + dotnet_interactive={"language": "csharp"} // This is needed that this Notebook works #r "nuget: ClosedXML, 0.95.4" // - // ## Required Namespaces // + dotnet_interactive={"language": "csharp"} using System.IO; using System.Globalization; using ClosedXML; using ClosedXML.Excel; // - // ## Reading by Column Name and Row Number // + dotnet_interactive={"language": "csharp"} public string GetValueByRowAndColumn(string path, int row, int column) { using (var workbook = new XLWorkbook(path)) { var worksheet = workbook.Worksheet(1); var value = worksheet.Cell(row+1, column).Value; return value.ToString(); } } // - // ## Usage // // Used xlsx-File: [email.xlsx](email.xlsx) // + dotnet_interactive={"language": "csharp"} var value = GetValueByRowAndColumn("email.xlsx", 3, 3); // - // When you execute it, the expected result is `Mary` // + dotnet_interactive={"language": "csharp"} Console.WriteLine($"Actual result: {value}");
CodeSnippets/Excel.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 # --- # # Project # student_name = '<NAME>' # # Tower of Hanoi # # The Tower of Hanoi is a mathematical puzzle in which the goal is to move a number of discs from one tower to another while adhering to the following rules: # # - Only one disc can be moved at a time # - No disc can be placed on top of a smaller disc # - Only the disc at the top of any tower may be moved. # # # # # ## Instructions # # Write a function that solves the Tower of Hanoi problem for 3 towers and `num_discs` discs. This function should create a list, `solution`, whose elements are the state of the towers after every move, including the initial state. For example, the following list would be generated for 3 discs (spacing added only for readability): # ``` # solution = [ [ [2, 1, 0], [], [] ], # [ [2, 1], [], [0] ], # [ [2], [1], [0] ], # [ [2], [1, 0], [] ], # [ [], [1, 0], [2] ], # [ [0], [1], [2] ], # [ [0], [], [2, 1] ], # [ [], [], [2, 1, 0] ] ] # ``` # # In the above example we see that each state (the current configuration of discs on the three towers) is itself a list, and each tower within the state is also a list. The list representing each tower is treated as a stack, where discs may only be appended to the end (when moving a disc to the tower) or popped from the end (when removing a disc from the tower). The indices of each disc correspond to the size of the disc. For example, the disc with index 0 is physically smaller than the disc with index 1. With this setup a tower is 'valid' only if its elements appear in a largest to smallest order. # # Several helper functions have been provided for you to display your solution as well as verify that each state adheres to the rules given above. # # # # ## Submitting Your Assignment # # You will submit your completed assignment in two formats: # # - Jupyter Notebook (.ipynb) # - HTML (.html) # # ##### Jupyter Notebook (.ipynb) # You may directly use this notebook to complete your assignment or you may use an external editor/IDE of your choice. However, to submit your code please ensure that your code works in this notebook. # # ##### HTML (.html) # To create an HTML file for your assignment simply select `File > Download as > HTML (.html)` from within the Jupyter Notebook. # # Both files should be uploaded to [Canvas](https://canvas.tamu.edu). # ## Hint # # The next few code blocks are to remind you that Python does not create copies as one might expect, instead it creates bindings between the target and an object. Review the following and understand why the first two blocks are different from the last two blocks. See [Shallow and deep copy operations](https://docs.python.org/2/library/copy.html) for more information. a = [2,1,0] b = [] b.append(a) print(b) a[0] = 5 print(b) # + import copy a = [2,1,0] b = [] b.append(copy.deepcopy(a)) print(b) # - a[0] = 5 print(b) # ## Helper Functions # # The following code block should import everything you need as well as some functions to help you display and verify your solution. # + # %matplotlib inline import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation from IPython.display import HTML import copy def init_tower_discs(towers, num_towers, num_discs, start_tower_idx): """ Initializes the variable tower to contain 'num_towers' towers, with 'num_discs' appropriately ordered on the first tower according to the rules of Tower of Hanoi. """ towers.clear() for c in range(num_towers): towers.append([]) for d in reversed(range(num_discs)): towers[start_tower_idx].append(d) def draw_towers(num_towers, num_discs, axes): """ Adds the towers as rectangular patches on 'axes' and sets their color to black. Draws, by default, will appear on top of any previous draws, and so this function should be called prior to any drawing of the discs so that the discs will appear on top of the towers. """ for i in range(num_towers): x_offset = i + (2 * i + 1) * num_discs / 2.0 + 0.875 tower = patches.Rectangle((x_offset, 0), 0.25, num_discs + 1) tower.set_color('0') axes.add_patch(tower) def draw_disc(num_discs, disc_idx, tower_idx, elevation, axes): """ Draws a single disc identified by 'disc_idx', on tower 'tower_idx' at height 'elevation': disc_idx takes a value from 0 to (num_discs-1) tower_idx takes a value from 0 to (num_towers-1) elevation takes a value from 0 to (num_discs-1) The width and color of a disc is defined by its index. A rectangular patch is added to 'axes' representing 'disc_idx'. """ tower_x_offset = tower_idx + (2 * tower_idx + 1) * num_discs / 2.0 + 0.5 disc_x_offset = tower_x_offset - (disc_idx+1) / 2.0 + 0.5 disc = patches.Rectangle((disc_x_offset, elevation), disc_idx+1, 1) plt.cm.N = num_discs disc.set_color(plt.cm.RdYlBu(disc_idx/num_discs)) axes.add_patch(disc) def draw_all_discs(num_discs, axes, *argv): """ Draws all discs in their current position. """ for tower_idx, tower_list in enumerate(*argv): for elevation, disc_idx in enumerate(tower_list): draw_disc(num_discs, disc_idx, tower_idx, elevation, axes) def verify_tower(state, tower_idx): """ Verifies that no larger disc is on top of a smaller disc for tower_idx. If found, this function displays a message that the tower has an invalid state. """ if state[tower_idx] != list(reversed(sorted(state[tower_idx]))): print('Tower', tower_idx, 'is invalid in', state) def verify_state(state, num_towers, num_discs): """ Verifies each tower in the current state to ensure no larger disc is on top of a smaller disc, and that the total number of discs in the state is equal to num_discs. """ for tower_idx in range(num_towers): verify_tower(state, tower_idx) if num_discs != sum([len(t) for t in state]): print('Incorrect number of discs found in', state) def verify_moves(solution, num_towers, num_discs): """ Verifies that each transition between states adheres to the rules, and uses verify_state to ensure that each state's tower configuration is valid. """ # make sure that no more than one disc is moved between states for i in range(len(solution)-1): # Check that state i is in a valid configuration verify_state(solution[i], num_towers, num_discs) # find the differences between state i and state i+1 delta_t = [len(s0) - len(s1) for s0,s1 in zip(solution[i],solution[i+1])] num_changes = sum([abs(dt) for dt in delta_t]) if num_changes < 2: print('Too few changes between states, i.e. No discs were moved during step', i) elif num_changes > 2: print('Too many changes between states, i.e. More than one discs moved during step', i) # verify that only the ends of the towers have been modified for t in range(num_towers): if delta_t[t] < 0: # a disc was added to tower t if solution[i][t] != solution[i+1][t][:-1]: print('Illegal modification to tower', t, 'in step', i) print('Expected', solution[i][t], '==', solution[i+1][t][:-1]) elif delta_t[t] > 0: # a disc was removed from tower t if solution[i][t][:-1] != solution[i+1][t]: print('Illegal modification to tower', t, 'in step', i) print('Expected', solution[i][t][:-1], '==', solution[i+1][t]) else: # the tower remained the same length if solution[i][t] != solution[i+1][t]: print('Illegal modification to tower', t, 'in step', i) print('Expected', solution[i][t], '==', solution[i+1][t]) # Check that the state is in a valid configuration if len(solution) > 0: verify_state(solution[-1], num_towers, num_discs) # - # #### Hanoi Towers Algorithm # # Let's consider the 3 tower case, and call the towers __source__, __aux__, and __target__. # # <img src= "https://www.tutorialspoint.com/data_structures_algorithms/images/tower_of_hanoi.gif" width="400px"/> # # One can split the original problem into 3 simpler problems. The ultimate goal of the algorithm is: # # # - Move discs __$D_1, \dots, D_{n-1}$__ from __source__ tower to __auxiliary__ tower # # # - Move the __largest__ disc __$D_{n}$__ from __source__ tower to __target__ tower # # # - Move discs __$D_1, \dots, D_{n-1}$__ from __auxiliary__ tower to __target__ tower # # __Step 1:__ If we __ignore__ the largest disc for a minute, then this problem is a __hanoi towers__ problem with $(n-1)$-discs, where the __target__ tower is __auxiliary__ tower. # # __Step 2:__ Note that, the second problem can be solved within one __move__ only. # # __Step 3:__ As a last step, let's again forget about the __largest__ disc for now. Then, we have another __hanoi towers__ problem with $(n-1)$-discs where the source tower is now the __auxiliary__ tower. # # Since, both __Step 1__ and __Step 3__ are __hanoi towers__ problems with $(n-1)$-discs themselves, we need a __recursive__ algorithm! # # <br> # # <div STYLE="background-color:#000000; height:2px; width:100%;"></div> # <b>Algorithm:</b> Hanoi Towers Algorithm # <div STYLE="background-color:#000000; height:1px; width:100%;"></div> # # - <b>Input:</b> $hanoi(m, n, H, \bar{H}, Source, Target)$ # # - $m$ : Number of towers # - $n$ : Number of total discs # - $H$: List of $m$ lists (towers) with total $n$ elements (discs) # - $\bar{H}$: List of $H$'s (states) with total $2^{n}-1$ elements # - $Source$: Starting tower index # - $Target$: Destination tower index # # - <b>Output:</b> Rearranged version of, $H$, the list of lists (towers) in whose last element all discs lie on $Target$ tower # # <div STYLE="background-color:#000000; height:1px; width:100%;"></div> # # 1. __if__ n == 0 __do__ (base condition for recursion) # # 2. $\quad$ return # # 3. __end if__ # # 4. Choose an $Aux$ (index) using $m$ # # 5. $hanoi(m, n-1, H, \bar{H}, Source, Aux)$ # # 6. __if__ $H[Source]$ is __not__ empty __do__ # # 7. $\quad$ Move a disc from $Source$ to $Target$ tower # # 8. $\quad$ Add new state $H$ to $\bar{H}$ # # 9. $\quad$ __end if__ # # 10. $hanoi(m, n-1, H, \bar{H},, Aux, Target)$ # # 11. __end if__ # # <div STYLE="background-color:#000000; height:2px; width:100%;"></div> # ## Your Solution # # Complete the `hanoi()` function below. def hanoi(initial_state, solution, num_towers, num_discs, start_tower_idx, target_tower_idx): """ This function solves the Tower of Hanoi problem for 3 towers and 'num_discs' discs. This function creates a list whose elements are the state of the towers after each move. For example, the following list would be generated for 3 discs (spacing added only for readability): [ [[2, 1, 0], [], [] ], [[2, 1], [], [0] ], [[2], [1], [0] ], [[2], [1, 0], [] ], [[], [1, 0], [2] ], [[0], [1], [2] ], [[0], [], [2, 1] ], [[], [], [2, 1, 0]] ] initial_state - The list of towers containing the discs in their initial state. solution - The list that shall contain the list of states moving from the initial_state to the final state upon completion of this function. num_towers - The number of towers in each state. You may assume this is always 3. num_discs - The number of discs. start_tower_idx - The index of the tower containing all of the discs in the initial state. target_tower_idx - The index of the tower that shall contain all of the discs in the final state. """ # Use the list `solution` to store the steps of your algorithm as described above. from copy import deepcopy from random import choice if num_towers == None: num_tower = 3 if solution == None: solution = [] # Add initial state to the solution if solution == []: solution.append(deepcopy(initial_state)) # Base condition of the recursion if num_discs == 0: # No more discs to move in this step return # pick an auxiliary tower aux_tower_idx = choice([i for i in range(num_towers) if i not in {start_tower_idx, target_tower_idx}]) # move n-1 discs from start_tower to aux_tower hanoi(initial_state, solution, num_towers, num_discs-1, start_tower_idx, aux_tower_idx) # until start_tower is exhausted if initial_state[start_tower_idx]: # move disc from start_tower to target_tower initial_state[target_tower_idx].append(initial_state[start_tower_idx].pop()) # add moving step to the solution solution.append(deepcopy(initial_state)) # move n-1 discs from aux_tower to target_tower hanoi(initial_state, solution, num_towers, num_discs-1, aux_tower_idx,target_tower_idx) #return solution m = 3; n = 3 initial_state = [list(range(n)[::-1]), [], []] hanoi(initial_state, [], m, n, 0, m-1) m = 3; n = 4 initial_state = [list(range(n)[::-1]), [], []] hanoi(initial_state, [], m, n, 0, m-1) m = 3; n = 5 initial_state = [list(range(n)[::-1]), [], []] hanoi(initial_state, [], m, n, 0, m-1) # ## Test Code # # After completing your function, `hanoi()`, above, run the following code block to test and view your results. # # The following code block will generate an animation of the states found in `solution`. If instead you wish only to draw a single frame, make the following modifications: # # - Change `generate_animation` to `False` # - Set `state_idx` to the index of the state in `solution` that you would like to be displayed. # + # This flag, if True, tells the code to build an animation from your # solution. If False, no animation will be generated, and instead # only a single state, specified by state_idx, will be rendered. generate_animation = True # If the generate_animation flag is False, this index will be used # to define which state, solution[state_idx], will be displayed. The # index is unused if generate_animation is True. state_idx = 0 # The number of discs in this puzzle. Use values less than 8. num_discs = 5 # The number of towers in this puzzle. Your solution is only required # to be correct for 3 towers, but you are welcome to try more. num_towers = 3 # The index of the tower on which all discs will begin start_tower_idx = 0 # The index of the tower onto which all discs shall be moved target_tower_idx = num_towers - 1 # Create figure and axes on which to draw fig = plt.figure() axes = fig.add_subplot() # set the horizontal and vertical limits of the figure plt.ylim((0, num_discs + 4)) plt.xlim((0, 1 + num_towers * (num_discs +1))) if generate_animation: plt.close() # prevents the additional plot display of the final frame # List of towers, the initial state, each entry in this list # is itself a list of discs on that tower. The order of the # tower lists is bottom to top (larger discs appear before # smaller discs). For example: [ [2, 1, 0], [], [] ] initial_state = [] # Initialize our towers, e.g. set towers = [ [2, 1, 0], [], [] ] init_tower_discs(initial_state, num_towers, num_discs, start_tower_idx) # Initialize our solution, empty. solution = [] # <- This is where your solution should be stored!!! # Execute your algorithm hanoi(initial_state, solution, num_towers, num_discs, start_tower_idx, target_tower_idx) # Check if any rules were violated verify_moves(solution, num_towers, num_discs) def draw_state(state_idx): """ Draws the system state for step state_idx in the solution """ [p.remove() for p in reversed(axes.patches)] # clear previous draws draw_towers(num_towers, num_discs, axes) draw_all_discs(num_discs, axes, solution[state_idx]) def init(): pass if generate_animation: if len(solution) > 0: # Create the animation ani = matplotlib.animation.FuncAnimation(fig, draw_state, frames=len(solution), init_func=init) # Generate HTML representation of the animation display(HTML(ani.to_jshtml())) else: print('Empty solution found') else: if state_idx in range(len(solution)): # Draw only a single state from your solution draw_state(state_idx) else: print('Invalid state index specified')
HW2-Hanoi-Towers.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 # --- # + id="F7jK6ifwvVBP" executionInfo={"status": "ok", "timestamp": 1633542937123, "user_tz": -180, "elapsed": 7, "user": {"displayName": "\u0421\u0435\u043c\u0451\u043d \u0421\u0435\u043c\u0435\u043d\u043e\u0432", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14GipOZU94FUM6Ph4lPkn4meRT9aXV3arYe2dAdQL=s64", "userId": "11122657228951885686"}} nums = [10,9,2,5,3,7,101,18] # + id="Hp5JwkFmvu9X"
Dynamic Programming/442. Find All Duplicates in an Array.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 # --- # # Spark SQL import pyspark from pyspark.sql import SparkSession spark = SparkSession \ .builder \ .appName('Spark DataFrames') \ .getOrCreate() sc = spark.sparkContext import pandas as pd data_dict = {'a': 1, 'b': 2, 'c': 3, 'd':3, 'e':1} pandas_df = pd.DataFrame.from_dict( data_dict, orient='index', columns=['position']) pandas_df spark_df = spark.createDataFrame(pandas_df) spark_df spark_df.show() # ### Running sql queries against DataFrames spark_df.createOrReplaceTempView('my_table') spark.sql("SELECT * FROM my_table LIMIT 5").show() # Multi-line statements need the use of triple quotes `"""` spark.sql("SHOW TABLES;").show() spark.sql(""" SELECT position FROM my_table LIMIT 2 """).show() # That's convenient, but we can use PySpark DataFrames API to perform the same operations. # #### `.limit(num)` # Like SQL's `LIMIT`. # Limit the DataFrame to `num` rows. spark_df.limit(2).show() # #### `.filter(...)` spark_df.filter(spark_df.position >= 3).show() # --- # > 💡 We can even mix both APIs # # --- spark_df.limit(2).selectExpr("position * 2", "abs(position)").show() # #### `.dropDuplicates(...)` spark_df.show() spark_df.dropDuplicates().show() # #### `.distinct()` spark_df.distinct().show() # #### `.orderBy(...)` # Alias to `.sort(...)` spark_df.orderBy('position').show() # We can call `.desc()` to get a descending order, but that means we need an actual `Column` object to call it on. spark_df.orderBy(spark_df.position.desc()).show() # #### `.groupBy(...)` spark_df.groupBy('position') # Returns a `GroupedData` object. We need to take some action on this. # Another action, this one works spark_df.groupBy('position').count() # ⚠️ When applied to a DataFrame, `.count()` is an action. In this case it returns a `DataFrame`, e.g. still waiting for an action. spark_df.groupBy('position').count().show() # #### Chaining everything together spark_df \ .filter(spark_df.position < 2) \ .groupBy('position') \ .count() \ .orderBy('count') \ .limit(5) \ .show() # Question: what if we want to order by descending count? spark_df \ .filter(spark_df.position < 10) \ .groupBy('position') \ .count() \ .orderBy('count', ascending=False) \ .limit(5) \ .show() spark_df \ .filter(spark_df.position < 10) \ .groupBy('position') \ .count() \ .orderBy(spark_df.position.desc()) \ .limit(5) \ .show() # ### Adding columns # Using pure select is possible, but can feel tedious spark_df.select('*', spark_df.position.alias('newColumn')).show() # #### `.withColumn(...)` # It's usually easier to use `.withColumn` for the same effect. spark_df.withColumn('newColumn', spark_df.position).show() # #### `withColumnRenamed(...)` spark_df.withColumnRenamed('position', 'newName').show() # ### Displaying the DataFrame # For when `.show()` won't cut it... # #### Converting to pandas' # Using `toPandas()`: this is an action, it will compute. # Hence, do **NOT** forget to `limit` or you'll explode the memory (unless the DataFrame is small, like the result of an aggregate). pandas_df = spark_df.limit(5).toPandas() pandas_df
demo/spark_030_SQL.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 # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import seaborn as sns # %matplotlib inline from sklearn.datasets import load_breast_cancer cancer = load_breast_cancer() cancer.keys() df = pd.DataFrame(cancer['data'], columns=cancer['feature_names'])#convert to data frame df.head() from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(df) #normalize data scaled_data = scaler.transform(df) # + # PCA from sklearn.decomposition import PCA # - pca = PCA(n_components=2) pca.fit(scaled_data) x_pca = pca.transform(scaled_data) # + x_pca_2d = pd.DataFrame(x_pca) x_pca_2d.columns = ['PC1','PC2'] x_pca_2d.head() # + print(pca.explained_variance_ratio_) #variance explained by the first PC # - plt.figure(figsize=(10,6)) plt.scatter(x_pca[:,0], x_pca[:,1], c=cancer['target'], cmap='plasma') plt.xlabel = "First Principal Component" plt.ylabel = "Second Principal component" plt.show() # #### which components contribute to explaining PC variation df_comp = pd.DataFrame(pca.components_, columns=cancer['feature_names']) plt.figure(figsize=(10,6)) sns.heatmap(df_comp, cmap='plasma') # + ##https://www.kaggle.com/xixiusa/t-sne # + ##https://www.kaggle.com/dikhvo/regression-classification-by-price # + ##http://sepans.github.io/weather-mining/method.html # + import time import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.feature_extraction import image from sklearn.cluster import spectral_clustering # - # load the raccoon face as a numpy array try: # SciPy >= 0.16 have face in misc from scipy.misc import face face = face(gray=True) except ImportError: face = sp.face(gray=True) # + # Resize it to 10% of the original size to speed up the processing face = sp.misc.imresize(face, 0.10) / 255. # Convert the image into a graph with the value of the gradient on the # edges. graph = image.img_to_graph(face) # + # actual image. For beta=1, the segmentation is close to a voronoi beta = 5 eps = 1e-6 graph.data = np.exp(-beta * graph.data / graph.data.std()) + eps # Apply spectral clustering (this step goes much faster if you have pyamg # installed) N_REGIONS = 25 # - for assign_labels in ('kmeans', 'discretize'): t0 = time.time() labels = spectral_clustering(graph, n_clusters=N_REGIONS, assign_labels=assign_labels, random_state=1) t1 = time.time() labels = labels.reshape(face.shape) plt.figure(figsize=(5, 5)) plt.imshow(face, cmap=plt.cm.gray) for l in range(N_REGIONS): plt.contour(labels == l, contours=1, colors=[plt.cm.spectral(l / float(N_REGIONS))]) plt.xticks(()) plt.yticks(()) title = 'Spectral clustering: %s, %.2fs' % (assign_labels, (t1 - t0)) print(title) plt.title(title) plt.show() # + #http://scikit-learn.org/stable/auto_examples/cluster/plot_face_segmentation.html#sphx-glr-auto-examples-cluster-plot-face-segmentation-py
section2/.ipynb_checkpoints/pca_cancer-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 # --- # # Request html document from the webserver # !pip install requests import requests url = 'https://www.lyrics.com/artist/Queen/5205' response = requests.get(url) # + # Check the status code response.status_code # 200: means that the request was valid and we got what we asked for # 404: Page not found # Everything with 400 means that we made a mistake or are not authorized # Everything with 500 means that there is an error on the server side # - # Where is the html print(response.text[:40]) html = response.text # # How can we use the structure that the html document provides us to our advantage? # # -> Parse html # !pip install beautifulsoup4 from bs4 import BeautifulSoup parsed_html = BeautifulSoup(html) # + # print(parsed_html.prettify()) # - # Find the body of the html document parsed_html.find('body').find('div') # # Extract the curriculum from https://spiced.academy/de/program/data-science # Request the page spiced_response = requests.get('https://spiced.academy/de/program/data-science') spiced_response.status_code # Turn this into a BeautifulSoup object parsed_spiced_html = BeautifulSoup(spiced_response.text) # + #print(parsed_spiced_html.prettify()) # + # Find all h3 tags parsed_spiced_html.find_all('h3', attrs={'class': 'mob-hidden'})[1].text # returns a bs4.ResultSet; it behaves like a list # - for entry in parsed_spiced_html.find_all('h3', attrs={'class': 'mob-hidden'})[1:]: print(entry.text) print('\n') # You can walk down the hierarchies with beautiful soup parsed_spiced_html.find('body').div.a.get('href')
week_04/web_scraping.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.8 64-bit (''tesi'': conda)' # language: python # name: python3 # --- # # Testing DEMV on _Contraceptive Method Choice_ dataset # Source: [https://archive.ics.uci.edu/ml/datasets/Contraceptive+Method+Choice](https://archive.ics.uci.edu/ml/datasets/Contraceptive+Method+Choice) # # - Label: `contr_use` # - Unprivileged group: `wife_religion=1 (islam) & wife_work=1 (non-work)` # - Positive label: `2 (long-term)` # + import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from fairlearn.reductions import ExponentiatedGradient, BoundedGroupLoss, ZeroOneLoss import matplotlib.pyplot as plt import seaborn as sns from utils import * from demv import DEMV import warnings warnings.filterwarnings('ignore') sns.set_style('whitegrid') # %load_ext autoreload # %autoreload 2 # - data = pd.read_csv('data2/cmc.data', names=['wife_age', 'wife_edu', 'hus_edu', 'num_child', 'wife_religion', 'wife_work', 'hus_occ', 'living', 'media', 'contr_use']) data label = 'contr_use' sensitive_features = ['wife_religion', 'wife_work'] unpriv_group = {'wife_religion': 1, 'wife_work': 1} positive_label= 2 pipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', LogisticRegression()) ]) data # ## Biased dataset model, bias_metrics = cross_val(pipeline, data, label, unpriv_group, sensitive_features, positive_label=positive_label) print_metrics(bias_metrics) # ## DEMV dataset demv = DEMV(round_level=1) demv_data = data.copy() model, demv_metrics = cross_val(pipeline, demv_data, label, unpriv_group, sensitive_features, debiaser=demv, positive_label=positive_label) print_metrics(demv_metrics) # ## DEMV Evaluation eval_data = data.copy() demv.get_iters() metrics = eval_demv(3, demv.get_iters(), eval_data, pipeline, label, unpriv_group, sensitive_features, positive_label) # Execution time: ~6min # ## Blackbox PostProcessing model, blackboxmetrics, pred = cross_val2(pipeline, data, label, unpriv_group, sensitive_features, positive_label=positive_label) # ## Plot df = prepareplots(metrics,'cmc') points = preparepoints(blackboxmetrics, demv.get_iters()) plot_metrics_curves(df, points, title='CMC Multiclass Dataset') unprivpergentage(data,unpriv_group, demv.get_iters()) blackboxmetrics save_metrics('blackbox', 'cmc', blackboxmetrics)
cmc copy.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 # --- # + id="FIKODrEnVFIS" colab_type="code" colab={} import pandas as pd import matplotlib.pyplot as plt from collections import Counter # + id="C4UJiqQXWcDK" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="c8e1741b-e048-4630-9993-d3eb223210d6" executionInfo={"status": "ok", "timestamp": 1586258168047, "user_tz": -120, "elapsed": 488, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} # cd '/content/drive/My Drive/Colab Notebooks/dw_matrix/matrix_three/dw_matrix_road_sign' # + id="7lHiKhRQWkqy" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="db40b849-d743-41b0-ca04-26f6a02b124e" executionInfo={"status": "ok", "timestamp": 1586258172035, "user_tz": -120, "elapsed": 2291, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} # ls # + id="W4YNOpI4XEQF" colab_type="code" colab={} train = pd.read_pickle("data/train.p") # + id="GD6BJCkyXN9E" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="0ce53639-b079-4d5e-f141-06aebedf22ca" executionInfo={"status": "ok", "timestamp": 1586258362434, "user_tz": -120, "elapsed": 616, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} train.keys() # + id="vBFXuWStXcek" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="41106b7a-5424-4c8e-b0d0-5fc589c56be8" executionInfo={"status": "ok", "timestamp": 1586258417262, "user_tz": -120, "elapsed": 664, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} X_train, y_train = train['features'], train['labels'] X_train.shape, y_train.shape # + id="OKu-Y7HhXuq6" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 285} outputId="82dfb2d8-1528-47e5-a55c-929cf07953f6" executionInfo={"status": "ok", "timestamp": 1586258512599, "user_tz": -120, "elapsed": 548, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} plt.imshow(X_train[0]) # + id="j98vvOxHYm1Z" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 206} outputId="ceef568d-b921-4c3a-f159-d4e27237f2bd" executionInfo={"status": "ok", "timestamp": 1586258705486, "user_tz": -120, "elapsed": 920, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} signs = pd.read_csv('data/signnames.csv') signs.head() # + id="XUPFeD8yY3D8" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 36} outputId="446c6100-4704-4a28-d2f1-77ce3a3f0b0e" executionInfo={"status": "ok", "timestamp": 1586258807825, "user_tz": -120, "elapsed": 568, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} dict_signs = signs.to_dict()['b'] dict_signs[30] # + id="B8tK3TYkZJXY" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 1000, "output_embedded_package_id": "1QOEE_VlsRVgBvaF5iUqb7d2eIIJUyw2Z"} outputId="d782602a-35d6-4979-d4ae-4db6572bbade" executionInfo={"status": "ok", "timestamp": 1586263992016, "user_tz": -120, "elapsed": 11871, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} for id_sign in dict_signs.keys(): given_signs = X_train[ y_train==id_sign ] plt.figure(figsize=(15,5)) for i in range(9): plt.subplot('19{0}'.format(i+1)) plt.imshow(given_signs[i]) plt.axis('off') plt.tight_layout plt.show() # + id="JJGdHvBHZXGk" colab_type="code" colab={} cnt = Counter(y_train).most_common() # + id="qC06cMjotgtP" colab_type="code" colab={} id_labels,cnt_labels = zip(*cnt) ids=range(len(id_labels)) # + id="k2zNFJ-etwGM" colab_type="code" colab={"base_uri": "https://localhost:8080/", "height": 848} outputId="7c4cfd68-4465-407a-a1e4-53332d40709d" executionInfo={"status": "ok", "timestamp": 1586264767550, "user_tz": -120, "elapsed": 1228, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gjkn-bRunnm5F-r9MC2PsMvAGv_o7nIWlW6q-wYug=s64", "userId": "18408314227964765224"}} plt.figure(figsize=(20,10)) plt.bar(ids, cnt_labels) plt.xlabel('Znaki') labels = [dict_signs[ id_labels[id_] ] for id_ in id_labels] plt.xticks(id_labels, labels, rotation='vertical') plt.show() # + id="_ro9XgInuZIJ" colab_type="code" colab={}
day2.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: ts # language: python # name: ts # --- # # task_substitution # # > Solve an auxiliary task using ML. # **This library is created by using [nbdev](https://github.com/fastai/nbdev), please check it out.** # **Task Substitution** is a method of solving an auxiliary problem ( with different features and different target ) in order to better understand the initial problem and solving it efficiently. # # Let's take a look at standard machine learning task, in the figure below you see a regression task with features `f1`, `f2`, `f3` and target variable `y`. # <img src="images/training_set.png"/> # We want to build on a model on the above dataset to predict for unknown `y` values in the test dataset shown below. # <img src="images/test.png"/> # **Exploratory Data Analysis** # First step we take to solve the problem is to look at the data, there can be many features with *missing values* or *outliers* which needs to be understood. It is possible that there is a relationship between a missing value and values of other features. # ## Recover Missing Values # It is possible for a feature to have a missing value, it could be a data recording issue or bug etc. Often times for numerical features we replace missing value with `mean` or `median` value as a approximation. Sometimes we replace missing value with values like `-9999` so that model treats them differently or sometimes we leave them as is as libraries like `xgboost` and `lightgbm` can handle `nulls`. Let's look at following dataset # <img src="images/missing_full.png"/> # Here we have a feature `f3` with missing values, this is a numerical feature, what we can do is that we can consider `f3` as target feature and reframe this as regresion problem where we try to predict for missing values. # <img src="images/missing_train.png"/> # <img src="images/missing_test.png"/> # The above setup is identical to the original regression task, here we would build a model to use `f1` and `f2` to predict for `f3`. So instead of using `mean`, `median` etc. we can build a model to restore missing values which can help us solve the original problem efficiently. # # We have to be careful to not overfit when building such models. # ## Check Train Test Distributions # Whenever we train a model we want to use it on a new sample, but what if the new sample comes from a different distribution compared to the data on which the model was trained on. When we deploy our solutions on production we want to be very careful of this change as our models would fail if there is a mismatch in train and test sets. We can pose this problem as an auxiliary task and create a new binary target `y`, where `1` represents whether row comes from `test` set and `0` represents whether it comes from `train` set and then we train our model to predict whether a row comes from `train` or `test` set if the performance ( e.g. `AUC` score ) is high we can conclude that the train and test set come from different distributions. Ofcourse, we need to remove the `original target` from the analysis. # <img src="images/ttm_train.png"/> # <img src="images/ttm_test.png"/> # **In the above images you can see two different datasets, we want to verify whether these two come from same distributions or not.** # # Consider the first example set as training set and second one as test set for this example. # <img src="images/ttm_train_with_target.png"/> # <img src="images/ttm_test_with_target.png"/> # We create a new target called `is_test` which denotes whether a row belongs to test set or not. # <img src="images/ttm_train_test_combined.png"/> # **Then we combine training and test set and train a model to predict whether a row comes from train or test set, if our model performs well then we know that these two datasets are from different distributions.** # # We would still have to dig deep into looking at whether that's the case but the above method can help identifying which features are have drifted apart in train and test datasets. If you look at feature importance of the model that was used to separated train and test apart you can identify such features. # ## Install # task_substitution in on pypi: # # ``` # pip install task_substitution # ``` # # For an editable install, use the following: # # ``` # git clone https://github.com/numb3r33/task_substitution.git # pip install -e task_substitution # ``` # ## How to use # **Recover Missing Values** # >Currently we only support missing value recovery for numerical features, we plan to extend support for other feature types as well. Also the model currently uses LightGBM model to recover missing values. # ``` # from task_substitution.recover_missing import * # from sklearn.metrics import mean_squared_error # # train = train.drop('original_target', axis=1) # # model_args = { # 'objective': 'regression', # 'learning_rate': 0.1, # 'num_leaves': 31, # 'min_data_in_leaf': 100, # 'num_boost_round': 100, # 'verbosity': -1, # 'seed': 41 # } # # split_args = { # 'test_size': .2, # 'random_state': 41 # } # # # target_fld: feature with missing values. # # cat_flds: categorical features in the original dataset. # # ignore_flds: features you want to ignore. ( these won't be used by LightGBM model to recover missing values) # # rec = RecoverMissing(target_fld='f3', # cat_flds=[], # ignore_flds=['f2'], # perf_fn=lambda tr,pe: np.sqrt(mean_squared_error(tr, pe)), # split_args=split_args, # model_args=model_args # ) # # train_recovered = rec.run(train) # ``` # **Check train test distributions** # >We use LightGBM model to predict whether a row comes from test or train distribution. # ``` # import lightgbm as lgb # from task_substitution.train_test_similarity import * # from sklearn.metrics import roc_auc_score # # train = train.drop('original_target', axis=1) # # split_args = {'test_size': 0.2, 'random_state': 41} # # model_args = { # 'num_boost_round': 100, # 'objective': 'binary', # 'learning_rate': 0.1, # 'num_leaves': 31, # 'nthread': -1, # 'verbosity': -1, # 'seed': 41 # } # # # cat_flds: categorical features in the original dataset. # # ignore_flds: features you want to ignore. ( these won't be used by LightGBM model ) # # tts = TrainTestSimilarity(cat_flds=[], # ignore_flds=None, # perf_fn=roc_auc_score, # split_args=split_args, # model_args=model_args) # tts.run(train, test) # # # to get feature importance # fig, ax = plt.subplots(1, figsize=(16, 10) # lgb.plot_importance(tts.trained_model, ax=ax, max_num_features=5, importance_type='gain') # ``` # ## Contributing # If you want to contribute to `task_substitution` please refer to [contributions guidelines](./CONTRIBUTING.md)
index.ipynb
# --- # jupyter: # jupytext: # text_representation: # extension: .jl # format_name: light # format_version: '1.5' # jupytext_version: 1.14.4 # kernelspec: # display_name: Julia 0.4.5 # language: julia # name: julia-0.4 # --- # # How To Use Swifter.jl and AppConsole # # * https://github.com/wookay/Swifter.jl # # * https://github.com/wookay/AppConsole # # 1. AppConsole # # * It's an RPC Server written in Swift # # ## Demo project # # * Install prerequisites using [CocoaPods](https://cocoapods.org). # ``` # AppConsole/Demo/ViewController $ pod install # ``` # ## Running the sample workspace on Xcode # # * Open and run AppConsole/Demo/ViewController/ViewController.xcworkspace # # ```swift # // part of ViewController.swift # class ViewController: UIViewController { # @IBOutlet var label: UILabel! # # override func viewDidLoad() { # super.viewDidLoad() # // Do any additional setup after loading the view, typically from a nib. # # label.text = AppConsole(initial: self).run() # } # # ... # ``` # * When running the project successfully, could get the output like this. # ``` # AppConsole.swift #28 run AppConsole Server has started on http://localhost:8080 # ``` # # 2. Swifter.jl # # * It's an RPC Client written in Julia # ## Install Julia # # * Download the Julia (0.4.5) and run http://julialang.org/downloads/ # ``` # _ # _ _ _(_)_ | A fresh approach to technical computing # (_) | (_) (_) | Documentation: http://docs.julialang.org # _ _ _| |_ __ _ | Type "?help" for help. # | | | | | | |/ _` | | # | | |_| | | | (_| | | Version 0.4.5 (2016-03-18 00:58 UTC) # _/ |\__'_|_|_|\__'_| | Official http://julialang.org/ release # |__/ | x86_64-apple-darwin13.4.0 # # julia> # ``` # ## Install Swifter.jl # ``` # julia> Pkg.add("Swifter") # ``` # ## Initial # * Inital connect to the endpoint. # ``` # julia> using Swifter # # julia> vc = initial("http://localhost:8080") # <ViewController.ViewController: 0x7f8dda71e4a0> # ``` # ## Query # * Query getter, setter expressions using @query macro. # ``` # julia> @query vc.view # <UIView: 0x7f8dda68fde0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7f8dda690160>> # ``` # * Query mode (> key) for REPL # # ``` # julia> @query vc.view # <UIView: 0x7f8dda68fde0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7f8dda690160>> # # Swifter> vc.view # <UIView: 0x7f8dda68fde0; frame = (0 0; 320 568); autoresize = W+H; layer = <CALayer: 0x7f8dda690160>> # ``` # ## IJulia # * Swifter.jl supports [Jupyter](http://jupyter.org) mime types. # * To run the Jupyter interactive environment, install IJulia. # ``` # julia> Pkg.add("IJulia") # julia> using IJulia # julia> notebook() # ``` # + using Swifter vc = initial("http://localhost:8080") @query vc.label.text = "Hello World" @query vc.view # - # ## More examples # - [UIControls.ipynb](https://github.com/wookay/AppConsole/blob/master/notebooks/UIControls.ipynb) # - [MultipleDevices.ipynb](https://github.com/wookay/AppConsole/blob/master/notebooks/MultipleDevices.ipynb) # - [TableViewController.ipynb](https://github.com/wookay/AppConsole/blob/master/notebooks/TableViewController.ipynb) # - [ViewController.ipynb](https://github.com/wookay/AppConsole/blob/master/notebooks/ViewController.ipynb)
notebooks/HowToUse.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_type="code" id="lCdA5A_4AawH" outputId="d46a6e84-b648-4ae6-cfdf-3fa05be57fde" executionInfo={"status": "ok", "timestamp": 1585762206308, "user_tz": 240, "elapsed": 17399, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8PmDhUFm8THlQ0eP76DD2UF2SIKi7FuSRfOrD=s64", "userId": "11853385700800863483"}} colab={"base_uri": "https://localhost:8080/", "height": 122} from google.colab import drive drive.mount('/content/drive') # + id="ho3k_anDWL09" colab_type="code" colab={} GOOGLE_COLAB = True # + colab_type="code" id="tBkHQA5CAYP2" colab={} # %reload_ext autoreload # %autoreload 2 # + colab_type="code" id="GmZLGhnTAYP7" outputId="7800dcf8-d9ff-430e-946a-5f172cd9170d" executionInfo={"status": "ok", "timestamp": 1585762209172, "user_tz": 240, "elapsed": 661, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8PmDhUFm8THlQ0eP76DD2UF2SIKi7FuSRfOrD=s64", "userId": "11853385700800863483"}} colab={"base_uri": "https://localhost:8080/", "height": 71} import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import random import pickle # + colab_type="code" id="vfTX4hByAYQE" colab={} import sys if GOOGLE_COLAB: sys.path.append('drive/My Drive/yelp_sentiment_analysis') else: sys.path.append('../') from yelpsent import data from yelpsent import features from yelpsent import metrics from yelpsent import visualization from yelpsent import models # + id="rMagodlQ0CPW" colab_type="code" outputId="71e83ff7-4c64-423c-ba14-4e526c3ea339" executionInfo={"status": "ok", "timestamp": 1585761996878, "user_tz": 240, "elapsed": 523, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8PmDhUFm8THlQ0eP76DD2UF2SIKi7FuSRfOrD=s64", "userId": "11853385700800863483"}} colab={"base_uri": "https://localhost:8080/", "height": 34} import importlib importlib.reload(features) # + [markdown] colab_type="text" id="5Eeg1CLlAYQH" # # Load Dataset # + colab_type="code" id="hGnUCDXLAYQI" colab={} if GOOGLE_COLAB: data_train, data_test = data.load_dataset("drive/My Drive/yelp_sentiment_analysis/data/yelp_train.json", "drive/My Drive/yelp_sentiment_analysis/data/yelp_test.json") else: data_train, data_test = data.load_dataset("../data/yelp_train.json", "../data/yelp_test.json") # + colab_type="code" id="qE4liC-yAYQX" colab={} X_train = data_train['review'].tolist() y_train = data_train['sentiment'].tolist() # + colab_type="code" id="K-pw_ebWAYQZ" colab={} X_test = data_test['review'].tolist() y_test = data_test['sentiment'].tolist() # + [markdown] id="axD67C9M-mPW" colab_type="text" # # Vectorize # + [markdown] id="neDNTeDY-rv1" colab_type="text" # - CountVectorizer # - Unigram + Bigram # - Remove non-words/numbers # - Remove stopwords # - Lemmatization # + id="4Vo9fg-F8Vrl" colab_type="code" colab={} import nltk # + id="oYHbZqlH-teo" colab_type="code" outputId="a7b748cc-4b5b-4adf-cc3d-351455405b4d" executionInfo={"status": "ok", "timestamp": 1585762246535, "user_tz": 240, "elapsed": 3500, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8PmDhUFm8THlQ0eP76DD2UF2SIKi7FuSRfOrD=s64", "userId": "11853385700800863483"}} colab={"base_uri": "https://localhost:8080/", "height": 187} nltk.download('punkt') nltk.download('stopwords') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') # + colab_type="code" id="49tu0dwHkoPy" colab={} vect = features.YelpSentCountVectorizer(ngram_range=(1,2), remove_nonwords=True, remove_stopwords=True, stem=False, lemmatize=True) # + id="Ude8hEE-kpO2" colab_type="code" outputId="465c59c3-b63b-46f5-c615-7a24063bf628" executionInfo={"status": "ok", "timestamp": 1585763964062, "user_tz": 240, "elapsed": 1705143, "user": {"displayName": "<NAME>", "photoUrl": "https://lh3.googleusercontent.com/a-/AOh14Gg8PmDhUFm8THlQ0eP76DD2UF2SIKi7FuSRfOrD=s64", "userId": "11853385700800863483"}} colab={"base_uri": "https://localhost:8080/", "height": 51} # %time cv = vect.fit(X_train) # + id="BLFwX2psxoge" colab_type="code" colab={} with open('drive/My Drive/yelp_sentiment_analysis/pickles/cv.pickle', 'wb') as f: pickle.dump(cv, f) # + id="qHQXMWE5-0lL" colab_type="code" colab={} X_train_dtm = vect.transform(X_train) X_test_dtm = vect.transform(X_test) # + id="wKn06We6-uuZ" colab_type="code" colab={} with open('drive/My Drive/yelp_sentiment_analysis/pickles/X_train_dtm.pickle', 'wb') as f: pickle.dump(X_train_dtm, f) with open('drive/My Drive/yelp_sentiment_analysis/pickles/X_test_dtm.pickle', 'wb') as f: pickle.dump(X_test_dtm, f)
notebooks/create_dtm.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="mdVuQT1mpQFy" # # Workshop 5 [Student] # # This notebook will cover the following topics: # # 1. polymorphism # 2. Object composition # 3. list of objects # 4. stacks and queues # + [markdown] id="njm6M9m0q_u7" # ## 5.1 Polymorphism (Follow): # # **Learning Objectives:** # # 1. Understand how functions can have the same name but do different things # 2. Understand how functions are called in inherited classes # 3. Understand function overloading # + id="376b166d" #add comments to code class Mammal: def __init__(self, species): self.__species = species def show_species(self): print('I am a', self.__species) def make_sound(self): print('Grrrrr') class Dog(Mammal): def __init__(self): super().__init__('Dog') def make_sound(self): print('Woof! Woof!') # super().make_sound() class Cat(Mammal): def __init__(self): Mammal.__init__(self, 'Cat') # + colab={"base_uri": "https://localhost:8080/"} id="bn-0BalZpowQ" outputId="95a46b74-00cc-4dd8-82da-9c925f16d722" def main(): mammal = Mammal('regular animal') dog = Dog() cat = Cat() print('Here are some animals and') print('the sounds they make.') print('--------------------------') show_mammal_info(mammal) print() show_mammal_info(dog) print() show_mammal_info(cat) def show_mammal_info(creature): creature.show_species() creature.make_sound() if __name__ == "__main__": main() # + [markdown] id="rjZZfD35sEuc" # ### While the above program executes, answer the following questions: # # 1. Which make sound function gets executed when? # 2. What does the mammal.__init() function do in the dog and cat class? # 3. Write a function named show_species in the cat or dog class and have it do something different than the parent function. # # # + [markdown] id="Cl71XkItrBEj" # ## 5.1 Polymorphism (Group): # # **Write a program that will do the following:** # # 1. Create a class person # 2. Create a class customer # 3. Person class has attributes name, address, and phone number # 4. Customer class should have attributes customer number, purchase amount # 5. All classes should have get and set methods for all attributes. # 6. Use the super init method inside the customer class # 7. Create a get info function for both classes that return everything in the object. # 8. All attributes should be private. # + id="3dec9c0e" class Person: def __init__(self, name, address, phone_number): self.__name = name self.__address = address self.__phone_number = phone_number def set_name(self, name): self.__name = name def set_address(self, address): self.__address = address def set_phone_number(self, phone_number): self.__phone_number = phone_number def get_name(self): return self.__name def get_address(self): return self.__address def get_phone_number(self): return self.__phone_number def get_everything(self): return [self.__name, self.__address, self.__phone_number] # + colab={"base_uri": "https://localhost:8080/"} id="7gmulm3MprjY" outputId="33be9df5-176f-4f1e-86b2-5f302c97d7fa" class Customer(Person): def __init__(self, name, address, phone_number, customer_number, purchase_amount): super().__init__(name, address, phone_number) self.__customer_number = customer_number self.__purchase_amount = purchase_amount def get_customer_number(self): return self.__customer_number def set_customer_number(self, customer_number): self.__customer_number = customer_number def get_purchase_amount(self): return self.__purchase_amount def set_purchase_amount(self, purchase_amount): self.__purchase_amount = purchase_amount def get_everything(self): name = super().get_name() address = super().get_address() phone_number = super().get_phone_number() return [name, address, phone_number, self.__purchase_amount,self.__customer_number] # + person1 = Person('Truc', '3033 LKKKK', 1231237) print(person1.get_everything()) # - person2 = Customer('Phuong', '3033 LKKKK', 1231237, 34324234, 234.3) print(person2.get_everything()) # + [markdown] id="iLlWETsapgvY" # ## 5.2 Object Composition (Follow): # # **Learning Objectives:** # # 1. Understand how objects can reference other objects # 2. Understand that objects can call functions inside other objects # + id="SjA7vcSRp1E5" #add comments to the code class Person: def __init__(self, name, age, weight): self.__name = name self.__age = age self.__weight = weight class F1_Driver: def __init__(self, name, age, weight, team, wins): self.__person = Person(name, age, weight) self.__team = team self.__wins = wins def get_team(self): return self.__team def get_wins(self): return self.__wins def get_person(self): return self.__person # + colab={"base_uri": "https://localhost:8080/"} id="AwD-Hjs8p115" outputId="1da44dca-2afe-4b9e-ad7f-58659b731390" if __name__ == "__main__": name1 = "<NAME>" name2 = "<NAME>" age1 = 37 age2 = 24 weight1 = 146 weight2 = 144 team1 = "Mercedes" team2 = "Red Bull" wins1 = 103 wins2 = 20 GOAT = F1_Driver(name1, age1, weight1, team1, wins1) Youngster = F1_Driver(name2, age2, weight2, team2, wins2) print(GOAT.get_team()) print(GOAT.get_person) # + [markdown] id="AMl2yXaksT_t" # ### While the above program executes, answer the following questions: # # 1. write functions in the appropriate places to return name, age, and weight. Why did you have to put them there? # 2. Write a function to increment the number of wins for the driver. # 3. Write another function to return all known values for one object. How did you accomplish this? # + [markdown] id="tWuOZ03Zp2Ls" # ## 5.2 Object Composition (Group): # # **Write a program that will do the following:** # # 1. Create a salary class. # 2. The salary class should have attributes monthly income and bonus. # 3. Create an employee class. # 4. The employee class should have attributes employee ID, Object Salary, and job title # 5. Create get and set methods for all variables. # 6. Create a couple of objects and print the contents to the screen. # # # + id="QXqJ9WCyqBR1" class Salary: def __init__(self, monthly_income, bonus): self.__monthly_income = monthly_income self.__bonus = bonus def get_monthly_income (self): return self.__monthly_income def set_monthly_income (self, monthly_income): self.__monthly_income = monthly_income def get_bonus (self): return self.__bonus def set_bonus (self, bonus): self.__bonus = bonus # + colab={"base_uri": "https://localhost:8080/"} id="UUfsmbTKqDLJ" outputId="ec5973ed-74c2-47d0-d276-a011171fe77b" class Employee: def __init__(self, monthly_income, bonus, employee_id, job_title): self.__salary = Salary(monthly_income, bonus) self.__employee_id = employee_id self.__job_title = job_title def get_employee_id(self): return self.__employee_id def set_employee_id(self, employee_id): self.__employee_id = employee_id def get_job_title(self): return self.__job_title def set_job_title(self, job_title): self.__job_title = job_title def get_salary (self): return self.__salary def set_salary_income (self, monthly_income): self.__salary.set_monthly_income = monthly_income def set_salary_bonus (self, bonus): self.__salary.set_bonus = bonus # def set_salary (self, monthly_income, bonus): # self.__salary.set_monthly_income = monthly_income # self.__salary.set_bonus = bonus # - salary1= Salary(123123, 980980) print(f"{salary1.get_monthly_income()}, {salary1.get_bonus()}") employee1 = Employee(2313, 88787788, 'HAG87678', 'Engineer') print(f"{employee1.get_employee_id()}, {employee1.get_job_title()}, {employee1.get_salary().get_monthly_income()}") # + [markdown] id="6majl1Bbq30B" # ## 5.3 Lists of Objects (Follow): # # **Learning Objectives:** # # 1. Understand how objects can be placed in lists. # 2. Understand the usefulness of lists of objects. # # + id="e3uvsrjVrA0U" # add comments to the code class Contact(): def __init__(self, name, age): self.__name = name self.__age = age def get_name(self): return self.__name def get_age(self): return self.__age # + colab={"base_uri": "https://localhost:8080/"} id="faSFA6tqrBlo" outputId="204ac9c5-a7f4-4b86-99bf-5ad859740e68" if __name__ == "__main__": contact_list = [] for i in range(9): contact = Contact("I am contact " + str(i) + " of 9", i) contact_list.append(contact) for i in range(9): print(contact_list[i].get_name()) # + [markdown] id="ZZSkEbxqsWXU" # ### While the above program executes, answer the following questions: # # 1. What is actually in the list? # 2. What does the line: contact = Contact("I am contact " + str(i) + " of 9", i) do? # # + [markdown] id="J9awaUcCrCYI" # ## 5.3 Lists of Objects (Group): # # **Write a program that will do the following:** # # 1. Create class employee # 2. Class employee should have attributes employee id, job title, monthly income, and name. # 3. The employee class should have getter functions for all attributes. # 4. Create a list with 10 employee objects. # 5. Print the contents of list only printing the employee id. # 6. For an added challenge, make employee ID random. # 7. You can also try printing the list of objects in different formats. # # + id="BXGtdH4PrLcx" class Employee: def __init__(self, employee_id, job_title, monthly_income, name): self.__employee_id = employee_id self.__job_title = job_title self.__monthly_income = monthly_income self.__name = name def get_employee_id (self): return self.__employee_id def set_employee_id (self, employee_id): self.__employee_id = employee_id def get_job_title (self): return self.__job_title def set_job_title (self, job_title): self.__job_title = job_title def get_monthly_income (self): return self.__monthly_income def set_monthly_income (self, ): self.__monthly_income = monthly_income def get_name (self): return self.__name def set_name (self, name): self.__name = name # - import random def generate_number(): return random.randrange(1000) # + colab={"base_uri": "https://localhost:8080/"} id="5e2Wy-BLrMQC" outputId="dba0f8d1-80d5-468a-a908-7ec483283001" import random if __name__== "__main__": salary = [1000, 1100, 2100, 1555] jobs = ['doctor', 'nurse', 'staff'] first_names=('John','Andy','Joe') last_names=('Johnson','Smith','Williams') employee_list=[] for i in range(1,11): employee_list.append(Employee(generate_number(), random.choice(jobs), random.choice(salary), random.choice(first_names)+" "+random.choice(last_names))) # - for employee in employee_list: print(employee.get_name(),', ', employee.get_employee_id()) # + [markdown] id="Z21hzYZNrMo3" # ## 5.4 Stacks and Queues (Follow): # # **Learning Objectives:** # # 1. Understand how stacks are implemented. # 2. Understand how queques are implemented. # 3. Understand the importance of stacks and queues in programming. # + colab={"base_uri": "https://localhost:8080/"} id="G5x9t35RrV-S" outputId="3d706715-4d93-4f65-ee58-4b2a51da2b60" #add comments to the code stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('\nElements popped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are popped:') print(stack) # + colab={"base_uri": "https://localhost:8080/"} id="hN3blzfOra_J" outputId="fc41ac8b-a76c-415e-8591-e53eebe6c06c" #add comments to the code queue = [] queue.append('a') queue.append('b') queue.append('c') print("Initial queue") print(queue) print("\nElements dequeued from queue") print(queue.pop(0)) print(queue.pop(0)) print(queue.pop(0)) print("\nQueue after removing elements") print(queue) # + [markdown] id="tmprS5USsZB_" # ### While the above program executes, answer the following questions: # # 1. Put print statements between each pop and explain the results. # 2. Where is an example you have seen a stack or queue used in real-life? # 3. What is the order that the items are put into the queue/stack and taken out? # # + [markdown] id="WoDukkV3rbRw" # ## 5.4 Stacks and Queues (Group): # # **Write a program that will do the following:** # # 1. Create an employee class. # 2. The employee class should have attributes name and employee ID # 3. Create at least three employee objects. # 4. Push the objects into a queue and stack. # 5. Remove the employees from the stack and queue until both are empty. # 6. Print the orders of both employee objects. # + id="utKkoMXkreOu" class Employee1: def __init__(self, employee_id, name): self.__employee_id = employee_id self.__name = name def get_employee_id (self): return self.__employee_id def set_employee_id (self, employee_id): self.__employee_id = employee_id def get_name (self): return self.__name def set_name (self, name): self.__name = name # + colab={"base_uri": "https://localhost:8080/"} id="sD5qnkuYrfRP" outputId="219ed508-a740-4177-bf97-40a13b04c578" import random first_names=('John','Andy','Joe','Truc') last_names=('Johnson','Smith','Williams','Lee') # Generate data employee_list=[] stack = [] queue = [] # Generate data for i in range(1,4): employee_list.append(Employee1(generate_number(),random.choice(first_names)+" "+random.choice(last_names))) # Clone the data into stack and queue stack = list(employee_list) queue = list(employee_list) for i in range(1,len(employee_list)+1): print(f"This is queue for position {i}: {queue.pop(0).get_name()}") print(f"This is stack for position {i}: {stack.pop().get_name()}") # + [markdown] id="bti2P433Fib2" # ## 5.5 Mini Project (Group): # # **Write a program that will do the following:** # # 1. Try to use the material you have been learning to create a program that will be usefule to your life/work. # 2. Try to use classes and objects. # 3. Try to use these objects to store and process information. # + id="kGIk56AbDovt" """ Print Job is a job that a printer can create """ class PrintJob: def __init__(self, job_id): self.__job_id = job_id def get_job_id(self): return self.__job_id def set_job_id(self, job_id): self.__job_id = job_id # + id="YBtnPlb6Fst3" """ Printer hold all the print job in a queue """ class Printer: def __init__(self): self.__queue = [] def push_queue(self, jobs): self.__queue.append(jobs) def pop_queue(self): return self.__queue.pop() def print_queue(self): print("This is the remaining papers in the queue: ") for data in self.__queue: print(data.get_job_id()) # + # create printer object printer = Printer() user_input = input("Enter the id here: ") # push print job inside printer, each of them is a print object printer.push_queue(PrintJob(user_input)) printer.push_queue(PrintJob(generate_number())) printer.push_queue(PrintJob(generate_number())) printer.push_queue(PrintJob(generate_number())) # print out the first paper in queue print(f"This is the paper that finish printing: {printer.pop_queue().get_job_id()}") # print out the remainning printer.print_queue()
src/.ipynb_checkpoints/WSK Week 5-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 # --- # + import os os.environ['CUDA_VISIBLE_DEVICES'] = '1' # - import sentencepiece as spm sp_model = spm.SentencePieceProcessor() sp_model.Load('prepare/sp10m.cased.ms-en.model') # + import tensorflow as tf import tensorflow_text import struct unknown = b'\xff\xff\xff\xff' def load_graph(frozen_graph_filename): with tf.gfile.GFile(frozen_graph_filename, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) for node in graph_def.node: if node.op == 'RefSwitch': node.op = 'Switch' for index in xrange(len(node.input)): if 'moving_' in node.input[index]: node.input[index] = node.input[index] + '/read' elif node.op == 'AssignSub': node.op = 'Sub' if 'use_locking' in node.attr: del node.attr['use_locking'] elif node.op == 'AssignAdd': node.op = 'Add' if 'use_locking' in node.attr: del node.attr['use_locking'] elif node.op == 'Assign': node.op = 'Identity' if 'use_locking' in node.attr: del node.attr['use_locking'] if 'validate_shape' in node.attr: del node.attr['validate_shape'] if len(node.input) == 2: node.input[0] = node.input[1] del node.input[1] if 'Reshape/shape' in node.name or 'Reshape_1/shape' in node.name: b = node.attr['value'].tensor.tensor_content arr_int = [int.from_bytes(b[i:i + 4], 'little') for i in range(0, len(b), 4)] if len(arr_int): arr_byte = [unknown] + [struct.pack('<i', i) for i in arr_int[1:]] arr_byte = b''.join(arr_byte) node.attr['value'].tensor.tensor_content = arr_byte if len(node.attr['value'].tensor.int_val): node.attr['value'].tensor.int_val[0] = -1 with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def) return graph # + with open('prepare/test_X') as fopen: X = fopen.read().split('\n') with open('prepare/test_Y') as fopen: Y = fopen.read().split('\n') # - g = load_graph('base/frozen_model.pb') x = g.get_tensor_by_name('import/inputs:0') logits = g.get_tensor_by_name('import/SelectV2_3:0') test_sess = tf.InteractiveSession(graph = g) # + from tqdm import tqdm batch_size = 10 results = [] for i in tqdm(range(0, len(X), batch_size)): batch_x = X[i: i + batch_size] batches = [] for b in batch_x: batches.append(f'grafik pengetahuan: {b}') g = test_sess.run(logits, feed_dict = {x:batches}) results.extend(g.tolist()) # - results_Y = [sp_model.DecodeIds(r) for r in results] results_Y[0], Y[0] from tensor2tensor.utils import bleu_hook bleu_hook.compute_bleu(reference_corpus = Y, translation_corpus = results_Y)
session/knowledge-graph/t5/bleu-base.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 # --- # # HW 2 - Starter Code # First, be sure the sqlite file (found here: https://github.com/jknecht/baseball-archive-sqlite/raw/master/lahman2014.sqlite) is in the same folder as your code. # # The database contains many tables / relations, but we will be mainly using 2 relations: Salaries and Teams. The schema (description of the fields in the tables) are given below. Not all columns/fields are relevant for this homework, and we will pointout relevant fields as we walk through the assignement. # # Salaries table # --------------- # - yearID Year # - teamID Team # - lgID League # - playerID Player ID code # - salary Salary # # # Teams Table # ----------- # - yearID Year # - lgID League # - teamID Team # - franchID Franchise (links to TeamsFranchise table) # - divID Team's division # - Rank Position in final standings # - G Games played # - GHome Games played at home # - W Wins # - L Losses # - DivWin Division Winner (Y or N) # - WCWin Wild Card Winner (Y or N) # - LgWin League Champion(Y or N) # - WSWin World Series Winner (Y or N) # - R Runs scored # - AB At bats # - H Hits by batters # - 2B Doubles # - 3B Triples # - HR Homeruns by batters # - BB Walks by batters # - SO Strikeouts by batters # - SB Stolen bases # - CS Caught stealing # - HBP Batters hit by pitch # - SF Sacrifice flies # - RA Opponents runs scored # - ER Earned runs allowed # - ERA Earned run average # - CG Complete games # - SHO Shutouts # - SV Saves # - IPOuts Outs Pitched (innings pitched x 3) # - HA Hits allowed # - HRA Homeruns allowed # - BBA Walks allowed # - SOA Strikeouts by pitchers # - E Errors # - DP Double Plays # - FP Fielding percentage # - name Team's full name # - park Name of team's home ballpark # - attendance Home attendance total # - BPF Three-year park factor for batters # - PPF Three-year park factor for pitchers # - teamIDBR Team ID used by Baseball Reference website # - teamIDlahman45 Team ID used in Lahman database version 4.5 # - teamIDretro Team ID used by Retrosheet # + import sqlite3 import pandas sqlite_file = 'lahman2014.sqlite' conn = sqlite3.connect(sqlite_file) # connect to database and ingest the tables # lets run a query to look at the data salary_query = "SELECT yearID, sum(salary) as total_payroll FROM Salaries WHERE lgID == 'AL' GROUP BY yearID" team_salaries = pandas.read_sql(salary_query, conn) team_salaries.head() # - # ## Analysis # # We want to understand how efficient teams have been historically at spending money and getting wins in return. In the case of Moneyball, one would expect that Oakland was not much more efficient than other teams in their spending before 2000, were much more efficient (they made a movie about it after all) between 2000 and 2005, and by then other teams may have caught up. Lets see how this is reflected in the data we have. # ### Relation Creation # # Using SQL compute a new relation that contains a subset of fields of interest to help us compute further statisitcs of interest. We neeed to think about the type of join used as it determines how missing data is handled. In the code below, a SQL statment is executed to create the new relation jusing a join between the two tables; # # # # + createTable_query = "CREATE TABLE statsTbl AS SELECT \ Salaries.yearID, Teams.teamID, Teams.name, Salaries.salary, Teams.G, Teams.W, Teams.L \ FROM Salaries \ JOIN Teams \ ON Salaries.yearID=Teams.yearID AND Salaries.teamID=Teams.teamID \ WHERE Salaries.lgID=='AL' ;" cursor = conn.cursor() cursor.execute(createTable_query) conn.commit() # if you run this mulitple times, you may see an error stating "statsTbl already exists". This error message can be ignored. # + query = "select * from statsTbl;" result = pandas.read_sql(query, conn) result.head() # As you can see, it generates a new table/relation which contains 7 fields: # yearID # teamID # name # salary # G --> denotes the number of games # W --> denotes the number of wins # L --> denotes the number of losses # - # Suppose we want to print the rows / entries for Oakland between 1988 - 1989. Hint: need to use a WHERE clause in the SQL query to filter out rows only for teamID="OAK" # + query = "SELECT * FROM statsTbl WHERE teamID='OAK' AND yearID>=1988 AND yearID<=1989;" result = pandas.read_sql(query, conn) result.head() # - # Suppose we want to print the year for which Oakland had the largest number of wins. Lets write that SQL query. # + query = "SELECT yearID, max(W) from statsTbl WHERE teamID='OAK';" result = pandas.read_sql(query, conn) result.head() # - # Suppose we want to compute the total payroll for teamID='OAK' for the yearID='1988'. To do this, we must sum-up all the salaries for a given team for a given year. # + query = "SELECT teamID, yearID, SUM(salary) AS TotalSalary \ FROM statsTbl \ WHERE yearID='1988' AND teamID='OAK' \ GROUP BY teamID,yearID;" result = pandas.read_sql(query, conn) result.head() # - # ## Problem 1 # # Using SQL, compute the result containing the total payroll and winning percentage (number of wins / number of games * 100) for each team (that is, for each teamID and yearID combination). # # Hint: Be sure to perform a groupby on the fields teamID and yearID # # # + query = "SELECT teamID, yearID, SUM(salary) AS Total, CAST(W AS Float)/CAST(G AS Float)*100 AS WinningPercentage FROM statsTbl GROUP BY teamID,yearID;" result = pandas.read_sql(query, conn) result.head() # - # ## Problem 2 # # Write code to printout the teamID that had the highest WinningPercentage over total sepending (salaries). # ## Problem 3 # # Write code to produce plots that illustrate the team's total spending (salaries) conditioned on time (from 1990-2014), specifically for teamID='OAK'. # + import matplotlib.pyplot as plt query = "SELECT teamID, yearID, SUM(salary) AS Total \ FROM statsTbl \ WHERE teamID='OAK' \ GROUP BY teamID , yearID;" result2 = pandas.read_sql(query, conn) result2.head() plt.plot(result2["yearID"],result2["Total"]) plt.ylabel('Total') plt.xlabel('Year') plt.show() # - # ## Problem 4 # # Write code to discretize year into five time periods (you can use pandas.cut to accomplish this) and then make a scatterplot showing mean winning percentage (y-axis) vs. mean payroll (x-axis) for each of the five time periods. # # What can you say about team payrolls across these periods? Are there any teams that standout as being particularly good at paying for wins across these time periods? What can you say about the Oakland A’s spending efficiency across these time periods (labeling points in the scatterplot can help interpretation). # + # Example - using Pandas Cut # we will use the query result2 from previous step, which contains the fields: teamID, yearID, Total print result2["Total"] # orginial data (total spending - salaries) # pandas.cut allows us to convert from continuous variable to a categorical variable. # the statement below converts the total spending to one of three catagories pandas.cut(result2["Total"],3, labels=["low","med","high"], retbins=True)
Homeworks/HW2/ECON128-HW2-StarterCodel-1 (1).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 dask library import dask.dataframe as dd #merge files into one df df = dd.read_csv('*.csv') # confirm size and content of df df.compute() # reduce column to lower case...Check for 'check' in comments df['CONTENT'] = df['CONTENT'].str.lower() df['CONTENT'] = df['CONTENT'].str.contains('check') #Filter for check and 1 df1 = df[(df['CONTENT'] == True) & (df['CLASS'] == 1)] #get list length len(df1) #Filter for check and 1 df2 = df[(df['CONTENT'] == True) & (df['CLASS'] == 0)] #get list length len(df2) # + You've been introduced to a variety of platforms (AWS SageMaker, AWS EMR, Databricks), libraries (Numba, Dask, MapReduce, Spark), and languages (Python, SQL, Scala, Java) that can "scale up" or "scale out" for faster processing of big data. Write a paragraph comparing some of these technology options. For example, you could describe which technology you may personally prefer to use, in what circumstances, for what reasons. (You can add your paragraph as a Markdown cell at the bottom of your SageMaker Notebook.) # - # ## Part 2 # # At the begining of my Lambda experience, there was very little content that looked familiar to me and nothing I could say I felt even remotely comfortable with. Conversely, this week was full of new platforms, libraries, and languages that immediately looked like familiar variations of the knowledge I have gained. Having the most familiartity with Python, I prefer to use this in most situations because I feel that I can acheive efficient results while building on knowledge. Because SQL can be used within Python, it seems like an extension of that language with new syntax and formats (triple quotes, capitalization, semi-colons). Scala is a bit frustrating in that it is similar but not the same as python. With that being said, I feel comfortable using the language for big data. As for platforms, the main three we have used this week, AWS SageMaker, AWS EMR, Databricks, they all seem fairly comprable. The speed of both AWS platforms is overwhelmingly impressive, while Databricks is easy to use and set up. As for libraries, begining the week Dask was a pleasant experience. I could quickly see how much of the functionality improves upon the more familiar Pandas. Spark is great once I remember which letters to capitalize.
SC_3_3/SC_3_3_Part1.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 # [【中文分词系列】 3. 字标注法与HMM模型 - 科学空间|Scientific Spaces](https://kexue.fm/archives/3922#Python%E5%AE%9E%E7%8E%B0) # # [一次性弄懂马尔可夫模型、隐马尔可夫模型、马尔可夫网络和条件随机场!(词性标注代码实现) - 知乎](https://zhuanlan.zhihu.com/p/74063873) 没啥用 # # ~~数据参考 https://github.com/pwxcoo/chinese-xinhua~~ # # TODO # 1. 数据参考应该改成jieba的 # 2. 重新写一个,并对比苏神的 # # 存在问题: # 1. 最后推出来的公式少了$P(O_1)$ # # 暂停: # 已经搞懂维提比和HMM,先看CRF FILE_PATH = '../data/chinese-xinhua-master/data/ci.json' import pandas as pd import json df = None with open(FILE_PATH, encoding='utf-8') as f: word = json.load(f) l = [len(w['ci']) for w in word] df = pd.DataFrame(l) df.describe() from collections import Counter from math import log import json hmm_model = {i:Counter() for i in 'sbme'} with open(FILE_PATH, encoding='utf-8') as f: word = json.load(f) cnt = 1 # 没有词频,假设每个词都出现一次,待改进 for w in word: w = w['ci'] if len(w) == 1: hmm_model['s'][w[0]] += cnt else: hmm_model['b'][w[0]] += cnt hmm_model['e'][w[-1]] += cnt for m in w[1:-1]:hmm_model['m'][m] += cnt # break; # hmm_model字典里面计算的是 $P(\lambda_k|o_k)$ 的分子部分 # # 下面计算分母部分 log_total = {i:log(sum(v.values())) for i,v in hmm_model.items()}; log_total # # 猜出来的$P(o_k|o_{k-1})$,即知道$o_{k-1}$,去枚举$o_k$,共bmes三种标签,因此有4*4 = 9项 # # 枚举$o_{k-1}$再枚举$o_{k}$,$\forall o_{k-1} \in bems, \sum_{o_{k} \in bems }{P(o_{k}|o_{k-1})} = 1, $ # 1. b # 1. ~~b~~ # 1. m 1 # 1. e 1 # 2. ~~s~~ # 2. m # 1. ~~b~~ # 2. m 1 # 3. e 1 # 4. ~~s~~ # 3. e # 1. b 1 # 2. ~~m~~ # 3. ~~e~~ # 4. s 1 # 4. s # 1. b 1 # 2. ~~m~~ # 3. ~~e~~ # 4. s 1 trans = {'ss':0.3, 'sb':0.7, 'bm':0.3, 'be':0.7, 'mm':0.3, 'me':0.7, 'es':0.3, 'eb':0.7 } # # nodes # # 是一个$ \{ P(\lambda_k|o_k) \}$矩阵 # # 列: $o_k \in bems$ # # 行:$\lambda_k \in input\_string$ # # paths # ```json # {'s': -5.805134968916488, 'b': -8.900571732689496, 'm': -7.770605048471433, 'e': -9.188253805141278} # {'ss': -11.310269937832976, 'sb': -13.97830772741787, 'mm': -14.251491896513892, 'me': -14.939575202775782} # {'sss': -16.122257726189517, 'ssb': -19.56800008436242, 'sbm': -23.57714448173857, 'sbe': -23.816488249508165} # ``` # # # ```json # // <bmes路径>[-1] 应该互不相同 # // <bmes路径>[-2:] in trans 才有效 # { # <bmes路径>:叠加概率 # } # ``` # + # https://stackoverflow.com/questions/49051492/index-generates-attributeerror-dict-values-object-has-no-attribute-index # python2 to python3 import operator def get_key_by_max_value(d): """ https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary """ return max(d.items(), key=operator.itemgetter(1))[0] def viterbi(nodes): paths = nodes[0] for node in nodes[1:]: # l 每个字 paths_ = paths print(paths) paths = {} for i,p_o in node.items(): # o_k 这个字的 bems nows = {} for path, path_p in paths_.items(): # 到 l - 1 为止 最大 的 <=4 维特比 路径 ;每条路径长度(paths的key) 是 j 即 nodes[0:j] 计算得到 trans_key = path[-1] + i current_path = path + i if trans_key in trans: # o_{i-1} + o{i} nows[ current_path ]= path_p + p_o + trans[trans_key] k = get_key_by_max_value(nows) assert i == k[-1] paths[k] = nows[k] return get_key_by_max_value(paths) def hmm_cut(s): nodes = [{i:log(j[t]+1)-log_total[i] for i,j in hmm_model.items()} for t in s] tags = viterbi(nodes) words = [s[0]] for i in range(1, len(s)): if tags[i] in ['b', 's']: words.append(s[i]) else: words[-1] += s[i] return words (hmm_cut('我是傻逼')) # - df # + from collections import Counter from math import log hmm_model = {i:Counter() for i in 'sbme'} with open('dict.txt') as f: for line in f: lines = line.decode('utf-8').split(' ') if len(lines[0]) == 1: hmm_model['s'][lines[0]] += int(lines[1])# 应该是频次吧 else: hmm_model['b'][lines[0][0]] += int(lines[1]) hmm_model['e'][lines[0][-1]] += int(lines[1]) for m in lines[0][1:-1]: hmm_model['m'][m] += int(lines[1]) log_total = {i:log(sum(hmm_model[i].values())) for i in 'sbme'} trans = {'ss':0.3, 'sb':0.7, 'bm':0.3, 'be':0.7, 'mm':0.3, 'me':0.7, 'es':0.3, 'eb':0.7 } trans = {i:log(j) for i,j in trans.iteritems()} def viterbi(nodes): paths = nodes[0] for l in range(1, len(nodes)): paths_ = paths paths = {} for i in nodes[l]: nows = {} for j in paths_: if j[-1]+i in trans: nows[j+i]= paths_[j]+nodes[l][i]+trans[j[-1]+i] k = nows.values().index(max(nows.values())) paths[nows.keys()[k]] = nows.values()[k] return paths.keys()[paths.values().index(max(paths.values()))] def hmm_cut(s): nodes = [{i:log(j[t]+1)-log_total[i] for i,j in hmm_model.iteritems()} for t in s] tags = viterbi(nodes) words = [s[0]] for i in range(1, len(s)): if tags[i] in ['b', 's']: words.append(s[i]) else: words[-1] += s[i] return words
hmm.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 # --- # ## Fourier Transforms # # The frequency components of an image can be displayed after doing a Fourier Transform (FT). An FT looks at the components of an image (edges that are high-frequency, and areas of smooth color as low-frequency), and plots the frequencies that occur as points in spectrum. # # In fact, an FT treats patterns of intensity in an image as sine waves with a particular frequency, and you can look at an interesting visualization of these sine wave components [on this page](https://plus.maths.org/content/fourier-transforms-images). # # In this notebook, we'll first look at a few simple image patterns to build up an idea of what image frequency components look like, and then transform a more complex image to see what it looks like in the frequency domain. # + import numpy as np import matplotlib.pyplot as plt import cv2 # %matplotlib inline # Read in the images image_stripes = cv2.imread('images/stripes.jpg') # Change color to RGB (from BGR) image_stripes = cv2.cvtColor(image_stripes, cv2.COLOR_BGR2RGB) # Read in the images image_solid = cv2.imread('images/pink_solid.jpg') # Change color to RGB (from BGR) image_solid = cv2.cvtColor(image_solid, cv2.COLOR_BGR2RGB) # Display the images f, (ax1,ax2) = plt.subplots(1, 2, figsize=(10,5)) ax1.imshow(image_stripes) ax2.imshow(image_solid) # + # convert to grayscale to focus on the intensity patterns in the image gray_stripes = cv2.cvtColor(image_stripes, cv2.COLOR_RGB2GRAY) gray_solid = cv2.cvtColor(image_solid, cv2.COLOR_RGB2GRAY) # normalize the image color values from a range of [0,255] to [0,1] for further processing norm_stripes = gray_stripes/255.0 norm_solid = gray_solid/255.0 # perform a fast fourier transform and create a scaled, frequency transform image def ft_image(norm_image): '''This function takes in a normalized, grayscale image and returns a frequency spectrum transform of that image. ''' f = np.fft.fft2(norm_image) fshift = np.fft.fftshift(f) frequency_tx = 20*np.log(np.abs(fshift)) return frequency_tx # + # Call the function on the normalized images # and display the transforms f_stripes = ft_image(norm_stripes) f_solid = ft_image(norm_solid) # display the images # original images to the left of their frequency transform f, (ax1,ax2,ax3,ax4) = plt.subplots(1, 4, figsize=(20,10)) ax1.set_title('original image') ax1.imshow(image_stripes) ax2.set_title('frequency transform image') ax2.imshow(f_stripes, cmap='gray') ax3.set_title('original image') ax3.imshow(image_solid) ax4.set_title('frequency transform image') ax4.imshow(f_solid, cmap='gray') # - # Low frequencies are at the center of the frequency transform image. # # The transform images for these example show that the solid image has most low-frequency components (as seen by the center bright spot). # # The stripes tranform image contains low-frequencies for the areas of white and black color and high frequencies for the edges in between those colors. The stripes transform image also tells us that there is one dominating direction for these frequencies; vertical stripes are represented by a horizontal line passing through the center of the frequency transform image. # # Next, let's see what this looks like applied to a real-world image. # + # Read in an image image = cv2.imread('images/birds.jpg') # Change color to RGB (from BGR) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) # normalize the image norm_image = gray/255.0 f_image = ft_image(norm_image) # Display the images f, (ax1,ax2) = plt.subplots(1, 2, figsize=(20,10)) ax1.imshow(image) ax2.imshow(f_image, cmap='gray') # - # Notice that this image has components of all frequencies. You can see a bright spot in the center of the transform image, which tells us that a large portion of the image is low-frequency; this makes sense since the body of the birds and background are solid colors. The transform image also tells us that there are **two** dominating directions for these frequencies; vertical edges (from the edges of birds) are represented by a horizontal line passing through the center of the frequency transform image, and horizontal edges (from the branch and tops of the birds' heads) are represented by a vertical line passing through the center.
06_Computer_Vision/02_Convolutional_filters_and_edge_detection/01_Fourier_transform.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 xarray as xr import numpy as np import pandas as pd import matplotlib.pyplot as plt import seawater as sw from scipy import interpolate from scipy import signal from glob import glob import scipy.ndimage import matplotlib.colors as colors from sklearn.linear_model import LinearRegression #import spectrum #data directory for saildrone data #more on the data here: https://podaac.jpl.nasa.gov/dataset/SAILDRONE_ATOMIC # DOI = 10.5067/SDRON-ATOM0 data_dir = './data/' saildrone_filenames = [x for x in glob(data_dir+'saildrone*.nc')] #output figs_dir = './figures/' #subroutines for calculating PSD & making plot def spectrum(data_in): #calculate PSD for each USV data_all=[] for iusv in range(3): ds_usv = data_in.isel(trajectory=iusv) ds2 = ds_usv.assign_coords(dist_total = ds_usv.dist_total) ds3 = ds2.swap_dims({'time':'dist_total'}) dist_interp = np.arange(ds2.dist_total[0],ds2.dist_total[-1],0.08) ds4 = ds3.interp(dist_total=dist_interp) den = ds4.density_mean.interpolate_na(dim='dist_total') den = den.where(np.isfinite(den),drop=True) ds4_detrend = signal.detrend(den) ds4_detrend_smooth = ds4_detrend #ds4_detrend_smooth = scipy.ndimage.filters.gaussian_filter1d(ds4_detrend, sigma=25) freq, Pxx_den = signal.periodogram(ds4_detrend_smooth,1/.080) #fs = sampled at .08km or 80m freq2, Pxx_den2 = signal.welch(ds4_detrend_smooth,1/.080,nperseg=1024*30) #fs = sampled at .08km or 80m if iusv==0: ps_all=Pxx_den[0:10000] ps_all_welch=Pxx_den2[0:10000] else: ps_all = np.vstack([ps_all,Pxx_den[0:10000]]) ps_all_welch = np.vstack([ps_all_welch,Pxx_den2[0:10000]]) Pxx_den = np.mean(ps_all,axis=0) Pxx_den_welch = np.mean(ps_all_welch,axis=0) return freq,freq2,Pxx_den,Pxx_den_welch def cal_pdf(data_in): #make arrays for sampling at different length scales length_scale = np.arange(.1,200,1) # create the empty data arrays to store the normalized histograms (normalized the *100 for percentage count) xx_in = np.arange(0,.2,.001) xx_in2 = np.arange(0,.2-.001,.001) data = np.zeros((len(length_scale),len(xx_in2))) ddn=xr.DataArray(data,dims=('length_scale','gradx'),coords={'length_scale':length_scale,'gradx':xx_in2}) for iusv in range(3): ds_usv = data_in.isel(trajectory=iusv) ds2 = ds_usv.assign_coords(dist_total = ds_usv.dist_total) #add dist traveled coordinate ds3 = ds2.swap_dims({'time':'dist_total'}) #swap from time to distance traveled for ilen2,len2 in enumerate(length_scale): dist_interp = np.arange(ds2.dist_total[0],ds2.dist_total[-1],len2) ds4 = ds3.interp(dist_total=dist_interp) den_grad = np.abs(np.gradient(ds4.density_mean)/len2) result,xx = np.histogram(den_grad,bins=xx_in) ddn[ilen2,:]=ddn[ilen2,:]+result for ilen2,len2 in enumerate(length_scale): ddn[ilen2,:]=ddn[ilen2,:]/sum(ddn[ilen2,:])*100 #normalize & turn into percent return ddn def psd_fig(f,data_in,Pxx_den,text1,fout,ifit): length_scale = np.arange(.1,200,1) xx_in = np.arange(0,.2,.001) xx_in2 = np.arange(0,.2-.001,.001) print(len(length_scale),len(xx_in)) fig = plt.figure(figsize=(14,10)) tem=data_in tem = tem.where(tem>.003) Z=tem.T ax = plt.pcolormesh(length_scale,xx_in2,Z, norm=colors.LogNorm(vmin=Z.min(), vmax=Z.max()),vmin=.01,vmax=100,cmap='hot') plt.text(10,0.179,'(a)'+text1,fontsize=16,color='k') plt.xlabel('Length scale (km)',fontsize=16) plt.ylabel('Density gradient (kg m$^{-3}$ km$^{-1}$)',fontsize=16) cb = plt.colorbar() cb.set_label(label='Percent count',fontsize=16) plt.axes([.33, .47, .4, .4]) #cal PSD #Pxx_den = np.mean(psd_in,axis=0) #f, Pxx_den = signal.periodogram(Pxx_den,1/.080) #fs = sampled at .08km or 80m istart,iend=10,5550 plt.loglog(f[istart:iend], Pxx_den[istart:iend]) #linear regression to PSD istart,iend=8,ifit XX = np.log(f[istart:iend]) YY = np.log(Pxx_den[istart:iend]) reg = LinearRegression().fit(XX.reshape(-1, 1), YY) a = float(reg.coef_) b = -1*float(reg.intercept_) plt.loglog(f[istart:iend], f[istart:iend]**(a)/np.exp(b),'r') #test from fit slp_str = 'slope = '+"{:.1f}".format(a) plt.text(.02,10,slp_str,fontsize=16,color='r') plt.ylim([10e-7,10e1]) plt.xlim([10e-4,10e-1]) plt.xticks(ticks=[.001,.01,.1,1],labels=['1000','100','10','1']) plt.text(.0011,10,'(b)',fontsize=16,color='k') #plt.xlabel('Wavenumber (cpkm)') plt.xlabel('Wavelength (km)') plt.ylabel('PSD ((kg m$^{-3}$)$^2$ cpkm$^{-1}$]') plt.grid() plt.savefig(figs_dir+fout) return # - # # Read in USV data for all 3 Saildrone # - caluclate density and wind speed # - caluclate distance between successive obs # - caluculate total cumulative distance # - switch from time to cumulative distance as index # - interpolate data onto grid # # + ds=[] for iusv in range(3): fname=saildrone_filenames[iusv] ds_usv=xr.open_dataset(fname).isel(trajectory=0).swap_dims({'obs':'time'}) ds_usv.close() # #make diruanl plot xlon=ds_usv.longitude.ffill(dim='time').data time_offset_to_lmt=(xlon/360.)*24.*60 tem = ds_usv.time+time_offset_to_lmt*np.timedelta64(1,'m') ds_usv['tlmt']=tem ds_usv2= ds_usv.swap_dims({'time':'tlmt'}) ds_usv2a = ds_usv2.where(ds_usv2.tlmt.dt.hour==6) dymn = ds_usv2a.groupby("tlmt.dayofyear").mean() ds_usv3 = ds_usv2.groupby("tlmt.dayofyear") - dymn ds_usv['TEMP_AIR_MEAN_DW'] = ds_usv3.swap_dims({'tlmt':'time'}).drop({'tlmt'}).TEMP_AIR_MEAN ds_usv['TEMP_SBE37_MEAN_DW'] = ds_usv3.swap_dims({'tlmt':'time'}).drop({'tlmt'}).TEMP_SBE37_MEAN ds_usv['wspd']=np.sqrt(ds_usv.UWND_MEAN**2+ds_usv.VWND_MEAN**2) tem=sw.dens0(ds_usv.SAL_SBE37_MEAN,ds_usv.TEMP_SBE37_MEAN) ds_usv['density_mean']=xr.DataArray(tem,dims=('time'),coords={'time':ds_usv.time}) tem=sw.alpha(ds_usv.SAL_SBE37_MEAN,ds_usv.TEMP_SBE37_MEAN,ds_usv.BARO_PRES_MEAN*0) #pressure =0 at surface ds_usv['alpha_ME']=xr.DataArray(tem,dims=('time'),coords={'time':ds_usv.time}) tem=sw.beta(ds_usv.SAL_SBE37_MEAN,ds_usv.TEMP_SBE37_MEAN,ds_usv.BARO_PRES_MEAN*0) #pressure =0 at surface ds_usv['beta_MEAN']=xr.DataArray(tem,dims=('time'),coords={'time':ds_usv.time}) ds_usv['latitude']=ds_usv.latitude.interpolate_na(dim='time') ds_usv['longitude']=ds_usv.longitude.interpolate_na(dim='time') xlat=ds_usv.latitude xlon=ds_usv.longitude dkm2 = abs(np.abs((((xlon[1:].data-xlon[0:-1].data)**2+(xlat[1:].data-xlat[0:-1].data)**2)**.5)*110.567*np.cos(np.pi*xlat[1:].data/180))) dkm2=np.append(dkm2,dkm2[66238]) #add on last point dkm3 = dkm2.cumsum() ds_usv['dist_total']=xr.DataArray(dkm3,dims=('time'),coords={'time':ds_usv.time}) ds_usv['dist_between']=xr.DataArray(dkm2,dims=('time'),coords={'time':ds_usv.time}) if iusv==0: ds = ds_usv else: ds = xr.concat([ds,ds_usv],dim='trajectory') ds_saildrone = ds.copy(deep=True) # + freq_usv,freq2_usv,Pxx_den_usv,Pxx_den_welch_usv = spectrum(ds) ddn_usv = cal_pdf(ds) # - psd_fig(freq_usv,ddn_usv,Pxx_den_usv,'Saildrone','PSD_den_grad_usv.png',5000)
2020_ATOMIC_bjorn/ATOMIC_spectrum_Salinity_plot_figure11.ipynb